diff --git a/deployments/archie/compose.enterprise.yml b/deployments/archie/compose.enterprise.yml new file mode 100644 index 000000000..e2b27939b --- /dev/null +++ b/deployments/archie/compose.enterprise.yml @@ -0,0 +1,80 @@ +# Hardened enterprise overlay for deployments/archie/compose.yml. +# Usage: docker compose -f compose.yml -f compose.enterprise.yml up -d +# +# Ensure ./config.toml omits database.owner_url and ./secrets/* holds: +# - db_runtime_url (DML-only archie_app connection string) +# - db_owner_url (DDL archie_owner connection string, mounted only in archie-migrate) +# - age_identity (AGE-SECRET-KEY-1...) +# - admin_token_sha256 (hex SHA-256) + +services: + archie-migrate: + image: ${ARCHIE_IMAGE:-gcr.io/distroless/static-debian12:nonroot} + restart: "no" + user: "65532:65532" + read_only: true + tmpfs: + - /tmp:rw,noexec,nosuid,nodev,size=64m + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + entrypoint: ["/archie/archie"] + command: ["-config", "", "migrate"] + environment: + HOME: /tmp + SSL_CERT_FILE: /etc/ssl/certs/enterprise-ca.crt + ARCHIE_DATABASE_URL_FILE: /run/secrets/db_runtime_url + ARCHIE_DATABASE_OWNER_URL_FILE: /run/secrets/db_owner_url + secrets: + - db_runtime_url + - db_owner_url + volumes: + - ./bin/archie:/archie/archie:ro + - ${ARCHIE_CA_BUNDLE:-./certs/enterprise-ca.crt}:/etc/ssl/certs/enterprise-ca.crt:ro + networks: [internal] + depends_on: + archie-db: + condition: service_healthy + + archie: + image: ${ARCHIE_IMAGE:-gcr.io/distroless/static-debian12:nonroot} + user: "65532:65532" + read_only: true + tmpfs: + - /tmp:rw,noexec,nosuid,nodev,size=128m + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + - seccomp=./seccomp.json + environment: + HOME: /tmp + SSL_CERT_FILE: /etc/ssl/certs/enterprise-ca.crt + HTTPS_PROXY: ${HTTPS_PROXY:-} + HTTP_PROXY: ${HTTP_PROXY:-} + NO_PROXY: ${NO_PROXY:-localhost,127.0.0.1,archie-db} + ARCHIE_DATABASE_URL_FILE: /run/secrets/db_runtime_url + ARCHIE_AGE_IDENTITY_FILE: /run/secrets/age_identity + ARCHIE_ADMIN_TOKEN_SHA256_FILE: /run/secrets/admin_token_sha256 + secrets: + - db_runtime_url + - age_identity + - admin_token_sha256 + volumes: + - ${ARCHIE_CA_BUNDLE:-./certs/enterprise-ca.crt}:/etc/ssl/certs/enterprise-ca.crt:ro + depends_on: + archie-db: + condition: service_healthy + archie-migrate: + condition: service_completed_successfully + +secrets: + db_runtime_url: + file: ./secrets/db_runtime_url + db_owner_url: + file: ./secrets/db_owner_url + age_identity: + file: ./secrets/age_identity + admin_token_sha256: + file: ./secrets/admin_token_sha256 diff --git a/deployments/helm/archie/Chart.yaml b/deployments/helm/archie/Chart.yaml new file mode 100644 index 000000000..aeb6f88e5 --- /dev/null +++ b/deployments/helm/archie/Chart.yaml @@ -0,0 +1,13 @@ +apiVersion: v2 +name: archie +description: Event-driven agentic automation platform with pre-action governance and isolated extension execution. +type: application +version: 0.1.0 +appVersion: "1.0.0" +keywords: + - archie + - automation + - governance + - enterprise +maintainers: + - name: Archie Platform Team diff --git a/deployments/helm/archie/templates/_helpers.tpl b/deployments/helm/archie/templates/_helpers.tpl new file mode 100644 index 000000000..382edd18d --- /dev/null +++ b/deployments/helm/archie/templates/_helpers.tpl @@ -0,0 +1,78 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "archie.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +*/}} +{{- define "archie.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "archie.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels. +*/}} +{{- define "archie.labels" -}} +helm.sh/chart: {{ include "archie.chart" . }} +{{ include "archie.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels. +*/}} +{{- define "archie.selectorLabels" -}} +app.kubernetes.io/name: {{ include "archie.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +ServiceAccount name. +*/}} +{{- define "archie.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "archie.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} + +{{/* +Container image reference, preferring digest pinning when configured. +*/}} +{{- define "archie.image" -}} +{{- if .Values.image.digest }} +{{- printf "%s@%s" .Values.image.repository .Values.image.digest }} +{{- else }} +{{- printf "%s:%s" .Values.image.repository (default .Chart.AppVersion .Values.image.tag) }} +{{- end }} +{{- end }} + +{{/* +Migration secret name. +*/}} +{{- define "archie.migrateSecretName" -}} +{{- default .Values.secrets.existingSecret .Values.migrate.existingSecret }} +{{- end }} diff --git a/deployments/helm/archie/templates/configmap.yaml b/deployments/helm/archie/templates/configmap.yaml new file mode 100644 index 000000000..c1921236c --- /dev/null +++ b/deployments/helm/archie/templates/configmap.yaml @@ -0,0 +1,65 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "archie.fullname" . }}-config + labels: + {{- include "archie.labels" . | nindent 4 }} +data: + config.toml: | + listen = {{ .Values.config.listen | quote }} + state_dir = {{ .Values.config.stateDir | quote }} + shutdown_grace = {{ .Values.config.shutdownGrace | quote }} + {{- if .Values.config.ageBackupRecipients }} + age_backup_recipients = [ + {{- range $i, $r := .Values.config.ageBackupRecipients }} + {{ $r | quote }}{{ if lt $i (sub (len $.Values.config.ageBackupRecipients) 1) }},{{ end }} + {{- end }} + ] + {{- end }} + + [catalogue] + disable_auto_update = {{ .Values.config.catalogue.disableAutoUpdate }} + {{- if .Values.config.catalogue.location }} + location = {{ .Values.config.catalogue.location | quote }} + {{- end }} + {{- if .Values.config.catalogue.publicKey }} + public_key = {{ .Values.config.catalogue.publicKey | quote }} + {{- end }} + + [extensions] + require_remote = {{ .Values.config.extensions.requireRemote }} + {{- if .Values.config.extensions.tls.existingSecret }} + ca_file = {{ printf "%s/ca.crt" .Values.config.extensions.tls.mountPath | quote }} + cert_file = {{ printf "%s/tls.crt" .Values.config.extensions.tls.mountPath | quote }} + key_file = {{ printf "%s/tls.key" .Values.config.extensions.tls.mountPath | quote }} + {{- end }} + {{- range $name, $ep := .Values.config.extensions.remote }} + + [extensions.remote.{{ $name }}] + address = {{ $ep.address | quote }} + {{- if $ep.serverName }} + server_name = {{ $ep.serverName | quote }} + {{- end }} + {{- end }} + {{- if and .Values.bootstrap.enabled .Values.bootstrap.publicUrl }} + bootstrap.toml: | + public_url = {{ .Values.bootstrap.publicUrl | quote }} + {{- if .Values.bootstrap.trustedProxies }} + trusted_proxies = [ + {{- range $i, $p := .Values.bootstrap.trustedProxies }} + {{ $p | quote }}{{ if lt $i (sub (len $.Values.bootstrap.trustedProxies) 1) }},{{ end }} + {{- end }} + ] + {{- end }} + + [owner] + email = {{ .Values.bootstrap.owner.email | quote }} + display_name = {{ .Values.bootstrap.owner.displayName | quote }} + + {{- if .Values.bootstrap.oidc.issuer }} + [oidc] + issuer = {{ .Values.bootstrap.oidc.issuer | quote }} + audience = {{ .Values.bootstrap.oidc.audience | quote }} + client_id = {{ .Values.bootstrap.oidc.clientId | quote }} + {{- end }} + {{- end }} diff --git a/deployments/helm/archie/templates/externalsecret.example.yaml b/deployments/helm/archie/templates/externalsecret.example.yaml new file mode 100644 index 000000000..863e5a7cf --- /dev/null +++ b/deployments/helm/archie/templates/externalsecret.example.yaml @@ -0,0 +1,31 @@ +{{- if .Values.externalSecret.enabled -}} +# Example ExternalSecret for External Secrets Operator (Vault / OpenBao / KMS). +# Enable with externalSecret.enabled=true or copy into your GitOps manifest repo. +apiVersion: external-secrets.io/v1beta1 +kind: ExternalSecret +metadata: + name: {{ .Values.secrets.existingSecret }} + labels: + {{- include "archie.labels" . | nindent 4 }} +spec: + refreshInterval: {{ .Values.externalSecret.refreshInterval }} + secretStoreRef: + name: {{ .Values.externalSecret.secretStoreRef.name }} + kind: {{ .Values.externalSecret.secretStoreRef.kind }} + target: + name: {{ .Values.secrets.existingSecret }} + creationPolicy: Owner + data: + - secretKey: {{ .Values.secrets.keys.databaseUrl }} + remoteRef: + key: {{ .Values.externalSecret.remoteRefs.databaseUrlKey }} + property: {{ .Values.externalSecret.remoteRefs.databaseUrlProperty }} + - secretKey: {{ .Values.secrets.keys.ageIdentity }} + remoteRef: + key: {{ .Values.externalSecret.remoteRefs.ageIdentityKey }} + property: {{ .Values.externalSecret.remoteRefs.ageIdentityProperty }} + - secretKey: {{ .Values.secrets.keys.adminTokenSha256 }} + remoteRef: + key: {{ .Values.externalSecret.remoteRefs.adminTokenSha256Key }} + property: {{ .Values.externalSecret.remoteRefs.adminTokenSha256Property }} +{{- end }} diff --git a/deployments/helm/archie/templates/ingress.yaml b/deployments/helm/archie/templates/ingress.yaml new file mode 100644 index 000000000..15183ff8e --- /dev/null +++ b/deployments/helm/archie/templates/ingress.yaml @@ -0,0 +1,73 @@ +{{- if .Values.ingress.perimeter.enabled }} +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "archie.fullname" . }}-perimeter + labels: + {{- include "archie.labels" . | nindent 4 }} + app.kubernetes.io/component: perimeter-ingress + {{- with .Values.ingress.perimeter.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- if .Values.ingress.perimeter.className }} + ingressClassName: {{ .Values.ingress.perimeter.className }} + {{- end }} + {{- with .Values.ingress.perimeter.tls }} + tls: + {{- toYaml . | nindent 4 }} + {{- end }} + rules: + {{- range .Values.ingress.perimeter.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ . }} + pathType: Prefix + backend: + service: + name: {{ include "archie.fullname" $ }} + port: + name: http + {{- end }} + {{- end }} +{{- end }} +{{- if .Values.ingress.internal.enabled }} +--- +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ include "archie.fullname" . }}-internal + labels: + {{- include "archie.labels" . | nindent 4 }} + app.kubernetes.io/component: internal-ingress + {{- with .Values.ingress.internal.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + {{- if .Values.ingress.internal.className }} + ingressClassName: {{ .Values.ingress.internal.className }} + {{- end }} + {{- with .Values.ingress.internal.tls }} + tls: + {{- toYaml . | nindent 4 }} + {{- end }} + rules: + {{- range .Values.ingress.internal.hosts }} + - host: {{ .host | quote }} + http: + paths: + {{- range .paths }} + - path: {{ . }} + pathType: Prefix + backend: + service: + name: {{ include "archie.fullname" $ }} + port: + name: http + {{- end }} + {{- end }} +{{- end }} diff --git a/deployments/helm/archie/templates/job-bootstrap.yaml b/deployments/helm/archie/templates/job-bootstrap.yaml new file mode 100644 index 000000000..2849847df --- /dev/null +++ b/deployments/helm/archie/templates/job-bootstrap.yaml @@ -0,0 +1,105 @@ +{{- if .Values.bootstrap.enabled -}} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ include "archie.fullname" . }}-bootstrap + labels: + {{- include "archie.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": post-install,post-upgrade + "helm.sh/hook-weight": {{ .Values.bootstrap.hookWeight | quote }} + "helm.sh/hook-delete-policy": {{ .Values.bootstrap.hookDeletePolicy | quote }} +spec: + backoffLimit: {{ .Values.bootstrap.backoffLimit }} + activeDeadlineSeconds: {{ .Values.bootstrap.activeDeadlineSeconds }} + template: + metadata: + labels: + {{- include "archie.labels" . | nindent 8 }} + app.kubernetes.io/component: bootstrap + spec: + restartPolicy: OnFailure + serviceAccountName: {{ include "archie.serviceAccountName" . }} + automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: bootstrap + image: {{ include "archie.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - "-config" + - "" + - "-spec" + - "/etc/archie/bootstrap.toml" + - "bootstrap" + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + env: + - name: HOME + value: "/tmp" + - name: ARCHIE_DATABASE_URL_FILE + value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }} + - name: ARCHIE_BOOTSTRAP_OWNER_PASSWORD_FILE + value: /run/secrets/archie-bootstrap/{{ .Values.bootstrap.owner.passwordSecretKey }} + {{- if .Values.caBundle.enabled }} + - name: SSL_CERT_FILE + value: {{ .Values.caBundle.mountPath | quote }} + {{- end }} + resources: + {{- toYaml .Values.bootstrap.resources | nindent 12 }} + volumeMounts: + - name: config + mountPath: /etc/archie/bootstrap.toml + subPath: bootstrap.toml + readOnly: true + - name: runtime-secrets + mountPath: /run/secrets/archie + readOnly: true + - name: bootstrap-secrets + mountPath: /run/secrets/archie-bootstrap + readOnly: true + - name: tmp + mountPath: /tmp + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + mountPath: {{ .Values.caBundle.mountPath }} + subPath: {{ .Values.caBundle.key }} + readOnly: true + {{- end }} + volumes: + - name: config + configMap: + name: {{ include "archie.fullname" . }}-config + - name: runtime-secrets + secret: + secretName: {{ .Values.secrets.existingSecret }} + defaultMode: 0400 + items: + - key: {{ .Values.secrets.keys.databaseUrl }} + path: {{ .Values.secrets.keys.databaseUrl }} + - name: bootstrap-secrets + secret: + secretName: {{ .Values.bootstrap.owner.passwordSecretName }} + defaultMode: 0400 + items: + - key: {{ .Values.bootstrap.owner.passwordSecretKey }} + path: {{ .Values.bootstrap.owner.passwordSecretKey }} + - name: tmp + emptyDir: {} + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + {{- if .Values.caBundle.existingSecret }} + secret: + secretName: {{ .Values.caBundle.existingSecret }} + defaultMode: 0444 + {{- else }} + configMap: + name: {{ .Values.caBundle.existingConfigMap }} + {{- end }} + {{- end }} +{{- end }} diff --git a/deployments/helm/archie/templates/job-bundle-sync.yaml b/deployments/helm/archie/templates/job-bundle-sync.yaml new file mode 100644 index 000000000..ad4d9d0f8 --- /dev/null +++ b/deployments/helm/archie/templates/job-bundle-sync.yaml @@ -0,0 +1,123 @@ +{{- if .Values.bundleSync.enabled -}} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ include "archie.fullname" . }}-bundle-sync + labels: + {{- include "archie.labels" . | nindent 4 }} + annotations: + {{- if .Values.bundleSync.hooks.helm }} + "helm.sh/hook": post-install,post-upgrade + "helm.sh/hook-weight": {{ .Values.bundleSync.hookWeight | quote }} + "helm.sh/hook-delete-policy": {{ .Values.bundleSync.hookDeletePolicy | quote }} + {{- end }} + {{- if .Values.bundleSync.hooks.argocd }} + "argocd.argoproj.io/hook": PostSync + "argocd.argoproj.io/hook-delete-policy": BeforeHookCreation + {{- end }} +spec: + backoffLimit: {{ .Values.bundleSync.backoffLimit }} + activeDeadlineSeconds: {{ .Values.bundleSync.activeDeadlineSeconds }} + template: + metadata: + labels: + {{- include "archie.labels" . | nindent 8 }} + app.kubernetes.io/component: bundle-sync + spec: + restartPolicy: OnFailure + serviceAccountName: {{ include "archie.serviceAccountName" . }} + automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: bundle-sync + image: {{ include "archie.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - "-config" + - "" + - "bundle" + - "apply" + - "--bundle" + - "/etc/archie/bundle/bundle.yaml" + {{- if .Values.bundleSync.bindings.enabled }} + - "--bindings" + - "/etc/archie/bindings/bindings.yaml" + {{- end }} + {{- if .Values.bundleSync.expectDigest }} + - "--expect-digest" + - {{ .Values.bundleSync.expectDigest | quote }} + {{- end }} + {{- if .Values.bundleSync.dryRun }} + - "--dry-run" + {{- end }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + env: + - name: HOME + value: "/tmp" + # Uses only the DML runtime role (archie_app), never owner_url. + - name: ARCHIE_DATABASE_URL_FILE + value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }} + {{- if .Values.caBundle.enabled }} + - name: SSL_CERT_FILE + value: {{ .Values.caBundle.mountPath | quote }} + {{- end }} + resources: + {{- toYaml .Values.bundleSync.resources | nindent 12 }} + volumeMounts: + - name: bundle + mountPath: /etc/archie/bundle/bundle.yaml + subPath: {{ .Values.bundleSync.bundleKey }} + readOnly: true + {{- if .Values.bundleSync.bindings.enabled }} + - name: bindings + mountPath: /etc/archie/bindings/bindings.yaml + subPath: {{ .Values.bundleSync.bindings.key }} + readOnly: true + {{- end }} + - name: runtime-secrets + mountPath: /run/secrets/archie + readOnly: true + - name: tmp + mountPath: /tmp + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + mountPath: {{ .Values.caBundle.mountPath }} + subPath: {{ .Values.caBundle.key }} + readOnly: true + {{- end }} + volumes: + - name: bundle + configMap: + name: {{ default (printf "%s-bundle" (include "archie.fullname" .)) .Values.bundleSync.existingConfigMap }} + {{- if .Values.bundleSync.bindings.enabled }} + - name: bindings + configMap: + name: {{ default (default (printf "%s-bundle" (include "archie.fullname" .)) .Values.bundleSync.existingConfigMap) .Values.bundleSync.bindings.existingConfigMap }} + {{- end }} + - name: runtime-secrets + secret: + secretName: {{ .Values.secrets.existingSecret }} + defaultMode: 0400 + items: + - key: {{ .Values.secrets.keys.databaseUrl }} + path: {{ .Values.secrets.keys.databaseUrl }} + - name: tmp + emptyDir: {} + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + {{- if .Values.caBundle.existingSecret }} + secret: + secretName: {{ .Values.caBundle.existingSecret }} + defaultMode: 0444 + {{- else }} + configMap: + name: {{ .Values.caBundle.existingConfigMap }} + {{- end }} + {{- end }} +{{- end }} diff --git a/deployments/helm/archie/templates/job-migrate.yaml b/deployments/helm/archie/templates/job-migrate.yaml new file mode 100644 index 000000000..998e9b05e --- /dev/null +++ b/deployments/helm/archie/templates/job-migrate.yaml @@ -0,0 +1,88 @@ +{{- if .Values.migrate.enabled -}} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ include "archie.fullname" . }}-migrate + labels: + {{- include "archie.labels" . | nindent 4 }} + annotations: + "helm.sh/hook": pre-install,pre-upgrade + "helm.sh/hook-weight": {{ .Values.migrate.hookWeight | quote }} + "helm.sh/hook-delete-policy": {{ .Values.migrate.hookDeletePolicy | quote }} +spec: + backoffLimit: {{ .Values.migrate.backoffLimit }} + activeDeadlineSeconds: {{ .Values.migrate.activeDeadlineSeconds }} + template: + metadata: + labels: + {{- include "archie.labels" . | nindent 8 }} + app.kubernetes.io/component: migrate + spec: + restartPolicy: OnFailure + serviceAccountName: {{ include "archie.serviceAccountName" . }} + automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: migrate + image: {{ include "archie.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - "-config" + - "" + - "migrate" + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + env: + - name: HOME + value: "/tmp" + - name: ARCHIE_DATABASE_URL_FILE + value: /run/secrets/archie-migrate/{{ .Values.secrets.keys.databaseUrl }} + - name: ARCHIE_DATABASE_OWNER_URL_FILE + value: /run/secrets/archie-migrate/{{ .Values.secrets.keys.databaseOwnerUrl }} + {{- if .Values.caBundle.enabled }} + - name: SSL_CERT_FILE + value: {{ .Values.caBundle.mountPath | quote }} + {{- end }} + resources: + {{- toYaml .Values.migrate.resources | nindent 12 }} + volumeMounts: + - name: migrate-secrets + mountPath: /run/secrets/archie-migrate + readOnly: true + - name: tmp + mountPath: /tmp + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + mountPath: {{ .Values.caBundle.mountPath }} + subPath: {{ .Values.caBundle.key }} + readOnly: true + {{- end }} + volumes: + - name: migrate-secrets + secret: + secretName: {{ include "archie.migrateSecretName" . }} + defaultMode: 0400 + items: + - key: {{ .Values.secrets.keys.databaseUrl }} + path: {{ .Values.secrets.keys.databaseUrl }} + - key: {{ .Values.secrets.keys.databaseOwnerUrl }} + path: {{ .Values.secrets.keys.databaseOwnerUrl }} + - name: tmp + emptyDir: {} + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + {{- if .Values.caBundle.existingSecret }} + secret: + secretName: {{ .Values.caBundle.existingSecret }} + defaultMode: 0444 + {{- else }} + configMap: + name: {{ .Values.caBundle.existingConfigMap }} + {{- end }} + {{- end }} +{{- end }} diff --git a/deployments/helm/archie/templates/networkpolicy.yaml b/deployments/helm/archie/templates/networkpolicy.yaml new file mode 100644 index 000000000..1fd0417f3 --- /dev/null +++ b/deployments/helm/archie/templates/networkpolicy.yaml @@ -0,0 +1,189 @@ +{{- if .Values.networkPolicy.enabled -}} +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "archie.fullname" . }}-default-deny + labels: + {{- include "archie.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "archie.selectorLabels" . | nindent 6 }} + policyTypes: + - Ingress + - Egress +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "archie.fullname" . }}-allow + labels: + {{- include "archie.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + {{- include "archie.selectorLabels" . | nindent 6 }} + policyTypes: + - Ingress + - Egress + ingress: + {{- if .Values.ingress.perimeter.enabled }} + - ports: + - protocol: TCP + port: 8080 + {{- if or .Values.networkPolicy.ingress.perimeter.namespaceSelector .Values.networkPolicy.ingress.perimeter.podSelector }} + from: + - {{- if .Values.networkPolicy.ingress.perimeter.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.ingress.perimeter.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.ingress.perimeter.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.ingress.perimeter.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + {{- if .Values.ingress.internal.enabled }} + - ports: + - protocol: TCP + port: 8080 + {{- if or .Values.networkPolicy.ingress.internal.namespaceSelector .Values.networkPolicy.ingress.internal.podSelector }} + from: + - {{- if .Values.networkPolicy.ingress.internal.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.ingress.internal.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.ingress.internal.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.ingress.internal.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + {{- if .Values.metrics.serviceMonitor.enabled }} + - ports: + - protocol: TCP + port: {{ .Values.metrics.port }} + {{- if or .Values.networkPolicy.ingress.metrics.namespaceSelector .Values.networkPolicy.ingress.metrics.podSelector }} + from: + - {{- if .Values.networkPolicy.ingress.metrics.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.ingress.metrics.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.ingress.metrics.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.ingress.metrics.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + egress: + # DNS resolution + - ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + {{- if or .Values.networkPolicy.egress.dns.namespaceSelector .Values.networkPolicy.egress.dns.podSelector }} + to: + - {{- if .Values.networkPolicy.egress.dns.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.egress.dns.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.egress.dns.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.egress.dns.podSelector | nindent 12 }} + {{- end }} + {{- end }} + # PostgreSQL / PgBouncer session pool + - ports: + - protocol: TCP + port: {{ .Values.networkPolicy.egress.postgres.port }} + {{- if or .Values.networkPolicy.egress.postgres.cidrs .Values.networkPolicy.egress.postgres.namespaceSelector .Values.networkPolicy.egress.postgres.podSelector }} + to: + {{- range .Values.networkPolicy.egress.postgres.cidrs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- if or .Values.networkPolicy.egress.postgres.namespaceSelector .Values.networkPolicy.egress.postgres.podSelector }} + - {{- if .Values.networkPolicy.egress.postgres.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.egress.postgres.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.egress.postgres.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.egress.postgres.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + # OIDC Identity Provider + - ports: + - protocol: TCP + port: {{ .Values.networkPolicy.egress.oidc.port }} + {{- if .Values.networkPolicy.egress.oidc.cidrs }} + to: + {{- range .Values.networkPolicy.egress.oidc.cidrs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- end }} + {{- if or .Values.proxy.httpsProxy .Values.proxy.httpProxy .Values.networkPolicy.egress.proxy.cidrs }} + # Corporate egress proxy + - ports: + - protocol: TCP + port: {{ .Values.networkPolicy.egress.proxy.port }} + {{- if .Values.networkPolicy.egress.proxy.cidrs }} + to: + {{- range .Values.networkPolicy.egress.proxy.cidrs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- end }} + {{- end }} + {{- if or .Values.config.extensions.remote .Values.networkPolicy.egress.extensions.cidrs .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }} + # Remote gRPC+mTLS extension endpoints + - ports: + {{- range .Values.networkPolicy.egress.extensions.ports }} + - protocol: TCP + port: {{ . }} + {{- end }} + {{- if or .Values.networkPolicy.egress.extensions.cidrs .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }} + to: + {{- range .Values.networkPolicy.egress.extensions.cidrs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- if or .Values.networkPolicy.egress.extensions.namespaceSelector .Values.networkPolicy.egress.extensions.podSelector }} + - {{- if .Values.networkPolicy.egress.extensions.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.egress.extensions.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.egress.extensions.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.egress.extensions.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + {{- end }} + {{- if or .Values.telemetry.otlpEndpoint .Values.networkPolicy.egress.otlp.cidrs .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }} + # OpenTelemetry collector + - ports: + - protocol: TCP + port: {{ .Values.networkPolicy.egress.otlp.port }} + {{- if or .Values.networkPolicy.egress.otlp.cidrs .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }} + to: + {{- range .Values.networkPolicy.egress.otlp.cidrs }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- if or .Values.networkPolicy.egress.otlp.namespaceSelector .Values.networkPolicy.egress.otlp.podSelector }} + - {{- if .Values.networkPolicy.egress.otlp.namespaceSelector }} + namespaceSelector: + {{- toYaml .Values.networkPolicy.egress.otlp.namespaceSelector | nindent 12 }} + {{- end }} + {{- if .Values.networkPolicy.egress.otlp.podSelector }} + podSelector: + {{- toYaml .Values.networkPolicy.egress.otlp.podSelector | nindent 12 }} + {{- end }} + {{- end }} + {{- end }} + {{- end }} +{{- end }} diff --git a/deployments/helm/archie/templates/poddisruptionbudget.yaml b/deployments/helm/archie/templates/poddisruptionbudget.yaml new file mode 100644 index 000000000..3eb5f18f0 --- /dev/null +++ b/deployments/helm/archie/templates/poddisruptionbudget.yaml @@ -0,0 +1,17 @@ +{{- if .Values.podDisruptionBudget.enabled -}} +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: {{ include "archie.fullname" . }} + labels: + {{- include "archie.labels" . | nindent 4 }} +spec: + {{- if not (kindIs "invalid" .Values.podDisruptionBudget.minAvailable) }} + minAvailable: {{ .Values.podDisruptionBudget.minAvailable }} + {{- else }} + maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable }} + {{- end }} + selector: + matchLabels: + {{- include "archie.selectorLabels" . | nindent 6 }} +{{- end }} diff --git a/deployments/helm/archie/templates/service.yaml b/deployments/helm/archie/templates/service.yaml new file mode 100644 index 000000000..3b12a7332 --- /dev/null +++ b/deployments/helm/archie/templates/service.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "archie.fullname" . }} + labels: + {{- include "archie.labels" . | nindent 4 }} + {{- with .Values.service.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + type: {{ .Values.service.type }} + ports: + - name: http + port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + - name: metrics + port: {{ .Values.service.metricsPort }} + targetPort: metrics + protocol: TCP + selector: + {{- include "archie.selectorLabels" . | nindent 4 }} diff --git a/deployments/helm/archie/templates/serviceaccount.yaml b/deployments/helm/archie/templates/serviceaccount.yaml new file mode 100644 index 000000000..d2f32d79f --- /dev/null +++ b/deployments/helm/archie/templates/serviceaccount.yaml @@ -0,0 +1,13 @@ +{{- if .Values.serviceAccount.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "archie.serviceAccountName" . }} + labels: + {{- include "archie.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }} +{{- end }} diff --git a/deployments/helm/archie/templates/servicemonitor.yaml b/deployments/helm/archie/templates/servicemonitor.yaml new file mode 100644 index 000000000..bef021c6f --- /dev/null +++ b/deployments/helm/archie/templates/servicemonitor.yaml @@ -0,0 +1,20 @@ +{{- if .Values.metrics.serviceMonitor.enabled -}} +apiVersion: monitoring.coreos.com/v1 +kind: ServiceMonitor +metadata: + name: {{ include "archie.fullname" . }} + labels: + {{- include "archie.labels" . | nindent 4 }} + {{- with .Values.metrics.serviceMonitor.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + selector: + matchLabels: + {{- include "archie.selectorLabels" . | nindent 6 }} + endpoints: + - port: metrics + path: {{ .Values.metrics.path }} + interval: {{ .Values.metrics.serviceMonitor.interval }} + scrapeTimeout: {{ .Values.metrics.serviceMonitor.scrapeTimeout }} +{{- end }} diff --git a/deployments/helm/archie/templates/statefulset.yaml b/deployments/helm/archie/templates/statefulset.yaml new file mode 100644 index 000000000..28f438797 --- /dev/null +++ b/deployments/helm/archie/templates/statefulset.yaml @@ -0,0 +1,190 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "archie.fullname" . }} + labels: + {{- include "archie.labels" . | nindent 4 }} +spec: + serviceName: {{ include "archie.fullname" . }} + # Active-Passive HA in Enterprise v1 requires a single active replica. + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "archie.selectorLabels" . | nindent 6 }} + template: + metadata: + annotations: + checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} + {{- with .Values.podAnnotations }} + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "archie.labels" . | nindent 8 }} + {{- with .Values.podLabels }} + {{- toYaml . | nindent 8 }} + {{- end }} + spec: + serviceAccountName: {{ include "archie.serviceAccountName" . }} + automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }} + terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: archie + image: {{ include "archie.image" . }} + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - "-config" + - "/etc/archie/config.toml" + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + ports: + - name: http + containerPort: 8080 + protocol: TCP + - name: metrics + containerPort: {{ .Values.metrics.port }} + protocol: TCP + env: + - name: HOME + value: "/tmp" + - name: ARCHIE_DATABASE_URL_FILE + value: /run/secrets/archie/{{ .Values.secrets.keys.databaseUrl }} + - name: ARCHIE_AGE_IDENTITY_FILE + value: /run/secrets/archie/{{ .Values.secrets.keys.ageIdentity }} + - name: ARCHIE_ADMIN_TOKEN_SHA256_FILE + value: /run/secrets/archie/{{ .Values.secrets.keys.adminTokenSha256 }} + {{- if .Values.caBundle.enabled }} + - name: SSL_CERT_FILE + value: {{ .Values.caBundle.mountPath | quote }} + {{- end }} + {{- if .Values.proxy.httpsProxy }} + - name: HTTPS_PROXY + value: {{ .Values.proxy.httpsProxy | quote }} + {{- end }} + {{- if .Values.proxy.httpProxy }} + - name: HTTP_PROXY + value: {{ .Values.proxy.httpProxy | quote }} + {{- end }} + {{- if or .Values.proxy.httpsProxy .Values.proxy.httpProxy }} + - name: NO_PROXY + value: {{ .Values.proxy.noProxy | quote }} + {{- end }} + {{- if .Values.telemetry.otlpEndpoint }} + - name: OTEL_EXPORTER_OTLP_ENDPOINT + value: {{ .Values.telemetry.otlpEndpoint | quote }} + {{- end }} + {{- with .Values.extraEnv }} + {{- toYaml . | nindent 12 }} + {{- end }} + startupProbe: + httpGet: + path: /startupz + port: http + initialDelaySeconds: {{ .Values.probes.startup.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.startup.periodSeconds }} + timeoutSeconds: {{ .Values.probes.startup.timeoutSeconds }} + failureThreshold: {{ .Values.probes.startup.failureThreshold }} + livenessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.liveness.periodSeconds }} + timeoutSeconds: {{ .Values.probes.liveness.timeoutSeconds }} + failureThreshold: {{ .Values.probes.liveness.failureThreshold }} + readinessProbe: + httpGet: + path: /readyz + port: http + initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.readiness.periodSeconds }} + timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }} + failureThreshold: {{ .Values.probes.readiness.failureThreshold }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumeMounts: + - name: config + mountPath: /etc/archie/config.toml + subPath: config.toml + readOnly: true + - name: runtime-secrets + mountPath: /run/secrets/archie + readOnly: true + - name: tmp + mountPath: /tmp + - name: state + mountPath: {{ .Values.config.stateDir }} + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + mountPath: {{ .Values.caBundle.mountPath }} + subPath: {{ .Values.caBundle.key }} + readOnly: true + {{- end }} + {{- if .Values.config.extensions.tls.existingSecret }} + - name: extensions-tls + mountPath: {{ .Values.config.extensions.tls.mountPath }} + readOnly: true + {{- end }} + volumes: + - name: config + configMap: + name: {{ include "archie.fullname" . }}-config + - name: runtime-secrets + secret: + secretName: {{ .Values.secrets.existingSecret }} + defaultMode: 0400 + items: + - key: {{ .Values.secrets.keys.databaseUrl }} + path: {{ .Values.secrets.keys.databaseUrl }} + - key: {{ .Values.secrets.keys.ageIdentity }} + path: {{ .Values.secrets.keys.ageIdentity }} + - key: {{ .Values.secrets.keys.adminTokenSha256 }} + path: {{ .Values.secrets.keys.adminTokenSha256 }} + - name: tmp + emptyDir: {} + {{- if not .Values.persistence.enabled }} + - name: state + emptyDir: {} + {{- else if .Values.persistence.existingClaim }} + - name: state + persistentVolumeClaim: + claimName: {{ .Values.persistence.existingClaim }} + {{- end }} + {{- if .Values.caBundle.enabled }} + - name: ca-bundle + {{- if .Values.caBundle.existingSecret }} + secret: + secretName: {{ .Values.caBundle.existingSecret }} + defaultMode: 0444 + {{- else }} + configMap: + name: {{ .Values.caBundle.existingConfigMap }} + {{- end }} + {{- end }} + {{- if .Values.config.extensions.tls.existingSecret }} + - name: extensions-tls + secret: + secretName: {{ .Values.config.extensions.tls.existingSecret }} + defaultMode: 0400 + {{- end }} + {{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }} + volumeClaimTemplates: + - metadata: + name: state + labels: + {{- include "archie.labels" . | nindent 10 }} + spec: + accessModes: + {{- toYaml .Values.persistence.accessModes | nindent 10 }} + {{- if .Values.persistence.storageClass }} + storageClassName: {{ .Values.persistence.storageClass | quote }} + {{- end }} + resources: + requests: + storage: {{ .Values.persistence.size | quote }} + {{- end }} diff --git a/deployments/helm/archie/values-dev.yaml b/deployments/helm/archie/values-dev.yaml new file mode 100644 index 000000000..5f98a99ca --- /dev/null +++ b/deployments/helm/archie/values-dev.yaml @@ -0,0 +1,32 @@ +# Development stage overlay: isolated non-prod database, key, and relaxed egress for local testing. + +image: + tag: "dev" + pullPolicy: IfNotPresent + +config: + catalogue: + disableAutoUpdate: false + extensions: + requireRemote: true + +persistence: + size: "2Gi" + +resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "500m" + memory: "512Mi" + +networkPolicy: + enabled: false + +podDisruptionBudget: + enabled: false + +metrics: + serviceMonitor: + enabled: false diff --git a/deployments/helm/archie/values-prod.yaml b/deployments/helm/archie/values-prod.yaml new file mode 100644 index 000000000..143246cae --- /dev/null +++ b/deployments/helm/archie/values-prod.yaml @@ -0,0 +1,70 @@ +# Production stage overlay: full restricted hardening, split ingress, remote mTLS extensions, and PDB. + +replicaCount: 1 + +image: + # Always pin an immutable cosign-verified digest in production (for example "sha256:..."). + digest: "" + pullPolicy: IfNotPresent + +terminationGracePeriodSeconds: 45 + +config: + shutdownGrace: "30s" + catalogue: + disableAutoUpdate: true + extensions: + requireRemote: true + +persistence: + enabled: true + size: "20Gi" + +resources: + requests: + cpu: "500m" + memory: "512Mi" + limits: + cpu: "2000m" + memory: "2Gi" + +ingress: + perimeter: + enabled: true + className: "external-nginx" + annotations: + nginx.ingress.kubernetes.io/ssl-redirect: "true" + nginx.ingress.kubernetes.io/limit-rps: "25" + hosts: + - host: hooks.archie.example.com + paths: + - /hooks + - /webhooks + tls: + - secretName: archie-prod-perimeter-tls + hosts: + - hooks.archie.example.com + internal: + enabled: true + className: "internal-nginx" + annotations: + nginx.ingress.kubernetes.io/ssl-redirect: "true" + hosts: + - host: archie.internal.example.com + paths: + - / + tls: + - secretName: archie-prod-internal-tls + hosts: + - archie.internal.example.com + +networkPolicy: + enabled: true + +metrics: + serviceMonitor: + enabled: true + +podDisruptionBudget: + enabled: true + maxUnavailable: 1 diff --git a/deployments/helm/archie/values-staging.yaml b/deployments/helm/archie/values-staging.yaml new file mode 100644 index 000000000..d3f13bcf1 --- /dev/null +++ b/deployments/helm/archie/values-staging.yaml @@ -0,0 +1,57 @@ +# Staging stage overlay: mirrors production hardening and ingress isolation with its own DB and keys. + +image: + # Pin digest before promoting from dev to staging. + digest: "" + +config: + catalogue: + disableAutoUpdate: true + extensions: + requireRemote: true + +persistence: + size: "5Gi" + +resources: + requests: + cpu: "250m" + memory: "256Mi" + limits: + cpu: "1000m" + memory: "1Gi" + +ingress: + perimeter: + enabled: true + className: "external-nginx" + hosts: + - host: hooks.staging.archie.example.com + paths: + - /hooks + - /webhooks + tls: + - secretName: archie-staging-perimeter-tls + hosts: + - hooks.staging.archie.example.com + internal: + enabled: true + className: "internal-nginx" + hosts: + - host: archie.staging.internal.example.com + paths: + - / + tls: + - secretName: archie-staging-internal-tls + hosts: + - archie.staging.internal.example.com + +networkPolicy: + enabled: true + +metrics: + serviceMonitor: + enabled: true + +podDisruptionBudget: + enabled: false diff --git a/deployments/helm/archie/values.yaml b/deployments/helm/archie/values.yaml new file mode 100644 index 000000000..32849aa1d --- /dev/null +++ b/deployments/helm/archie/values.yaml @@ -0,0 +1,285 @@ +# Default production-oriented values for Archie Enterprise (Active-Passive v1). +# Pair with values-dev.yaml, values-staging.yaml, or values-prod.yaml. + +replicaCount: 1 + +image: + repository: ghcr.io/samcharles93/archie + tag: "v1.0.0" + # Set digest (e.g. "sha256:...") to pin the exact immutable artifact in staging and prod. + digest: "" + pullPolicy: IfNotPresent + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +serviceAccount: + create: true + name: "" + annotations: {} + automountServiceAccountToken: false + +# Exceeds config.shutdownGrace (30s) so active requests and run checkpoints drain on SIGTERM. +terminationGracePeriodSeconds: 45 + +podAnnotations: {} +podLabels: {} + +podSecurityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + +securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + capabilities: + drop: + - ALL + +config: + listen: "0.0.0.0:8080" + stateDir: "/var/lib/archie" + shutdownGrace: "30s" + # Public age1... backup recipients used alongside the primary sealing identity. + ageBackupRecipients: [] + catalogue: + # Must be set together with publicKey when overriding the default catalogue mirror. + location: "" + publicKey: "" + disableAutoUpdate: true + extensions: + # Kubernetes restricted PSS forbids CLONE_NEWUSER namespaces; require remote gRPC+mTLS extensions. + requireRemote: true + tls: + # Secret holding ca.crt, tls.crt, and tls.key for mTLS client authentication to extensions. + existingSecret: "" + mountPath: "/etc/archie/extensions-tls" + # Map extension key or name to { address: "ext.ns.svc:50051", serverName: "ext.internal" }. + remote: {} + +secrets: + # Secret holding database-url, age-identity, and admin-token-sha256 for runtime pods. + existingSecret: "archie-runtime-secrets" + keys: + databaseUrl: "database-url" + databaseOwnerUrl: "database-owner-url" + ageIdentity: "age-identity" + adminTokenSha256: "admin-token-sha256" + +caBundle: + enabled: false + existingConfigMap: "" + existingSecret: "" + key: "ca-certificates.crt" + mountPath: "/etc/ssl/certs/archie-ca.crt" + +proxy: + httpsProxy: "" + httpProxy: "" + noProxy: "localhost,127.0.0.1,.svc,.cluster.local" + +telemetry: + otlpEndpoint: "" + +extraEnv: [] + +persistence: + enabled: true + existingClaim: "" + storageClass: "" + accessModes: + - ReadWriteOnce + size: "10Gi" + +resources: + requests: + cpu: "250m" + memory: "256Mi" + limits: + cpu: "1000m" + memory: "1Gi" + +probes: + startup: + initialDelaySeconds: 2 + periodSeconds: 5 + timeoutSeconds: 3 + failureThreshold: 30 + liveness: + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + readiness: + initialDelaySeconds: 2 + periodSeconds: 5 + timeoutSeconds: 3 + failureThreshold: 3 + +migrate: + enabled: true + # Dedicated migration secret holding database-owner-url and database-url. + # Keeps DDL credentials completely out of the runtime StatefulSet. + existingSecret: "archie-migrate-secrets" + hookWeight: "-5" + hookDeletePolicy: "before-hook-creation,hook-succeeded" + backoffLimit: 3 + activeDeadlineSeconds: 300 + resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "500m" + memory: "256Mi" + +bootstrap: + enabled: false + hookWeight: "-1" + hookDeletePolicy: "before-hook-creation,hook-succeeded" + backoffLimit: 2 + activeDeadlineSeconds: 180 + publicUrl: "" + trustedProxies: [] + owner: + email: "" + displayName: "Platform Owner" + passwordSecretName: "archie-bootstrap-secrets" + passwordSecretKey: "owner-password" + oidc: + issuer: "" + audience: "" + clientId: "" + resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "500m" + memory: "256Mi" + +bundleSync: + enabled: false + hooks: + helm: true + argocd: true + hookWeight: "5" + hookDeletePolicy: "before-hook-creation,hook-succeeded" + backoffLimit: 2 + activeDeadlineSeconds: 180 + # ConfigMap holding bundle.yaml (and optional bindings.yaml). + existingConfigMap: "" + bundleKey: "bundle.yaml" + bindings: + enabled: true + # Optional separate ConfigMap for stage-local bindings; falls back to bundleSync.existingConfigMap. + existingConfigMap: "" + key: "bindings.yaml" + expectDigest: "" + dryRun: false + resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "500m" + memory: "256Mi" + +service: + type: ClusterIP + port: 8080 + metricsPort: 9090 + annotations: {} + +metrics: + port: 9090 + path: "/metrics" + serviceMonitor: + enabled: false + interval: "30s" + scrapeTimeout: "10s" + labels: {} + +ingress: + # External edge ingress admitting webhook intake (/hooks/ and /webhooks/) only. + perimeter: + enabled: false + className: "" + annotations: {} + hosts: [] + tls: [] + # Internal corporate VPN / SSO ingress serving Dashboard, /api/, and OIDC routes. + internal: + enabled: false + className: "" + annotations: {} + hosts: [] + tls: [] + +networkPolicy: + enabled: true + ingress: + perimeter: + namespaceSelector: {} + podSelector: {} + internal: + namespaceSelector: {} + podSelector: {} + metrics: + namespaceSelector: {} + podSelector: {} + egress: + dns: + namespaceSelector: + kubernetes.io/metadata.name: kube-system + podSelector: + k8s-app: kube-dns + postgres: + port: 5432 + cidrs: [] + namespaceSelector: {} + podSelector: {} + oidc: + port: 443 + cidrs: [] + proxy: + port: 3128 + cidrs: [] + extensions: + ports: + - 50051 + cidrs: [] + namespaceSelector: {} + podSelector: {} + otlp: + port: 4317 + cidrs: [] + namespaceSelector: {} + podSelector: {} + +podDisruptionBudget: + enabled: false + maxUnavailable: 1 + minAvailable: null + +externalSecret: + enabled: false + refreshInterval: "1h" + secretStoreRef: + name: "vault-backend" + kind: "ClusterSecretStore" + remoteRefs: + databaseUrlKey: "archie/prod/database" + databaseUrlProperty: "runtime_url" + ageIdentityKey: "archie/prod/age" + ageIdentityProperty: "identity" + adminTokenSha256Key: "archie/prod/admin" + adminTokenSha256Property: "token_sha256" diff --git a/docs/enterprise/compliance-control-mapping.md b/docs/enterprise/compliance-control-mapping.md new file mode 100644 index 000000000..12eeee4be --- /dev/null +++ b/docs/enterprise/compliance-control-mapping.md @@ -0,0 +1,54 @@ +# Enterprise Compliance Control Mapping + +Archie enforces preventive, detective, and corrective controls in code and deployment files. This guide maps each control to its source code, deployment files, `go test -short` tests, and compliance frameworks. It covers SOC 2 (CC6, CC7, CC8), ISO/IEC 27001:2022, SOX ITGC, and APRA CPS 234. + +## Control Matrix + +| Control area | Archie code | Deployment files | Automated test proof | Framework mapping | +| --- | --- | --- | --- | --- | +| Database role split | `pg.Migrate` (`owner_url`) vs DML-only `url` checked by `pg.VerifySchema` (`internal/platform/pg/pg.go`) | `job-migrate.yaml` mounts `owner_url`; `statefulset.yaml` and `compose.enterprise.yml` omit `owner_url` | `TestMissingMigrations` (`internal/platform/pg/pg_test.go`), `TestLoadMigrateConfigRequiresOnlyDatabaseRoles` (`internal/app/archie/config_test.go`) | SOC 2 CC6.1, CC6.3; ISO 27001 A.5.15, A.8.2; SOX ITGC Access; CPS 234 (15-17) | +| API and setup gate | Cedar policy checks on every route (`internal/app/archie/api.go`, `modules/governance/access.go`) and closed gate (`internal/app/archie/gate.go`) | Split internal vs perimeter ingress (`ingress.yaml`) | `TestEveryOperationIsAuthorized`, `TestUnwiredAuthorizerRefuses` (`internal/app/archie/access_test.go`), `TestClosedGateServesOnlySetup`, `TestGateIsNotBypassedByPathTricks` (`internal/app/archie/gate_test.go`), `TestEnforcementFailsClosedAndRecordsDecisions` (`modules/governance/enforce_test.go`) | SOC 2 CC6.1, CC6.2; ISO 27001 A.5.15, A.8.3; SOX ITGC Access; CPS 234 (15-18) | +| Identity and SSO | Confidential OIDC, role mapping, SSO-only mode, session limits, and back-channel logout (`modules/governance/oidc.go`, `identity.go`) | Headless `archie bootstrap` (`job-bootstrap.yaml`, `internal/app/archie/bootstrap.go`) | `TestAuthenticateRequest` (`modules/governance/auth_test.go`), `TestAuthenticationSettingsRejectUntrustedOrigins`, `TestPasswordVerification` (`modules/governance/identity_test.go`), `TestLoadBootstrapSpecAndEnvFiles` (`internal/app/archie/bootstrap_test.go`) | SOC 2 CC6.1, CC6.2; ISO 27001 A.5.17, A.8.5; SOX ITGC Access; CPS 234 (15-17) | +| Four-eyes SoD and step-up | Cedar judgement (`modules/judgement/`), passkey checks (`modules/approvals/`), and SoD rule blocking self-approval | Stage-local autonomy caps; prod approval gates | `TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove`, `TestIrreversibleActionsNeedFreshAuthentication` (`modules/approvals/dashboard_test.go`), `TestExecuteApprovedRunsOnlyWhatThePersonSaw` (`modules/judgement/judgement_test.go`), `TestChatProhibitsPrivilegedActions` (`modules/judgement/chat_test.go`) | SOC 2 CC6.3, CC8.1; ISO 27001 A.5.3; SOX ITGC Changes; CPS 234 (16-18) | +| Keys and secrets | Label-bound `age` X25519 sealing (`internal/platform/seal/seal.go`), `*_FILE` loading (`config.go`), `archie rekey`, and log redaction (`auditjson/`) | `*_FILE` mounts in `statefulset.yaml` and `compose.enterprise.yml`; `externalsecret.example.yaml` | `TestSealedValueOpensOnlyWhereItBelongs` (`internal/platform/seal/seal_test.go`), `TestCredentialRoutesNeverReturnASecret`, `TestBearerTokenByIDRespectsScope` (`modules/connectors/credentials_test.go`), `TestStoredPayloadKeepsCredentialsOut` (`internal/platform/auditjson/auditjson_test.go`), `TestLoadConfigRuntimeAndEnvFiles` (`internal/app/archie/config_test.go`) | SOC 2 CC6.1, CC6.7; ISO 27001 A.8.24; SOX ITGC Access; CPS 234 (15-20) | +| Pod and extension isolation | `RemoteGRPCRuntime` over mTLS (`modules/connectors/internal/host/remote.go`) and `LocalNamespaceRuntime` with egress tunnel (`egress/tunnel.go`) | `restricted` PSS in `statefulset.yaml`; `seccomp.json` in `compose.enterprise.yml`; `networkpolicy.yaml` | `TestRemoteGRPCRequiresMTLSAndEnforcesTrust` (`modules/connectors/internal/host/remote_test.go`), `TestCommandConfinesOnlyWithEgress`, `TestNamespaceLimitRefusesDisabledNamespaces` (`modules/connectors/internal/host/host_test.go`), `TestTunnelEnforcesAllowListBeforeCorporateProxy` (`modules/connectors/internal/egress/tunnel_test.go`) | SOC 2 CC6.6, CC6.7; ISO 27001 A.8.20, A.8.22; SOX ITGC Ops; CPS 234 (16-18) | +| Supply chain and webhooks | Ed25519-signed catalogues with SHA-256 checks (`catalogue/`) and pre-parse HMAC checks (`modules/events/verify.go`) | Digest-pinned images (`values-prod.yaml`); `[catalogue]` mirror; perimeter `/hooks/` ingress | `TestFetchRefusesAnArtifactWhoseDigestDoesNotMatch`, `TestAcceptRefusesGrantsTheExtensionNeverDeclared`, `TestVerifyRefusesAForgedOrMalformedCatalogue` (`modules/connectors/internal/catalogue/catalogue_test.go`), `TestReadOCIChecksSignatureAndPackagePin` (`oci_test.go`), `TestHMACSourceVerifiesBeforeParsing` (`modules/events/verify_test.go`) | SOC 2 CC7.1, CC8.1; ISO 27001 A.8.25, A.8.28; SOX ITGC Changes; CPS 234 (21-22) | +| Audit, tracing, and changes | Append-only `audit.events` (`SELECT`, `INSERT`), stdout JSON audit logs, OTel trace IDs, `archie bundle`, and change windows | `servicemonitor.yaml`; SIEM log shipping; `values-{dev,staging,prod}.yaml` | `TestEveryDecisionIsRecorded`, `TestAllowedDecisionNeedsItsRecord` (`modules/governance/decisions_test.go`), `TestReadAuditRoleBoundary` (`modules/governance/access_test.go`), `TestTimingHoldsChangingActionsOutsideTheSchedule` (`modules/governance/timing_test.go`), `TestAutonomyIsEarnedSlowlyAndLostAtOnce` (`modules/judgement/autonomy_test.go`) | SOC 2 CC7.2, CC7.3, CC8.1; ISO 27001 A.8.15, A.8.32; SOX ITGC Changes, Ops; CPS 234 (23-28) | +| Availability and deletion record | `/healthz`, `/startupz`, `/readyz` (`health/health.go`), `ClaimServe` lock (`pg/pg.go`), and deletion ledger (`deletions/deletions.go`) | RWO PVC in `statefulset.yaml`; `poddisruptionbudget.yaml`; `dr-and-backup.md` drill | `TestProbesSeparateStartupFromReadiness` (`internal/platform/health/health_test.go`), `TestLogRecordsEachDeletion` (`internal/platform/deletions/deletions_test.go`), `TestForgetCommitsThenRecords`, `TestReapplyDeletionsAppliesEveryRecordedNote` (`modules/memory/notes_test.go`) | SOC 2 CC7.4, A1.2; ISO 27001 A.5.30; SOX ITGC Ops; CPS 234 (19, 25) | + +## Framework Alignment Summary + +### SOC 2 (CC6, CC7, CC8) + +- **CC6 (Access Controls):** Archie enforces OIDC SSO, Cedar checks on every route (`TestEveryOperationIsAuthorized`), DML-only database roles, `age` sealing, and default-deny `NetworkPolicy`. +- **CC7 (System Operations):** Archie checks webhook HMACs before parsing (`TestHMACSourceVerifiesBeforeParsing`), runs as UID `65532` with a read-only root filesystem, and exposes `/healthz`, `/startupz`, `/readyz`, stdout JSON audit logs, and `/metrics`. +- **CC8 (Change Management):** Archie splits `archie migrate` from serving pods, signs extension catalogues, promotes stages with `archie bundle`, checks change windows (`TestTimingHoldsChangingActionsOutsideTheSchedule`), and enforces SoD on approvals. + +### ISO/IEC 27001:2022 + +- **Access Rights (A.5.15, A.5.17, A.8.2, A.8.5):** Separate `archie_owner` and `archie_app` roles limit schema rights. OIDC role mapping, SSO-only mode, and passkey checks gate high-risk actions. +- **Crypto and Networks (A.8.20, A.8.22, A.8.24):** Deployments use PostgreSQL `sslmode=verify-full`, TLS 1.3 mTLS for remote gRPC extensions, `age` keys with backup recipients, and `HTTPS_PROXY` allow-lists. +- **Logs, Supply Chain, and Continuity (A.8.15, A.8.25, A.8.32, A.5.30):** Append-only audit logs, Ed25519-signed catalogues, `task check` (`golangci-lint`, `gosec`, `go test -short`), and quarterly DR drills cover daily operations. + +### SOX ITGC + +- **Access to Programs and Data:** Only `archie migrate` holds DDL rights. Runtime pods cannot change schemas, edit audit rows, or return secrets (`TestCredentialRoutesNeverReturnASecret`). +- **Program Changes:** Stages stay isolated across `dev`, `staging`, and `prod`. Digest-pinned OCI images, `archie bundle diff` and `apply`, and four-eyes SoD gate all changes. +- **Computer Operations:** `ClaimServe` blocks serving pods during database restores. `shutdown_grace` drains active runs cleanly. `memory.ReapplyDeletions` keeps deleted notes removed after a snapshot restore. + +### APRA CPS 234 + +- **Asset Controls and Testing (Paragraphs 15-22):** Controls scale with impact via Cedar guards, extension trust ceilings (`TestGuardExtensionsDecideAtTheLowestCeiling`), mTLS checks, and automated `task check` suites. +- **Detection and Recovery (Paragraphs 23-28):** Pre-parse webhook checks, stdout JSON audit streams to SIEM/WORM storage, OpenTelemetry trace IDs, and quarterly DR drills provide full audit trails. + +## Continuous Gate + +Run the repository gate, Helm lint, and prose checks before each release and audit: + +```bash +task check +helm lint deployments/helm/archie -f deployments/helm/archie/values-prod.yaml +vale docs/enterprise/*.md +``` + +`task check` runs `go test -short ./...`, `golangci-lint` (including `gosec`), and generated schema and OpenAPI checks. diff --git a/docs/enterprise/deployment-architecture.md b/docs/enterprise/deployment-architecture.md new file mode 100644 index 000000000..bee9784ff --- /dev/null +++ b/docs/enterprise/deployment-architecture.md @@ -0,0 +1,82 @@ +# Enterprise Deployment Architecture + +Archie runs as a single static binary (`cmd/archie`) backed by PostgreSQL. Regulated deployments isolate each stage, separate DDL from DML credentials, split external webhook ingress from internal operator access, and enforce strict pod or container boundaries. + +## Multi-Stage Isolation Zones + +Deploy Archie into three independent stages: `dev`, `staging`, and `prod`. Each stage runs its own Archie instance and shares no runtime state with any other stage. + +| Resource | `dev` | `staging` | `prod` | +| --- | --- | --- | --- | +| Kubernetes namespace or host | `archie-dev` | `archie-staging` | `archie-prod` | +| PostgreSQL database | Isolated dev instance | Isolated staging instance | Managed HA PostgreSQL (`sslmode=verify-full`) | +| `age` sealing key | Stage-local `age_identity` | Stage-local `age_identity` | Stage-local `age_identity` with offline `age_backup_recipients` | +| OIDC client | Non-prod IdP client | Staging IdP client | Production IdP confidential client | +| Earned autonomy | Local to `dev` | Local to `staging` | Built independently in `prod` | +| Helm overlay | `values-dev.yaml` | `values-staging.yaml` | `values-prod.yaml` | + +Earned autonomy in `staging` never promotes to `prod`. Promote declarative configuration (workflows, Cedar policies, judgement rules, and action-type metadata) with `archie bundle`. Keep credentials, OIDC bindings, target hosts, and autonomy counters local to each stage. + +Pin container images by immutable SHA-256 digest (`image.digest` in Helm) and verify cosign signatures before deploying to `staging` and `prod`. Set `[catalogue]` `disable_auto_update = true` and mirror signed extension catalogues internally in air-gapped stages. + +### Stage Promotion Models + +Choose one of two promotion workflows depending on your delivery pipeline: + +1. **Push CI/CD (GitHub Actions, GitLab CI, or Jenkins):** + - On pull requests, run `archie bundle validate` offline to check workflow YAML, Cedar policy syntax, judgement rules, and stage `Bindings` without database access. + - Export the tested bundle from `staging` and record its canonical SHA-256 digest (`Bundle.Digest()`). + - After manual change approval, the `prod` pipeline runs `archie bundle apply --expect-digest ` over HTTPS using `ARCHIE_URL` and `ARCHIE_TOKEN_FILE`. The CI runner never touches PostgreSQL directly. +2. **Pull GitOps (Argo CD or Flux):** + - Store the stage Helm values (`values-staging.yaml`, `values-prod.yaml`), `bundle.yaml`, and stage-local `bindings.yaml` in Git. + - Enable `bundleSync.enabled: true` in `deployments/helm/archie` to run `templates/job-bundle-sync.yaml` as an Argo CD `PostSync` or Helm `post-install,post-upgrade` Job. + - The Job mounts the bundle `ConfigMap`, uses only the runtime `archie_app` database secret (`ARCHIE_DATABASE_URL_FILE`), and applies unchanged bundles idempotently with optional `expectDigest` verification. + +## Split Ingress and Network Boundaries + +Separate external webhook delivery from operator and administrator access using two ingress resources (`deployments/helm/archie/templates/ingress.yaml`): + +1. **Perimeter webhook ingress (`ingress.perimeter`):** Expose only webhook intake paths (`/hooks/` for `cmd/archie` intake and `/webhooks/` where routed by a reverse proxy). Terminate TLS at the edge and apply rate limits. The `events` module verifies each payload's HMAC signature before parsing JSON (`modules/events/verify.go`). +2. **Internal operator ingress (`ingress.internal`):** Serve the Dashboard, `/api/`, and OIDC routes behind a corporate VPN or internal load balancer. Never expose `/api/` or the setup surface on the perimeter ingress. + +Enforce default-deny `NetworkPolicy` rules (`deployments/helm/archie/templates/networkpolicy.yaml`) in `staging` and `prod`. Permit ingress only from the perimeter ingress controller (port `8080`), internal ingress controller (port `8080`), and Prometheus scraper (port `9090` on `/metrics`). Permit egress only to DNS (`53`), PostgreSQL or PgBouncer (`5432`), the OIDC issuer (`443`), configured remote extension endpoints, the corporate proxy (`HTTPS_PROXY`), and the OpenTelemetry collector (`4317`). + +## Database Role Split and PgBouncer Session Pooling + +Archie separates schema ownership from runtime operations across two PostgreSQL roles: + +- **`archie_owner` (`ARCHIE_DATABASE_OWNER_URL_FILE`):** Holds DDL rights. Used only by `archie migrate` inside the Helm pre-install/pre-upgrade `Job` (`job-migrate.yaml`) or the Compose `archie-migrate` init service (`deployments/archie/compose.enterprise.yml`). +- **`archie_app` (`ARCHIE_DATABASE_URL_FILE`):** Holds only `USAGE` and DML privileges (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, and `SELECT` on `public.goose_db_version`). The runtime `StatefulSet` and Compose `archie` service mount only this credential. At startup, `pg.VerifySchema` (`internal/platform/pg/pg.go`) checks that every embedded migration is applied and fails closed if the schema lags behind. + +### PgBouncer Session-Pooling Requirement for `ClaimServe` + +At boot, `cmd/archie` calls `pg.ClaimServe` (`internal/platform/pg/pg.go`). `ClaimServe` opens a dedicated connection via `db.Conn(ctx)` and acquires a shared PostgreSQL session advisory lock (`pg_try_advisory_lock_shared(hashtextextended('archie.serve.owner', 0))`). It holds that lock for the entire lifetime of the serving process. A database restore takes the same key exclusively so no serving pod can start or run during a restore window. + +If you deploy PgBouncer in front of PostgreSQL, configure `pool_mode = session` for Archie's runtime pool. PgBouncer `transaction` and `statement` pooling modes share server backends across clients and release or drop session advisory locks between transactions. Direct connections to the HA PostgreSQL primary also satisfy this requirement. + +## Pod Security and Extension Confinement + +Extension execution differs between Kubernetes and Docker Compose because Kubernetes `restricted` Pod Security Standards forbid user namespaces. + +| Control | Kubernetes (`deployments/helm/archie`) | Hardened Compose (`deployments/archie/compose.enterprise.yml`) | +| --- | --- | --- | +| User and root filesystem | `runAsNonRoot: true`, UID/GID `65532`, read-only root filesystem, `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]` | `user: "65532:65532"`, `read_only: true`, `tmpfs: /tmp`, `cap_drop: [ALL]`, `no-new-privileges:true` | +| Seccomp profile | `seccompProfile.type: RuntimeDefault` | `deployments/archie/seccomp.json` (Docker default plus `clone` for namespaces) | +| Extension runtime | `RemoteGRPCRuntime` over mTLS or Unix socket (`require_remote = true`) | `LocalNamespaceRuntime` (`CLONE_NEWUSER` and `CLONE_NEWNET`) | +| Egress proxy and PKI | `HTTPS_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` propagated to runtime and `NetworkPolicy` | `HTTPS_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` propagated into confined namespaces | + +In Kubernetes, run extensions as separate Pods or sidecars under `restricted` Pod Security Standards and isolate them with `NetworkPolicy`. Configure `[extensions]` in `config.toml` (`templates/configmap.yaml`) with `require_remote = true`, TLS 1.3 mTLS certificates (`ca_file`, `cert_file`, `key_file`), and explicit `[extensions.remote.]` targets. If neither `RemoteGRPCRuntime` nor `LocalNamespaceRuntime` is available, `modules/connectors/internal/host/remote.go` fails closed. + +In Docker Compose and VM hosts, `LocalNamespaceRuntime` confines each extension binary in its own user and network namespace behind an allow-list forward proxy (`modules/connectors/internal/egress/tunnel.go`). The tunnel enforces Archie's host allow-list and loopback checks before chaining allowed traffic through `HTTPS_PROXY`. + +## Probes, Graceful Drain, and High Availability + +`cmd/archie` exposes three health endpoints (`internal/platform/health/health.go`): + +- `/healthz`: Liveness probe. Returns `200` while the HTTP server process is alive. +- `/startupz`: Startup probe. Verifies database connectivity and confirms the deletion ledger is consistent before Kubernetes routes traffic or triggers liveness checks. +- `/readyz`: Readiness probe. Requires `/startupz` checks plus completion of owner setup (`gate.go`), and returns `503` as soon as `SIGTERM` begins draining. + +Set `terminationGracePeriodSeconds` (`45` seconds in `values-prod.yaml`) higher than `shutdown_grace` (`30s`) so in-flight HTTP requests and run checkpoints finish before `SIGKILL`. + +Enterprise v1 runs Active-Passive HA with `replicaCount: 1` on a `StatefulSet` backed by a `ReadWriteOnce` PVC for `state_dir`. Never scale `replicaCount` above `1` in v1 without shared `state_dir` storage and v2 Active-Active coordination (`LISTEN/NOTIFY` hub, lease election, and object-lock deletion ledger). diff --git a/docs/enterprise/dr-and-backup.md b/docs/enterprise/dr-and-backup.md new file mode 100644 index 000000000..334160ca0 --- /dev/null +++ b/docs/enterprise/dr-and-backup.md @@ -0,0 +1,65 @@ +# Disaster Recovery and Backup Runbook + +Archie keeps durable state across three separate stores: PostgreSQL, the `age` sealing keys, and the external deletion ledger (`deletions.jsonl`). Back up and protect each store independently. Restoring PostgreSQL alone is never enough if `age` keys or the deletion ledger are lost. + +## Recovery Objectives + +| Store | What it holds | RPO target | RTO target | Backup mechanism | +| --- | --- | --- | --- | --- | +| PostgreSQL (`archie` database) | Workflows, runs, approvals, events, governance, sealed credentials, audit events | 5 minutes or less | 30 minutes | Automated base snapshots plus continuous WAL archiving (PITR) | +| `age` recovery keys (`age_backup_recipients`) | Ability to open sealed connector credentials and event HMAC secrets | Zero key loss | Immediate on restore | Offline escrow in enterprise secret manager or HSM vault | +| Deletion ledger (`state_dir/deletions.jsonl`) | Append-only record of deleted memory notes | Zero acknowledged deletion loss | 15 minutes | Independent PVC or host volume snapshots replicated off-cluster | + +## Independent Backup Strategy + +### 1. PostgreSQL Database + +Back up the PostgreSQL cluster using continuous WAL archiving and scheduled base backups so you can restore to a point in time. + +- Back up as the `postgres` or `archie_owner` administrative role, not `archie_app`. +- Include the `public.goose_db_version` table and every Archie module schema (`runs`, `connectors`, `events`, `governance`, `deliveries`, `judgement`, `approvals`, `memory`, `alerts`, `proposals`, `chat`, and `audit`). +- Exclude `state_dir` and `age` private keys from database backup media so a database dump alone cannot decrypt stored credentials. + +### 2. `age` Sealing Keys and Key Rotation + +`internal/platform/seal/seal.go` seals connector credentials (`connectors.credentials`) and webhook secrets (`events.sources.hmac_secret_sealed`) with `age` X25519 keys bound to record labels. If the active `age_identity` and all `age_backup_recipients` are lost, every sealed secret in the database is unrecoverable. + +Protect sealing keys with two controls: + +1. **Configure offline backup recipients:** Generate a recovery `age` keypair in your enterprise vault (`archie -new-age-identity` or `age-keygen`) and list its public `age1...` string under `age_backup_recipients` in `config.toml`. Keep the matching `AGE-SECRET-KEY-1...` offline in your secret manager. +2. **Rotate keys with `archie rekey`:** Rotate compromised or expiring `age` identities atomically using `archie rekey`. The command takes a PostgreSQL advisory lock (`archie.rekey.owner`). It opens every sealed credential and webhook secret with the old identity, re-seals and checks decryption with the new identity in one transaction, and writes a JSON audit log. + +Never delete the old identity from your vault until the post-rotation database backup completes. + +### 3. External Deletion Ledger (`deletions.jsonl`) + +When a user deletes a memory note, `modules/memory` commits the deletion in PostgreSQL and appends an `Entry` (`table`, `org_id`, `id`, `at`) to `deletions.jsonl` inside `state_dir` (`internal/platform/deletions/deletions.go`). Each append uses `flock` and `fsync` on both the file and parent directories so the record outlives the database. + +Keep `state_dir` on an independent `ReadWriteOnce` persistent volume (or dedicated host volume in Compose) and snapshot it separately from PostgreSQL. Never restore `state_dir` from a snapshot older than the database snapshot you are restoring. If `deletions.jsonl` is lost on an instance that previously recorded deletions, `memory.ReapplyDeletions` returns `deletions.ErrUnsafeRollback` and stops startup rather than exposing deleted notes. + +## Restore Procedure + +Follow these steps to recover a stage from backup: + +1. **Stop active Archie pods or containers:** Scale the `StatefulSet` to `0` (`kubectl scale statefulset archie --replicas=0`) or run `docker compose stop archie`. +2. **Acquire the exclusive serve lock:** If restoring onto an active PostgreSQL instance, hold `pg_advisory_lock(hashtextextended('archie.serve.owner', 0))` in your restore session so no stray Archie process can pass `pg.ClaimServe` before recovery finishes. +3. **Restore PostgreSQL:** Restore the base snapshot and replay WAL logs to the target recovery timestamp. Verify `public.goose_db_version` is intact. +4. **Restore or preserve `state_dir`:** Keep the existing `state_dir` volume containing the latest `deletions.jsonl`, or restore the newest `state_dir` backup taken at or after the database restore timestamp. +5. **Restore `age` key material:** Ensure `ARCHIE_AGE_IDENTITY_FILE` mounts a valid `age_identity` (or the backup identity stored in your vault if the primary key was lost). If you recover with the backup identity, run `archie rekey` right after startup to rotate to a new runtime key. +6. **Run migrations and start Archie:** Run the `archie migrate` Job if the restored snapshot precedes the deployed binary schema version, then scale the `StatefulSet` back to `1`. +7. **Verify reconciliation and readiness:** Watch stdout JSON logs for `applied the record of deletions` (`memory.ReapplyDeletions`) and confirm `/startupz` and `/readyz` return `200`. + +## Restore Verification Drill + +Run this drill in `staging` each quarter and after any backup architecture change. Record the completion timestamp, operator, and measured RTO in your compliance log. + +1. Sign in to the `staging` instance and create a test memory note. Record its note ID and confirm it appears in `GET /api/memory/notes`. +2. Take an on-demand PostgreSQL snapshot (`pre-deletion snapshot`). +3. Delete the test memory note through the UI or API. Verify `state_dir/deletions.jsonl` contains a new JSON line matching the deleted note ID. +4. Scale the `staging` Archie `StatefulSet` to `0`. +5. Restore the `staging` PostgreSQL database to the `pre-deletion snapshot` taken in step 2. Leave `state_dir` untouched. +6. Verify the deleted note row is temporarily present again in PostgreSQL before Archie starts. +7. Scale the `staging` Archie `StatefulSet` back to `1`. +8. Check pod logs for `applied the record of deletions` and wait for `/readyz` to return `200`. +9. Query `GET /api/memory/notes` and PostgreSQL to confirm the test note remains deleted. +10. Verify credential decryption works using the backup `age` recipient key (or perform a test `archie rekey` rotation and confirm an existing connector still passes health checks). diff --git a/internal/app/archie/rekey.go b/internal/app/archie/rekey.go new file mode 100644 index 000000000..2280b0082 --- /dev/null +++ b/internal/app/archie/rekey.go @@ -0,0 +1,159 @@ +package archie + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "strings" + + "filippo.io/age" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/buildinfo" + "github.com/samcharles93/archie-core/internal/platform/pg" + "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/events" +) + +const rekeyLockKey = "archie.rekey.owner" + +// RekeyConfig holds the old and new age identities and optional backup +// recipients used by `archie rekey`. +type RekeyConfig struct { + OldIdentity string + NewIdentity string + NewBackups []string +} + +// LoadRekeyConfig resolves old and new age identities from flags or +// ARCHIE_OLD_AGE_IDENTITY[_FILE] and ARCHIE_NEW_AGE_IDENTITY[_FILE], and +// validates that both are non-empty, valid, and distinct. +func LoadRekeyConfig(oldIdentity, newIdentity string, newBackups []string) (RekeyConfig, error) { + oldVal := strings.TrimSpace(oldIdentity) + if envOld, ok, err := envOrFile("ARCHIE_OLD_AGE_IDENTITY", "ARCHIE_OLD_AGE_IDENTITY_FILE"); err != nil { + return RekeyConfig{}, err + } else if ok { + oldVal = envOld + } + + newVal := strings.TrimSpace(newIdentity) + if envNew, ok, err := envOrFile("ARCHIE_NEW_AGE_IDENTITY", "ARCHIE_NEW_AGE_IDENTITY_FILE"); err != nil { + return RekeyConfig{}, err + } else if ok { + newVal = envNew + } + + backups := make([]string, len(newBackups)) + for i, b := range newBackups { + backups[i] = strings.TrimSpace(b) + } + + rcfg := RekeyConfig{ + OldIdentity: oldVal, + NewIdentity: newVal, + NewBackups: backups, + } + if _, _, err := rcfg.sealers(); err != nil { + return RekeyConfig{}, err + } + return rcfg, nil +} + +func (c RekeyConfig) sealers() (oldSealer, newSealer *seal.Sealer, err error) { + if c.OldIdentity == "" { + return nil, nil, errors.New("old age identity is required") + } + if c.NewIdentity == "" { + return nil, nil, errors.New("new age identity is required") + } + oldID, err := age.ParseX25519Identity(c.OldIdentity) + if err != nil { + return nil, nil, fmt.Errorf("old age identity: %w", err) + } + newID, err := age.ParseX25519Identity(c.NewIdentity) + if err != nil { + return nil, nil, fmt.Errorf("new age identity: %w", err) + } + if oldID.String() == newID.String() { + return nil, nil, errors.New("old and new age identities must be distinct") + } + oldSealer, err = seal.New(oldID.String(), nil) + if err != nil { + return nil, nil, fmt.Errorf("old sealer: %w", err) + } + newSealer, err = seal.New(newID.String(), c.NewBackups) + if err != nil { + return nil, nil, fmt.Errorf("new sealer: %w", err) + } + return oldSealer, newSealer, nil +} + +// Rekey rotates age sealing identities atomically across connectors credentials +// and event HMAC secrets under a Postgres advisory lock. +func Rekey(ctx context.Context, configPath string, rcfg RekeyConfig) error { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version) + oldSealer, newSealer, err := rcfg.sealers() + if err != nil { + return err + } + dbURL, err := LoadRuntimeDBConfig(configPath) + if err != nil { + return err + } + db, err := pg.Open(ctx, dbURL) + if err != nil { + return err + } + defer func() { _ = db.Close() }() + if err := pg.VerifySchema(ctx, db); err != nil { + return err + } + release, err := lockRekey(ctx, db) + if err != nil { + return err + } + defer release() + + tx, err := db.BeginTxx(ctx, nil) + if err != nil { + return fmt.Errorf("begin rekey transaction: %w", err) + } + defer func() { _ = tx.Rollback() }() + + creds, err := connectors.RekeyCredentials(ctx, tx, oldSealer, newSealer) + if err != nil { + return err + } + sources, err := events.RekeySources(ctx, tx, oldSealer, newSealer) + if err != nil { + return err + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit rekey transaction: %w", err) + } + log.InfoContext(ctx, "age sealing keys rotated", + "credentials_rekeyed", creds, + "sources_rekeyed", sources, + "backup_recipients", len(rcfg.NewBackups), + ) + return nil +} + +func lockRekey(ctx context.Context, db *sqlx.DB) (func(), error) { + conn, err := db.Conn(ctx) + if err != nil { + return nil, fmt.Errorf("lock rekey: %w", err) + } + if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock(hashtextextended($1, 0))", rekeyLockKey); err != nil { + _ = conn.Close() + return nil, fmt.Errorf("lock rekey: %w", err) + } + return func() { + _, _ = conn.ExecContext(context.WithoutCancel(ctx), + "SELECT pg_advisory_unlock(hashtextextended($1, 0))", rekeyLockKey) + _ = conn.Close() + }, nil +} diff --git a/internal/app/archie/rekey_test.go b/internal/app/archie/rekey_test.go new file mode 100644 index 000000000..25fdb3e31 --- /dev/null +++ b/internal/app/archie/rekey_test.go @@ -0,0 +1,102 @@ +package archie + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "filippo.io/age" +) + +func genAgeIdentity(t *testing.T) *age.X25519Identity { + t.Helper() + id, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + return id +} + +// TestLoadRekeyConfigValidationAndOverrides guards `archie rekey` key parsing, +// *_FILE secret loading, ambiguity refusal, and identical-key rejection. +func TestLoadRekeyConfigValidationAndOverrides(t *testing.T) { + oldID := genAgeIdentity(t) + newID := genAgeIdentity(t) + backupID := genAgeIdentity(t) + + dir := t.TempDir() + oldFile := filepath.Join(dir, "old_age_key") + newFile := filepath.Join(dir, "new_age_key") + if err := os.WriteFile(oldFile, []byte(oldID.String()+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(newFile, []byte(newID.String()+"\n"), 0o600); err != nil { + t.Fatal(err) + } + + t.Run("flags", func(t *testing.T) { + cfg, err := LoadRekeyConfig(oldID.String(), newID.String(), []string{backupID.Recipient().String()}) + if err != nil { + t.Fatalf("LoadRekeyConfig: %v", err) + } + if cfg.OldIdentity != oldID.String() || cfg.NewIdentity != newID.String() || len(cfg.NewBackups) != 1 { + t.Fatalf("unexpected RekeyConfig: %+v", cfg) + } + }) + + t.Run("env file overrides", func(t *testing.T) { + t.Setenv("ARCHIE_OLD_AGE_IDENTITY_FILE", oldFile) + t.Setenv("ARCHIE_NEW_AGE_IDENTITY_FILE", newFile) + cfg, err := LoadRekeyConfig("", "", nil) + if err != nil { + t.Fatalf("LoadRekeyConfig from *_FILE: %v", err) + } + if cfg.OldIdentity != oldID.String() || cfg.NewIdentity != newID.String() { + t.Fatalf("unexpected RekeyConfig from files: %+v", cfg) + } + }) + + t.Run("both env and file rejected", func(t *testing.T) { + t.Setenv("ARCHIE_OLD_AGE_IDENTITY", oldID.String()) + t.Setenv("ARCHIE_OLD_AGE_IDENTITY_FILE", oldFile) + t.Setenv("ARCHIE_NEW_AGE_IDENTITY", newID.String()) + if _, err := LoadRekeyConfig("", "", nil); err == nil || !strings.Contains(err.Error(), "not both") { + t.Fatalf("expected ambiguity error, got %v", err) + } + }) + + tests := []struct { + name string + oldKey string + newKey string + backups []string + wantSub string + }{ + {name: "empty old", oldKey: "", newKey: newID.String(), wantSub: "old age identity is required"}, + {name: "empty new", oldKey: oldID.String(), newKey: "", wantSub: "new age identity is required"}, + {name: "invalid old", oldKey: "not-an-age-key", newKey: newID.String(), wantSub: "old age identity"}, + {name: "invalid new", oldKey: oldID.String(), newKey: "not-an-age-key", wantSub: "new age identity"}, + {name: "invalid backup", oldKey: oldID.String(), newKey: newID.String(), backups: []string{"bad-recipient"}, wantSub: "backup recipient"}, + {name: "identical keys", oldKey: oldID.String(), newKey: oldID.String(), wantSub: "must be distinct"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + _, err := LoadRekeyConfig(tc.oldKey, tc.newKey, tc.backups) + if err == nil || !strings.Contains(err.Error(), tc.wantSub) { + t.Fatalf("LoadRekeyConfig(%q, %q) = %v, want substring %q", tc.oldKey, tc.newKey, err, tc.wantSub) + } + }) + } +} + +func TestRekeyRejectsInvalidConfigBeforeOpeningDB(t *testing.T) { + id := genAgeIdentity(t) + if err := Rekey(t.Context(), "", RekeyConfig{OldIdentity: id.String(), NewIdentity: id.String()}); err == nil { + t.Fatal("expected error for identical identities") + } + other := genAgeIdentity(t) + if err := Rekey(t.Context(), "", RekeyConfig{OldIdentity: id.String(), NewIdentity: other.String()}); err == nil { + t.Fatal("expected error when database.url is missing") + } +} diff --git a/internal/platform/pg/migrations/00020_audit_events.sql b/internal/platform/pg/migrations/00020_audit_events.sql new file mode 100644 index 000000000..11c9ebb36 --- /dev/null +++ b/internal/platform/pg/migrations/00020_audit_events.sql @@ -0,0 +1,24 @@ +-- +goose Up +CREATE SCHEMA audit; + +-- Append-only audit events. The runtime database role holds only SELECT and +-- INSERT privileges on this schema so records cannot be modified or deleted. +CREATE TABLE audit.events ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + at timestamptz NOT NULL DEFAULT now(), + category text NOT NULL, + action text NOT NULL, + actor_id text NOT NULL, + actor_kind text NOT NULL DEFAULT '', + resource_kind text NOT NULL DEFAULT '', + resource_id text NOT NULL DEFAULT '', + outcome text NOT NULL, + trace_id text NOT NULL DEFAULT '', + detail jsonb NOT NULL DEFAULT '{}' +); +CREATE INDEX idx_audit_events_org_at ON audit.events (org_id, at DESC); +CREATE INDEX idx_audit_events_org_category_at ON audit.events (org_id, category, at DESC); + +-- +goose Down +DROP SCHEMA audit CASCADE; diff --git a/internal/platform/pg/pg.go b/internal/platform/pg/pg.go index 9db99ec50..8a24b9d9e 100644 --- a/internal/platform/pg/pg.go +++ b/internal/platform/pg/pg.go @@ -102,6 +102,15 @@ func lockMigrate(ctx context.Context, db *sqlx.DB) (release func(), err error) { func migrateLockKey() string { return "archie." + migrateLockName + ".owner" } +// schemaPrivileges returns the runtime DML privileges for schema. The audit +// schema is append-only so the runtime role may never UPDATE or DELETE rows. +func schemaPrivileges(schema string) string { + if schema == "audit" { + return "SELECT, INSERT" + } + return "SELECT, INSERT, UPDATE, DELETE" +} + // grantRuntime gives the runtime role USAGE and DML on each schema, never DDL. func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error { cfg, err := pgx.ParseConfig(runtimeURL) @@ -111,9 +120,10 @@ func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas [ role := pgx.Identifier{cfg.User}.Sanitize() for _, schema := range schemas { name := pgx.Identifier{schema}.Sanitize() + privs := schemaPrivileges(schema) for _, stmt := range []string{ "GRANT USAGE ON SCHEMA " + name + " TO " + role, - "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role, + "GRANT " + privs + " ON ALL TABLES IN SCHEMA " + name + " TO " + role, // A table keyed by a serial draws from a sequence, which is its // own grant: a module whose insert draws on one would fail DML it // is otherwise allowed. diff --git a/internal/platform/pg/pg_test.go b/internal/platform/pg/pg_test.go index 225916398..46b08660c 100644 --- a/internal/platform/pg/pg_test.go +++ b/internal/platform/pg/pg_test.go @@ -2,6 +2,7 @@ package pg import ( "slices" + "strings" "testing" ) @@ -41,3 +42,28 @@ func TestMissingMigrations(t *testing.T) { }) } } + +// TestSchemaPrivileges guards the append-only privilege split for the audit +// schema so runtime database credentials can never UPDATE or DELETE audit rows. +func TestSchemaPrivileges(t *testing.T) { + tests := []struct { + schema string + want string + }{ + {schema: "audit", want: "SELECT, INSERT"}, + {schema: "governance", want: "SELECT, INSERT, UPDATE, DELETE"}, + {schema: "runs", want: "SELECT, INSERT, UPDATE, DELETE"}, + {schema: "", want: "SELECT, INSERT, UPDATE, DELETE"}, + } + for _, tc := range tests { + t.Run(tc.schema, func(t *testing.T) { + got := schemaPrivileges(tc.schema) + if got != tc.want { + t.Fatalf("schemaPrivileges(%q) = %q, want %q", tc.schema, got, tc.want) + } + if tc.schema == "audit" && (strings.Contains(got, "UPDATE") || strings.Contains(got, "DELETE")) { + t.Fatalf("audit schema must not grant UPDATE or DELETE, got %q", got) + } + }) + } +} diff --git a/internal/platform/telemetry/telemetry.go b/internal/platform/telemetry/telemetry.go new file mode 100644 index 000000000..05e0475fa --- /dev/null +++ b/internal/platform/telemetry/telemetry.go @@ -0,0 +1,260 @@ +// Package telemetry configures OpenTelemetry trace export, trace-correlated +// structured logging, HTTP span middleware, and an internal Prometheus /metrics +// endpoint using the Go standard library. +package telemetry + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "os" + "runtime" + "strconv" + "strings" + "sync/atomic" + "time" + + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.43.0" + "go.opentelemetry.io/otel/trace" +) + +const ( + otlpEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT" + metricsMediaType = "text/plain; version=0.0.4; charset=utf-8" + shutdownTimeout = 5 * time.Second +) + +// Setup registers the W3C TraceContext propagator and, when +// OTEL_EXPORTER_OTLP_ENDPOINT is set, installs an OTLP/gRPC TracerProvider. +// The returned shutdown function flushes pending spans on exit. +func Setup(ctx context.Context, serviceName, version string) (func(context.Context) error, error) { + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, + propagation.Baggage{}, + )) + if strings.TrimSpace(os.Getenv(otlpEndpointEnv)) == "" { + return func(context.Context) error { return nil }, nil + } + res, err := resource.Merge(resource.Default(), resource.NewWithAttributes( + semconv.SchemaURL, + semconv.ServiceName(serviceName), + semconv.ServiceVersion(version), + semconv.ServiceInstanceID(instanceID()), + )) + if err != nil { + return nil, fmt.Errorf("telemetry resource: %w", err) + } + exporter, err := otlptracegrpc.New(ctx) + if err != nil { + return nil, fmt.Errorf("telemetry exporter: %w", err) + } + tp := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(res), + ) + otel.SetTracerProvider(tp) + return func(shutdownCtx context.Context) error { + if _, hasDeadline := shutdownCtx.Deadline(); !hasDeadline { + var cancel context.CancelFunc + shutdownCtx, cancel = context.WithTimeout(context.WithoutCancel(shutdownCtx), shutdownTimeout) + defer cancel() + } + return tp.Shutdown(shutdownCtx) + }, nil +} + +func instanceID() string { + host, _ := os.Hostname() + return host + "-" + strconv.Itoa(os.Getpid()) +} + +// stampedKey marks a context whose log record already carries trace_id and +// span_id so nested trace handlers do not emit duplicate attributes. +type stampedKey struct{} + +type logHandler struct { + inner slog.Handler +} + +// NewLogHandler wraps base so log records emitted with an active span in ctx +// include trace_id and span_id attributes. +func NewLogHandler(base slog.Handler) slog.Handler { + return logHandler{inner: base} +} + +func (h logHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.inner.Enabled(ctx, level) +} + +func (h logHandler) Handle(ctx context.Context, r slog.Record) error { + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && ctx.Value(stampedKey{}) == nil { + r.AddAttrs( + slog.String("trace_id", sc.TraceID().String()), + slog.String("span_id", sc.SpanID().String()), + ) + ctx = context.WithValue(ctx, stampedKey{}, true) + } + return h.inner.Handle(ctx, r) +} + +func (h logHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return logHandler{inner: h.inner.WithAttrs(attrs)} +} + +func (h logHandler) WithGroup(name string) slog.Handler { + return logHandler{inner: h.inner.WithGroup(name)} +} + +// Metrics tracks process-local HTTP request counts, latency sums, and Go +// runtime metrics for Prometheus scraping. +type Metrics struct { + started time.Time + inFlight atomic.Int64 + requests2xx atomic.Int64 + requests3xx atomic.Int64 + requests4xx atomic.Int64 + requests5xx atomic.Int64 + requestsOther atomic.Int64 + durationNanos atomic.Int64 + durationCount atomic.Int64 +} + +// NewMetrics returns a Metrics collector anchored at the current time. +func NewMetrics() *Metrics { + return &Metrics{started: time.Now()} +} + +// Middleware records HTTP request counts, durations, and in-flight requests, +// and wraps next in otelhttp.NewHandler for HTTP span creation. +func (m *Metrics) Middleware(next http.Handler) http.Handler { + instrumented := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + m.inFlight.Add(1) + start := time.Now() + sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + defer func() { + m.inFlight.Add(-1) + m.recordRequest(sw.status, time.Since(start)) + }() + next.ServeHTTP(sw, r) + }) + return otelhttp.NewHandler(instrumented, "http", + otelhttp.WithFilter(func(r *http.Request) bool { + return !isProbeOrMetrics(r.URL.Path) + }), + ) +} + +func isProbeOrMetrics(path string) bool { + return strings.HasPrefix(path, "/health") || path == "/readyz" || path == "/startupz" || path == "/metrics" +} + +func (m *Metrics) recordRequest(status int, took time.Duration) { + m.durationCount.Add(1) + m.durationNanos.Add(took.Nanoseconds()) + switch status / 100 { + case 2: + m.requests2xx.Add(1) + case 3: + m.requests3xx.Add(1) + case 4: + m.requests4xx.Add(1) + case 5: + m.requests5xx.Add(1) + default: + m.requestsOther.Add(1) + } +} + +type statusWriter struct { + http.ResponseWriter + status int + wroteHeader bool +} + +func (w *statusWriter) WriteHeader(code int) { + if !w.wroteHeader { + w.status = code + w.wroteHeader = true + } + w.ResponseWriter.WriteHeader(code) +} + +func (w *statusWriter) Write(p []byte) (int, error) { + if !w.wroteHeader { + w.wroteHeader = true + } + return w.ResponseWriter.Write(p) +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +// MetricsHandler serves Prometheus text format metrics on an internal endpoint. +func (m *Metrics) MetricsHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + var ms runtime.MemStats + runtime.ReadMemStats(&ms) + + uptime := time.Since(m.started).Seconds() + durSec := float64(m.durationNanos.Load()) / float64(time.Second) + + w.Header().Set("Content-Type", metricsMediaType) + w.Header().Set("Cache-Control", "no-store") + _, _ = fmt.Fprintf(w, + "# HELP archie_uptime_seconds Process uptime in seconds.\n"+ + "# TYPE archie_uptime_seconds gauge\n"+ + "archie_uptime_seconds %.6f\n"+ + "# HELP archie_http_requests_in_flight Current number of in-flight HTTP requests.\n"+ + "# TYPE archie_http_requests_in_flight gauge\n"+ + "archie_http_requests_in_flight %d\n"+ + "# HELP archie_http_requests_total Total number of HTTP requests handled by status class.\n"+ + "# TYPE archie_http_requests_total counter\n"+ + "archie_http_requests_total{status=\"2xx\"} %d\n"+ + "archie_http_requests_total{status=\"3xx\"} %d\n"+ + "archie_http_requests_total{status=\"4xx\"} %d\n"+ + "archie_http_requests_total{status=\"5xx\"} %d\n"+ + "archie_http_requests_total{status=\"other\"} %d\n"+ + "# HELP archie_http_request_duration_seconds Total HTTP request duration and count.\n"+ + "# TYPE archie_http_request_duration_seconds summary\n"+ + "archie_http_request_duration_seconds_sum %.6f\n"+ + "archie_http_request_duration_seconds_count %d\n"+ + "# HELP go_goroutines Number of goroutines that currently exist.\n"+ + "# TYPE go_goroutines gauge\n"+ + "go_goroutines %d\n"+ + "# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.\n"+ + "# TYPE go_memstats_alloc_bytes gauge\n"+ + "go_memstats_alloc_bytes %d\n"+ + "# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.\n"+ + "# TYPE go_memstats_heap_inuse_bytes gauge\n"+ + "go_memstats_heap_inuse_bytes %d\n"+ + "# HELP go_memstats_sys_bytes Number of bytes obtained from system.\n"+ + "# TYPE go_memstats_sys_bytes gauge\n"+ + "go_memstats_sys_bytes %d\n"+ + "# HELP go_gc_cycles_total Total number of completed GC cycles.\n"+ + "# TYPE go_gc_cycles_total counter\n"+ + "go_gc_cycles_total %d\n", + uptime, + m.inFlight.Load(), + m.requests2xx.Load(), + m.requests3xx.Load(), + m.requests4xx.Load(), + m.requests5xx.Load(), + m.requestsOther.Load(), + durSec, + m.durationCount.Load(), + runtime.NumGoroutine(), + ms.Alloc, + ms.HeapInuse, + ms.Sys, + ms.NumGC, + ) + }) +} diff --git a/internal/platform/telemetry/telemetry_test.go b/internal/platform/telemetry/telemetry_test.go new file mode 100644 index 000000000..a0c126648 --- /dev/null +++ b/internal/platform/telemetry/telemetry_test.go @@ -0,0 +1,136 @@ +package telemetry + +import ( + "bytes" + "context" + json "encoding/json/v2" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "go.opentelemetry.io/otel" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" +) + +// TestLogHandlerInjectsTraceAndSpanIDs guards that NewLogHandler attaches +// trace_id and span_id once when a valid span exists in ctx, and omits them +// when no span is active. +func TestLogHandlerInjectsTraceAndSpanIDs(t *testing.T) { + var buf bytes.Buffer + handler := NewLogHandler(NewLogHandler(slog.NewJSONHandler(&buf, nil))) + logger := slog.New(handler) + + logger.InfoContext(t.Context(), "without span") + if strings.Contains(buf.String(), "trace_id") || strings.Contains(buf.String(), "span_id") { + t.Fatalf("unexpected trace fields without span: %s", buf.String()) + } + buf.Reset() + + tp := sdktrace.NewTracerProvider() + t.Cleanup(func() { _ = tp.Shutdown(context.Background()) }) + ctx, span := tp.Tracer("telemetry-test").Start(t.Context(), "op") + defer span.End() + + logger.InfoContext(ctx, "with span") + line := buf.String() + if strings.Count(line, `"trace_id"`) != 1 || strings.Count(line, `"span_id"`) != 1 { + t.Fatalf("expected single trace_id and span_id fields, got: %s", line) + } + + var parsed map[string]any + if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil { + t.Fatalf("unmarshal log line: %v (%s)", err, line) + } + if parsed["trace_id"] != span.SpanContext().TraceID().String() { + t.Fatalf("trace_id = %v, want %s", parsed["trace_id"], span.SpanContext().TraceID().String()) + } + if parsed["span_id"] != span.SpanContext().SpanID().String() { + t.Fatalf("span_id = %v, want %s", parsed["span_id"], span.SpanContext().SpanID().String()) + } +} + +// TestMetricsMiddlewareAndPrometheusOutput guards HTTP span creation, request +// status counting, and Prometheus text exposition formatting. +func TestMetricsMiddlewareAndPrometheusOutput(t *testing.T) { + prevTP := otel.GetTracerProvider() + tp := sdktrace.NewTracerProvider() + otel.SetTracerProvider(tp) + t.Cleanup(func() { + otel.SetTracerProvider(prevTP) + _ = tp.Shutdown(context.Background()) + }) + + m := NewMetrics() + var sawValidSpan bool + var probeHadSpan bool + mux := http.NewServeMux() + mux.HandleFunc("/api/ok", func(w http.ResponseWriter, r *http.Request) { + sawValidSpan = trace.SpanContextFromContext(r.Context()).IsValid() + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/api/missing", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + mux.HandleFunc("/api/fail", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + }) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + probeHadSpan = trace.SpanContextFromContext(r.Context()).IsValid() + w.WriteHeader(http.StatusOK) + }) + + wrapped := m.Middleware(mux) + for _, path := range []string{"/api/ok", "/api/missing", "/api/fail", "/healthz"} { + rec := httptest.NewRecorder() + wrapped.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) + } + if !sawValidSpan { + t.Fatal("expected otelhttp middleware to create a valid span for /api/ok") + } + if probeHadSpan { + t.Fatal("expected /healthz probe to be excluded from otelhttp span creation") + } + + metricsRec := httptest.NewRecorder() + m.MetricsHandler().ServeHTTP(metricsRec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil)) + if metricsRec.Code != http.StatusOK { + t.Fatalf("/metrics status = %d, want 200", metricsRec.Code) + } + if gotCT := metricsRec.Header().Get("Content-Type"); gotCT != metricsMediaType { + t.Fatalf("/metrics Content-Type = %q, want %q", gotCT, metricsMediaType) + } + + body := metricsRec.Body.String() + for _, want := range []string{ + "archie_uptime_seconds ", + "archie_http_requests_in_flight 0", + `archie_http_requests_total{status="2xx"} 2`, + `archie_http_requests_total{status="4xx"} 1`, + `archie_http_requests_total{status="5xx"} 1`, + "archie_http_request_duration_seconds_count 4", + "archie_http_request_duration_seconds_sum ", + "go_goroutines ", + "go_memstats_alloc_bytes ", + "go_gc_cycles_total ", + } { + if !strings.Contains(body, want) { + t.Fatalf("/metrics output missing %q:\n%s", want, body) + } + } +} + +// TestSetupWithoutEndpoint guards that Setup succeeds as a no-op when +// OTEL_EXPORTER_OTLP_ENDPOINT is unset. +func TestSetupWithoutEndpoint(t *testing.T) { + t.Setenv(otlpEndpointEnv, "") + shutdown, err := Setup(t.Context(), "archie", "test") + if err != nil { + t.Fatalf("Setup() error = %v", err) + } + if err := shutdown(t.Context()); err != nil { + t.Fatalf("shutdown() error = %v", err) + } +} diff --git a/modules/audit/api.go b/modules/audit/api.go new file mode 100644 index 000000000..770d861c9 --- /dev/null +++ b/modules/audit/api.go @@ -0,0 +1,257 @@ +package audit + +import ( + "context" + "encoding/csv" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "io" + "net/http" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/audit/internal/store" + "github.com/samcharles93/archie-core/modules/governance" +) + +const ( + exportFormatJSONL = "jsonl" + exportFormatCSV = "csv" +) + +type eventsInput struct { + Category string `query:"category" doc:"Only events in this category"` + Action string `query:"action" doc:"Only events for this action"` + Actor string `query:"actor" doc:"Only events by this actor ID"` + Since time.Time `query:"since" doc:"Only events recorded at or after this time"` + Until time.Time `query:"until" doc:"Only events recorded before this time"` + Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many events to return"` + Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching events to skip"` +} + +type exportInput struct { + Category string `query:"category" doc:"Only events in this category"` + Action string `query:"action" doc:"Only events for this action"` + Actor string `query:"actor" doc:"Only events by this actor ID"` + Since time.Time `query:"since" doc:"Only events recorded at or after this time"` + Until time.Time `query:"until" doc:"Only events recorded before this time"` + Limit int `query:"limit" default:"1000" minimum:"1" maximum:"1000" doc:"Maximum number of events to export"` + Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching events to skip"` + Format string `query:"format" default:"jsonl" enum:"jsonl,csv" doc:"Export format: jsonl or csv"` +} + +type eventsBody struct { + Events []Event `json:"events"` + More bool `json:"more" doc:"Whether older events match beyond this page"` +} + +// Register adds the Cedar-gated audit query and export routes. +func (m *Module) Register(api huma.API) { + tags := []string{"Audit"} + httpapi.Register(api, httpapi.Authorized(governance.ActionReadAudit, governance.KindAudit), huma.Operation{ + OperationID: "list-audit-events", + Method: http.MethodGet, + Path: "/api/audit/events", + Summary: "List append-only audit events", + Tags: tags, + }, m.listEvents) + httpapi.Register(api, httpapi.Authorized(governance.ActionReadAudit, governance.KindAudit), huma.Operation{ + OperationID: "export-audit-events", + Method: http.MethodGet, + Path: "/api/audit/events/export", + Summary: "Export append-only audit events as JSONL or CSV", + Tags: tags, + Responses: map[string]*huma.Response{"200": { + Description: "Audit events exported as JSON Lines or CSV", + Content: map[string]*huma.MediaType{ + "application/x-ndjson": {Schema: &huma.Schema{Type: huma.TypeString}}, + "text/csv": {Schema: &huma.Schema{Type: huma.TypeString}}, + }, + }}, + }, m.exportEvents) +} + +func (m *Module) listEvents(ctx context.Context, in *eventsInput) (*httpapi.Reply[eventsBody], error) { + if m.store == nil { + return nil, huma.Error503ServiceUnavailable("audit store is unavailable") + } + f := Filter{ + OrgID: m.callerOrg(ctx), + Category: in.Category, + Action: in.Action, + Actor: in.Actor, + Since: in.Since, + Until: in.Until, + Limit: in.Limit, + Offset: in.Offset, + } + if err := f.Validate(); err != nil { + return nil, huma.Error400BadRequest(err.Error()) + } + rows, err := m.store.List(ctx, store.Filter{ + OrgID: f.OrgID, + Category: f.Category, + Action: f.Action, + ActorID: f.Actor, + Since: f.Since, + Until: f.Until, + Limit: f.Limit + 1, + Offset: f.Offset, + }) + if err != nil { + if m.log != nil { + m.log.ErrorContext(ctx, "list audit events", "error", err) + } + return nil, huma.Error500InternalServerError("could not list audit events") + } + more := len(rows) > f.Limit + events := eventsFromRows(rows[:min(len(rows), f.Limit)]) + return httpapi.OK(eventsBody{Events: events, More: more}), nil +} + +func (m *Module) exportEvents(ctx context.Context, in *exportInput) (*huma.StreamResponse, error) { + if m.store == nil { + return nil, huma.Error503ServiceUnavailable("audit store is unavailable") + } + format := in.Format + if format == "" { + format = exportFormatJSONL + } + if format != exportFormatJSONL && format != exportFormatCSV { + return nil, huma.Error400BadRequest(fmt.Sprintf("unsupported export format %q", format)) + } + f := Filter{ + OrgID: m.callerOrg(ctx), + Category: in.Category, + Action: in.Action, + Actor: in.Actor, + Since: in.Since, + Until: in.Until, + Limit: in.Limit, + Offset: in.Offset, + } + if err := f.Validate(); err != nil { + return nil, huma.Error400BadRequest(err.Error()) + } + events, err := m.List(ctx, f) + if err != nil { + if errors.Is(err, ErrInvalidFilter) { + return nil, huma.Error400BadRequest(err.Error()) + } + if m.log != nil { + m.log.ErrorContext(ctx, "export audit events", "error", err) + } + return nil, huma.Error500InternalServerError("could not export audit events") + } + return &huma.StreamResponse{Body: func(hc huma.Context) { + writeExport(hc, format, events) + }}, nil +} + +func (m *Module) callerOrg(ctx context.Context) string { + if p, ok := governance.PrincipalFromContext(ctx); ok && p.Org != "" { + return string(p.Org) + } + return m.orgID +} + +func writeExport(hc huma.Context, format string, events []Event) { + hc.SetHeader("Cache-Control", "no-store") + w := hc.BodyWriter() + if format == exportFormatCSV { + hc.SetHeader("Content-Type", "text/csv; charset=utf-8") + hc.SetHeader("Content-Disposition", `attachment; filename="audit-events.csv"`) + hc.SetStatus(http.StatusOK) + _ = writeCSV(w, events) + return + } + hc.SetHeader("Content-Type", "application/x-ndjson; charset=utf-8") + hc.SetHeader("Content-Disposition", `attachment; filename="audit-events.jsonl"`) + hc.SetStatus(http.StatusOK) + _ = writeJSONL(w, events) +} + +func writeJSONL(w io.Writer, events []Event) error { + for _, ev := range events { + raw, err := json.Marshal(ev) + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + } + return nil +} + +func writeCSV(w io.Writer, events []Event) error { + cw := csv.NewWriter(w) + header := []string{ + "id", "org_id", "at", "category", "action", + "actor_id", "actor_kind", "resource_kind", "resource_id", + "outcome", "trace_id", "detail", + } + if err := cw.Write(header); err != nil { + return err + } + for _, ev := range events { + detail := formatDetailString(ev.Detail) + row := []string{ + neutralizeCSVFormula(ev.ID.String()), + neutralizeCSVFormula(ev.OrgID), + neutralizeCSVFormula(ev.At.UTC().Format(time.RFC3339Nano)), + neutralizeCSVFormula(ev.Category), + neutralizeCSVFormula(ev.Action), + neutralizeCSVFormula(ev.ActorID), + neutralizeCSVFormula(ev.ActorKind), + neutralizeCSVFormula(ev.ResourceKind), + neutralizeCSVFormula(ev.ResourceID), + neutralizeCSVFormula(ev.Outcome), + neutralizeCSVFormula(ev.TraceID), + neutralizeCSVFormula(detail), + } + if err := cw.Write(row); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +func formatDetailString(detail any) string { + if detail == nil { + return "{}" + } + if raw, ok := detail.(jsontext.Value); ok { + if len(raw) == 0 { + return "{}" + } + return string(raw) + } + raw, err := json.Marshal(detail) + if err != nil { + return "{}" + } + return string(raw) +} + +// neutralizeCSVFormula prefixes spreadsheet formula triggers (=, +, -, @, tab, +// carriage return) with a single quote so exported CSV cells cannot execute as +// formulas when opened in Excel or LibreOffice Calc. +func neutralizeCSVFormula(s string) string { + if s == "" { + return s + } + switch s[0] { + case '=', '+', '-', '@', '\t', '\r': + return "'" + s + } + return s +} diff --git a/modules/audit/audit.go b/modules/audit/audit.go new file mode 100644 index 000000000..d73df8ba1 --- /dev/null +++ b/modules/audit/audit.go @@ -0,0 +1,222 @@ +// Package audit records and exports append-only security and operational audit +// events, backed by PostgreSQL and a structured stdout log stream. +package audit + +import ( + "bytes" + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + "go.opentelemetry.io/otel/trace" + + "github.com/samcharles93/archie-core/internal/platform/auditjson" + "github.com/samcharles93/archie-core/modules/audit/internal/store" +) + +const ( + defaultLimit = 100 + maxLimit = 1000 +) + +// ErrInvalidFilter indicates invalid query or export filter parameters. +var ErrInvalidFilter = errors.New("invalid audit filter") + +// Event is a single immutable audit record. +type Event struct { + ID uuid.UUID `json:"id"` + OrgID string `json:"org_id"` + At time.Time `json:"at"` + Category string `json:"category"` + Action string `json:"action"` + ActorID string `json:"actor_id"` + ActorKind string `json:"actor_kind,omitzero"` + ResourceKind string `json:"resource_kind,omitzero"` + ResourceID string `json:"resource_id,omitzero"` + Outcome string `json:"outcome"` + TraceID string `json:"trace_id,omitzero"` + Detail any `json:"detail,omitzero"` +} + +// Filter narrows audit event queries. +type Filter struct { + OrgID string + Category string + Action string + Actor string + Since time.Time + Until time.Time + Limit int + Offset int +} + +// Validate checks filter bounds and time range ordering. +func (f Filter) Validate() error { + if f.Limit < 1 || f.Limit > maxLimit { + return fmt.Errorf("%w: limit must be between 1 and %d", ErrInvalidFilter, maxLimit) + } + if f.Offset < 0 { + return fmt.Errorf("%w: offset must be non-negative", ErrInvalidFilter) + } + if !f.Since.IsZero() && !f.Until.IsZero() && f.Since.After(f.Until) { + return fmt.Errorf("%w: since must not be after until", ErrInvalidFilter) + } + return nil +} + +type auditStore interface { + Insert(ctx context.Context, row store.EventRow) error + List(ctx context.Context, f store.Filter) ([]store.EventRow, error) +} + +// Module records and serves one organisation's append-only audit stream. +type Module struct { + orgID string + store auditStore + log *slog.Logger +} + +// NewModule returns the audit module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module { + var st auditStore + if db != nil { + st = store.New(db) + } + return &Module{orgID: orgID, store: st, log: log} +} + +// Record redacts e.Detail, persists the event to audit.events, and emits a +// structured JSON log record tagged with "audit", true. +func (m *Module) Record(ctx context.Context, e Event) error { + if m.store == nil { + return errors.New("audit store is not configured") + } + if e.Category == "" || e.Action == "" || e.ActorID == "" || e.Outcome == "" { + return errors.New("audit event requires category, action, actor_id, and outcome") + } + if e.ID == uuid.Nil { + e.ID = uuid.New() + } + if e.OrgID == "" { + e.OrgID = m.orgID + } + if e.At.IsZero() { + e.At = time.Now().UTC() + } + if e.TraceID == "" { + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() { + e.TraceID = sc.TraceID().String() + } + } + detail := redactDetail(e.Detail) + row := store.EventRow{ + ID: e.ID, + OrgID: e.OrgID, + At: e.At.UTC(), + Category: e.Category, + Action: e.Action, + ActorID: e.ActorID, + ActorKind: e.ActorKind, + ResourceKind: e.ResourceKind, + ResourceID: e.ResourceID, + Outcome: e.Outcome, + TraceID: e.TraceID, + Detail: detail, + } + if err := m.store.Insert(ctx, row); err != nil { + return err + } + if m.log != nil { + m.log.InfoContext(ctx, "audit event", + "audit", true, + "audit_id", row.ID.String(), + "org_id", row.OrgID, + "at", row.At.Format(time.RFC3339Nano), + "category", row.Category, + "action", row.Action, + "actor_id", row.ActorID, + "actor_kind", row.ActorKind, + "resource_kind", row.ResourceKind, + "resource_id", row.ResourceID, + "outcome", row.Outcome, + "trace_id", row.TraceID, + "detail", detail, + ) + } + return nil +} + +// List returns matching audit events ordered newest first. +func (m *Module) List(ctx context.Context, f Filter) ([]Event, error) { + if m.store == nil { + return nil, errors.New("audit store is not configured") + } + if f.OrgID == "" { + f.OrgID = m.orgID + } + if f.Limit == 0 { + f.Limit = defaultLimit + } + if err := f.Validate(); err != nil { + return nil, err + } + rows, err := m.store.List(ctx, store.Filter{ + OrgID: f.OrgID, + Category: f.Category, + Action: f.Action, + ActorID: f.Actor, + Since: f.Since, + Until: f.Until, + Limit: f.Limit, + Offset: f.Offset, + }) + if err != nil { + return nil, err + } + return eventsFromRows(rows), nil +} + +func redactDetail(v any) jsontext.Value { + if v == nil { + return jsontext.Value(`{}`) + } + if raw, ok := v.(jsontext.Value); ok && len(bytes.TrimSpace(raw)) == 0 { + return jsontext.Value(`{}`) + } + payload := auditjson.FromValue(v) + if !payload.Truncated && len(payload.JSON) > 0 { + return payload.JSON + } + raw, err := json.Marshal(payload) + if err != nil { + return jsontext.Value(`{}`) + } + return raw +} + +func eventsFromRows(rows []store.EventRow) []Event { + out := make([]Event, 0, len(rows)) + for _, r := range rows { + out = append(out, Event{ + ID: r.ID, + OrgID: r.OrgID, + At: r.At, + Category: r.Category, + Action: r.Action, + ActorID: r.ActorID, + ActorKind: r.ActorKind, + ResourceKind: r.ResourceKind, + ResourceID: r.ResourceID, + Outcome: r.Outcome, + TraceID: r.TraceID, + Detail: r.Detail, + }) + } + return out +} diff --git a/modules/audit/audit_test.go b/modules/audit/audit_test.go new file mode 100644 index 000000000..39bc89692 --- /dev/null +++ b/modules/audit/audit_test.go @@ -0,0 +1,264 @@ +package audit + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/audit/internal/store" + "github.com/samcharles93/archie-core/modules/governance" +) + +type fakeAuditStore struct { + inserted []store.EventRow + rows []store.EventRow +} + +func (f *fakeAuditStore) Insert(_ context.Context, row store.EventRow) error { + f.inserted = append(f.inserted, row) + return nil +} + +func (f *fakeAuditStore) List(_ context.Context, _ store.Filter) ([]store.EventRow, error) { + return f.rows, nil +} + +// TestRecordRedactsDetailAndEmitsAuditLog guards that Record strips credentials +// from detail before persistence and stdout logging, attaches the active trace +// ID, and marks stdout records with audit=true. +func TestRecordRedactsDetailAndEmitsAuditLog(t *testing.T) { + var buf bytes.Buffer + st := &fakeAuditStore{} + m := &Module{ + orgID: "default", + store: st, + log: slog.New(slog.NewJSONHandler(&buf, nil)), + } + + tp := sdktrace.NewTracerProvider() + t.Cleanup(func() { _ = tp.Shutdown(context.Background()) }) + ctx, span := tp.Tracer("audit-test").Start(t.Context(), "record") + defer span.End() + + err := m.Record(ctx, Event{ + Category: "auth", + Action: "oidc.login", + ActorID: "user-1", + ActorKind: "user", + ResourceKind: "session", + ResourceID: "sess-1", + Outcome: "allowed", + Detail: map[string]any{ + "password": "hunter2-secret", + "api_key": "sk-live-12345", + "host": "prod-web-1", + }, + }) + if err != nil { + t.Fatalf("Record() error = %v", err) + } + if len(st.inserted) != 1 { + t.Fatalf("inserted rows = %d, want 1", len(st.inserted)) + } + row := st.inserted[0] + if row.TraceID != span.SpanContext().TraceID().String() { + t.Fatalf("row.TraceID = %q, want %q", row.TraceID, span.SpanContext().TraceID().String()) + } + detailText := string(row.Detail) + for _, secret := range []string{"hunter2-secret", "sk-live-12345"} { + if strings.Contains(detailText, secret) { + t.Fatalf("persisted detail leaked secret %q: %s", secret, detailText) + } + if strings.Contains(buf.String(), secret) { + t.Fatalf("stdout audit log leaked secret %q: %s", secret, buf.String()) + } + } + if !strings.Contains(detailText, "[redacted]") || !strings.Contains(detailText, "prod-web-1") { + t.Fatalf("persisted detail unexpected: %s", detailText) + } + + var logged map[string]any + if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &logged); err != nil { + t.Fatalf("unmarshal stdout log: %v (%s)", err, buf.String()) + } + if logged["audit"] != true { + t.Fatalf("log audit flag = %v, want true", logged["audit"]) + } + if logged["trace_id"] != span.SpanContext().TraceID().String() { + t.Fatalf("log trace_id = %v, want %s", logged["trace_id"], span.SpanContext().TraceID().String()) + } +} + +// TestCSVFormulaNeutralisation guards CSV export against spreadsheet formula +// injection on every dangerous prefix. +func TestCSVFormulaNeutralisation(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "equals", in: "=CMD|'/C calc'!A0", want: "'=CMD|'/C calc'!A0"}, + {name: "plus", in: "+1+1", want: "'+1+1"}, + {name: "minus", in: "-2+3", want: "'-2+3"}, + {name: "at", in: "@SUM(1+1)", want: "'@SUM(1+1)"}, + {name: "tab", in: "\t=1+1", want: "'\t=1+1"}, + {name: "carriage return", in: "\r=1+1", want: "'\r=1+1"}, + {name: "safe text", in: "alice@example.com", want: "alice@example.com"}, + {name: "empty", in: "", want: ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := neutralizeCSVFormula(tc.in); got != tc.want { + t.Fatalf("neutralizeCSVFormula(%q) = %q, want %q", tc.in, got, tc.want) + } + }) + } + + var out bytes.Buffer + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + err := writeCSV(&out, []Event{{ + ID: uuid.MustParse("11111111-1111-1111-1111-111111111111"), + OrgID: "default", + At: now, + Category: "auth", + Action: "=HYPERLINK(\"http://evil\")", + ActorID: "+admin", + Outcome: "@evil", + Detail: jsontext.Value(`{"note":"ok"}`), + }}) + if err != nil { + t.Fatalf("writeCSV() error = %v", err) + } + records, err := csv.NewReader(&out).ReadAll() + if err != nil { + t.Fatalf("csv.ReadAll() error = %v", err) + } + if len(records) != 2 { + t.Fatalf("csv rows = %d, want 2", len(records)) + } + if records[1][4] != "'=HYPERLINK(\"http://evil\")" { + t.Fatalf("csv action cell = %q, want formula-neutralised", records[1][4]) + } + if records[1][5] != "'+admin" { + t.Fatalf("csv actor cell = %q, want formula-neutralised", records[1][5]) + } + if records[1][9] != "'@evil" { + t.Fatalf("csv outcome cell = %q, want formula-neutralised", records[1][9]) + } +} + +// TestFilterValidation guards bounds and time-range checks on audit query and +// export inputs. +func TestFilterValidation(t *testing.T) { + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + tests := []struct { + name string + filter Filter + wantErr bool + }{ + {name: "valid defaults", filter: Filter{Limit: 100}}, + {name: "valid bounds", filter: Filter{Limit: 1000, Offset: 0, Since: now.Add(-time.Hour), Until: now}}, + {name: "limit zero", filter: Filter{Limit: 0}, wantErr: true}, + {name: "limit negative", filter: Filter{Limit: -5}, wantErr: true}, + {name: "limit over max", filter: Filter{Limit: 1001}, wantErr: true}, + {name: "negative offset", filter: Filter{Limit: 10, Offset: -1}, wantErr: true}, + {name: "since after until", filter: Filter{Limit: 10, Since: now, Until: now.Add(-time.Minute)}, wantErr: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := tc.filter.Validate() + if (err != nil) != tc.wantErr { + t.Fatalf("Validate() error = %v, wantErr = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, ErrInvalidFilter) { + t.Fatalf("Validate() error = %v, want ErrInvalidFilter", err) + } + }) + } + + m := &Module{orgID: "default", store: &fakeAuditStore{}} + if _, err := m.exportEvents(t.Context(), &exportInput{Limit: 10, Format: "xml"}); err == nil { + t.Fatal("expected error for unsupported export format") + } +} + +type stubAuth struct { + principal governance.Principal +} + +func (a stubAuth) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) { + return governance.WithPrincipal(ctx, a.principal), false, nil +} + +type stubAuthz struct { + allow bool + got string +} + +func (a *stubAuthz) Allow(_ context.Context, action, kind string) error { + a.got = action + ":" + kind + if !a.allow { + return httpapi.ErrDenied + } + return nil +} + +// TestAuditRoutesRequireReadAuditPermission guards Cedar enforcement on the +// audit query and export routes and checks JSONL export output. +func TestAuditRoutesRequireReadAuditPermission(t *testing.T) { + st := &fakeAuditStore{ + rows: []store.EventRow{{ + ID: uuid.MustParse("22222222-2222-2222-2222-222222222222"), + OrgID: "default", + At: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC), + Category: "policy", + Action: "put", + ActorID: "root", + Outcome: "allowed", + Detail: jsontext.Value(`{"id":"p1"}`), + }}, + } + m := &Module{orgID: "default", store: st, log: slog.New(slog.DiscardHandler)} + + authz := &stubAuthz{allow: false} + mux := http.NewServeMux() + api := httpapi.New(mux, "test", stubAuth{principal: governance.SharedTokenOwner()}, authz) + m.Register(api) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit/events", nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("denied status = %d, want 403", rec.Code) + } + if authz.got != string(governance.ActionReadAudit)+":"+string(governance.KindAudit) { + t.Fatalf("checked permission = %q, want %s:%s", authz.got, governance.ActionReadAudit, governance.KindAudit) + } + + authz.allow = true + exportReq := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit/events/export?format=jsonl", nil) + exportRec := httptest.NewRecorder() + mux.ServeHTTP(exportRec, exportReq) + if exportRec.Code != http.StatusOK { + t.Fatalf("export status = %d, want 200 (%s)", exportRec.Code, exportRec.Body.String()) + } + if ct := exportRec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/x-ndjson") { + t.Fatalf("export Content-Type = %q, want application/x-ndjson", ct) + } + if !strings.Contains(exportRec.Body.String(), `"category":"policy"`) { + t.Fatalf("export body missing event: %s", exportRec.Body.String()) + } +} diff --git a/modules/audit/internal/store/store.go b/modules/audit/internal/store/store.go new file mode 100644 index 000000000..5552a6638 --- /dev/null +++ b/modules/audit/internal/store/store.go @@ -0,0 +1,95 @@ +// Package store holds the SQL persistence for append-only audit events. +package store + +import ( + "context" + "encoding/json/jsontext" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// EventRow is one row in audit.events. +type EventRow struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + At time.Time `db:"at"` + Category string `db:"category"` + Action string `db:"action"` + ActorID string `db:"actor_id"` + ActorKind string `db:"actor_kind"` + ResourceKind string `db:"resource_kind"` + ResourceID string `db:"resource_id"` + Outcome string `db:"outcome"` + TraceID string `db:"trace_id"` + Detail jsontext.Value `db:"detail"` +} + +// Filter narrows List queries on audit.events. +type Filter struct { + OrgID string + Category string + Action string + ActorID string + Since time.Time + Until time.Time + Limit int + Offset int +} + +// Store persists and queries audit.events. +type Store struct { + db *sqlx.DB +} + +// New returns a Store backed by db. +func New(db *sqlx.DB) *Store { + return &Store{db: db} +} + +// Insert appends row to audit.events. +func (s *Store) Insert(ctx context.Context, row EventRow) error { + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO audit.events ( + id, org_id, at, category, action, actor_id, actor_kind, + resource_kind, resource_id, outcome, trace_id, detail + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + row.ID, row.OrgID, row.At, row.Category, row.Action, row.ActorID, + row.ActorKind, row.ResourceKind, row.ResourceID, row.Outcome, row.TraceID, row.Detail, + ); err != nil { + return fmt.Errorf("insert audit event: %w", err) + } + return nil +} + +// List returns events matching f ordered newest first. +func (s *Store) List(ctx context.Context, f Filter) ([]EventRow, error) { + var out []EventRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, org_id, at, category, action, actor_id, actor_kind, + resource_kind, resource_id, outcome, trace_id, detail + FROM audit.events + WHERE org_id = $1 + AND ($2 = '' OR category = $2) + AND ($3 = '' OR action = $3) + AND ($4 = '' OR actor_id = $4) + AND ($5::timestamptz IS NULL OR at >= $5) + AND ($6::timestamptz IS NULL OR at < $6) + ORDER BY at DESC, id DESC + LIMIT $7 OFFSET $8`, + f.OrgID, f.Category, f.Action, f.ActorID, + nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset, + ); err != nil { + return nil, fmt.Errorf("list audit events: %w", err) + } + return out, nil +} + +func nullTime(t time.Time) *time.Time { + if t.IsZero() { + return nil + } + return &t +} diff --git a/modules/connectors/rekey.go b/modules/connectors/rekey.go new file mode 100644 index 000000000..2777f1bd4 --- /dev/null +++ b/modules/connectors/rekey.go @@ -0,0 +1,76 @@ +package connectors + +import ( + "bytes" + "context" + "errors" + "fmt" + + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/connectors/internal/store" +) + +// RekeyCredentials decrypts every row in connectors.credentials with oldSealer, +// re-encrypts it under newSealer with the same label binding, verifies the +// round-trip, and updates the row inside tx. +func RekeyCredentials(ctx context.Context, tx *sqlx.Tx, oldSealer, newSealer *seal.Sealer) (int, error) { + if tx == nil { + return 0, errors.New("rekey credentials: transaction is nil") + } + if oldSealer == nil || newSealer == nil { + return 0, errors.New("rekey credentials: both old and new sealers are required") + } + + var rows []store.Credential + if err := tx.SelectContext(ctx, &rows, ` + SELECT id, scope, org_id, person_id, name, kind, sealed + FROM connectors.credentials + ORDER BY id + FOR UPDATE`); err != nil { + return 0, fmt.Errorf("select credentials for rekey: %w", err) + } + + for _, row := range rows { + resealed, err := rekeyCredentialRow(row, oldSealer, newSealer) + if err != nil { + return 0, err + } + if _, err := tx.ExecContext(ctx, ` + UPDATE connectors.credentials + SET sealed = $2, updated_at = now() + WHERE id = $1`, row.ID, resealed); err != nil { + return 0, fmt.Errorf("update credential %s: %w", row.ID, err) + } + } + return len(rows), nil +} + +func rekeyCredentialRow(row store.Credential, oldSealer, newSealer *seal.Sealer) ([]byte, error) { + if oldSealer == nil || newSealer == nil { + return nil, errors.New("rekey credential: both old and new sealers are required") + } + label := credentialLabel(store.Owner{ + Scope: row.Scope, + OrgID: row.OrgID, + PersonID: row.PersonID, + }, row.Name, row.Kind) + + plain, err := oldSealer.Open(label, row.Sealed) + if err != nil { + return nil, fmt.Errorf("open credential %s (%s): %w", row.ID, row.Name, err) + } + resealed, err := newSealer.Seal(label, plain) + if err != nil { + return nil, fmt.Errorf("seal credential %s (%s): %w", row.ID, row.Name, err) + } + verified, err := newSealer.Open(label, resealed) + if err != nil { + return nil, fmt.Errorf("verify resealed credential %s (%s): %w", row.ID, row.Name, err) + } + if !bytes.Equal(verified, plain) { + return nil, fmt.Errorf("verify resealed credential %s (%s): plaintext mismatch", row.ID, row.Name) + } + return resealed, nil +} diff --git a/modules/connectors/rekey_test.go b/modules/connectors/rekey_test.go new file mode 100644 index 000000000..3e9cd1fe3 --- /dev/null +++ b/modules/connectors/rekey_test.go @@ -0,0 +1,114 @@ +package connectors + +import ( + "bytes" + json "encoding/json/v2" + "errors" + "testing" + + "filippo.io/age" + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/connectors/internal/store" +) + +func generateTestSealer(t *testing.T, backups ...string) (*seal.Sealer, *age.X25519Identity) { + t.Helper() + id, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + s, err := seal.New(id.String(), backups) + if err != nil { + t.Fatal(err) + } + return s, id +} + +// TestRekeyCredentialRowRotatesAndPreservesLabelBinding guards credential key +// rotation: re-sealed rows open under the new key (and backup recipient) with +// the original plaintext and label, no longer open under the old key, and refuse +// wrong keys or cross-owner row tampering. +func TestRekeyCredentialRowRotatesAndPreservesLabelBinding(t *testing.T) { + oldSealer, _ := generateTestSealer(t) + _, backupID := generateTestSealer(t) + newSealer, _ := generateTestSealer(t, backupID.Recipient().String()) + backupSealer, err := seal.New(backupID.String(), nil) + if err != nil { + t.Fatal(err) + } + strangerSealer, _ := generateTestSealer(t) + + cases := []struct { + name string + owner store.Owner + cred string + kind string + }{ + {name: "instance bearer", owner: store.Owner{Scope: store.ScopeInstance}, cred: "ops-token", kind: "bearer"}, + {name: "org basic", owner: store.Owner{Scope: store.ScopeOrg, OrgID: "org-1"}, cred: "git-basic", kind: "basic"}, + {name: "person age", owner: store.Owner{Scope: store.ScopePerson, PersonID: "user-1"}, cred: "personal-key", kind: "age"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + plain, err := json.Marshal(map[string]Field{"token": {Value: "plainly-fake-secret-" + tc.cred}}) + if err != nil { + t.Fatal(err) + } + label := credentialLabel(tc.owner, tc.cred, tc.kind) + sealed, err := oldSealer.Seal(label, plain) + if err != nil { + t.Fatal(err) + } + row := store.Credential{ + ID: uuid.New(), + Scope: tc.owner.Scope, + OrgID: tc.owner.OrgID, + PersonID: tc.owner.PersonID, + Name: tc.cred, + Kind: tc.kind, + Sealed: sealed, + } + + resealed, err := rekeyCredentialRow(row, oldSealer, newSealer) + if err != nil { + t.Fatalf("rekeyCredentialRow: %v", err) + } + got, err := newSealer.Open(label, resealed) + if err != nil || !bytes.Equal(got, plain) { + t.Fatalf("open with new sealer: got=%q err=%v", got, err) + } + gotBackup, err := backupSealer.Open(label, resealed) + if err != nil || !bytes.Equal(gotBackup, plain) { + t.Fatalf("open with backup sealer: got=%q err=%v", gotBackup, err) + } + if _, err := oldSealer.Open(label, resealed); err == nil { + t.Fatal("resealed credential still opens with old key") + } + if _, err := rekeyCredentialRow(row, strangerSealer, newSealer); err == nil { + t.Fatal("expected wrong-key refusal") + } + + moved := row + moved.Name = "other-name" + if _, err := rekeyCredentialRow(moved, oldSealer, newSealer); !errors.Is(err, seal.ErrWrongLabel) { + t.Fatalf("expected ErrWrongLabel for moved row, got %v", err) + } + }) + } +} + +func TestRekeyCredentialsGuardsInputs(t *testing.T) { + s, _ := generateTestSealer(t) + if _, err := RekeyCredentials(t.Context(), nil, s, s); err == nil { + t.Fatal("expected error for nil tx") + } + if _, err := rekeyCredentialRow(store.Credential{}, nil, s); err == nil { + t.Fatal("expected error for nil oldSealer") + } + if _, err := rekeyCredentialRow(store.Credential{}, s, nil); err == nil { + t.Fatal("expected error for nil newSealer") + } +} diff --git a/modules/events/rekey.go b/modules/events/rekey.go new file mode 100644 index 000000000..3f7d4cbfc --- /dev/null +++ b/modules/events/rekey.go @@ -0,0 +1,78 @@ +package events + +import ( + "bytes" + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/seal" +) + +type sealedSourceRow struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + HMACSecretSealed []byte `db:"hmac_secret_sealed"` +} + +// RekeySources decrypts every non-empty HMAC signing secret in events.sources +// with oldSealer, re-encrypts it under newSealer with the same label binding, +// verifies the round-trip, and updates the row inside tx. +func RekeySources(ctx context.Context, tx *sqlx.Tx, oldSealer, newSealer *seal.Sealer) (int, error) { + if tx == nil { + return 0, errors.New("rekey sources: transaction is nil") + } + if oldSealer == nil || newSealer == nil { + return 0, errors.New("rekey sources: both old and new sealers are required") + } + + var rows []sealedSourceRow + if err := tx.SelectContext(ctx, &rows, ` + SELECT id, org_id, hmac_secret_sealed + FROM events.sources + WHERE octet_length(hmac_secret_sealed) > 0 + ORDER BY id + FOR UPDATE`); err != nil { + return 0, fmt.Errorf("select sources for rekey: %w", err) + } + + for _, row := range rows { + resealed, err := rekeySourceRow(row, oldSealer, newSealer) + if err != nil { + return 0, err + } + if _, err := tx.ExecContext(ctx, ` + UPDATE events.sources + SET hmac_secret_sealed = $2, updated_at = now() + WHERE id = $1`, row.ID, resealed); err != nil { + return 0, fmt.Errorf("update source %s: %w", row.ID, err) + } + } + return len(rows), nil +} + +func rekeySourceRow(row sealedSourceRow, oldSealer, newSealer *seal.Sealer) ([]byte, error) { + if oldSealer == nil || newSealer == nil { + return nil, errors.New("rekey source: both old and new sealers are required") + } + label := secretLabel(row.OrgID, row.ID) + plain, err := oldSealer.Open(label, row.HMACSecretSealed) + if err != nil { + return nil, fmt.Errorf("open source secret %s: %w", row.ID, err) + } + resealed, err := newSealer.Seal(label, plain) + if err != nil { + return nil, fmt.Errorf("seal source secret %s: %w", row.ID, err) + } + verified, err := newSealer.Open(label, resealed) + if err != nil { + return nil, fmt.Errorf("verify resealed source secret %s: %w", row.ID, err) + } + if !bytes.Equal(verified, plain) { + return nil, fmt.Errorf("verify resealed source secret %s: plaintext mismatch", row.ID) + } + return resealed, nil +} diff --git a/modules/events/rekey_test.go b/modules/events/rekey_test.go new file mode 100644 index 000000000..9ee54c78b --- /dev/null +++ b/modules/events/rekey_test.go @@ -0,0 +1,109 @@ +package events + +import ( + "bytes" + "errors" + "net/http" + "testing" + + "filippo.io/age" + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/modules/events/internal/store" +) + +func generateTestSealer(t *testing.T, backups ...string) (*seal.Sealer, *age.X25519Identity) { + t.Helper() + id, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + s, err := seal.New(id.String(), backups) + if err != nil { + t.Fatal(err) + } + return s, id +} + +// TestRekeySourceRowRotatesAndPreservesHMACVerification guards HMAC secret +// rotation: re-sealed secrets verify webhooks under the new sealer, open under +// backup recipients, fail under the old or stranger key, and reject moved rows. +func TestRekeySourceRowRotatesAndPreservesHMACVerification(t *testing.T) { + oldSealer, _ := generateTestSealer(t) + _, backupID := generateTestSealer(t) + newSealer, _ := generateTestSealer(t, backupID.Recipient().String()) + backupSealer, err := seal.New(backupID.String(), nil) + if err != nil { + t.Fatal(err) + } + strangerSealer, _ := generateTestSealer(t) + + const secret = "plainly-fake-hmac-secret" //nolint:gosec // test fixture signing secret + sourceID := uuid.New() + orgID := "org-1" + label := secretLabel(orgID, sourceID) + sealed, err := oldSealer.Seal(label, []byte(secret)) + if err != nil { + t.Fatal(err) + } + row := sealedSourceRow{ + ID: sourceID, + OrgID: orgID, + HMACSecretSealed: sealed, + } + + resealed, err := rekeySourceRow(row, oldSealer, newSealer) + if err != nil { + t.Fatalf("rekeySourceRow: %v", err) + } + got, err := newSealer.Open(label, resealed) + if err != nil || !bytes.Equal(got, []byte(secret)) { + t.Fatalf("open with new sealer: got=%q err=%v", got, err) + } + gotBackup, err := backupSealer.Open(label, resealed) + if err != nil || !bytes.Equal(gotBackup, []byte(secret)) { + t.Fatalf("open with backup sealer: got=%q err=%v", gotBackup, err) + } + if _, err := oldSealer.Open(label, resealed); err == nil { + t.Fatal("resealed source secret still opens with old key") + } + + // End-to-end HMAC verification check using the re-sealed secret. + m := &Module{sealer: newSealer} + src := store.Source{ + ID: sourceID, + OrgID: orgID, + HMACHeader: "X-Signature", + HMACPrefix: "sha256=", + HMACSecretSealed: resealed, + } + const body = `{"event":"ping"}` + h := http.Header{} + h.Set("X-Signature", "sha256="+sign(secret, body)) + if err := m.verifyHMAC(src, h, []byte(body)); err != nil { + t.Fatalf("verifyHMAC with rekeyed secret: %v", err) + } + + if _, err := rekeySourceRow(row, strangerSealer, newSealer); err == nil { + t.Fatal("expected wrong-key refusal") + } + moved := row + moved.OrgID = "other-org" + if _, err := rekeySourceRow(moved, oldSealer, newSealer); !errors.Is(err, seal.ErrWrongLabel) { + t.Fatalf("expected ErrWrongLabel for moved row, got %v", err) + } +} + +func TestRekeySourcesGuardsInputs(t *testing.T) { + s, _ := generateTestSealer(t) + if _, err := RekeySources(t.Context(), nil, s, s); err == nil { + t.Fatal("expected error for nil tx") + } + if _, err := rekeySourceRow(sealedSourceRow{}, nil, s); err == nil { + t.Fatal("expected error for nil oldSealer") + } + if _, err := rekeySourceRow(sealedSourceRow{}, s, nil); err == nil { + t.Fatal("expected error for nil newSealer") + } +}