From 161a468b6a7952f0e03a0209211de67cf2606e6f Mon Sep 17 00:00:00 2001 From: bruckins Date: Wed, 4 Nov 2026 16:51:05 +0100 Subject: [PATCH 01/17] Add idp-google chart and wire it into k8shell-bundle Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/chart-idp-google.yaml | 58 ++++++++++++ CLAUDE.md | 2 +- README.md | 4 +- idp-google/Chart.yaml | 5 + idp-google/templates/_helpers.tpl | 64 +++++++++++++ idp-google/templates/cert-idp-google.yaml | 22 +++++ idp-google/templates/cm-config.yaml | 60 ++++++++++++ idp-google/templates/dep-idp-google.yaml | 77 +++++++++++++++ idp-google/templates/regcred.yaml | 9 ++ idp-google/templates/sa-idp-google.yaml | 8 ++ idp-google/templates/sec-idp-google.yaml | 40 ++++++++ idp-google/templates/svc-idp-google.yaml | 19 ++++ idp-google/values-internal.yaml | 8 ++ idp-google/values.yaml | 99 ++++++++++++++++++++ k8shell-bundle/Chart.yaml | 2 +- k8shell-bundle/templates/app-idp-google.yaml | 46 +++++++++ k8shell-bundle/templates/app-k8shell.yaml | 4 + k8shell-bundle/templates/app-secrets.yaml | 4 + k8shell-bundle/values-internal.yaml | 11 +++ k8shell-bundle/values.yaml | 39 +++++++- 20 files changed, 577 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/chart-idp-google.yaml create mode 100644 idp-google/Chart.yaml create mode 100644 idp-google/templates/_helpers.tpl create mode 100644 idp-google/templates/cert-idp-google.yaml create mode 100644 idp-google/templates/cm-config.yaml create mode 100644 idp-google/templates/dep-idp-google.yaml create mode 100644 idp-google/templates/regcred.yaml create mode 100644 idp-google/templates/sa-idp-google.yaml create mode 100644 idp-google/templates/sec-idp-google.yaml create mode 100644 idp-google/templates/svc-idp-google.yaml create mode 100644 idp-google/values-internal.yaml create mode 100644 idp-google/values.yaml create mode 100644 k8shell-bundle/templates/app-idp-google.yaml diff --git a/.github/workflows/chart-idp-google.yaml b/.github/workflows/chart-idp-google.yaml new file mode 100644 index 0000000..eb4cde9 --- /dev/null +++ b/.github/workflows/chart-idp-google.yaml @@ -0,0 +1,58 @@ +name: Build idp-google chart + +on: + push: + tags: + - "v*-idp-google" + + pull_request: + branches: + - "*" + paths: + - "idp-google/**" + - ".github/workflows/chart-idp-google.yaml" + + workflow_dispatch: + +permissions: + contents: read + checks: write + pull-requests: write + +jobs: + idp-google-chart: + runs-on: k8shell-runner + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Compute chart version + id: ver + shell: bash + run: | + set -euo pipefail + + BASE_VERSION="$(awk '/^version:/ {print $2; exit}' idp-google/Chart.yaml)" + CHART_VERSION="${BASE_VERSION}" + COMMIT_ID=$(git rev-parse --short HEAD) + + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + COMMIT_ID=$(echo "${{ github.event.pull_request.head.sha }}" | cut -c1-7) + PR_NUMBER="${{ github.event.pull_request.number }}" + CHART_VERSION="${BASE_VERSION}-pr-${PR_NUMBER}-${COMMIT_ID}" + fi + + echo "chart_version=${CHART_VERSION}" >> "$GITHUB_OUTPUT" + echo "Using chart version: ${CHART_VERSION}" + + - name: Package helm chart + run: | + mkdir -p dist + helm package idp-google -d dist/ --version "${{ steps.ver.outputs.chart_version }}" + + - name: Push helm chart + run: | + helm registry login "${{ secrets.REGISTRY_EXT }}" --username "${{ secrets.HARBOR_USER }}" \ + --password "${{ secrets.HARBOR_PASSWORD }}" + helm push dist/*.tgz "oci://${{ secrets.REGISTRY_EXT }}/charts" diff --git a/CLAUDE.md b/CLAUDE.md index 0329559..c14f222 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,7 +32,7 @@ Each top-level directory is an independent Helm chart published to `oci://ghcr.i |-------|------| | `k8shell` | Core platform — the primary chart users install | | `k8shell-bundle` | Umbrella chart; wraps all charts as ArgoCD `Application` objects | -| `idp-github` / `idp-gitlab` | External identity providers; plugged into k8shell via `identity.remoteProviders` | +| `idp-github` / `idp-gitlab` / `idp-google` | External identity providers; plugged into k8shell via `identity.remoteProviders` | | `vault-secrets` | Maps HashiCorp Vault secrets to Kubernetes Secrets | | `worktrace-detector` | Threat detection engine; DaemonSet consuming Tetragon events (needs Tetragon installed). Ships no rules: a leader-elected `controller` Deployment reads them from an externally provided ConfigMap (`rules.configMap`), serves them to the detectors and generates the TracingPolicy from them | diff --git a/README.md b/README.md index 9522478..8a2ce93 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![k8shell-bundle chart](https://github.com/k8shell-io/charts/actions/workflows/chart-k8shell-bundle.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-k8shell-bundle.yaml) [![idp-github chart](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-github.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-github.yaml) [![idp-gitlab chart](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-gitlab.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-gitlab.yaml) +[![idp-google chart](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-google.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-idp-google.yaml) [![worktrace-detector chart](https://github.com/k8shell-io/charts/actions/workflows/chart-worktrace-detector.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-worktrace-detector.yaml) [![vault-secrets chart](https://github.com/k8shell-io/charts/actions/workflows/chart-vault-secrets.yaml/badge.svg)](https://github.com/k8shell-io/charts/actions/workflows/chart-vault-secrets.yaml) @@ -17,10 +18,11 @@ Helm charts for [k8shell](https://k8shell.io) — Cloud-native Development Envir | [k8shell-bundle](./k8shell-bundle) | Umbrella chart deploying k8shell together with PostgreSQL, NATS, and Vault-backed secrets. | | [idp-github](./idp-github) | GitHub Identity Provider — authenticates users via GitHub OAuth. | | [idp-gitlab](./idp-gitlab) | GitLab Identity Provider — authenticates users via GitLab OAuth. | +| [idp-google](./idp-google) | Google Identity Provider — authenticates users via Google OAuth (Workspace and optionally personal accounts). | | [vault-secrets](./vault-secrets) | Maps HashiCorp Vault secrets to Kubernetes secrets. | | [worktrace-detector](./worktrace-detector) | Worktrace threat detection engine — runs as a DaemonSet and evaluates Tetragon events against detection rules. | -`k8shell-bundle`, `idp-github`, and `idp-gitlab` are available under the [Early Access Program](https://docs.k8shell.io/licensing#early-access). +`k8shell-bundle`, `idp-github`, `idp-gitlab`, and `idp-google` are available under the [Early Access Program](https://docs.k8shell.io/licensing#early-access). ## Requirements diff --git a/idp-google/Chart.yaml b/idp-google/Chart.yaml new file mode 100644 index 0000000..3710384 --- /dev/null +++ b/idp-google/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v2 +name: idp-google +description: A Helm chart for Google Identity Provider +version: 0.1.0 +appVersion: 0.1.0 diff --git a/idp-google/templates/_helpers.tpl b/idp-google/templates/_helpers.tpl new file mode 100644 index 0000000..2fbf564 --- /dev/null +++ b/idp-google/templates/_helpers.tpl @@ -0,0 +1,64 @@ +{{- define "idp-google.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{- define "idp-google.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{- define "idp-google.labels" -}} +helm.sh/chart: {{ include "idp-google.chart" . }} +{{ include "idp-google.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{- define "idp-google.selectorLabels" -}} +app.kubernetes.io/name: {{ include "idp-google.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Add env variable from secret +*/}} +{{- define "idp-google.secretEnv" -}} +{{- if .enabled }} +- name: {{ .name }} + valueFrom: + secretKeyRef: + {{- if .secretDef.secretName }} + name: {{ .secretDef.secretName }} + key: {{ .secretDef.secretKey }} + {{- else }} + name: int-{{ .defaultSecret }} + key: {{ .name }} + {{- end }} +{{- else }} +- name: {{ .name }} + value: "" +{{- end }} +{{- end }} + +{{/* +Render Secret data entries from a key/value dict +*/}} +{{- define "idp-google.secretData" -}} +{{- range $key, $value := . }} +{{ $key }}: {{ $value | b64enc }} +{{- end }} +{{- end }} + +{{/* +Add imagePullSecrets +*/}} +{{- define "idp-google.imagePullSecrets" -}} +{{- if and .Values.imageRegistry.host .Values.imageRegistry.existingSecret }} +imagePullSecrets: +- name: {{ .Values.imageRegistry.existingSecret }} +{{- else if and .Values.imageRegistry.host .Values.imageRegistry.username .Values.imageRegistry.password }} +imagePullSecrets: +- name: {{ printf "%s-regcred" .Release.Name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} \ No newline at end of file diff --git a/idp-google/templates/cert-idp-google.yaml b/idp-google/templates/cert-idp-google.yaml new file mode 100644 index 0000000..6f94824 --- /dev/null +++ b/idp-google/templates/cert-idp-google.yaml @@ -0,0 +1,22 @@ +{{- if .Values.certManager.enabled }} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: idp-google-cert + labels: + {{- include "idp-google.labels" . | nindent 4 }} +spec: + secretName: idp-google-tls + duration: {{ .Values.certManager.duration }} + renewBefore: {{ .Values.certManager.renewBefore }} + commonName: idp-google.{{ .Release.Namespace }}.svc.cluster.local + dnsNames: + - idp-google + - idp-google.{{ .Release.Namespace }}.svc + - idp-google.{{ .Release.Namespace }}.svc.cluster.local + usages: + - server auth + issuerRef: + name: {{ .Values.certManager.issuer.name }} + kind: {{ .Values.certManager.issuer.kind }} +{{- end }} diff --git a/idp-google/templates/cm-config.yaml b/idp-google/templates/cm-config.yaml new file mode 100644 index 0000000..722f363 --- /dev/null +++ b/idp-google/templates/cm-config.yaml @@ -0,0 +1,60 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: idp-google-config + labels: + app: idp-google +data: + config.yaml: | + grpc: + port: 9031 + + {{- if .Values.certManager.enabled }} + enableTLS: true + certFile: /etc/tls/identity/tls.crt + keyFile: /etc/tls/identity/tls.key + {{- else }} + enableTLS: false + {{- end }} + + # JWT required claims for authentication + authEnabled: {{ .Values.authEnabled }} + audience: identity + allowed: + - serviceAccount: identity + + nats: + enabled: {{ .Values.nats.enabled }} + url: nats://{{ .Values.nats.host }}:{{ .Values.nats.port }} + username: {{ .Values.nats.username }} + password: ${NATS_K8SHELL_PASSWORD} + + db: + enabled: true + database: {{ .Values.postgresql.database }} + hostname: {{ .Values.postgresql.host }} + port: {{ .Values.postgresql.port }} + username: ${POSTGRES_USERNAME} + password: ${POSTGRES_PASSWORD} + + google: + clientId: ${GOOGLE_CLIENT_ID} + clientSecret: ${GOOGLE_CLIENT_SECRET} + + allowedDomains: + {{- toYaml .Values.google.allowedDomains | nindent 8 }} + allowPersonal: {{ .Values.google.allowPersonal }} + {{- with .Values.google.personalEmailDomains }} + personalEmailDomains: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.google.personalAllowedEmails }} + personalAllowedEmails: + {{- toYaml . | nindent 8 }} + {{- end }} + + onboardRules: + {{- toYaml .Values.google.onboardRules | nindent 8 }} + + onboardRuleTemplate: | + {{- .Values.google.onboardRuleTemplate | nindent 8 }} diff --git a/idp-google/templates/dep-idp-google.yaml b/idp-google/templates/dep-idp-google.yaml new file mode 100644 index 0000000..05db9a5 --- /dev/null +++ b/idp-google/templates/dep-idp-google.yaml @@ -0,0 +1,77 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: idp-google + labels: + {{- include "idp-google.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google +spec: + replicas: {{ .Values.replicas }} + selector: + matchLabels: + k8shell.io/app: idp-google + template: + metadata: + labels: + k8shell.io/app: idp-google + {{- include "idp-google.labels" . | nindent 8 }} + spec: + {{- include "idp-google.imagePullSecrets" . | nindent 6 }} + serviceAccountName: idp-google + containers: + - name: idp-google + image: {{ .Values.image.repository }}:{{ .Values.image.tag }} + workingDir: /app + ports: + - containerPort: 9031 + name: grpc + env: + {{- include "idp-google.secretEnv" (dict + "enabled" .Values.nats.enabled + "name" "NATS_K8SHELL_PASSWORD" + "secretDef" .Values.nats.password + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "idp-google.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_USERNAME" + "secretDef" .Values.postgresql.username + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "idp-google.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_PASSWORD" + "secretDef" .Values.postgresql.password + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "idp-google.secretEnv" (dict + "enabled" true + "name" "GOOGLE_CLIENT_ID" + "secretDef" .Values.google.clientId + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "idp-google.secretEnv" (dict + "enabled" true + "name" "GOOGLE_CLIENT_SECRET" + "secretDef" .Values.google.clientSecret + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + volumeMounts: + - name: idp-google-config + mountPath: /app/config + readOnly: true + {{- if .Values.certManager.enabled }} + - name: idp-google-cert + mountPath: /etc/tls/identity + readOnly: true + {{- end }} + + volumes: + - name: idp-google-config + configMap: + name: idp-google-config + {{- if .Values.certManager.enabled }} + - name: idp-google-cert + secret: + secretName: idp-google-tls + {{- end }} diff --git a/idp-google/templates/regcred.yaml b/idp-google/templates/regcred.yaml new file mode 100644 index 0000000..66aa922 --- /dev/null +++ b/idp-google/templates/regcred.yaml @@ -0,0 +1,9 @@ +{{- if and .Values.imageRegistry.host .Values.imageRegistry.username .Values.imageRegistry.password (not .Values.imageRegistry.existingSecret) }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ printf "%s-regcred" .Release.Name | trunc 63 | trimSuffix "-" }} +type: kubernetes.io/dockerconfigjson +data: + .dockerconfigjson: {{ printf "{\"auths\":{\"%s\":{\"username\":\"%s\",\"password\":\"%s\",\"auth\":\"%s\"}}}" .Values.imageRegistry.host .Values.imageRegistry.username .Values.imageRegistry.password (printf "%s:%s" .Values.imageRegistry.username .Values.imageRegistry.password | b64enc) | b64enc | quote }} +{{- end }} \ No newline at end of file diff --git a/idp-google/templates/sa-idp-google.yaml b/idp-google/templates/sa-idp-google.yaml new file mode 100644 index 0000000..7984b38 --- /dev/null +++ b/idp-google/templates/sa-idp-google.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: idp-google + namespace: {{ .Release.Namespace }} + labels: + {{- include "idp-google.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google diff --git a/idp-google/templates/sec-idp-google.yaml b/idp-google/templates/sec-idp-google.yaml new file mode 100644 index 0000000..c3200dc --- /dev/null +++ b/idp-google/templates/sec-idp-google.yaml @@ -0,0 +1,40 @@ +{{- if not .Values.postgresql.enabled -}} +{{- fail "postgresql.enabled must be true: idp-google requires a PostgreSQL database" -}} +{{- end -}} +{{- if and (not .Values.google.clientId.value) (not .Values.google.clientId.secretName) -}} +{{- fail "google.clientId is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- if and (not .Values.google.clientSecret.value) (not .Values.google.clientSecret.secretName) -}} +{{- fail "google.clientSecret is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- $secrets := dict -}} +{{- if .Values.nats.enabled -}} +{{- if .Values.nats.password.value -}} +{{- $_ := set $secrets "NATS_K8SHELL_PASSWORD" .Values.nats.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.postgresql.enabled -}} +{{- if .Values.postgresql.username.value -}} +{{- $_ := set $secrets "POSTGRES_USERNAME" .Values.postgresql.username.value -}} +{{- end -}} +{{- if .Values.postgresql.password.value -}} +{{- $_ := set $secrets "POSTGRES_PASSWORD" .Values.postgresql.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.google.clientId.value -}} +{{- $_ := set $secrets "GOOGLE_CLIENT_ID" .Values.google.clientId.value -}} +{{- end -}} +{{- if .Values.google.clientSecret.value -}} +{{- $_ := set $secrets "GOOGLE_CLIENT_SECRET" .Values.google.clientSecret.value -}} +{{- end -}} +{{- if $secrets }} +apiVersion: v1 +kind: Secret +metadata: + name: int-idp-google + labels: + {{- include "idp-google.labels" . | nindent 4 }} +type: Opaque +data: +{{ include "idp-google.secretData" $secrets | nindent 2 }} +{{- end }} diff --git a/idp-google/templates/svc-idp-google.yaml b/idp-google/templates/svc-idp-google.yaml new file mode 100644 index 0000000..cb9bdad --- /dev/null +++ b/idp-google/templates/svc-idp-google.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Service +metadata: + name: idp-google + labels: + {{- include "idp-google.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google +spec: + type: ClusterIP + {{- if and .Values.grpc .Values.grpc.roundRobin }} + clusterIP: None + {{- end }} + ports: + - port: 9031 + targetPort: grpc + protocol: TCP + name: grpc + selector: + k8shell.io/app: idp-google diff --git a/idp-google/values-internal.yaml b/idp-google/values-internal.yaml new file mode 100644 index 0000000..1295563 --- /dev/null +++ b/idp-google/values-internal.yaml @@ -0,0 +1,8 @@ +# values-internal.yaml +# +# Overrides image repository to use the internal registry (registry.k8shell.io) +# instead of the default public registry (ghcr.io). +# Use with: helm install ... -f values.yaml -f values-internal.yaml + +image: + repository: registry.k8shell.io/k8shell-idp/idp-google diff --git a/idp-google/values.yaml b/idp-google/values.yaml new file mode 100644 index 0000000..8e1ead9 --- /dev/null +++ b/idp-google/values.yaml @@ -0,0 +1,99 @@ +# values.yaml for idp-google Helm chart +# +# NOTE on usernames/passwords: +# usernames and passwords are provided as env variables in Pods. +# When a field has a value of {}, there are two options: +# +# 1. field.value: the actual value will be used to create a Kubernetes secret with key equal +# to the env variable name. See templates/sec-idp-google.yaml for how the secret is created +# and dep-idp-google.yaml for how it is consumed via the idp-google.secretEnv helper. +# +# 2. field.secretName and field.secretKey: uses an existing Kubernetes secret. + +replicas: 1 + +image: + repository: ghcr.io/k8shell-io/idp-google + tag: pr-1-4952aba + +# imageRegistry defines a private container registry used to create an image pull secret (regcred). +imageRegistry: + host: "" + existingSecret: "" + username: "" + password: "" + +authEnabled: true + +certManager: + enabled: false + issuer: + name: vault-root-issuer + kind: ClusterIssuer + duration: 24h + renewBefore: 12h + +grpc: + roundRobin: true + +nats: + enabled: true + host: nats + port: 4222 + username: "k8shell-service" + password: {} + +postgresql: + enabled: true + host: "postgresql" + port: 5432 + database: "" + username: {} + password: {} + +google: + # OAuth 2.0 "Web application" client from Google Cloud Console (APIs & Services > + # Credentials). Its authorized redirect URIs must include the URI the identity + # client passes to OnboardUserWebFlow. + clientId: {} + clientSecret: {} + + # --- Who may sign in (hard gate, evaluated before the template below) --------- + # Google Workspace domains ("hd" claim) that may sign in. "*" admits any Workspace. + allowedDomains: + - example.com + + # Personal Google accounts (no "hd" claim, e.g. @gmail.com). Off by default. + allowPersonal: false + # Email domains accepted for personal accounts (default: gmail.com, googlemail.com). + personalEmailDomains: [] + # Narrow personal sign-in to exactly these addresses (empty = any personal account). + personalAllowedEmails: [] + + # --- What an admitted user gets ------------------------------------------------- + # Fixed rules per username (the username the template produces), taking priority + # over the template. They never bypass the gate above. + onboardRules: [] + # - username: "tomas.vitvar" + # sudo: true + # roles: ["admin"] + # action: "allow" + + # onboardRuleTemplate is the fallback rule applied to admitted users. + # Stored as a raw string to preserve !cel tags (Helm's YAML parser strips custom tags). + # + # CEL scope: `claims` (sub, email, email_verified, hd, name, given_name, family_name, + # picture, locale), `personal` (bool: no "hd"), `uid` (uint, derived from sub) and + # the lowercased email split into `emailLocal` (tomas.vitvar), `emailDomain` + # (example.com) and `emailProvider` (first domain label: example). The CEL + # environment has no split()/substring(), hence these helpers. + # Workspace users get their email local part (tomas.vitvar@example.com -> + # tomas.vitvar); personal users should be suffixed with the mail provider + # (tomas@gmail.com -> tomas-gmail) so they cannot collide with Workspace users. + onboardRuleTemplate: | + username: !cel "emailLocal" + fullname: !cel "claims.name" + email: !cel "claims.email" + uid: !cel "uid" + gid: !cel "uid" + action: allow diff --git a/k8shell-bundle/Chart.yaml b/k8shell-bundle/Chart.yaml index 0171d5c..6c630a0 100644 --- a/k8shell-bundle/Chart.yaml +++ b/k8shell-bundle/Chart.yaml @@ -2,4 +2,4 @@ apiVersion: v2 name: k8shell-bundle description: k8shell app with postgres, NATS and secrets from vault appVersion: 26.11.1 -version: 0.7.4 +version: 0.7.5 diff --git a/k8shell-bundle/templates/app-idp-google.yaml b/k8shell-bundle/templates/app-idp-google.yaml new file mode 100644 index 0000000..d3fa6ac --- /dev/null +++ b/k8shell-bundle/templates/app-idp-google.yaml @@ -0,0 +1,46 @@ +{{- if .Values.idpGoogle.enabled }} +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: idp-google + namespace: {{ .Values.targetNamespace }} + finalizers: + - resources-finalizer.argocd.argoproj.io +spec: + project: 'default' + source: + chart: "{{ .Values.charts.idpGoogle.chartName }}" + repoURL: {{ .Values.charts.idpGoogle.repoURL }} + targetRevision: "{{ .Values.charts.idpGoogle.chartVersion }}" + helm: + valuesObject: + imageRegistry: + {{- toYaml .Values.k8shell.imageRegistry | nindent 10 }} + + certManager: + {{- toYaml .Values.k8shell.certManager | nindent 10 }} + + grpc: + {{- toYaml .Values.k8shell.grpc | nindent 10 }} + + nats: + {{- merge .Values.idpGoogle.nats (dict "enabled" .Values.k8shell.nats.enabled "host" .Values.k8shell.nats.host "port" .Values.k8shell.nats.port) | toYaml | nindent 10 }} + + postgresql: + {{- toYaml .Values.k8shell.postgresql | nindent 10 }} + + authEnabled: {{ .Values.k8shell.authEnabled }} + + {{- with .Values.idpGoogle }} + replicas: {{ .replicas }} + image: + {{- toYaml .image | nindent 10 }} + google: + {{- toYaml .google | nindent 10 }} + {{- end }} + + destination: + server: https://kubernetes.default.svc + namespace: {{ .Values.targetNamespace }} + {{- include "k8shell-bundle.syncPolicy" (dict "root" .) | nindent 2 }} +{{- end }} diff --git a/k8shell-bundle/templates/app-k8shell.yaml b/k8shell-bundle/templates/app-k8shell.yaml index 7c9e05d..afde8db 100644 --- a/k8shell-bundle/templates/app-k8shell.yaml +++ b/k8shell-bundle/templates/app-k8shell.yaml @@ -31,6 +31,10 @@ spec: {{- $idpProvider := dict "address" (printf "%sidp-gitlab:9030" $addressPrefix) "serverName" "idp-gitlab" }} {{- $existing = append $existing $idpProvider }} {{- end }} + {{- if .Values.idpGoogle.enabled }} + {{- $idpProvider := dict "address" (printf "%sidp-google:9031" $addressPrefix) "serverName" "idp-google" }} + {{- $existing = append $existing $idpProvider }} + {{- end }} {{- $_ := set $k8shell.identity "remoteProviders" $existing }} {{- $cmaps := default list $k8shell.provisioner.blueprintFilesConfigMaps }} {{- if or .Values.idpGithub.enabled .Values.idpGitlab.enabled }} diff --git a/k8shell-bundle/templates/app-secrets.yaml b/k8shell-bundle/templates/app-secrets.yaml index 318b4d5..dafa62d 100644 --- a/k8shell-bundle/templates/app-secrets.yaml +++ b/k8shell-bundle/templates/app-secrets.yaml @@ -31,6 +31,10 @@ spec: - name: vault-gitlab path: "{{ .Values.vault.pathPrefix }}/gitlab" {{- end }} + {{- if .Values.idpGoogle.enabled }} + - name: vault-google + path: "{{ .Values.vault.pathPrefix }}/google" + {{- end }} {{- if .Values.k8shell.sshShield.enabled }} - name: vault-nfgate path: "{{ .Values.vault.pathPrefix }}/nfgate" diff --git a/k8shell-bundle/values-internal.yaml b/k8shell-bundle/values-internal.yaml index cb8d2ec..5f924d9 100644 --- a/k8shell-bundle/values-internal.yaml +++ b/k8shell-bundle/values-internal.yaml @@ -14,6 +14,10 @@ charts: repoURL: registry.k8shell.io chartName: "charts/idp-github" + idpGoogle: + repoURL: registry.k8shell.io + chartName: "charts/idp-google" + idpGitlab: repoURL: registry.k8shell.io chartName: "charts/idp-gitlab" @@ -77,3 +81,10 @@ idpGitlab: existingSecret: regcred image: repository: registry.k8shell.io/k8shell-idp/idp-gitlab + +idpGoogle: + imageRegistry: + host: registry.k8shell.io + existingSecret: regcred + image: + repository: registry.k8shell.io/k8shell-idp/idp-google diff --git a/k8shell-bundle/values.yaml b/k8shell-bundle/values.yaml index 0c9c09c..3455f45 100644 --- a/k8shell-bundle/values.yaml +++ b/k8shell-bundle/values.yaml @@ -21,6 +21,11 @@ charts: chartName: "charts/idp-gitlab" chartVersion: 0.1.8 # not updated in this release, should be disabled (will not work) + idpGoogle: + repoURL: ghcr.io/k8shell-io + chartName: "charts/idp-google" + chartVersion: 0.1.0 + nats: repoURL: https://nats-io.github.io/k8s/helm/charts/ chartName: nats @@ -87,7 +92,7 @@ k8shell: secretName: "vault-jwt" secretKey: "SIGNING_METHOD" - # Static remote providers. idp-github is injected automatically when idpGithub.enabled=true. + # Static remote providers. idp-github / idp-google are injected automatically when idpGithub.enabled / idpGoogle.enabled=true. remoteProviders: [] smtp: @@ -335,6 +340,38 @@ idpGithub: # username: !cel "user.login" # ... +#### idp-google app +idpGoogle: + enabled: false + replicas: 1 + image: {} + + nats: + enabled: true + host: "nats" + port: 4222 + username: "k8shell-service" + password: + secretName: "vault-nats" + secretKey: "NATS_K8SHELL_PASSWORD" + + google: + clientId: + secretName: "vault-google" + secretKey: "GOOGLE_CLIENT_ID" + clientSecret: + secretName: "vault-google" + secretKey: "GOOGLE_CLIENT_SECRET" + # Google Workspace domains ("hd" claim) that may sign in. "*" admits any Workspace. + allowedDomains: [] + allowPersonal: false + personalEmailDomains: [] + personalAllowedEmails: [] + onboardRules: [] + # onboardRuleTemplate: | + # username: !cel "emailLocal" + # ... + idpGitlab: enabled: true replicas: 1 From 0ba6643714c758c36f017acb78fcd88e529fa83e Mon Sep 17 00:00:00 2001 From: bruckins Date: Wed, 4 Nov 2026 16:54:56 +0100 Subject: [PATCH 02/17] dummy --- k8shell-bundle/values.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8shell-bundle/values.yaml b/k8shell-bundle/values.yaml index 3455f45..dc058fc 100644 --- a/k8shell-bundle/values.yaml +++ b/k8shell-bundle/values.yaml @@ -25,7 +25,7 @@ charts: repoURL: ghcr.io/k8shell-io chartName: "charts/idp-google" chartVersion: 0.1.0 - + nats: repoURL: https://nats-io.github.io/k8s/helm/charts/ chartName: nats From b492e984154d299fe80667bb426e279d71d81192 Mon Sep 17 00:00:00 2001 From: bruckins Date: Wed, 4 Nov 2026 20:46:59 +0100 Subject: [PATCH 03/17] temp fix --- idp-google/values.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/idp-google/values.yaml b/idp-google/values.yaml index 8e1ead9..46f14ed 100644 --- a/idp-google/values.yaml +++ b/idp-google/values.yaml @@ -96,4 +96,3 @@ google: email: !cel "claims.email" uid: !cel "uid" gid: !cel "uid" - action: allow From 76cb4f269ab5ad0c649f7b67a8c8cca9d6313bd4 Mon Sep 17 00:00:00 2001 From: bruckins Date: Wed, 4 Nov 2026 20:48:14 +0100 Subject: [PATCH 04/17] temp fix --- idp-google/Chart.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/idp-google/Chart.yaml b/idp-google/Chart.yaml index 3710384..ef917e5 100644 --- a/idp-google/Chart.yaml +++ b/idp-google/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 name: idp-google description: A Helm chart for Google Identity Provider -version: 0.1.0 +version: 0.1.1 appVersion: 0.1.0 From 990a540dc16221d9f239d471d07a1c4787c9ddbb Mon Sep 17 00:00:00 2001 From: bruckins Date: Wed, 4 Nov 2026 20:49:05 +0100 Subject: [PATCH 05/17] idp google bump --- k8shell-bundle/Chart.yaml | 2 +- k8shell-bundle/values.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/k8shell-bundle/Chart.yaml b/k8shell-bundle/Chart.yaml index 6c630a0..7efb85e 100644 --- a/k8shell-bundle/Chart.yaml +++ b/k8shell-bundle/Chart.yaml @@ -2,4 +2,4 @@ apiVersion: v2 name: k8shell-bundle description: k8shell app with postgres, NATS and secrets from vault appVersion: 26.11.1 -version: 0.7.5 +version: 0.7.6 diff --git a/k8shell-bundle/values.yaml b/k8shell-bundle/values.yaml index dc058fc..7f0eb9e 100644 --- a/k8shell-bundle/values.yaml +++ b/k8shell-bundle/values.yaml @@ -24,7 +24,7 @@ charts: idpGoogle: repoURL: ghcr.io/k8shell-io chartName: "charts/idp-google" - chartVersion: 0.1.0 + chartVersion: 0.1.1 nats: repoURL: https://nats-io.github.io/k8s/helm/charts/ From 886744b22015714dbe2f15cc9194333df7490f16 Mon Sep 17 00:00:00 2001 From: bruckins Date: Sun, 8 Nov 2026 19:06:02 +0100 Subject: [PATCH 06/17] k8shell-bundle: make the Vault objects optional (vault.enabled) vault.enabled was not used: the k8shell-secrets app, the vault-sa service account and the CNPG superuser VaultStaticSecret were always rendered, so the bundle could not be synced without the Vault Secrets Operator. With vault.enabled false they are left out and the Secrets they would create (listed in values.yaml) must exist under the same names and keys, e.g. created from sops by Ansible. With the default (true) the rendered output is unchanged. Co-Authored-By: Claude Opus 5.5 --- k8shell-bundle/templates/app-secrets.yaml | 2 ++ k8shell-bundle/templates/cnpg-postgresql.yaml | 4 ++++ k8shell-bundle/templates/vault-sa.yaml | 4 +++- k8shell-bundle/values.yaml | 16 ++++++++++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/k8shell-bundle/templates/app-secrets.yaml b/k8shell-bundle/templates/app-secrets.yaml index dafa62d..934956d 100644 --- a/k8shell-bundle/templates/app-secrets.yaml +++ b/k8shell-bundle/templates/app-secrets.yaml @@ -1,3 +1,4 @@ +{{- if .Values.vault.enabled }} apiVersion: argoproj.io/v1alpha1 kind: Application metadata: @@ -56,3 +57,4 @@ spec: server: https://kubernetes.default.svc namespace: {{ .Values.targetNamespace }} {{- include "k8shell-bundle.syncPolicy" (dict "root" .) | nindent 2 }} +{{- end }} diff --git a/k8shell-bundle/templates/cnpg-postgresql.yaml b/k8shell-bundle/templates/cnpg-postgresql.yaml index 3d3b5e4..0d4f871 100644 --- a/k8shell-bundle/templates/cnpg-postgresql.yaml +++ b/k8shell-bundle/templates/cnpg-postgresql.yaml @@ -1,5 +1,8 @@ {{- if eq (include "k8shell-bundle.postgresqlMode" .) "cnpg" }} {{- $cnpg := .Values.postgresql.cnpg }} +{{- /* without Vault the secret db-postgresql-superuser must exist (username + postgres, password = POSTGRES_PASSWORD of vault-db), see values.yaml */}} +{{- if .Values.vault.enabled }} {{- $pathParts := regexSplit "/" (printf "%s/db" .Values.vault.pathPrefix) -1 }} # CloudNativePG requires a kubernetes.io/basic-auth secret for the superuser; # vault-db has POSTGRES_USERNAME/POSTGRES_PASSWORD keys, so remap them here. @@ -28,6 +31,7 @@ spec: password: text: {{ `{{ get .Secrets "POSTGRES_PASSWORD" }}` | quote }} --- +{{- end }} apiVersion: postgresql.cnpg.io/v1 kind: Cluster metadata: diff --git a/k8shell-bundle/templates/vault-sa.yaml b/k8shell-bundle/templates/vault-sa.yaml index 51908bc..894e816 100644 --- a/k8shell-bundle/templates/vault-sa.yaml +++ b/k8shell-bundle/templates/vault-sa.yaml @@ -1,5 +1,7 @@ +{{- if .Values.vault.enabled }} apiVersion: v1 kind: ServiceAccount metadata: name: vault-sa - namespace: {{ .Values.targetNamespace }} \ No newline at end of file + namespace: {{ .Values.targetNamespace }} +{{- end }} diff --git a/k8shell-bundle/values.yaml b/k8shell-bundle/values.yaml index 7f0eb9e..7fd2eea 100644 --- a/k8shell-bundle/values.yaml +++ b/k8shell-bundle/values.yaml @@ -42,6 +42,22 @@ charts: chartVersion: "18.2.3" #### Vault +# enabled: the k8shell-secrets app (vault-secrets chart), the vault-sa service +# account and, with postgresql.mode cnpg, a VaultStaticSecret for the superuser +# sync the secrets below from Vault (needs the Vault Secrets Operator). +# disabled: create these Kubernetes Secrets by other means (e.g. sops + Ansible), +# with the same names and keys: +# vault-ssh SERVER_KEY +# vault-jwt PRIVATE_KEY, SIGNING_METHOD +# vault-db POSTGRES_USERNAME, POSTGRES_PASSWORD +# vault-nats NATS_K8SHELL_PASSWORD +# vault-private-registry ADDRESS, USERNAME, PASSWORD +# vault-smtp SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_FROM +# regcred kubernetes.io/dockerconfigjson for the registry +# vault-github K8SHELL_CLIENT_ID, K8SHELL_CLIENT_SECRET (idpGithub.enabled) +# vault-gitlab (idpGitlab.enabled) +# vault-nfgate NFGATE_AUTH_KEY (k8shell.sshShield.enabled) +# db-postgresql-superuser kubernetes.io/basic-auth, username postgres (postgresql.mode cnpg) vault: enabled: true address: "" From 42ae6fcb570e56b2d15d2f08eb7ff5c1dd4976ae Mon Sep 17 00:00:00 2001 From: bruckins Date: Sun, 8 Nov 2026 19:07:09 +0100 Subject: [PATCH 07/17] k8shell-bundle 0.7.7: vault.enabled false works without Vault Co-Authored-By: Claude Opus 5.5 --- k8shell-bundle/Chart.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8shell-bundle/Chart.yaml b/k8shell-bundle/Chart.yaml index 7efb85e..2a442d2 100644 --- a/k8shell-bundle/Chart.yaml +++ b/k8shell-bundle/Chart.yaml @@ -2,4 +2,4 @@ apiVersion: v2 name: k8shell-bundle description: k8shell app with postgres, NATS and secrets from vault appVersion: 26.11.1 -version: 0.7.6 +version: 0.7.7 From 4a1ccf93e0d44a446b77aa9814e284b4559cb40b Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 13:10:07 +0100 Subject: [PATCH 08/17] k8shell 2.0.0: the whole platform in one chart The k8shell chart now installs everything k8shell-bundle deployed as ArgoCD Applications, with plain Helm and without ArgoCD (k8shell-bundle stays at 0.7.x for existing installs): - PostgreSQL: postgresql.mode simple (single instance, the default), cnpg (CloudNativePG Cluster) or external; the Service db-postgresql in both installed modes, the data volume is kept on uninstall - NATS: the official chart as the subchart natsServer (nats.install), a 3-node JetStream cluster (the services create KV buckets with 3 replicas); checked to read the same password Secret as the services - idp-github and idp-google as part of the chart (idpGithub, idpGoogle), on the shared settings, added to identity.remoteProviders automatically; git-blueprints and the git-dev default blueprint with idpGithub - default authz policies (ConfigMap authz-policies-default, without any site-specific settings: permissions follow from roles), replaced as a whole by authz.policiesConfigMap; policy tests in policy-tests/ - default blueprints replaced by provisioner.blueprintsConfigMap, extended by blueprintFilesConfigMaps - k8shell-infra-versions for api-server - every service restarts when its configuration changes Defaults that make a plain install work: authz, api-server, session and frontend enabled, frontend navigation "full", session detach allowed (web terminal), the users of identity.users get an onboarding rule (default admin: roles admin and developer), SMTP block only with SMTP enabled, session reads the database credentials of identity. values-internal.yaml uses the identity and frontend images of PRs k8shell-io/identity#46 and k8shell-io/frontend#89 until they are released. quickstart.sh: database and NATS passwords kept across upgrades, roles for the admin user, --chart, --values and --yes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/chart-k8shell.yaml | 2 + CLAUDE.md | 19 +- README.md | 4 +- bin/quickstart.sh | 51 ++- k8shell/.gitignore | 1 + k8shell/.helmignore | 7 + k8shell/Chart.lock | 6 + k8shell/Chart.yaml | 12 +- k8shell/files/git-blueprints/git-dev.yaml | 31 ++ k8shell/files/policies/announcement.rego | 36 ++ k8shell/files/policies/audit.rego | 29 ++ k8shell/files/policies/blueprint.rego | 47 ++ k8shell/files/policies/common.rego | 78 ++++ k8shell/files/policies/git.rego | 21 + k8shell/files/policies/onboardrule.rego | 20 + k8shell/files/policies/org.rego | 47 ++ k8shell/files/policies/role.rego | 47 ++ k8shell/files/policies/session_list.rego | 69 +++ k8shell/files/policies/session_record.rego | 78 ++++ k8shell/files/policies/session_recording.rego | 87 ++++ .../policies/session_recording_override.rego | 45 ++ k8shell/files/policies/ssh.rego | 26 ++ k8shell/files/policies/threat_detect.rego | 275 ++++++++++++ .../policies/threat_detection_override.rego | 36 ++ k8shell/files/policies/threat_list.rego | 24 ++ k8shell/files/policies/user.rego | 27 ++ k8shell/files/policies/user_access.rego | 187 ++++++++ k8shell/files/policies/user_auth.rego | 43 ++ k8shell/files/policies/user_create.rego | 17 + k8shell/files/policies/user_delete.rego | 34 ++ k8shell/files/policies/user_exists.rego | 35 ++ k8shell/files/policies/user_token.rego | 28 ++ k8shell/files/policies/workspace_access.rego | 174 ++++++++ k8shell/files/policies/workspace_list.rego | 69 +++ k8shell/policy-tests/git_test.rego | 85 ++++ k8shell/policy-tests/org_test.rego | 22 + k8shell/policy-tests/run.sh | 20 + .../session_recording_override_test.rego | 79 ++++ .../policy-tests/session_recording_test.rego | 93 ++++ k8shell/policy-tests/session_test.rego | 201 +++++++++ k8shell/policy-tests/threat_test.rego | 401 ++++++++++++++++++ k8shell/templates/_helpers.tpl | 87 ++++ .../templates/api-server/dep-api-server.yaml | 9 +- .../templates/authz/cm-authz-policies.yaml | 15 + k8shell/templates/authz/dep-authz.yaml | 11 +- k8shell/templates/cm-infra-versions.yaml | 25 ++ k8shell/templates/identity/cm-identity.yaml | 29 +- k8shell/templates/identity/dep-identity.yaml | 3 + .../templates/idp-github/cert-idp-github.yaml | 24 ++ .../idp-github/cm-idp-github-config.yaml | 51 +++ .../idp-github/cm-idp-github-files.yaml | 11 + .../templates/idp-github/dep-idp-github.yaml | 88 ++++ .../templates/idp-github/sa-idp-github.yaml | 10 + .../templates/idp-github/sec-idp-github.yaml | 42 ++ .../templates/idp-github/svc-idp-github.yaml | 21 + .../templates/idp-google/cert-idp-google.yaml | 24 ++ .../idp-google/cm-idp-google-config.yaml | 62 +++ .../templates/idp-google/dep-idp-google.yaml | 82 ++++ .../templates/idp-google/sa-idp-google.yaml | 10 + .../templates/idp-google/sec-idp-google.yaml | 42 ++ .../templates/idp-google/svc-idp-google.yaml | 21 + .../templates/postgresql/cnpg-postgresql.yaml | 57 +++ .../templates/postgresql/pvc-postgresql.yaml | 26 ++ .../templates/postgresql/sts-postgresql.yaml | 98 +++++ .../templates/postgresql/svc-postgresql.yaml | 47 ++ .../templates/provisioner/cm-blueprints.yaml | 2 + .../provisioner/cm-git-blueprints.yaml | 14 + .../templates/provisioner/cm-provisioner.yaml | 2 +- .../provisioner/dep-provisioner.yaml | 12 +- k8shell/templates/session/dep-session.yaml | 7 +- .../templates/ssh-proxy/dep-ssh-proxy.yaml | 3 + .../templates/ssh-shield/dep-ssh-shield.yaml | 3 + k8shell/templates/validate.yaml | 20 + k8shell/values-internal.yaml | 18 + k8shell/values.schema.json | 237 ++++++++++- k8shell/values.yaml | 299 +++++++++++-- 76 files changed, 4057 insertions(+), 68 deletions(-) create mode 100644 k8shell/.gitignore create mode 100644 k8shell/.helmignore create mode 100644 k8shell/Chart.lock create mode 100644 k8shell/files/git-blueprints/git-dev.yaml create mode 100644 k8shell/files/policies/announcement.rego create mode 100644 k8shell/files/policies/audit.rego create mode 100644 k8shell/files/policies/blueprint.rego create mode 100644 k8shell/files/policies/common.rego create mode 100644 k8shell/files/policies/git.rego create mode 100644 k8shell/files/policies/onboardrule.rego create mode 100644 k8shell/files/policies/org.rego create mode 100644 k8shell/files/policies/role.rego create mode 100644 k8shell/files/policies/session_list.rego create mode 100644 k8shell/files/policies/session_record.rego create mode 100644 k8shell/files/policies/session_recording.rego create mode 100644 k8shell/files/policies/session_recording_override.rego create mode 100644 k8shell/files/policies/ssh.rego create mode 100644 k8shell/files/policies/threat_detect.rego create mode 100644 k8shell/files/policies/threat_detection_override.rego create mode 100644 k8shell/files/policies/threat_list.rego create mode 100644 k8shell/files/policies/user.rego create mode 100644 k8shell/files/policies/user_access.rego create mode 100644 k8shell/files/policies/user_auth.rego create mode 100644 k8shell/files/policies/user_create.rego create mode 100644 k8shell/files/policies/user_delete.rego create mode 100644 k8shell/files/policies/user_exists.rego create mode 100644 k8shell/files/policies/user_token.rego create mode 100644 k8shell/files/policies/workspace_access.rego create mode 100644 k8shell/files/policies/workspace_list.rego create mode 100644 k8shell/policy-tests/git_test.rego create mode 100644 k8shell/policy-tests/org_test.rego create mode 100755 k8shell/policy-tests/run.sh create mode 100644 k8shell/policy-tests/session_recording_override_test.rego create mode 100644 k8shell/policy-tests/session_recording_test.rego create mode 100644 k8shell/policy-tests/session_test.rego create mode 100644 k8shell/policy-tests/threat_test.rego create mode 100644 k8shell/templates/authz/cm-authz-policies.yaml create mode 100644 k8shell/templates/cm-infra-versions.yaml create mode 100644 k8shell/templates/idp-github/cert-idp-github.yaml create mode 100644 k8shell/templates/idp-github/cm-idp-github-config.yaml create mode 100644 k8shell/templates/idp-github/cm-idp-github-files.yaml create mode 100644 k8shell/templates/idp-github/dep-idp-github.yaml create mode 100644 k8shell/templates/idp-github/sa-idp-github.yaml create mode 100644 k8shell/templates/idp-github/sec-idp-github.yaml create mode 100644 k8shell/templates/idp-github/svc-idp-github.yaml create mode 100644 k8shell/templates/idp-google/cert-idp-google.yaml create mode 100644 k8shell/templates/idp-google/cm-idp-google-config.yaml create mode 100644 k8shell/templates/idp-google/dep-idp-google.yaml create mode 100644 k8shell/templates/idp-google/sa-idp-google.yaml create mode 100644 k8shell/templates/idp-google/sec-idp-google.yaml create mode 100644 k8shell/templates/idp-google/svc-idp-google.yaml create mode 100644 k8shell/templates/postgresql/cnpg-postgresql.yaml create mode 100644 k8shell/templates/postgresql/pvc-postgresql.yaml create mode 100644 k8shell/templates/postgresql/sts-postgresql.yaml create mode 100644 k8shell/templates/postgresql/svc-postgresql.yaml create mode 100644 k8shell/templates/provisioner/cm-git-blueprints.yaml create mode 100644 k8shell/templates/validate.yaml diff --git a/.github/workflows/chart-k8shell.yaml b/.github/workflows/chart-k8shell.yaml index 9a22e75..87c8151 100644 --- a/.github/workflows/chart-k8shell.yaml +++ b/.github/workflows/chart-k8shell.yaml @@ -50,6 +50,8 @@ jobs: - name: Package helm chart run: | mkdir -p dist + # the NATS subchart (Chart.lock) + helm dependency build k8shell helm package k8shell -d dist/ --version "${{ steps.ver.outputs.chart_version }}" - name: Push helm chart diff --git a/CLAUDE.md b/CLAUDE.md index c14f222..6f909f7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,9 +30,9 @@ Each top-level directory is an independent Helm chart published to `oci://ghcr.i | Chart | Role | |-------|------| -| `k8shell` | Core platform — the primary chart users install | -| `k8shell-bundle` | Umbrella chart; wraps all charts as ArgoCD `Application` objects | -| `idp-github` / `idp-gitlab` / `idp-google` | External identity providers; plugged into k8shell via `identity.remoteProviders` | +| `k8shell` | The whole platform in one chart (2.x): services, PostgreSQL, NATS (subchart), idp-github/idp-google, default policies and blueprints | +| `k8shell-bundle` | Umbrella chart for k8shell 1.x; wraps all charts as ArgoCD `Application` objects. Frozen at 0.7.x, replaced by k8shell 2.x | +| `idp-github` / `idp-gitlab` / `idp-google` | Identity providers as separate charts (used by k8shell-bundle); idp-github and idp-google are also part of the k8shell chart since 2.0 | | `vault-secrets` | Maps HashiCorp Vault secrets to Kubernetes Secrets | | `worktrace-detector` | Threat detection engine; DaemonSet consuming Tetragon events (needs Tetragon installed). Ships no rules: a leader-elected `controller` Deployment reads them from an externally provided ConfigMap (`rules.configMap`), serves them to the detectors and generates the TracingPolicy from them | @@ -42,11 +42,16 @@ The k8shell chart deploys two tiers of services: **Core (always enabled):** `ssh-proxy`, `identity`, `provisioner`, `authz` -**Extended (disabled by default, enabled in k8shell-bundle):** `api-server`, `session`, `frontend` +**Extended (enabled by default since 2.0):** `api-server`, `session`, `frontend`, `authz` **Optional (disabled by default, opt-in even in k8shell-bundle):** `sshShield` -**External dependencies (disabled by default):** `postgresql`, `nats` — toggled via `postgresql.enabled` / `nats.enabled`. +**Infrastructure (installed by default since 2.0):** +- `postgresql` — `postgresql.mode`: `simple` (a single-instance StatefulSet `db-postgresql`, official postgres image, PVC kept on uninstall), `cnpg` (a CloudNativePG `Cluster` `db-postgresql`, operator required) or `external`. The Service `db-postgresql` points at the primary in both installed modes. +- `nats` — `nats.install` adds the official NATS chart as the subchart `natsServer` (values under `natsServer`, `fullnameOverride: nats`). `nats.enabled` still means "the services use NATS"; `templates/validate.yaml` checks that the NATS server reads the same password Secret as the services. +- `k8shell-infra-versions` ConfigMap (versions of the installed PostgreSQL/NATS for api-server) is created automatically. + +**Identity providers (disabled by default):** `idpGithub`, `idpGoogle` — templates in `templates/idp-github/`, `templates/idp-google/`, using the chart's shared settings (certManager, grpc, authEnabled, imageRegistry, nats, postgresql). Enabled providers are appended to `identity.remoteProviders`; idpGithub also adds the `git-blueprints` ConfigMap (`files/git-blueprints/`) and makes `git-dev` the default custom blueprint. Service-to-service communication is gRPC. When `certManager.enabled: true`, every service gets a cert-manager-issued TLS certificate and the chart wires mTLS automatically. Without cert-manager, services fall back to plaintext. @@ -54,7 +59,7 @@ JWT auth (`authEnabled: true`) is enforced across all gRPC endpoints. The `ident ### authz service -`authz` (disabled by default, `authz.enabled: false`) is an OPA-based authorization sidecar on gRPC port 9011. It accepts requests from `ssh-proxy`, `provisioner`, `api-server`, and `identity`. Policies are either mounted from a ConfigMap (`authz.policiesConfigMap`) or fall back to the inline `authz.defaultPolicy` Rego rule. It shares the JWT private key with `identity`. +`authz` (disabled by default, `authz.enabled: false`) is an OPA-based authorization sidecar on gRPC port 9011. It accepts requests from `ssh-proxy`, `provisioner`, `api-server`, and `identity`. The chart ships default policies (`files/policies/*.rego`, ConfigMap `authz-policies-default`); they hold no site-specific settings, permissions follow from roles (`admin`, `org-admin`, `-admin`, `developer` for inject mode, `git-workspace` for repositories). `authz.policiesConfigMap` replaces the whole set with an external ConfigMap. `authz.defaultPolicy` is the inline rule used when no policy file matches. Policy tests: `k8shell/policy-tests/run.sh` (needs opa, jq). It shares the JWT private key with `identity`. ### sshShield service @@ -62,7 +67,7 @@ JWT auth (`authEnabled: true`) is enforced across all gRPC endpoints. The `ident ### Blueprints -`provisioner` mounts workspace blueprint YAML from `k8shell/files/blueprints/` (`base.yaml` always; `samples.yaml` when `provisioner.includeBlueprintSamples: true`). Extra blueprints can be injected via `provisioner.blueprintFilesConfigMaps`. When an IDP chart is enabled in k8shell-bundle, a `git-blueprints` ConfigMap is automatically appended to that list. +`provisioner` mounts workspace blueprint YAML from `k8shell/files/blueprints/` (`base.yaml` always; `samples.yaml` when `provisioner.includeBlueprintSamples: true`) as the ConfigMap `blueprint-base-files`; `provisioner.blueprintsConfigMap` replaces it with an external ConfigMap. Extra blueprints are added via `provisioner.blueprintFilesConfigMaps` (file names unique across ConfigMaps, blueprint names unique across files). With idpGithub enabled, `git-blueprints` is appended automatically. ## k8shell-bundle Architecture diff --git a/README.md b/README.md index 8a2ce93..263a3d7 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,8 @@ Helm charts for [k8shell](https://k8shell.io) — Cloud-native Development Envir | Chart | Description | |-------|-------------| -| [k8shell](./k8shell) | Core k8shell platform — open-source components (ssh-proxy, identity, provisioner) plus extended services (api-server, authz, session, frontend, sshShield). | -| [k8shell-bundle](./k8shell-bundle) | Umbrella chart deploying k8shell together with PostgreSQL, NATS, and Vault-backed secrets. | +| [k8shell](./k8shell) | The k8shell platform in one chart (2.x): the services (ssh-proxy, identity, provisioner, authz, api-server, session, frontend, sshShield), PostgreSQL (single instance, CloudNativePG cluster or external), NATS, the GitHub and Google identity providers, default authz policies and blueprints. | +| [k8shell-bundle](./k8shell-bundle) | Umbrella chart deploying k8shell 1.x together with PostgreSQL, NATS, and Vault-backed secrets as ArgoCD Applications. Frozen at 0.7.x, replaced by k8shell 2.x. | | [idp-github](./idp-github) | GitHub Identity Provider — authenticates users via GitHub OAuth. | | [idp-gitlab](./idp-gitlab) | GitLab Identity Provider — authenticates users via GitLab OAuth. | | [idp-google](./idp-google) | Google Identity Provider — authenticates users via Google OAuth (Workspace and optionally personal accounts). | diff --git a/bin/quickstart.sh b/bin/quickstart.sh index 053e191..f7e2c0b 100755 --- a/bin/quickstart.sh +++ b/bin/quickstart.sh @@ -21,9 +21,12 @@ set -euo pipefail SCRIPT_VERSION="1.0.0" CHART_VERSION="" +CHART_REF="oci://ghcr.io/k8shell-io/charts/k8shell" +VALUES_FILES=() +ASSUME_YES="false" NAMESPACE="k8shell-system" TARGET_NAMESPACE="k8shell-workspaces" -QUICKSTART_DIR="$HOME/k8shell-quickstart" +QUICKSTART_DIR="${K8SHELL_QUICKSTART_DIR:-$HOME/k8shell-quickstart}" GENERATED_SSH_KEY="$QUICKSTART_DIR/admin-ssh-key" NODE_PORT_ENABLED="true" NODE_PORT="30022" @@ -41,6 +44,11 @@ License : AGPL-3.0-or-later — https://github.com/k8shell-io/charts Options: -v, --version VERSION Helm chart version (default: latest) + -c, --chart REF Chart to install: OCI reference or local chart + directory (default: $CHART_REF) + -f, --values FILE Additional values file (repeatable), e.g. for a + private registry + -y, --yes Do not ask for confirmation -n, --namespace NS k8shell release namespace (default: $NAMESPACE) -t, --target-namespace NS Workspace target namespace (default: $TARGET_NAMESPACE) --node-port PORT Expose SSH via NodePort (default: $NODE_PORT) @@ -54,6 +62,9 @@ EOF while [[ $# -gt 0 ]]; do case "$1" in -v|--version) CHART_VERSION="$2"; shift 2 ;; + -c|--chart) CHART_REF="$2"; shift 2 ;; + -f|--values) VALUES_FILES+=("$2"); shift 2 ;; + -y|--yes) ASSUME_YES="true"; shift ;; -n|--namespace) NAMESPACE="$2"; shift 2 ;; -t|--target-namespace) TARGET_NAMESPACE="$2"; shift 2 ;; --node-port) NODE_PORT="$2"; shift 2 ;; @@ -118,6 +129,17 @@ ensure_ec_key() { cat "$file" } +# a random password kept in a file, so upgrades keep it (the database and NATS +# are initialized with it) +ensure_password() { + local file="$1" + if [ ! -f "$file" ]; then + info "Generating password: $file" + (umask 077; openssl rand -hex 24 > "$file") + fi + cat "$file" +} + resolve_admin_public_key() { # 1. Prefer ~/.ssh/id_rsa.pub if it exists local default_pub="$HOME/.ssh/id_rsa.pub" @@ -211,7 +233,10 @@ fi echo echo " Helm action : $helmAction" -echo " Chart version : ${CHART_VERSION:-latest}" +echo " Chart : $CHART_REF ${CHART_VERSION:-(latest)}" +for f in ${VALUES_FILES[@]+"${VALUES_FILES[@]}"}; do +echo " Values file : $f" +done echo " Release namespace : $NAMESPACE (will be created if absent)" echo " Target namespace : $TARGET_NAMESPACE ($targetNsStatus)" echo " SSH NodePort : $([ "$NODE_PORT_ENABLED" = "true" ] && echo "enabled (port $NODE_PORT)" || echo "disabled")" @@ -219,7 +244,11 @@ echo " SSH proxy key : $serverKeyDesc" echo " Admin user : admin (sudo enabled, shell: /bin/bash)" echo " Admin SSH key : $adminKeySource" echo -read -rp "Proceed with installation? [y/N] " confirm -admin +# of their own organization could perform, across every group in that org +is_org_admin(subject) if "org-admin" in subject.roles + +# roles the subject holds that follow the "-admin" convention; a +# subject may administer more than one group +group_admin_roles(roles) := {role | + some role in roles + endswith(role, "-admin") +} + +# a full site admin's account is off limits to org-admin/-admin +# management entirely, even within their own org — only another full site +# admin may read or write it +protected_admin(target_user) if "admin" in target_user.roles + +# true if subject is a -admin managing target_user's account: both +# belong to the same organization and target_user holds the matching +# -user role +managed_by_group_admin(subject, target_user) if { + admin_roles := group_admin_roles(subject.roles) + count(admin_roles) > 0 + subject.org == target_user.organization + not protected_admin(target_user) + some admin_role in admin_roles + managed_role := sprintf("%s-user", [trim_suffix(admin_role, "-admin")]) + managed_role in target_user.roles +} + +# a -admin also manages the account of a peer -admin — someone +# else holding the same -admin role — so, e.g., two arc-admins can +# reach each other's owner-scoped resources (workspaces included) the same +# way an arc-admin already reaches an arc-user's +managed_by_group_admin(subject, target_user) if { + admin_roles := group_admin_roles(subject.roles) + count(admin_roles) > 0 + subject.org == target_user.organization + not protected_admin(target_user) + subject.username != target_user.username + some admin_role in admin_roles + admin_role in target_user.roles +} + +# an org-admin manages every user in their own organization, regardless of +# which -user role that user holds +managed_by_group_admin(subject, target_user) if { + is_org_admin(subject) + subject.org == target_user.organization + not protected_admin(target_user) +} + +# inject_role is the role that allows inject mode (workspace:create and +# workspace:provision with context.mode == "inject"): attaching a workspace +# to an existing workload is a higher-trust operation than a standalone +# workspace, so it is gated to a role rather than open to everyone +inject_role := "developer" + +# git_workspace_role is the role that gives a user of an external identity +# provider access to its repository catalog (user:read data_type=repos) and +# git-sourced workspaces; which users get it is decided by the onboarding +# rules of the identity providers, not by the policies +git_workspace_role := "git-workspace" + +# true if user was onboarded through an external identity provider +# ("idp.k8shell.io/", not identity's own user file) and holds the +# git_workspace_role; providers without a repository catalog simply have +# none to browse +onboarded_via_git_idp(user) if { + startswith(user.source, "idp.k8shell.io/") + user.source != "idp.k8shell.io/file" + git_workspace_role in user.roles +} diff --git a/k8shell/files/policies/git.rego b/k8shell/files/policies/git.rego new file mode 100644 index 0000000..cf7347e --- /dev/null +++ b/k8shell/files/policies/git.rego @@ -0,0 +1,21 @@ +package git + +import rego.v1 + +# git:fetch and git:push cover git's smart-HTTP protocol through api-server's +# git proxy (fetch: clone/fetch/pull; push: receive-pack, checked already on +# the info/refs advertisement). The resource is the upstream repo +# (type "repo", id like "github.com/acme/app", attributes.host). + +default allow := false + +git_actions := {"git:fetch", "git:push"} + +allow if { + input.action in git_actions + input.resource.type == "repo" + input.resource.id != "" + input.subject.username != "" + input.context.workspace != "" + input.context.workspace_owner == input.subject.username +} diff --git a/k8shell/files/policies/onboardrule.rego b/k8shell/files/policies/onboardrule.rego new file mode 100644 index 0000000..1a0042c --- /dev/null +++ b/k8shell/files/policies/onboardrule.rego @@ -0,0 +1,20 @@ +package onboardrule + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any onboardrule action, in any org +allow if { + input.action in {"onboardrule:list", "onboardrule:create", "onboardrule:update", "onboardrule:delete"} + common.is_admin(input.subject) +} + +# org-admins can perform any onboardrule action within their own organization; +# onboardrule:update also gates ApproveOnboardRequest/RejectOnboardRequest +allow if { + input.action in {"onboardrule:list", "onboardrule:create", "onboardrule:update", "onboardrule:delete"} + common.is_org_admin(input.subject) + input.resource.attributes.org == input.subject.org +} diff --git a/k8shell/files/policies/org.rego b/k8shell/files/policies/org.rego new file mode 100644 index 0000000..02180c8 --- /dev/null +++ b/k8shell/files/policies/org.rego @@ -0,0 +1,47 @@ +package org + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any org action; role/user-scoped access (e.g. an +# org-admin managing their own org) is not yet defined here +allow if { + input.action in { + "org:list", "org:create", "org:delete", "org:update", "org:read", + "org:envvar:read", "org:envvar:write", "org:node:write", + } + common.is_admin(input.subject) +} + +# org:node:write (replacing an org's node selectors and listing the node +# selector options, which expose cluster topology) is deliberately absent from +# the org-admin rule below: it is kept off org:update so an org-admin cannot +# steer their org's workspaces onto particular nodes + +# org-admins can read or update their own org, including its environment +# variables (org:envvar:read/write is kept separate from org:read/update — see +# the contract docs in this file — but an org-admin gets both the same way) +allow if { + input.action in {"org:read", "org:update", "org:envvar:read", "org:envvar:write"} + common.is_org_admin(input.subject) + input.resource.id == input.subject.org +} + +# org-admins can list orgs, scoped to their own org via the "orgs" obligation +# below +allow if { + input.action == "org:list" + common.is_org_admin(input.subject) +} + +# --- org:list obligations --- + +# an org-admin's listing is scoped to the single org they're a member of; +# full admins are exempt since they can see every org +obligations["org"] := input.subject.org if { + input.action == "org:list" + common.is_org_admin(input.subject) + not common.is_admin(input.subject) +} diff --git a/k8shell/files/policies/role.rego b/k8shell/files/policies/role.rego new file mode 100644 index 0000000..90aa3fc --- /dev/null +++ b/k8shell/files/policies/role.rego @@ -0,0 +1,47 @@ +package role + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any role action, unscoped; role:list's "org" obligation +# is left unset, which the enforcer treats as no restriction +allow if { + input.action in {"role:list", "role:create", "role:delete", "role:update"} + common.is_admin(input.subject) +} + +# an org-admin can create, update, or delete roles scoped to their own +# organization +allow if { + input.action in {"role:create", "role:update", "role:delete"} + common.is_org_admin(input.subject) + input.resource.attributes.org == input.subject.org +} + +# a -admin can list roles; this also covers org-admin, since +# "org-admin" itself follows the "-admin" convention. The listing is +# scoped to the subject's own org via the "org" obligation below — role:list's +# contract has no per-role-name obligation, so a -admin (e.g. +# am2-admin) sees every role in their org rather than only am2-user/am2-admin +allow if { + input.action == "role:list" + count(common.group_admin_roles(input.subject.roles)) > 0 +} + +# --- role:list obligations --- + +# only full admins may also see global (org-less) roles alongside org-scoped +# ones; absent is treated as "false" for everyone else +obligations["global_roles"] := "true" if { + input.action == "role:list" + common.is_admin(input.subject) +} + +# every non-admin listing (org-admins and -admins alike) is scoped to +# the subject's own organization +obligations["org"] := input.subject.org if { + input.action == "role:list" + not common.is_admin(input.subject) +} diff --git a/k8shell/files/policies/session_list.rego b/k8shell/files/policies/session_list.rego new file mode 100644 index 0000000..6ac1e52 --- /dev/null +++ b/k8shell/files/policies/session_list.rego @@ -0,0 +1,69 @@ +package session + +import rego.v1 +import data.common + +# a -admin can list sessions of users with role -user, for +# every group they administer (scoped via the "roles" obligation below); when +# checked against a specific resource (e.g. a capability check), that +# resource's owner must resolve to an actual managed -user account — +# a nonexistent or unmanaged owner must not pass +allow if { + input.action == "session:list" + count(common.group_admin_roles(input.subject.roles)) > 0 + not input.resource.attributes.owner +} + +allow if { + input.action == "session:list" + owner := input.resource.attributes.owner + owner + common.managed_by_group_admin(input.subject, enrich.user(owner)) +} + +# a user who is not a group admin can list only their own sessions when no +# specific owner is requested (scoped via the "username" obligation below) +allow if { + input.action == "session:list" + count(common.group_admin_roles(input.subject.roles)) == 0 + not input.resource.attributes.owner +} + +# a subject can always list their own sessions, regardless of any +# -admin role they also hold — a -admin's own account is never +# a "managed" account (common.managed_by_group_admin requires the target to +# hold the matching "-user" role), so without this rule a -admin's +# self-owned capability check would fall through every rule above and deny +allow if { + input.action == "session:list" + input.resource.attributes.owner == input.subject.username +} + +# --- session:list obligations --- + +# a -admin's listing is scoped to -admin and -user +# accounts, for every group they administer; an org-admin sees every role +# within their organization and is left unscoped here +obligations["roles"] := scoped_roles if { + input.action == "session:list" + admin_roles := common.group_admin_roles(input.subject.roles) + count(admin_roles) > 0 + not common.is_org_admin(input.subject) + scoped_roles := admin_roles | {managed_role | + some admin_role in admin_roles + managed_role := sprintf("%s-user", [trim_suffix(admin_role, "-admin")]) + } +} + +# a non-admin's listing is always scoped to their own organization +obligations["org"] := input.subject.org if { + input.action == "session:list" + not common.is_admin(input.subject) +} + +# a non-group-admin's listing is scoped to their own sessions only +obligations["username"] := input.subject.username if { + input.action == "session:list" + count(common.group_admin_roles(input.subject.roles)) == 0 + not common.is_admin(input.subject) +} diff --git a/k8shell/files/policies/session_record.rego b/k8shell/files/policies/session_record.rego new file mode 100644 index 0000000..966ae5e --- /dev/null +++ b/k8shell/files/policies/session_record.rego @@ -0,0 +1,78 @@ +package session + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any session action +allow if common.is_admin(input.subject) + +# session:list is defined in session_list.rego + +# --- session:record --- + +# session:record decides what to record for a session; it is not an access +# check. The ssh:* (ssh.rego) and workspace:connect (workspace_access.rego) +# entry rules are the only gate on whether a session may happen, and callers +# consume only the obligations, never allowed — so any well-formed request +# is allowed here. +allow if input.action == "session:record" + +# a malformed session:record request is rejected, regardless of admin status +deny if { + input.action == "session:record" + not valid_record_input +} + +valid_record_input if { + input.resource.type == "workspace" + input.resource.id != "" + input.resource.attributes.owner != "" + input.context.session_type in object.keys(record_channels) + input.context.session_source in {"ssh-proxy", "api-server"} +} + +# the record obligation's comma-separated tokens for each session_type; recording +# a port-forward (direct-tcpip) also records the VS Code terminals it carries and +# their keystrokes +record_channels := { + "shell": "shell", + "tcpip": "direct-tcpip,vscode-terminals,vscode-input", + "exec": "exec", + "sftp": "sftp", +} + +# --- session:record obligations --- + +# record the session when the subject holds the matching record- +# role (record-shell, record-tcpip, record-exec, record-sftp) or the session +# matches a record_rules entry; the obligation value lists the tokens to record +obligations["record"] := record_channels[input.context.session_type] if { + input.action == "session:record" + records_session_type +} + +# explicitly disable recording for everyone else, rather than leaving it to +# the enforcer's default +obligations["record"] := "none" if { + input.action == "session:record" + not records_session_type +} + +records_session_type if { + sprintf("record-%s", [input.context.session_type]) in input.subject.roles +} + +records_session_type if { + some rule in record_rules + rule.org == input.subject.org + rule.blueprint == input.resource.attributes.blueprint + input.context.session_type in rule.session_types +} + +# sessions recorded regardless of roles: by subjects of org on workspaces built +# from blueprint, for the listed session_types +record_rules := [ + {"org": "tul-fm", "blueprint": "ct1-content", "session_types": {"shell", "tcpip", "exec"}}, +] diff --git a/k8shell/files/policies/session_recording.rego b/k8shell/files/policies/session_recording.rego new file mode 100644 index 0000000..70a818e --- /dev/null +++ b/k8shell/files/policies/session_recording.rego @@ -0,0 +1,87 @@ +package session + +import rego.v1 +import data.common + +# session:recording:read follows session:list (session_list.rego) for admins: +# admins read everything, org-admins read recordings of users in their +# organization, -admins read recordings of users they manage. Unlike +# session:list, a plain user (no admin role) cannot read any recordings, +# including their own. It is a separate permission — being able to list sessions +# does not imply being able to read what was recorded in them. One action +# covers every recording type and format. + +# a -admin (org-admins included) can read recordings across users when +# no specific owner is requested; the result is scoped via the obligations below +allow if { + input.action == "session:recording:read" + count(common.group_admin_roles(input.subject.roles)) > 0 + not input.resource.attributes.owner +} + +# when checked against a specific owner, that owner must resolve to an account +# the subject manages (org-admin: same org; -admin: same org and group) +# — a nonexistent or unmanaged owner must not pass +allow if { + input.action == "session:recording:read" + owner := input.resource.attributes.owner + owner + common.managed_by_group_admin(input.subject, enrich.user(owner)) +} + +# a -admin can always read their own recordings (their own account is +# never a "managed" account; full admins are covered by the admin rule in +# session_record.rego); a plain user gets no rule and so cannot read +# recordings at all, not even their own +allow if { + input.action == "session:recording:read" + count(common.group_admin_roles(input.subject.roles)) > 0 + input.resource.attributes.owner == input.subject.username +} + +# a session-recorder can read their own recordings, and browse with no owner +# given, scoped to their own via the username obligation below. A subject who +# also holds a -admin role is covered by the rules above instead. +allow if { + input.action == "session:recording:read" + "session-recorder" in input.subject.roles + input.resource.attributes.owner == input.subject.username +} + +allow if { + input.action == "session:recording:read" + "session-recorder" in input.subject.roles + count(common.group_admin_roles(input.subject.roles)) == 0 + not input.resource.attributes.owner +} + +# --- session:recording:read obligations --- + +# a -admin is scoped to -admin and -user accounts, for +# every group they administer; an org-admin is left unscoped here and bounded +# by the org obligation instead +obligations["roles"] := scoped_roles if { + input.action == "session:recording:read" + admin_roles := common.group_admin_roles(input.subject.roles) + count(admin_roles) > 0 + not common.is_org_admin(input.subject) + scoped_roles := admin_roles | {managed_role | + some admin_role in admin_roles + managed_role := sprintf("%s-user", [trim_suffix(admin_role, "-admin")]) + } +} + +# everyone except a full admin is scoped to their own organization +obligations["org"] := input.subject.org if { + input.action == "session:recording:read" + not common.is_admin(input.subject) +} + +# a session-recorder without any -admin role is scoped to their own +# recordings only +obligations["username"] := input.subject.username if { + input.action == "session:recording:read" + "session-recorder" in input.subject.roles + count(common.group_admin_roles(input.subject.roles)) == 0 + not common.is_admin(input.subject) +} diff --git a/k8shell/files/policies/session_recording_override.rego b/k8shell/files/policies/session_recording_override.rego new file mode 100644 index 0000000..3a5e032 --- /dev/null +++ b/k8shell/files/policies/session_recording_override.rego @@ -0,0 +1,45 @@ +package session + +import rego.v1 +import data.common + +# session:recording:override covers reading, setting and clearing a +# workspace's recording override, which replaces the session:record obligation +# for every later session to that workspace. Since an override can switch +# recording off, it is granted narrowly: admins on every workspace (the admin +# rule in session_record.rego), org-admins on workspaces of users in their +# organization and on their own workspaces, -admins on workspaces of +# users they manage. Nobody else gets it, not even the workspace owner. + +# an org-admin or -admin may override the recording of a workspace +# owned by an account they manage (org-admin: same org; -admin: same +# org and group, or a peer -admin); with no resource id this answers +# the capability probe for that owner. Their own workspaces are excluded +# here; an org-admin gets theirs through the rule below. +allow if { + input.action == "session:recording:override" + input.resource.type == "workspace" + owner := input.resource.attributes.owner + owner != "" + owner != input.subject.username + common.managed_by_group_admin(input.subject, enrich.user(owner)) +} + +# an org-admin may also override the recording of their own workspace; a +# -admin still may not. With no resource id this answers the +# capability probe. +allow if { + input.action == "session:recording:override" + input.resource.type == "workspace" + common.is_org_admin(input.subject) + input.resource.attributes.owner == input.subject.username +} + +# a session-recorder may override the recording of their own workspace, and +# of no one else's. With no resource id this answers the capability probe. +allow if { + input.action == "session:recording:override" + input.resource.type == "workspace" + "session-recorder" in input.subject.roles + input.resource.attributes.owner == input.subject.username +} diff --git a/k8shell/files/policies/ssh.rego b/k8shell/files/policies/ssh.rego new file mode 100644 index 0000000..7a4778b --- /dev/null +++ b/k8shell/files/policies/ssh.rego @@ -0,0 +1,26 @@ +package ssh + +import rego.v1 +import data.common + +default allow := false + +allow if { + input.resource.type == "workspace" + common.is_admin(input.subject) +} + +_ssh_user_actions := {"ssh:shell", "ssh:exec", "ssh:sftp", + "ssh:direct-tcpip", "ssh:direct-streamlocal", "ssh:agent-forward"} + +allow if { + input.action in _ssh_user_actions + input.resource.type == "workspace" + input.resource.attributes.owner == input.subject.username +} + +deny if { + input.action in {"ssh:shell", "ssh:exec"} + input.context.as_user == "root" + not input.subject.sudo == true +} \ No newline at end of file diff --git a/k8shell/files/policies/threat_detect.rego b/k8shell/files/policies/threat_detect.rego new file mode 100644 index 0000000..1a60c94 --- /dev/null +++ b/k8shell/files/policies/threat_detect.rego @@ -0,0 +1,275 @@ +package threat + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any threat action +allow if common.is_admin(input.subject) + +# --- threat:detect --- + +# threat:detect decides which attack categories worktrace watches on a +# workspace; it is not an access check. The provisioner evaluates it when it +# provisions a workspace and consumes only the obligations, never allowed — so +# any well-formed request is allowed here. +allow if input.action == "threat:detect" + +# a malformed threat:detect request is rejected, regardless of admin status +deny if { + input.action == "threat:detect" + not valid_detect_input +} + +valid_detect_input if { + input.resource.type == "workspace" + input.resource.id != "" + input.resource.attributes.owner != "" + input.context.namespace != "" + valid_detect_mode +} + +valid_detect_mode if input.context.mode == "standalone" + +valid_detect_mode if { + input.context.mode == "inject" + input.context.workload_name != "" + input.context.workload_kind != "" +} + +# --- threat:detect obligations --- + +# detect the categories granted by the subject's detect- roles +# (detect-all for every category) and by matching detect_rules entries; the +# obligation value lists them comma-separated, or "all" when any grant is "all" +obligations["detect"] := "all" if { + input.action == "threat:detect" + "all" in detect_categories +} + +obligations["detect"] := concat(",", sort(detect_categories)) if { + input.action == "threat:detect" + count(detect_categories) > 0 + not "all" in detect_categories +} + +# explicitly disable detection for everyone else, rather than leaving it to +# the enforcer's default (worktrace's global rule rollout) +obligations["detect"] := "none" if { + input.action == "threat:detect" + count(detect_categories) == 0 +} + +detect_categories contains category if { + some role in input.subject.roles + startswith(role, "detect-") + category := trim_prefix(role, "detect-") + category != "" +} + +detect_categories contains category if { + some rule in matched_rules + some category in rule.categories +} + +detect_categories contains category if { + some class in detection_classes + some category in detect_classes[class].categories +} + +# what led to the detect obligation, returned as the decision's reason +# (PolicyResult.Reason): one entry per detect- role, matched +# detect_rules entry and detection class, with the conditions that matched +# the class +reason := concat("; ", sort(detect_reasons)) if { + input.action == "threat:detect" + count(detect_reasons) > 0 +} + +reason := "no detect role, rule or class matched" if { + input.action == "threat:detect" + count(detect_reasons) == 0 +} + +detect_reasons contains sprintf("role %s", [role]) if { + some role in input.subject.roles + startswith(role, "detect-") + trim_prefix(role, "detect-") != "" +} + +detect_reasons contains sprintf("rule %s: %s", [json.marshal(object.remove(rule, {"categories"})), concat(",", sort(rule.categories))]) if { + some rule in matched_rules +} + +detect_reasons contains reason if { + some class in detection_classes + evidence := {e | some [c, e] in class_evidence; c == class} + reason := sprintf("class %s: %s (%s)", [ + class, + concat(",", sort(detect_classes[class].categories)), + concat(", ", sort(evidence)), + ]) +} + +# [class, evidence] pairs: the conditions of each detection class that hold, +# and why the sudo class holds +class_evidence contains [class, json.marshal(cond)] if { + some class in detection_classes + spec := detect_classes[class] + some cond in array.concat(object.get(spec, "any", []), object.get(spec, "all", [])) + resource_condition(cond) +} + +class_evidence contains ["sudo", sprintf("owner %s has sudo", [input.resource.attributes.owner])] if owner_has_sudo + +matched_rules contains rule if { + some rule in detect_rules + object.get(rule, "org", input.subject.org) == input.subject.org + object.get(rule, "blueprint", blueprint_name) == blueprint_name + object.get(rule, "class", "") in detection_classes | {""} +} + +# workspaces detected regardless of roles, for the listed categories ("all" +# for every category). Each of org, blueprint and class is optional and, when +# set, must match: org the subject's org, blueprint the blueprint name, class +# one of the workspace's detection_classes, e.g. +# {"org": "tul-fm", "blueprint": "ct1-content", "categories": {"all"}} +# {"org": "tul-fm", "class": "privileged", "categories": {"all"}} +# (array.concat types the empty default as array[any]; a literal [] has no +# element type and fails type checking where the rules are iterated) +detect_rules := array.concat([], []) + +# --- workspace detection classes --- + +# the workspace chart as the provisioner renders it, decoded from +# context.resources: an object of Kubernetes documents keyed "Kind/name" +# (Secrets are left out, ConfigMaps carry metadata only). In inject mode it +# holds only what the workspace chart contributes, not the target workload's +# own containers. Undefined when the caller passed none (or it does not +# decode), in which case no detection class matches. +resources := json.unmarshal(input.context.resources) if is_string(input.context.resources) + +default blueprint_name := "" + +blueprint_name := input.resource.attributes.blueprint + +# detection_classes is the set of detect_classes whose conditions hold on the +# rendered resources. A class holds when any of its "any" conditions holds, +# or every one of its "all" conditions holds (a class may set either, or both). +detection_classes contains class if { + some class, spec in detect_classes + some cond in object.get(spec, "any", []) + resource_condition(cond) +} + +detection_classes contains class if { + some class, spec in detect_classes + conds := object.get(spec, "all", []) + count(conds) > 0 + every cond in conds { + resource_condition(cond) + } +} + +# the workspace owner, not the provisioning subject, is the user k8shelld +# creates in the workspace, so sudo is read from the owner's account +detection_classes contains "sudo" if owner_has_sudo + +owner_has_sudo if enrich.user(input.resource.attributes.owner).sudo == true + +# resource_condition(cond) holds when some value at cond.path in some rendered +# resource satisfies cond's test. kind optionally limits the resources to that +# kind; without it every resource is searched. path is dot-separated from the +# resource root; a "*" segment matches any map key or list index and "a|b" +# matches either key, e.g. "spec.containers|initContainers.*.image" (kind +# takes "A|B" too). The test is one of: +# "equals": v the value is v +# "in": [v, ...] the value is one of the listed values +# "prefix": s the value is a string starting with s +# "present": true the path exists and its value is not null, false or empty +resource_condition(cond) if { + some value in resource_values(cond) + value_test(cond, value) +} + +resource_values(cond) := {value | + pattern := split(cond.path, ".") + some res in resources + kind_matches(cond, res) + walk(res, [p, value]) + count(p) == count(pattern) + every i, seg in pattern { + path_segment_matches(seg, p[i]) + } +} + +kind_matches(cond, _) if not "kind" in object.keys(cond) + +kind_matches(cond, res) if res.kind in split(cond.kind, "|") + +path_segment_matches("*", _) + +path_segment_matches(seg, key) if sprintf("%v", [key]) in split(seg, "|") + +value_test(cond, value) if value == cond.equals + +value_test(cond, value) if value in cond["in"] + +value_test(cond, value) if { + is_string(value) + startswith(value, cond.prefix) +} + +value_test(cond, value) if { + cond.present == true + not value in {null, false, "", [], {}} +} + +# traits of the rendered workspace mapped to the worktrace categories +# (threat.Categories, or "all") watched on workspaces that have them, for +# every subject +detect_classes := { + # a privileged container, or one granted kernel-level capabilities, can + # reach the host kernel and devices + "privileged": { + "any": [ + {"kind": "Pod", "path": "spec.containers|initContainers.*.securityContext.privileged", "equals": true}, + { + "kind": "Pod", + "path": "spec.containers|initContainers.*.securityContext.capabilities.add.*", + "in": ["ALL", "SYS_ADMIN", "SYS_MODULE", "SYS_PTRACE", "SYS_RAWIO", "DAC_READ_SEARCH", "BPF"], + }, + ], + "categories": {"container-escape", "privilege-escalation-and-kernel"}, + }, + # the pod shares the host's process or IPC namespace + "host-namespaces": { + "any": [{"kind": "Pod", "path": "spec.hostPID|hostIPC", "equals": true}], + "categories": {"container-escape", "privilege-escalation-and-kernel"}, + }, + # the pod runs in the host's network namespace + "host-network": { + "any": [{"kind": "Pod", "path": "spec.hostNetwork", "equals": true}], + "categories": {"container-escape", "lateral-movement-and-network"}, + }, + # a host directory is mounted into the pod + "host-path": { + "any": [{"kind": "Pod", "path": "spec.volumes.*.hostPath.path", "present": true}], + "categories": {"container-escape", "persistence"}, + }, + # the workspace user k8shelld creates may sudo (k8shelld itself always + # runs as root, so the pod's runAsUser tells nothing); matched by + # owner_has_sudo rather than by resource conditions + "sudo": {"categories": {"privilege-escalation-and-kernel"}}, + # the chart grants the workspace Kubernetes API permissions + "cluster-access": { + "any": [{"kind": "RoleBinding|ClusterRoleBinding", "path": "roleRef.name", "present": true}], + "categories": {"container-runtime-and-k8s-api", "credential-access", "lateral-movement-and-network"}, + }, + # a network policy opens egress to anywhere + "open-egress": { + "any": [{"kind": "NetworkPolicy", "path": "spec.egress.*.to.*.ipBlock.cidr", "in": ["0.0.0.0/0", "::/0"]}], + "categories": {"lateral-movement-and-network", "reverse-shells-and-execution", "cryptomining"}, + }, +} diff --git a/k8shell/files/policies/threat_detection_override.rego b/k8shell/files/policies/threat_detection_override.rego new file mode 100644 index 0000000..2c20700 --- /dev/null +++ b/k8shell/files/policies/threat_detection_override.rego @@ -0,0 +1,36 @@ +package threat + +import rego.v1 +import data.common + +# threat:detection:override covers reading, setting and clearing a +# workspace's detection override, which replaces the threat:detect obligation +# for the workspace until it is cleared. Since an override can switch +# detection off, it is granted narrowly: admins on every workspace (the admin +# rule in threat_detect.rego), org-admins on workspaces of users in their +# organization and on their own workspaces, -admins on workspaces of +# users they manage. Nobody else gets it, not even the workspace owner. + +# an org-admin or -admin may override the detection of a workspace +# owned by an account they manage (org-admin: same org; -admin: same +# org and group, or a peer -admin); with no resource id this answers +# the capability probe for that owner. Their own workspaces are excluded +# here; an org-admin gets theirs through the rule below. +allow if { + input.action == "threat:detection:override" + input.resource.type == "workspace" + owner := input.resource.attributes.owner + owner != "" + owner != input.subject.username + common.managed_by_group_admin(input.subject, enrich.user(owner)) +} + +# an org-admin may also override the detection of their own workspace; a +# -admin still may not. With no resource id this answers the +# capability probe. +allow if { + input.action == "threat:detection:override" + input.resource.type == "workspace" + common.is_org_admin(input.subject) + input.resource.attributes.owner == input.subject.username +} diff --git a/k8shell/files/policies/threat_list.rego b/k8shell/files/policies/threat_list.rego new file mode 100644 index 0000000..6a27d6e --- /dev/null +++ b/k8shell/files/policies/threat_list.rego @@ -0,0 +1,24 @@ +package threat + +import rego.v1 +import data.common + +# threat:list grants querying the threats worktrace detected. Admins list +# every threat (the admin rule in threat_detect.rego); org-admins list the +# threats of the organization they manage, scoped via the "org" obligation +# below. Nobody else gets it. + +allow if { + input.action == "threat:list" + common.is_org_admin(input.subject) +} + +# --- threat:list obligations --- + +# an org-admin's listing is scoped to the single org they're a member of; +# full admins are exempt since they can see every org +obligations["org"] := input.subject.org if { + input.action == "threat:list" + common.is_org_admin(input.subject) + not common.is_admin(input.subject) +} diff --git a/k8shell/files/policies/user.rego b/k8shell/files/policies/user.rego new file mode 100644 index 0000000..332bdc1 --- /dev/null +++ b/k8shell/files/policies/user.rego @@ -0,0 +1,27 @@ +package user + +import rego.v1 +import data.common + +default allow := false + +# admins can perform any user action except those explicitly denied +admin_denied_actions := {"token:create"} + +allow if { + common.is_admin(input.subject) + not input.action in admin_denied_actions +} + +# users can create tokens for themselves +allow if { + input.action == "token:create" + input.subject.username == input.resource.id +} + +# --- token:create obligations --- + +obligations["expires_in"] := "24h" if { + input.action == "token:create" + input.context.source == "web-flow" +} diff --git a/k8shell/files/policies/user_access.rego b/k8shell/files/policies/user_access.rego new file mode 100644 index 0000000..f611568 --- /dev/null +++ b/k8shell/files/policies/user_access.rego @@ -0,0 +1,187 @@ +package user + +import rego.v1 +import data.common + +# users can read their own data (any data type except repos, which needs a +# git-based IdP account behind it — see the repos-specific rule below) +allow if { + input.action == "user:read" + input.subject.username == input.resource.id + input.context.data_type != "repos" +} + +# repos is the identity-provider repository catalog, so a self-read only +# makes sense (and is only allowed) when the user was onboarded through one +# an external identity provider with the git-workspace role (see +# common.onboarded_via_git_idp) +allow if { + input.action == "user:read" + input.subject.username == input.resource.id + input.context.data_type == "repos" + common.onboarded_via_git_idp(input.subject) +} + +# data types an owning user may write on their own record — least privilege: +# only the data types with no admin/security implications; "credentials" +# is handled separately below since it needs credential_type-aware scoping. +# "envvars" is included here but deliberately omitted from +# group_admin_editable_data_types below — see the envvars deny rule near the +# bottom of this file. "logins" is included here too, but unlike envvars it +# is *also* in group_admin_editable_data_types below, since org-admins and +# -admins may revoke a managed user's sessions, not just their own +self_editable_data_types := {"profile", "password", "keys", "envvars", "logins"} + +allow if { + input.action == "user:write" + input.subject.username == input.resource.id + input.context.data_type in self_editable_data_types +} + +# a user may write their own git/registry credentials, but never their own +# kubernetes credentials — kubernetes credential writes are reserved for full +# site admins only, even on the admin's own account (see the admin bypass in +# user.rego); with no allow rule covering a self-write of kubernetes creds, +# it falls through to the default deny for everyone else, org-admins and +# -admins included +allow if { + input.action == "user:write" + input.subject.username == input.resource.id + input.context.data_type == "credentials" + input.context.credential_type in {"git", "registry"} +} + +# a -admin manages other users' accounts, never their own — self-edits +# always go through the self-write rule above, which is intentionally more +# restrictive (e.g. it never grants "roles", "sudo", "locked", or "org"). +# repos is excluded here too, same reasoning as the self-read rule above. +allow if { + input.action == "user:read" + input.subject.username != input.resource.id + input.context.data_type != "repos" + common.managed_by_group_admin(input.subject, enrich.user(input.resource.id)) +} + +# a -admin may browse a managed user's repos catalog, but only if that +# managed user actually has one — see common.onboarded_via_git_idp +allow if { + input.action == "user:read" + input.subject.username != input.resource.id + input.context.data_type == "repos" + target_user := enrich.user(input.resource.id) + common.managed_by_group_admin(input.subject, target_user) + common.onboarded_via_git_idp(target_user) +} + +# data types a -admin may write on their managed users' accounts; org +# is omitted, so only a full site admin (user.rego) can ever write it, keys +# is omitted — see the sshkey deny rule below, which locks key writes to the +# owning user only, the same as token:create — and credentials is omitted +# since it needs credential_type-aware scoping, handled separately below. +# "logins" is included — an org-admin/-admin revoking a managed +# user's login session is the same data_type as a self-revoke, decided here +# by policy rather than a separate contract (see the contract comment on +# user:write's logins data_type) +group_admin_editable_data_types := { + "profile", "password", "blueprints", "sudo", "locked", "logins" +} + +allow if { + input.action == "user:write" + input.subject.username != input.resource.id + input.context.data_type in group_admin_editable_data_types + common.managed_by_group_admin(input.subject, enrich.user(input.resource.id)) +} + +# common.managed_by_group_admin covers both org-admins (any user in their +# org) and -admins (their managed -user accounts) — either may +# write git/registry credentials for a user they manage, but never that +# user's kubernetes credentials; kubernetes credential writes stay reserved +# for full site admins only (user.rego's admin bypass) +allow if { + input.action == "user:write" + input.subject.username != input.resource.id + input.context.data_type == "credentials" + input.context.credential_type in {"git", "registry"} + common.managed_by_group_admin(input.subject, enrich.user(input.resource.id)) +} + +# an org-admin may edit roles on any user within their own organization; +# plain -admins cannot — role changes are reserved for org-wide admins. +# A full site admin's own roles are still off limits, even to an org-admin in +# the same org — see common.protected_admin. +allow if { + input.action == "user:write" + input.subject.username != input.resource.id + input.context.data_type == "roles" + common.is_org_admin(input.subject) + target_user := enrich.user(input.resource.id) + input.subject.org == target_user.organization + not common.protected_admin(target_user) +} + +# a -admin can list users (scoped to -user accounts via the +# "roles" obligation below) +allow if { + input.action == "user:list" + count(common.group_admin_roles(input.subject.roles)) > 0 +} + +# a -admin's listing is scoped to -admin and -user +# accounts only, unless they're also a full site admin or an org-admin (who +# sees every role within their organization) +obligations["roles"] := scoped_roles if { + input.action == "user:list" + admin_roles := common.group_admin_roles(input.subject.roles) + count(admin_roles) > 0 + not common.is_admin(input.subject) + not common.is_org_admin(input.subject) + scoped_roles := admin_roles | {managed_role | + some admin_role in admin_roles + managed_role := sprintf("%s-user", [trim_suffix(admin_role, "-admin")]) + } +} + +# a -admin's listing is further scoped to their own organization +obligations["org"] := input.subject.org if { + input.action == "user:list" + not common.is_admin(input.subject) +} + +# ssh public keys can only ever be written by the owning user — same rule as +# token:create. group_admin_editable_data_types already omits "keys" so +# -admins are covered, but a full site admin still bypasses data_type +# checks entirely via the admin rule in user.rego, so this deny closes that +# gap explicitly rather than carving "user:write" out of admin_denied_actions +# wholesale (which would also block admins from writing roles/sudo/locked/org) +deny if { + input.action == "user:write" + input.context.data_type == "keys" + input.subject.username != input.resource.id +} + +# environment variables can only ever be written by the owning user — same +# reasoning as "keys" above. Full site admins, org-admins, and -admins +# may still read another user's envvars (covered by the generic user:read +# rules above, which don't restrict by data_type), but writes stay +# self-service only; group_admin_editable_data_types already omits "envvars" +# so -admins/org-admins are covered, and this deny closes the same +# full-site-admin bypass gap as the "keys" deny +deny if { + input.action == "user:write" + input.context.data_type == "envvars" + input.subject.username != input.resource.id +} + +# locked status can only ever be written on another user's account — never on +# the subject's own. self_editable_data_types and group_admin_editable_data_types +# already keep the specific write rules above from granting a self-write of +# "locked", but a full site admin still bypasses data_type checks entirely via +# the admin rule in user.rego, which would otherwise let an admin unlock (or +# lock) their own account; this deny closes that gap explicitly, the same as +# the "keys" deny above +deny if { + input.action == "user:write" + input.context.data_type == "locked" + input.subject.username == input.resource.id +} diff --git a/k8shell/files/policies/user_auth.rego b/k8shell/files/policies/user_auth.rego new file mode 100644 index 0000000..1c5b377 --- /dev/null +++ b/k8shell/files/policies/user_auth.rego @@ -0,0 +1,43 @@ +package user + +import rego.v1 +import data.common + +# any authenticated user can authenticate via SSH or web +allow if input.action == "user:auth" + +# true when the subject already authenticated upstream through an external +# IdP; such subjects must never fall back to a local password, on any surface. +# idp.k8shell.io/file is identity's own local user file (identity.users of the +# chart), not an external IdP: its users may use their password. +onboarded_via_idp if { + startswith(input.subject.source, "idp.k8shell.io/") + input.subject.source != "idp.k8shell.io/file" +} + +# local users may use a password on the web surface +obligations["auth_methods"] := ["password"] if { + input.action == "user:auth" + input.context.surface == "web" + not onboarded_via_idp +} + +# IdP-onboarded subjects (github/gitlab/oidc/...) are SSO-only on the web +# surface — no password fallback +obligations["auth_methods"] := ["sso"] if { + input.action == "user:auth" + input.context.surface == "web" + onboarded_via_idp +} + +obligations["auth_methods"] := ["publickey", "password"] if { + input.action == "user:auth" + input.context.surface == "ssh" + not onboarded_via_idp +} + +obligations["auth_methods"] := ["publickey"] if { + input.action == "user:auth" + input.context.surface == "ssh" + onboarded_via_idp +} diff --git a/k8shell/files/policies/user_create.rego b/k8shell/files/policies/user_create.rego new file mode 100644 index 0000000..e4e32d1 --- /dev/null +++ b/k8shell/files/policies/user_create.rego @@ -0,0 +1,17 @@ +package user + +import rego.v1 +import data.common + +# admins can create any user account +allow if { + input.action == "user:create" + common.is_admin(input.subject) +} + +# an org-admin can create user accounts within their own organization +allow if { + input.action == "user:create" + common.is_org_admin(input.subject) + input.resource.attributes.org == input.subject.org +} diff --git a/k8shell/files/policies/user_delete.rego b/k8shell/files/policies/user_delete.rego new file mode 100644 index 0000000..d67599b --- /dev/null +++ b/k8shell/files/policies/user_delete.rego @@ -0,0 +1,34 @@ +package user + +import rego.v1 +import data.common + +# admins can delete any user account except their own +allow if { + input.action == "user:delete" + common.is_admin(input.subject) + input.subject.username != input.resource.id +} + +# an org-admin can delete user accounts within their own organization, but +# never their own account; a full site admin's account is off limits even +# here — see common.protected_admin +allow if { + input.action == "user:delete" + common.is_org_admin(input.subject) + input.subject.username != input.resource.id + target_user := enrich.user(input.resource.id) + input.subject.org == target_user.organization + not common.protected_admin(target_user) +} + +# no subject may ever delete their own account. The two allow rules above +# already require subject != resource, but a full site admin still bypasses +# those checks entirely via the admin rule in user.rego (user:delete is not +# in admin_denied_actions), which would otherwise let an admin delete their +# own account; this deny closes that gap explicitly, mirroring the "locked" +# self-write deny in user_access.rego +deny if { + input.action == "user:delete" + input.subject.username == input.resource.id +} diff --git a/k8shell/files/policies/user_exists.rego b/k8shell/files/policies/user_exists.rego new file mode 100644 index 0000000..f4f7db5 --- /dev/null +++ b/k8shell/files/policies/user_exists.rego @@ -0,0 +1,35 @@ +package user + +import rego.v1 +import data.common + +# Contract: user:exists +# +# Resource type="user" +# id (none) — the check targets an arbitrary, possibly nonexistent, +# username or email supplied by the caller, not a record the subject +# already has standing to act on. +# +# Context +# field username | email (required) — which identifier is being checked, +# mirroring FindUserRequest's "exactly one of username or email" +# contract on the identity side. +# +# Subject injected by the backend from JWT claims (username, roles, email, ...) +# +# Obligations (none) — allow/deny only. The response this backs only ever +# reveals whether the identifier is taken, never who owns it. + +# admins can check whether any username or email is already taken +allow if { + input.action == "user:exists" + common.is_admin(input.subject) +} + +# org-admins can also check whether any username or email is already taken; +# there is no resource id/org to scope against (see contract above), so this +# is unscoped like the admin rule above rather than restricted to their org +allow if { + input.action == "user:exists" + common.is_org_admin(input.subject) +} diff --git a/k8shell/files/policies/user_token.rego b/k8shell/files/policies/user_token.rego new file mode 100644 index 0000000..8f22ae0 --- /dev/null +++ b/k8shell/files/policies/user_token.rego @@ -0,0 +1,28 @@ +package user + +import rego.v1 +import data.common + +# users can read/write/delete their own tokens +allow if { + input.action in {"token:read", "token:write", "token:delete"} + input.subject.username == input.resource.id +} + +# an org-admin can read/write/delete tokens of any user within their own +# organization; a full site admin's tokens are off limits even here — token +# access is equivalent to impersonation, so this is guarded the same way as +# user:delete and the roles data type — see common.protected_admin +allow if { + input.action in {"token:read", "token:write", "token:delete"} + common.is_org_admin(input.subject) + target_user := enrich.user(input.resource.id) + input.subject.org == target_user.organization + not common.protected_admin(target_user) +} + +# a -admin can read/write/delete tokens of their managed -user accounts +allow if { + input.action in {"token:read", "token:write", "token:delete"} + common.managed_by_group_admin(input.subject, enrich.user(input.resource.id)) +} diff --git a/k8shell/files/policies/workspace_access.rego b/k8shell/files/policies/workspace_access.rego new file mode 100644 index 0000000..ad47919 --- /dev/null +++ b/k8shell/files/policies/workspace_access.rego @@ -0,0 +1,174 @@ +package workspace + +import rego.v1 +import data.common + +default allow := false + +# admins may perform any workspace action +allow if common.is_admin(input.subject) + +# workspace actions scoped to a single resource's owner; workspace:list is +# handled separately in workspace_list.rego since it has no single owner +owner_scoped_actions := {"workspace:provision", "workspace:create", + "workspace:read", "workspace:delete", "workspace:connect", + "workspace:files", "workspace:app"} + +# users may perform any owner-scoped workspace action on resources they own +allow if { + input.action in owner_scoped_actions + input.resource.attributes.owner == input.subject.username +} + +# a -admin can perform any owner-scoped workspace action on resources +# owned by their managed -user accounts +allow if { + input.action in owner_scoped_actions + common.managed_by_group_admin(input.subject, enrich.user(input.resource.attributes.owner)) +} + +# --- workspace:update --- + +# cpu, memory, network, proxy, and schedule are the mutable +# runtime-configuration slices a workspace can be updated on; +# workspace:update is evaluated once per data_type (see the contract comment +# at the top of this file), so this set gates each evaluation independently +update_data_types := {"cpu", "memory", "network", "proxy", "schedule"} + +# owner_update_data_types is the subset of update_data_types a plain owner +# may update on their own workspace. "proxy" (network.webProxy, which in +# turn authorizes the {port}--{workspace} port-forward proxy) is the owner's +# to open up or lock down; cpu/memory/network stay admin/org-admin only. +# "schedule" (overriding a running workspace's expiry "to" and grace +# periods, or reverting to the blueprint's schedule) also stays +# admin/org-admin only: the provisioner does not authorize it and there is no +# obligation capping how far "to" may move, so letting owners do it would let +# them extend their own workspace indefinitely. +owner_update_data_types := {"proxy"} + +# owners may update the owner-updatable slices of their own workspace; unlike +# owner_scoped_actions this is not extended to -admins — only full +# site admins (blanket rule above) and org-admins (rule below) may do it on +# someone else's workspace +allow if { + input.action == "workspace:update" + input.context.data_type in owner_update_data_types + input.resource.attributes.owner == input.subject.username +} + +# an org-admin can update any of the mutable slices for a workspace owned by +# a user in their own organization; full site admins already cover every +# workspace via the blanket admin rule above. This is intentionally narrower +# than owner_scoped_actions' common.managed_by_group_admin: a plain +# -admin (e.g. "developer-admin") does not get this permission, only +# an org-admin does — and a full site admin's own workspace stays off limits +# to an org-admin, same as common.protected_admin elsewhere +allow if { + input.action == "workspace:update" + input.context.data_type in update_data_types + common.is_org_admin(input.subject) + owner := enrich.user(input.resource.attributes.owner) + input.subject.org == owner.organization + not common.protected_admin(owner) +} + +# --- workspace:start:force --- + +# workspace:start:force never gates the start itself (the route's own authz +# does); api-server evaluates it on every start and sets force on the +# provisioner's StartWorkspace only when allowed, letting the caller start a +# workspace stopped by schedule expiry. The provisioner does not authorize +# force, so this is the only gate. Plain owners are deliberately left out — +# force-starting past expiry is the same kind of override as +# workspace:update data_type=schedule, which is admin-only too. Full site +# admins are covered by the blanket admin rule above. + +# a -admin or org-admin may force-start workspaces owned by accounts +# they manage (see common.managed_by_group_admin: managed -users, peer +# -admins, and for an org-admin everyone in their org); a full site +# admin's workspace stays off limits via common.protected_admin +allow if { + input.action == "workspace:start:force" + common.managed_by_group_admin(input.subject, enrich.user(input.resource.attributes.owner)) +} + +# a -admin or org-admin may also force-start their own workspace +# ("org-admin" ends in "-admin", so common.group_admin_roles covers it) +allow if { + input.action == "workspace:start:force" + input.resource.attributes.owner == input.subject.username + count(common.group_admin_roles(input.subject.roles)) > 0 +} + +# inject-mode provisioning is restricted to users holding common.inject_role +# — attaching a workspace to an existing workload requires it regardless of +# ownership or admin status +deny if { + input.action == "workspace:provision" + input.context.mode == "inject" + not common.inject_role in input.subject.roles +} + +# inject-mode workspace:create is evaluated against the target owner's +# roles, not the acting subject's — this lets a -admin create an +# inject-mode workspace on behalf of a managed user based on that user's own +# standing, rather than the admin's; standalone workspace:create is +# unaffected and continues to be governed solely by the owner-scoped rules +# above +deny if { + input.action == "workspace:create" + input.context.mode == "inject" + owner := enrich.user(input.resource.attributes.owner) + not common.inject_role in owner.roles +} + +# --- git-source provisioning/creation --- + +# git-source provisioning is restricted to users holding the "git-workspace" +# role — same role common.onboarded_via_git_idp gates repo-catalog access +# behind, since a context.source == "git" request supplies an ad hoc +# blueprint from that same repo catalog. Applies regardless of ownership or +# admin status, same as the inject-mode checks above. +deny if { + input.action == "workspace:provision" + input.context.source == "git" + not common.git_workspace_role in input.subject.roles +} + +# workspace:create's source check is evaluated against the target owner, not +# the acting subject — same as the inject-mode workspace:create checks +# above, since the resulting workspace (and its git access) belongs to that +# owner, not necessarily to a -admin creating on their behalf +deny if { + input.action == "workspace:create" + input.context.source == "git" + owner := enrich.user(input.resource.attributes.owner) + not common.git_workspace_role in owner.roles +} + +# --- catalog-source provisioning --- + +# standalone catalog-source provisioning is restricted to blueprints the +# owner is actually assigned (enrich.user(...).blueprints) — inject mode is +# exempt because there the blueprint name is derived from the target repo, +# not picked from the catalog, and can never appear in a user's assigned +# blueprint list. A "*" entry (assigned to e.g. admins, see +# usermap-template.yaml) means the owner is assigned every blueprint. +deny if { + input.action == "workspace:provision" + input.context.mode == "standalone" + input.context.source == "catalog" + parsed_blueprint := yaml.unmarshal(input.context.blueprint) + owner := enrich.user(input.resource.attributes.owner) + not parsed_blueprint.metadata.name in owner.blueprints + not "*" in owner.blueprints +} + +# --- workspace:provision obligations --- + +# non-privileged for plain users; full admins and org-admins are exempt +obligations["patch:/securityContext/privileged"] := false if { + input.action == "workspace:provision" + not common.is_admin(input.subject) + not common.is_org_admin(input.subject) +} \ No newline at end of file diff --git a/k8shell/files/policies/workspace_list.rego b/k8shell/files/policies/workspace_list.rego new file mode 100644 index 0000000..61ef445 --- /dev/null +++ b/k8shell/files/policies/workspace_list.rego @@ -0,0 +1,69 @@ +package workspace + +import rego.v1 +import data.common + +# a -admin can list workspaces of users with role -user, for +# every group they administer (scoped via the "roles" obligation below); when +# checked against a specific resource (e.g. a capability check), that +# resource's owner must resolve to an actual managed -user account — +# a nonexistent or unmanaged owner must not pass +allow if { + input.action == "workspace:list" + count(common.group_admin_roles(input.subject.roles)) > 0 + not input.resource.attributes.owner +} + +allow if { + input.action == "workspace:list" + owner := input.resource.attributes.owner + owner + common.managed_by_group_admin(input.subject, enrich.user(owner)) +} + +# a user who is not a group admin can list only their own workspaces when no +# specific owner is requested (scoped via the "username" obligation below) +allow if { + input.action == "workspace:list" + count(common.group_admin_roles(input.subject.roles)) == 0 + not input.resource.attributes.owner +} + +# a subject can always list their own workspaces, regardless of any +# -admin role they also hold — a -admin's own account is never +# a "managed" account (common.managed_by_group_admin requires the target to +# hold the matching "-user" role), so without this rule a -admin's +# self-owned capability check would fall through every rule above and deny +allow if { + input.action == "workspace:list" + input.resource.attributes.owner == input.subject.username +} + +# --- workspace:list obligations --- + +# a -admin's listing is scoped to -admin and -user +# accounts, for every group they administer; an org-admin sees every role +# within their organization and is left unscoped here +obligations["roles"] := scoped_roles if { + input.action == "workspace:list" + admin_roles := common.group_admin_roles(input.subject.roles) + count(admin_roles) > 0 + not common.is_org_admin(input.subject) + scoped_roles := admin_roles | {managed_role | + some admin_role in admin_roles + managed_role := sprintf("%s-user", [trim_suffix(admin_role, "-admin")]) + } +} + +# a non-admin's listing is always scoped to their own organization +obligations["org"] := input.subject.org if { + input.action == "workspace:list" + not common.is_admin(input.subject) +} + +# a non-group-admin's listing is scoped to their own workspaces only +obligations["username"] := input.subject.username if { + input.action == "workspace:list" + count(common.group_admin_roles(input.subject.roles)) == 0 + not common.is_admin(input.subject) +} diff --git a/k8shell/policy-tests/git_test.rego b/k8shell/policy-tests/git_test.rego new file mode 100644 index 0000000..0af808e --- /dev/null +++ b/k8shell/policy-tests/git_test.rego @@ -0,0 +1,85 @@ +package git_test + +import rego.v1 + +# a request bound to workspace, owned by owner ("" workspace = unbound, no owner) +git_req(action, username, roles, workspace, owner) := { + "action": action, + "subject": {"username": username, "roles": roles, "org": "default"}, + "resource": {"type": "repo", "id": "github.com/acme/app", "attributes": {"host": "github.com"}}, + "context": {"workspace": workspace, "workspace_owner": owner}, +} if workspace != "" + +git_req(action, username, roles, "", _) := { + "action": action, + "subject": {"username": username, "roles": roles, "org": "default"}, + "resource": {"type": "repo", "id": "github.com/acme/app", "attributes": {"host": "github.com"}}, + "context": {"workspace": ""}, +} + +# a request from the subject's own workspace +git_input(action, username, roles, workspace) := git_req(action, username, roles, workspace, username) + +git_allowed(inp) if { + data.git.allow with input as inp + not data.git.deny with input as inp +} + +test_user_fetches_from_own_workspace if git_allowed(git_input("git:fetch", "alice", [], "alice-ws")) + +test_user_pushes_from_own_workspace if git_allowed(git_input("git:push", "alice", [], "alice-ws")) + +test_unbound_request_denied if { + not git_allowed(git_input("git:fetch", "alice", [], "")) + not git_allowed(git_input("git:push", "alice", [], "")) +} + +test_missing_workspace_denied if { + inp := object.remove(git_input("git:push", "alice", [], "x"), ["context"]) + not git_allowed(inp) +} + +test_other_users_workspace_denied if { + not git_allowed(git_req("git:fetch", "alice", [], "carol-ws", "carol")) + not git_allowed(git_req("git:push", "alice", [], "carol-ws", "carol")) +} + +test_admin_from_other_users_workspace_denied if { + not git_allowed(git_req("git:fetch", "root", ["admin"], "alice-ws", "alice")) + not git_allowed(git_req("git:push", "root", ["admin"], "alice-ws", "alice")) +} + +test_org_admin_from_managed_users_workspace_denied if not git_allowed(git_req("git:push", "orga", ["org-admin", "developer-admin"], "alice-ws", "alice")) + +test_workspace_without_owner_denied if { + inp := object.remove(git_input("git:fetch", "alice", [], "alice-ws"), ["context"]) + not git_allowed(object.union(inp, {"context": {"workspace": "alice-ws"}})) +} + +test_empty_username_denied if not git_allowed(git_req("git:fetch", "", [], "ws", "")) + +test_admin_from_own_workspace_allowed if git_allowed(git_input("git:push", "root", ["admin"], "root-ws")) + +test_admin_without_own_workspace_denied if { + not git_allowed(git_input("git:fetch", "root", ["admin"], "")) + not git_allowed(git_input("git:push", "root", ["admin"], "")) +} + +test_group_admin_without_own_workspace_denied if not git_allowed(git_input("git:push", "bob", ["developer-admin", "org-admin"], "")) + +test_wrong_resource_type_denied if { + inp := object.union(git_input("git:fetch", "alice", [], "alice-ws"), {"resource": {"type": "workspace", "id": "alice-ws"}}) + not git_allowed(inp) +} + +test_empty_repo_id_denied if { + inp := object.union(git_input("git:fetch", "alice", [], "alice-ws"), {"resource": {"id": ""}}) + not git_allowed(inp) +} + +test_other_action_denied if not git_allowed(git_input("git:delete", "alice", [], "alice-ws")) + +test_no_obligations if { + inp := git_input("git:push", "alice", [], "alice-ws") + not data.git.obligations with input as inp +} diff --git a/k8shell/policy-tests/org_test.rego b/k8shell/policy-tests/org_test.rego new file mode 100644 index 0000000..1b0ffa9 --- /dev/null +++ b/k8shell/policy-tests/org_test.rego @@ -0,0 +1,22 @@ +package org_test + +import rego.v1 +import data.org + +node_write(subject) := { + "action": "org:node:write", + "resource": {"type": "org", "id": "default"}, + "subject": subject, +} + +test_admin_node_write_allowed if { + org.allow with input as node_write({"username": "a", "roles": ["admin"]}) +} + +test_org_admin_node_write_denied if { + not org.allow with input as node_write({"username": "o", "org": "default", "roles": ["org-admin"]}) +} + +test_user_node_write_denied if { + not org.allow with input as node_write({"username": "u", "org": "default", "roles": ["developer"]}) +} diff --git a/k8shell/policy-tests/run.sh b/k8shell/policy-tests/run.sh new file mode 100755 index 0000000..db57c84 --- /dev/null +++ b/k8shell/policy-tests/run.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Runs the Rego policy tests against the chart's default policies +# (files/policies). enrich.user is a custom builtin provided by the authz +# service, so it is declared in a generated capabilities file and mocked in the +# tests with `with enrich.user as ...`. +# Needs opa and jq; set OPA to the opa binary if it isn't on PATH. +# Extra arguments go to opa test (e.g. -v). +set -euo pipefail + +OPA="${OPA:-opa}" +here="$(cd "$(dirname "$0")" && pwd)" +chart="$(dirname "$here")" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +"$OPA" capabilities --current \ + | jq '.builtins += [{"name": "enrich.user", "decl": {"type": "function", "args": [{"type": "string"}], "result": {"type": "any"}}}]' \ + > "$tmp/capabilities.json" + +"$OPA" test --capabilities "$tmp/capabilities.json" "$chart/files/policies" "$here" "$@" diff --git a/k8shell/policy-tests/session_recording_override_test.rego b/k8shell/policy-tests/session_recording_override_test.rego new file mode 100644 index 0000000..ef1cb49 --- /dev/null +++ b/k8shell/policy-tests/session_recording_override_test.rego @@ -0,0 +1,79 @@ +package session_test + +import rego.v1 + +# fixtures (users, mock_enrich_user, session_allowed) live in session_test.rego; +# rec_user/rec_subject/rec_enrich in session_recording_test.rego + +override_input(who, owner) := { + "action": "session:recording:override", + "subject": rec_subject(who), + "resource": {"type": "workspace", "id": "ws1", "attributes": {"owner": owner}}, + "context": {}, +} + +override_probe(who, owner) := { + "action": "session:recording:override", + "subject": rec_subject(who), + "resource": {"type": "workspace", "attributes": {"owner": owner}}, + "context": {}, +} + +override_allowed(inp) if { + data.session.allow with input as inp with enrich.user as rec_enrich + not data.session.deny with input as inp with enrich.user as rec_enrich +} + +test_override_plain_user_cannot_override_own if not override_allowed(override_input("alice", "alice")) + +test_override_plain_user_cannot_override_other if not override_allowed(override_input("alice", "carol")) + +test_override_group_admin_overrides_group_user if { + override_allowed(override_input("bob", "alice")) + override_allowed(override_probe("bob", "alice")) +} + +test_override_group_admin_cannot_override_other_group if not override_allowed(override_input("bob", "gina")) + +test_override_group_admin_cannot_override_other_org if not override_allowed(override_input("bob", "carol")) + +test_override_group_admin_cannot_override_site_admin if not override_allowed(override_input("bob", "root")) + +test_override_group_admin_cannot_override_own if not override_allowed(override_input("bob", "bob")) + +test_override_org_admin_overrides_any_group_in_org if { + override_allowed(override_input("orga", "alice")) + override_allowed(override_input("orga", "gina")) + override_allowed(override_input("orga", "bob")) + override_allowed(override_probe("orga", "gina")) +} + +test_override_org_admin_overrides_own if { + override_allowed(override_input("orga", "orga")) + override_allowed(override_probe("orga", "orga")) +} + +test_override_org_admin_cannot_override_other_org if not override_allowed(override_input("orga", "carol")) + +test_override_org_admin_cannot_override_site_admin if not override_allowed(override_input("orga", "root")) + +test_override_admin_overrides_everything if { + override_allowed(override_input("root", "carol")) + override_allowed(override_input("root", "root")) + override_allowed(override_probe("root", "carol")) +} + +test_override_no_obligations if { + inp := override_input("bob", "alice") + data.session.obligations == {} with input as inp with enrich.user as rec_enrich +} + +test_override_session_recorder_overrides_own if { + override_allowed(override_input("rita", "rita")) + override_allowed(override_probe("rita", "rita")) +} + +test_override_session_recorder_cannot_override_other if { + not override_allowed(override_input("rita", "alice")) + not override_allowed(override_input("rita", "carol")) +} diff --git a/k8shell/policy-tests/session_recording_test.rego b/k8shell/policy-tests/session_recording_test.rego new file mode 100644 index 0000000..6fd0ce5 --- /dev/null +++ b/k8shell/policy-tests/session_recording_test.rego @@ -0,0 +1,93 @@ +package session_test + +import rego.v1 + +# fixtures (users, subject, mock_enrich_user, session_allowed) live in session_test.rego + +rec_users := { + "orga": {"username": "orga", "organization": "acme", "roles": ["org-admin"]}, + "gina": {"username": "gina", "organization": "acme", "roles": ["ops-user"]}, + "rita": {"username": "rita", "organization": "acme", "roles": ["dev-user", "session-recorder"]}, +} + +rec_user(name) := object.union(users, rec_users)[name] + +rec_subject(name) := { + "username": name, + "org": rec_user(name).organization, + "roles": rec_user(name).roles, +} + +rec_enrich(name) := rec_user(name) + +rec_input(who, owner) := { + "action": "session:recording:read", + "subject": rec_subject(who), + "resource": {"type": "workspace", "attributes": {"owner": owner}}, + "context": {}, +} + +rec_input_any(who) := { + "action": "session:recording:read", + "subject": rec_subject(who), + "resource": {"type": "workspace", "attributes": {}}, + "context": {}, +} + +rec_allowed(inp) if data.session.allow with input as inp with enrich.user as rec_enrich + +test_recording_plain_user_cannot_read_own if not rec_allowed(rec_input("alice", "alice")) + +test_recording_plain_user_cannot_read_other if not rec_allowed(rec_input("alice", "carol")) + +test_recording_plain_user_cannot_list_any if not rec_allowed(rec_input_any("alice")) + +test_recording_group_admin_reads_group_user if rec_allowed(rec_input("bob", "alice")) + +test_recording_group_admin_cannot_read_other_group if not rec_allowed(rec_input("bob", "gina")) + +test_recording_group_admin_cannot_read_other_org if not rec_allowed(rec_input("bob", "carol")) + +test_recording_group_admin_cannot_read_site_admin if not rec_allowed(rec_input("bob", "root")) + +test_recording_group_admin_reads_own if rec_allowed(rec_input("bob", "bob")) + +test_recording_group_admin_scoped_by_roles if { + inp := rec_input_any("bob") + data.session.obligations == {"org": "acme", "roles": {"dev-admin", "dev-user"}} with input as inp +} + +test_recording_org_admin_reads_any_group_in_org if { + rec_allowed(rec_input("orga", "alice")) + rec_allowed(rec_input("orga", "gina")) +} + +test_recording_org_admin_cannot_read_other_org if not rec_allowed(rec_input("orga", "carol")) + +test_recording_org_admin_scoped_by_org_only if { + inp := rec_input_any("orga") + data.session.obligations == {"org": "acme"} with input as inp +} + +test_recording_admin_reads_everything if { + rec_allowed(rec_input("root", "carol")) + rec_allowed(rec_input_any("root")) +} + +test_recording_admin_unscoped if { + inp := rec_input_any("root") + data.session.obligations == {} with input as inp +} + +test_recording_session_recorder_reads_own if rec_allowed(rec_input("rita", "rita")) + +test_recording_session_recorder_cannot_read_other if { + not rec_allowed(rec_input("rita", "alice")) + not rec_allowed(rec_input("rita", "carol")) +} + +test_recording_session_recorder_lists_scoped_to_own if { + inp := rec_input_any("rita") + rec_allowed(inp) + data.session.obligations == {"org": "acme", "username": "rita"} with input as inp +} diff --git a/k8shell/policy-tests/session_test.rego b/k8shell/policy-tests/session_test.rego new file mode 100644 index 0000000..c7727d8 --- /dev/null +++ b/k8shell/policy-tests/session_test.rego @@ -0,0 +1,201 @@ +package session_test + +import rego.v1 + +# --- fixtures --- + +users := { + "alice": {"username": "alice", "organization": "acme", "roles": ["dev-user"]}, + "bob": {"username": "bob", "organization": "acme", "roles": ["dev-admin"]}, + "carol": {"username": "carol", "organization": "other", "roles": ["dev-user"]}, + "root": {"username": "root", "organization": "acme", "roles": ["admin"]}, + "dave": {"username": "dave", "organization": "acme", "roles": ["dev-user", + "record-shell", "record-tcpip", "record-exec", "record-sftp"]}, + "erin": {"username": "erin", "organization": "acme", "roles": ["dev-user", "record-shell"]}, + "auditor": {"username": "auditor", "organization": "acme", "roles": ["admin", "record-exec"]}, + "frank": {"username": "frank", "organization": "tul-fm", "roles": ["dev-user"]}, +} + +subject(name) := { + "username": name, + "org": users[name].organization, + "roles": users[name].roles, +} + +mock_enrich_user(name) := users[name] + +record_input(action, who, owner, session_type, session_source) := { + "action": action, + "subject": subject(who), + "resource": {"type": "workspace", "id": "ws1", "attributes": {"owner": owner, "blueprint": "default"}}, + "context": {"session_type": session_type, "session_source": session_source}, +} + +entry_input(action, who, owner) := { + "action": action, + "subject": subject(who), + "resource": {"type": "workspace", "id": "ws1", "attributes": {"owner": owner}}, + "context": {}, +} + +# every session_type/session_source combination the contract allows +record_cases := {[t, s] | + some t in {"shell", "tcpip", "exec", "sftp"} + some s in {"ssh-proxy", "api-server"} +} + +ssh_entry_actions := {"ssh:shell", "ssh:exec", "ssh:sftp", "ssh:direct-tcpip", + "ssh:direct-streamlocal", "ssh:agent-forward"} + +# a decision is allowed when allow holds and no deny fires, as the authz +# service evaluates it +session_allowed(inp) if { + data.session.allow with input as inp with enrich.user as mock_enrich_user + not data.session.deny with input as inp with enrich.user as mock_enrich_user +} + +ssh_allowed(inp) if { + data.ssh.allow with input as inp + not data.ssh.deny with input as inp +} + +workspace_allowed(inp) if { + data.workspace.allow with input as inp with enrich.user as mock_enrich_user + not data.workspace.deny with input as inp with enrich.user as mock_enrich_user +} + +record_obligation(inp) := ob if { + ob := data.session.obligations.record with input as inp with enrich.user as mock_enrich_user +} + +# --- record obligation --- + +expected_channels := {"shell": "shell", "tcpip": "direct-tcpip,vscode-terminals,vscode-input", "exec": "exec", "sftp": "sftp"} + +test_record_obligation_records_channel_with_matching_role if { + every c in record_cases { + record_obligation(record_input("session:record", "dave", "alice", c[0], c[1])) == expected_channels[c[0]] + } +} + +test_record_obligation_none_without_any_record_role if { + every who in {"alice", "bob", "carol", "root"} { + every c in record_cases { + record_obligation(record_input("session:record", who, "alice", c[0], c[1])) == "none" + } + } +} + +# a record- role covers only that session_type +test_record_obligation_only_for_session_type_of_held_role if { + every c in record_cases { + expected := {true: "shell", false: "none"}[c[0] == "shell"] + record_obligation(record_input("session:record", "erin", "alice", c[0], c[1])) == expected + } +} + +# admin status neither forces nor suppresses recording; only the role counts +test_record_obligation_admin_with_record_role if { + record_obligation(record_input("session:record", "auditor", "alice", "exec", "ssh-proxy")) == "exec" + record_obligation(record_input("session:record", "auditor", "alice", "shell", "ssh-proxy")) == "none" +} + +# --- session:record never gates access for a valid request --- + +test_session_record_allowed_for_any_valid_request if { + every who in object.keys(users) { + every c in record_cases { + session_allowed(record_input("session:record", who, "alice", c[0], c[1])) + } + } +} + +# --- malformed session:record input is rejected --- + +test_session_record_unknown_session_type_rejected if { + every who in {"alice", "root"} { + not session_allowed(record_input("session:record", who, "alice", "x11", "api-server")) + } +} + +test_session_record_unknown_session_source_rejected if { + every who in {"alice", "root"} { + not session_allowed(record_input("session:record", who, "alice", "shell", "browser")) + } +} + +test_session_record_missing_id_rejected if { + inp := json.remove(record_input("session:record", "alice", "alice", "shell", "api-server"), ["resource/id"]) + not session_allowed(inp) +} + +test_session_record_missing_owner_rejected if { + inp := json.remove(record_input("session:record", "alice", "alice", "shell", "api-server"), ["resource/attributes/owner"]) + not session_allowed(inp) +} + +test_session_record_non_workspace_resource_rejected if { + inp := json.patch(record_input("session:record", "alice", "alice", "shell", "api-server"), + [{"op": "replace", "path": "/resource/type", "value": "user"}]) + not session_allowed(inp) +} + +# --- access is gated at the entry rules, not session:record --- + +test_unrelated_user_denied_at_ssh_entry_rules if { + every action in ssh_entry_actions { + not ssh_allowed(entry_input(action, "carol", "alice")) + } +} + +test_unrelated_user_denied_at_workspace_connect if { + not workspace_allowed(entry_input("workspace:connect", "carol", "alice")) +} + +test_owner_allowed_at_entry_rules if { + every action in ssh_entry_actions { + ssh_allowed(entry_input(action, "alice", "alice")) + } + workspace_allowed(entry_input("workspace:connect", "alice", "alice")) +} + +test_group_admin_allowed_at_workspace_connect if { + workspace_allowed(entry_input("workspace:connect", "bob", "alice")) +} + +# ssh:* admits only admins and owners — a -admin can reach a managed +# user's workspace via workspace:connect but not over ssh +test_group_admin_denied_at_ssh_entry_rules if { + every action in ssh_entry_actions { + not ssh_allowed(entry_input(action, "bob", "alice")) + } +} + +# --- record_rules: recording by org and blueprint --- + +with_blueprint(inp, bp) := json.patch(inp, [{"op": "replace", "path": "/resource/attributes/blueprint", "value": bp}]) + +test_record_obligation_org_blueprint_rule if { + every c in record_cases { + inp := with_blueprint(record_input("session:record", "frank", "frank", c[0], c[1]), "ct1") + record_obligation(inp) == expected_channels[c[0]] + } +} + +test_record_obligation_org_rule_other_blueprint if { + every c in record_cases { + record_obligation(record_input("session:record", "frank", "frank", c[0], c[1])) == "none" + } +} + +test_record_obligation_org_rule_missing_blueprint if { + inp := json.remove(record_input("session:record", "frank", "frank", "shell", "ssh-proxy"), ["resource/attributes/blueprint"]) + record_obligation(inp) == "none" +} + +test_record_obligation_blueprint_rule_other_org if { + every c in record_cases { + inp := with_blueprint(record_input("session:record", "alice", "alice", c[0], c[1]), "ct1") + record_obligation(inp) == "none" + } +} diff --git a/k8shell/policy-tests/threat_test.rego b/k8shell/policy-tests/threat_test.rego new file mode 100644 index 0000000..762b081 --- /dev/null +++ b/k8shell/policy-tests/threat_test.rego @@ -0,0 +1,401 @@ +package threat_test + +import rego.v1 + +# --- fixtures --- + +users := { + "alice": {"username": "alice", "organization": "acme", "roles": ["dev-user"]}, + "bob": {"username": "bob", "organization": "acme", "roles": ["dev-admin"]}, + "carol": {"username": "carol", "organization": "other", "roles": ["dev-user"]}, + "gina": {"username": "gina", "organization": "acme", "roles": ["ops-user"]}, + "orga": {"username": "orga", "organization": "acme", "roles": ["org-admin"]}, + "root": {"username": "root", "organization": "acme", "roles": ["admin"]}, + "dave": {"username": "dave", "organization": "acme", "roles": ["dev-user", "detect-all"]}, + "erin": {"username": "erin", "organization": "acme", "roles": ["dev-user", "detect-exfil", "detect-crypto"]}, + "sam": {"username": "sam", "organization": "acme", "roles": ["dev-user"], "sudo": true}, +} + +subject(name) := { + "username": name, + "org": users[name].organization, + "roles": users[name].roles, +} + +mock_enrich_user(name) := users[name] + +detect_input(who) := { + "action": "threat:detect", + "subject": subject(who), + "resource": {"type": "workspace", "id": "ws1", "attributes": {"owner": who, "blueprint": "default"}}, + "context": {"mode": "standalone", "namespace": "workspaces"}, +} + +inject_input(who) := json.patch(detect_input(who), [{"op": "replace", "path": "/context", "value": { + "mode": "inject", "namespace": "app", "workload_name": "web", "workload_kind": "Deployment", +}}]) + +override_input(who, owner) := { + "action": "threat:detection:override", + "subject": subject(who), + "resource": {"type": "workspace", "id": "ws1", "attributes": {"owner": owner}}, + "context": {}, +} + +override_probe(who, owner) := json.remove(override_input(who, owner), ["resource/id"]) + +# a decision is allowed when allow holds and no deny fires, as the authz +# service evaluates it +threat_allowed(inp) if { + data.threat.allow with input as inp with enrich.user as mock_enrich_user + not data.threat.deny with input as inp with enrich.user as mock_enrich_user +} + +detect_obligation(inp) := ob if { + ob := data.threat.obligations.detect with input as inp with enrich.user as mock_enrich_user +} + +# --- detect obligation --- + +test_detect_none_by_default if { + every who in {"alice", "bob", "orga", "root"} { + detect_obligation(detect_input(who)) == "none" + detect_obligation(inject_input(who)) == "none" + } +} + +test_detect_all_with_detect_all_role if detect_obligation(detect_input("dave")) == "all" + +test_detect_categories_from_roles if detect_obligation(detect_input("erin")) == "crypto,exfil" + +test_detect_rule_by_org_and_blueprint if { + rules := [{"org": "acme", "blueprint": "default", "categories": {"exfil"}}] + data.threat.obligations.detect == "exfil" with input as detect_input("alice") with data.threat.detect_rules as rules with enrich.user as mock_enrich_user + data.threat.obligations.detect == "none" with input as detect_input("carol") with data.threat.detect_rules as rules with enrich.user as mock_enrich_user +} + +test_detect_rule_all_wins if { + rules := [{"org": "acme", "blueprint": "default", "categories": {"all"}}] + data.threat.obligations.detect == "all" with input as detect_input("erin") with data.threat.detect_rules as rules with enrich.user as mock_enrich_user +} + +# --- detect from rendered workspace resources --- + +plain_pod := { + "apiVersion": "v1", + "kind": "Pod", + "metadata": {"name": "alice-85a782e", "namespace": "workspaces"}, + "spec": { + "containers": [{"name": "workspace", "image": "ws:latest", "securityContext": {"runAsUser": 1000}}], + "initContainers": [{"name": "init", "image": "k8shelld:latest"}], + "volumes": [{"name": "home", "persistentVolumeClaim": {"claimName": "alice-home"}}], + }, +} + +plain_netpol := { + "apiVersion": "networking.k8s.io/v1", + "kind": "NetworkPolicy", + "metadata": {"name": "alice-85a782e"}, + "spec": {"podSelector": {}, "egress": [{"to": [{"ipBlock": {"cidr": "10.0.0.0/8"}}]}]}, +} + +plain_configmap := {"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "alice-85a782e-init"}} + +# the rendered chart of a plain workspace, keyed "Kind/name" +plain_resources := { + "Pod/alice-85a782e": plain_pod, + "NetworkPolicy/alice-85a782e": plain_netpol, + "ConfigMap/alice-85a782e-init": plain_configmap, +} + +# detect_input(who) with resources as context.resources +resources_input(who, resources) := json.patch(detect_input(who), [{ + "op": "add", "path": "/context/resources", "value": json.marshal(resources), +}]) + +# detect_input(who) rendering plain_resources with the pod patched with ops +pod_input(who, ops) := resources_input(who, json.patch(plain_resources, [ + {"op": "replace", "path": "/Pod~1alice-85a782e", "value": json.patch(plain_pod, ops)}, +])) + +classes(inp) := cls if { + cls := data.threat.detection_classes with input as inp with enrich.user as mock_enrich_user +} + +test_detect_plain_pod_has_no_class if { + classes(pod_input("alice", [])) == set() + detect_obligation(pod_input("alice", [])) == "none" +} + +test_detect_resources_absent_has_no_class if { + classes(detect_input("alice")) == set() + detect_obligation(detect_input("alice")) == "none" + detect_obligation(detect_input("dave")) == "all" +} + +test_detect_privileged_container if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/containers/0/securityContext/privileged", "value": true}]) + classes(inp) == {"privileged"} + detect_obligation(inp) == "container-escape,privilege-escalation-and-kernel" +} + +test_detect_privileged_init_container if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/initContainers/0/securityContext", "value": {"privileged": true}}]) + classes(inp) == {"privileged"} +} + +test_detect_privileged_false_is_no_class if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/containers/0/securityContext/privileged", "value": false}]) + classes(inp) == set() +} + +test_detect_kernel_capability if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/containers/0/securityContext/capabilities", "value": {"add": ["NET_BIND_SERVICE", "SYS_ADMIN"]}}]) + classes(inp) == {"privileged"} + benign := pod_input("alice", [{"op": "add", "path": "/spec/containers/0/securityContext/capabilities", "value": {"add": ["NET_BIND_SERVICE"]}}]) + classes(benign) == set() +} + +test_detect_host_namespaces if { + every field in {"hostPID", "hostIPC"} { + inp := pod_input("alice", [{"op": "add", "path": concat("", ["/spec/", field]), "value": true}]) + classes(inp) == {"host-namespaces"} + detect_obligation(inp) == "container-escape,privilege-escalation-and-kernel" + } +} + +test_detect_host_network if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/hostNetwork", "value": true}]) + classes(inp) == {"host-network"} +} + +test_detect_host_path if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/volumes/-", "value": {"name": "sock", "hostPath": {"path": "/var/run"}}}]) + classes(inp) == {"host-path"} +} + +test_detect_root_pod_is_no_class if { + # k8shelld always runs as root, so runAsUser 0 alone classifies nothing + inp := pod_input("alice", [{"op": "replace", "path": "/spec/containers/0/securityContext/runAsUser", "value": 0}]) + classes(inp) == set() +} + +test_detect_sudo_owner if { + classes(pod_input("sam", [])) == {"sudo"} + detect_obligation(pod_input("sam", [])) == "privilege-escalation-and-kernel" + # without resources too: sudo comes from the owner's account + detect_obligation(detect_input("sam")) == "privilege-escalation-and-kernel" +} + +test_detect_sudo_is_the_owners_not_the_subjects if { + # root provisions for sam: sam's sudo counts + for_sam := json.patch(pod_input("root", []), [{"op": "replace", "path": "/resource/attributes/owner", "value": "sam"}]) + classes(for_sam) == {"sudo"} + # sam provisions for alice: sam's sudo does not + for_alice := json.patch(pod_input("sam", []), [{"op": "replace", "path": "/resource/attributes/owner", "value": "alice"}]) + classes(for_alice) == set() +} + +test_detect_cluster_access if { + binding := {"kind": "RoleBinding", "metadata": {"name": "alice"}, "roleRef": {"kind": "Role", "name": "edit"}} + inp := resources_input("alice", object.union(plain_resources, {"RoleBinding/alice": binding})) + classes(inp) == {"cluster-access"} +} + +test_detect_open_egress if { + netpol := json.patch(plain_netpol, [{"op": "add", "path": "/spec/egress/-", "value": {"to": [{"ipBlock": {"cidr": "0.0.0.0/0"}}]}}]) + inp := resources_input("alice", object.union(plain_resources, {"NetworkPolicy/alice-85a782e": netpol})) + classes(inp) == {"open-egress"} +} + +test_detect_kind_limits_condition if { + # a ConfigMap carrying a pod-like field does not match a Pod condition + cm := object.union(plain_configmap, {"spec": {"hostPID": true}}) + inp := resources_input("alice", object.union(plain_resources, {"ConfigMap/alice-85a782e-init": cm})) + classes(inp) == set() +} + +test_detect_classes_combine_with_roles if { + inp := pod_input("erin", [{"op": "add", "path": "/spec/hostNetwork", "value": true}]) + detect_obligation(inp) == "container-escape,crypto,exfil,lateral-movement-and-network" +} + +test_detect_all_condition if { + cls := {"privileged-host-network": { + "all": [ + {"kind": "Pod", "path": "spec.hostNetwork", "equals": true}, + {"kind": "Pod", "path": "spec.containers.*.securityContext.privileged", "equals": true}, + ], + "categories": {"all"}, + }} + net := pod_input("alice", [{"op": "add", "path": "/spec/hostNetwork", "value": true}]) + data.threat.obligations.detect == "none" with input as net with data.threat.detect_classes as cls with enrich.user as mock_enrich_user + both := pod_input("alice", [ + {"op": "add", "path": "/spec/hostNetwork", "value": true}, + {"op": "add", "path": "/spec/containers/0/securityContext/privileged", "value": true}, + ]) + data.threat.obligations.detect == "all" with input as both with data.threat.detect_classes as cls with enrich.user as mock_enrich_user +} + +test_detect_prefix_condition if { + cls := {"untrusted-image": {"any": [{"kind": "Pod", "path": "spec.containers.*.image", "prefix": "docker.io/"}], "categories": {"cryptomining"}}} + inp := pod_input("alice", [{"op": "replace", "path": "/spec/containers/0/image", "value": "docker.io/foo:1"}]) + data.threat.obligations.detect == "cryptomining" with input as inp with data.threat.detect_classes as cls with enrich.user as mock_enrich_user + data.threat.obligations.detect == "none" with input as pod_input("alice", []) with data.threat.detect_classes as cls with enrich.user as mock_enrich_user +} + +test_detect_rule_by_class if { + rules := [{"org": "acme", "class": "host-network", "categories": {"all"}}] + inp := pod_input("alice", [{"op": "add", "path": "/spec/hostNetwork", "value": true}]) + data.threat.obligations.detect == "all" with input as inp with data.threat.detect_rules as rules with enrich.user as mock_enrich_user + data.threat.obligations.detect == "none" with input as pod_input("alice", []) with data.threat.detect_rules as rules with enrich.user as mock_enrich_user +} + +test_detect_undecodable_resources_has_no_class if { + inp := json.patch(detect_input("alice"), [{"op": "add", "path": "/context/resources", "value": "{not json"}]) + classes(inp) == set() + threat_allowed(inp) +} + +# --- threat:detect never gates access for a valid request --- + +test_detect_allowed_for_any_valid_request if { + every who in {"alice", "bob", "carol", "root"} { + threat_allowed(detect_input(who)) + threat_allowed(inject_input(who)) + } +} + +# --- malformed threat:detect input is rejected --- + +test_detect_unknown_mode_rejected if { + inp := json.patch(detect_input("root"), [{"op": "replace", "path": "/context/mode", "value": "sidecar"}]) + not threat_allowed(inp) +} + +test_detect_missing_namespace_rejected if not threat_allowed(json.remove(detect_input("root"), ["context/namespace"])) + +test_detect_inject_missing_workload_rejected if { + not threat_allowed(json.remove(inject_input("root"), ["context/workload_name"])) + not threat_allowed(json.remove(inject_input("root"), ["context/workload_kind"])) +} + +test_detect_missing_id_rejected if not threat_allowed(json.remove(detect_input("alice"), ["resource/id"])) + +test_detect_missing_owner_rejected if not threat_allowed(json.remove(detect_input("alice"), ["resource/attributes/owner"])) + +test_detect_non_workspace_resource_rejected if { + inp := json.patch(detect_input("alice"), [{"op": "replace", "path": "/resource/type", "value": "user"}]) + not threat_allowed(inp) +} + +# --- threat:detection:override --- + +test_override_plain_user_cannot_override_own if not threat_allowed(override_input("alice", "alice")) + +test_override_plain_user_cannot_override_other if not threat_allowed(override_input("alice", "carol")) + +test_override_detect_role_does_not_grant_override if not threat_allowed(override_input("dave", "alice")) + +test_override_group_admin_overrides_group_user if { + threat_allowed(override_input("bob", "alice")) + threat_allowed(override_probe("bob", "alice")) +} + +test_override_group_admin_cannot_override_other_group if not threat_allowed(override_input("bob", "gina")) + +test_override_group_admin_cannot_override_other_org if not threat_allowed(override_input("bob", "carol")) + +test_override_group_admin_cannot_override_site_admin if not threat_allowed(override_input("bob", "root")) + +test_override_group_admin_cannot_override_own if not threat_allowed(override_input("bob", "bob")) + +test_override_org_admin_overrides_any_group_in_org if { + threat_allowed(override_input("orga", "alice")) + threat_allowed(override_input("orga", "gina")) + threat_allowed(override_input("orga", "bob")) + threat_allowed(override_probe("orga", "gina")) +} + +test_override_org_admin_overrides_own if { + threat_allowed(override_input("orga", "orga")) + threat_allowed(override_probe("orga", "orga")) +} + +test_override_org_admin_cannot_override_other_org if not threat_allowed(override_input("orga", "carol")) + +test_override_admin_overrides_everything if { + threat_allowed(override_input("root", "carol")) + threat_allowed(override_input("root", "root")) + threat_allowed(override_probe("root", "carol")) +} + +test_override_no_obligations if { + inp := override_input("bob", "alice") + data.threat.obligations == {} with input as inp with enrich.user as mock_enrich_user +} + +# --- detect reason --- + +detect_reason(inp) := r if { + r := data.threat.reason with input as inp with enrich.user as mock_enrich_user +} + +test_detect_reason_is_not_an_obligation if { + not "detect_reason" in object.keys(data.threat.obligations) with input as detect_input("erin") with enrich.user as mock_enrich_user +} + +test_detect_reason_nothing_matched if { + detect_reason(pod_input("alice", [])) == "no detect role, rule or class matched" +} + +test_detect_reason_roles if detect_reason(detect_input("erin")) == "role detect-crypto; role detect-exfil" + +test_detect_reason_class_names_matched_condition if { + inp := pod_input("alice", [{"op": "add", "path": "/spec/containers/0/securityContext/privileged", "value": true}]) + detect_reason(inp) == `class privileged: container-escape,privilege-escalation-and-kernel ({"equals":true,"kind":"Pod","path":"spec.containers|initContainers.*.securityContext.privileged"})` +} + +test_detect_reason_sudo if { + detect_reason(pod_input("sam", [])) == "class sudo: privilege-escalation-and-kernel (owner sam has sudo)" +} + +test_detect_reason_rule if { + rules := [{"org": "acme", "blueprint": "default", "categories": {"exfil"}}] + r := data.threat.reason with input as detect_input("alice") with data.threat.detect_rules as rules with enrich.user as mock_enrich_user + r == `rule {"blueprint":"default","org":"acme"}: exfil` +} + +test_detect_reason_combines_sources if { + inp := pod_input("erin", [{"op": "add", "path": "/spec/hostNetwork", "value": true}]) + detect_reason(inp) == `class host-network: container-escape,lateral-movement-and-network ({"equals":true,"kind":"Pod","path":"spec.hostNetwork"}); role detect-crypto; role detect-exfil` +} + +# --- threat:list --- + +list_input(who) := { + "action": "threat:list", + "subject": subject(who), + "resource": {"type": "threat"}, + "context": {}, +} + +list_obligations(who) := ob if { + ob := data.threat.obligations with input as list_input(who) with enrich.user as mock_enrich_user +} + +test_list_admin_allowed_unscoped if { + threat_allowed(list_input("root")) + not "org" in object.keys(list_obligations("root")) +} + +test_list_org_admin_allowed_scoped_to_own_org if { + threat_allowed(list_input("orga")) + list_obligations("orga").org == "acme" +} + +test_list_group_admin_denied if not threat_allowed(list_input("bob")) + +test_list_plain_user_denied if not threat_allowed(list_input("alice")) + +test_list_detect_role_does_not_grant_list if not threat_allowed(list_input("dave")) diff --git a/k8shell/templates/_helpers.tpl b/k8shell/templates/_helpers.tpl index 72b7ea8..806bbf6 100644 --- a/k8shell/templates/_helpers.tpl +++ b/k8shell/templates/_helpers.tpl @@ -93,3 +93,90 @@ imagePullSecrets: {{- end }} {{- end }} + +{{/* +PostgreSQL mode: simple (single instance run by the chart), cnpg +(CloudNativePG Cluster) or external (nothing installed). +*/}} +{{- define "k8shell.postgresqlMode" -}} +{{- $mode := .Values.postgresql.mode | default "simple" -}} +{{- if not (has $mode (list "simple" "cnpg" "external")) -}} +{{- fail (printf "postgresql.mode must be simple, cnpg or external, got %q" $mode) -}} +{{- end -}} +{{- $mode -}} +{{- end }} + +{{/* +secretKeyRef of a secret field ({value} or {secretName, secretKey}) for a +container env variable whose name differs from the key in the chart's int-* +Secret. Usage: include "k8shell.secretKeyRef" (dict "secretDef" .Values.x "defaultSecret" "identity" "defaultKey" "POSTGRES_PASSWORD") +*/}} +{{- define "k8shell.secretKeyRef" -}} +secretKeyRef: + {{- if .secretDef.secretName }} + name: {{ .secretDef.secretName }} + key: {{ .secretDef.secretKey }} + {{- else }} + name: int-{{ .defaultSecret }} + key: {{ .defaultKey }} + {{- end }} +{{- end }} + +{{/* +Fails unless a secret field has a value or a secretName/secretKey. +Usage: include "k8shell.requireSecret" (dict "field" .Values.x "path" "x") +*/}} +{{- define "k8shell.requireSecret" -}} +{{- $f := .field | default dict -}} +{{- if not (or $f.value (and $f.secretName $f.secretKey)) -}} +{{- fail (printf "%s is required: set %s.value or %s.secretName and %s.secretKey" .path .path .path .path) -}} +{{- end -}} +{{- end }} + +{{/* +Identity providers installed with the chart: list of dicts with name, port +and git (backed by a git forge). Rendered as JSON. +*/}} +{{- define "k8shell.idps" -}} +{{- $idps := list -}} +{{- if .Values.idpGithub.enabled -}} +{{- $idps = append $idps (dict "name" "idp-github" "port" 9030 "git" true) -}} +{{- end -}} +{{- if .Values.idpGoogle.enabled -}} +{{- $idps = append $idps (dict "name" "idp-google" "port" 9031 "git" false) -}} +{{- end -}} +{{- toJson $idps -}} +{{- end }} + +{{/* +true if a git identity provider is installed (adds the git-blueprints ConfigMap) +*/}} +{{- define "k8shell.gitIdpEnabled" -}} +{{- if .Values.idpGithub.enabled }}true{{ end -}} +{{- end }} + +{{/* +Name of the ConfigMap with the infra versions api-server shows: the value of +apiServer.infraVersionsConfigMap, else the chart's k8shell-infra-versions when +the chart installs PostgreSQL or NATS, else empty. +*/}} +{{- define "k8shell.infraVersionsConfigMap" -}} +{{- if .Values.apiServer.infraVersionsConfigMap -}} +{{- .Values.apiServer.infraVersionsConfigMap -}} +{{- else if or (and .Values.postgresql.enabled (ne (include "k8shell.postgresqlMode" .) "external")) .Values.nats.install -}} +k8shell-infra-versions +{{- end -}} +{{- end }} + +{{/* +Additional blueprint ConfigMaps mounted into the provisioner: the +git-blueprints of a git identity provider, then provisioner.blueprintFilesConfigMaps. +Rendered as JSON. +*/}} +{{- define "k8shell.blueprintFilesConfigMaps" -}} +{{- $cms := list -}} +{{- if include "k8shell.gitIdpEnabled" . -}} +{{- $cms = append $cms "git-blueprints" -}} +{{- end -}} +{{- toJson (concat $cms (.Values.provisioner.blueprintFilesConfigMaps | default list) | uniq) -}} +{{- end }} diff --git a/k8shell/templates/api-server/dep-api-server.yaml b/k8shell/templates/api-server/dep-api-server.yaml index 28b8c3f..bd1bd24 100644 --- a/k8shell/templates/api-server/dep-api-server.yaml +++ b/k8shell/templates/api-server/dep-api-server.yaml @@ -13,6 +13,9 @@ spec: k8shell.io/app: api-server template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/api-server/cm-api-server.yaml") .) | sha256sum }} labels: k8shell.io/app: api-server {{- include "k8shell.labels" . | nindent 8 }} @@ -52,7 +55,7 @@ spec: - name: versions mountPath: /app/versions readOnly: true - {{- if .Values.apiServer.infraVersionsConfigMap }} + {{- if include "k8shell.infraVersionsConfigMap" . }} - name: infra-versions mountPath: /app/infra-versions readOnly: true @@ -75,10 +78,10 @@ spec: - name: versions configMap: name: k8shell-versions - {{- if .Values.apiServer.infraVersionsConfigMap }} + {{- if include "k8shell.infraVersionsConfigMap" . }} - name: infra-versions configMap: - name: {{ .Values.apiServer.infraVersionsConfigMap }} + name: {{ include "k8shell.infraVersionsConfigMap" . }} {{- end }} - name: jwt projected: diff --git a/k8shell/templates/authz/cm-authz-policies.yaml b/k8shell/templates/authz/cm-authz-policies.yaml new file mode 100644 index 0000000..fc6737f --- /dev/null +++ b/k8shell/templates/authz/cm-authz-policies.yaml @@ -0,0 +1,15 @@ +{{- if and .Values.authz.enabled (not .Values.authz.policiesConfigMap) }} +# default policies; replaced by authz.policiesConfigMap +apiVersion: v1 +kind: ConfigMap +metadata: + name: authz-policies-default + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: authz +data: +{{- range $path, $file := .Files.Glob "files/policies/*.rego" }} + {{ base $path }}: | +{{ $file | toString | indent 4 }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/authz/dep-authz.yaml b/k8shell/templates/authz/dep-authz.yaml index 8691d2f..71f0a5b 100644 --- a/k8shell/templates/authz/dep-authz.yaml +++ b/k8shell/templates/authz/dep-authz.yaml @@ -13,6 +13,11 @@ spec: k8shell.io/app: authz template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/authz/cm-authz.yaml") .) | sha256sum }} + # restart when the chart's default policies change + checksum/policies: {{ include (print $.Template.BasePath "/authz/cm-authz-policies.yaml") . | sha256sum }} labels: k8shell.io/app: authz {{- include "k8shell.labels" . | nindent 8 }} @@ -90,12 +95,8 @@ spec: configMap: name: authz-config - name: authz-policies - {{- if .Values.authz.policiesConfigMap }} configMap: - name: {{ .Values.authz.policiesConfigMap }} - {{- else }} - emptyDir: {} - {{- end }} + name: {{ .Values.authz.policiesConfigMap | default "authz-policies-default" }} {{- if .Values.certManager.enabled }} - name: authz-cert secret: diff --git a/k8shell/templates/cm-infra-versions.yaml b/k8shell/templates/cm-infra-versions.yaml new file mode 100644 index 0000000..57a8246 --- /dev/null +++ b/k8shell/templates/cm-infra-versions.yaml @@ -0,0 +1,25 @@ +{{- if and .Values.apiServer.enabled (not .Values.apiServer.infraVersionsConfigMap) (include "k8shell.infraVersionsConfigMap" .) }} +{{- $versions := dict }} +{{- if and .Values.postgresql.enabled (ne (include "k8shell.postgresqlMode" .) "external") }} +{{- if eq (include "k8shell.postgresqlMode" .) "simple" }} +{{- $_ := set $versions "postgresql" (dict "imageTag" (toString .Values.postgresql.simple.image.tag)) }} +{{- else }} +{{- $image := .Values.postgresql.cnpg.imageName }} +{{- $_ := set $versions "postgresql" (dict "imageTag" (ternary (regexReplaceAll "^.*:" $image "") "cnpg" (contains ":" $image))) }} +{{- end }} +{{- end }} +{{- if .Values.nats.install }} +{{- $chart := "" }} +{{- range .Chart.Dependencies }}{{ if eq .Name "natsServer" "nats" }}{{ $chart = .Version }}{{ end }}{{ end }} +{{- $_ := set $versions "nats" (dict "chartVersion" $chart "imageTag" (toString .Values.natsServer.container.image.tag)) }} +{{- end }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: k8shell-infra-versions + labels: + {{- include "k8shell.labels" . | nindent 4 }} +data: + versions.json: | + {{ $versions | toJson }} +{{- end }} diff --git a/k8shell/templates/identity/cm-identity.yaml b/k8shell/templates/identity/cm-identity.yaml index d8aa2d9..adf883c 100644 --- a/k8shell/templates/identity/cm-identity.yaml +++ b/k8shell/templates/identity/cm-identity.yaml @@ -53,10 +53,20 @@ data: - /app/files/identity-users.yaml {{- end }} - {{- if .Values.identity.remoteProviders }} + {{- /* the identity providers installed with the chart are added to + identity.remoteProviders */}} + {{- $providers := concat (.Values.identity.remoteProviders | default list) list }} + {{- range (include "k8shell.idps" . | fromJsonArray) }} + {{- $address := printf "%s:%v" .name .port }} + {{- if and $.Values.grpc $.Values.grpc.roundRobin }} + {{- $address = printf "dns:///%s" $address }} + {{- end }} + {{- $providers = append $providers (dict "address" $address "serverName" .name) }} + {{- end }} + {{- if $providers }} {{- $root := . }} remoteProviders: - {{- range .Values.identity.remoteProviders }} + {{- range $providers }} - address: {{ .address }} tokenFilePath: /var/run/secrets/k8shell.io/identity {{- if $root.Values.certManager.enabled }} @@ -85,7 +95,13 @@ data: signingMethod: ${JWT_SIGNING_METHOD} privateKeyFile: /run/secrets/jwt-issuer/private-key.pem - {{- with .Values.identity.onboardRules }} + {{- /* the local users of identity.users are onboarded as defined there: + identity rejects users no rule allows */}} + {{- $rules := concat (.Values.identity.onboardRules | default list) list }} + {{- range .Values.identity.users }} + {{- $rules = append $rules (dict "idp" "idp.k8shell.io/file" "usernamePattern" .username "org" (default "default" .organization) "action" "allow" "sudo" (default false .sudo) "roles" (default list .roles)) }} + {{- end }} + {{- with $rules }} onboardRules: {{- toYaml . | nindent 6 }} {{- end }} @@ -98,15 +114,14 @@ data: # SMTP relay for password-reset and announcement email smtp: enabled: {{ .Values.identity.smtp.enabled }} + {{- /* without SMTP the variables are empty, and an empty port is not an int */}} + {{- if .Values.identity.smtp.enabled }} host: ${SMTP_HOST} port: !!int ${SMTP_PORT} username: ${SMTP_USERNAME} - {{- if .Values.identity.smtp.enabled }} password: !file ${SECRET_FILES}/smtp_password - {{- else }} - password: "" - {{- end }} from: ${SMTP_FROM} + {{- end }} # Password-reset token lifecycle passwordReset: diff --git a/k8shell/templates/identity/dep-identity.yaml b/k8shell/templates/identity/dep-identity.yaml index 3dd8ba3..3e564e3 100644 --- a/k8shell/templates/identity/dep-identity.yaml +++ b/k8shell/templates/identity/dep-identity.yaml @@ -12,6 +12,9 @@ spec: k8shell.io/app: identity template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/identity/cm-identity.yaml") .) (include (print $.Template.BasePath "/identity/cm-identity-users.yaml") .) (include (print $.Template.BasePath "/identity/sec-identity-users.yaml") .) | sha256sum }} labels: k8shell.io/app: identity {{- include "k8shell.labels" . | nindent 8 }} diff --git a/k8shell/templates/idp-github/cert-idp-github.yaml b/k8shell/templates/idp-github/cert-idp-github.yaml new file mode 100644 index 0000000..4b966fb --- /dev/null +++ b/k8shell/templates/idp-github/cert-idp-github.yaml @@ -0,0 +1,24 @@ +{{- if .Values.idpGithub.enabled }} +{{- if .Values.certManager.enabled }} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: idp-github-cert + labels: + {{- include "k8shell.labels" . | nindent 4 }} +spec: + secretName: idp-github-tls + duration: {{ .Values.certManager.duration }} + renewBefore: {{ .Values.certManager.renewBefore }} + commonName: idp-github.{{ .Release.Namespace }}.svc.cluster.local + dnsNames: + - idp-github + - idp-github.{{ .Release.Namespace }}.svc + - idp-github.{{ .Release.Namespace }}.svc.cluster.local + usages: + - server auth + issuerRef: + name: {{ .Values.certManager.issuer.name }} + kind: {{ .Values.certManager.issuer.kind }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/idp-github/cm-idp-github-config.yaml b/k8shell/templates/idp-github/cm-idp-github-config.yaml new file mode 100644 index 0000000..9c2252a --- /dev/null +++ b/k8shell/templates/idp-github/cm-idp-github-config.yaml @@ -0,0 +1,51 @@ +{{- if .Values.idpGithub.enabled }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: idp-github-config + labels: + app: idp-github +data: + config.yaml: | + grpc: + port: 9030 + + {{- if .Values.certManager.enabled }} + enableTLS: true + certFile: /etc/tls/identity/tls.crt + keyFile: /etc/tls/identity/tls.key + {{- else }} + enableTLS: false + {{- end }} + + # JWT required claims for authentication + authEnabled: {{ .Values.authEnabled }} + audience: identity + allowed: + - serviceAccount: identity + + nats: + enabled: {{ .Values.nats.enabled }} + url: nats://{{ .Values.nats.host }}:{{ .Values.nats.port }} + username: {{ .Values.nats.username }} + password: ${NATS_K8SHELL_PASSWORD} + + db: + enabled: true + database: {{ .Values.postgresql.database }} + hostname: {{ .Values.postgresql.host }} + port: {{ .Values.postgresql.port }} + username: ${POSTGRES_USERNAME} + password: ${POSTGRES_PASSWORD} + + github: + clientId: ${GITHUB_CLIENT_ID} + clientSecret: ${GITHUB_CLIENT_SECRET} + appSlug: {{ .Values.idpGithub.github.appSlug }} + + onboardRules: + {{- toYaml .Values.idpGithub.github.onboardRules | nindent 8 }} + + onboardRuleTemplate: | + {{- .Values.idpGithub.github.onboardRuleTemplate | nindent 8 }} +{{- end }} diff --git a/k8shell/templates/idp-github/cm-idp-github-files.yaml b/k8shell/templates/idp-github/cm-idp-github-files.yaml new file mode 100644 index 0000000..60a04e3 --- /dev/null +++ b/k8shell/templates/idp-github/cm-idp-github-files.yaml @@ -0,0 +1,11 @@ +{{- if .Values.idpGithub.enabled }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: idp-github-files + labels: + app: idp-github +data: + github-user-template.yaml: | + {{- .Values.idpGithub.githubUserTemplate | nindent 4 }} +{{- end }} diff --git a/k8shell/templates/idp-github/dep-idp-github.yaml b/k8shell/templates/idp-github/dep-idp-github.yaml new file mode 100644 index 0000000..9f4f162 --- /dev/null +++ b/k8shell/templates/idp-github/dep-idp-github.yaml @@ -0,0 +1,88 @@ +{{- if .Values.idpGithub.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: idp-github + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-github +spec: + replicas: {{ .Values.idpGithub.replicas }} + selector: + matchLabels: + k8shell.io/app: idp-github + template: + metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/idp-github/cm-idp-github-config.yaml") .) (include (print $.Template.BasePath "/idp-github/cm-idp-github-files.yaml") .) | sha256sum }} + labels: + k8shell.io/app: idp-github + {{- include "k8shell.labels" . | nindent 8 }} + spec: + {{- include "k8shell.imagePullSecrets" . | nindent 6 }} + serviceAccountName: idp-github + containers: + - name: idp-github + image: {{ .Values.idpGithub.image.repository }}:{{ .Values.idpGithub.image.tag }} + workingDir: /app + ports: + - containerPort: 9030 + name: grpc + env: + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.nats.enabled + "name" "NATS_K8SHELL_PASSWORD" + "secretDef" .Values.nats.password + "defaultSecret" "idp-github" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_USERNAME" + "secretDef" .Values.postgresql.username + "defaultSecret" "idp-github" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_PASSWORD" + "secretDef" .Values.postgresql.password + "defaultSecret" "idp-github" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" true + "name" "GITHUB_CLIENT_ID" + "secretDef" .Values.idpGithub.github.clientId + "defaultSecret" "idp-github" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" true + "name" "GITHUB_CLIENT_SECRET" + "secretDef" .Values.idpGithub.github.clientSecret + "defaultSecret" "idp-github" + "context" .) | nindent 12 }} + volumeMounts: + - name: idp-github-config + mountPath: /app/config + readOnly: true + - name: idp-github-files + mountPath: /app/files + readOnly: true + {{- if .Values.certManager.enabled }} + - name: idp-github-cert + mountPath: /etc/tls/identity + readOnly: true + {{- end }} + + volumes: + - name: idp-github-config + configMap: + name: idp-github-config + - name: idp-github-files + configMap: + name: idp-github-files + {{- if .Values.certManager.enabled }} + - name: idp-github-cert + secret: + secretName: idp-github-tls + {{- end }} +{{- end }} diff --git a/k8shell/templates/idp-github/sa-idp-github.yaml b/k8shell/templates/idp-github/sa-idp-github.yaml new file mode 100644 index 0000000..21fb4f3 --- /dev/null +++ b/k8shell/templates/idp-github/sa-idp-github.yaml @@ -0,0 +1,10 @@ +{{- if .Values.idpGithub.enabled }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: idp-github + namespace: {{ .Release.Namespace }} + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-github +{{- end }} diff --git a/k8shell/templates/idp-github/sec-idp-github.yaml b/k8shell/templates/idp-github/sec-idp-github.yaml new file mode 100644 index 0000000..824e53f --- /dev/null +++ b/k8shell/templates/idp-github/sec-idp-github.yaml @@ -0,0 +1,42 @@ +{{- if .Values.idpGithub.enabled }} +{{- if not .Values.postgresql.enabled -}} +{{- fail "postgresql.enabled must be true: idp-github requires a PostgreSQL database" -}} +{{- end -}} +{{- if and (not .Values.idpGithub.github.clientId.value) (not .Values.idpGithub.github.clientId.secretName) -}} +{{- fail "idpGithub.github.clientId is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- if and (not .Values.idpGithub.github.clientSecret.value) (not .Values.idpGithub.github.clientSecret.secretName) -}} +{{- fail "idpGithub.github.clientSecret is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- $secrets := dict -}} +{{- if .Values.nats.enabled -}} +{{- if .Values.nats.password.value -}} +{{- $_ := set $secrets "NATS_K8SHELL_PASSWORD" .Values.nats.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.postgresql.enabled -}} +{{- if .Values.postgresql.username.value -}} +{{- $_ := set $secrets "POSTGRES_USERNAME" .Values.postgresql.username.value -}} +{{- end -}} +{{- if .Values.postgresql.password.value -}} +{{- $_ := set $secrets "POSTGRES_PASSWORD" .Values.postgresql.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.idpGithub.github.clientId.value -}} +{{- $_ := set $secrets "GITHUB_CLIENT_ID" .Values.idpGithub.github.clientId.value -}} +{{- end -}} +{{- if .Values.idpGithub.github.clientSecret.value -}} +{{- $_ := set $secrets "GITHUB_CLIENT_SECRET" .Values.idpGithub.github.clientSecret.value -}} +{{- end -}} +{{- if $secrets }} +apiVersion: v1 +kind: Secret +metadata: + name: int-idp-github + labels: + {{- include "k8shell.labels" . | nindent 4 }} +type: Opaque +data: +{{ include "k8shell.secretData" $secrets | nindent 2 }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/idp-github/svc-idp-github.yaml b/k8shell/templates/idp-github/svc-idp-github.yaml new file mode 100644 index 0000000..f4e017a --- /dev/null +++ b/k8shell/templates/idp-github/svc-idp-github.yaml @@ -0,0 +1,21 @@ +{{- if .Values.idpGithub.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: idp-github + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-github +spec: + type: ClusterIP + {{- if and .Values.grpc .Values.grpc.roundRobin }} + clusterIP: None + {{- end }} + ports: + - port: 9030 + targetPort: grpc + protocol: TCP + name: grpc + selector: + k8shell.io/app: idp-github +{{- end }} diff --git a/k8shell/templates/idp-google/cert-idp-google.yaml b/k8shell/templates/idp-google/cert-idp-google.yaml new file mode 100644 index 0000000..bd78ec4 --- /dev/null +++ b/k8shell/templates/idp-google/cert-idp-google.yaml @@ -0,0 +1,24 @@ +{{- if .Values.idpGoogle.enabled }} +{{- if .Values.certManager.enabled }} +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: idp-google-cert + labels: + {{- include "k8shell.labels" . | nindent 4 }} +spec: + secretName: idp-google-tls + duration: {{ .Values.certManager.duration }} + renewBefore: {{ .Values.certManager.renewBefore }} + commonName: idp-google.{{ .Release.Namespace }}.svc.cluster.local + dnsNames: + - idp-google + - idp-google.{{ .Release.Namespace }}.svc + - idp-google.{{ .Release.Namespace }}.svc.cluster.local + usages: + - server auth + issuerRef: + name: {{ .Values.certManager.issuer.name }} + kind: {{ .Values.certManager.issuer.kind }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/idp-google/cm-idp-google-config.yaml b/k8shell/templates/idp-google/cm-idp-google-config.yaml new file mode 100644 index 0000000..1e200bc --- /dev/null +++ b/k8shell/templates/idp-google/cm-idp-google-config.yaml @@ -0,0 +1,62 @@ +{{- if .Values.idpGoogle.enabled }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: idp-google-config + labels: + app: idp-google +data: + config.yaml: | + grpc: + port: 9031 + + {{- if .Values.certManager.enabled }} + enableTLS: true + certFile: /etc/tls/identity/tls.crt + keyFile: /etc/tls/identity/tls.key + {{- else }} + enableTLS: false + {{- end }} + + # JWT required claims for authentication + authEnabled: {{ .Values.authEnabled }} + audience: identity + allowed: + - serviceAccount: identity + + nats: + enabled: {{ .Values.nats.enabled }} + url: nats://{{ .Values.nats.host }}:{{ .Values.nats.port }} + username: {{ .Values.nats.username }} + password: ${NATS_K8SHELL_PASSWORD} + + db: + enabled: true + database: {{ .Values.postgresql.database }} + hostname: {{ .Values.postgresql.host }} + port: {{ .Values.postgresql.port }} + username: ${POSTGRES_USERNAME} + password: ${POSTGRES_PASSWORD} + + google: + clientId: ${GOOGLE_CLIENT_ID} + clientSecret: ${GOOGLE_CLIENT_SECRET} + + allowedDomains: + {{- toYaml .Values.idpGoogle.google.allowedDomains | nindent 8 }} + allowPersonal: {{ .Values.idpGoogle.google.allowPersonal }} + {{- with .Values.idpGoogle.google.personalEmailDomains }} + personalEmailDomains: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.idpGoogle.google.personalAllowedEmails }} + personalAllowedEmails: + {{- toYaml . | nindent 8 }} + {{- end }} + + onboardRules: + {{- toYaml .Values.idpGoogle.google.onboardRules | nindent 8 }} + + onboardRuleTemplate: | + {{- .Values.idpGoogle.google.onboardRuleTemplate | nindent 8 }} +{{- end }} diff --git a/k8shell/templates/idp-google/dep-idp-google.yaml b/k8shell/templates/idp-google/dep-idp-google.yaml new file mode 100644 index 0000000..9eb8e34 --- /dev/null +++ b/k8shell/templates/idp-google/dep-idp-google.yaml @@ -0,0 +1,82 @@ +{{- if .Values.idpGoogle.enabled }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: idp-google + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google +spec: + replicas: {{ .Values.idpGoogle.replicas }} + selector: + matchLabels: + k8shell.io/app: idp-google + template: + metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/idp-google/cm-idp-google-config.yaml") .) | sha256sum }} + labels: + k8shell.io/app: idp-google + {{- include "k8shell.labels" . | nindent 8 }} + spec: + {{- include "k8shell.imagePullSecrets" . | nindent 6 }} + serviceAccountName: idp-google + containers: + - name: idp-google + image: {{ .Values.idpGoogle.image.repository }}:{{ .Values.idpGoogle.image.tag }} + workingDir: /app + ports: + - containerPort: 9031 + name: grpc + env: + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.nats.enabled + "name" "NATS_K8SHELL_PASSWORD" + "secretDef" .Values.nats.password + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_USERNAME" + "secretDef" .Values.postgresql.username + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" .Values.postgresql.enabled + "name" "POSTGRES_PASSWORD" + "secretDef" .Values.postgresql.password + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" true + "name" "GOOGLE_CLIENT_ID" + "secretDef" .Values.idpGoogle.google.clientId + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + {{- include "k8shell.secretEnv" (dict + "enabled" true + "name" "GOOGLE_CLIENT_SECRET" + "secretDef" .Values.idpGoogle.google.clientSecret + "defaultSecret" "idp-google" + "context" .) | nindent 12 }} + volumeMounts: + - name: idp-google-config + mountPath: /app/config + readOnly: true + {{- if .Values.certManager.enabled }} + - name: idp-google-cert + mountPath: /etc/tls/identity + readOnly: true + {{- end }} + + volumes: + - name: idp-google-config + configMap: + name: idp-google-config + {{- if .Values.certManager.enabled }} + - name: idp-google-cert + secret: + secretName: idp-google-tls + {{- end }} +{{- end }} diff --git a/k8shell/templates/idp-google/sa-idp-google.yaml b/k8shell/templates/idp-google/sa-idp-google.yaml new file mode 100644 index 0000000..c82b6ac --- /dev/null +++ b/k8shell/templates/idp-google/sa-idp-google.yaml @@ -0,0 +1,10 @@ +{{- if .Values.idpGoogle.enabled }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: idp-google + namespace: {{ .Release.Namespace }} + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google +{{- end }} diff --git a/k8shell/templates/idp-google/sec-idp-google.yaml b/k8shell/templates/idp-google/sec-idp-google.yaml new file mode 100644 index 0000000..3be3cd1 --- /dev/null +++ b/k8shell/templates/idp-google/sec-idp-google.yaml @@ -0,0 +1,42 @@ +{{- if .Values.idpGoogle.enabled }} +{{- if not .Values.postgresql.enabled -}} +{{- fail "postgresql.enabled must be true: idp-google requires a PostgreSQL database" -}} +{{- end -}} +{{- if and (not .Values.idpGoogle.google.clientId.value) (not .Values.idpGoogle.google.clientId.secretName) -}} +{{- fail "idpGoogle.google.clientId is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- if and (not .Values.idpGoogle.google.clientSecret.value) (not .Values.idpGoogle.google.clientSecret.secretName) -}} +{{- fail "idpGoogle.google.clientSecret is required (set .value or .secretName/.secretKey)" -}} +{{- end -}} +{{- $secrets := dict -}} +{{- if .Values.nats.enabled -}} +{{- if .Values.nats.password.value -}} +{{- $_ := set $secrets "NATS_K8SHELL_PASSWORD" .Values.nats.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.postgresql.enabled -}} +{{- if .Values.postgresql.username.value -}} +{{- $_ := set $secrets "POSTGRES_USERNAME" .Values.postgresql.username.value -}} +{{- end -}} +{{- if .Values.postgresql.password.value -}} +{{- $_ := set $secrets "POSTGRES_PASSWORD" .Values.postgresql.password.value -}} +{{- end -}} +{{- end -}} +{{- if .Values.idpGoogle.google.clientId.value -}} +{{- $_ := set $secrets "GOOGLE_CLIENT_ID" .Values.idpGoogle.google.clientId.value -}} +{{- end -}} +{{- if .Values.idpGoogle.google.clientSecret.value -}} +{{- $_ := set $secrets "GOOGLE_CLIENT_SECRET" .Values.idpGoogle.google.clientSecret.value -}} +{{- end -}} +{{- if $secrets }} +apiVersion: v1 +kind: Secret +metadata: + name: int-idp-google + labels: + {{- include "k8shell.labels" . | nindent 4 }} +type: Opaque +data: +{{ include "k8shell.secretData" $secrets | nindent 2 }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/idp-google/svc-idp-google.yaml b/k8shell/templates/idp-google/svc-idp-google.yaml new file mode 100644 index 0000000..fd126ef --- /dev/null +++ b/k8shell/templates/idp-google/svc-idp-google.yaml @@ -0,0 +1,21 @@ +{{- if .Values.idpGoogle.enabled }} +apiVersion: v1 +kind: Service +metadata: + name: idp-google + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: idp-google +spec: + type: ClusterIP + {{- if and .Values.grpc .Values.grpc.roundRobin }} + clusterIP: None + {{- end }} + ports: + - port: 9031 + targetPort: grpc + protocol: TCP + name: grpc + selector: + k8shell.io/app: idp-google +{{- end }} diff --git a/k8shell/templates/postgresql/cnpg-postgresql.yaml b/k8shell/templates/postgresql/cnpg-postgresql.yaml new file mode 100644 index 0000000..2186ef4 --- /dev/null +++ b/k8shell/templates/postgresql/cnpg-postgresql.yaml @@ -0,0 +1,57 @@ +{{- if and .Values.postgresql.enabled (eq (include "k8shell.postgresqlMode" .) "cnpg") }} +{{- $cnpg := .Values.postgresql.cnpg }} +{{- /* the superuser Secret (kubernetes.io/basic-auth, username postgres) is + created outside the chart, see values.yaml */}} +apiVersion: postgresql.cnpg.io/v1 +kind: Cluster +metadata: + name: db-postgresql + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql +spec: + instances: {{ $cnpg.instances }} + {{- with $cnpg.imageName }} + imageName: {{ . | quote }} + {{- end }} + enableSuperuserAccess: true + superuserSecret: + name: {{ $cnpg.superuserSecret }} + {{- with $cnpg.bootstrap }} + bootstrap: + {{- toYaml . | nindent 4 }} + {{- else }} + bootstrap: + initdb: + database: app + owner: app + {{- end }} + {{- with $cnpg.externalClusters }} + externalClusters: + {{- toYaml . | nindent 4 }} + {{- end }} + storage: + {{- with $cnpg.storage.storageClassName }} + storageClass: {{ . | quote }} + {{- end }} + size: {{ $cnpg.storage.size | quote }} + {{- with .Values.postgresql.resources }} + resources: + {{- toYaml . | nindent 4 }} + {{- end }} + affinity: + enablePodAntiAffinity: true + topologyKey: kubernetes.io/hostname + podAntiAffinityType: {{ $cnpg.podAntiAffinityType }} + {{- if or $cnpg.parameters $cnpg.synchronous }} + postgresql: + {{- with $cnpg.parameters }} + parameters: + {{- toYaml . | nindent 6 }} + {{- end }} + {{- with $cnpg.synchronous }} + synchronous: + {{- toYaml . | nindent 6 }} + {{- end }} + {{- end }} +{{- end }} diff --git a/k8shell/templates/postgresql/pvc-postgresql.yaml b/k8shell/templates/postgresql/pvc-postgresql.yaml new file mode 100644 index 0000000..e7dd48c --- /dev/null +++ b/k8shell/templates/postgresql/pvc-postgresql.yaml @@ -0,0 +1,26 @@ +{{- if and .Values.postgresql.enabled (eq (include "k8shell.postgresqlMode" .) "simple") }} +{{- $p := .Values.postgresql.simple.persistence }} +{{- if and $p.enabled (not $p.existingClaim) }} +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: data-db-postgresql + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql + annotations: + # helm uninstall keeps the database + helm.sh/resource-policy: keep + {{- with $p.annotations }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + accessModes: [ReadWriteOnce] + {{- with $p.storageClassName }} + storageClassName: {{ . | quote }} + {{- end }} + resources: + requests: + storage: {{ $p.size | quote }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/postgresql/sts-postgresql.yaml b/k8shell/templates/postgresql/sts-postgresql.yaml new file mode 100644 index 0000000..efe7b0e --- /dev/null +++ b/k8shell/templates/postgresql/sts-postgresql.yaml @@ -0,0 +1,98 @@ +{{- if and .Values.postgresql.enabled (eq (include "k8shell.postgresqlMode" .) "simple") }} +{{- $pg := .Values.postgresql }} +{{- $s := $pg.simple }} +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: db-postgresql + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql +spec: + replicas: 1 + serviceName: db-postgresql + selector: + matchLabels: + k8shell.io/app: db-postgresql + template: + metadata: + labels: + k8shell.io/app: db-postgresql + {{- include "k8shell.labels" . | nindent 8 }} + app.kubernetes.io/component: postgresql + spec: + {{- include "k8shell.imagePullSecrets" . | nindent 6 }} + securityContext: + # uid/gid of the postgres user in the official image + runAsUser: 999 + runAsGroup: 999 + fsGroup: 999 + fsGroupChangePolicy: OnRootMismatch + {{- with $s.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with $s.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with $s.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + containers: + - name: postgresql + image: {{ $s.image.repository }}:{{ $s.image.tag }} + ports: + - containerPort: 5432 + name: postgresql + env: + - name: POSTGRES_USER + valueFrom: + {{- include "k8shell.secretKeyRef" (dict "secretDef" $pg.username "defaultSecret" "identity" "defaultKey" "POSTGRES_USERNAME") | nindent 12 }} + - name: POSTGRES_PASSWORD + valueFrom: + {{- include "k8shell.secretKeyRef" (dict "secretDef" $pg.password "defaultSecret" "identity" "defaultKey" "POSTGRES_PASSWORD") | nindent 12 }} + - name: POSTGRES_DB + value: {{ $pg.database | quote }} + # a subdirectory: initdb refuses a non-empty directory (lost+found) + - name: PGDATA + value: /var/lib/postgresql/data/pgdata + readinessProbe: + exec: + command: ["sh", "-c", "pg_isready -h 127.0.0.1 -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""] + periodSeconds: 10 + timeoutSeconds: 5 + livenessProbe: + exec: + command: ["sh", "-c", "pg_isready -h 127.0.0.1 -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""] + initialDelaySeconds: 30 + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 6 + {{- with $pg.resources }} + resources: + {{- toYaml . | nindent 10 }} + {{- end }} + volumeMounts: + - name: data + mountPath: /var/lib/postgresql/data + - name: run + mountPath: /var/run/postgresql + - name: shm + mountPath: /dev/shm + volumes: + - name: data + {{- if $s.persistence.enabled }} + persistentVolumeClaim: + claimName: {{ $s.persistence.existingClaim | default "data-db-postgresql" }} + {{- else }} + emptyDir: {} + {{- end }} + - name: run + emptyDir: {} + - name: shm + emptyDir: + medium: Memory + sizeLimit: 256Mi +{{- end }} diff --git a/k8shell/templates/postgresql/svc-postgresql.yaml b/k8shell/templates/postgresql/svc-postgresql.yaml new file mode 100644 index 0000000..7c8a609 --- /dev/null +++ b/k8shell/templates/postgresql/svc-postgresql.yaml @@ -0,0 +1,47 @@ +{{- if .Values.postgresql.enabled }} +{{- $mode := include "k8shell.postgresqlMode" . }} +{{- if ne $mode "external" }} +{{- $selector := dict "k8shell.io/app" "db-postgresql" }} +{{- if eq $mode "cnpg" }} +{{- $selector = dict "cnpg.io/cluster" "db-postgresql" "cnpg.io/instanceRole" "primary" }} +{{- end }} +# The primary, under the same name in both modes ("db-postgresql"; CloudNativePG +# itself only creates db-postgresql-rw/-ro/-r). +apiVersion: v1 +kind: Service +metadata: + name: db-postgresql + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql +spec: + type: ClusterIP + ports: + - name: postgresql + port: 5432 + targetPort: 5432 + protocol: TCP + selector: + {{- toYaml $selector | nindent 4 }} +{{- if .Values.postgresql.nodePort.enabled }} +--- +apiVersion: v1 +kind: Service +metadata: + name: np-postgresql + labels: + {{- include "k8shell.labels" . | nindent 4 }} + app.kubernetes.io/component: postgresql +spec: + type: NodePort + ports: + - name: postgresql + port: 5432 + targetPort: 5432 + protocol: TCP + nodePort: {{ required "postgresql.nodePort.port is required when postgresql.nodePort.enabled=true" .Values.postgresql.nodePort.port }} + selector: + {{- toYaml $selector | nindent 4 }} +{{- end }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/provisioner/cm-blueprints.yaml b/k8shell/templates/provisioner/cm-blueprints.yaml index b1a2dc3..4642d3a 100644 --- a/k8shell/templates/provisioner/cm-blueprints.yaml +++ b/k8shell/templates/provisioner/cm-blueprints.yaml @@ -1,3 +1,4 @@ +{{- if not .Values.provisioner.blueprintsConfigMap }} apiVersion: v1 kind: ConfigMap metadata: @@ -9,3 +10,4 @@ data: samples.yaml: | {{ .Files.Get "files/blueprints/samples.yaml" | indent 4 }} {{- end }} +{{- end }} diff --git a/k8shell/templates/provisioner/cm-git-blueprints.yaml b/k8shell/templates/provisioner/cm-git-blueprints.yaml new file mode 100644 index 0000000..22b26a8 --- /dev/null +++ b/k8shell/templates/provisioner/cm-git-blueprints.yaml @@ -0,0 +1,14 @@ +{{- if include "k8shell.gitIdpEnabled" . }} +# blueprints of workspaces created from a git repository (git identity providers) +apiVersion: v1 +kind: ConfigMap +metadata: + name: git-blueprints + labels: + {{- include "k8shell.labels" . | nindent 4 }} +data: +{{- range $path, $file := .Files.Glob "files/git-blueprints/*" }} + {{ base $path }}: | +{{ $file | toString | indent 4 }} +{{- end }} +{{- end }} diff --git a/k8shell/templates/provisioner/cm-provisioner.yaml b/k8shell/templates/provisioner/cm-provisioner.yaml index 93b869c..637630e 100644 --- a/k8shell/templates/provisioner/cm-provisioner.yaml +++ b/k8shell/templates/provisioner/cm-provisioner.yaml @@ -143,4 +143,4 @@ data: # Blueprints configuration blueprints: directory: /app/blueprints - defaultCustomBlueprint: {{ .Values.provisioner.defaultCustomBlueprint | default "base" }} + defaultCustomBlueprint: {{ .Values.provisioner.defaultCustomBlueprint | default (ternary "git-dev" "base" (eq (include "k8shell.gitIdpEnabled" .) "true")) }} diff --git a/k8shell/templates/provisioner/dep-provisioner.yaml b/k8shell/templates/provisioner/dep-provisioner.yaml index 7ce144d..c9a6aa4 100644 --- a/k8shell/templates/provisioner/dep-provisioner.yaml +++ b/k8shell/templates/provisioner/dep-provisioner.yaml @@ -12,6 +12,12 @@ spec: k8shell.io/app: provisioner template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/provisioner/cm-provisioner.yaml") .) | sha256sum }} + # restart when the chart's blueprints change (external ConfigMaps are + # hot-reloaded by the provisioner) + checksum/blueprints: {{ include (print $.Template.BasePath "/provisioner/cm-blueprints.yaml") . | sha256sum }} labels: k8shell.io/app: provisioner {{- include "k8shell.labels" . | nindent 8 }} @@ -128,13 +134,11 @@ spec: projected: sources: - configMap: - name: blueprint-base-files - {{- if .Values.provisioner.blueprintFilesConfigMaps }} - {{- range .Values.provisioner.blueprintFilesConfigMaps }} + name: {{ .Values.provisioner.blueprintsConfigMap | default "blueprint-base-files" }} + {{- range include "k8shell.blueprintFilesConfigMaps" . | fromJsonArray }} - configMap: name: {{ . }} {{- end }} - {{- end }} {{ if .Values.provisioner.privateRegistry.cert }} - name: regcert secret: diff --git a/k8shell/templates/session/dep-session.yaml b/k8shell/templates/session/dep-session.yaml index 7f1cb5c..d9e5c9e 100644 --- a/k8shell/templates/session/dep-session.yaml +++ b/k8shell/templates/session/dep-session.yaml @@ -13,6 +13,9 @@ spec: k8shell.io/app: session template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/session/cm-session.yaml") .) | sha256sum }} labels: k8shell.io/app: session {{- include "k8shell.labels" . | nindent 8 }} @@ -31,14 +34,14 @@ spec: "enabled" .Values.postgresql.enabled "name" "POSTGRES_USERNAME" "secretDef" .Values.postgresql.username - "defaultSecret" "session" + "defaultSecret" "identity" "context" .) | nindent 8 }} {{- include "k8shell.secretEnv" (dict "enabled" .Values.postgresql.enabled "name" "POSTGRES_PASSWORD" "secretDef" .Values.postgresql.password - "defaultSecret" "session" + "defaultSecret" "identity" "context" .) | nindent 8 }} {{- include "k8shell.secretEnv" (dict diff --git a/k8shell/templates/ssh-proxy/dep-ssh-proxy.yaml b/k8shell/templates/ssh-proxy/dep-ssh-proxy.yaml index 038e2e5..e3542b0 100644 --- a/k8shell/templates/ssh-proxy/dep-ssh-proxy.yaml +++ b/k8shell/templates/ssh-proxy/dep-ssh-proxy.yaml @@ -13,6 +13,9 @@ spec: k8shell.io/app: ssh-proxy template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/ssh-proxy/cm-ssh-proxy.yaml") .) | sha256sum }} labels: k8shell.io/app: ssh-proxy {{- include "k8shell.labels" . | nindent 8 }} diff --git a/k8shell/templates/ssh-shield/dep-ssh-shield.yaml b/k8shell/templates/ssh-shield/dep-ssh-shield.yaml index e965583..aaad347 100644 --- a/k8shell/templates/ssh-shield/dep-ssh-shield.yaml +++ b/k8shell/templates/ssh-shield/dep-ssh-shield.yaml @@ -14,6 +14,9 @@ spec: k8shell.io/app: ssh-shield template: metadata: + annotations: + # restart when the configuration changes + checksum/config: {{ print (include (print $.Template.BasePath "/ssh-shield/cm-ssh-shield.yaml") .) (include (print $.Template.BasePath "/ssh-shield/cm-ssh-shield-plugins.yaml") .) | sha256sum }} labels: k8shell.io/app: ssh-shield {{- include "k8shell.labels" . | nindent 8 }} diff --git a/k8shell/templates/validate.yaml b/k8shell/templates/validate.yaml new file mode 100644 index 0000000..bbf5dd3 --- /dev/null +++ b/k8shell/templates/validate.yaml @@ -0,0 +1,20 @@ +{{- /* checks of the database and NATS settings; renders nothing */}} +{{- if .Values.postgresql.enabled }} +{{- $mode := include "k8shell.postgresqlMode" . }} +{{- include "k8shell.requireSecret" (dict "field" .Values.postgresql.username "path" "postgresql.username") }} +{{- include "k8shell.requireSecret" (dict "field" .Values.postgresql.password "path" "postgresql.password") }} +{{- if and (ne $mode "external") (not (hasPrefix "db-postgresql" .Values.postgresql.host)) }} +{{- fail (printf "postgresql.host must be the chart's Service db-postgresql with postgresql.mode %s (got %q)" $mode .Values.postgresql.host) }} +{{- end }} +{{- end }} +{{- if .Values.nats.enabled }} +{{- include "k8shell.requireSecret" (dict "field" .Values.nats.password "path" "nats.password") }} +{{- end }} +{{- if .Values.nats.install }} +{{- $ref := .Values.natsServer.container.env.NATS_K8SHELL_PASSWORD.valueFrom.secretKeyRef }} +{{- $name := .Values.nats.password.secretName | default "int-nats" }} +{{- $key := .Values.nats.password.secretKey | default "NATS_K8SHELL_PASSWORD" }} +{{- if or (ne $ref.name $name) (ne $ref.key $key) }} +{{- fail (printf "the NATS server must read the password the services use: set natsServer.container.env.NATS_K8SHELL_PASSWORD.valueFrom.secretKeyRef to name %q, key %q (now %q, %q)" $name $key $ref.name $ref.key) }} +{{- end }} +{{- end }} diff --git a/k8shell/values-internal.yaml b/k8shell/values-internal.yaml index 24a7b6e..37215d1 100644 --- a/k8shell/values-internal.yaml +++ b/k8shell/values-internal.yaml @@ -11,6 +11,9 @@ sshProxy: identity: image: repository: registry.k8shell.io/k8shell-base/identity + # TODO: identity PR #46 (local users: uid/gid, password; developer and + # git-workspace roles); replace with the release that contains it + tag: pr-46-723947c authz: image: @@ -26,6 +29,9 @@ provisioner: frontend: image: repository: registry.k8shell.io/k8shell-base/frontend + # TODO: frontend PR #89 (runtime values not cached as immutable); replace + # with the release that contains it + tag: pr-89-b933566 apiServer: image: @@ -34,3 +40,15 @@ apiServer: session: image: repository: registry.k8shell.io/k8shell-base/session + +sshShield: + image: + repository: registry.k8shell.io/k8shell-base/ssh-shield + +idpGithub: + image: + repository: registry.k8shell.io/k8shell-idp/idp-github + +idpGoogle: + image: + repository: registry.k8shell.io/k8shell-idp/idp-google diff --git a/k8shell/values.schema.json b/k8shell/values.schema.json index a383b92..946ba23 100644 --- a/k8shell/values.schema.json +++ b/k8shell/values.schema.json @@ -587,7 +587,9 @@ "items": { "type": "string" }, - "default": ["k8shell.io/pool"] + "default": [ + "k8shell.io/pool" + ] }, "workspaceStorageClass": { "type": "string" @@ -677,6 +679,9 @@ } } } + }, + "blueprintsConfigMap": { + "type": "string" } } }, @@ -708,7 +713,13 @@ "additionalProperties": false, "properties": { "navigation": { - "type": "string" + "type": "string", + "enum": [ + "off", + "short", + "full", + "" + ] } } }, @@ -922,7 +933,10 @@ "properties": { "type": { "type": "string", - "enum": ["memory", "nats-kv"] + "enum": [ + "memory", + "nats-kv" + ] }, "bucket": { "type": "string" @@ -960,6 +974,118 @@ }, "password": { "$ref": "#/definitions/secretRef" + }, + "mode": { + "type": "string", + "enum": [ + "simple", + "cnpg", + "external" + ] + }, + "resources": { + "type": "object" + }, + "simple": { + "type": "object", + "additionalProperties": false, + "properties": { + "image": { + "$ref": "#/definitions/image" + }, + "persistence": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "existingClaim": { + "type": "string" + }, + "storageClassName": { + "type": "string" + }, + "size": { + "type": "string" + }, + "annotations": { + "type": "object" + } + } + }, + "nodeSelector": { + "type": "object" + }, + "tolerations": { + "type": "array" + }, + "affinity": { + "type": "object" + } + } + }, + "cnpg": { + "type": "object", + "additionalProperties": false, + "properties": { + "instances": { + "type": "integer", + "minimum": 1 + }, + "imageName": { + "type": "string" + }, + "superuserSecret": { + "type": "string" + }, + "storage": { + "type": "object", + "additionalProperties": false, + "properties": { + "storageClassName": { + "type": "string" + }, + "size": { + "type": "string" + } + } + }, + "podAntiAffinityType": { + "type": "string", + "enum": [ + "preferred", + "required" + ] + }, + "parameters": { + "type": "object" + }, + "synchronous": { + "type": "object" + }, + "bootstrap": { + "type": "object" + }, + "externalClusters": { + "type": "array" + } + } + }, + "nodePort": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "port": { + "type": [ + "integer", + "string" + ] + } + } } } }, @@ -987,8 +1113,111 @@ }, "password": { "$ref": "#/definitions/natsPassword" + }, + "install": { + "type": "boolean" + } + } + }, + "global": { + "type": "object" + }, + "natsServer": { + "type": "object", + "description": "values of the nats subchart (nats.install)" + }, + "idpGithub": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "replicas": { + "type": "integer" + }, + "image": { + "$ref": "#/definitions/image" + }, + "github": { + "type": "object", + "additionalProperties": false, + "properties": { + "clientId": { + "$ref": "#/definitions/secretRef" + }, + "clientSecret": { + "$ref": "#/definitions/secretRef" + }, + "appSlug": { + "type": "string" + }, + "onboardRules": { + "type": "array" + }, + "onboardRuleTemplate": { + "type": "string" + } + } + }, + "githubUserTemplate": { + "type": "string" + } + } + }, + "idpGoogle": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "replicas": { + "type": "integer" + }, + "image": { + "$ref": "#/definitions/image" + }, + "google": { + "type": "object", + "additionalProperties": false, + "properties": { + "clientId": { + "$ref": "#/definitions/secretRef" + }, + "clientSecret": { + "$ref": "#/definitions/secretRef" + }, + "allowedDomains": { + "type": "array", + "items": { + "type": "string" + } + }, + "allowPersonal": { + "type": "boolean" + }, + "personalEmailDomains": { + "type": "array", + "items": { + "type": "string" + } + }, + "personalAllowedEmails": { + "type": "array", + "items": { + "type": "string" + } + }, + "onboardRules": { + "type": "array" + }, + "onboardRuleTemplate": { + "type": "string" + } + } } } } } -} \ No newline at end of file +} diff --git a/k8shell/values.yaml b/k8shell/values.yaml index f2f8d22..a692cb8 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -4,6 +4,12 @@ # k8shell Helm chart. Users can override these values by providing their own # values.yaml file or by using --set during helm install/upgrade commands. # +# The chart installs the whole platform: the k8shell services, PostgreSQL +# (postgresql.mode), NATS (nats.install, values under natsServer) and the +# optional identity providers (idpGithub, idpGoogle). Not installed: cert-manager +# (certManager.enabled), the CloudNativePG operator (postgresql.mode cnpg) and +# the Secrets the fields below refer to by secretName. +# # NOTE on usernames/passwords: # usernames and passwords are provided as env variables in Pods. # When a field with name "field1" has a value of {}, there can be following @@ -192,7 +198,8 @@ identity: blueprints: ["*"] sudo: true shell: /bin/bash - roles: [admin] + # developer: may also inject workspaces into existing workloads + roles: [admin, developer] organization: "default" password: "" publicKey: "" @@ -212,7 +219,9 @@ identity: # publicKey: "" # onboardRules is a list of explicit allow/deny/waitlist rules matched against - # incoming users from remote identity providers during onboarding. + # incoming users from remote identity providers during onboarding. Users no + # rule allows are rejected. The users above get an allow rule automatically + # (provider idp.k8shell.io/file, with their organization, roles and sudo). onboardRules: [] # - idp: "idp.k8shell.io/github" # usernamePattern: "bobmarley" @@ -231,14 +240,20 @@ identity: # authz is the authorization service that evaluates OPA policies. authz: - enabled: false + enabled: true replicas: 1 image: repository: ghcr.io/k8shell-io/authz tag: v0.3.3 # policiesConfigMap is the name of an existing ConfigMap whose keys are - # mounted as policy files into /app/policies. Leave empty to omit the mount. + # mounted as policy files (*.rego) into /app/policies, replacing the chart's + # default policies. Empty: the chart creates the ConfigMap + # authz-policies-default from files/policies/. The default policies hold no + # site-specific settings: what users may do follows from their roles + # (admin, org-admin, -admin, developer for inject mode, + # git-workspace for repositories). A replacement must hold the complete + # policy set (copy the chart's files/policies/ as a starting point). policiesConfigMap: "" # defaultPolicy is the inline OPA Rego policy used when no policy file matches. @@ -273,16 +288,27 @@ provisioner: repository: ghcr.io/k8shell-io/k8shelld tag: v0.17.3 + # blueprintsConfigMap is the name of an existing ConfigMap with blueprint + # files that replaces the chart's defaults (the ConfigMap blueprint-base-files + # with files/blueprints/base.yaml and, with includeBlueprintSamples, + # samples.yaml). A replacement must define the "base" template if any of its + # blueprints (or those of blueprintFilesConfigMaps) extend it. + blueprintsConfigMap: "" + # if true, the sample blueprints (samples.yaml) will be included alongside - # the base blueprints (base.yaml). base.yaml is always included. + # the base blueprints (base.yaml). Only used without blueprintsConfigMap. includeBlueprintSamples: true - # defaultCustomBlueprint is the default blueprint when custom blueprint - # does not exist in a git repository - defaultCustomBlueprint: base + # defaultCustomBlueprint is the default blueprint when custom blueprint + # does not exist in a git repository. Empty: "git-dev" when a git identity + # provider (idpGithub) is enabled, otherwise "base". + defaultCustomBlueprint: "" - # optional list of configmaps that provide extra files for workspace blueprints - # their files are mounted into /app/blueprints together with blueprint-base-files + # optional list of ConfigMaps with additional blueprint files, mounted into + # /app/blueprints together with the defaults (or blueprintsConfigMap); the + # git-blueprints ConfigMap is added automatically when idpGithub is enabled. + # File names must be unique across all of them, blueprint names across all + # files (the provisioner refuses duplicates). blueprintFilesConfigMaps: [] # targetNamespace is the namespace where provisioner will create workspaces. @@ -332,7 +358,8 @@ provisioner: # shells configures PTY shell session behavior for k8shell workspaces. shells: # allowSessionDetach controls whether clients can detach from PTY shell sessions - allowSessionDetach: false + # (and reattach to them); the web terminal needs it + allowSessionDetach: true # detachedTTL is how long a detached session is kept alive before automatic termination detachedTTL: "30m" # allowUnlimittedTTL allows clients to set unlimited TTL for detached sessions @@ -355,13 +382,9 @@ provisioner: -# Below services are disabled in k8shell chart. They are used in k8shell-bundle -# that provides full set of k8shell services with postgresql and nats -# dependencies. - # frontend serves the k8shell web UI. frontend: - enabled: false + enabled: true replicas: 1 image: repository: ghcr.io/k8shell-io/frontend @@ -375,11 +398,12 @@ frontend: maxAgeSeconds: 86400 path: /api/v1 features: - navigation: "" + # web UI navigation (sidebar): off, short or full + navigation: full # apiServer provides the k8shell REST API. apiServer: - enabled: false + enabled: true replicas: 1 image: repository: ghcr.io/k8shell-io/api-server @@ -391,9 +415,9 @@ apiServer: enabled: false # infraVersionsConfigMap is the name of an existing ConfigMap holding version - # info for external infra services (e.g. postgresql, nats). When set, it is - # mounted into api-server at /app/infra-versions. When empty, nothing is - # mounted. k8shell-bundle populates this automatically. + # info for infra services (e.g. postgresql, nats), mounted into api-server at + # /app/infra-versions. Empty: the chart's own k8shell-infra-versions, with the + # versions of the PostgreSQL and NATS it installs. infraVersionsConfigMap: "" # workspaces configures the domain used to build ssh / VS Code Remote connection strings for workspaces. @@ -403,7 +427,7 @@ apiServer: # session manages terminal session state and recording. session: - enabled: false + enabled: true replicas: 1 image: repository: ghcr.io/k8shell-io/session @@ -477,19 +501,240 @@ sshShield: # every gRPC call. Must match the authKey configured on the nfgate server. authKey: {} -# postgresql is the database backend for identity, session, and provisioner services. + +# postgresql is the database of identity, session, provisioner, authz and the +# identity providers. postgresql: - enabled: false - host: "postgresql" + enabled: true + # mode decides who runs the database: + # simple: the chart runs a single PostgreSQL instance (StatefulSet with + # one pod), no prerequisites; no HA, no built-in backups + # cnpg: the chart creates a CloudNativePG Cluster (HA, failover); + # the CloudNativePG operator must be installed + # external: an existing server at host:port, nothing is installed + mode: simple + # simple/cnpg: the Service the chart creates for the primary + host: "db-postgresql" port: 5432 - database: "" + database: "postgres" + # credentials of the k8shell services; simple mode creates this user as the + # superuser, cnpg mode expects the superuser "postgres" (see cnpg below) username: {} password: {} + resources: {} + + simple: + image: + repository: postgres + tag: "18" + persistence: + # false: emptyDir, the data is lost when the pod is deleted + enabled: true + # an existing PVC to use instead of the one the chart creates + existingClaim: "" + # empty: the cluster's default StorageClass + storageClassName: "" + size: 10Gi + annotations: {} + # node selection for the database pod (its volume may be node-local) + nodeSelector: {} + tolerations: [] + affinity: {} + + cnpg: + instances: 3 + # empty = operator default image + imageName: "" + # kubernetes.io/basic-auth Secret with username "postgres" and the password + # of postgresql.password, created outside the chart + superuserSecret: db-postgresql-superuser + storage: + storageClassName: "" + size: 20Gi + # "preferred" spreads instances over nodes when possible, "required" insists + podAntiAffinityType: preferred + # postgresql.conf parameters + parameters: {} + # e.g. { method: any, number: 1 } for quorum synchronous replication; + # empty = asynchronous replicas + synchronous: {} + # replaces the default initdb bootstrap, e.g. initdb.import or recovery + bootstrap: {} + externalClusters: [] + + # additional NodePort Service to the primary (simple and cnpg modes) + nodePort: + enabled: false + port: "" # nats is the message broker used for inter-service communication and KV storage. nats: - enabled: false + enabled: true + # install the NATS server (subchart, values under natsServer); false: use an + # existing server at host:port + install: true host: "nats" port: 4222 + # the user the k8shell services connect as; natsServer's auth.conf defines it username: "k8shell-service" + # with nats.install the NATS server reads the password from the same Secret: + # .value -> the chart's Secret int-nats (natsServer default); .secretName -> + # set natsServer.container.env.NATS_K8SHELL_PASSWORD to the same Secret/key password: {} + +# natsServer configures the NATS server installed with nats.install: values of +# the official chart (https://github.com/nats-io/k8s/tree/main/helm/charts/nats). +# The defaults run a cluster of 3 servers with JetStream on 10Gi volumes: the +# k8shell services create JetStream KV buckets with 3 replicas, which a single +# server refuses. +natsServer: + fullnameOverride: nats + container: + image: + repository: nats + tag: "2.11.9-alpine" + env: + NATS_K8SHELL_PASSWORD: + valueFrom: + secretKeyRef: + name: int-nats + key: NATS_K8SHELL_PASSWORD + config: + cluster: + enabled: true + replicas: 3 + merge: + $include: auth.conf + jetstream: + enabled: true + fileStore: + enabled: true + pvc: + enabled: true + size: 10Gi + # storageClassName: "" + configMap: + merge: + data: + auth.conf: | + authorization: { + users: [ + { + user: "k8shell-service", + password: $NATS_K8SHELL_PASSWORD, + permissions: { + subscribe: { allow: [">"] }, + publish: { allow: [">"] } + } + }, + ] + } + natsBox: + enabled: true + statefulSet: + merge: + spec: + persistentVolumeClaimRetentionPolicy: + whenDeleted: Delete + +# idpGithub is the GitHub identity provider (users sign in with GitHub, through +# a GitHub App). It uses the settings above (certManager, grpc, authEnabled, +# imageRegistry, nats, postgresql) and is added to identity.remoteProviders +# automatically. +idpGithub: + enabled: false + replicas: 1 + image: + repository: ghcr.io/k8shell-io/idp-github + tag: v0.14.3 + + github: + # client ID/secret of the GitHub App + clientId: {} + clientSecret: {} + appSlug: "k8shell-io" + + # onboardRules is a list of explicit allow/deny/waitlist rules matched against + # incoming GitHub users before onboardRuleTemplate is applied. + onboardRules: [] + # - username: "bobmarley" + # sudo: true + # roles: ["admin"] + # action: "allow" + + # onboardRuleTemplate is the fallback rule applied to users not matched by onboardRules. + # Stored as a raw string to preserve !cel tags (Helm's YAML parser strips custom tags). + onboardRuleTemplate: | + username: !cel "user.login" + fullname: !cel "has(user.name) && user.name != null ? user.name : ''" + uid: !cel "uint(user.id)" + gid: !cel "uint(user.id)" + email: !cel | + emails.exists(e, e.primary == true) + ? emails.filter(e, e.primary == true)[0].email + : "unknown@nowhere.com" + + # githubUserTemplate is used to map the user from github to the k8shell user. + # Stored as a raw string to preserve !cel tags (Helm's YAML parser strips custom tags). + githubUserTemplate: | + user: + username: !cel "user.login" + fullname: "" + uid: !cel "100000 + int(user.id)" + gid: !cel "100000 + int(user.id)" + email: !cel | + emails.exists(e, e.primary == true) + ? emails.filter(e, e.primary == true)[0].email + : "unknown@nowhere.com" + auths: [publickey] + blueprints: ["*"] + roles: ["workspace-user"] + isValid: true + shell: "/bin/bash" + sudo: true + organization: "github" + +# idpGoogle is the Google identity provider (Google Workspace and, optionally, +# personal Google accounts). Like idpGithub it uses the shared settings above +# and is added to identity.remoteProviders automatically. +idpGoogle: + enabled: false + replicas: 1 + image: + repository: ghcr.io/k8shell-io/idp-google + # as in the idp-google chart 0.1.1 (no release tag yet) + tag: pr-1-4952aba + + google: + # OAuth 2.0 "Web application" client from Google Cloud Console (APIs & Services > + # Credentials). Its authorized redirect URIs must include the URI the identity + # client passes to OnboardUserWebFlow. + clientId: {} + clientSecret: {} + + # --- Who may sign in (hard gate, evaluated before the template below) --------- + # Google Workspace domains ("hd" claim) that may sign in. "*" admits any Workspace. + allowedDomains: [] + + # Personal Google accounts (no "hd" claim, e.g. @gmail.com). Off by default. + allowPersonal: false + # Email domains accepted for personal accounts (default: gmail.com, googlemail.com). + personalEmailDomains: [] + # Narrow personal sign-in to exactly these addresses (empty = any personal account). + personalAllowedEmails: [] + + # --- What an admitted user gets ------------------------------------------------- + # Fixed rules per username (the username the template produces), taking priority + # over the template. They never bypass the gate above. + onboardRules: [] + + # onboardRuleTemplate is the fallback rule applied to admitted users. + # Stored as a raw string to preserve !cel tags (Helm's YAML parser strips custom tags). + # See the idp-google chart for the CEL scope (claims, personal, uid, emailLocal, + # emailDomain, emailProvider). + onboardRuleTemplate: | + username: !cel "emailLocal" + fullname: !cel "claims.name" + email: !cel "claims.email" + uid: !cel "uid" + gid: !cel "uid" From 5c5b683b8fe9bd10c0131089d6a5dbbbdbe4433c Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 13:15:33 +0100 Subject: [PATCH 09/17] chart-k8shell: add the NATS repository before the dependency build Co-Authored-By: Claude Opus 5.5 --- .github/workflows/chart-k8shell.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/chart-k8shell.yaml b/.github/workflows/chart-k8shell.yaml index 87c8151..7008d5c 100644 --- a/.github/workflows/chart-k8shell.yaml +++ b/.github/workflows/chart-k8shell.yaml @@ -50,7 +50,8 @@ jobs: - name: Package helm chart run: | mkdir -p dist - # the NATS subchart (Chart.lock) + # the NATS subchart (Chart.lock); build needs the repository known + helm repo add nats https://nats-io.github.io/k8s/helm/charts/ helm dependency build k8shell helm package k8shell -d dist/ --version "${{ steps.ver.outputs.chart_version }}" From 4a860d6b44dd8a23659b2a20b6ea59f0a9a4be2f Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 13:36:46 +0100 Subject: [PATCH 10/17] Organizations and roles from identity.organizations and identity.roles identity has no built-in organization any more (k8shell-io/identity#46): - identity.roles: global roles created at startup if missing (defaults developer and git-workspace, used by the default policies) - identity.organizations: organizations created at startup if missing, with node selectors (set only while the organization has none; default organization "default" on all Linux nodes, so workspaces start without a manual step) and organization-scoped roles (admin and org-admin rejected) - identity.users: organization required and checked against identity.organizations; no fallback to "default" - values-internal.yaml: identity image of PR #46 at f9ec532 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 + .../templates/identity/cm-identity-users.yaml | 2 +- k8shell/templates/identity/cm-identity.yaml | 12 +++- k8shell/templates/validate.yaml | 9 ++- k8shell/values-internal.yaml | 6 +- k8shell/values.schema.json | 72 ++++++++++++++++++- k8shell/values.yaml | 28 +++++++- 7 files changed, 123 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6f909f7..8feac32 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,6 +51,8 @@ The k8shell chart deploys two tiers of services: - `nats` — `nats.install` adds the official NATS chart as the subchart `natsServer` (values under `natsServer`, `fullnameOverride: nats`). `nats.enabled` still means "the services use NATS"; `templates/validate.yaml` checks that the NATS server reads the same password Secret as the services. - `k8shell-infra-versions` ConfigMap (versions of the installed PostgreSQL/NATS for api-server) is created automatically. +**Organizations and roles:** identity has no built-in organization. `identity.organizations` (name, description, nodeSelectors, organization-scoped roles) and `identity.roles` (global roles besides the built-in `admin` and `org-admin`; defaults `developer`, `git-workspace`) are rendered into identity's config and created at startup if missing; node selectors are set only while an organization has none. Every entry of `identity.users` needs an `organization` declared there (`templates/validate.yaml`) and gets an onboarding rule with its organization, roles and sudo. + **Identity providers (disabled by default):** `idpGithub`, `idpGoogle` — templates in `templates/idp-github/`, `templates/idp-google/`, using the chart's shared settings (certManager, grpc, authEnabled, imageRegistry, nats, postgresql). Enabled providers are appended to `identity.remoteProviders`; idpGithub also adds the `git-blueprints` ConfigMap (`files/git-blueprints/`) and makes `git-dev` the default custom blueprint. Service-to-service communication is gRPC. When `certManager.enabled: true`, every service gets a cert-manager-issued TLS certificate and the chart wires mTLS automatically. Without cert-manager, services fall back to plaintext. diff --git a/k8shell/templates/identity/cm-identity-users.yaml b/k8shell/templates/identity/cm-identity-users.yaml index 0c3c658..5a30da3 100644 --- a/k8shell/templates/identity/cm-identity-users.yaml +++ b/k8shell/templates/identity/cm-identity-users.yaml @@ -32,7 +32,7 @@ data: shell: {{ default "/bin/bash" .shell }} auths: [{{ $auths | join ", " }}] roles: {{ .roles | toJson }} - organization: {{ default "default" .organization | quote }} + organization: {{ .organization | quote }} {{- if ne $pub "" }} authKeys: !file /app/secrets/users/{{ .username }}/publickey {{- end }} diff --git a/k8shell/templates/identity/cm-identity.yaml b/k8shell/templates/identity/cm-identity.yaml index adf883c..e4c2f6c 100644 --- a/k8shell/templates/identity/cm-identity.yaml +++ b/k8shell/templates/identity/cm-identity.yaml @@ -99,13 +99,23 @@ data: identity rejects users no rule allows */}} {{- $rules := concat (.Values.identity.onboardRules | default list) list }} {{- range .Values.identity.users }} - {{- $rules = append $rules (dict "idp" "idp.k8shell.io/file" "usernamePattern" .username "org" (default "default" .organization) "action" "allow" "sudo" (default false .sudo) "roles" (default list .roles)) }} + {{- $rules = append $rules (dict "idp" "idp.k8shell.io/file" "usernamePattern" .username "org" .organization "action" "allow" "sudo" (default false .sudo) "roles" (default list .roles)) }} {{- end }} {{- with $rules }} onboardRules: {{- toYaml . | nindent 6 }} {{- end }} + {{- /* created at startup if missing, before the onboarding rules */}} + {{- with .Values.identity.roles }} + roles: + {{- toYaml . | nindent 6 }} + {{- end }} + {{- with .Values.identity.organizations }} + organizations: + {{- toYaml . | nindent 6 }} + {{- end }} + # Password brute-force lockout for AuthUserPassword passwordLockout: maxAttempts: {{ .Values.identity.passwordLockout.maxAttempts }} diff --git a/k8shell/templates/validate.yaml b/k8shell/templates/validate.yaml index bbf5dd3..baf2dfc 100644 --- a/k8shell/templates/validate.yaml +++ b/k8shell/templates/validate.yaml @@ -1,4 +1,4 @@ -{{- /* checks of the database and NATS settings; renders nothing */}} +{{- /* checks of the settings; renders nothing */}} {{- if .Values.postgresql.enabled }} {{- $mode := include "k8shell.postgresqlMode" . }} {{- include "k8shell.requireSecret" (dict "field" .Values.postgresql.username "path" "postgresql.username") }} @@ -18,3 +18,10 @@ {{- fail (printf "the NATS server must read the password the services use: set natsServer.container.env.NATS_K8SHELL_PASSWORD.valueFrom.secretKeyRef to name %q, key %q (now %q, %q)" $name $key $ref.name $ref.key) }} {{- end }} {{- end }} +{{- $orgs := list }} +{{- range .Values.identity.organizations }}{{ $orgs = append $orgs .name }}{{ end }} +{{- range .Values.identity.users }} +{{- if not (has .organization $orgs) }} +{{- fail (printf "identity.users: the organization %q of user %q must be declared in identity.organizations (declared: %s)" (toString .organization) .username (join ", " $orgs)) }} +{{- end }} +{{- end }} diff --git a/k8shell/values-internal.yaml b/k8shell/values-internal.yaml index 37215d1..894db90 100644 --- a/k8shell/values-internal.yaml +++ b/k8shell/values-internal.yaml @@ -11,9 +11,9 @@ sshProxy: identity: image: repository: registry.k8shell.io/k8shell-base/identity - # TODO: identity PR #46 (local users: uid/gid, password; developer and - # git-workspace roles); replace with the release that contains it - tag: pr-46-723947c + # TODO: identity PR #46 (local users: uid/gid, password; organizations and + # roles from the config); replace with the release that contains it + tag: pr-46-f9ec532 authz: image: diff --git a/k8shell/values.schema.json b/k8shell/values.schema.json index 946ba23..d105c7e 100644 --- a/k8shell/values.schema.json +++ b/k8shell/values.schema.json @@ -359,7 +359,8 @@ "required": [ "username", "uid", - "gid" + "gid", + "organization" ], "properties": { "username": { @@ -462,6 +463,75 @@ } } } + }, + "roles": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string" + } + } + } + }, + "organizations": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string" + }, + "nodeSelectors": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "roles": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "minLength": 1, + "not": { + "enum": [ + "admin", + "org-admin" + ] + } + }, + "description": { + "type": "string" + } + } + } + } + } + } } } }, diff --git a/k8shell/values.yaml b/k8shell/values.yaml index a692cb8..cca6f8e 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -189,6 +189,32 @@ identity: # trailing 24h window. 0 disables the cap. dailyRecipientCap: 0 + # roles are global roles created at startup if missing, besides the built-in + # admin and org-admin. The default policies give developer inject mode and + # git-workspace the repositories and git workspaces of external identity + # providers. Existing roles are left untouched. + roles: + - name: developer + description: Inject workspaces into existing workloads + - name: git-workspace + description: Repository catalog and git-sourced workspaces of the identity provider + + # organizations are created at startup if missing; no organization is built + # in. nodeSelectors (label key -> value) place the workspaces of an + # organization's users and are set only while the organization has none, so + # changes made in the admin UI are kept; without any, an admin must set them + # before its users can start workspaces. roles are organization-scoped roles + # (admin and org-admin cannot be declared here: they are global). + organizations: + - name: default + description: Default organization + nodeSelectors: + kubernetes.io/os: linux + roles: [] + + # users are local users (identity's user file). organization is required and + # must be one of the organizations above; each user gets an onboarding rule + # with its organization, roles and sudo. users: - username: "admin" uid: 1001 @@ -213,7 +239,7 @@ identity: # blueprints: ["*"] # sudo: false # shell: /bin/bash - # roles: [workspace-user] + # roles: [developer] # organization: "default" # password: "" # publicKey: "" From 97ebfd6d0b834a4944b88ab2f3e117a863222801 Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 13:41:35 +0100 Subject: [PATCH 11/17] Organization node selector keys must be provisioner.nodeSelectorKeys The provisioner rejects node selector keys it does not discover (provisioner.nodeSelectorKeys), so the default organization's kubernetes.io/os: linux matched "no nodes". kubernetes.io/os is now one of the default keys, and the chart refuses organizations using other keys. Co-Authored-By: Claude Opus 5.5 --- k8shell/templates/validate.yaml | 9 +++++++++ k8shell/values.yaml | 2 ++ 2 files changed, 11 insertions(+) diff --git a/k8shell/templates/validate.yaml b/k8shell/templates/validate.yaml index baf2dfc..a67708d 100644 --- a/k8shell/templates/validate.yaml +++ b/k8shell/templates/validate.yaml @@ -25,3 +25,12 @@ {{- fail (printf "identity.users: the organization %q of user %q must be declared in identity.organizations (declared: %s)" (toString .organization) .username (join ", " $orgs)) }} {{- end }} {{- end }} +{{- $keys := .Values.provisioner.nodeSelectorKeys | default list }} +{{- range .Values.identity.organizations }} +{{- $org := .name }} +{{- range $k, $v := .nodeSelectors }} +{{- if not (has $k $keys) }} +{{- fail (printf "identity.organizations: node selector key %q of organization %q must be one of provisioner.nodeSelectorKeys (%s): the provisioner rejects other keys" $k $org (join ", " $keys)) }} +{{- end }} +{{- end }} +{{- end }} diff --git a/k8shell/values.yaml b/k8shell/values.yaml index cca6f8e..f286d96 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -360,8 +360,10 @@ provisioner: # placement options (see the GetNodeSelectorOptions RPC). When non-empty, a # ClusterRole granting get/list/watch on nodes is created for the provisioner. # Set to [] to disable node discovery. + # The node selectors of identity.organizations may only use these keys. nodeSelectorKeys: - k8shell.io/pool + - kubernetes.io/os # defaultRegistry is the default registry host for workspace images when no # registry is specified in a blueprint. From d1406ad5e90245a5aa0986043695e68e1828bd4a Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 17:45:23 +0100 Subject: [PATCH 12/17] Images from registry.k8shell.io with the latest releases; quickstart logs in ghcr.io lacks the current releases and some images are not public, so the chart's defaults now use registry.k8shell.io (for now) with the latest release of each service: identity v0.18.5 and frontend v0.18.4 (the fixes of k8shell-io/identity#46 and k8shell-io/frontend#89), api-server v0.21.1, the others unchanged. values-internal.yaml no longer overrides anything. The registry needs credentials: quickstart.sh takes --registry-username and --registry-password (or K8SHELL_REGISTRY_USERNAME/PASSWORD) and writes them to a values file for the pull Secret and the provisioner's private registry (k8shelld in workspaces). Tested: quickstart into an empty namespace on cozy-dev, SSH into an Ubuntu workspace. Co-Authored-By: Claude Opus 5.5 --- bin/quickstart.sh | 33 +++++++++++++++++++++- k8shell/values-internal.yaml | 55 +++--------------------------------- k8shell/values.yaml | 36 ++++++++++++----------- 3 files changed, 56 insertions(+), 68 deletions(-) diff --git a/bin/quickstart.sh b/bin/quickstart.sh index f7e2c0b..cbfd7e0 100755 --- a/bin/quickstart.sh +++ b/bin/quickstart.sh @@ -24,6 +24,9 @@ CHART_VERSION="" CHART_REF="oci://ghcr.io/k8shell-io/charts/k8shell" VALUES_FILES=() ASSUME_YES="false" +REGISTRY_HOST="registry.k8shell.io" +REGISTRY_USERNAME="${K8SHELL_REGISTRY_USERNAME:-}" +REGISTRY_PASSWORD="${K8SHELL_REGISTRY_PASSWORD:-}" NAMESPACE="k8shell-system" TARGET_NAMESPACE="k8shell-workspaces" QUICKSTART_DIR="${K8SHELL_QUICKSTART_DIR:-$HOME/k8shell-quickstart}" @@ -49,6 +52,9 @@ Options: -f, --values FILE Additional values file (repeatable), e.g. for a private registry -y, --yes Do not ask for confirmation + --registry-username U Username for $REGISTRY_HOST, where the images + come from (or K8SHELL_REGISTRY_USERNAME) + --registry-password P Its password (or K8SHELL_REGISTRY_PASSWORD) -n, --namespace NS k8shell release namespace (default: $NAMESPACE) -t, --target-namespace NS Workspace target namespace (default: $TARGET_NAMESPACE) --node-port PORT Expose SSH via NodePort (default: $NODE_PORT) @@ -65,6 +71,8 @@ while [[ $# -gt 0 ]]; do -c|--chart) CHART_REF="$2"; shift 2 ;; -f|--values) VALUES_FILES+=("$2"); shift 2 ;; -y|--yes) ASSUME_YES="true"; shift ;; + --registry-username) REGISTRY_USERNAME="$2"; shift 2 ;; + --registry-password) REGISTRY_PASSWORD="$2"; shift 2 ;; -n|--namespace) NAMESPACE="$2"; shift 2 ;; -t|--target-namespace) TARGET_NAMESPACE="$2"; shift 2 ;; --node-port) NODE_PORT="$2"; shift 2 ;; @@ -214,6 +222,10 @@ EOF check_prereqs +if [ -z "$REGISTRY_USERNAME" ] || [ -z "$REGISTRY_PASSWORD" ]; then + error "Credentials for $REGISTRY_HOST are required: --registry-username and --registry-password (or K8SHELL_REGISTRY_USERNAME and K8SHELL_REGISTRY_PASSWORD)" +fi + mkdir -p "$QUICKSTART_DIR" serverKeyDesc=$(describe_ec_key "$QUICKSTART_DIR/server-key.pem" | sed "s|$HOME|~|g") @@ -275,7 +287,26 @@ fi info "Running helm $helmAction for k8shell ${CHART_VERSION:-latest}..." -valuesArgs=() +# Registry credentials as a values file (not --set: passwords may hold +# commas); services pull with the pull Secret, workspaces pull k8shelld through +# the provisioner's private registry. +yamlQuote() { printf "'%s'" "${1//\'/\'\'}"; } +registryValues="$QUICKSTART_DIR/registry-values.yaml" +(umask 077; cat > "$registryValues" < Date: Mon, 9 Nov 2026 17:45:40 +0100 Subject: [PATCH 13/17] quickstart: chart from registry.k8shell.io, logged in with the registry credentials Co-Authored-By: Claude Opus 5.5 --- bin/quickstart.sh | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/bin/quickstart.sh b/bin/quickstart.sh index cbfd7e0..6955117 100755 --- a/bin/quickstart.sh +++ b/bin/quickstart.sh @@ -21,7 +21,7 @@ set -euo pipefail SCRIPT_VERSION="1.0.0" CHART_VERSION="" -CHART_REF="oci://ghcr.io/k8shell-io/charts/k8shell" +CHART_REF="oci://registry.k8shell.io/charts/k8shell" VALUES_FILES=() ASSUME_YES="false" REGISTRY_HOST="registry.k8shell.io" @@ -307,6 +307,13 @@ EOV ) valuesArgs=(-f "$registryValues") + +# the chart itself is in the same registry +if [[ "$CHART_REF" == "oci://$REGISTRY_HOST/"* ]]; then + printf '%s' "$REGISTRY_PASSWORD" | helm registry login "$REGISTRY_HOST" \ + --username "$REGISTRY_USERNAME" --password-stdin >/dev/null \ + || error "helm registry login to $REGISTRY_HOST failed" +fi for f in ${VALUES_FILES[@]+"${VALUES_FILES[@]}"}; do valuesArgs+=(-f "$f") done From c06936c731f93d263e625a3eb592a2ec31be9eb1 Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 17:54:01 +0100 Subject: [PATCH 14/17] certManager.ingressIssuer: separate issuer for the web host's certificate e.g. Let's Encrypt for a public host while the services' certificates come from an internal CA (certManager.issuer). Empty name: certManager.issuer, as before; duration/renewBefore apply only then. Co-Authored-By: Claude Opus 5.5 --- k8shell/templates/frontend/cert-ingress.yaml | 8 ++++++-- k8shell/values.schema.json | 16 ++++++++++++++++ k8shell/values.yaml | 7 +++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/k8shell/templates/frontend/cert-ingress.yaml b/k8shell/templates/frontend/cert-ingress.yaml index c3f83c5..71857de 100644 --- a/k8shell/templates/frontend/cert-ingress.yaml +++ b/k8shell/templates/frontend/cert-ingress.yaml @@ -6,16 +6,20 @@ metadata: name: ingress-cert spec: secretName: ingress-tls + {{- if not .Values.certManager.ingressIssuer.name }} duration: {{ .Values.certManager.duration }} renewBefore: {{ .Values.certManager.renewBefore }} + {{- end }} commonName: {{ .Values.frontend.host }} dnsNames: - {{ .Values.frontend.host }} - "*.{{ .Values.frontend.host }}" usages: - server auth + {{- $issuer := .Values.certManager.issuer }} + {{- if .Values.certManager.ingressIssuer.name }}{{ $issuer = .Values.certManager.ingressIssuer }}{{ end }} issuerRef: - name: {{ .Values.certManager.issuer.name }} - kind: {{ .Values.certManager.issuer.kind }} + name: {{ $issuer.name }} + kind: {{ $issuer.kind }} {{- end }} {{- end }} \ No newline at end of file diff --git a/k8shell/values.schema.json b/k8shell/values.schema.json index d105c7e..e2cc6b2 100644 --- a/k8shell/values.schema.json +++ b/k8shell/values.schema.json @@ -120,6 +120,22 @@ }, "renewBefore": { "type": "string" + }, + "ingressIssuer": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "Issuer", + "ClusterIssuer" + ] + } + } } } }, diff --git a/k8shell/values.yaml b/k8shell/values.yaml index 2769503..b8ff63f 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -55,6 +55,13 @@ certManager: kind: ClusterIssuer duration: 24h renewBefore: 12h + # ingressIssuer issues the certificate of the web host (frontend.host and + # *.frontend.host), e.g. a public ACME issuer while the services use an + # internal CA; empty name: issuer above. Its certificate keeps the issuer's + # own lifetime (duration/renewBefore apply to the services only). + ingressIssuer: + name: "" + kind: ClusterIssuer grpc: # enables client-side load balancing for gRPC communication between services. From cd97a4cd954c81e59b6d951779fad316947b56ce Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 17:58:40 +0100 Subject: [PATCH 15/17] api-server back to v0.19.4 The registry's v0.21.1 has no tag in k8shell-io/api-server (newest v0.19.5, not built) and lacks /auth/login/password. Co-Authored-By: Claude Opus 5.5 --- k8shell/values.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k8shell/values.yaml b/k8shell/values.yaml index b8ff63f..05ceffa 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -446,7 +446,7 @@ apiServer: replicas: 1 image: repository: registry.k8shell.io/k8shell-base/api-server - tag: v0.21.1 + tag: v0.19.4 logging: requestHeaders: false responseHeaders: false From 0f6a66a1a77e28185b0d753f50b3758a6b95d662 Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 18:01:32 +0100 Subject: [PATCH 16/17] Schema: priority and note on identity.onboardRules identity supports both (a catch-all rule with a higher priority number ranks below exact matches); the schema rejected them. Co-Authored-By: Claude Opus 5.5 --- k8shell/values.schema.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/k8shell/values.schema.json b/k8shell/values.schema.json index e2cc6b2..09ca5f0 100644 --- a/k8shell/values.schema.json +++ b/k8shell/values.schema.json @@ -476,6 +476,12 @@ "items": { "type": "string" } + }, + "priority": { + "type": "integer" + }, + "note": { + "type": "string" } } } From e6695be775e9ffd0e1b8c21c3c7b4531add06b9d Mon Sep 17 00:00:00 2001 From: bruckins Date: Mon, 9 Nov 2026 18:32:56 +0100 Subject: [PATCH 17/17] Session cookie path / by default With /api/v1 the browser never sends the session cookie to workspace apps on --., and api-server redirects every app request to sign-in. env-dev uses / as well. Co-Authored-By: Claude Opus 5.5 --- k8shell/values.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/k8shell/values.yaml b/k8shell/values.yaml index 05ceffa..52c37ee 100644 --- a/k8shell/values.yaml +++ b/k8shell/values.yaml @@ -435,7 +435,9 @@ frontend: httpOnly: true sameSite: Strict maxAgeSeconds: 86400 - path: /api/v1 + # "/": the cookie (domain .) must also reach workspace apps + # on the subdomains --. + path: / features: # web UI navigation (sidebar): off, short or full navigation: full