Compare commits

...
Sign in to create a new pull request.

54 commits

Author SHA1 Message Date
Aleksei Sviridkin
1f771fec88
ci: retry CI
Empty commit to retrigger E2E that hit two known flakes:
- kubernetes-previous (CSINode registration race per
  flake-kubernetes-previous-csi memory): nfs-test-pvc timed out waiting
  for condition.
- vminstance: VMI did not get IP in 20s timeout (KubeVirt flake).

Neither is related to the admission-chain or VAP changes in this PR.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-26 07:38:38 +03:00
Aleksei Sviridkin
8fb47c72fa
ci: retry CI
Empty commit to retrigger E2E that flaked on KubeVirt vminstance test
(Create a VM Instance — VMI did not get IP in 20s timeout). Same flake
that hit #2489 earlier in this session; not related to the
admission-chain or VAP changes in this PR.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-26 05:58:55 +03:00
Aleksei Sviridkin
1146abce94
fix(cozystack-api): invoke admission chain on Application Create and Delete
The custom REST handler at pkg/registry/apps/application/rest.go is the
storage backend for every kind in apps.cozystack.io/v1alpha1 (Tenant,
MariaDB, Postgres, Kubernetes, ...). genericapiserver passes the
admission chain — mutating webhooks, validating webhooks, and
ValidatingAdmissionPolicies — to each storage method as a callback:
createValidation for Create, updateValidation for Update,
deleteValidation for Delete. Update was correctly invoking its callback
since 23e399bd, but Create and Delete accepted the parameter and never
called it. Admission was silently bypassed for both verbs on every
apps.cozystack.io resource.

The ValidatingAdmissionPolicy cozystack-tenant-host-policy added in
this PR is the first in-tree policy that depends on Create-side
enforcement. The accompanying e2e probe
'cozystack-tenant-host-policy blocks non-trusted callers from setting
tenant.spec.host' caught the gap.

Mirrors the existing updateValidation pattern: invoke createValidation
in Create after the cheap format/length checks but before any state
change, and invoke deleteValidation in Delete after the HelmRelease has
been resolved (so admission sees the same shape it would on UPDATE) but
before the actual r.c.Delete call.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-26 04:35:19 +03:00
Aleksei Sviridkin
75c06ce6e8
fix(tests): use dashless tenant name in tenant-host-policy probe
The gateway.bats e2e test creates a Tenant named 'vap-host-probe' to
verify that a non-trusted ServiceAccount cannot set tenant.spec.host.
Tenant name validation rejects dashes (lowercase letters and digits
only), so the apply was rejected by the name validator before reaching
the cozystack-tenant-host-policy ValidatingAdmissionPolicy. Under the
test's set -e, the subsequent grep for 'ValidatingAdmissionPolicy' in
the error output then exits non-zero, failing the test.

Renaming the probe to 'vaphostprobe' lets the request pass the name
validator and reach the VAP, which is what the test is meant to
exercise.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-26 02:51:35 +03:00
Aleksei Sviridkin
0457e98ee7
ci: retry CI
Empty commit to retrigger Build job that failed on Docker Hub anonymous
pull rate limit (429 Too Many Requests) for alpine:latest.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-26 01:24:14 +03:00
Aleksei Sviridkin
206a31f89c
refactor(gateway): delegate CiliumLoadBalancerIPPool to tenant chart
#2468 introduced packages/apps/tenant/templates/cilium-lb-pool.yaml as the per-tenant owner of the LoadBalancer IP pool. Extend that template with the .Values.gateway branch: the pool now renders when either _cluster.expose-mode=loadBalancer (with .Values.ingress=true on the publishing tenant) OR .Values.gateway=true. Cilium LB IPAM forbids overlapping CIDRs across pools regardless of serviceSelector, so a single pool per tenant is required — the same CIDRs cannot back both ingress and gateway from two separate pools without one of them being marked Conflicting.

Delete packages/extra/gateway/templates/cilium-lb-pool.yaml — the gateway chart no longer renders its own pool. The empty-externalIPs render-time fail moves to the tenant template, guarded on the gateway branch so the legacy ingress path remains unchanged.

Gateway tests lose the pool-rendering asserts that previously lived in packages/extra/gateway/tests/gateway_test.yaml. The tenant chart tests in packages/apps/tenant/tests/exposure_test.yaml gain five gateway-path cases covering pool rendering, non-publishing-tenant rendering, the simultaneous ingress+gateway single-pool case, gateway-only with ingress=false, and the empty-externalIPs fail.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:07:08 +03:00
Aleksei Sviridkin
604b84f78f
test(e2e): invert VAP rejection tests to use if ! so set -e is respected
Previous pattern relied on a "__SUCCEEDED__" marker captured via
`output=$(kubectl apply … && echo "__SUCCEEDED__")`. On dash
(hack/cozytest.sh is #!/bin/sh with set -e) a failing command
substitution propagates its non-zero exit through the assignment and
kills the test before the follow-up grep can run — so admission
correctly rejecting the probe read as a test failure. The marker
approach also hides what actually happened behind a string comparison.

Rewrite each VAP negative-path test as `if ! output=$(…); then …
else …; fi`. The if-condition disables set -e per POSIX, the exit
code is consumed directly (admission reject = happy path), and on the
unexpected-success branch we print the captured admission response
and clean up the resource that slipped through. Happy-path cleanup
only removes the scaffolding RBAC because the probe resource was
never created.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:04 +03:00
Aleksei Sviridkin
ac70320544
fix(cozystack-basics): Flux lives in cozy-fluxcd, not flux-system
Root cause of the install regression on run 24885268333: the Flux
ServiceAccount in cozystack is `system:serviceaccount:cozy-fluxcd:flux`,
not `flux-system:flux`. My trustedCaller list had
`system:serviceaccounts:flux-system`, so once the namespace-host-label
VAP was broadened to CREATE, Flux's first-time write of
`namespace.cozystack.io/host` on tenant-test got rejected:

  namespaces "tenant-test" is forbidden: ValidatingAdmissionPolicy
  'cozystack-namespace-host-label-policy' denied request: namespace
  label namespace.cozystack.io/host is immutable once set (was ,
  requested test.example.org); only cluster-admins and cozystack/Flux
  service accounts may change it. Request user:
  system:serviceaccount:cozy-fluxcd:flux

Replace `flux-system` with `cozy-fluxcd` in the trustedCaller group
list of both cozystack-tenant-host-policy and
cozystack-namespace-host-label-policy, plus the README.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:04 +03:00
Aleksei Sviridkin
3a698e76d3
fix(cozystack-basics): close namespace-host-label-policy CREATE gap
The policy previously only fired on UPDATE and only when oldObject already
carried namespace.cozystack.io/host, which left two paths unguarded:

  - CREATE of a namespace with the label pre-set.
  - UPDATE that adds the label for the first time (oldObject has no label,
    so the matchCondition was false and the VAP was skipped).

Both paths required namespace create/update on labels, which is normally
cluster-admin-only, but the VAP is meant to be the source of truth for
this label's integrity. Close the gap:

  - operations: [CREATE, UPDATE]
  - matchCondition now fires when either object or oldObject carries the
    label (renamed had-host-label -> touches-host-label).
  - oldHost is computed with a null-safe ternary so CREATE (where
    oldObject is null) evaluates cleanly.

The existing validation (newHost == oldHost || trustedCaller) then
naturally denies first-time label writes from non-trusted callers while
still allowing cozy-system / cozy-cert-manager / flux-system / kube-system
SAs to stamp the label during the tenant chart apply.

Update packages/extra/gateway/README.md layer 5 description to match and
add an e2e test that asserts a namespace CREATE with the label from an
untrusted SA is rejected.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:04 +03:00
Aleksei Sviridkin
ff52afc02a
test(e2e): fix shell logic — set -e killed VAP tests on happy path
Observed on run 24880685728: the hostname-policy VAP correctly rejected
the foreign-hostname Gateway (apiserver returned the exact "Gateway
listener hostname must equal test.example.org" message), but the bats
test still failed. Root cause: the guard

  echo "$output" | grep -q "__SUCCEEDED__" && { return 1; }

is an AND list at statement level. When the marker is ABSENT (the
intended happy path — admission rejected, no marker captured), grep
exits 1, && short-circuits, the overall compound command returns 1,
and cozytest.sh's set -e kills the test.

Rewrite each of the four VAP negative-path guards as an if-statement:

  if echo "$output" | grep -q "__SUCCEEDED__"; then
    echo "BUG: …" >&2
    return 1
  fi

Bash's set -e explicitly ignores non-zero exits from commands inside
if-conditions, so the happy path falls through to the follow-up greps
that verify the expected rejection message.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:04 +03:00
Aleksei Sviridkin
e036a644e7
test(e2e): grant RBAC to impersonated SA in gateway VAP negative tests
Address review feedback from coderabbitai on hack/e2e-apps/gateway.bats:170 —
the VAP negative-path tests impersonate
system:serviceaccount:tenant-test:default, but that SA has no RBAC to
create apps.cozystack.io/tenants or to update/patch namespaces.
Authorization runs BEFORE admission, so without those grants the
apiserver returns a plain RBAC Forbidden, the test's grep for
"ValidatingAdmissionPolicy" fails, and the test appears to be a VAP
regression when the VAP is actually fine.

Create an ad-hoc Role + RoleBinding in tenant-test granting create/update
on apps.cozystack.io/tenants to default SA (scoped to tenant-test) for
the tenant-host-policy test, and a ClusterRole + ClusterRoleBinding
granting update/patch on core namespaces for the namespace-host-label
policy test. Both are deleted after the test runs so the sandbox stays
clean for subsequent tests.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
2925795a5f
fix(cilium): set defensive envoy DaemonSet resource baseline
Address observation from kitsunoff on packages/system/cilium/values.yaml:21 —
envoy.enabled: true turns on a per-node envoy DaemonSet but the upstream
default leaves envoy.resources at {} (no requests, no limits). PR
description cites ~100 MB RAM/node at idle; under L7 traffic that grows
without a cap, and the lack of requests also lets the DaemonSet schedule
onto any node with zero reserved headroom.

Pin the baseline matching the commented-out example in the upstream
Helm values: 100m CPU + 512Mi memory requests, 1Gi memory limit. That
gives the scheduler something to plan around and prevents a runaway
listener from OOM-ing the node without drawing attention.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
a622d346c6
fix(cozystack-basics): close tenant-host-policy bypass via clearing spec.host
Address review feedback from coderabbitai on
packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml:133 —
the matchCondition required object.spec.host != "", so an UPDATE that
unset or emptied the host field skipped the VAP entirely. A tenant with
empty spec.host inherits the apex from its parent, so clearing a
previously-set host is itself an effective apex change that the policy's
intent already covers. A non-trusted caller with UPDATE permission on
the Tenant could flip spec.host: foo.example.org → "" without ever
hitting the trustedCaller gate.

Rewrite the gate so the VAP fires whenever EITHER side of the update
has a non-empty host, and compute hostChanged over both oldHost and
newHost (each with its own CEL variable and ternary fallback to ""
when the field is absent). Leaves the validation unchanged: the change
is allowed only when hostChanged=false or variables.trustedCaller=true.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
9c96dc8e78
fix(gateway): require dns01 solver — Let's Encrypt refuses HTTP-01 for wildcard certs
Address review feedback from kitsunoff on
packages/extra/gateway/templates/issuer.yaml:21 — the per-tenant Issuer was
emitting an http01.gatewayHTTPRoute solver while the accompanying
Certificate in gateway.yaml requests both the apex and the *.<apex>
wildcard. Let's Encrypt refuses to issue wildcard certificates through
HTTP-01 (see LE challenge-types docs and the cert-manager CRD schema
note at crd-cert-manager.io_clusterissuers.yaml:728-729). Under the
default publishing.certificates.solver=http01, the Order would loop
forever, the Secret would never be created, and the Gateway HTTPS
listeners would sit without a cert. cert-manager-issuers ClusterIssuers
already branch on _cluster.solver (http01 vs dns01 Cloudflare); the
per-tenant Issuer was ignoring that signal entirely and the E2E flag
that would have exercised the full issuance flow was reverted in
a4bef14, so CI missed the regression.

Fail the render when publishing.certificates.solver=http01 with an
explicit message pointing at the root cause and the dns01/selfsigned
alternatives, and switch the emitted solver to dns01.cloudflare (same
shape cluster-issuers.yaml uses). Add a unit test for the http01-fail
path and update the existing Issuer test asserts to match the dns01
solver shape.

Follow-up: add an E2E assertion that actually issues a Certificate
through the per-tenant Issuer and waits for .status.conditions[Ready]=True
once the gateway.enabled=true install path is re-enabled.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
3ff3d68132
fix(cozystack-basics): matchCondition by namespace prefix, move label lookup to variables with ternary fallback
Previous matchConditions on namespaceObject.metadata.labels were evaluating
to false or skipping silently despite the label being present
(verified via diagnostic test on run 24875535058: VAP exists, binding
has validationActions: [Deny], tenant-test namespace has
namespace.cozystack.io/host=test.example.org, yet admission still
accepted a Gateway with listener hostname dashboard.example.org).

Restructure the VAP so matchCondition does NOT touch namespaceObject —
it just checks the Gateway's declared namespace starts with tenant-
via object.metadata.namespace. The namespaceObject-based label lookup
moves into a CEL variable with a ternary that returns "" when the label
is missing, and the validation accepts if tenantHost is empty (skip) or
if every listener hostname matches. This way the gate fires predictably
for every tenant-* Gateway and the namespaceObject access happens in a
context where its shape is easier to reason about.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
4ef14c4147
fix(cozystack-basics,e2e): diagnose and simplify hostname-policy matchCondition
Run 24870368740 showed the VAP still not rejecting cross-tenant hostname
after the CEL chain fix. Diagnostic test on run 24873181209 confirmed:

1. tenant-test namespace DOES have namespace.cozystack.io/host=test.example.org.
2. admission still CREATES a Gateway with listener hostname dashboard.example.org
   (__SUCCEEDED__ marker appeared — kubectl apply returned 0).

So the label is present but the VAP's matchCondition evaluates to false
for some reason, skipping the policy entirely. The prime suspect is
has(namespaceObject.metadata) on a Kubernetes unstructured representation
where the has() macro semantics don't match the typed Namespace resource
my chain fix assumed.

Simplify the matchCondition to use only the in-operator for map-key
presence ("k" in map) — this is the canonical CEL pattern for
K8s-style unstructured labels and does not rely on has() working
consistently across nested selection:

  namespaceObject != null &&
  "namespace.cozystack.io/host" in namespaceObject.metadata.labels &&
  namespaceObject.metadata.labels["..."] != ""

Also add a diagnostic test to hack/e2e-apps/gateway.bats that dumps the
VAP + binding yaml and asserts validationActions includes Deny — so if
anything structural breaks with the VAP installation, the failure is
visible in the first few lines of output.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:03 +03:00
Aleksei Sviridkin
992c67a433
test(e2e): diagnostic test — verify tenant-test has host label before VAP tests
The VAP 'ValidatingAdmissionPolicy rejects Gateway with foreign hostname'
silently fails to reject when tenant-test namespace lacks the
namespace.cozystack.io/host label — matchCondition returns false, VAP
skips, Gateway is admitted. That's what happened on run 24870368740.

Add a dedicated test BEFORE the VAP tests that asserts tenant-test
actually has the expected host label. If it doesn't, the test fails with
a clear SETUP FAILURE message and dumps the full namespace yaml to CI
logs, so the real root-cause (label missing — tenant chart bug, helm
timing, or namespaceObject representation issue) is visible instead of
being obscured by the downstream VAP test failure.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:02 +03:00
Aleksei Sviridkin
74c406e331
test(e2e): rewrite VAP tests without bats run helper (cozytest.sh is pure shell)
hack/cozytest.sh is a pure-shell bats-compat runner, not real bats. The
'run' builtin that bats ships (captures cmd output/status into $output
and $status) is unavailable, so every test using 'run kubectl …' fails
with 'run: not found' as soon as it's exercised. Previous runs didn't
surface this because install-cozystack was failing before the gateway
bats file could execute — now that the install path is green, the VAP
tests actually run and hit this trap.

Rewrite the four VAP negative-path tests to capture kubectl output and
exit status manually. Uses '&& echo __SUCCEEDED__' inside the command
substitution so the happy-path (admission accepted something it
shouldn't) is detectable, and captures stderr via 2>&1 so admission
rejection messages land in $output for grep assertions.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:02 +03:00
Aleksei Sviridkin
cec5f8d1d2
fix(cozystack-basics): chain has() through each level of namespaceObject
Second CEL bug in the same VAP surfaced in E2E run 24862782568 (gateway
bats test on tenant-test namespace): matchCondition
has(namespaceObject.metadata.labels) errored at admission time with
"no such key: metadata" — apiserver rejected the Gateway with
"ValidatingAdmissionPolicy denied request: expression '...' resulted in
error: no such key: metadata".

In Kubernetes CEL the has() macro checks field presence at the last
selection only — has(a.b.c) requires a.b to already be resolvable.
When the intermediate step is missing or the object is represented as
an unstructured map with a missing key, CEL raises 'no such key' at
evaluation rather than letting has() short-circuit to false.

Chain the checks per Kubernetes CEL docs recommendation (Check if a
field is set → has(a.b) && has(a.b.c) && ...):

  namespaceObject != null &&
  has(namespaceObject.metadata) &&
  has(namespaceObject.metadata.labels) &&
  "namespace.cozystack.io/host" in namespaceObject.metadata.labels &&
  namespaceObject.metadata.labels["namespace.cozystack.io/host"] != ""

The null-check handles the cluster-scoped case that K8s documents as
'namespaceObject is null when the incoming object is cluster-scoped',
the has() chain handles the unstructured-map case that surfaced in the
gateway-e2e-probe on tenant-test.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:02 +03:00
Aleksei Sviridkin
e4963d47f4
fix(cozystack-basics): has(oldObject) is not valid CEL — use oldObject != null
The cozystack-tenant-host-policy VAP failed to install because its CEL
variable used has(oldObject), which is not a valid CEL macro: has()
requires a field selection expression like has(x.y), not a bare
identifier check. The apiserver rejected the policy with
"invalid argument to has() macro", Helm install of cozystack-basics
failed, Flux triggered uninstall remediation which deleted the namespaces
created by the chart (cozy-public, tenant-root), and every downstream
HelmRelease that had to create resources in cozy-public or tenant-root
(kubevirt-cdi, the tenant chart, etc.) then failed with
"namespace ... because it is being terminated". Root cause for the
whole install-cozystack E2E regression on this branch.

Replace has(oldObject) with oldObject != null. On CREATE oldObject is
null and the ternary returns true (hostChanged); on UPDATE oldObject is
set and the rest of the condition runs as before.

Found via the cozyreport artifact from run 24858285228 rerun — the
kubectl describe hr cozystack-basics output exposed the VAP compilation
error that the top-level HelmRelease status message truncated with
"1 error occurred: ...".

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:02 +03:00
Aleksei Sviridkin
f5066e977a
fix(gateway): fail render when publishing.externalIPs is empty and guard pre-CIDR input
Address review feedback from kitsunoff on
packages/extra/gateway/templates/cilium-lb-pool.yaml:9: the previous
behaviour rendered the tenant Gateway without a matching
CiliumLoadBalancerIPPool when publishing.externalIPs was empty. Cilium LB
IPAM then had no pool to serve the tenant's cilium-gateway-cozystack
Service, so the Service sat in <pending> forever with no address and the
operator got a silently non-working Gateway.

Replace the conditional skip with an explicit helm fail that names the
root cause. Also guard the CIDR suffix append on the absence of "/" to
accept pre-CIDR input (consistent with the same guard already shipped on
packages/extra/ingress/templates/cilium-lb-pool.yaml).

Update the unit test that asserted hasDocuments: count: 0 to assert the
new failed-template error message, and add expose-external-ips to every
other test so they don't accidentally cross the empty-IPs guard.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:02 +03:00
Aleksei Sviridkin
824be9354c
test(e2e): cover the three remaining VAPs in gateway.bats
Address review feedback from kitsunoff on
hack/e2e-apps/gateway.bats:79: only cozystack-gateway-hostname-policy was
exercised end-to-end. Commit 8770b87 specifically retrofitted
matchConditions onto the other three VAPs to stop failurePolicy: Fail from
turning missing fields into denials, which is a high-regression-risk area,
so each VAP needs its own test.

Add:
- cozystack-gateway-attached-namespaces-policy rejects a Package with a
  tenant-* entry in spec.components.platform.values.gateway.attachedNamespaces.
- cozystack-tenant-host-policy rejects a Tenant.spec.host set by an
  impersonated tenant-namespace ServiceAccount (non-trusted group list).
- cozystack-namespace-host-label-policy rejects a kubectl label overwrite
  on namespace.cozystack.io/host by the same non-trusted SA.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
afa69148cb
docs(gateway): rewrite security model to cover all four VAPs plus the render-time check
Address review feedback from kitsunoff on
packages/extra/gateway/README.md:17: the security model section described
only two layers, but packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml
ships four ValidatingAdmissionPolicies plus a render-time fail in
cozystack-basics. Rewrite the section to cover each VAP's scope and what
it guards against, plus the listener allowedRoutes whitelist and the
render-time fail — six layers, each one explained.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
ccde31cc8b
fix(platform): add default namespace to gateway.attachedNamespaces
Address review feedback from kitsunoff on
packages/system/cozystack-api/templates/api-tlsroute.yaml:10: the
kubernetes-api TLSRoute lives in the default namespace (it has to sit
next to the kubernetes Service it points at), but default was missing
from the platform's gateway.attachedNamespaces default list. The tenant
Gateway's listener allowedRoutes selector then rejected the TLSRoute,
so Kubernetes API through Gateway API silently failed to work.

Add default to the default whitelist, plus a comment explaining why it
has to be there.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
e60549e7da
fix(tenant): stop inheriting parent gateway reference
Address review feedback from kitsunoff on
packages/apps/tenant/templates/namespace.yaml:32: the previous
$gateway := $parentNamespace.gateway | default "" pattern made a child
tenant without gateway: true inherit the parent's gateway namespace into
_namespace.gateway. Harbor and Bucket in that child would then render
HTTPRoutes with parentRefs.namespace pointing at the parent, which fails
in two ways:

1. The parent Gateway's listener allowedRoutes selector whitelists only
   the parent namespace plus publishing.gateway.attachedNamespaces (a static
   cozy-* list). The child tenant namespace is not there, so the HTTPRoute
   ends up NotAllowedByListeners.
2. The parent wildcard Certificate covers <apex> and *.<apex> only. A
   child tenant apex is <name>.<parent-apex>, so a harbor hostname would
   be harbor.<name>.<parent-apex> — two subdomain levels deep — and no
   valid cert would be presented.

Drop the inheritance and require explicit tenant.spec.gateway=true on
each tenant that should host Gateway-attached apps. Tenants without
their own gateway fall back to the inherited ingress reference, which is
the same behaviour the ingress path already has.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
8aeeab0ae2
fix(bucket): bind HTTPRoute to the https listener only
Address review feedback from kitsunoff on
packages/system/bucket/templates/httproute.yaml:9: same HTTP->HTTPS
redirect regression as dashboard's HTTPRoute. Pin sectionName: https so
the bucket UI HTTPRoute stays on the TLS listener and the generic
http-to-https-redirect on port 80 actually fires for cleartext requests.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
966659903f
fix(harbor): bind HTTPRoute to the https listener only
Address review feedback from kitsunoff on
packages/apps/harbor/templates/httproute.yaml:10: same HTTP->HTTPS redirect
regression as dashboard's HTTPRoute. Pin sectionName: https so port 80
stays owned by the generic redirect HTTPRoute on the tenant Gateway.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:01 +03:00
Aleksei Sviridkin
4a5e856f7b
fix(keycloak): bind HTTPRoute to the https listener only
Address review feedback from kitsunoff on
packages/system/keycloak/templates/httproute.yaml:11: same HTTP->HTTPS
redirect regression as dashboard's HTTPRoute — without sectionName, the
route attached to both listeners and a specific-hostname route on port 80
won the precedence contest against the generic redirect HTTPRoute. Pin
sectionName: https so the keycloak route stays on the TLS-terminating
listener exclusively.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
49bc8c487a
fix(dashboard): bind HTTPRoute to the https listener only
Address review feedback from kitsunoff on
packages/system/dashboard/templates/httproute.yaml:11: without sectionName,
the HTTPRoute attached to both http:80 and https:443. Under Gateway API
hostname-precedence rules, a route with a specific hostname wins over the
generic http-to-https-redirect HTTPRoute on the http listener, so HTTP
traffic to http://dashboard.example.org/ was proxied directly to the
backend with no TLS — a regression against ingress-nginx behaviour.

Pin sectionName: https so port 80 stays fully owned by the redirect route.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
57f1c82aea
fix(cozystack-basics): narrow trustedCaller to explicit cozystack group list
Address review feedback from kitsunoff on
packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml:120:
startsWith("system:serviceaccount:cozy-") without a trailing colon trusted
any ServiceAccount in any namespace whose name begins with cozy- — including
a hypothetical attacker-controlled cozy-evil namespace. Creating such a
namespace requires cluster-admin today, so this is not an active escalation
path, but it is an unnecessarily wide trust boundary for a defense-in-depth
check.

Switch both tenant-host-policy and namespace-host-label-policy to a
group-based check that matches the exact system:serviceaccounts:<ns> group
for cozy-system, cozy-cert-manager, flux-system and kube-system. Every SA
in those namespaces is a member of that group automatically, so there is no
behaviour regression for cozystack's own controllers.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
21a3f21777
fix(cozystack-basics): gate gateway-hostname-policy with matchConditions
Address review feedback from kitsunoff on
packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml:22:
the first VAP had no matchConditions, so with failurePolicy: Fail and a
validation expression of variables.tenantHost != "", any Gateway in a
namespace without the namespace.cozystack.io/host label (kube-system,
default, any non-cozystack namespace) was rejected cluster-wide, including
clusters running with gateway.enabled: false.

Hoist the namespace-label precondition into matchConditions so the VAP only
fires for cozystack-managed tenant namespaces, then simplify the validation
body — the explicit tenantHost-nonempty check becomes redundant.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
9ea31dbcfb
fix(platform): move gateway-api-crds include out of the variant prologue to avoid YAML comment+separator collision
The bundle file begins with a variant-switching '# Networking'
comment followed by '{{- if eq .Values.bundles.system.variant ...}}'.
The left-strip on that if eats the newline after '# Networking' and
the next emitted '---' from the first package helper ends up
appended to the comment as '# Networking---', which YAML treats as
pure comment (no document separator). That hides the separator
between whatever was emitted before the variant block and the first
Package inside it, so the two documents merge and duplicate-key
errors fire at Flux post-render time.

Pre-existing behaviour was safe only because the variant block
itself produced the first cozystack.io Package, so no previous
Package existed to duplicate keys with. The previous commit put a
brand-new 'cozystack.gateway-api-crds' Package include right before
the '# Networking' comment — that Package's apiVersion then
collided with the networking Package's apiVersion because the
separator between them was consumed by the comment.

Move the gateway-api-crds include down to the 'Common Packages'
section, which has no strip-dash interaction with surrounding
comments. Package ordering in the bundle does not determine install
ordering — Flux honours the dependsOn chain on cozystack.networking
and cozystack.cert-manager, both of which declare a dependsOn on
cozystack.gateway-api-crds.

Verified locally that the rendered platform chart now emits every
Package preceded by '# Source:' comment on its own line, with the
helper-emitted '---' on a dedicated line. 'apiVersion' keys no
longer duplicate within any single YAML document.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
74046751cb
fix(cozystack-basics): gate VAP validations through matchConditions for safe CEL evaluation
Three of the four ValidatingAdmissionPolicies walked deeply into
object fields inside validation CEL expressions. With failurePolicy:
Fail and non-structural CRD schemas (Package, Tenant) the evaluator
could reject the request instead of skipping — which would cascade
into HelmReleases never being produced and the e2e install hanging
on 'waiting for more than 10 HelmReleases'.

Move path existence checks into matchConditions (Kubernetes 1.30+).
matchConditions are evaluated before validations; a false matchCondition
cleanly skips the validation rather than forcing failurePolicy. Switch
to the 'key in map' operator where possible — it is the supported safe
form for Kubernetes JSON without structural schema guarantees.

Policies fixed:

- cozystack-gateway-attached-namespaces-policy: matchCondition
  'has-gateway-attached-namespaces' checks every level of the path
  spec.components.platform.values.gateway.attachedNamespaces using
  'key in map'. Validation runs only on Packages that actually carry
  the field.
- cozystack-tenant-host-policy: matchCondition 'has-host-field' skips
  Tenants without a non-empty spec.host. The hostChanged variable no
  longer needs defensive has() checks.
- cozystack-namespace-host-label-policy: matchCondition 'had-host-label'
  skips namespaces that never had the namespace.cozystack.io/host label.
  The immutability rule now only fires on true UPDATE-of-set-label.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:04:00 +03:00
Aleksei Sviridkin
f9041fa49a
feat(cozystack-basics): two more runtime VAPs close the tenant.spec.host and namespace label hijack vectors
Security review left two residual trust-assumption gaps:

1. tenant.spec.host is user-controlled. A tenant admin with RBAC
   permission to create Tenant CRs could claim an arbitrary host
   (dashboard.example.org), have the tenant chart write that host
   into their namespace label, and thereby satisfy the per-namespace
   host VAP with a hijacked value.

2. namespace.cozystack.io/host is written by cozystack charts but
   there is no runtime check that prevents a later update to the
   label from an untrusted principal. A tenant with Update on their
   own namespace could rewrite the label to whatever they want and
   bypass the per-namespace host VAP.

Both close with parallel VAPs. 'Make it impossible — forbid it twice.'

cozystack-tenant-host-policy

  matchConstraints: apps.cozystack.io/v1alpha1 tenants, CREATE/UPDATE.
  Rejects setting or changing spec.host unless the caller is
  cluster-admin (system:masters group) or a cozystack/Flux/kube-system
  service account. Tenants are still free to leave spec.host empty
  (the normal default) — the tenant chart will compute the
  inherited host from the parent namespace. Admins who need to
  override do so explicitly via kubectl / cozystack-api.

cozystack-namespace-host-label-policy

  matchConstraints: core/v1 namespaces, UPDATE only.
  Rejects any change to the namespace.cozystack.io/host label once
  it has been set, unless the caller is in the same trusted caller
  whitelist. CREATE is unrestricted (initial label write happens
  there, by the chart). Result: the label is effectively
  write-once-by-cozystack — no tenant can rewrite their own host
  label after it is provisioned.

Both policies use failurePolicy: Fail and validationActions: [Deny],
so a missing paramRef or CEL error fails closed.

Combined with the two earlier VAPs (Gateway listener hostname +
Package attachedNamespaces) and the listener allowedRoutes namespace
whitelist, the hijack surface for multi-tenant Gateway API is now
guarded at four independent admission points and one runtime-proxy
allow-list. Bypass requires compromising a trusted service account
or obtaining cluster-admin credentials — at which point Gateway API
isolation is not the weakest link anyway.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:59 +03:00
Aleksei Sviridkin
3869a83983
feat(cozystack-basics): runtime VAP pair — per-namespace host + Package attachedNamespaces
Replaces the earlier ConfigMap-parameterised hostname VAP with two
independent ValidatingAdmissionPolicies that both enforce at runtime
and do not depend on the publisher's assumption that 'tenant host is
always <name>.<platform apex>'.

1. cozystack-gateway-hostname-policy

Now reads the tenant's real apex from the namespace label
namespace.cozystack.io/host, which the tenant chart already writes
onto every child tenant namespace and which this commit adds to
tenant-root itself. No CRD lookup, no paramRef, no assumption that
the tenant host is a subdomain of the cluster-wide publishing.host.

CEL:
  tenantHost := namespaceObject.metadata.labels['namespace.cozystack.io/host']
  every listener.hostname must equal tenantHost or endsWith '.' + tenantHost

Consequence:
- tenant-alice with spec.host = alice.example.org gets label
  alice.example.org → may publish alice.example.org and
  *.alice.example.org, nothing else.
- tenant-corp with spec.host = customer1.io (fully independent
  domain, NOT a subdomain of the platform apex) gets label
  customer1.io → may publish customer1.io and *.customer1.io.
  Previous VAP would have rejected this legitimate case.
- A namespace without the label (no cozystack-managed tenant) falls
  through tenantHost == '' → all listener hostnames rejected.

2. cozystack-gateway-attached-namespaces-policy (new)

Runtime counterpart to the render-time 'fail' guard on
_cluster.gateway-attached-namespaces. Watches Package CRs
(cozystack.io/v1alpha1) and rejects any UPDATE that introduces a
tenant-* entry under spec.components.platform.values.gateway.attachedNamespaces.
'kubectl edit packages.cozystack.io cozystack.cozystack-platform'
bypasses the Helm render path; this policy catches it.

CEL walks the array via .all(ns, !ns.startsWith('tenant-')) with
full path presence guards so it ignores packages that do not touch
the gateway block.

3. tenant-root namespace label

cozystack-basics/templates/tenant-root.yaml now writes
  labels.namespace.cozystack.io/host = {{ _cluster.root-host }}
so root tenant's Gateway resources get validated through the same
label-based VAP as child tenants. No ConfigMap-driven param, no
split path between root and child.

Both policies use failurePolicy: Fail and validationActions: [Deny].
They install unconditionally (no gateway.enabled gate) — Gateway CRDs
are installed on every bundle variant, so the policies must guard
every path.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:59 +03:00
Aleksei Sviridkin
31f630f763
fix(gateway): read per-tenant apex from _namespace.host, not _cluster.host
Two correctness fixes that make extra/gateway actually work in a real
cluster, not just in the tests:

1. _cluster.host does not exist

The Secret projected from platform's apps.yaml only exports
_cluster.root-host — the cluster-wide publishing apex (e.g.
example.org). There is no _cluster.host key. The gateway template was
reading _cluster.host, which always evaluated to empty, which always
tripped the 'publishing.host must be set' fail guard. extra/gateway
therefore never rendered in a real cluster; the helm-unittest cases
passed only because they explicitly put a host field under _cluster,
which never happens in production. Switch to _namespace.host — the
per-tenant apex that cozystack-basics (for tenant-root) and the
tenant chart's namespace.yaml (for child tenants) both populate.

2. Guard against 'non-publishing namespace' blocked child tenants

The previous 'if not (eq $exposeIngress .Release.Namespace)' guard
forced extra/gateway to render only in the publishing tenant
namespace. Child tenants with spec.gateway=true deploy extra/gateway
into their own namespace, so the guard always fired and no child
Gateway was ever materialised — despite earlier commits claiming
child-tenant ACME works. The guard is removed; extra/gateway now
renders in whichever namespace it is released into, which matches
the per-tenant HelmRelease template.

Side-effects:

- CiliumLoadBalancerIPPool no longer carries the '== publishing
  namespace' condition — each tenant-scoped release produces its
  own pool, selecting its own cilium-gateway-cozystack Service by
  io.kubernetes.service.namespace. Different pools do not conflict
  as Kubernetes resources; IP allocation across pools with
  overlapping blocks is an operator concern (document).
- issuer.yaml unchanged — the Issuer's parentRef already had no
  namespace, so the solver attaches to the local Gateway regardless
  of which tenant namespace we render in.
- A new helm-unittest case exercises the child-tenant path
  (tenant-alice with host=alice.example.org): Certificate dnsNames,
  Gateway listener hostnames, allowedRoutes whitelist, and
  CiliumLoadBalancerIPPool selector all resolve to the child's
  apex and namespace.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:59 +03:00
Aleksei Sviridkin
0f44e2af57
docs(gateway): child-tenant ACME is no longer a limitation
Remove the child-tenant ACME HTTP-01 entry from Known limitations in
the gateway README. With the per-tenant Issuer added in the previous
commit, each tenant that opts into gateway: true gets its own ACME
account, its own HTTPRoute solver targeting its own Gateway, and no
dependency on the publishing tenant's Gateway.

In its place, document the actual remaining constraint: the
per-tenant Issuer template currently supports two issuer names
(letsencrypt-prod, letsencrypt-stage) — any other value fails the
render with an actionable error. Supporting more ACME providers is
a one-case extension of templates/issuer.yaml, so operators know
exactly where to hook in.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:59 +03:00
Aleksei Sviridkin
49d896caca
feat(gateway): per-tenant Issuer enables child-tenant ACME, VAP unconditional
Two correctness fixes for multi-tenant Gateway ACME, plus a small
default-tightening.

1. Per-tenant Issuer (child-tenant ACME closes)

packages/extra/gateway/templates/issuer.yaml (new): render a
cert-manager.io/v1 Issuer named 'gateway' in the tenant's own
namespace. It carries its own ACME account (privateKeySecretRef
'gateway-acme-account') and an http01.gatewayHTTPRoute solver whose
parentRef points to the local Gateway 'cozystack' at sectionName http
— no namespace on parentRef, so it attaches in-namespace only.

packages/extra/gateway/templates/gateway.yaml: the wildcard
Certificate now references issuerRef kind: Issuer, name: gateway
(namespace-scoped) instead of the previous cluster-scoped
letsencrypt-prod. The result: every tenant that enables
tenant.spec.gateway=true gets a fully self-contained ACME flow —
its own account, its own HTTPRoute, its own Gateway, no cross-
namespace dependency on the publishing tenant. Child tenants with
gateway: true now work end-to-end for ACME HTTP-01.

The template maps 'publishing.certificates.issuerName' to a
concrete ACME server URL: letsencrypt-prod →
acme-v02.api.letsencrypt.org/directory, letsencrypt-stage →
acme-staging-v02.api.letsencrypt.org/directory. Any other value
fails the render with an explicit error pointing at the file to
extend.

Three new helm-unittest cases cover Certificate→Issuer linkage,
staging-server selection, and the unknown-issuer fail path.

2. Hostname VAP installs unconditionally

packages/system/cozystack-basics/templates/gateway-hostname-policy.yaml:
drop the 'eq gateway-enabled true' guard. The ValidatingAdmissionPolicy
now installs whenever publishing.host is set, regardless of whether
gateway.enabled is flipped. Rationale: Gateway CRDs ship
unconditionally (gateway-api-crds is loaded in every bundle), so a
tenant could create a Gateway manually even with gateway.enabled=false.
The VAP must guard that path too.

3. Restore opt-in default in e2e

hack/e2e-install-cozystack.bats: revert the gateway.enabled: true
line so the default e2e platform configuration matches production
defaults. Gateway API remains strictly opt-in. The
'exposed services render HTTPRoute/TLSRoute but not Ingress' test
(which required platform-wide gateway.enabled=true) is removed; the
VAP cross-tenant reject test stays and now works against the
unconditionally-installed policy.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:59 +03:00
Aleksei Sviridkin
8442f4e44e
test(e2e): flip gateway.enabled=true by default and extend gateway.bats
hack/e2e-install-cozystack.bats: add 'gateway: {enabled: true}' to the
values used for the cozystack.cozystack-platform Package. The e2e
pipeline therefore exercises the Gateway API path as its primary
integration scenario — dashboard, keycloak render as HTTPRoutes;
cozystack-api, vm-exportproxy, cdi-uploadproxy render as TLSRoutes;
the legacy Ingresses for those services should not exist.

hack/e2e-apps/gateway.bats: two new test cases.

1. 'exposed services render HTTPRoute/TLSRoute but not Ingress when
   gateway.enabled=true' — waits for the HTTPRoutes for dashboard and
   keycloak to reach Accepted, confirms the three TLSRoutes exist in
   their respective namespaces, and asserts (negative tests) that the
   old Ingress objects are gone. Catches regressions where a developer
   forgets to wrap an Ingress in the gateway-enabled conditional.
2. 'ValidatingAdmissionPolicy rejects Gateway with foreign hostname' —
   tries to apply a Gateway in tenant-test that claims
   dashboard.example.org (a domain outside the tenant's allowed suffix
   test.example.org), asserts kubectl fails with the expected VAP error
   and the expected message.

Together these cover the two most important regressions this PR is
shipping against: Ingress leaking through when it should not, and
the hostname-hijacking defence silently disappearing.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
72b2c80cf1
docs(gateway): recommend per-tenant certificate count quota, refresh known limitations
README now shows the exact Tenant manifest snippet for capping the
number of Certificate objects a tenant may create
(count/certificates.cert-manager.io: 10), and calls out that the
default is unlimited so operators on shared-apex multi-tenant clusters
must set this before handing gateway=true to untrusted tenants.

Also rewrites the 'Known limitations' section to reflect what this
PR actually ships: TLS passthrough (cozystack-api, vm-exportproxy,
cdi-uploadproxy) and per-tenant apps (harbor, bucket) are no longer
limitations — they all migrate to Gateway API when gateway.enabled=true.
What's left:

- Child-tenant ACME HTTP-01 still relies on the publishing tenant's
  Gateway; a follow-up PR will add namespace-scoped Issuers.
- Upstream application-level gaps (harbor ACL / bucket upstream
  features) — carried as upstream PRs, not a cozystack blocker.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
1cddf71288
feat(cozystack-basics): reject tenant-* namespaces in gateway.attachedNamespaces
Render-time guard at the top of gateway-hostname-policy.yaml walks
_cluster.gateway-attached-namespaces and fails the chart render with
an explicit message if any entry begins with 'tenant-'.

Adding a tenant namespace to the attached whitelist would defeat the
whole point of the whitelist: that tenant could then attach arbitrary
HTTPRoutes to the publishing tenant's Gateway and pick any hostname
inside the apex domain. Catching this at 'helm template' time beats
catching it after the Gateway listener is already programmed and
traffic can flow.

The message spells out the correct recourse — child tenants that
need their own Gateway must flip tenant.spec.gateway=true, which
materialises their own Gateway in their own namespace rather than
borrowing the publishing tenant's.

Applies whether gateway.enabled is true or false — validation on the
attachedNamespaces list is orthogonal to whether the policy itself
is installed.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
b719cf67e3
feat(tenant,harbor,bucket): wire per-tenant apps through the tenant Gateway
Tenants can now opt their own apps into Gateway API without touching
the publishing tenant. The mechanism mirrors the existing
_namespace.ingress contract exactly.

packages/apps/tenant/templates/namespace.yaml:

- Compute a new $gateway value: if the tenant sets .Values.gateway
  it becomes the tenant's own namespace, otherwise it inherits from
  the parent namespace (empty means no Gateway anywhere in the chain).
- Ship $gateway out through the cozystack-values Secret under
  _namespace.gateway and through a namespace label
  namespace.cozystack.io/gateway.

packages/apps/harbor and packages/system/bucket:

- Existing Ingress wrapped in '{{ if not $gateway }}' so it only
  renders when no Gateway is attached anywhere up the tenant chain.
- New templates/httproute.yaml render when $gateway is non-empty:
  apiVersion gateway.networking.k8s.io/v1 HTTPRoute, parentRef to
  the 'cozystack' Gateway in whichever namespace $gateway points
  at, hostname <release>.<host> (harbor) or <bucketName>.<host>
  (bucket), backendRef to the existing Service on its current port.

Per-tenant resolution: a tenant with .Values.gateway=true gets its
own Gateway in its own namespace, and harbor/bucket deployed inside
that tenant attach to that namespace's Gateway — no cross-namespace
references, no coupling to the publishing tenant.

Default remains ingress-nginx: tenants that do not opt in keep
rendering Ingress verbatim.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
2c5bf50f43
feat(gateway): TLSRoute for TLS-passthrough services (cozystack-api, vm-exportproxy, cdi-uploadproxy)
Wire the three HTTPS-passthrough services through Gateway API so
ingress-nginx is no longer required for them when gateway.enabled=true.

extra/gateway chart: new values.tlsPassthroughServices (defaults to
[api, vm-exportproxy, cdi-uploadproxy]). For each service in that list
AND in _cluster.expose-services, the Gateway emits an extra
port-443 listener with protocol: TLS, tls.mode: Passthrough, hostname
<svc>.<host>, and allowedRoutes.kinds restricted to TLSRoute. The
specific hostname wins over the wildcard HTTPS Terminate listener at
SNI-matching time per Gateway API spec.

Per-service packages:

- packages/system/cozystack-api: existing Ingress wrapped in
  '!= gateway-enabled=true'. New api-tlsroute.yaml renders
  apiVersion gateway.networking.k8s.io/v1alpha2 TLSRoute in the
  'default' namespace (where the kubernetes Service lives) targeting
  the tls-api listener, hostname api.<root-host>, backendRef kubernetes:443.
- packages/system/kubevirt: same treatment for
  vm-exportproxy-ingress.yaml → vm-exportproxy-tlsroute.yaml,
  hostname vm-exportproxy.<root-host>, backendRef vm-exportproxy:443
  in cozy-kubevirt.
- packages/system/kubevirt-cdi: same for cdi-uploadproxy —
  hostname cdi-uploadproxy.<root-host>, backendRef cdi-uploadproxy:443
  in cozy-kubevirt-cdi.

TLSRoute apiVersion v1alpha2 is intentional: Cilium 1.19 vendors
Gateway API CRDs v1.4 (TLSRoute is v1alpha2 there) and v1.5.1 ships
both v1 and v1alpha2 in the experimental channel, so v1alpha2 is
compatible with both. A follow-up can bump to v1 once Cilium v1.20
(Gateway API v1.5) lands in the platform.

Backward compatibility: default gateway.enabled=false keeps the
existing Ingress path verbatim for all three services.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
6914b8dbc0
docs(gateway): document security model, Let's Encrypt rate limits, known gaps
Add operator-facing documentation for the Gateway API feature:

packages/extra/gateway/README.md grows three sections:

- Security model — explains the two layers that protect cross-tenant
  isolation (Gateway listener allowedRoutes namespace whitelist +
  ValidatingAdmissionPolicy for tenant hostname ownership). Makes it
  explicit which namespaces are on the default whitelist so operators
  who add a new system component know where to register it.
- Rate limits — spells out the Let's Encrypt quotas (50 certs /
  registered domain / week, 5 duplicate certs / week, 300 new orders /
  account / 3h), lists mitigations (letsencrypt-stage, resourceQuotas
  with count/certificates.cert-manager.io, self-signed ClusterIssuer,
  internal ACME).
- Known limitations — TLS passthrough services still use ingress-nginx,
  tenant-scoped apps (harbor, bucket) not yet wired to per-tenant
  Gateway, child-tenant ACME HTTP-01 needs a namespace-scoped Issuer.
  All three are tracked as follow-up work rather than hidden failure
  modes.

packages/core/platform/values.yaml adds a comment block under
publishing.certificates.issuerName reminding operators of the
rate-limit consequences before they flip gateway.enabled=true on a
production cluster.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:58 +03:00
Aleksei Sviridkin
9505b08dd2
test(e2e): gateway.bats smoke-tests Cilium Gateway API wiring
Three bats test cases verify the end-to-end infrastructure brought up
by this PR:

1. Gateway API CRDs are installed (gatewayclasses, gateways, httproutes)
   and the 'cilium' GatewayClass is Accepted by the controller —
   proves gateway-api-crds installed and cilium.gatewayAPI.enabled
   propagated.
2. A minimal Gateway in tenant-test reconciles to Programmed and the
   controller materialises its cilium-gateway-<name> LoadBalancer
   Service — proves envoy.enabled kicked in and the data-plane wiring
   is live.
3. An HTTPRoute with a matching parentRef reaches Accepted status —
   proves Cilium's HTTPRoute attachment logic works.

Not covered (because the test harness has no reachable Let's Encrypt
endpoint and no way to flip cluster-wide gateway.enabled mid-pipeline
without trampling other tests):

- cert-manager HTTP-01 solver via gatewayHTTPRoute.
- The ValidatingAdmissionPolicy that enforces tenant hostname
  ownership (installed only when gateway.enabled=true at platform
  level).
- Full tenant.spec.gateway=true flow with extra/gateway chart and
  CiliumLoadBalancerIPPool.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:57 +03:00
Aleksei Sviridkin
bb3fc7cf26
feat(cozystack-basics): ValidatingAdmissionPolicy blocks cross-tenant hostname hijacking on Gateways
When gateway.enabled is true and publishing.host is set, cozystack-basics
now installs a ValidatingAdmissionPolicy (plus its Binding and a
ConfigMap that carries the apex host and publishing namespace as
parameters) that rejects any Gateway whose listeners reference a
hostname outside the tenant's own domain suffix.

Scheme:

- Publishing tenant namespace ($publishing.ingressName, default
  tenant-root): allowed suffix is the platform-wide $publishing.host.
- Any namespace prefixed with 'tenant-': allowed suffix is
  <name-stripped-of-tenant-prefix>.$publishing.host.
- Any other namespace: the CEL variable resolves to "" and every
  listener with a hostname is rejected — only cluster-admin-managed
  namespaces should be creating Gateways anyway.

The VAP is scoped to CREATE and UPDATE on gateway.networking.k8s.io/v1
(and v1beta1) Gateways cluster-wide; the Binding uses
validationActions: [Deny] with parameterNotFoundAction: Deny so that
if the ConfigMap is missing the policy fails safe instead of
open-allowing. messageExpression spells out the tenant-scoped allowed
suffix in the rejection, so operators can see at a glance why the
request was denied.

This closes the hostname-hijacking half of the multi-tenant threat
model on top of the namespace whitelist on Gateway listeners. The two
work in layers: the whitelist stops a non-authorised namespace from
attaching any HTTPRoute; the VAP stops an authorised namespace from
claiming someone else's hostname on its own Gateway.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:57 +03:00
Aleksei Sviridkin
142108e507
feat(dashboard,keycloak): attach to tenant Gateway via HTTPRoute when gateway.enabled
Each package now ships a conditional templates/httproute.yaml which is
rendered only when the cluster-wide gateway.enabled flag is true
(propagated via _cluster.gateway-enabled). The existing Ingress
template is wrapped in the inverse condition, so exactly one of the
two is rendered at a time and traffic does not split.

Dashboard: HTTPRoute hostname dashboard.<root-host>, backendRef
incloud-web-gatekeeper:8000 (same as the existing Ingress).

Keycloak: HTTPRoute hostname <ingress.host> (default
keycloak.<root-host>), backendRef keycloak-http:80.

Both routes parentRef the tenant Gateway named 'cozystack' in the
publishing namespace and rely on the namespace whitelist on Gateway
listeners (see 'fix(gateway): restrict tenant Gateway listener
allowedRoutes') to ensure only authorised namespaces can attach.

Known gap (follow-up): services that rely on TLS passthrough
(cozystack-api, vm-exportproxy, cdi-uploadproxy) still render their
existing Ingress regardless of gateway.enabled, because Gateway API
passthrough requires a separate TLSRoute + a dedicated
mode: Passthrough listener on the Gateway. Harbor and bucket are
tenant-scoped apps that need _namespace.gateway plumbing — also
follow-up.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:57 +03:00
Aleksei Sviridkin
6c2872af33
fix(gateway): restrict tenant Gateway listener allowedRoutes to an explicit namespace whitelist
Security fix: before this change the Gateway listeners used
'allowedRoutes.namespaces.from: Selector' with the tenant namespace
label, but when per-service HTTPRoutes had to live outside the
tenant namespace that label model broke — so the natural fix was to
relax to 'from: All'. That would have let any namespace in the
cluster attach an HTTPRoute with an arbitrary hostname to the
publishing tenant's Gateway, which is hostname hijacking across
tenants.

The correct solution is to pin each listener to an explicit namespace
whitelist using the built-in 'kubernetes.io/metadata.name' label that
kube-apiserver assigns to every namespace by default. Namespaces not
on the whitelist literally cannot attach HTTPRoutes to this Gateway,
so a non-publishing tenant cannot create a hijacking HTTPRoute in its
own namespace.

The whitelist is the union of:
- The publishing tenant namespace (always, implicitly added).
- 'publishing.gateway.attachedNamespaces' in the platform chart —
  a list of system namespaces that host exposed services and need to
  attach HTTPRoutes (cozy-cert-manager for ACME, cozy-dashboard,
  cozy-keycloak, cozy-system, cozy-harbor, cozy-bucket,
  cozy-kubevirt, cozy-kubevirt-cdi, cozy-monitoring,
  cozy-linstor-gui).

Plumbed through cozystack-values as '_cluster.gateway-attached-namespaces'
(CSV of namespaces). The gateway chart concats this CSV with the
release namespace, de-dupes via 'uniq', and emits the result as the
matchExpressions 'values' list on every listener.

Tests: 3 new helm-unittest cases in packages/extra/gateway/tests/
covering the default (publishing namespace only), CSV parsing with
empty-entry filtering, and the invariant that HTTPS listeners share
the whitelist with the HTTP listener.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:57 +03:00
Aleksei Sviridkin
77b57e8075
feat(cert-manager): switch HTTP-01 solver to gatewayHTTPRoute when gateway.enabled
Add a cluster-wide 'gateway.enabled' flag in packages/core/platform/values.yaml
(default false) and plumb it into cozystack-values as _cluster.gateway-enabled.
When set to true, the cert-manager ClusterIssuers in cert-manager-issuers
switch their http01 solver from the ingress-nginx backend (ingressClassName)
to the Gateway API backend (gatewayHTTPRoute). Both letsencrypt-prod and
letsencrypt-stage are updated in lockstep.

The new solver attaches to the tenant Gateway named 'cozystack' in the
publishing namespace via parentRefs with sectionName: http, so cert-manager
places its ephemeral HTTPRoute on the Gateway's HTTP (:80) listener. Path
matching on /.well-known/acme-challenge/ is more specific than the sibling
HTTPRoute that redirects HTTP to HTTPS, so ACME challenges arrive correctly.

Default behaviour (gateway.enabled=false) is unchanged — ingress-nginx
path remains the only solver on existing clusters.

Tests: packages/system/cert-manager-issuers/tests/solver_test.yaml adds
4 helm-unittest cases covering the ingress fallback, the gateway path for
both issuers, dns01 unaffected by the flag, and the empty-string default.
Picked up automatically by hack/helm-unit-tests.sh via the new Makefile
test target.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:57 +03:00
Aleksei Sviridkin
8afa6601c9
fix(tenant,gateway): regenerate values.schema.json and ApplicationDefinition CRD with cozyvalues-gen v1.3.0
The previous commit in this PR regenerated schema and CRD artefacts
using a local 'dev' build of cozyvalues-gen, which sorts
properties alphabetically. CI installs the pinned upstream release
(v1.3.0), which preserves values.yaml source order, so the committed
outputs diverged from what CI regenerates and pre-commit failed with
exit code 123.

Re-ran 'make generate' locally with the release binary from
https://github.com/cozystack/cozyvalues-gen/releases/tag/v1.3.0 to
produce the same output the CI pipeline expects.

Files refreshed:

- api/apps/v1alpha1/tenant/types.go — field order reverted to
  values.yaml source order (host, etcd, monitoring, ingress, gateway,
  seaweedfs, schedulingClass, resourceQuotas).
- packages/apps/tenant/values.schema.json — same reordering.
- packages/system/tenant-rd/cozyrds/tenant.yaml — regenerated from
  the refreshed schema, gateway bool field now properly sorted.
- packages/extra/gateway/values.schema.json — regenerated for the
  same reason; gateway package itself has only one field so the diff
  is cosmetic, but keeps the pipeline clean.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:40 +03:00
Aleksei Sviridkin
5dc416293f
feat(gateway): add per-tenant Gateway API package and tenant toggle
Introduces a full per-tenant Gateway API setup backed by Cilium. The
publishing tenant (the one whose namespace matches
publishing.ingressName) can opt into a Gateway via tenant.spec.gateway
instead of or alongside the existing Service.spec.externalIPs-based
ingress-nginx deployment.

Package layout:

- packages/extra/gateway/ — new Helm chart that renders, per release:
  * cert-manager Certificate for the apex and wildcard hostnames.
  * One Gateway with three listeners — HTTP:80 (ACME challenges and
    redirect), HTTPS:443 wildcard *.<host>, HTTPS:443 apex <host>.
    Each listener uses allowedRoutes.namespaces.from=Selector keyed on
    label cozystack.io/gateway=<tenant namespace> so system services
    can attach HTTPRoutes cross-namespace without ReferenceGrants.
  * HTTPRoute http-to-https-redirect (301) on the HTTP listener.
    cert-manager's own ACME solver HTTPRoute for
    /.well-known/acme-challenge/ will take precedence via Gateway
    API's more-specific-path matching rules.
  * CiliumLoadBalancerIPPool scoped to the tenant namespace and the
    Gateway's cilium-gateway-cozystack Service, so the IPs from
    publishing.externalIPs get announced via LB IPAM.
  * Render-time guards: fails loudly if released outside the
    publishing namespace or if publishing.host is unset.

- packages/apps/tenant/ — new values key 'gateway: false' and a
  conditional HelmRelease template that references the gateway
  ExternalArtifact when the tenant opts in. Mirrors the existing
  ingress toggle verbatim, including labels and Flux reconcile config.

- packages/core/platform/sources/gateway-application.yaml — new
  PackageSource cozystack.gateway-application with a single 'default'
  variant that wires extra/gateway as a tenant module and dependsOn
  cozystack.gateway-api-crds + cozystack.cert-manager.

- packages/core/platform/templates/bundles/system.yaml — loads
  cozystack.gateway-application in every system variant so the
  ExternalArtifact is materialised before any tenant tries to use it.

- api/apps/v1alpha1/tenant/types.go, values.schema.json, README.md,
  packages/system/tenant-rd/cozyrds/tenant.yaml — regenerated to
  include the new Gateway bool field on TenantSpec.

- packages/extra/gateway/tests/gateway_test.yaml — 6 helm-unittest
  cases covering the IPv4/IPv6/mixed IP paths, empty-entry filtering,
  the no-IPs-still-renders-Gateway path, the non-publishing-namespace
  guard, and the empty-host guard.

Default behaviour is unchanged: tenants default to gateway=false and
the platform only materialises the ExternalArtifact (no resources
inside any tenant namespace unless it opts in).

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:39 +03:00
Aleksei Sviridkin
7f2354170e
feat(platform): install gateway-api-crds on the host cluster
Register a dedicated cozystack.gateway-api-crds PackageSource and wire
it into the system bundle before networking/cert-manager load. Without
this the host cluster has no gateway.networking.k8s.io CRDs, Cilium's
Gateway API controller cannot bootstrap (no GatewayClass registered),
and cert-manager's gateway-shim controller silently disables Gateway
API certificate automation.

- New PackageSource cozystack.gateway-api-crds → installs
  packages/system/gateway-api-crds into namespace cozy-gateway-api.
- cozystack.networking (variants cilium, cilium-kilo, cilium-generic,
  kubeovn-cilium, kubeovn-cilium-generic) dependsOn
  cozystack.gateway-api-crds so Cilium only starts once the CRDs are
  present.
- cozystack.cert-manager dependsOn cozystack.gateway-api-crds, closing
  the startup race that the #2208 discussion flagged — cert-manager's
  gateway-shim discovers CRDs at process start, so racing with CRD
  install left Gateway API solvers permanently disabled until the pod
  was restarted.
- system bundle loads cozystack.gateway-api-crds unconditionally for
  every variant (isp-full, isp-hosted, isp-full-generic).

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:39 +03:00
Aleksei Sviridkin
2eb7bccee4
feat(cilium): enable embedded envoy and Gateway API controller
Flip envoy.enabled and gatewayAPI.enabled on the vendored Cilium chart.
Cilium becomes the Gateway API implementation for Cozystack:
cilium-envoy DaemonSet starts on each node (approximately 100MB RAM
per node in steady state), and the Cilium operator begins reconciling
gateway.networking.k8s.io resources and publishing the built-in
'cilium' GatewayClass.

This value flip alone does not create any Gateway objects. The
platform installs only an idle Envoy DaemonSet and a GatewayClass
until per-tenant gateway manifests are actually created by the
platform chart.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:39 +03:00
Aleksei Sviridkin
47aca33c5a
chore(gateway-api-crds): bump to v1.5.1
Align vendored Gateway API CRDs with the latest stable upstream
release (v1.5.1, Oct 2026). TLSRoute graduates to GA in v1.5, still
shipped from the experimental channel to keep the superset of
optional fields. Cilium 1.19 consumes Gateway API CRDs through
standard backward-compatible versioning, so a v1.5 schema is
compatible with the Cilium 1.19 controller.

Notable additions over the previous v1.2.0 vendoring:

- ListenerSet (was XListenerSet / GEP-1713) — shared Gateway with
  listeners delegated from separate LS objects. Will enable a
  one-Gateway-per-cluster topology for the upcoming Gateway API work.
- BackendTLSPolicy for upstream-to-upstream TLS termination.
- XMesh (experimental) for mesh-specific routing hooks.
- ValidatingAdmissionPolicy 'safe-upgrades.gateway.networking.k8s.io'
  plus its binding, shipped by upstream to prevent mixing channels
  and downgrading CRD versions.

Stepping stone for the upcoming Gateway API via Cilium work; isolated
from that change so it can be rolled back on its own if any downstream
consumer breaks on the newer schema.

Assisted-By: Claude <noreply@anthropic.com>
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-04-24 17:03:39 +03:00
51 changed files with 10153 additions and 1334 deletions

View file

@ -29,6 +29,9 @@ type ConfigSpec struct {
// Deploy own Ingress Controller.
// +kubebuilder:default:=false
Ingress bool `json:"ingress"`
// Deploy own Gateway API Gateway (backed by Cilium Gateway API controller).
// +kubebuilder:default:=false
Gateway bool `json:"gateway"`
// Deploy own SeaweedFS.
// +kubebuilder:default:=false
Seaweedfs bool `json:"seaweedfs"`

356
hack/e2e-apps/gateway.bats Normal file
View file

@ -0,0 +1,356 @@
#!/usr/bin/env bats
@test "Gateway API CRDs are installed and the cilium GatewayClass is Accepted" {
# Gateway API CRDs must exist — installed by packages/system/gateway-api-crds
kubectl wait crd/gatewayclasses.gateway.networking.k8s.io --for=condition=Established --timeout=60s
kubectl wait crd/gateways.gateway.networking.k8s.io --for=condition=Established --timeout=60s
kubectl wait crd/httproutes.gateway.networking.k8s.io --for=condition=Established --timeout=60s
# Cilium must have registered its built-in GatewayClass once gatewayAPI.enabled
# is true in the cilium values. This verifies the flip in
# packages/system/cilium/values.yaml propagated end-to-end.
timeout 120 sh -ec 'until kubectl get gatewayclass cilium >/dev/null 2>&1; do sleep 2; done'
kubectl wait gatewayclass/cilium --for=condition=Accepted --timeout=3m
}
@test "Cilium Gateway API controller reconciles a minimal Gateway to Programmed" {
# Use the pre-existing tenant-test namespace created by e2e-install-cozystack.bats.
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: gateway-e2e-probe
namespace: tenant-test
spec:
gatewayClassName: cilium
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: Same
EOF
# The controller must accept and program the Gateway.
kubectl -n tenant-test wait gateway/gateway-e2e-probe --for=condition=Accepted --timeout=2m
kubectl -n tenant-test wait gateway/gateway-e2e-probe --for=condition=Programmed --timeout=3m
# Cilium materialises a LoadBalancer Service named cilium-gateway-<gateway-name>
# for each programmed Gateway. Its existence is the observable proof that the
# full data-plane wiring kicked in.
kubectl -n tenant-test get svc cilium-gateway-gateway-e2e-probe
# Cleanup
kubectl -n tenant-test delete gateway/gateway-e2e-probe --ignore-not-found --timeout=1m
}
@test "cozystack-gateway-hostname-policy VAP and binding are installed" {
# Diagnose the hostname-policy enforcement path from the ground up.
# If these resources are missing, admission cannot reject anything.
kubectl get validatingadmissionpolicy cozystack-gateway-hostname-policy -o yaml
kubectl get validatingadmissionpolicybinding cozystack-gateway-hostname-policy -o yaml
# Binding MUST have validationActions: [Deny] — [Audit] / [] would let requests through silently.
actions=$(kubectl get validatingadmissionpolicybinding cozystack-gateway-hostname-policy -o jsonpath='{.spec.validationActions}')
echo "binding.validationActions=$actions"
case "$actions" in
*Deny*) ;;
*) echo "SETUP FAILURE: binding.validationActions lacks Deny (got '$actions')" >&2; return 1 ;;
esac
}
@test "tenant-test namespace carries namespace.cozystack.io/host label from tenant chart" {
# Diagnostic: the whole hostname-policy VAP keys off this label. If it is
# missing or empty, the VAP's matchCondition returns false, VAP skips, and
# EVERY Gateway in the namespace is admitted regardless of listener hostname.
# Make that bug loud instead of letting it fall through as a silent pass.
host_label=$(kubectl get namespace tenant-test -o jsonpath='{.metadata.labels.namespace\.cozystack\.io/host}')
if [ -z "$host_label" ]; then
echo "SETUP FAILURE: tenant-test namespace lacks namespace.cozystack.io/host label" >&2
kubectl get namespace tenant-test -o yaml >&2
return 1
fi
if [ "$host_label" != "test.example.org" ]; then
echo "SETUP FAILURE: tenant-test host label is '$host_label', expected 'test.example.org'" >&2
kubectl get namespace tenant-test -o yaml >&2
return 1
fi
}
@test "ValidatingAdmissionPolicy rejects Gateway with foreign hostname" {
# tenant-test namespace should only be allowed to publish its own
# domain suffix ('.test.example.org'); a listener hostname from the
# root tenant's apex must be denied by cozystack-gateway-hostname-policy.
# hack/cozytest.sh is /bin/sh (dash) with set -e — a failing command
# substitution propagates its exit status through variable assignment and
# kills the test. We specifically EXPECT admission to reject the apply, so
# use `if !` — set -e is disabled inside the if-condition, the exit status
# is captured, and $output is filled either way for the follow-up greps.
if ! output=$(kubectl apply -f - 2>&1 <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: hostname-hijack-probe
namespace: tenant-test
spec:
gatewayClassName: cilium
listeners:
- name: https
protocol: HTTPS
port: 443
hostname: "dashboard.example.org"
tls:
mode: Terminate
certificateRefs:
- name: noop
allowedRoutes:
namespaces:
from: Same
EOF
); then
# Happy path: admission rejected the Gateway. Verify the rejection came
# from our VAP and names the expected tenant host.
echo "$output" | grep -qi "ValidatingAdmissionPolicy"
echo "$output" | grep -q "must equal test.example.org"
else
echo "BUG: admission accepted cross-tenant hostname — Gateway 'hostname-hijack-probe' was created in tenant-test" >&2
echo "$output" >&2
return 1
fi
}
@test "cozystack-gateway-attached-namespaces-policy rejects Packages with tenant-* entries" {
# The platform Package default name is cozystack.cozystack-platform, managed by
# cozystack-api. Creating a dummy Package with tenant-alice in gateway.attachedNamespaces
# must fail at admission time.
if ! output=$(kubectl apply -f - 2>&1 <<'EOF'
apiVersion: cozystack.io/v1alpha1
kind: Package
metadata:
name: vap-reject-probe
spec:
variant: isp-full
components:
platform:
values:
gateway:
attachedNamespaces:
- tenant-alice
EOF
); then
echo "$output" | grep -qi "ValidatingAdmissionPolicy"
echo "$output" | grep -q "must not contain any tenant-"
else
echo "BUG: admission accepted tenant-* in attachedNamespaces — Package 'vap-reject-probe' was created" >&2
echo "$output" >&2
kubectl delete package vap-reject-probe --ignore-not-found
return 1
fi
}
@test "cozystack-tenant-host-policy blocks non-trusted callers from setting tenant.spec.host" {
# Impersonate a tenant-scoped ServiceAccount that is NOT in the trustedCaller
# group list. First grant RBAC to create Tenants — authorization runs BEFORE
# admission, so without this grant the apiserver returns a plain RBAC
# Forbidden and the test would fail grep-ing for 'ValidatingAdmissionPolicy'
# even though the VAP itself is fine.
kubectl apply -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: vap-probe-tenant-create
namespace: tenant-test
rules:
- apiGroups: ["apps.cozystack.io"]
resources: ["tenants"]
verbs: ["create","get","list","watch","update","patch","delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: vap-probe-tenant-create
namespace: tenant-test
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: vap-probe-tenant-create
subjects:
- kind: ServiceAccount
name: default
namespace: tenant-test
EOF
if ! output=$(kubectl --as=system:serviceaccount:tenant-test:default \
--as-group=system:serviceaccounts \
--as-group=system:serviceaccounts:tenant-test \
apply -f - 2>&1 <<'EOF'
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
metadata:
name: vaphostprobe
namespace: tenant-test
spec:
host: foreign.example.org
EOF
); then
kubectl -n tenant-test delete rolebinding vap-probe-tenant-create --ignore-not-found
kubectl -n tenant-test delete role vap-probe-tenant-create --ignore-not-found
echo "$output" | grep -qi "ValidatingAdmissionPolicy"
echo "$output" | grep -q "spec.host can only be set"
else
kubectl -n tenant-test delete tenants.apps.cozystack.io vaphostprobe --ignore-not-found
kubectl -n tenant-test delete rolebinding vap-probe-tenant-create --ignore-not-found
kubectl -n tenant-test delete role vap-probe-tenant-create --ignore-not-found
echo "BUG: admission accepted tenant.spec.host from untrusted SA — Tenant 'vaphostprobe' was created" >&2
echo "$output" >&2
return 1
fi
}
@test "cozystack-namespace-host-label-policy blocks non-trusted callers from changing the host label" {
# tenant-test namespace already has namespace.cozystack.io/host set by the
# cozystack tenant chart. Grant patch on namespaces cluster-wide to the
# impersonated SA — namespaces is a cluster-scoped resource so this needs a
# ClusterRole. Authorization runs before admission, so without this grant
# the test would fail with plain RBAC Forbidden rather than a VAP rejection.
kubectl apply -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: vap-probe-namespace-patch
rules:
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["get","list","watch","update","patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: vap-probe-namespace-patch
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: vap-probe-namespace-patch
subjects:
- kind: ServiceAccount
name: default
namespace: tenant-test
EOF
if ! output=$(kubectl --as=system:serviceaccount:tenant-test:default \
--as-group=system:serviceaccounts \
--as-group=system:serviceaccounts:tenant-test \
label namespace tenant-test \
namespace.cozystack.io/host=foreign.example.org --overwrite 2>&1); then
kubectl delete clusterrolebinding vap-probe-namespace-patch --ignore-not-found
kubectl delete clusterrole vap-probe-namespace-patch --ignore-not-found
echo "$output" | grep -qi "ValidatingAdmissionPolicy"
echo "$output" | grep -q "immutable"
else
# Revert label if apiserver somehow accepted the overwrite.
kubectl label namespace tenant-test namespace.cozystack.io/host=test.example.org --overwrite
kubectl delete clusterrolebinding vap-probe-namespace-patch --ignore-not-found
kubectl delete clusterrole vap-probe-namespace-patch --ignore-not-found
echo "BUG: admission accepted host label change from untrusted SA" >&2
echo "$output" >&2
return 1
fi
}
@test "cozystack-namespace-host-label-policy blocks non-trusted callers from setting the host label at CREATE" {
# Defense-in-depth: a non-trusted caller must not be able to stamp
# namespace.cozystack.io/host=X on a brand-new namespace either — only
# cozystack/Flux SAs may write the label. Authorization runs before
# admission, so grant cluster-wide namespace create to the impersonated SA
# first, otherwise the test would fail with plain RBAC Forbidden.
kubectl apply -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: vap-probe-namespace-create
rules:
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["create","get","list","delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: vap-probe-namespace-create
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: vap-probe-namespace-create
subjects:
- kind: ServiceAccount
name: default
namespace: tenant-test
EOF
if ! output=$(kubectl --as=system:serviceaccount:tenant-test:default \
--as-group=system:serviceaccounts \
--as-group=system:serviceaccounts:tenant-test \
apply -f - 2>&1 <<'EOF'
apiVersion: v1
kind: Namespace
metadata:
name: vap-host-label-probe
labels:
namespace.cozystack.io/host: foreign.example.org
EOF
); then
kubectl delete clusterrolebinding vap-probe-namespace-create --ignore-not-found
kubectl delete clusterrole vap-probe-namespace-create --ignore-not-found
echo "$output" | grep -qi "ValidatingAdmissionPolicy"
echo "$output" | grep -q "immutable"
else
kubectl delete namespace vap-host-label-probe --ignore-not-found --wait=false
kubectl delete clusterrolebinding vap-probe-namespace-create --ignore-not-found
kubectl delete clusterrole vap-probe-namespace-create --ignore-not-found
echo "BUG: admission accepted first-time host label write from untrusted SA at CREATE — Namespace 'vap-host-label-probe' was created" >&2
echo "$output" >&2
return 1
fi
}
@test "HTTPRoute with a matching parentRef reaches Accepted status" {
# Put a Gateway and a route in the same namespace so allowedRoutes: Same accepts them.
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: gateway-route-probe
namespace: tenant-test
spec:
gatewayClassName: cilium
listeners:
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: Same
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: httproute-probe
namespace: tenant-test
spec:
parentRefs:
- name: gateway-route-probe
sectionName: http
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: kubernetes
namespace: default
port: 443
EOF
kubectl -n tenant-test wait gateway/gateway-route-probe --for=condition=Programmed --timeout=3m
timeout 120 sh -ec 'until kubectl -n tenant-test get httproute httproute-probe -o jsonpath="{.status.parents[0].conditions[?(@.type==\"Accepted\")].status}" 2>/dev/null | grep -q True; do sleep 2; done'
kubectl -n tenant-test delete httproute/httproute-probe --ignore-not-found
kubectl -n tenant-test delete gateway/gateway-route-probe --ignore-not-found
}

View file

@ -0,0 +1,22 @@
{{- $gateway := .Values._namespace.gateway | default "" }}
{{- $host := .Values._namespace.host }}
{{- $harborHost := .Values.host | default (printf "%s.%s" .Release.Name $host) }}
{{- if $gateway }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ .Release.Name }}
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $gateway }}
sectionName: https
hostnames:
- {{ $harborHost | quote }}
rules:
- backendRefs:
- name: {{ .Release.Name }}
port: 80
{{- end }}

View file

@ -1,8 +1,10 @@
{{- $ingress := .Values._namespace.ingress }}
{{- $gateway := .Values._namespace.gateway | default "" }}
{{- $host := .Values._namespace.host }}
{{- $harborHost := .Values.host | default (printf "%s.%s" .Release.Name $host) }}
{{- $solver := (index .Values._cluster "solver") | default "http01" }}
{{- $clusterIssuer := (index .Values._cluster "issuer-name") | default "letsencrypt-prod" }}
{{- if not $gateway }}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
@ -35,3 +37,4 @@ spec:
name: {{ .Release.Name }}
port:
number: 80
{{- end }}

View file

@ -80,6 +80,7 @@ tenant-u1
| `etcd` | Deploy own Etcd cluster. | `bool` | `false` |
| `monitoring` | Deploy own Monitoring Stack. | `bool` | `false` |
| `ingress` | Deploy own Ingress Controller. | `bool` | `false` |
| `gateway` | Deploy own Gateway API Gateway (backed by Cilium Gateway API controller). | `bool` | `false` |
| `seaweedfs` | Deploy own SeaweedFS. | `bool` | `false` |
| `schedulingClass` | The name of a SchedulingClass CR to apply scheduling constraints for this tenant's workloads. | `string` | `""` |
| `resourceQuotas` | Define resource quotas for the tenant. | `map[string]quantity` | `{}` |

View file

@ -12,7 +12,11 @@
(eq $exposeMode "loadBalancer")
(eq $exposeIngress .Release.Namespace)
.Values.ingress }}
{{- if and $isPublishingIngressLB $ipsList }}
{{- $hasOwnGateway := .Values.gateway | default false }}
{{- if and $hasOwnGateway (not $ipsList) }}
{{- fail "publishing.externalIPs is empty — a tenant Gateway has no CiliumLoadBalancerIPPool to draw from. The Gateway Service would stay in <pending> with no address. Set publishing.externalIPs on the platform (or publishing.exposure=loadBalancer with a BGP / L2-announce pool you manage separately) before enabling tenant.spec.gateway=true." }}
{{- end }}
{{- if and (or $isPublishingIngressLB $hasOwnGateway) $ipsList }}
apiVersion: cilium.io/v2
kind: CiliumLoadBalancerIPPool
metadata:

View file

@ -0,0 +1,32 @@
{{- if .Values.gateway }}
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
name: gateway
namespace: {{ include "tenant.name" . }}
labels:
sharding.fluxcd.io/key: tenants
internal.cozystack.io/tenantmodule: "true"
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
apps.cozystack.io/application.kind: Gateway
apps.cozystack.io/application.group: apps.cozystack.io
apps.cozystack.io/application.name: gateway
spec:
chartRef:
kind: ExternalArtifact
name: cozystack-gateway-application-default-gateway
namespace: cozy-system
interval: 5m
timeout: 10m
install:
remediation:
retries: -1
upgrade:
force: true
remediation:
retries: -1
valuesFrom:
- kind: Secret
name: cozystack-values
{{- end }}

View file

@ -29,6 +29,23 @@
{{- $ingress = $tenantName }}
{{- end }}
{{/*
Gateway reference is NOT inherited from parent. Unlike ingress (where nginx
serves from the publishing namespace and any tenant can attach via the shared
apex), a Gateway's allowedRoutes.namespaces selector is restrictive: a child
tenant namespace is not on the parent Gateway's whitelist, so an HTTPRoute
from the child would be NotAllowedByListeners. The parent Gateway's cert also
only covers <apex> and *.<apex> (one level), and a child apex is
<name>.<parent-apex> — two levels deep — so even if admission let the route
through, TLS would break. Require explicit tenant.spec.gateway=true on each
tenant that wants Gateway-attached apps; otherwise apps fall back to the
inherited Ingress.
*/}}
{{- $gateway := "" }}
{{- if .Values.gateway }}
{{- $gateway = $tenantName }}
{{- end }}
{{- $monitoring := $parentNamespace.monitoring | default "" }}
{{- if .Values.monitoring }}
{{- $monitoring = $tenantName }}
@ -61,6 +78,7 @@ metadata:
{{/* Labels for network policies */}}
namespace.cozystack.io/etcd: {{ $etcd | quote }}
namespace.cozystack.io/ingress: {{ $ingress | quote }}
namespace.cozystack.io/gateway: {{ $gateway | quote }}
namespace.cozystack.io/monitoring: {{ $monitoring | quote }}
namespace.cozystack.io/seaweedfs: {{ $seaweedfs | quote }}
namespace.cozystack.io/host: {{ $computedHost | quote }}
@ -92,6 +110,7 @@ stringData:
_namespace:
etcd: {{ $etcd | quote }}
ingress: {{ $ingress | quote }}
gateway: {{ $gateway | quote }}
monitoring: {{ $monitoring | quote }}
seaweedfs: {{ $seaweedfs | quote }}
host: {{ $computedHost | quote }}

View file

@ -139,3 +139,78 @@ tests:
asserts:
- hasDocuments:
count: 0
- it: gateway=true in any tenant renders pool with namespace-only selector
set:
gateway: true
_cluster:
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
asserts:
- hasDocuments:
count: 1
- equal:
path: metadata.name
value: root-exposure
- equal:
path: spec.blocks
value:
- cidr: 192.0.2.10/32
- equal:
path: spec.serviceSelector.matchLabels["io.kubernetes.service.namespace"]
value: tenant-root
- it: gateway=true in a non-publishing tenant renders its own pool (not tied to publishing tenant)
set:
gateway: true
_cluster:
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
release:
name: tenant-u1
namespace: tenant-u1
asserts:
- hasDocuments:
count: 1
- equal:
path: metadata.name
value: u1-exposure
- equal:
path: spec.serviceSelector.matchLabels["io.kubernetes.service.namespace"]
value: tenant-u1
- it: gateway=true + ingress=true + loadBalancer mode renders a single shared pool (no overlapping CIDR conflict)
set:
gateway: true
ingress: true
_cluster:
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
expose-mode: loadBalancer
asserts:
- hasDocuments:
count: 1
- equal:
path: metadata.name
value: root-exposure
- it: gateway=true with ingress=false still renders pool (gateway alone is enough)
set:
gateway: true
ingress: false
_cluster:
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
asserts:
- hasDocuments:
count: 1
- it: gateway=true with empty externalIPs fails chart render with explicit message
set:
gateway: true
_cluster:
expose-ingress: tenant-root
expose-external-ips: ""
asserts:
- failedTemplate:
errorMessage: "publishing.externalIPs is empty — a tenant Gateway has no CiliumLoadBalancerIPPool to draw from. The Gateway Service would stay in <pending> with no address. Set publishing.externalIPs on the platform (or publishing.exposure=loadBalancer with a BGP / L2-announce pool you manage separately) before enabling tenant.spec.gateway=true."

View file

@ -22,6 +22,11 @@
"type": "boolean",
"default": false
},
"gateway": {
"description": "Deploy own Gateway API Gateway (backed by Cilium Gateway API controller).",
"type": "boolean",
"default": false
},
"seaweedfs": {
"description": "Deploy own SeaweedFS.",
"type": "boolean",

View file

@ -14,6 +14,9 @@ monitoring: false
## @param {bool} ingress - Deploy own Ingress Controller.
ingress: false
## @param {bool} gateway - Deploy own Gateway API Gateway (backed by Cilium Gateway API controller).
gateway: false
## @param {bool} seaweedfs - Deploy own SeaweedFS.
seaweedfs: false

View file

@ -13,6 +13,7 @@ spec:
- name: default
dependsOn:
- cozystack.networking
- cozystack.gateway-api-crds
components:
- name: cert-manager-crds
path: system/cert-manager-crds

View file

@ -0,0 +1,20 @@
---
apiVersion: cozystack.io/v1alpha1
kind: PackageSource
metadata:
name: cozystack.gateway-api-crds
spec:
sourceRef:
kind: OCIRepository
name: cozystack-packages
namespace: cozy-system
path: /
variants:
- name: default
dependsOn: []
components:
- name: gateway-api-crds
path: system/gateway-api-crds
install:
namespace: cozy-gateway-api
releaseName: gateway-api-crds

View file

@ -0,0 +1,23 @@
---
apiVersion: cozystack.io/v1alpha1
kind: PackageSource
metadata:
name: cozystack.gateway-application
spec:
sourceRef:
kind: OCIRepository
name: cozystack-packages
namespace: cozy-system
path: /
variants:
- name: default
dependsOn:
- cozystack.gateway-api-crds
- cozystack.cert-manager
libraries:
- name: cozy-lib
path: library/cozy-lib
components:
- name: gateway
path: extra/gateway
libraries: ["cozy-lib"]

View file

@ -13,7 +13,8 @@ spec:
- name: noop
components: []
- name: cilium
dependsOn: []
dependsOn:
- cozystack.gateway-api-crds
components:
- name: cilium
path: system/cilium
@ -34,7 +35,8 @@ spec:
dependsOn:
- cilium
- name: cilium-kilo
dependsOn: []
dependsOn:
- cozystack.gateway-api-crds
components:
- name: cilium
path: system/cilium
@ -60,7 +62,8 @@ spec:
- cilium
# Generic Cilium variant for non-Talos clusters (kubeadm, k3s, RKE2, etc.)
- name: cilium-generic
dependsOn: []
dependsOn:
- cozystack.gateway-api-crds
components:
- name: cilium
path: system/cilium
@ -81,7 +84,8 @@ spec:
dependsOn:
- cilium
- name: kubeovn-cilium
dependsOn: []
dependsOn:
- cozystack.gateway-api-crds
components:
- name: cilium
path: system/cilium
@ -112,7 +116,8 @@ spec:
- cilium
# Generic KubeOVN+Cilium variant for non-Talos clusters (kubeadm, k3s, RKE2, etc.)
- name: kubeovn-cilium-generic
dependsOn: []
dependsOn:
- cozystack.gateway-api-crds
components:
- name: cilium
path: system/cilium

View file

@ -31,6 +31,8 @@ stringData:
expose-ingress: {{ .Values.publishing.ingressName | quote }}
expose-external-ips: {{ .Values.publishing.externalIPs | join "," | quote }}
expose-mode: {{ .Values.publishing.exposure | default "externalIPs" | quote }}
gateway-enabled: {{ .Values.gateway.enabled | default false | quote }}
gateway-attached-namespaces: {{ .Values.gateway.attachedNamespaces | default (list) | join "," | quote }}
cluster-domain: {{ .Values.networking.clusterDomain | quote }}
api-server-endpoint: {{ .Values.publishing.apiServerEndpoint | quote }}
{{- with .Values.branding }}

View file

@ -118,6 +118,7 @@
{{- end }}
# Common Packages
{{include "cozystack.platform.package.default" (list "cozystack.gateway-api-crds" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.cert-manager" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.flux-plunger" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.victoria-metrics-operator" $) }}
@ -126,6 +127,7 @@
{{- $_ := set $tenantComponents "tenant" (dict "values" $tenantClusterValues) }}
{{include "cozystack.platform.package" (list "cozystack.tenant-application" "default" $ $tenantComponents) }}
{{include "cozystack.platform.package.default" (list "cozystack.ingress-application" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.gateway-application" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.seaweedfs-application" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.info-application" $) }}
{{include "cozystack.platform.package.default" (list "cozystack.monitoring-application" $) }}

View file

@ -83,6 +83,15 @@ publishing:
certificates:
solver: http01 # "http01" or "dns01"
issuerName: letsencrypt-prod
# Rate-limit note: every tenant with gateway=true issues one
# Certificate for its wildcard + apex hostnames. If many tenants share
# the same apex domain with issuerName=letsencrypt-prod, the cluster
# can hit the Let's Encrypt limits (50 certs / registered domain /
# week, 5 duplicate certs / week, 300 new orders / account / 3h).
# Use letsencrypt-stage for non-production clusters or gate the
# number of certificates per tenant via tenant.spec.resourceQuotas
# with count/certificates.cert-manager.io. See
# https://letsencrypt.org/docs/rate-limits/.
# Authentication configuration
authentication:
oidc:
@ -94,6 +103,42 @@ authentication:
# userinfo, logout) through this URL while keeping browser redirects on the external URL.
# Example: http://keycloak-http.cozy-keycloak.svc:8080/realms/cozy
keycloakInternalUrl: ""
# Gateway API configuration
gateway:
# Enable Gateway API support across the platform. When true:
# - cert-manager ClusterIssuers use an http01.gatewayHTTPRoute solver
# that attaches to the root tenant's Gateway, so Certificate issuance
# works for tenants whose ingress is via Gateway API rather than
# ingress-nginx.
# - Exposed services (dashboard, keycloak, harbor, bucket, grafana,
# cozystack-api, vm-exportproxy, cdi-uploadproxy) render an
# HTTPRoute attached to the tenant's Gateway.
# Per-tenant opt-in is still governed by tenant.spec.gateway=true, which
# materialises the Gateway itself. This flag only controls platform-wide
# Gateway API integration (cert-manager solver + per-service HTTPRoutes).
enabled: false
# Namespaces that are allowed to attach HTTPRoute or TLSRoute to a tenant
# Gateway. The publishing tenant namespace is always included implicitly.
# Additional entries must be the exact namespace name (matched on the
# built-in kubernetes.io/metadata.name label). Tenants not on this list
# cannot attach a route to somebody else's Gateway, which prevents
# hostname hijacking across tenants.
#
# The `default` namespace is included because the Kubernetes API's
# TLSRoute (shipped by the cozystack-api package) has to live next to
# the `kubernetes` Service it points at, which is always in `default`.
attachedNamespaces:
- cozy-cert-manager
- cozy-dashboard
- cozy-keycloak
- cozy-system
- cozy-harbor
- cozy-bucket
- cozy-kubevirt
- cozy-kubevirt-cdi
- cozy-monitoring
- cozy-linstor-gui
- default
# Pod scheduling configuration
scheduling:
globalAppTopologySpreadConstraints: ""

View file

@ -0,0 +1,2 @@
.helmignore
/Makefile

View file

@ -0,0 +1,5 @@
apiVersion: v2
name: gateway
description: Cozystack per-tenant Gateway API resource backed by Cilium
type: application
version: 0.0.0 # Placeholder, the actual version will be automatically set during the build process

View file

@ -0,0 +1,9 @@
NAME=gateway
include ../../../hack/package.mk
generate:
cozyvalues-gen -v values.yaml -s values.schema.json -r README.md
test:
helm unittest .

View file

@ -0,0 +1,59 @@
# Cozystack Tenant Gateway
Per-tenant Gateway API Gateway backed by Cilium. Installed automatically when `tenant.spec.gateway=true` on the publishing tenant.
## Parameters
### Common parameters
| Name | Description | Type | Value |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ---------------------------------------- |
| `gatewayClassName` | GatewayClass to attach the tenant Gateway to. Must exist cluster-wide. Default matches the Cilium-managed class. | `string` | `cilium` |
| `tlsPassthroughServices` | Names (from publishing.exposedServices) whose traffic is TLS-passthrough rather than TLS-terminate. For each such service a dedicated HTTPS listener with tls.mode=Passthrough is rendered on the Gateway, and the service is expected to attach a TLSRoute instead of an HTTPRoute. | `[]string` | `[api, vm-exportproxy, cdi-uploadproxy]` |
## Security model
Six independent layers protect cross-tenant isolation. Compromising one of them does not bypass the others; admission-time checks (layers 25) fail closed (`failurePolicy: Fail`, `validationActions: [Deny]`).
1. **Namespace whitelist on listeners.** The Gateway's `allowedRoutes.namespaces.from: Selector` matches the built-in `kubernetes.io/metadata.name` label (written by kube-apiserver, unspoofable). It accepts routes from the publishing tenant's namespace plus `publishing.gateway.attachedNamespaces` in the platform chart (default includes the `cozy-*` namespaces for platform services and `default` for the Kubernetes API TLSRoute). A namespace outside the list literally cannot attach any `HTTPRoute` or `TLSRoute` to this Gateway.
2. **`cozystack-gateway-hostname-policy`** — `ValidatingAdmissionPolicy` on `gateway.networking.k8s.io/v1 Gateway` CREATE/UPDATE. Reads `namespaceObject.metadata.labels["namespace.cozystack.io/host"]` and rejects any listener hostname that is not equal to that value or a subdomain of it. `matchConditions` gate the VAP to cozystack-managed namespaces only — Gateways in unrelated namespaces (e.g. `kube-system`) are not touched.
3. **`cozystack-gateway-attached-namespaces-policy`** — VAP on `cozystack.io/v1alpha1 Package` CREATE/UPDATE. Rejects any `tenant-*` entry in `spec.components.platform.values.gateway.attachedNamespaces`. Catches direct `kubectl edit packages.cozystack.io` that would bypass the helm render-time guard in layer 6.
4. **`cozystack-tenant-host-policy`** — VAP on `apps.cozystack.io/v1alpha1 Tenant` CREATE/UPDATE. Rejects setting or changing `spec.host` unless the caller's groups contain `system:masters`, `system:serviceaccounts:cozy-system`, `system:serviceaccounts:cozy-cert-manager`, `system:serviceaccounts:cozy-fluxcd` or `system:serviceaccounts:kube-system`. Closes the path where a tenant user sets `spec.host=dashboard.example.org` on their own tenant to have the tenant chart write a hijacked label into the namespace.
5. **`cozystack-namespace-host-label-policy`** — VAP on core `v1 Namespace` CREATE/UPDATE. Rejects any set or change of the `namespace.cozystack.io/host` label, except by the same trusted-caller whitelist as layer 4. This closes both first-time label writes on CREATE and first-time adds on UPDATE — only cozystack/Flux service accounts (which apply the tenant chart) can stamp the label.
6. **Render-time `fail` in cozystack-basics.** The cozystack-basics chart fails the helm render if `_cluster.gateway-attached-namespaces` contains any `tenant-*` entry. Triggers on the helm-install path before the cluster ever sees the values — complements layer 3 which triggers at `kubectl apply` time.
For `tenant-root` the allowed host suffix is `publishing.host`; for any `tenant-<name>` that inherits from its parent the suffix is `<name>.<parent apex>`. A child tenant with an independent apex (`customer1.io` instead of a subdomain) is handled correctly because the VAP reads the per-namespace label rather than assuming a subdomain hierarchy.
## Rate limits
cert-manager issues one `Certificate` per Gateway release. With `issuerName: letsencrypt-prod` (the default), the `Certificate` for a tenant Gateway counts against the [Let's Encrypt rate limits](https://letsencrypt.org/docs/rate-limits/):
- 50 new certificates per registered domain per week.
- 5 duplicate certificates per week for the same set of hostnames.
- 300 new orders per account per 3 hours.
A cluster where many tenants share the same apex domain can exhaust these quickly. Mitigations:
- Use `publishing.certificates.issuerName: letsencrypt-stage` for non-production clusters (staging does not count against prod quotas).
- Limit the number of simultaneous tenant Gateways per cluster via the platform's package quota, or cap it via `tenant.spec.resourceQuotas` with `count/certificates.cert-manager.io` to limit how many `Certificate` objects a tenant may create.
- For bare-metal or air-gapped deployments consider an internal ACME server or the self-signed `ClusterIssuer` (`selfsigned-cluster-issuer`) that ships alongside the Let's Encrypt issuers.
Recommended tenant-level quota to contain a misbehaving tenant:
```yaml
apiVersion: apps.cozystack.io/v1alpha1
kind: Tenant
spec:
gateway: true
resourceQuotas:
count/certificates.cert-manager.io: "10"
```
The default for a fresh tenant is unlimited; operators running shared-apex multi-tenant clusters should set this explicitly (or stage it via the tenant-application default values) before opening `gateway: true` to non-trusted tenants.
## Known limitations
- **Upstream application gaps** — some chart-level features (harbor ACL integrations, bucket upstream limitations) remain on ingress-nginx workflows in upstream docs; cozystack tracks those separately as upstream PRs.
- **Supported ACME issuers**`publishing.certificates.issuerName` for Gateway-based tenants must be `letsencrypt-prod` or `letsencrypt-stage` (the chart maps those names to concrete ACME server URLs). To support another ACME provider, extend `templates/issuer.yaml` with an additional branch.

View file

@ -0,0 +1 @@
../../../library/cozy-lib

View file

@ -0,0 +1,23 @@
{
"comments": {
"format": "##"
},
"tags": {
"param": "@param",
"section": "@section",
"descriptionStart": "@descriptionStart",
"descriptionEnd": "@descriptionEnd",
"skip": "@skip",
"extra": "@extra"
},
"modifiers": {
"array": "array",
"object": "object",
"string": "string",
"nullable": "nullable",
"default": "default"
},
"regexp": {
"paramsSectionTitle": "Parameters"
}
}

View file

@ -0,0 +1,108 @@
{{- $host := (index .Values._namespace "host") | default "" }}
{{- if not $host }}
{{- fail "_namespace.host is empty — the tenant has no apex domain. Either set tenant.spec.host on this tenant or inherit it from a parent that has host set." }}
{{- end }}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: {{ trimPrefix "tenant-" .Release.Namespace }}-gateway-tls
spec:
secretName: {{ trimPrefix "tenant-" .Release.Namespace }}-gateway-tls
issuerRef:
name: gateway
kind: Issuer
dnsNames:
- {{ $host | quote }}
- {{ printf "*.%s" $host | quote }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: cozystack
labels:
cozystack.io/gateway: {{ .Release.Namespace }}
spec:
gatewayClassName: {{ .Values.gatewayClassName | quote }}
listeners:
{{- $extraNs := list }}
{{- range splitList "," ((index .Values._cluster "gateway-attached-namespaces") | default "") }}
{{- $ns := . | trim }}
{{- if $ns }}
{{- $extraNs = append $extraNs $ns }}
{{- end }}
{{- end }}
{{- $allowedNamespaces := concat (list .Release.Namespace) $extraNs | uniq }}
{{- $allowedNamespacesSelector := dict "matchExpressions" (list (dict
"key" "kubernetes.io/metadata.name"
"operator" "In"
"values" $allowedNamespaces)) }}
- name: http
protocol: HTTP
port: 80
allowedRoutes:
namespaces:
from: Selector
selector:
{{- toYaml $allowedNamespacesSelector | nindent 10 }}
- name: https
protocol: HTTPS
port: 443
hostname: {{ printf "*.%s" $host | quote }}
tls:
mode: Terminate
certificateRefs:
- name: {{ trimPrefix "tenant-" .Release.Namespace }}-gateway-tls
allowedRoutes:
namespaces:
from: Selector
selector:
{{- toYaml $allowedNamespacesSelector | nindent 10 }}
- name: https-apex
protocol: HTTPS
port: 443
hostname: {{ $host | quote }}
tls:
mode: Terminate
certificateRefs:
- name: {{ trimPrefix "tenant-" .Release.Namespace }}-gateway-tls
allowedRoutes:
namespaces:
from: Selector
selector:
{{- toYaml $allowedNamespacesSelector | nindent 10 }}
{{- $exposedServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- range .Values.tlsPassthroughServices }}
{{- $svc := . }}
{{- if has $svc $exposedServices }}
- name: {{ printf "tls-%s" $svc | quote }}
protocol: TLS
port: 443
hostname: {{ printf "%s.%s" $svc $host | quote }}
tls:
mode: Passthrough
allowedRoutes:
kinds:
- group: gateway.networking.k8s.io
kind: TLSRoute
namespaces:
from: Selector
selector:
{{- toYaml $allowedNamespacesSelector | nindent 10 }}
{{- end }}
{{- end }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: http-to-https-redirect
spec:
parentRefs:
- name: cozystack
sectionName: http
rules:
- filters:
- type: RequestRedirect
requestRedirect:
scheme: https
statusCode: 301

View file

@ -0,0 +1,42 @@
{{- $issuerName := (index .Values._cluster "issuer-name") | default "letsencrypt-prod" }}
{{- $solver := (index .Values._cluster "solver") | default "http01" }}
{{- $acmeServer := "" }}
{{- if eq $issuerName "letsencrypt-prod" }}
{{- $acmeServer = "https://acme-v02.api.letsencrypt.org/directory" }}
{{- else if eq $issuerName "letsencrypt-stage" }}
{{- $acmeServer = "https://acme-staging-v02.api.letsencrypt.org/directory" }}
{{- else }}
{{- fail (printf "packages/extra/gateway currently supports publishing.certificates.issuerName=letsencrypt-prod or letsencrypt-stage (got %q). For other issuers, extend templates/issuer.yaml to map the name to the corresponding ACME server URL." $issuerName) }}
{{- end }}
{{- /*
Let's Encrypt refuses to issue wildcard certificates via HTTP-01 (see
cert-manager/cert-manager-crds/.../crd-cert-manager.io_clusterissuers.yaml
at the http01 field description, and LE policy
https://letsencrypt.org/docs/challenge-types/#http-01-challenge). The
tenant Gateway's Certificate requests apex + *.apex, so HTTP-01 would
loop the Order forever and the HTTPS listeners would never get a cert.
Require dns01 (or selfsigned) for Gateway API tenants — fail fast so
the operator sees the mismatch at install time instead of during a
stuck cert-manager challenge.
*/}}
{{- if eq $solver "http01" }}
{{- fail "publishing.certificates.solver=http01 cannot issue the wildcard certificate the tenant Gateway needs (Let's Encrypt refuses HTTP-01 for wildcard identifiers). Set publishing.certificates.solver=dns01 (with a Cloudflare API token Secret in cozy-cert-manager) before enabling tenant.spec.gateway=true, or use the self-signed ClusterIssuer for air-gapped clusters." }}
{{- else if ne $solver "dns01" }}
{{- fail (printf "packages/extra/gateway currently supports publishing.certificates.solver=dns01 only (got %q). Extend templates/issuer.yaml to add additional solver types." $solver) }}
{{- end }}
---
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
name: gateway
spec:
acme:
server: {{ $acmeServer }}
privateKeySecretRef:
name: gateway-acme-account
solvers:
- dns01:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token

View file

@ -0,0 +1,284 @@
suite: tenant gateway
templates:
- templates/gateway.yaml
- templates/issuer.yaml
release:
name: gateway
namespace: tenant-root
tests:
- it: renders Certificate, Gateway and redirect HTTPRoute when IPs and host are set
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10,192.0.2.11"
issuer-name: letsencrypt-prod
_namespace:
host: example.org
asserts:
- template: templates/gateway.yaml
hasDocuments:
count: 3
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: kind
value: Certificate
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: spec.dnsNames
value:
- example.org
- "*.example.org"
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: kind
value: Gateway
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.gatewayClassName
value: cilium
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].name
value: http
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[1].hostname
value: "*.example.org"
- template: templates/gateway.yaml
documentIndex: 2
equal:
path: kind
value: HTTPRoute
- template: templates/gateway.yaml
documentIndex: 2
equal:
path: spec.rules[0].filters[0].requestRedirect.scheme
value: https
- it: child tenant renders its own Gateway with the child's per-tenant apex
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.11"
_namespace:
host: alice.example.org
release:
namespace: tenant-alice
asserts:
- template: templates/gateway.yaml
hasDocuments:
count: 3
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: spec.dnsNames
value:
- alice.example.org
- "*.alice.example.org"
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[1].hostname
value: "*.alice.example.org"
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[2].hostname
value: "alice.example.org"
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.selector.matchExpressions[0].values
value:
- tenant-alice
- it: empty _namespace.host fails with explicit error
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
_namespace:
host: ""
asserts:
- template: templates/gateway.yaml
failedTemplate:
errorMessage: "_namespace.host is empty — the tenant has no apex domain. Either set tenant.spec.host on this tenant or inherit it from a parent that has host set."
- it: allowedRoutes whitelist defaults to publishing namespace only when no extra namespaces are set
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
_namespace:
host: example.org
asserts:
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.from
value: Selector
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.selector.matchExpressions[0].key
value: kubernetes.io/metadata.name
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.selector.matchExpressions[0].operator
value: In
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.selector.matchExpressions[0].values
value:
- tenant-root
- it: allowedRoutes whitelist prepends publishing namespace to the gateway-attached-namespaces list and filters empty entries
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
gateway-attached-namespaces: "cozy-cert-manager,,cozy-dashboard, cozy-keycloak,"
_namespace:
host: example.org
asserts:
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[0].allowedRoutes.namespaces.selector.matchExpressions[0].values
value:
- tenant-root
- cozy-cert-manager
- cozy-dashboard
- cozy-keycloak
- it: Certificate references the per-tenant Issuer (not a shared ClusterIssuer) so each tenant gets isolated ACME state
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
issuer-name: letsencrypt-prod
_namespace:
host: example.org
asserts:
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: kind
value: Certificate
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: spec.issuerRef.kind
value: Issuer
- template: templates/gateway.yaml
documentIndex: 0
equal:
path: spec.issuerRef.name
value: gateway
- template: templates/issuer.yaml
hasDocuments:
count: 1
- template: templates/issuer.yaml
equal:
path: kind
value: Issuer
- template: templates/issuer.yaml
equal:
path: metadata.name
value: gateway
- template: templates/issuer.yaml
equal:
path: spec.acme.server
value: https://acme-v02.api.letsencrypt.org/directory
- template: templates/issuer.yaml
equal:
path: spec.acme.solvers[0].dns01.cloudflare.apiTokenSecretRef.name
value: cloudflare-api-token-secret
- template: templates/issuer.yaml
equal:
path: spec.acme.solvers[0].dns01.cloudflare.apiTokenSecretRef.key
value: api-token
- it: chart render fails when publishing.certificates.solver=http01 because Let's Encrypt refuses HTTP-01 for wildcard certs
set:
_cluster:
solver: http01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
issuer-name: letsencrypt-prod
_namespace:
host: example.org
asserts:
- template: templates/issuer.yaml
failedTemplate:
errorMessage: "publishing.certificates.solver=http01 cannot issue the wildcard certificate the tenant Gateway needs (Let's Encrypt refuses HTTP-01 for wildcard identifiers). Set publishing.certificates.solver=dns01 (with a Cloudflare API token Secret in cozy-cert-manager) before enabling tenant.spec.gateway=true, or use the self-signed ClusterIssuer for air-gapped clusters."
- it: Issuer picks the staging ACME server when publishing.certificates.issuerName=letsencrypt-stage
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
issuer-name: letsencrypt-stage
_namespace:
host: example.org
asserts:
- template: templates/issuer.yaml
equal:
path: spec.acme.server
value: https://acme-staging-v02.api.letsencrypt.org/directory
- it: unknown issuer-name fails chart render with an explicit error
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
issuer-name: my-custom-ca
_namespace:
host: example.org
asserts:
- template: templates/issuer.yaml
failedTemplate:
errorMessage: 'packages/extra/gateway currently supports publishing.certificates.issuerName=letsencrypt-prod or letsencrypt-stage (got "my-custom-ca"). For other issuers, extend templates/issuer.yaml to map the name to the corresponding ACME server URL.'
- it: HTTPS and HTTPS-apex listeners share the same allowedRoutes whitelist
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
expose-external-ips: "192.0.2.10"
gateway-attached-namespaces: "cozy-dashboard"
_namespace:
host: example.org
asserts:
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[1].allowedRoutes.namespaces.selector.matchExpressions[0].values
value:
- tenant-root
- cozy-dashboard
- template: templates/gateway.yaml
documentIndex: 1
equal:
path: spec.listeners[2].allowedRoutes.namespaces.selector.matchExpressions[0].values
value:
- tenant-root
- cozy-dashboard

View file

@ -0,0 +1,23 @@
{
"title": "Chart Values",
"type": "object",
"properties": {
"gatewayClassName": {
"description": "GatewayClass to attach the tenant Gateway to. Must exist cluster-wide. Default matches the Cilium-managed class.",
"type": "string",
"default": "cilium"
},
"tlsPassthroughServices": {
"description": "Names (from publishing.exposedServices) whose traffic is TLS-passthrough rather than TLS-terminate. For each such service a dedicated HTTPS listener with tls.mode=Passthrough is rendered on the Gateway, and the service is expected to attach a TLSRoute instead of an HTTPRoute.",
"type": "array",
"default": [
"api",
"vm-exportproxy",
"cdi-uploadproxy"
],
"items": {
"type": "string"
}
}
}
}

View file

@ -0,0 +1,12 @@
##
## @section Common parameters
##
## @param {string} gatewayClassName - GatewayClass to attach the tenant Gateway to. Must exist cluster-wide. Default matches the Cilium-managed class.
gatewayClassName: cilium
## @param {[]string} tlsPassthroughServices - Names (from publishing.exposedServices) whose traffic is TLS-passthrough rather than TLS-terminate. For each such service a dedicated HTTPS listener with tls.mode=Passthrough is rendered on the Gateway, and the service is expected to attach a TLSRoute instead of an HTTPRoute.
tlsPassthroughServices:
- api
- vm-exportproxy
- cdi-uploadproxy

View file

@ -0,0 +1,21 @@
{{- $host := .Values._namespace.host }}
{{- $gateway := .Values._namespace.gateway | default "" }}
{{- if $gateway }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ .Values.bucketName }}-ui
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $gateway }}
sectionName: https
hostnames:
- {{ printf "%s.%s" .Values.bucketName $host | quote }}
rules:
- backendRefs:
- name: {{ .Values.bucketName }}-ui
port: 8080
{{- end }}

View file

@ -1,7 +1,9 @@
{{- $host := .Values._namespace.host }}
{{- $ingress := .Values._namespace.ingress }}
{{- $gateway := .Values._namespace.gateway | default "" }}
{{- $solver := (index .Values._cluster "solver") | default "http01" }}
{{- $clusterIssuer := (index .Values._cluster "issuer-name") | default "letsencrypt-prod" }}
{{- if not $gateway }}
apiVersion: networking.k8s.io/v1
kind: Ingress
@ -32,3 +34,4 @@ spec:
name: {{ .Values.bucketName }}-ui
port:
number: 8080
{{- end }}

View file

@ -2,3 +2,6 @@ export NAME=cert-manager-issuers
export NAMESPACE=cozy-cert-manager
include ../../../hack/package.mk
test:
helm unittest .

View file

@ -1,57 +1,73 @@
{{- $solver := (index .Values._cluster "solver") | default "http01" }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- define "cert-manager-issuers.httpSolver" -}}
{{- $gatewayEnabled := index . "gatewayEnabled" -}}
{{- $exposeIngress := index . "exposeIngress" -}}
{{- if eq $gatewayEnabled "true" }}
http01:
gatewayHTTPRoute:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: http
{{- else }}
http01:
ingress:
ingressClassName: {{ $exposeIngress }}
{{- end }}
{{- end }}
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
privateKeySecretRef:
name: letsencrypt-prod
server: https://acme-v02.api.letsencrypt.org/directory
solvers:
- {{- if eq $solver "dns01" }}
dns01:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token
{{- else }}
http01:
ingress:
ingressClassName: {{ $exposeIngress }}
{{- end }}
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
privateKeySecretRef:
name: letsencrypt-prod
server: https://acme-v02.api.letsencrypt.org/directory
solvers:
- {{- if eq $solver "dns01" }}
dns01:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token
{{- else }}
{{- include "cert-manager-issuers.httpSolver" (dict "gatewayEnabled" $gatewayEnabled "exposeIngress" $exposeIngress) | nindent 8 }}
{{- end }}
---
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-stage
spec:
acme:
privateKeySecretRef:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-stage
spec:
acme:
privateKeySecretRef:
name: letsencrypt-stage
server: https://acme-staging-v02.api.letsencrypt.org/directory
solvers:
- {{- if eq $solver "dns01" }}
dns01:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token
{{- else }}
http01:
ingress:
ingressClassName: {{ $exposeIngress }}
{{- end }}
server: https://acme-staging-v02.api.letsencrypt.org/directory
solvers:
- {{- if eq $solver "dns01" }}
dns01:
cloudflare:
apiTokenSecretRef:
name: cloudflare-api-token-secret
key: api-token
{{- else }}
{{- include "cert-manager-issuers.httpSolver" (dict "gatewayEnabled" $gatewayEnabled "exposeIngress" $exposeIngress) | nindent 8 }}
{{- end }}
---
---
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: selfsigned-cluster-issuer
spec:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: selfsigned-cluster-issuer
spec:
selfSigned: {}

View file

@ -0,0 +1,103 @@
suite: cluster-issuer solver selection
templates:
- templates/cluster-issuers.yaml
release:
name: cert-manager-issuers
namespace: cozy-cert-manager
tests:
- it: default renders ingress-nginx HTTP-01 solver on both ACME issuers
set:
_cluster:
solver: http01
expose-ingress: tenant-root
asserts:
- documentIndex: 0
equal:
path: metadata.name
value: letsencrypt-prod
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.ingress.ingressClassName
value: tenant-root
- documentIndex: 0
notExists:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute
- documentIndex: 1
equal:
path: metadata.name
value: letsencrypt-stage
- documentIndex: 1
equal:
path: spec.acme.solvers[0].http01.ingress.ingressClassName
value: tenant-root
- it: gateway-enabled=true renders gatewayHTTPRoute solver on both ACME issuers
set:
_cluster:
solver: http01
expose-ingress: tenant-root
gateway-enabled: "true"
asserts:
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].group
value: gateway.networking.k8s.io
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].kind
value: Gateway
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].name
value: cozystack
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].namespace
value: tenant-root
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].sectionName
value: http
- documentIndex: 0
notExists:
path: spec.acme.solvers[0].http01.ingress
- documentIndex: 1
equal:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute.parentRefs[0].name
value: cozystack
- it: solver=dns01 is unaffected by gateway-enabled flag
set:
_cluster:
solver: dns01
expose-ingress: tenant-root
gateway-enabled: "true"
asserts:
- documentIndex: 0
equal:
path: spec.acme.solvers[0].dns01.cloudflare.apiTokenSecretRef.name
value: cloudflare-api-token-secret
- documentIndex: 0
notExists:
path: spec.acme.solvers[0].http01
- documentIndex: 1
equal:
path: spec.acme.solvers[0].dns01.cloudflare.apiTokenSecretRef.name
value: cloudflare-api-token-secret
- it: gateway-enabled defaults to ingress solver when unset
set:
_cluster:
solver: http01
expose-ingress: tenant-root
gateway-enabled: ""
asserts:
- documentIndex: 0
equal:
path: spec.acme.solvers[0].http01.ingress.ingressClassName
value: tenant-root
- documentIndex: 0
notExists:
path: spec.acme.solvers[0].http01.gatewayHTTPRoute

View file

@ -18,7 +18,20 @@ cilium:
tag: 1.19.3
digest: "sha256:700f06f4803a838a8e830be5ace4650e3ad82bdefabfb2f4d110368d307a5efb"
envoy:
enabled: false
enabled: true
# Upstream default is {} — no requests/limits. The embedded envoy DaemonSet
# idles at ~100 MB RAM/node and grows under L7 traffic; without requests
# the DaemonSet schedules onto any node with no reserved headroom, and
# without a memory limit a runaway listener could OOM the node.
# The baseline matches the commented-out example in the upstream Helm values.
resources:
requests:
cpu: 100m
memory: 512Mi
limits:
memory: 1Gi
gatewayAPI:
enabled: true
rollOutCiliumPods: true
operator:
rollOutPods: true

View file

@ -1,8 +1,9 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "api" $exposeServices) }}
{{- if and (has "api" $exposeServices) (ne $gatewayEnabled "true") }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:

View file

@ -0,0 +1,24 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "api" $exposeServices) (eq $gatewayEnabled "true") }}
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TLSRoute
metadata:
name: kubernetes-api
namespace: default
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: tls-api
hostnames:
- {{ printf "api.%s" $host | quote }}
rules:
- backendRefs:
- name: kubernetes
port: 443
{{- end }}

View file

@ -0,0 +1,203 @@
{{- $attachedNamespaces := (index .Values._cluster "gateway-attached-namespaces") | default "" }}
{{- range splitList "," $attachedNamespaces }}
{{- $ns := . | trim }}
{{- if and $ns (hasPrefix "tenant-" $ns) }}
{{- fail (printf "publishing.gateway.attachedNamespaces must not contain tenant-* namespaces (got %q). Adding a tenant namespace here lets that tenant attach HTTPRoutes to the publishing tenant's Gateway and hijack hostnames. Child tenants that need their own Gateway must opt in via tenant.spec.gateway=true instead." $ns) }}
{{- end }}
{{- end }}
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: cozystack-gateway-hostname-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["gateway.networking.k8s.io"]
apiVersions: ["v1", "v1beta1"]
operations: ["CREATE", "UPDATE"]
resources: ["gateways"]
matchConditions:
- name: tenant-namespace
expression: object.metadata.namespace.startsWith("tenant-")
variables:
- name: tenantHost
expression: >-
(namespaceObject != null &&
has(namespaceObject.metadata.labels) &&
"namespace.cozystack.io/host" in namespaceObject.metadata.labels)
? namespaceObject.metadata.labels["namespace.cozystack.io/host"]
: ""
validations:
- expression: >-
variables.tenantHost == "" ||
!has(object.spec.listeners) ||
object.spec.listeners.all(l,
!has(l.hostname) ||
l.hostname == variables.tenantHost ||
l.hostname.endsWith("." + variables.tenantHost)
)
messageExpression: >-
"Gateway listener hostname must equal " + variables.tenantHost +
" or end with ." + variables.tenantHost +
" (namespace " + object.metadata.namespace + " carries label namespace.cozystack.io/host=" + variables.tenantHost + ")"
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: cozystack-gateway-hostname-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
policyName: cozystack-gateway-hostname-policy
validationActions: [Deny]
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: cozystack-gateway-attached-namespaces-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["cozystack.io"]
apiVersions: ["v1alpha1"]
operations: ["CREATE", "UPDATE"]
resources: ["packages"]
matchConditions:
- name: has-gateway-attached-namespaces
expression: >-
has(object.spec) &&
has(object.spec.components) &&
"platform" in object.spec.components &&
has(object.spec.components.platform.values) &&
"gateway" in object.spec.components.platform.values &&
"attachedNamespaces" in object.spec.components.platform.values.gateway
validations:
- expression: >-
object.spec.components.platform.values.gateway.attachedNamespaces.all(ns, !ns.startsWith("tenant-"))
messageExpression: >-
"spec.components.platform.values.gateway.attachedNamespaces must not contain any tenant-* namespace; use tenant.spec.gateway=true instead of adding a tenant namespace to the publishing Gateway's whitelist"
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: cozystack-gateway-attached-namespaces-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
policyName: cozystack-gateway-attached-namespaces-policy
validationActions: [Deny]
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: cozystack-tenant-host-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps.cozystack.io"]
apiVersions: ["v1alpha1"]
operations: ["CREATE", "UPDATE"]
resources: ["tenants"]
matchConditions:
- name: has-host-field
expression: >-
(has(object.spec) && "host" in object.spec && object.spec.host != "") ||
(oldObject != null && has(oldObject.spec) && "host" in oldObject.spec && oldObject.spec.host != "")
variables:
- name: oldHost
expression: >-
(oldObject != null && has(oldObject.spec) && "host" in oldObject.spec) ? oldObject.spec.host : ""
- name: newHost
expression: >-
(has(object.spec) && "host" in object.spec) ? object.spec.host : ""
- name: hostChanged
expression: variables.oldHost != variables.newHost
- name: trustedCaller
expression: >-
has(request.userInfo.groups) && request.userInfo.groups.exists(g,
g == "system:masters" ||
g == "system:serviceaccounts:cozy-system" ||
g == "system:serviceaccounts:cozy-cert-manager" ||
g == "system:serviceaccounts:cozy-fluxcd" ||
g == "system:serviceaccounts:kube-system")
validations:
- expression: "!variables.hostChanged || variables.trustedCaller"
messageExpression: >-
"tenant.spec.host can only be set or changed by cluster-admins (system:masters) or by cozystack/Flux service accounts; request user is " + request.userInfo.username + ". A tenant with empty spec.host inherits the apex from its parent tenant."
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: cozystack-tenant-host-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
policyName: cozystack-tenant-host-policy
validationActions: [Deny]
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: cozystack-namespace-host-label-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["namespaces"]
matchConditions:
- name: touches-host-label
expression: >-
(has(object.metadata.labels) && "namespace.cozystack.io/host" in object.metadata.labels) ||
(oldObject != null && has(oldObject.metadata.labels) && "namespace.cozystack.io/host" in oldObject.metadata.labels)
variables:
- name: oldHost
expression: >-
(oldObject != null && has(oldObject.metadata.labels) && "namespace.cozystack.io/host" in oldObject.metadata.labels)
? oldObject.metadata.labels["namespace.cozystack.io/host"]
: ""
- name: newHost
expression: >-
has(object.metadata.labels) && "namespace.cozystack.io/host" in object.metadata.labels
? object.metadata.labels["namespace.cozystack.io/host"]
: ""
- name: trustedCaller
expression: >-
has(request.userInfo.groups) && request.userInfo.groups.exists(g,
g == "system:masters" ||
g == "system:serviceaccounts:cozy-system" ||
g == "system:serviceaccounts:cozy-cert-manager" ||
g == "system:serviceaccounts:cozy-fluxcd" ||
g == "system:serviceaccounts:kube-system")
validations:
- expression: "variables.newHost == variables.oldHost || variables.trustedCaller"
messageExpression: >-
"namespace label namespace.cozystack.io/host is immutable once set (was " + variables.oldHost + ", requested " + variables.newHost + "); only cluster-admins and cozystack/Flux service accounts may change it. Request user: " + request.userInfo.username
reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: cozystack-namespace-host-label-policy
labels:
internal.cozystack.io/managed-by-cozystack: ""
spec:
policyName: cozystack-namespace-host-label-policy
validationActions: [Deny]

View file

@ -3,6 +3,8 @@ apiVersion: v1
kind: Namespace
metadata:
name: tenant-root
labels:
namespace.cozystack.io/host: {{ index .Values._cluster "root-host" | quote }}
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease

View file

@ -0,0 +1,23 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "dashboard" $exposeServices) (eq $gatewayEnabled "true") }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: dashboard
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: https
hostnames:
- {{ printf "dashboard.%s" $host | quote }}
rules:
- backendRefs:
- name: incloud-web-gatekeeper
port: 8000
{{- end }}

View file

@ -3,8 +3,9 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "dashboard" $exposeServices) }}
{{- if and (has "dashboard" $exposeServices) (ne $gatewayEnabled "true") }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:

View file

@ -6,4 +6,4 @@ include ../../../hack/package.mk
update:
rm -rf templates
mkdir templates
kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd/experimental?ref=v1.2.0" > templates/crds-experimental.yaml
kubectl kustomize "github.com/kubernetes-sigs/gateway-api/config/crd/experimental?ref=v1.5.1" > templates/crds-experimental.yaml

View file

@ -0,0 +1,23 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $ingressHost := .Values.ingress.host | default (printf "keycloak.%s" $host) }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if eq $gatewayEnabled "true" }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: keycloak
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: https
hostnames:
- {{ $ingressHost | quote }}
rules:
- backendRefs:
- name: keycloak-http
port: 80
{{- end }}

View file

@ -3,6 +3,8 @@
{{- $solver := (index .Values._cluster "solver") | default "http01" }}
{{- $clusterIssuer := (index .Values._cluster "issuer-name") | default "letsencrypt-prod" }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if ne $gatewayEnabled "true" }}
apiVersion: networking.k8s.io/v1
kind: Ingress
@ -33,3 +35,4 @@ spec:
name: keycloak-http
port:
name: http
{{- end }}

View file

@ -1,9 +1,10 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "cdi-uploadproxy" $exposeServices) }}
{{- if and (has "cdi-uploadproxy" $exposeServices) (ne $gatewayEnabled "true") }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:

View file

@ -0,0 +1,23 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "cdi-uploadproxy" $exposeServices) (eq $gatewayEnabled "true") }}
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TLSRoute
metadata:
name: cdi-uploadproxy
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: tls-cdi-uploadproxy
hostnames:
- {{ printf "cdi-uploadproxy.%s" $host | quote }}
rules:
- backendRefs:
- name: cdi-uploadproxy
port: 443
{{- end }}

View file

@ -1,8 +1,9 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "vm-exportproxy" $exposeServices) }}
{{- if and (has "vm-exportproxy" $exposeServices) (ne $gatewayEnabled "true") }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:

View file

@ -0,0 +1,23 @@
{{- $host := index .Values._cluster "root-host" }}
{{- $exposeServices := splitList "," ((index .Values._cluster "expose-services") | default "") }}
{{- $exposeIngress := (index .Values._cluster "expose-ingress") | default "tenant-root" }}
{{- $gatewayEnabled := (index .Values._cluster "gateway-enabled") | default "false" }}
{{- if and (has "vm-exportproxy" $exposeServices) (eq $gatewayEnabled "true") }}
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TLSRoute
metadata:
name: vm-exportproxy
spec:
parentRefs:
- group: gateway.networking.k8s.io
kind: Gateway
name: cozystack
namespace: {{ $exposeIngress }}
sectionName: tls-vm-exportproxy
hostnames:
- {{ printf "vm-exportproxy.%s" $host | quote }}
rules:
- backendRefs:
- name: vm-exportproxy
port: 443
{{- end }}

View file

@ -8,7 +8,7 @@ spec:
singular: tenant
plural: tenants
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"host":{"description":"The hostname used to access tenant services (defaults to using the tenant name as a subdomain for its parent tenant host).","type":"string","default":""},"etcd":{"description":"Deploy own Etcd cluster.","type":"boolean","default":false},"monitoring":{"description":"Deploy own Monitoring Stack.","type":"boolean","default":false},"ingress":{"description":"Deploy own Ingress Controller.","type":"boolean","default":false},"seaweedfs":{"description":"Deploy own SeaweedFS.","type":"boolean","default":false},"schedulingClass":{"description":"The name of a SchedulingClass CR to apply scheduling constraints for this tenant's workloads.","type":"string","default":""},"resourceQuotas":{"description":"Define resource quotas for the tenant.","type":"object","default":{},"additionalProperties":{"pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}
{"title":"Chart Values","type":"object","properties":{"host":{"description":"The hostname used to access tenant services (defaults to using the tenant name as a subdomain for its parent tenant host).","type":"string","default":""},"etcd":{"description":"Deploy own Etcd cluster.","type":"boolean","default":false},"monitoring":{"description":"Deploy own Monitoring Stack.","type":"boolean","default":false},"ingress":{"description":"Deploy own Ingress Controller.","type":"boolean","default":false},"gateway":{"description":"Deploy own Gateway API Gateway (backed by Cilium Gateway API controller).","type":"boolean","default":false},"seaweedfs":{"description":"Deploy own SeaweedFS.","type":"boolean","default":false},"schedulingClass":{"description":"The name of a SchedulingClass CR to apply scheduling constraints for this tenant's workloads.","type":"string","default":""},"resourceQuotas":{"description":"Define resource quotas for the tenant.","type":"object","default":{},"additionalProperties":{"pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}
release:
prefix: tenant-
labels:
@ -23,7 +23,7 @@ spec:
plural: Tenants
description: Separated tenant namespace
icon: PHN2ZyB3aWR0aD0iMTQ0IiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDE0NCAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxNDQiIGhlaWdodD0iMTQ0IiByeD0iMjQiIGZpbGw9InVybCgjcGFpbnQwX2xpbmVhcl82ODdfMzQwMykiLz4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwXzY4N18zNDAzKSI+CjxwYXRoIGQ9Ik03MiAyOUM2Ni4zOTI2IDI5IDYxLjAxNDggMzEuMjM4OCA1Ny4wNDk3IDM1LjIyNEM1My4wODQ3IDM5LjIwOTEgNTAuODU3MSA0NC42MTQxIDUwLjg1NzEgNTAuMjVDNTAuODU3MSA1NS44ODU5IDUzLjA4NDcgNjEuMjkwOSA1Ny4wNDk3IDY1LjI3NkM2MS4wMTQ4IDY5LjI2MTIgNjYuMzkyNiA3MS41IDcyIDcxLjVDNzcuNjA3NCA3MS41IDgyLjk4NTIgNjkuMjYxMiA4Ni45NTAzIDY1LjI3NkM5MC45MTUzIDYxLjI5MDkgOTMuMTQyOSA1NS44ODU5IDkzLjE0MjkgNTAuMjVDOTMuMTQyOSA0NC42MTQxIDkwLjkxNTMgMzkuMjA5MSA4Ni45NTAzIDM1LjIyNEM4Mi45ODUyIDMxLjIzODggNzcuNjA3NCAyOSA3MiAyOVpNNjAuOTgyNiA4My4zMDM3QzYwLjQ1NCA4Mi41ODk4IDU5LjU5NTEgODIuMTkxNCA1OC43MTk2IDgyLjI3NDRDNDUuMzg5NyA4My43MzU0IDM1IDk1LjEwNzQgMzUgMTA4LjkwM0MzNSAxMTEuNzI2IDM3LjI3OTUgMTE0IDQwLjA3MSAxMTRIMTAzLjkyOUMxMDYuNzM3IDExNCAxMDkgMTExLjcwOSAxMDkgMTA4LjkwM0MxMDkgOTUuMTA3NCA5OC42MTAzIDgzLjc1MiA4NS4yNjM4IDgyLjI5MUM4NC4zODg0IDgyLjE5MTQgODMuNTI5NSA4Mi42MDY0IDgzLjAwMDkgODMuMzIwM0w3NC4wOTc4IDk1LjI0MDJDNzMuMDQwNiA5Ni42NTE0IDcwLjkyNjMgOTYuNjUxNCA2OS44NjkyIDk1LjI0MDJMNjAuOTY2MSA4My4zMjAzTDYwLjk4MjYgODMuMzAzN1oiIGZpbGw9ImJsYWNrIi8+CjwvZz4KPGRlZnM+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQwX2xpbmVhcl82ODdfMzQwMyIgeDE9IjcyIiB5MT0iMTQ0IiB4Mj0iLTEuMjgxN2UtMDUiIHkyPSI0IiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CjxzdG9wIHN0b3AtY29sb3I9IiNDMEQ2RkYiLz4KPHN0b3Agb2Zmc2V0PSIwLjMiIHN0b3AtY29sb3I9IiNDNERBRkYiLz4KPHN0b3Agb2Zmc2V0PSIwLjY1IiBzdG9wLWNvbG9yPSIjRDNFOUZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0U5RkZGRiIvPgo8L2xpbmVhckdyYWRpZW50Pgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzY4N18zNDAzIj4KPHJlY3Qgd2lkdGg9Ijc0IiBoZWlnaHQ9Ijg1IiBmaWxsPSJ3aGl0ZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMzUgMjkpIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==
keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "etcd"], ["spec", "monitoring"], ["spec", "ingress"], ["spec", "seaweedfs"], ["spec", "schedulingClass"], ["spec", "resourceQuotas"]]
keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "host"], ["spec", "etcd"], ["spec", "monitoring"], ["spec", "ingress"], ["spec", "gateway"], ["spec", "seaweedfs"], ["spec", "schedulingClass"], ["spec", "resourceQuotas"]]
secrets:
exclude: []
include: []

View file

@ -181,6 +181,16 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
return nil, apierrors.NewBadRequest(err.Error())
}
// Run the genericapiserver-supplied admission chain (mutating + validating
// webhooks and ValidatingAdmissionPolicies) before persisting anything.
// Custom REST handlers must invoke this hook explicitly — unlike
// genericregistry.Store, which wires it automatically.
if createValidation != nil {
if err := createValidation(ctx, obj); err != nil {
return nil, err
}
}
// Convert Application to HelmRelease
helmRelease, err := r.ConvertApplicationToHelmRelease(app)
if err != nil {
@ -590,6 +600,22 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name)
}
// Run the genericapiserver-supplied admission chain (validating webhooks
// and ValidatingAdmissionPolicies) on the resolved Application before
// removing the underlying HelmRelease. Custom REST handlers must invoke
// this hook explicitly — unlike genericregistry.Store, which wires it
// automatically.
if deleteValidation != nil {
converted, convErr := r.ConvertHelmReleaseToApplication(ctx, helmRelease)
if convErr != nil {
klog.Errorf("Failed to convert HelmRelease %s to Application for delete admission: %v", helmReleaseName, convErr)
return nil, false, convErr
}
if err := deleteValidation(ctx, &converted); err != nil {
return nil, false, err
}
}
klog.V(6).Infof("Deleting HelmRelease %s in namespace %s", helmReleaseName, namespace)
// Delete the HelmRelease corresponding to the Application