diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0d801c..423fc42 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,15 +23,15 @@ env: jobs: markup-lint: name: Markup - uses: devpro/github-workflow-parts/.github/workflows/reusable-markup-lint.yml@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/.github/workflows/reusable-markup-lint.yml@398cf79719f90e41e3407bc9f060e297629d800d # The VitePress site is published by the GitLab pipeline, as the Pages of this repository serve the chart repository. docs: name: Docs - uses: devpro/github-workflow-parts/.github/workflows/reusable-node-quality.yml@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/.github/workflows/reusable-node-quality.yml@398cf79719f90e41e3407bc9f060e297629d800d with: job-name: Docs - workflow-parts-version: 99e797d0672c8a4fb39c4174173fa677c00a5d1e + workflow-parts-version: 398cf79719f90e41e3407bc9f060e297629d800d charts: name: Charts @@ -50,13 +50,13 @@ jobs: # note: important to have chart-testing work (see https://github.com/helm/chart-testing/issues/186) fetch-depth: 0 - name: Install Helm - uses: devpro/github-workflow-parts/actions/helm/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/helm/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Install kube-linter - uses: devpro/github-workflow-parts/actions/kube-linter/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/kube-linter/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Run kube-linter run: kube-linter lint charts --config .kube-linter.yaml - name: Set up chart-testing - uses: devpro/github-workflow-parts/actions/chart-testing/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/chart-testing/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Add dependency chart repositories run: ./scripts/add_helm_repo.sh - name: List changed charts @@ -72,12 +72,12 @@ jobs: if: steps.list-changed.outputs.changed == 'true' run: ct lint $CHARTS_DIRECTORIES_ARG --target-branch "$DEFAULT_BRANCH" - name: Install kubeconform - uses: devpro/github-workflow-parts/actions/kubeconform/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/kubeconform/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Validate manifests against the Kubernetes schemas run: ./scripts/validate_charts.sh # The standalone binary of the helm-unittest plugin, so no plugin is installed into Helm. - name: Install helm-unittest - uses: devpro/github-workflow-parts/actions/helm-unittest/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/helm-unittest/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Run chart unit tests run: | charts=$(dirname charts/*/tests | sort -u) @@ -96,14 +96,14 @@ jobs: with: fetch-depth: 0 - name: Install Helm - uses: devpro/github-workflow-parts/actions/helm/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/helm/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Set up chart-testing - uses: devpro/github-workflow-parts/actions/chart-testing/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/chart-testing/setup@398cf79719f90e41e3407bc9f060e297629d800d - name: Add dependency chart repositories run: ./scripts/add_helm_repo.sh # kind and kubectl are installed by an action of the workflow parts, as helm/kind-action is a JavaScript action, and a container image has neither preinstalled. - name: Install kind and kubectl - uses: devpro/github-workflow-parts/actions/kind/setup@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/actions/kind/setup@398cf79719f90e41e3407bc9f060e297629d800d # The cluster name carries the run, so two runs on one Docker daemon never share a cluster. - name: Create kind cluster id: create-cluster diff --git a/.github/workflows/pkg.yml b/.github/workflows/pkg.yml index 57f668b..64a2b84 100644 --- a/.github/workflows/pkg.yml +++ b/.github/workflows/pkg.yml @@ -20,6 +20,6 @@ concurrency: jobs: helm-publication: name: Helm - uses: devpro/github-workflow-parts/.github/workflows/reusable-helm-publication.yml@99e797d0672c8a4fb39c4174173fa677c00a5d1e + uses: devpro/github-workflow-parts/.github/workflows/reusable-helm-publication.yml@398cf79719f90e41e3407bc9f060e297629d800d with: - workflow-parts-version: 99e797d0672c8a4fb39c4174173fa677c00a5d1e + workflow-parts-version: 398cf79719f90e41e3407bc9f060e297629d800d diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 622967b..8348d2d 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,21 +1,21 @@ -stages: - - deploy - -# avoid duplicate GitLab pipeline runs from GitHub notifications (two messages are received on a commit on a branch with a Pull Request) +# runs once for a merge request, and once for the default branch; +# the default branch publishes the documentation site, as the Pages of the GitHub repository serve the chart repository workflow: rules: - - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - - if: '$CI_PIPELINE_SOURCE == "web"' + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH + +stages: + - test + - deploy -pages: - stage: deploy - image: node:22 - cache: - paths: - - node_modules/ - script: - - npm install - - npm run docs:build - artifacts: - paths: - - public +include: + # pins a commit, as a tag can move + - component: $CI_SERVER_FQDN/devpro-labs/compliance/gitlab-components/markup-lint@c2dfed0c4ba1511063ef03cd6cba61c15dd60b33 + - component: $CI_SERVER_FQDN/devpro-labs/compliance/gitlab-components/helm-quality@c2dfed0c4ba1511063ef03cd6cba61c15dd60b33 + inputs: + # adds the chart repositories of the dependencies + setup_command: ./scripts/add_helm_repo.sh + - component: $CI_SERVER_FQDN/devpro-labs/compliance/gitlab-components/pages-deployment@c2dfed0c4ba1511063ef03cd6cba61c15dd60b33 + inputs: + build_command: npm ci && npm run docs:build diff --git a/charts/sidelab/Chart.yaml b/charts/sidelab/Chart.yaml index cd897e6..b8e8743 100644 --- a/charts/sidelab/Chart.yaml +++ b/charts/sidelab/Chart.yaml @@ -4,7 +4,7 @@ description: > Self-hosted interactive lab platform. Deploys the Sidelab launcher, which manages lab sessions as ephemeral Kubernetes Pods inside tenant-scoped namespaces. type: application -version: 0.1.11 +version: 0.1.12 appVersion: "0.1.0" keywords: - sidelab diff --git a/charts/sidelab/ci/oidc-values.yaml b/charts/sidelab/ci/oidc-values.yaml new file mode 100644 index 0000000..c762056 --- /dev/null +++ b/charts/sidelab/ci/oidc-values.yaml @@ -0,0 +1,17 @@ +# Single sign-on behind the dashboard Ingress, the public URL derived from its host. +# Guards the OIDC keys of the ConfigMap and the generated Secret, and their validation in _helpers.tpl. +image: + repository: ci-dummy-registry/app + +domain: example.test + +ingress: + enabled: true + tls: + enabled: true + +oidc: + issuer: https://keycloak.example.test/realms/platform + clientId: sidelab + clientSecret: ci-dummy-secret + name: Keycloak diff --git a/charts/sidelab/fallstar.yaml b/charts/sidelab/fallstar.yaml index 9392296..15d81ea 100644 --- a/charts/sidelab/fallstar.yaml +++ b/charts/sidelab/fallstar.yaml @@ -93,6 +93,33 @@ options: default: true when: { equals: { labAccess: ingress } } + - key: signIn + title: Sign-in + description: The launcher's own accounts only, or a Keycloak realm as well, whose organizations are the tenants. + group: Sign-in + type: enum + values: [password, keycloak] + default: password + bind: + - { resource: Job/keycloak/sidelab-oidc-client, exists: false, as: password } + - { resource: Job/keycloak/sidelab-oidc-client, exists: true, as: keycloak } + when: { equals: { labAccess: ingress } } + - key: keycloakHost + title: Keycloak host + group: Sign-in + type: string + default: keycloak.${{ cluster.domain }} + bind: { chart: sidelab, path: [values, oidc, issuer], pattern: '^https://([^/]+)/' } + when: { equals: { labAccess: ingress, signIn: keycloak } } + - key: keycloakRealm + title: Keycloak realm + description: The realm of the Keycloak app, which this app adds its client to. + group: Sign-in + type: string + default: platform + bind: { chart: sidelab, path: [values, oidc, issuer], pattern: '/realms/([^/]+)$' } + when: { equals: { labAccess: ingress, signIn: keycloak } } + - key: sessionDefaultDuration title: Default session duration, in minutes group: Sessions @@ -193,6 +220,38 @@ patches: extraEnv: - name: TRUST_PROXY value: "1" + - when: { equals: { labAccess: ingress, signIn: keycloak } } + chart: sidelab + notes: + - path: [values, oidc] + text: The client secret is the OIDC_CLIENT_SECRET key of the auth Secret, which the Job of the sidelab client gives Keycloak too. + patch: + values: + oidc: + issuer: https://${{ options.keycloakHost }}/realms/${{ options.keycloakRealm }} + clientId: sidelab + name: Keycloak + - when: { secretStore: true, equals: { labAccess: ingress, signIn: keycloak } } + resource: ExternalSecret/sidelab/sidelab-auth + notes: + - path: [spec, data] + text: The list is replaced as a whole, so it repeats the two entries of the resource. + patch: + spec: + target: + template: + data: + OIDC_CLIENT_SECRET: "{{ .oidcClientSecret }}" + data: + - secretKey: jwtSecret + remoteRef: + key: sidelab-jwt-secret + - secretKey: adminPassword + remoteRef: + key: sidelab-admin-password + - secretKey: oidcClientSecret + remoteRef: + key: sidelab-oidc-client-secret - when: { equals: { labAccess: nodeport } } chart: sidelab patch: @@ -307,6 +366,157 @@ resources: - secretKey: password remoteRef: key: ghcr-token + - file: apps/externalsecrets/sidelab.yaml + when: { secretStore: true, equals: { labAccess: ingress, signIn: keycloak } } + notes: + - path: [] + text: The same client secret as OIDC_CLIENT_SECRET of sidelab-auth, for the Job registering the client at Keycloak. + object: + apiVersion: external-secrets.io/v1 + kind: ExternalSecret + metadata: { name: sidelab-oidc, namespace: keycloak } + spec: + refreshInterval: 1h + secretStoreRef: + name: ${{ cluster.secretStore }} + kind: ClusterSecretStore + target: + name: sidelab-oidc + creationPolicy: Owner + data: + - secretKey: CLIENT_SECRET + remoteRef: + key: sidelab-oidc-client-secret + - file: apps/keycloak/sidelab-client.yaml + when: { equals: { labAccess: ingress, signIn: keycloak } } + notes: + - path: [data] + text: |- + The client of the launcher in the realm of the Keycloak app, applied by keycloak-config-cli as that app applies the realm. + The file never changes: the realm, the address and the secret come from the environment of the Job, so a changed option changes the Job and Flux runs it again. + The device grant is for sidelab-cli auth login, which the launcher runs as this client, and the post-logout address for the dashboard's sign-out. + object: + apiVersion: v1 + kind: ConfigMap + metadata: { name: sidelab-oidc-client, namespace: keycloak } + data: + client.json: |- + { + "realm": "$(env:REALM)", + "roles": { + "client": { + "sidelab": [ + { "name": "global-admin", "description": "Every tenant, every account, the course catalog" }, + { "name": "tenant-admin", "description": "The accounts and lab secrets of the organization the account belongs to" } + ] + } + }, + "clients": [ + { + "clientId": "sidelab", + "name": "Sidelab", + "enabled": true, + "protocol": "openid-connect", + "publicClient": false, + "secret": "$(env:CLIENT_SECRET)", + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "redirectUris": [ "$(env:PUBLIC_URL)/api/auth/oidc/callback" ], + "webOrigins": [], + "attributes": { + "pkce.code.challenge.method": "S256", + "oauth2.device.authorization.grant.enabled": "true", + "post.logout.redirect.uris": "$(env:PUBLIC_URL)/" + }, + "defaultClientScopes": [ "profile", "email", "organization" ], + "optionalClientScopes": [], + "protocolMappers": [ + { + "name": "sidelab roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-client-role-mapper", + "config": { + "usermodel.clientRoleMapping.clientId": "sidelab", + "claim.name": "resource_access.${client_id}.roles", + "jsonType.label": "String", + "multivalued": "true", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "false" + } + } + ] + } + ] + } + - file: apps/keycloak/sidelab-client.yaml + when: { equals: { labAccess: ingress, signIn: keycloak } } + notes: + - path: [spec, template, spec, containers, '0', env] + text: no-delete, as the Job of the realm, so neither deletes the clients and roles the other applies. + object: + apiVersion: batch/v1 + kind: Job + metadata: + name: sidelab-oidc-client + namespace: keycloak + annotations: + kustomize.toolkit.fluxcd.io/force: enabled + argocd.argoproj.io/hook: Sync + argocd.argoproj.io/hook-delete-policy: BeforeHookCreation + spec: + backoffLimit: 10 + template: + spec: + restartPolicy: OnFailure + securityContext: + runAsNonRoot: true + seccompProfile: { type: RuntimeDefault } + containers: + - name: config + image: docker.io/adorsys/keycloak-config-cli:6.5.1-26 + env: + - name: REALM + value: ${{ options.keycloakRealm }} + - name: PUBLIC_URL + value: https://sidelab.${{ options.domain }} + - name: CLIENT_SECRET + valueFrom: + secretKeyRef: { name: sidelab-oidc, key: CLIENT_SECRET } + - name: KEYCLOAK_URL + value: http://keycloak-keycloakx-http.keycloak.svc + - name: KEYCLOAK_USER + valueFrom: + secretKeyRef: { name: keycloak-admin, key: username } + - name: KEYCLOAK_PASSWORD + valueFrom: + secretKeyRef: { name: keycloak-admin, key: password } + - name: KEYCLOAK_AVAILABILITYCHECK_ENABLED + value: "true" + - name: KEYCLOAK_AVAILABILITYCHECK_TIMEOUT + value: 300s + - name: IMPORT_FILES_LOCATIONS + value: /config/client.json + - name: IMPORT_VARSUBSTITUTION_ENABLED + value: "true" + - name: IMPORT_MANAGED_CLIENT + value: no-delete + - name: IMPORT_MANAGED_ROLE + value: no-delete + - name: IMPORT_MANAGED_CLIENTSCOPE + value: no-delete + securityContext: + allowPrivilegeEscalation: false + capabilities: { drop: [ALL] } + volumeMounts: + - name: config + mountPath: /config + readOnly: true + volumes: + - name: config + configMap: { name: sidelab-oidc-client } secrets: - { name: sidelab-jwt-secret, description: Signing key of the launcher tokens., generate: hex32, when: { secretsManaged: true }, target: { secret: sidelab-auth, key: JWT_SECRET, namespace: sidelab } } @@ -317,10 +527,17 @@ secrets: - { name: sidelab-mongodb-url, description: "mongodb://root:@sidelab-mongodb:27017/sidelab?authSource=admin, with the root password above.", when: { secretsManaged: true, secretStore: false, equals: { database: mongo-bundled } }, target: { secret: sidelab-db, key: DB_URL, namespace: sidelab } } - { name: ghcr-username, description: GitHub user pulling the private images., when: { secretStore: true, option: privateImages } } - { name: ghcr-token, description: "GitHub token with read:packages on ghcr.io/devpro.", when: { secretStore: true, option: privateImages } } + - { name: sidelab-oidc-client-secret, description: Secret of the sidelab client at Keycloak., generate: hex32, when: { secretsManaged: true, equals: { labAccess: ingress, signIn: keycloak } }, target: { secret: sidelab-auth, key: OIDC_CLIENT_SECRET, namespace: sidelab } } warnings: - when: { secretsManaged: false, equals: { database: [mongo, mongo-bundled] } } text: reads its database from Secret sidelab-db in namespace sidelab, which neither a secret store nor SOPS creates on this cluster + - when: { equals: { labAccess: ingress, signIn: keycloak }, not: { uses: { identity-provider: keycloak } } } + text: signs in through Keycloak, which no app of this cluster provides, so the Job adding its client waits for a Keycloak that never answers + - when: { secretStore: false, equals: { labAccess: ingress, signIn: keycloak } } + text: gives Keycloak its client secret from Secret sidelab-oidc in namespace keycloak, key CLIENT_SECRET, which only a secret store creates; without one it holds the OIDC_CLIENT_SECRET of sidelab-auth, created by hand + - when: { equals: { labAccess: ingress, signIn: keycloak, tls: none } } + text: registers an https redirect URI at Keycloak, which a dashboard without TLS does not answer guide: prerequisites: @@ -331,6 +548,7 @@ guide: - kubectl get pods -n sidelab - kubectl logs -n sidelab deploy/sidelab --tail=30 - kubectl get ns -l app.kubernetes.io/managed-by=sidelab + - "With Keycloak: kubectl logs -n keycloak job/sidelab-oidc-client --tail=20" gotchas: - title: Every lab orders its own certificate, rate limit hit cause: TLS from cert-manager, whose annotation the chart copies onto every session Ingress. @@ -347,3 +565,9 @@ guide: - title: Tenant namespaces left after a teardown cause: The launcher creates them, not Flux. fix: Delete the namespaces labelled app.kubernetes.io/managed-by=sidelab by hand. + - title: Keycloak sign-in refused, no tenant for the organization + cause: The launcher never creates a tenant from a claim. + fix: Create the tenant in Admin > Tenants with the alias of the organization as its name, before its members sign in. + - title: Keycloak sign-in refused for a member of several organizations + cause: One account belongs to one tenant, so the launcher cannot pick. + fix: Keep the person in one organization of the realm. diff --git a/charts/sidelab/templates/_helpers.tpl b/charts/sidelab/templates/_helpers.tpl index 0a9b0c0..baddfad 100644 --- a/charts/sidelab/templates/_helpers.tpl +++ b/charts/sidelab/templates/_helpers.tpl @@ -114,6 +114,19 @@ Empty if neither is set. {{- end -}} {{- end }} +{{/* +Address of the dashboard. +launcher.publicUrl wins; otherwise derived from the dashboard Ingress host, https when ingress.tls.enabled. +Empty without either, as a NodePort dashboard has no address the chart knows. +*/}} +{{- define "sidelab.publicUrl" -}} +{{- if .Values.launcher.publicUrl -}} +{{- .Values.launcher.publicUrl -}} +{{- else if and .Values.ingress.enabled (include "sidelab.ingressHost" .) -}} +{{- printf "%s://%s" (ternary "https" "http" .Values.ingress.tls.enabled) (include "sidelab.ingressHost" .) -}} +{{- end -}} +{{- end }} + {{/* Lab session wildcard domain. launcher.labDomain wins; otherwise derived from the shared top-level `domain` value as "labs.". @@ -220,6 +233,17 @@ Validate required values and emit a clear error message. {{- if and (eq .Values.launcher.labAccess "ingress") (not (include "sidelab.labDomain" .)) }} {{- fail "launcher.labDomain or domain is required when launcher.labAccess=ingress." }} {{- end }} +{{- if .Values.oidc.issuer }} +{{- if not .Values.oidc.clientId }} +{{- fail "oidc.clientId is required when oidc.issuer is set." }} +{{- end }} +{{- if and (not .Values.auth.existingSecret) (not .Values.oidc.clientSecret) }} +{{- fail "oidc.clientSecret is required when oidc.issuer is set, unless auth.existingSecret holds OIDC_CLIENT_SECRET." }} +{{- end }} +{{- if not (include "sidelab.publicUrl" .) }} +{{- fail "launcher.publicUrl, or the dashboard Ingress, is required when oidc.issuer is set: the redirect URI is built from it." }} +{{- end }} +{{- end }} {{- if gt (int (include "sidelab.maxReplicas" .)) 1 }} {{- if eq .Values.database.backend "sqlite" }} {{- fail "database.backend=sqlite is a single local file and cannot be shared between launcher Pods. More than one replica requires database.backend=mongo and persistence.enabled=false." }} diff --git a/charts/sidelab/templates/configmap.yaml b/charts/sidelab/templates/configmap.yaml index 449cdf6..5b312a3 100644 --- a/charts/sidelab/templates/configmap.yaml +++ b/charts/sidelab/templates/configmap.yaml @@ -25,6 +25,16 @@ data: K8S_LAB_DOMAIN: {{ include "sidelab.labDomain" . | quote }} K8S_INGRESS_TEMPLATE: "/app/config/ingress-template.yaml" {{- end }} + {{- with include "sidelab.publicUrl" . }} + LAUNCHER_PUBLIC_URL: {{ . | quote }} + {{- end }} + {{- with .Values.oidc.issuer }} + OIDC_ISSUER: {{ . | quote }} + OIDC_CLIENT_ID: {{ $.Values.oidc.clientId | quote }} + {{- with $.Values.oidc.name }} + OIDC_NAME: {{ . | quote }} + {{- end }} + {{- end }} K8S_NAMESPACE_PREFIX: {{ .Values.launcher.namespacePrefix | quote }} {{- if .Values.launcher.labImagePullSecret }} K8S_LAB_IMAGE_PULL_SECRET: {{ .Values.launcher.labImagePullSecret | quote }} diff --git a/charts/sidelab/templates/secret.yaml b/charts/sidelab/templates/secret.yaml index b7173e6..14aee6b 100644 --- a/charts/sidelab/templates/secret.yaml +++ b/charts/sidelab/templates/secret.yaml @@ -12,6 +12,9 @@ stringData: JWT_SECRET: {{ include "sidelab.jwtSecret" . | quote }} ADMIN_USERNAME: {{ .Values.auth.adminUsername | quote }} ADMIN_PASSWORD: {{ include "sidelab.adminPassword" . | quote }} + {{- if .Values.oidc.issuer }} + OIDC_CLIENT_SECRET: {{ .Values.oidc.clientSecret | quote }} + {{- end }} {{- end }} {{- if and (eq .Values.database.backend "mongo") (not .Values.database.mongo.existingSecret) }} --- diff --git a/charts/sidelab/values.yaml b/charts/sidelab/values.yaml index 0bdbc1b..9a518e8 100644 --- a/charts/sidelab/values.yaml +++ b/charts/sidelab/values.yaml @@ -27,6 +27,17 @@ auth: # -- Existing Secret with the keys JWT_SECRET, ADMIN_USERNAME and ADMIN_PASSWORD, replacing the three values above. existingSecret: "" +# Single sign-on through OpenID Connect (docs/configuration.md in sidelab), off while issuer is empty. +oidc: + # -- Issuer URL, such as https://keycloak.example.com/realms/platform. + issuer: "" + # -- The launcher's client at the provider. + clientId: "" + # -- Secret of that client, written to the generated auth Secret; with auth.existingSecret, its OIDC_CLIENT_SECRET key instead. + clientSecret: "" + # -- What the button says after "Sign in with", the launcher's default when empty. + name: "" + database: # -- sqlite or mongo. backend: "sqlite" @@ -86,6 +97,9 @@ launcher: # -- Wildcard domain of lab sessions when labAccess=ingress, defaults to labs.. labDomain: "" + # -- Address of the dashboard, which single sign-on and password reset build their links from; https:// with the dashboard Ingress, http:// without ingress.tls.enabled. + publicUrl: "" + # -- ConfigMap holding a custom lab session Ingress template (key ingress-template.yaml), replacing the generated one. ingressTemplateConfigMap: "" diff --git a/charts/terraform-backend-mongodb/Chart.yaml b/charts/terraform-backend-mongodb/Chart.yaml index ccea1b2..d577195 100644 --- a/charts/terraform-backend-mongodb/Chart.yaml +++ b/charts/terraform-backend-mongodb/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: terraform-backend-mongodb description: Helm chart for Terraform Backend MongoDB type: application -version: 0.3.2 +version: 0.3.4 appVersion: "1.3.0" home: https://github.com/devpro/terraform-backend-mongodb sources: diff --git a/charts/terraform-backend-mongodb/README.md b/charts/terraform-backend-mongodb/README.md index 183da1c..617e6c6 100644 --- a/charts/terraform-backend-mongodb/README.md +++ b/charts/terraform-backend-mongodb/README.md @@ -110,6 +110,18 @@ network: - 10.42.0.0/16 ``` +`networkPolicy.enabled` is what makes `trustAllProxies: true` safe on a cluster whose CNI enforces NetworkPolicy. +It admits the ingress controller alone, so no other workload can reach the pod and choose the address its failed attempts are counted against. +The defaults match the Traefik of k3s and RKE2, and another controller is named by its namespace and pod labels, for example with ingress-nginx: + +```yaml +networkPolicy: + enabled: true + ingressControllerNamespace: ingress-nginx + ingressControllerPodSelector: + app.kubernetes.io/name: ingress-nginx +``` + Rate limiting by source address belongs at the ingress rather than in the application, since the edge rejects a request before any CPU is spent on it and holds one counter across every replica. The annotation depends on the ingress controller, for example with ingress-nginx: @@ -124,6 +136,26 @@ TLS termination is not optional for this application. The password is replayed on every request, so a single plaintext hop exposes the state of every workspace in the tenant. Note that `skip_cert_verification` in a Terraform backend block defeats the protection it appears to configure. +HSTS belongs at the ingress too, so that a client never sends the password over plain HTTP after its first visit. +ingress-nginx adds the header by default to a host with TLS. +Traefik adds it through a `Middleware` with `headers.stsSeconds: 31536000`, referenced by the `traefik.ingress.kubernetes.io/router.middlewares` annotation. + +## State history + +Application version 1.3.1 computes the history of a state after the write returns, in a background worker, so a large state never slows a `terraform apply`. +The defaults under `history` in [values.yaml](values.yaml) suit most deployments. +A change whose diff is estimated above `history.maxDiffComparisons` is set aside with an error naming the array, and with `dotnet.openTelemetry.enabled` the error reaches the collector as a span and a counter. + +## Database security + +The database holds the Terraform state of every workspace, with every secret it carries, in the clear. +It is protected as a secret store: + +- encryption at rest, of the volume or of the MongoDB storage engine +- a read-only user for each application that reads `tf_state`, and the read-write user for the backend alone +- network access from the backend and those applications only +- backups and dumps handled as secrets, with the same access control and retention as the database + ## Going further Check the [contribution guide](CONTRIBUTING.md). diff --git a/charts/terraform-backend-mongodb/ci/network-policy-values.yaml b/charts/terraform-backend-mongodb/ci/network-policy-values.yaml new file mode 100644 index 0000000..f5ea622 --- /dev/null +++ b/charts/terraform-backend-mongodb/ci/network-policy-values.yaml @@ -0,0 +1,9 @@ +# The NetworkPolicy, rendered against the bundled MongoDB so that the server starts. +mongodb: + enabled: true + auth: + rootPassword: ci-only-password +networkPolicy: + enabled: true + additionalIngressNamespaces: + - monitoring diff --git a/charts/terraform-backend-mongodb/templates/deployment.yaml b/charts/terraform-backend-mongodb/templates/deployment.yaml index f87388a..5e0a0d3 100644 --- a/charts/terraform-backend-mongodb/templates/deployment.yaml +++ b/charts/terraform-backend-mongodb/templates/deployment.yaml @@ -111,6 +111,10 @@ spec: value: {{ $.Values.authentication.maxFailedAttempts | quote }} - name: Authentication__LockoutSeconds value: {{ $.Values.authentication.lockoutSeconds | quote }} + - name: Features__IsHistoryWorkerEnabled + value: {{ $.Values.history.workerEnabled | quote }} + - name: History__MaxDiffComparisons + value: {{ $.Values.history.maxDiffComparisons | int64 | quote }} - name: Network__TrustAllProxies value: {{ $.Values.network.trustAllProxies | quote }} {{- range $index, $proxy := $.Values.network.knownProxies }} @@ -134,6 +138,14 @@ spec: value: {{ $.Values.dotnet.openTelemetry.endpoint | quote }} - name: OTEL_EXPORTER_OTLP_PROTOCOL value: {{ $.Values.dotnet.openTelemetry.protocol | quote }} + # a MongoDB span can carry the command it traces, and a state write carries every secret of the workspace + - name: OTEL_DOTNET_AUTO_TRACES_MONGODB_INSTRUMENTATION_ENABLED + value: "false" + # export the span and the counters of the history worker, which report a change set aside + - name: OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES + value: "Devpro.TerraformBackend.History" + - name: OTEL_DOTNET_AUTO_METRICS_ADDITIONAL_SOURCES + value: "Devpro.TerraformBackend.History" {{- else }} - name: OTEL_TRACES_EXPORTER value: "none" diff --git a/charts/terraform-backend-mongodb/templates/networkpolicy.yaml b/charts/terraform-backend-mongodb/templates/networkpolicy.yaml new file mode 100644 index 0000000..87eb6ac --- /dev/null +++ b/charts/terraform-backend-mongodb/templates/networkpolicy.yaml @@ -0,0 +1,41 @@ +{{- if and .Values.networkPolicy.enabled .Values.webapi.enabled }} +{{- $fullname := include "terraform-backend-mongodb.fullname" (dict "app" .Values.webapi "root" $) }} +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ $fullname }} + labels: + app: {{ $fullname }} + app.kubernetes.io/name: {{ $fullname }} + {{- include "terraform-backend-mongodb.commonLabels" (dict "app" .Values.webapi "root" $) | nindent 4 }} +spec: + podSelector: + matchLabels: + app: {{ $fullname }} + app.kubernetes.io/name: {{ $fullname }} + # egress stays open: the database and the OpenTelemetry collector can be anywhere + policyTypes: + - Ingress + ingress: + # the ingress controller is the only caller, so the X-Forwarded-For the application trusts comes from it + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .Values.networkPolicy.ingressControllerNamespace }} + podSelector: + matchLabels: + {{- toYaml .Values.networkPolicy.ingressControllerPodSelector | nindent 14 }} + ports: + - port: {{ .Values.webapi.containerPort }} + protocol: TCP + {{- range .Values.networkPolicy.additionalIngressNamespaces }} + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ . }} + ports: + - port: {{ $.Values.webapi.containerPort }} + protocol: TCP + {{- end }} +{{- end }} diff --git a/charts/terraform-backend-mongodb/values.yaml b/charts/terraform-backend-mongodb/values.yaml index cade6a6..6f66420 100644 --- a/charts/terraform-backend-mongodb/values.yaml +++ b/charts/terraform-backend-mongodb/values.yaml @@ -81,6 +81,18 @@ authentication: # The application refuses to start at 0 or below. lockoutSeconds: 300 +# State history, available from application version 1.3.1. +# A state write queues the replaced version, and a background worker computes the change into tf_state_history after the write returns. +history: + # -- Run the worker that computes the history. + # At least one replica must run it, or the queue grows and no history is written. + workerEnabled: true + # -- Estimated array item comparisons, about 70 bytes of memory each, above which a change is not computed. + # The default bounds one diff to about 280 MB: size the memory limit of the container above it. + # A change above it is set aside with an error naming the array, and the state itself is saved as usual. + # The application refuses to start below 1. + maxDiffComparisons: 4000000 + # Which reverse proxies the application believes when it reads the caller's address. # This is a prerequisite for the lockout above and for the authentication failure log, not a detail: behind an ingress an unconfigured application sees the proxy's address on every request, so every caller shares one lockout bucket and an attacker on the internet can lock the real operator out of the backend. network: @@ -96,6 +108,19 @@ network: knownNetworks: [] # - 10.42.0.0/16 +# Admits the ingress controller alone, which is what makes trustAllProxies safe: no other workload can reach the pod and choose the address its failed attempts are counted against. +# It needs a CNI that enforces NetworkPolicy, and the defaults match the Traefik of k3s and RKE2. +networkPolicy: + # -- Render the NetworkPolicy. + enabled: false + # -- Namespace of the ingress controller, for example ingress-nginx. + ingressControllerNamespace: kube-system + # -- Pod labels of the ingress controller in that namespace, for example app.kubernetes.io/name: ingress-nginx. + ingressControllerPodSelector: + app.kubernetes.io/name: traefik + # -- Other namespaces admitted, for example one that scrapes the pod. + additionalIngressNamespaces: [] + # optional: image registry credentials, e.g. for a private mirror of the image above imagePullSecrets: [] # - name: my-registry-secret diff --git a/docs/custom-charts/terraform-backend-mongodb.md b/docs/custom-charts/terraform-backend-mongodb.md index 78b2e9a..d5d4d77 100644 --- a/docs/custom-charts/terraform-backend-mongodb.md +++ b/docs/custom-charts/terraform-backend-mongodb.md @@ -46,6 +46,14 @@ webapi: databaseName: tfbackend_beta ``` +```yaml [Network policy] +networkPolicy: + enabled: true + ingressControllerNamespace: kube-system # or ingress-nginx + ingressControllerPodSelector: + app.kubernetes.io/name: traefik # or ingress-nginx +``` + ::: ## Deployment diff --git a/docs/getting-started/release-cleanup.md b/docs/getting-started/release-cleanup.md new file mode 100644 index 0000000..b72897e --- /dev/null +++ b/docs/getting-started/release-cleanup.md @@ -0,0 +1,54 @@ +# Release cleanup + +## Why + +Every chart version published on `main` becomes a GitHub release, a tag and an entry of `index.yaml` on the `gh-pages` branch. +Nothing ever removes them, so the chart repository keeps offering old versions, and versions of charts removed from `charts/`. +`scripts/delete_old_releases.sh` keeps only the latest version of each chart in `charts/`, and removes everything else. + +## Requirements + +- `git`, `curl`, `jq` and `helm` on the `PATH`. +- A clone of the repository whose `origin` can push to `devpro/helm-charts`. +- A GitHub token in `GITHUB_TOKEN`, allowed to write the repository contents: + a fine-grained token on `devpro/helm-charts` with **Contents: Read and write**, or a classic token with the `repo` scope. + +## Usage + +List the tags whose release would be deleted, without changing anything: + +```bash +scripts/delete_old_releases.sh +``` + +Delete them: + +```bash +GITHUB_TOKEN= scripts/delete_old_releases.sh --apply +``` + +Delete given tags only, instead of the computed list: + +```bash +GITHUB_TOKEN= scripts/delete_old_releases.sh --apply cow-demo-0.2.3 sidelab-0.1.6 +``` + +With `--apply`, the script: + +1. Deletes the GitHub release of each tag, before the tag, as a release can no longer be found by a deleted tag. +2. Deletes the tags with `git push origin --delete`, and prunes them from the clone. +3. Builds `index.yaml` again from the packages of the releases left, and pushes it to `gh-pages`. + +The site serves the new index once the `PKG` workflow runs again, on the next push to `main` or by hand from the Actions tab. + +## Immutable releases + +GitHub never lets the tag of an immutable release be created again, even once the release and the tag are deleted. +It does no harm for an old version, which is never published again, and the script says which tags it blocked. +A version to publish again is never deleted while its release is immutable: it is published under a new version only, by bumping `version` in its `Chart.yaml`. + +The immutable releases are listed with: + +```bash +curl -s "https://api.github.com/repos/devpro/helm-charts/releases?per_page=100" | jq -r '.[] | "\(.tag_name)\timmutable=\(.immutable)"' +``` diff --git a/scripts/delete_old_releases.sh b/scripts/delete_old_releases.sh new file mode 100644 index 0000000..ea36bbf --- /dev/null +++ b/scripts/delete_old_releases.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# Deletes the GitHub releases and tags of old chart versions, so that the chart repository only offers the versions still maintained. +# Each chart under charts keeps its latest tag, and a chart removed from charts loses all of its tags. +# The tags to delete are listed, and only deleted with --apply, which then builds the index of the gh-pages branch again; tags given as arguments replace the computed list. +# Usage: GITHUB_TOKEN= scripts/delete_old_releases.sh [--apply] [tag...] + +set -euo pipefail + +apply=false +if [[ "${1:-}" == "--apply" ]]; then + apply=true + shift +fi + +repository="devpro/helm-charts" +api="https://api.github.com/repos/${repository}" +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +if [[ $# -gt 0 ]]; then + tags=("$@") +else + # A tag is -, and sort -V orders the versions of a chart from the oldest to the latest. + mapfile -t tags < <(git ls-remote --tags --refs origin | sed 's#.*refs/tags/##' | sort -V | awk ' + { + chart = $0 + sub(/-[0-9][^-]*$/, "", chart) + if (chart in latest) print latest[chart] + latest[chart] = $0 + charts[chart] = 1 + } + END { + for (chart in charts) { + if (system("test -f charts/" chart "/Chart.yaml") != 0) print latest[chart] + } + }' | sort) +fi + +if [[ ${#tags[@]} -eq 0 ]]; then + echo "No tag to delete" + exit 0 +fi +printf '%s\n' "${tags[@]}" +echo "${#tags[@]} tags and their releases to delete" +if [[ "$apply" != true ]]; then + echo "Nothing deleted, run again with --apply to delete them" + exit 0 +fi + +: "${GITHUB_TOKEN:?GITHUB_TOKEN must hold a token allowed to write the contents of ${repository}}" +auth=(-H "Authorization: Bearer ${GITHUB_TOKEN}" -H "Accept: application/vnd.github+json") + +# The releases go first, as a release whose tag is deleted can no longer be found by its tag. +deleted=() +for tag in "${tags[@]}"; do + release=$(curl -fsS "${auth[@]}" "${api}/releases/tags/${tag}" 2>/dev/null || true) + if [[ -z "$release" ]]; then + echo "${tag}: no release" + deleted+=("refs/tags/${tag}") + continue + fi + curl -fsS -X DELETE "${auth[@]}" "${api}/releases/$(jq -r '.id' <<< "$release")" + # GitHub never lets the tag of an immutable release be created again, which only matters for a version to publish again. + if [[ "$(jq -r '.immutable' <<< "$release")" == true ]]; then + echo "${tag}: immutable release deleted, its tag name is blocked for good" + else + echo "${tag}: release deleted" + fi + deleted+=("refs/tags/${tag}") +done + +if [[ ${#deleted[@]} -eq 0 ]]; then + exit 0 +fi +git push origin --delete "${deleted[@]}" +git fetch origin --prune --prune-tags + +# The index is built again from the packages of the releases left, so that it offers no version whose download is gone. +work=$(mktemp -d) +trap 'git worktree remove --force "${work}/pages" 2>/dev/null || true; rm -rf "$work"' EXIT +for tag in $(git ls-remote --tags --refs origin | sed 's#.*refs/tags/##'); do + mkdir "${work}/${tag}" + curl -fsSL -o "${work}/${tag}/${tag}.tgz" "https://github.com/${repository}/releases/download/${tag}/${tag}.tgz" + merge=() + if [[ -f "${work}/index.yaml" ]]; then + merge=(--merge "${work}/index.yaml") + fi + helm repo index "${work}/${tag}" --url "https://github.com/${repository}/releases/download/${tag}" "${merge[@]}" + mv "${work}/${tag}/index.yaml" "${work}/index.yaml" +done +git worktree add --detach "${work}/pages" origin/gh-pages +cp "${work}/index.yaml" "${work}/pages/index.yaml" +git -C "${work}/pages" commit -am "Build the index again from the releases left, once old chart versions are deleted" +git -C "${work}/pages" push origin HEAD:gh-pages