From 173f3f47c2b44b75fa8c34c25a7840ce23619ab1 Mon Sep 17 00:00:00 2001 From: Fuming Zhang Date: Thu, 29 Oct 2026 06:58:09 +0000 Subject: [PATCH 1/3] feat(custom): run approved harnesses through common Sandbox Reuse the common executor for governed Custom creation, retained lifecycle, typed Gateway and network controls, private Chat and isolated terminal access. Preserve image entrypoints and non-root identities while retaining existing managed and non-Sandbox behavior.\n\nInclude generated policy schemas, Portal wiring, static probe packaging and offline regression coverage. Keep unsupported identity, mTLS and desktop combinations fail-closed and document the live qualification boundary. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- DEVELOPMENT.md | 18 ++ app/cetirun-chart/README.md | 18 +- .../agents/custom/bootstrap/init-home.sh | 8 +- app/cetirun-chart/templates/_sandbox.tpl | 4 +- .../templates/agents/custom/_runtime.tpl | 4 +- .../templates/agents/custom/_sandbox.tpl | 255 ++++++++++++++++ .../templates/custom-terminal.yaml | 190 +++++++++++- app/cetirun-chart/values.schema.json | 16 +- app/cetirun-operator/Dockerfile.terminal | 3 + app/cetirun-operator/Makefile | 3 +- app/cetirun-operator/README.md | 15 +- .../api/v1alpha1/agentpolicy_schema_test.go | 8 +- .../api/v1alpha1/agentpolicy_types.go | 7 +- .../api/v1alpha1/execution_intent.go | 44 +++ .../api/v1alpha1/lifecycle.go | 6 +- .../cetirun.microsoft.com_agentpolicies.yaml | 8 +- .../cmd/loopback-probe/main.go | 86 ++++++ .../cmd/loopback-probe/main_test.go | 62 ++++ .../cetirun.microsoft.com_agentpolicies.yaml | 8 +- .../internal/admission/pod.go | 5 +- .../internal/admission/terminal.go | 174 +++++++++++ .../internal/controller/agent_controller.go | 269 ++++++++-------- .../internal/controller/ai_gateway.go | 26 +- .../internal/controller/custom_terminal.go | 66 +++- .../internal/controller/migration_test.go | 6 +- .../internal/controller/policy.go | 26 +- .../controller/reconciled_custom_access.go | 106 +++++++ .../internal/controller/sandbox_bootstrap.go | 12 +- .../internal/controller/sandbox_custom.go | 252 +++++++++++++++ .../controller/sandbox_custom_envtest_test.go | 223 ++++++++++++++ .../sandbox_custom_integrations_test.go | 106 +++++++ .../sandbox_custom_terminal_test.go | 239 +++++++++++++++ .../controller/sandbox_custom_test.go | 167 ++++++++++ .../sandbox_home_access_envtest_test.go | 12 +- .../sandbox_kubernetes_prerequisites.go | 7 +- .../sandbox_native_execution_test.go | 5 + .../sandbox_native_start_envtest_test.go | 14 + .../controller/sandbox_preparation.go | 39 +++ .../controller/sandbox_preparation_access.go | 27 ++ .../controller/sandbox_preparation_sources.go | 13 +- .../internal/controller/sandbox_reconcile.go | 75 ++++- .../controller/sandbox_reconcile_test.go | 20 +- .../controller/sandbox_registry_test.go | 4 +- app/cetirun-operator/internal/helm/agent.go | 17 +- app/cetirun-operator/internal/helm/client.go | 7 +- app/cetirun-operator/internal/helm/sandbox.go | 8 +- .../internal/helm/sandbox_custom.go | 40 +++ .../internal/helm/sandbox_custom_test.go | 118 +++++++ .../internal/helm/sandbox_reconcile.go | 17 +- .../internal/helm/sandbox_reconcile_test.go | 2 +- .../internal/helm/sandbox_terminal.go | 127 ++++++++ .../internal/helm/testfixture/pre_proxy.go | 20 +- .../internal/sandbox/capabilities.go | 8 +- .../internal/sandbox/capabilities_test.go | 4 +- .../internal/sandbox/container_test.go | 4 +- .../internal/sandbox/normalize.go | 6 +- .../internal/sandbox/policy_selection.go | 4 +- .../internal/sandbox/resolver_test.go | 4 +- .../internal/sandboxbinding/authorization.go | 4 +- .../internal/sandboxpolicy/compiler.go | 52 +++- .../internal/sandboxpolicy/custom_test.go | 83 +++++ .../internal/sandboxpolicy/network.go | 173 ++++++++++- .../internal/sandboxpolicy/types.go | 26 +- .../internal/sandboxworkload/build.go | 17 +- .../internal/sandboxworkload/contract.go | 5 + .../internal/sandboxworkload/custom.go | 287 ++++++++++++++++++ .../internal/sandboxworkload/finalpod.go | 115 +------ .../internal/sandboxworkload/objects.go | 31 +- .../internal/sandboxworkload/reconcile.go | 45 ++- .../internal/sandboxworkload/sources.go | 28 +- .../sandboxworkload/testfixture/fixture.go | 3 + .../internal/sandboxworkload/values.go | 63 +++- .../chart/templates/chat-rbac.yaml | 31 ++ .../chart/templates/deployment.yaml | 2 + app/cetirun-portal/chart/values.yaml | 2 + app/cetirun-portal/go.mod | 10 + app/cetirun-portal/internal/config/config.go | 2 + .../internal/handler/admin_policy.go | 5 +- .../internal/handler/sandbox_runtime_test.go | 26 ++ app/cetirun-portal/internal/kube/chat.go | 51 +++- .../internal/kube/chat_common.go | 232 ++++++++++++++ .../internal/kube/chat_common_test.go | 184 +++++++++++ app/cetirun-portal/internal/kube/client.go | 10 +- app/cetirun-portal/main.go | 1 + app/cetirun-portal/web/src/api/adminPolicy.ts | 2 +- .../src/pages/admin/PolicyEditPage.test.tsx | 11 + .../web/src/pages/admin/PolicyEditPage.tsx | 11 +- app/internal/podtemplate/podtemplate.go | 150 +++++++++ app/internal/podtemplate/podtemplate_test.go | 77 +++++ scripts/tests/test_custom_initialization.py | 17 ++ scripts/tests/test_portal_chat_chart.py | 20 ++ site/content/en/docs/guides/custom-chat.md | 19 +- site/content/en/docs/guides/lifecycle.md | 27 +- .../en/docs/reference/agent-harness.md | 72 ++++- site/content/en/docs/reference/crds.md | 8 +- 95 files changed, 4498 insertions(+), 446 deletions(-) create mode 100644 app/cetirun-chart/templates/agents/custom/_sandbox.tpl create mode 100644 app/cetirun-operator/api/v1alpha1/execution_intent.go create mode 100644 app/cetirun-operator/cmd/loopback-probe/main.go create mode 100644 app/cetirun-operator/cmd/loopback-probe/main_test.go create mode 100644 app/cetirun-operator/internal/admission/terminal.go create mode 100644 app/cetirun-operator/internal/controller/reconciled_custom_access.go create mode 100644 app/cetirun-operator/internal/controller/sandbox_custom.go create mode 100644 app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go create mode 100644 app/cetirun-operator/internal/controller/sandbox_custom_integrations_test.go create mode 100644 app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go create mode 100644 app/cetirun-operator/internal/controller/sandbox_custom_test.go create mode 100644 app/cetirun-operator/internal/helm/sandbox_custom.go create mode 100644 app/cetirun-operator/internal/helm/sandbox_custom_test.go create mode 100644 app/cetirun-operator/internal/helm/sandbox_terminal.go create mode 100644 app/cetirun-operator/internal/sandboxpolicy/custom_test.go create mode 100644 app/cetirun-operator/internal/sandboxworkload/custom.go create mode 100644 app/cetirun-portal/internal/kube/chat_common.go create mode 100644 app/cetirun-portal/internal/kube/chat_common_test.go create mode 100644 app/internal/podtemplate/podtemplate.go create mode 100644 app/internal/podtemplate/podtemplate_test.go diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 1e240222c..35482fed5 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -138,6 +138,24 @@ node --test app/cetirun-operator/internal/terminal/reconnect.test.cjs make -C app/cetirun-operator build-terminal ``` +The same build target also produces `bin/loopback-probe`, the static HTTP probe +packaged with the terminal image for governed Custom HTTP workloads. Focused +common Custom checks are: + +```bash +go -C app/cetirun-operator test ./cmd/loopback-probe ./internal/helm ./internal/sandboxpolicy ./internal/controller -run 'TestCommonCustom|TestCustomSandbox|TestCompileCustom|TestProbe' -count=1 -timeout=20m +python3 -B -m unittest discover -s scripts/tests -p test_custom_initialization.py -v +KUBEBUILDER_ASSETS=/path/to/local/envtest \ + go -C app/cetirun-operator test -tags=envtest ./internal/controller -run '^TestCommonCustom(Terminal)?APIServer$' -count=1 -timeout=20m +``` + +These cover both registered backends, all three Custom endpoint modes, the +generated policy schema, current source RBAC, final-Pod admission, retained +restart/suspend/resume/migration and isolated terminal authority. API-server +tests use synthetic scheduler/kubelet/Gateway observations, not live model, +tool, Cilium, CSI, identity-provider or image qualification. Run the normal +Portal backend, frontend and chart checks when changing Custom owner access. + Image building is a separate step and can download pinned base images and Go dependencies: diff --git a/app/cetirun-chart/README.md b/app/cetirun-chart/README.md index 498354bca..473abd06b 100644 --- a/app/cetirun-chart/README.md +++ b/app/cetirun-chart/README.md @@ -1,6 +1,6 @@ # CetiRun agent chart -The chart deploys an OpenClaw or Hermes instance. Read the +The chart deploys an OpenClaw, Hermes or approved Custom instance. Read the [Helm configuration reference](../../site/content/en/docs/reference/helm.md) for settings and defaults, and the [local checks guide](../../site/content/en/docs/getting-started/local-checks.md) @@ -33,10 +33,18 @@ original per-Agent overrides **before** merging, then applies the complete protected bundle last. `sandboxWorkload` is an internal chart contract, not a tenant override or a way to enable Sandbox execution. -This path supports OpenClaw and Hermes. It renders zero replicas and the Helm -client refuses to apply the prepared Sandbox release. Governed Custom runtimes -and the separate platform Copilot helper are explicitly unsupported; neither -falls back to an ungoverned runtime. +Common reconciliation supports OpenClaw, Hermes and Gateway-qualified Custom. +The retained preparation-only path still renders zero replicas and does not +authorize execution; Custom requires the common executor and never falls back +to an ungoverned runtime. + +Custom preserves its approved image entrypoint and inherited numeric non-root +identity, reuses the existing HOME claim, and projects immutable canonical +context at its actual HOME. HTTP modes use the static probe packaged in the +approved terminal image; headless mode has no probes. The optional isolated +terminal is separately rendered, resource-bounded and policy-controlled. +See the [governed Custom contract](../../site/content/en/docs/reference/agent-harness.md#policy-governed-custom-execution) +for registration, artifact pins and unsupported combinations. The protected inventory includes: diff --git a/app/cetirun-chart/agents/custom/bootstrap/init-home.sh b/app/cetirun-chart/agents/custom/bootstrap/init-home.sh index c190edbf6..43846616a 100644 --- a/app/cetirun-chart/agents/custom/bootstrap/init-home.sh +++ b/app/cetirun-chart/agents/custom/bootstrap/init-home.sh @@ -22,11 +22,15 @@ agent_check_requirements() { init_error "ImageAgentsPathInvalid" return 1 fi - [ -r "${CETIRUN_CONTEXT_DIR:-/etc/cetirun-context}/AGENTS.md" ] && - [ -r "${CETIRUN_CONTEXT_DIR:-/etc/cetirun-context}/skills/cetirun-memory/SKILL.md" ] || { + [ -r "${CETIRUN_CONTEXT_DIR:-/etc/cetirun-context}/AGENTS.md" ] || { init_error "ContextBindingPending" return 1 } + if [ -z "${CETIRUN_CONTEXT_VIEW:-}" ] && + [ ! -r "${CETIRUN_CONTEXT_DIR:-/etc/cetirun-context}/skills/cetirun-memory/SKILL.md" ]; then + init_error "ContextBindingPending" + return 1 + fi } agent_prepare_home() { diff --git a/app/cetirun-chart/templates/_sandbox.tpl b/app/cetirun-chart/templates/_sandbox.tpl index a966dfd1c..d8cc07222 100644 --- a/app/cetirun-chart/templates/_sandbox.tpl +++ b/app/cetirun-chart/templates/_sandbox.tpl @@ -27,8 +27,8 @@ Licensed under the MIT License. {{- fail "managed ingress mTLS requires common built-in API/UI/terminal/desktop routing without alternate ingress" -}} {{- end -}} {{- end -}} -{{- if eq (include "cetirun.agent.type" .) "custom" -}} -{{- fail "governed Custom rendering is unsupported" -}} +{{- if and (eq (include "cetirun.agent.type" .) "custom") (not $reconciled) -}} +{{- fail "Custom requires common reconciled Sandbox execution" -}} {{- end -}} {{- if or (ne (index .Values.podAnnotations "sidecar.istio.io/inject") "false") .Values.sidecarScope.enabled (not .Values.networkPolicy.enabled) (gt (len .Values.sidecarScope.additionalEgressHosts) 0) -}} {{- fail "Sandbox network controls are protected" -}} diff --git a/app/cetirun-chart/templates/agents/custom/_runtime.tpl b/app/cetirun-chart/templates/agents/custom/_runtime.tpl index 64d55e8ba..39d6ee9d3 100644 --- a/app/cetirun-chart/templates/agents/custom/_runtime.tpl +++ b/app/cetirun-chart/templates/agents/custom/_runtime.tpl @@ -23,7 +23,7 @@ Licensed under the MIT License. {{/* Agent HTTP callers are bound separately; the gateway exposes only platform services. */}} {{- end }} -{{- define "cetirun.custom.validate" -}} +{{- define "cetirun.custom.legacyValidate" -}} {{- if not .Values.runtime -}}{{- fail "Custom requires a platform-prepared runtime plan" -}}{{- end -}} {{- $r := .Values.runtime -}} {{- if or (ne $r.contractVersion "v1") (ne $r.agent.type "custom") -}}{{- fail "Invalid Custom runtime contract" -}}{{- end -}} @@ -57,7 +57,7 @@ podSelector: {{- toYaml .podLabels | nindent 4 }} {{- end }} -{{- define "cetirun.custom.runtime" -}} +{{- define "cetirun.custom.legacyRuntime" -}} {{- include "cetirun.custom.validate" . -}} {{- $r := .Values.runtime -}} {{- $b := $r.bindings -}} diff --git a/app/cetirun-chart/templates/agents/custom/_sandbox.tpl b/app/cetirun-chart/templates/agents/custom/_sandbox.tpl new file mode 100644 index 000000000..4955be8d0 --- /dev/null +++ b/app/cetirun-chart/templates/agents/custom/_sandbox.tpl @@ -0,0 +1,255 @@ +{{/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT License. +*/}} +{{- define "cetirun.custom.runtime" -}} +{{- if .Values.sandboxWorkload -}} +{{- include "cetirun.custom.sandboxRuntime" . -}} +{{- else -}} +{{- include "cetirun.custom.legacyRuntime" . -}} +{{- end -}} +{{- end -}} + +{{- define "cetirun.custom.validate" -}} +{{- if .Values.sandboxWorkload -}} +{{- include "cetirun.custom.sandboxValidate" . -}} +{{- else -}} +{{- include "cetirun.custom.legacyValidate" . -}} +{{- end -}} +{{- end -}} + +{{- define "cetirun.custom.sandboxValidate" -}} +{{- $r := .Values.runtime | default dict -}} +{{- $s := .Values.sandboxWorkload | default dict -}} +{{- if not $s.reconciled -}} +{{- fail "Custom requires common reconciled Sandbox execution" -}} +{{- end -}} +{{- if or (not $r.agent) (not $r.model) $r.bindings $r.planHash -}} +{{- fail "Custom requires the compiler-owned Harness and Gateway contribution" -}} +{{- end -}} +{{- if or (ne $r.agent.type "custom") (not $r.agent.image) (not $r.agent.home) (not $r.model.apiBase) (not $r.model.keySecretName) -}} +{{- fail "Custom requires an approved image, HOME and Gateway binding" -}} +{{- end -}} +{{- if or (not $s.context) (not $s.context.name) (ne (len $s.context.files) 1) (ne (index $s.context.files "AGENTS.md") "AGENTS.md") -}} +{{- fail "Custom requires a controller-owned canonical context" -}} +{{- end -}} +{{- if and $r.http (or (not $r.agent.port) (not $s.loopbackProbe) (not $s.loopbackProbe.image)) -}} +{{- fail "Custom HTTP requires a platform loopback probe image and port" -}} +{{- end -}} +{{- if or .Values.agentIdentity.enabled .Values.connectionsMCP.enabled -}} +{{- fail "Custom Agent Identity and Connections require a qualified credential executor" -}} +{{- end -}} +{{- end -}} + +{{- define "cetirun.custom.sandboxRuntime" -}} +{{- include "cetirun.custom.sandboxValidate" . -}} +{{- $r := .Values.runtime -}} +{{- $s := .Values.sandboxWorkload -}} +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: {{ include "cetirun.fullname" . }} + ownerReferences: + {{- toYaml $s.ownerReferences | nindent 4 }} + labels: + {{- include "cetirun.labels" . | nindent 4 }} + annotations: + {{- toYaml .Values.podAnnotations | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + serviceName: {{ include "cetirun.fullname" . }} + updateStrategy: + type: RollingUpdate + selector: + matchLabels: + {{- include "cetirun.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- include "cetirun.platform.podMetadata" . | nindent 6 }} + spec: + {{- include "cetirun.platform.podSettings" . | nindent 6 }} + initContainers: + {{- include "cetirun.memory.init" . | nindent 8 }} + - name: init-home-data + image: {{ $r.agent.image | quote }} + imagePullPolicy: IfNotPresent + command: ["/bin/sh", "/etc/cetirun/custom-init-home.sh"] + securityContext: + {{- toYaml $s.securityContext | nindent 12 }} + resources: + {{- toYaml $s.helperResources | nindent 12 }} + env: + - name: SOURCE_HOME + value: {{ $r.agent.home | quote }} + - name: TARGET_HOME + value: /home-data + - name: CETIRUN_INIT_IMAGE + value: {{ $r.agent.image | quote }} + - name: CETIRUN_INIT_COMMON + value: /etc/cetirun/init-home-common.sh + - name: CETIRUN_CONTEXT_DIR + value: /etc/cetirun-context + - name: CETIRUN_CONTEXT_VIEW + value: /etc/cetirun-context-view + {{- if .Values.skills.shared }} + - name: CETIRUN_SHARED_SKILLS_DIR + value: /etc/cetirun-shared-skills + {{- end }} + {{- if .Values.memoryContext.enabled }} + - name: CETIRUN_MEMORY_ASSETS + value: /opt/cetirun-memory + {{- end }} + volumeMounts: + - name: data + mountPath: /home-data + - name: config + mountPath: /etc/cetirun + readOnly: true + - name: tmp + mountPath: /tmp + - name: context + mountPath: /etc/cetirun-context + readOnly: true + - name: context-view + mountPath: /etc/cetirun-context-view + {{- if .Values.skills.shared }} + - name: shared-skills + mountPath: /etc/cetirun-shared-skills + readOnly: true + {{- end }} + {{- if .Values.memoryContext.enabled }} + - name: memory-assets + mountPath: /opt/cetirun-memory + readOnly: true + {{- end }} + {{- with $r.http }} + - name: install-loopback-probe + image: {{ $s.loopbackProbe.image | quote }} + imagePullPolicy: IfNotPresent + command: ["/loopback-probe", "install", "/cetirun-probe/http-probe"] + securityContext: + {{- toYaml $s.securityContext | nindent 12 }} + resources: + {{- toYaml $s.helperResources | nindent 12 }} + volumeMounts: + - name: loopback-probe + mountPath: /cetirun-probe + {{- end }} + containers: + - name: {{ .Chart.Name }} + image: {{ $r.agent.image | quote }} + imagePullPolicy: IfNotPresent + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + env: + {{- range $r.environment }} + - name: {{ .name }} + {{- if .credentialSlot }} + {{- if ne .credentialSlot "model" }}{{- fail "Unknown Custom credential slot" }}{{- end }} + valueFrom: + secretKeyRef: + name: {{ $r.model.keySecretName | quote }} + key: {{ $r.model.keySecretKey | quote }} + {{- else }} + value: {{ .value | quote }} + {{- end }} + {{- end }} + {{- include "cetirun.memory.env" . | nindent 12 }} + {{- with $s.identityEnvironment }} + {{- toYaml . | nindent 12 }} + {{- end }} + {{- if $r.ports }} + ports: + {{- range $r.ports }} + - name: {{ .name | quote }} + containerPort: {{ .number }} + protocol: TCP + {{- end }} + {{- end }} + {{- with $r.http }} + startupProbe: + exec: + command: ["/cetirun-probe/http-probe", "--url", {{ printf "http://127.0.0.1:%v%s" $r.agent.port .startupPath | quote }}] + periodSeconds: 5 + timeoutSeconds: 3 + failureThreshold: 60 + readinessProbe: + exec: + command: ["/cetirun-probe/http-probe", "--url", {{ printf "http://127.0.0.1:%v%s" $r.agent.port .healthPath | quote }}] + periodSeconds: 10 + timeoutSeconds: 3 + {{- end }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumeMounts: + - name: data + mountPath: {{ $r.agent.home | quote }} + - name: tmp + mountPath: /tmp + - name: config + mountPath: /etc/cetirun + readOnly: true + {{- with $s.identityMounts }} + {{- toYaml . | nindent 12 }} + {{- end }} + - name: context-view + mountPath: {{ printf "%s/.agents" $r.agent.home | quote }} + subPath: current + readOnly: true + {{- with $r.http }} + - name: loopback-probe + mountPath: /cetirun-probe + readOnly: true + {{- end }} + {{- include "cetirun.memory.mounts" . | nindent 12 }} + volumes: + - name: config + configMap: + name: {{ include "cetirun.configMapName" . }} + defaultMode: 0444 + - name: data + persistentVolumeClaim: + claimName: {{ .Values.persistence.existingClaim | quote }} + - name: context + configMap: + name: {{ $s.context.name | quote }} + defaultMode: 0444 + items: + - key: AGENTS.md + path: AGENTS.md + - name: context-view + emptyDir: + sizeLimit: {{ $s.scratchSizeLimit | quote }} + {{- with $r.http }} + - name: loopback-probe + emptyDir: + sizeLimit: {{ $s.scratchSizeLimit | quote }} + {{- end }} + {{- include "cetirun.platform.temporaryVolumes" . | nindent 8 }} + {{- if .Values.skills.shared }} + - name: shared-skills + persistentVolumeClaim: + claimName: {{ .Values.skills.existingClaim | quote }} + readOnly: true + {{- end }} + {{- include "cetirun.memory.volumes" . | nindent 8 }} + {{- with $s.identityVolumes }} + {{- toYaml . | nindent 8 }} + {{- end }} +{{- if and (not $r.ports) (not .Values.desktop.enabled) }} +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ include "cetirun.fullname" . }} + ownerReferences: + {{- toYaml $s.ownerReferences | nindent 4 }} + labels: + {{- include "cetirun.labels" . | nindent 4 }} +spec: + type: ClusterIP + clusterIP: None + selector: + {{- include "cetirun.selectorLabels" . | nindent 4 }} +{{- end }} +{{- end }} diff --git a/app/cetirun-chart/templates/custom-terminal.yaml b/app/cetirun-chart/templates/custom-terminal.yaml index 990ac1467..9bdadc27b 100644 --- a/app/cetirun-chart/templates/custom-terminal.yaml +++ b/app/cetirun-chart/templates/custom-terminal.yaml @@ -5,7 +5,195 @@ Licensed under the MIT License. The Operator supplies typed, validated platform resources. Custom images do not supply these objects and cannot override their permissions or targets. */ -}} -{{- if and (eq (include "cetirun.agent.type" .) "custom") .Values.ttyd.enabled }} +{{- if and (eq (include "cetirun.agent.type" .) "custom") .Values.sandboxWorkload }} +{{- $s := .Values.sandboxWorkload }} +{{- $terminal := $s.terminal | default dict }} +{{- if $terminal.enabled }} +{{- $labels := dict "app.kubernetes.io/name" "cetirun-terminal" "app.kubernetes.io/instance" .Release.Name "cetirun.microsoft.com/terminal" "true" "sandbox.cetirun.microsoft.com/agent-uid" (index $s.podLabels "sandbox.cetirun.microsoft.com/agent-uid") }} +{{- $owner := $s.ownerReferences }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $terminal.serviceAccountName }} + ownerReferences: + {{- toYaml $owner | nindent 4 }} + labels: + {{- toYaml $labels | nindent 4 }} +automountServiceAccountToken: false +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $terminal.serviceAccountName }} + ownerReferences: + {{- toYaml $owner | nindent 4 }} + labels: + {{- toYaml $labels | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ $terminal.serviceAccountName }} + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $terminal.serviceAccountName }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $terminal.serviceAccountName }}-exec + ownerReferences: + {{- toYaml $owner | nindent 4 }} + labels: + {{- toYaml $labels | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ $terminal.serviceAccountName }} + namespace: {{ .Release.Namespace }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cetirun-terminal-exec +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $terminal.serviceAccountName }} + ownerReferences: + {{- toYaml $owner | nindent 4 }} + labels: + {{- toYaml $labels | nindent 4 }} +spec: + type: ClusterIP + ports: + - name: terminal + port: {{ $terminal.port }} + targetPort: terminal + protocol: TCP + selector: + {{- toYaml $labels | nindent 4 }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $terminal.serviceAccountName }} + ownerReferences: + {{- toYaml $owner | nindent 4 }} + labels: + {{- toYaml $labels | nindent 4 }} +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + {{- toYaml $labels | nindent 6 }} + template: + metadata: + annotations: + sidecar.istio.io/inject: "false" + labels: + {{- toYaml $labels | nindent 8 }} + spec: + {{- if .Values.runtimeClassName }} + runtimeClassName: {{ .Values.runtimeClassName | quote }} + {{- end }} + enableServiceLinks: false + automountServiceAccountToken: false + dnsPolicy: None + dnsConfig: + {{- toYaml $s.dnsConfig | nindent 8 }} + serviceAccountName: {{ $terminal.serviceAccountName }} + securityContext: + runAsUser: 65532 + runAsGroup: 65532 + runAsNonRoot: true + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + {{- include "cetirun.platform.scheduling" . | nindent 6 }} + containers: + - name: terminal + image: {{ $terminal.image | quote }} + imagePullPolicy: IfNotPresent + command: ["/terminal"] + args: ["serve"] + ports: + - name: terminal + containerPort: {{ $terminal.port }} + protocol: TCP + env: + - name: PORT + value: {{ $terminal.port | quote }} + - name: CETIRUN_TERMINAL_AGENT_NAME + value: {{ (index $owner 0).name | quote }} + - name: CETIRUN_TERMINAL_AGENT_UID + value: {{ (index $owner 0).uid | quote }} + - name: CETIRUN_TERMINAL_NAMESPACE + value: {{ .Release.Namespace | quote }} + - name: CETIRUN_TERMINAL_STATEFULSET + value: {{ include "cetirun.fullname" . | quote }} + - name: CETIRUN_TERMINAL_CONTAINER + value: {{ .Chart.Name | quote }} + - name: CETIRUN_TERMINAL_SESSION_SECONDS + value: {{ $terminal.sessionSeconds | quote }} + securityContext: + runAsUser: 65532 + runAsGroup: 65532 + runAsNonRoot: true + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + seccompProfile: + type: RuntimeDefault + resources: + {{- toYaml $s.helperResources | nindent 12 }} + readinessProbe: + httpGet: + path: /healthz + port: terminal + periodSeconds: 5 + timeoutSeconds: 2 + failureThreshold: 3 + livenessProbe: + httpGet: + path: /livez + port: terminal + periodSeconds: 5 + timeoutSeconds: 2 + failureThreshold: 3 + volumeMounts: + - name: tmp + mountPath: /tmp + - name: api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + volumes: + - name: tmp + emptyDir: + sizeLimit: {{ $s.scratchSizeLimit | quote }} + - name: api-access + projected: + defaultMode: 288 + sources: + - serviceAccountToken: + path: token + expirationSeconds: 3600 + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + apiVersion: v1 + fieldPath: metadata.namespace +{{- end }} +{{- else if and (eq (include "cetirun.agent.type" .) "custom") .Values.ttyd.enabled }} {{- if not .Values.runtime.terminalResources }} {{- fail "Custom terminal requires a platform-prepared terminal plan" }} {{- end }} diff --git a/app/cetirun-chart/values.schema.json b/app/cetirun-chart/values.schema.json index 40ae27ab8..afb435292 100644 --- a/app/cetirun-chart/values.schema.json +++ b/app/cetirun-chart/values.schema.json @@ -22,6 +22,20 @@ "contractVersion": {"const": "v1"}, "executionHeld": {"type": "boolean"}, "reconciled": {"const": true}, + "context": { + "type": "object", "additionalProperties": false, + "properties": {"name": {"type": "string", "minLength": 1}, "files": {"type": "object", "additionalProperties": false, "properties": {"AGENTS.md": {"const": "AGENTS.md"}}, "required": ["AGENTS.md"]}}, + "required": ["name", "files"] + }, + "loopbackProbe": { + "type": "object", "additionalProperties": false, + "properties": {"image": {"type": "string", "pattern": "^[^\\s@]+@sha256:[a-f0-9]{64}$"}}, "required": ["image"] + }, + "terminal": { + "type": "object", "additionalProperties": false, + "properties": {"enabled": {"type": "boolean"}, "image": {"type": "string", "pattern": "^[^\\s@]+@sha256:[a-f0-9]{64}$"}, "port": {"type": "integer", "minimum": 1024, "maximum": 65535}, "sessionSeconds": {"type": "integer", "minimum": 60, "maximum": 3600}, "serviceAccountName": {"type": "string", "minLength": 1}}, + "required": ["enabled", "image", "port", "sessionSeconds", "serviceAccountName"] + }, "ingressMTLS": {"const": true, "description": "Internal common-executor managed Envoy endpoint; absent for ordinary ingress"}, "skillsMode": { "const": "empty", @@ -1639,7 +1653,7 @@ }, "then": { "properties": { - "agentType": {"enum": ["openclaw", "hermes"]}, + "agentType": {"enum": ["openclaw", "hermes", "custom"]}, "aiGateway": { "properties": {"enabled": {"const": true}}, "required": ["enabled"] diff --git a/app/cetirun-operator/Dockerfile.terminal b/app/cetirun-operator/Dockerfile.terminal index be9d31c76..bbd3d414f 100644 --- a/app/cetirun-operator/Dockerfile.terminal +++ b/app/cetirun-operator/Dockerfile.terminal @@ -17,6 +17,8 @@ COPY app/cetirun-operator/ . COPY app/internal/ ../internal/ RUN CGO_ENABLED=0 GOOS="${TARGETOS}" GOARCH="${TARGETARCH}" \ go build -trimpath -o /terminal ./cmd/terminal +RUN CGO_ENABLED=0 GOOS="${TARGETOS}" GOARCH="${TARGETARCH}" \ + go build -trimpath -o /loopback-probe ./cmd/loopback-probe ARG TTYD_VERSION=1.7.7 ARG TTYD_SHA256_AMD64=8a217c968aba172e0dbf3f34447218dc015bc4d5e59bf51db2f2cd12b7be4f55 @@ -39,6 +41,7 @@ LABEL org.opencontainers.image.source="https://github.com/Azure/CetiRun" \ org.opencontainers.image.revision="${GIT_SHA}" \ org.opencontainers.image.licenses="MIT" COPY --from=builder /terminal /terminal +COPY --from=builder /loopback-probe /loopback-probe COPY --from=builder /ttyd /ttyd COPY app/cetirun-operator/third_party/ttyd.LICENSE /licenses/ttyd.LICENSE USER 65532:65532 diff --git a/app/cetirun-operator/Makefile b/app/cetirun-operator/Makefile index 259a5f5d2..fcac08ebb 100644 --- a/app/cetirun-operator/Makefile +++ b/app/cetirun-operator/Makefile @@ -33,9 +33,10 @@ all: build build: CGO_ENABLED=$(CGO_ENABLED) go build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o bin/manager ./cmd/main.go -## Build the independent Custom terminal entrypoint +## Build the independent Custom terminal and static HTTP probe build-terminal: CGO_ENABLED=$(CGO_ENABLED) go build $(GOFLAGS) -o bin/terminal ./cmd/terminal + CGO_ENABLED=$(CGO_ENABLED) go build $(GOFLAGS) -o bin/loopback-probe ./cmd/loopback-probe ## Build the standalone opt-in node guard prototype; not part of operator startup build-node-guard: diff --git a/app/cetirun-operator/README.md b/app/cetirun-operator/README.md index ae5f93958..5cc325ca1 100644 --- a/app/cetirun-operator/README.md +++ b/app/cetirun-operator/README.md @@ -316,8 +316,8 @@ and their cleanup; it does not remove an existing destination pin. This scope requires one bound filesystem CSI `ReadWriteOncePod` or `ReadWriteOnce` HOME, with no other PVC mounts, a CSI driver that requires attachment, and a healthy source on a different Node. It preserves Agent, namespace, StatefulSet, HOME -PVC/PV, chart pin, Gateway key and spending identities. It does not support -Custom or retained single-start lifetimes, shared-volume migration, +PVC/PV, chart pin, Gateway key and spending identities. Governed Custom uses +the same common migration path. It does not support retained single-start lifetimes, shared-volume migration, cross-cluster moves, forced deletion/detach, or unavailable-source recovery. Use an explicitly authorized environment and qualify the actual runtime/CSI artifact set before enabling this feature. @@ -1053,7 +1053,8 @@ Setting any Team policy/Sandbox field opts that Team into the full binding contract: one policy, permitted Sandboxes, and a creation default. Partial configuration is not a legacy fallback. Policy-bound Agents must explicitly request model sources. They require a permitted Sandbox and current -authorization, and Custom remains unsupported in that policy contract. +authorization. Custom requires the common executor and an explicitly +Gateway-qualified image; see the [Custom contract](../../site/content/en/docs/reference/agent-harness.md#policy-governed-custom-execution). Portal creation accepts legacy Teams without a default Sandbox. With the Gateway disabled, it also accepts no Team, as before. With the Gateway enabled, it still requires an existing Team and supported model routing. Portal support @@ -1286,7 +1287,8 @@ The preparation chain is `sandboxbinding.Read` -> `sandbox.Resolve` -> Hermes; it does not introduce another runtime renderer. Generic user values are validated before merging, and the protected bundle is applied last. The `sandboxWorkload` chart values are compiler-owned outputs, not a user activation -switch. Policy-bound Custom rendering is explicitly unsupported by this slice. +switch. Custom joins the common reconciled renderer; the retained held-only +preparation path does not support Custom. Prepared manifests protect resource accounting (including init/helper containers and RuntimeClass overhead), runtime/security settings, owned HOME, read-only @@ -1427,8 +1429,9 @@ pool isolation, qualified old-writer fencing, a distinct pre-start enforcement acknowledgement and trusted current Pod/node/epoch observations. Neither a held expectation nor pool deletion alone supplies those authorities. -Tailscale, Teams, workload identity and policy-bound Custom configurations remain -unsupported by this native path. They retain an explanatory `UnsupportedControl` +Tailscale, Teams and workload identity remain unsupported by this native path. +Custom requires common reconciliation rather than retained single-start execution. +Unsupported requests retain an explanatory `UnsupportedControl` hold and bounded requeue instead of a permanent preparation-error loop. Existing grants are revoked if a previously prepared Agent transitions to one of them. Unqualified platform controls also retain the bounded `UnsupportedControl` diff --git a/app/cetirun-operator/api/v1alpha1/agentpolicy_schema_test.go b/app/cetirun-operator/api/v1alpha1/agentpolicy_schema_test.go index 7b4b72dd3..68c7f3064 100644 --- a/app/cetirun-operator/api/v1alpha1/agentpolicy_schema_test.go +++ b/app/cetirun-operator/api/v1alpha1/agentpolicy_schema_test.go @@ -16,8 +16,7 @@ import ( "sigs.k8s.io/yaml" ) -// Validate the generated schemas, rather than the Go markers: flattening a -// shared enum previously admitted Custom policies despite their item marker. +// Validate the generated schemas rather than only the Go markers. func TestGeneratedPolicyHarnessSchema(t *testing.T) { for _, directory := range []string{"config/crd/bases", "chart/templates/crds"} { t.Run(directory, func(t *testing.T) { @@ -30,8 +29,9 @@ func TestGeneratedPolicyHarnessSchema(t *testing.T) { {"openclaw", []any{"openclaw"}, true}, {"hermes", []any{"hermes"}, true}, {"both", []any{"openclaw", "hermes"}, true}, - {"custom", []any{"custom"}, false}, - {"mixed custom", []any{"hermes", "custom"}, false}, + {"custom", []any{"custom"}, true}, + {"mixed custom", []any{"hermes", "custom"}, true}, + {"unknown", []any{"unknown"}, false}, {"empty", []any{}, false}, } { t.Run(test.name, func(t *testing.T) { diff --git a/app/cetirun-operator/api/v1alpha1/agentpolicy_types.go b/app/cetirun-operator/api/v1alpha1/agentpolicy_types.go index 66647f098..3c3b79d31 100644 --- a/app/cetirun-operator/api/v1alpha1/agentpolicy_types.go +++ b/app/cetirun-operator/api/v1alpha1/agentpolicy_types.go @@ -51,11 +51,8 @@ type AgentPolicySpec struct { type AgentPolicyHarnesses struct { // +kubebuilder:validation:MinItems=1 - // Policy has typed Gateway and Sandbox enforcement adapters only for - // the built-in harnesses. Custom workloads cannot be granted a policy. - // Keep the enum on each field: a type-level AgentType enum overrides the - // narrower item enum when controller-gen flattens the schema. - // +kubebuilder:validation:items:Enum=openclaw;hermes + // Custom execution additionally requires an approved Gateway-qualified image. + // +kubebuilder:validation:items:Enum=openclaw;hermes;custom // +listType=set Allowed []AgentType `json:"allowed"` } diff --git a/app/cetirun-operator/api/v1alpha1/execution_intent.go b/app/cetirun-operator/api/v1alpha1/execution_intent.go new file mode 100644 index 000000000..b966b714b --- /dev/null +++ b/app/cetirun-operator/api/v1alpha1/execution_intent.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package v1alpha1 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "slices" +) + +// SandboxExecutionIntentDigest binds the complete spec and execution-affecting +// metadata, excluding status churn. It does not authorize the captured intent. +func (a *Agent) SandboxExecutionIntentDigest() (string, error) { + if a == nil { + return "", fmt.Errorf("Sandbox Agent intent requires an Agent") + } + annotations := make(map[string]string, 2) + for _, key := range []string{AnnotationSandboxAuthorization, AnnotationSandboxReauthorize} { + if value, found := a.Annotations[key]; found { + annotations[key] = value + } + } + intent := struct { + Spec AgentSpec + Annotations map[string]string + Held bool + Prepared bool + Bootstrapped bool `json:",omitempty"` + }{ + Spec: a.Spec, Annotations: annotations, + Held: slices.Contains(a.Finalizers, SandboxHoldFinalizer), + Prepared: slices.Contains(a.Finalizers, SandboxPreparationFinalizer), + Bootstrapped: slices.Contains(a.Finalizers, SandboxBootstrapFinalizer), + } + raw, err := json.Marshal(intent) + if err != nil { + return "", fmt.Errorf("encode Sandbox Agent intent: %w", err) + } + digest := sha256.Sum256(raw) + return hex.EncodeToString(digest[:]), nil +} diff --git a/app/cetirun-operator/api/v1alpha1/lifecycle.go b/app/cetirun-operator/api/v1alpha1/lifecycle.go index c816a674e..fffd0c82b 100644 --- a/app/cetirun-operator/api/v1alpha1/lifecycle.go +++ b/app/cetirun-operator/api/v1alpha1/lifecycle.go @@ -8,7 +8,11 @@ import "regexp" const ( AnnotationRestartRequestID = "cetirun.microsoft.com/restart-request-id" // SandboxPreparationFinalizer identifies retained single-start lifetimes. - SandboxPreparationFinalizer = "cetirun.microsoft.com/sandbox-preparation" + SandboxPreparationFinalizer = "cetirun.microsoft.com/sandbox-preparation" + SandboxHoldFinalizer = "cetirun.microsoft.com/sandbox-hold" + SandboxBootstrapFinalizer = "cetirun.microsoft.com/sandbox-bootstrap" + AnnotationSandboxAuthorization = "cetirun.microsoft.com/sandbox-authorization" + AnnotationSandboxReauthorize = "cetirun.microsoft.com/sandbox-reauthorize" ) var restartRequestIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`) diff --git a/app/cetirun-operator/chart/templates/crds/cetirun.microsoft.com_agentpolicies.yaml b/app/cetirun-operator/chart/templates/crds/cetirun.microsoft.com_agentpolicies.yaml index ebf0d241e..700166c40 100644 --- a/app/cetirun-operator/chart/templates/crds/cetirun.microsoft.com_agentpolicies.yaml +++ b/app/cetirun-operator/chart/templates/crds/cetirun.microsoft.com_agentpolicies.yaml @@ -80,17 +80,15 @@ spec: description: Harnesses limits runtimes that can receive this policy. properties: allowed: - description: |- - Policy has typed Gateway and Sandbox enforcement adapters only for - the built-in harnesses. Custom workloads cannot be granted a policy. - Keep the enum on each field: a type-level AgentType enum overrides the - narrower item enum when controller-gen flattens the schema. + description: Custom execution additionally requires an approved + Gateway-qualified image. items: description: AgentType identifies a built-in integration or a user-supplied image. enum: - openclaw - hermes + - custom type: string minItems: 1 type: array diff --git a/app/cetirun-operator/cmd/loopback-probe/main.go b/app/cetirun-operator/cmd/loopback-probe/main.go new file mode 100644 index 000000000..adb1d9fea --- /dev/null +++ b/app/cetirun-operator/cmd/loopback-probe/main.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +const probeDestination = "/cetirun-probe/http-probe" + +func install(destination string) error { + if destination != probeDestination { + return errors.New("probe install destination is invalid") + } + source, err := os.Open(os.Args[0]) + if err != nil { + return err + } + defer source.Close() + target, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) + if err != nil { + return err + } + _, copyErr := io.Copy(target, source) + return errors.Join(copyErr, target.Close()) +} + +func probe(rawURL string) error { + u, err := url.Parse(rawURL) + if err != nil || u == nil { + return errors.New("probe URL must be an HTTP numeric loopback endpoint") + } + port, portErr := strconv.ParseUint(u.Port(), 10, 16) + if portErr != nil || port == 0 || u.Scheme != "http" || u.User != nil || u.Hostname() != "127.0.0.1" || + !strings.HasPrefix(u.EscapedPath(), "/") || u.RawQuery != "" || u.Fragment != "" { + return errors.New("probe URL must be an HTTP numeric loopback endpoint") + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return err + } + client := &http.Client{Timeout: 2 * time.Second, Transport: &http.Transport{Proxy: nil}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, err := client.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices { + return fmt.Errorf("loopback health endpoint returned status %d", response.StatusCode) + } + return nil +} + +func run(arguments []string) error { + if len(arguments) == 2 && arguments[0] == "install" { + return install(arguments[1]) + } + flags := flag.NewFlagSet("loopback-probe", flag.ContinueOnError) + flags.SetOutput(io.Discard) + endpoint := flags.String("url", "", "") + if err := flags.Parse(arguments); err != nil || *endpoint == "" || flags.NArg() != 0 { + return errors.New("usage: http-probe --url http://127.0.0.1:PORT/PATH") + } + return probe(*endpoint) +} + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/app/cetirun-operator/cmd/loopback-probe/main_test.go b/app/cetirun-operator/cmd/loopback-probe/main_test.go new file mode 100644 index 000000000..b68251911 --- /dev/null +++ b/app/cetirun-operator/cmd/loopback-probe/main_test.go @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package main + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +func TestProbeAcceptsOnlySuccessfulNumericLoopbackHTTP(t *testing.T) { + var redirected atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + redirected.Add(1) + })) + defer target.Close() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/bad": + w.WriteHeader(http.StatusServiceUnavailable) + case "/redirect": + http.Redirect(w, r, target.URL, http.StatusFound) + case "/slow": + time.Sleep(3 * time.Second) + default: + w.WriteHeader(http.StatusNoContent) + } + })) + defer server.Close() + if err := probe(server.URL + "/healthz"); err != nil { + t.Fatal(err) + } + for _, path := range []string{"/bad", "/redirect", "/slow"} { + if err := probe(server.URL + path); err == nil { + t.Fatalf("accepted failed health endpoint %s", path) + } + } + if redirected.Load() != 0 { + t.Fatal("followed a redirect beyond the original loopback endpoint") + } + for _, endpoint := range []string{ + "https://127.0.0.1:8080/healthz", "http://localhost:8080/healthz", "http://example.test:8080/healthz", + "http://127.0.0.1/healthz", "http://127.0.0.1:0/healthz", "http://127.0.0.1:65536/healthz", + "http://127.0.0.1:18446744073709551616/healthz", "http://127.0.0.1:8080/healthz?query", + "http://user@127.0.0.1:8080/healthz", "http://127.0.0.1:8080/healthz#fragment", "http://[bad", + } { + if err := probe(endpoint); err == nil { + t.Fatalf("accepted invalid probe endpoint %q", endpoint) + } + } +} + +func TestProbeCommandRejectsUnexpectedArgumentsAndDestinations(t *testing.T) { + for _, arguments := range [][]string{nil, {"--url"}, {"install", "/tmp/other"}, {"--url", "http://127.0.0.1:8080/healthz", "extra"}} { + if err := run(arguments); err == nil { + t.Fatalf("accepted invalid probe invocation %v", arguments) + } + } +} diff --git a/app/cetirun-operator/config/crd/bases/cetirun.microsoft.com_agentpolicies.yaml b/app/cetirun-operator/config/crd/bases/cetirun.microsoft.com_agentpolicies.yaml index ebf0d241e..700166c40 100644 --- a/app/cetirun-operator/config/crd/bases/cetirun.microsoft.com_agentpolicies.yaml +++ b/app/cetirun-operator/config/crd/bases/cetirun.microsoft.com_agentpolicies.yaml @@ -80,17 +80,15 @@ spec: description: Harnesses limits runtimes that can receive this policy. properties: allowed: - description: |- - Policy has typed Gateway and Sandbox enforcement adapters only for - the built-in harnesses. Custom workloads cannot be granted a policy. - Keep the enum on each field: a type-level AgentType enum overrides the - narrower item enum when controller-gen flattens the schema. + description: Custom execution additionally requires an approved + Gateway-qualified image. items: description: AgentType identifies a built-in integration or a user-supplied image. enum: - openclaw - hermes + - custom type: string minItems: 1 type: array diff --git a/app/cetirun-operator/internal/admission/pod.go b/app/cetirun-operator/internal/admission/pod.go index 8b195169a..15425f8fd 100644 --- a/app/cetirun-operator/internal/admission/pod.go +++ b/app/cetirun-operator/internal/admission/pod.go @@ -131,8 +131,9 @@ func (h *PodHandler) Validate(ctx context.Context, request admission.Request) ad } if request.Resource.Group == "" && request.Resource.Resource == "pods" && request.Resource.Version == "v1" && request.Operation == admissionv1.Connect && slices.Contains([]string{"exec", "attach", "portforward"}, request.SubResource) { - // CONNECT carries an options object, not a Pod. It must not depend on - // workload expectations or inherit a controller/administrator exemption. + if request.SubResource == "exec" && terminalConnectPreflight(request) { + return h.validateTerminalConnect(ctx, request) + } return rejectPod(ctx, request, podDenied("ConnectForbidden", "interactive access to protected Pods is not supported")) } if request.Resource.Group != "" || request.Resource.Resource != "pods" || request.Resource.Version != "v1" || diff --git a/app/cetirun-operator/internal/admission/terminal.go b/app/cetirun-operator/internal/admission/terminal.go new file mode 100644 index 000000000..c53d9628c --- /dev/null +++ b/app/cetirun-operator/internal/admission/terminal.go @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sandboxadmission + +import ( + "context" + "encoding/json" + "errors" + "slices" + "strings" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandbox" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxbinding" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxcoordination" + w "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" + "github.com/Azure/CetiRun/app/internal/terminalpolicy" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// Reject unrelated callers before any authoritative API reads. +func terminalConnectPreflight(request admission.Request) bool { + workload, matched := strings.CutSuffix(request.Name, "-0") + if request.Namespace == "" || !matched || workload == "" || + (request.RequestSubResource != "" && request.RequestSubResource != "exec") || + request.UserInfo.Username != "system:serviceaccount:"+request.Namespace+":"+terminalpolicy.WorkloadName(workload) { + return false + } + var options corev1.PodExecOptions + return json.Unmarshal(request.Object.Raw, &options) == nil && options.Container == "cetirun" && terminalCommandPermitted(options) +} + +func terminalCommandPermitted(options corev1.PodExecOptions) bool { + if !options.Stdout { + return false + } + for _, candidate := range terminalpolicy.ShellCandidates() { + if slices.Equal(options.Command, candidate.Probe) { + return !options.Stdin && !options.TTY + } + command, err := terminalpolicy.ShellCommand(candidate.Name) + if err == nil && slices.Equal(options.Command, command) { + return options.Stdin && options.TTY + } + } + return false +} + +func (h *PodHandler) validateTerminalConnect(ctx context.Context, request admission.Request) admission.Response { + ctx, cancel := context.WithTimeout(ctx, h.config.RequestTimeout) + defer cancel() + deny := func(reason, message string) admission.Response { + return rejectPod(ctx, request, podDenied(reason, message)) + } + expected, state, handled, failure := h.reconciledExpectation(ctx, request.Namespace) + if failure != nil { + return rejectPod(ctx, request, failure) + } + if !handled || expected.Terminal == nil { + return deny("TerminalUnavailable", "terminal access is unavailable for this Sandbox") + } + terminal := expected.Terminal + if terminal.ServiceAccountName != terminalpolicy.WorkloadName(terminal.TargetWorkload) || + request.UserInfo.Username != "system:serviceaccount:"+request.Namespace+":"+terminal.ServiceAccountName || + request.Name != terminal.TargetWorkload+"-0" { + return deny("TerminalIdentityUnauthorized", "terminal caller or target differs from the current Sandbox plan") + } + var options corev1.PodExecOptions + if err := json.Unmarshal(request.Object.Raw, &options); err != nil || options.Container != terminal.Container || + !terminalCommandPermitted(options) { + return deny("TerminalCommandUnauthorized", "terminal exec command differs from the approved shell protocol") + } + agent, binding, err := sandboxbinding.Read(ctx, h.reader, client.ObjectKey{Name: expected.Agent.Name}) + if err != nil || agent.UID != expected.Agent.UID || agent.Generation != expected.AgentGeneration || binding != expected.Binding || + agent.Spec.Agent.Type != api.AgentTypeCustom || agent.Spec.Suspended || !agent.DeletionTimestamp.IsZero() || + slices.Contains(agent.Finalizers, sandbox.HoldFinalizer) { + return deny("BindingUnauthorized", "terminal binding or lifecycle state is not current") + } + if failure := h.validateReconciledSources(ctx, expected); failure != nil { + return rejectPod(ctx, request, failure) + } + checkReservation := func() *podFailure { + if h.coordination == nil { + return nil + } + intent, err := sandboxcoordination.ReconciledIntentFor(expected) + if err != nil { + return podDenied("NativeReservationRequired", "terminal requires the current Sandbox reservation") + } + if err := h.coordination.AuthorizeNativeStart(ctx, intent); err != nil { + if errors.Is(err, sandboxcoordination.ErrConflict) { + return podDenied("NativeReservationRequired", "terminal requires the current non-stopping Sandbox reservation") + } + return podReadFailure("NativeReservation", err) + } + return nil + } + if failure := checkReservation(); failure != nil { + return rejectPod(ctx, request, failure) + } + if failure := h.validateTerminalAuthority(ctx, expected, agent); failure != nil { + return rejectPod(ctx, request, failure) + } + confirmed := &corev1.ConfigMap{} + if err := h.reader.Get(ctx, client.ObjectKeyFromObject(state), confirmed); err != nil { + return rejectPod(ctx, request, podReadFailure("Expectation", err)) + } + if confirmed.UID != state.UID || confirmed.ResourceVersion != state.ResourceVersion { + return deny("ExpectationChanged", "terminal expectation changed during authorization") + } + if failure := h.validateReconciledSources(ctx, expected); failure != nil { + return rejectPod(ctx, request, failure) + } + if ctx.Err() != nil { + return rejectPod(ctx, request, podReadFailure("Expectation", ctx.Err())) + } + // A lifecycle stop may have fenced the reservation during the API reads. + if failure := checkReservation(); failure != nil { + return rejectPod(ctx, request, failure) + } + return admission.Allowed("terminal exec matches the current common Sandbox expectation") +} + +func (h *PodHandler) validateTerminalAuthority(ctx context.Context, expected w.ReconcileExpectation, agent *api.Agent) *podFailure { + terminal := expected.Terminal + serviceAccount := &corev1.ServiceAccount{} + if err := h.reader.Get(ctx, client.ObjectKey{Namespace: expected.Namespace.Name, Name: terminal.ServiceAccountName}, serviceAccount); err != nil { + return podReadFailure("TerminalServiceAccount", err) + } + owner := w.AgentOwner(agent.Name, agent.UID) + if !serviceAccount.DeletionTimestamp.IsZero() || ptr.Deref(serviceAccount.AutomountServiceAccountToken, true) || + !equality.Semantic.DeepEqual(serviceAccount.OwnerReferences, []metav1.OwnerReference{owner}) { + return podDenied("TerminalServiceAccountMismatch", "terminal service account differs from the current Sandbox plan") + } + main := &appsv1.StatefulSet{} + if err := h.reader.Get(ctx, client.ObjectKey{Namespace: expected.Namespace.Name, Name: terminal.TargetWorkload}, main); err != nil { + return podReadFailure("TerminalTarget", err) + } + index := slices.IndexFunc(expected.Workloads, func(workload w.RenderedWorkload) bool { + return workload.Kind == "StatefulSet" && workload.Identity.Name == terminal.TargetWorkload + }) + if index < 0 || expected.Workloads[index].Identity.UID == "" || main.UID != expected.Workloads[index].Identity.UID || + !main.DeletionTimestamp.IsZero() || ptr.Deref(main.Spec.Replicas, 0) != 1 || main.Status.ObservedGeneration < main.Generation || + main.Status.ReadyReplicas < 1 || !equality.Semantic.DeepEqual(main.OwnerReferences, []metav1.OwnerReference{owner}) || + !w.SamePodTemplate(main.Spec.Template, expected.Workloads[index].Template) { + return podDenied("TerminalTargetUnavailable", "terminal target is not the current ready Sandbox workload") + } + pod := &corev1.Pod{} + if err := h.reader.Get(ctx, client.ObjectKey{Namespace: expected.Namespace.Name, Name: terminal.TargetWorkload + "-0"}, pod); err != nil { + return podReadFailure("TerminalTargetPod", err) + } + containerReady := slices.ContainsFunc(pod.Status.ContainerStatuses, func(status corev1.ContainerStatus) bool { + return status.Name == terminal.Container && status.Ready && status.State.Running != nil && status.ContainerID != "" + }) + podOwner := metav1.OwnerReference{APIVersion: "apps/v1", Kind: "StatefulSet", Name: main.Name, UID: main.UID, + Controller: ptr.To(true), BlockOwnerDeletion: ptr.To(true)} + if pod.UID == "" || !pod.DeletionTimestamp.IsZero() || pod.Status.Phase != corev1.PodRunning || !containerReady || + !equality.Semantic.DeepEqual(pod.OwnerReferences, []metav1.OwnerReference{podOwner}) { + return podDenied("TerminalTargetUnavailable", "terminal target Pod is not the current ready workload Pod") + } + wanted := expected.Workloads[index] + wanted.Template.Spec.NodeName = pod.Spec.NodeName + if err := w.ValidateRenderedPod(pod, wanted, podOwner, main.Status.UpdateRevision); err != nil { + return podDenied("TerminalTargetUnavailable", "terminal target Pod differs from the current Sandbox template") + } + return nil +} diff --git a/app/cetirun-operator/internal/controller/agent_controller.go b/app/cetirun-operator/internal/controller/agent_controller.go index c1091e67e..1dada7537 100644 --- a/app/cetirun-operator/internal/controller/agent_controller.go +++ b/app/cetirun-operator/internal/controller/agent_controller.go @@ -285,6 +285,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu result, holdErr := r.holdReconciledSandbox(ctx, instance) return result, stderrors.Join(err, holdErr) } + commonCustom := reconciledSandbox && instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom if allowed, result, err := r.reconcileMigration(ctx, instance, reconciledSandbox); !allowed { return result, err } @@ -356,13 +357,13 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu return r.holdSandbox(ctx, instance) } - if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom && instance.Spec.Suspended { + if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom && instance.Spec.Suspended && !commonCustom { return r.suspendCustom(ctx, instance) } if instance.Spec.Agent.Type != cetirunv1alpha1.AgentTypeCustom && instance.Spec.Suspended && registryManaged(instance) { return r.suspendRegistryBuiltin(ctx, instance) } - if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom { + if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom && !commonCustom { if err := r.retryCustomCompletion(ctx, instance); err != nil { return r.customWaiting(ctx, instance, "CustomCompletionPending", "Waiting to acknowledge the previous apply outcome") } @@ -418,7 +419,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu return ctrl.Result{}, fmt.Errorf("get Team %s: %w", instance.Spec.Team, teamErr) } - if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom { + if instance.Spec.Agent.Type == cetirunv1alpha1.AgentTypeCustom && !commonCustom { return r.reconcileCustom(ctx, instance, team) } @@ -440,7 +441,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } if instance.Spec.Agent.RegistrySecretRef != nil && instance.Spec.Agent.Image != nil && !instance.Spec.Suspended && - (!reconciledSandbox || instance.Spec.Agent.Port != nil) { + (!reconciledSandbox || instance.Spec.Agent.Port != nil || commonCustom) { // Owned bootstrap needs the runtime pins defaulted below. Registry sync // must not create a namespace that protected bootstrap cannot adopt. if reconciledSandbox { @@ -450,13 +451,16 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } } // Credential rotation must not pull the runtime chart or enter Helm. - values, err := buildHelmValues(instance, team, r.DomainSuffix, r.SkillsStorageAccount, r.CetiRunHelmValues, r.ChartRegistry, r.DefaultModel) - if err != nil { - return r.registryWaiting(ctx, instance, "RegistryRuntimeConfigRejected") - } - sa, err := registryServiceAccount(values, instanceServiceName(instance.Name)) - if err != nil { - return r.registryWaiting(ctx, instance, "RegistryIsolationUnverified") + sa := "default" + if !commonCustom { + values, err := buildHelmValues(instance, team, r.DomainSuffix, r.SkillsStorageAccount, r.CetiRunHelmValues, r.ChartRegistry, r.DefaultModel) + if err != nil { + return r.registryWaiting(ctx, instance, "RegistryRuntimeConfigRejected") + } + sa, err = registryServiceAccount(values, instanceServiceName(instance.Name)) + if err != nil { + return r.registryWaiting(ctx, instance, "RegistryIsolationUnverified") + } } if _, err := r.syncRegistryCredentials(ctx, instance, sa); err != nil { return r.registryWaiting(ctx, instance, err.Error()) @@ -464,7 +468,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } var prepared *helm.PreparedRelease - if instance.Spec.Agent.Image == nil || instance.Spec.Agent.Port == nil { + if !commonCustom && (instance.Spec.Agent.Image == nil || instance.Spec.Agent.Port == nil) { var err error prepared, err = r.prepareAgent(instance, team) if err != nil { @@ -598,7 +602,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } } - if prepared == nil { + if prepared == nil && !commonCustom { var err error prepared, err = r.prepareAgent(instance, team) if err != nil { @@ -679,6 +683,11 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } return r.failWith(ctx, instance, "ProvisioningFailed", fmt.Sprintf("ensure namespace: %v", namespaceErr)) } + if commonCustom { + if err := r.ensureCommonCustomRuntimeAuthentication(ctx, instance, logger); err != nil { + return r.failWith(ctx, instance, "ProvisioningFailed", fmt.Sprintf("ensure Custom runtime authentication: %v", err)) + } + } // 6a. Ensure namespaced Role + RoleBinding so the operator's access to Secrets, // ConfigMaps, Services, StatefulSets, PVCs, and ServiceAccounts is scoped to @@ -696,33 +705,35 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu if err := r.reconcileConnectionsMCPBrokerRBAC(ctx, instance, !sandboxRequested(instance, team) || r.nativeConnectionsRequested(instance)); err != nil { return r.failWith(ctx, instance, "BrokerStorageAccessFailed", fmt.Sprintf("Broker storage access setup failed: %v", err)) } - // 7. Ensure gateway token secret. - logger.V(1).Info("Ensuring gateway token secret", "alias", alias) - if err := r.ensureGatewayToken(ctx, instance); err != nil { - logger.Error(err, "failed to ensure gateway token", "alias", alias) - setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionReady, - metav1.ConditionFalse, "GatewayTokenError", err.Error()) - _ = r.updateStatus(ctx, instance) - return ctrl.Result{RequeueAfter: 30 * time.Second}, nil - } + if !commonCustom { + // 7. Ensure gateway token secret. + logger.V(1).Info("Ensuring gateway token secret", "alias", alias) + if err := r.ensureGatewayToken(ctx, instance); err != nil { + logger.Error(err, "failed to ensure gateway token", "alias", alias) + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionReady, + metav1.ConditionFalse, "GatewayTokenError", err.Error()) + _ = r.updateStatus(ctx, instance) + return ctrl.Result{RequeueAfter: 30 * time.Second}, nil + } - // 8. Ensure Tailscale auth key is in the gateway token Secret (if configured). - // The operator uses secrets.existingSecret, so the chart's Secret template is skipped. - // We must patch the auth key directly into the gateway token Secret for the StatefulSet - // to find TAILSCALE_AUTH_KEY via its secretKeyRef. - if err := r.ensureTailscaleAuthKey(ctx, instance); err != nil { - logger.Error(err, "failed to ensure Tailscale auth key", "alias", alias) - setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, - metav1.ConditionFalse, "TailscaleAuthKeyFailed", err.Error()) - _ = r.updateStatus(ctx, instance) - return ctrl.Result{RequeueAfter: 30 * time.Second}, nil - } - if instance.Spec.Tailscale != nil { - setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, - metav1.ConditionTrue, "TailscaleAuthKeyReady", "Tailscale auth key written to gateway Secret") - } else { - setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, - metav1.ConditionFalse, "TailscaleDisabled", "Tailscale is not configured") + // 8. Ensure Tailscale auth key is in the gateway token Secret (if configured). + // The operator uses secrets.existingSecret, so the chart's Secret template is skipped. + // We must patch the auth key directly into the gateway token Secret for the StatefulSet + // to find TAILSCALE_AUTH_KEY via its secretKeyRef. + if err := r.ensureTailscaleAuthKey(ctx, instance); err != nil { + logger.Error(err, "failed to ensure Tailscale auth key", "alias", alias) + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, + metav1.ConditionFalse, "TailscaleAuthKeyFailed", err.Error()) + _ = r.updateStatus(ctx, instance) + return ctrl.Result{RequeueAfter: 30 * time.Second}, nil + } + if instance.Spec.Tailscale != nil { + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, + metav1.ConditionTrue, "TailscaleAuthKeyReady", "Tailscale auth key written to gateway Secret") + } else { + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionTailscaleReady, + metav1.ConditionFalse, "TailscaleDisabled", "Tailscale is not configured") + } } // 8a. Reconcile Teams integration (Azure AD app, FIC, Bot Service, Teams channel). @@ -785,7 +796,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu // workload: an Agent routed through the Gateway needs its key at startup. var aiGatewayRequeueAfter time.Duration if r.AIGateway.Enabled { - chartSupported := aiGatewayChartSupports(prepared, instance.Spec.Agent.Type) + chartSupported := commonCustom || aiGatewayChartSupports(prepared, instance.Spec.Agent.Type) if err := r.reconcileAIGateway(ctx, instance, chartSupported); err != nil { logger.Error(err, "AI Gateway virtual key reconciliation failed", "instance", instance.Name) _ = r.updateStatus(ctx, instance) @@ -840,7 +851,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu // have guaranteed the Secret exists and may have modified its content. { gwSecret := &corev1.Secret{} - gwSecretKey := types.NamespacedName{Namespace: ns, Name: instance.Spec.GatewayTokenSecretRef} + gwSecretKey := types.NamespacedName{Namespace: ns, Name: sandboxRuntimeSecretName(instance)} if err := r.Get(ctx, gwSecretKey, gwSecret); err != nil { if !errors.IsNotFound(err) { return ctrl.Result{}, fmt.Errorf("re-read gateway Secret for operator hash: %w", err) @@ -853,71 +864,67 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu alreadyDeployed := isConditionTrue(instance.Status.Conditions, cetirunv1alpha1.ConditionHelmDeployed) && instance.Status.ObservedGeneration == instance.Generation && instance.Status.ObservedOperatorHash == r.configHash(instance, team, gwSecretHash, teamResourceVersion(team)) - // Teams may have resolved its application ID and Tailscale its auth key. - // Rebuild from current bindings without reloading the versioned chart. - helmValues, err := buildHelmValuesWithAgentIdentity(instance, team, r.DomainSuffix, r.SkillsStorageAccount, r.CetiRunHelmValues, r.ChartRegistry, r.DefaultModel, AgentIdentityHelmConfig{ - Enabled: r.AgentIdentityEnabled, - BrokerURL: r.AgentIdentityBrokerURL, - ConnectionsMCPURL: r.ConnectionsMCPURL, - ConnectionsMCPAudience: r.ConnectionsMCPAudience, - ConnectionsMCPCASecretName: r.ConnectionsMCPCASecretName, - ConnectionsMCPRuntimeTypes: r.ConnectionsMCPRuntimeTypes, - }) - if err != nil { - return r.rejectAgentConfig(ctx, instance, err) - } - if err := r.applyAIGatewayValues(helmValues, instance); err != nil { - return r.rejectAgentConfig(ctx, instance, err) - } - helmValues["memoryOptions"] = r.memoryOptions() - if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartResponsesValue) { - r.applyCopilotResponsesModels(helmValues, instance) - } - if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartProxyKeyValue) { - applyCopilotProxyKeyID(helmValues, instance) - } - if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartSignInValue) { - applyCopilotSignInGeneration(helmValues, instance) - } - if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, "replicaCount") { - gateway, _ := helmValues[aiGatewayChartValue].(map[string]any) - if proxy, ok := gateway[aiGatewayChartCopilotValue].(map[string]any); ok && proxy["enabled"] == true { - proxy["replicaCount"] = 1 - if instance.Spec.Suspended { - proxy["replicaCount"] = 0 - } + var helmValues map[string]any + if commonCustom { + if !sandboxGatewayProjectionReadyForLifecycle(instance) { + return ctrl.Result{RequeueAfter: 15 * time.Second}, nil } - } - { - secret := &corev1.Secret{} - if err := r.Get(ctx, types.NamespacedName{Namespace: ns, Name: instance.Spec.GatewayTokenSecretRef}, secret); err != nil { - return ctrl.Result{}, fmt.Errorf("read native integration bindings: %w", err) + prepared, err = r.prepareReconciledSandbox(ctx, instance, prepared, nil) + if err != nil { + result, holdErr := r.holdPolicyDependencyUnavailable(ctx, instance) + return result, stderrors.Join(err, holdErr) } - helmValues["agentRequest"].(map[string]any)["tailscaleEnabled"] = len(secret.Data["TAILSCALE_AUTH_KEY"]) > 0 - } - if gatewaySecretResourceVersion != "" { - helmValues["podAnnotations"] = deepMerge(helmValues["podAnnotations"], map[string]interface{}{ - gatewaySecretResourceVersionAnnotation: gatewaySecretResourceVersion, - }) - } - if connectionsCAHash != "" && reconciledSandbox { - helmValues["podAnnotations"] = deepMerge(helmValues["podAnnotations"], map[string]interface{}{"cetirun.microsoft.com/connections-ca-hash": connectionsCAHash}) - } - if reconciledSandbox { - prepared, err = r.prepareReconciledSandbox(ctx, instance, prepared, helmValues) + helmValues = prepared.Values } else { - prepared, err = r.HelmClient.Refresh(prepared, helmValues) - } - if err != nil { - if reconciledSandbox && stderrors.Is(err, errSandboxIngressMTLS) { - result, holdErr := r.holdReconciledSandbox(ctx, instance) - return result, stderrors.Join(err, holdErr) + // Teams may have resolved its application ID and Tailscale its auth key. + // Rebuild from current bindings without reloading the versioned chart. + helmValues, err = buildHelmValuesWithAgentIdentity(instance, team, r.DomainSuffix, r.SkillsStorageAccount, r.CetiRunHelmValues, r.ChartRegistry, r.DefaultModel, AgentIdentityHelmConfig{ + Enabled: r.AgentIdentityEnabled, + BrokerURL: r.AgentIdentityBrokerURL, + ConnectionsMCPURL: r.ConnectionsMCPURL, + ConnectionsMCPAudience: r.ConnectionsMCPAudience, + ConnectionsMCPCASecretName: r.ConnectionsMCPCASecretName, + ConnectionsMCPRuntimeTypes: r.ConnectionsMCPRuntimeTypes, + }) + if err != nil { + return r.rejectAgentConfig(ctx, instance, err) } - if reconciledSandbox && stderrors.Is(err, errSandboxSourceChanged) { - result, holdErr := r.holdPolicyDependencyUnavailable(ctx, instance) - return result, stderrors.Join(err, holdErr) + if err := r.applyAIGatewayValues(helmValues, instance); err != nil { + return r.rejectAgentConfig(ctx, instance, err) + } + helmValues["memoryOptions"] = r.memoryOptions() + r.applyCopilotChartValues(helmValues, instance, prepared) + { + secret := &corev1.Secret{} + if err := r.Get(ctx, types.NamespacedName{Namespace: ns, Name: instance.Spec.GatewayTokenSecretRef}, secret); err != nil { + return ctrl.Result{}, fmt.Errorf("read native integration bindings: %w", err) + } + helmValues["agentRequest"].(map[string]any)["tailscaleEnabled"] = len(secret.Data["TAILSCALE_AUTH_KEY"]) > 0 + } + if gatewaySecretResourceVersion != "" { + helmValues["podAnnotations"] = deepMerge(helmValues["podAnnotations"], map[string]interface{}{ + gatewaySecretResourceVersionAnnotation: gatewaySecretResourceVersion, + }) + } + if connectionsCAHash != "" && reconciledSandbox { + helmValues["podAnnotations"] = deepMerge(helmValues["podAnnotations"], map[string]interface{}{"cetirun.microsoft.com/connections-ca-hash": connectionsCAHash}) + } + if reconciledSandbox { + prepared, err = r.prepareReconciledSandbox(ctx, instance, prepared, helmValues) + } else { + prepared, err = r.HelmClient.Refresh(prepared, helmValues) + } + if err != nil { + if reconciledSandbox && stderrors.Is(err, errSandboxIngressMTLS) { + result, holdErr := r.holdReconciledSandbox(ctx, instance) + return result, stderrors.Join(err, holdErr) + } + if reconciledSandbox && stderrors.Is(err, errSandboxSourceChanged) { + result, holdErr := r.holdPolicyDependencyUnavailable(ctx, instance) + return result, stderrors.Join(err, holdErr) + } + return r.rejectAgentConfig(ctx, instance, err) } - return r.rejectAgentConfig(ctx, instance, err) } if instance.Spec.Suspended { if err := validateSuspendedHome(prepared.Values); err != nil { @@ -933,7 +940,7 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } r.recordSignInHelper(instance, prepared.ServesSignInHelper()) setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionAgentConfigReady, - metav1.ConditionTrue, "AgentConfigResolved", "Built-in Harness configuration resolved") + metav1.ConditionTrue, "AgentConfigResolved", "Agent Harness configuration resolved") helmValues = prepared.Values if connectionsCAHash != "" && !reconciledSandbox { helmValues["podAnnotations"] = deepMerge(helmValues["podAnnotations"], map[string]interface{}{"cetirun.microsoft.com/connections-ca-hash": connectionsCAHash}) @@ -1120,37 +1127,47 @@ func (r *AgentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (resu } } - // 10a. Ensure VirtualService (non-suspended path). - // TODO: VirtualService failure should block Ready (return error, set phase=Failed). - // Currently best-effort because Istio is not installed on all test clusters. - // When Istio is guaranteed to be present, change this block to: - // if err != nil { return r.failWith(ctx, instance, "VirtualServiceFailed", err.Error()) } - logger.V(1).Info("Ensuring VirtualService", "alias", alias) - if result, err := r.ensureVirtualService(ctx, instance); err != nil { - logger.Error(err, "VirtualService creation/update failed (best-effort)", "alias", alias) - setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionIngressReady, - metav1.ConditionFalse, "VirtualServiceFailed", err.Error()) - if reconciledSandbox { - instance.Status.AccessURL = "" - instance.Status.Phase = cetirunv1alpha1.PhaseProvisioning + if commonCustom { + if err := r.configureReconciledCustomRuntime(ctx, instance, prepared); err != nil { + logger.Error(err, "Common Custom access configuration failed", "alias", alias) setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionReady, - metav1.ConditionFalse, "VirtualServiceFailed", "Current Sandbox ingress is not established") + metav1.ConditionFalse, "CustomAccessUnavailable", err.Error()) + instance.Status.Phase = cetirunv1alpha1.PhaseProvisioning return ctrl.Result{RequeueAfter: 15 * time.Second}, stderrors.Join(err, r.updateStatus(ctx, instance)) } } else { - logger.V(1).Info("VirtualService ensured", "alias", alias, "result", result) - ingress := meta.FindStatusCondition(instance.Status.Conditions, cetirunv1alpha1.ConditionIngressReady) - if !reconciledSandbox || ingress == nil || ingress.Reason != "IngressDisabled" { - instance.Status.AccessURL = accessURLPathBased(instance.Name, r.DomainSuffix) + // 10a. Ensure VirtualService (non-suspended path). + // TODO: VirtualService failure should block Ready (return error, set phase=Failed). + // Currently best-effort because Istio is not installed on all test clusters. + // When Istio is guaranteed to be present, change this block to: + // if err != nil { return r.failWith(ctx, instance, "VirtualServiceFailed", err.Error()) } + logger.V(1).Info("Ensuring VirtualService", "alias", alias) + if result, err := r.ensureVirtualService(ctx, instance); err != nil { + logger.Error(err, "VirtualService creation/update failed (best-effort)", "alias", alias) setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionIngressReady, - metav1.ConditionTrue, "VirtualServiceCreated", "Istio ingress configured") - } - if result != controllerutil.OperationResultNone { - r.EventRecorder.Eventf(instance, corev1.EventTypeNormal, "IngressConfigured", - "Istio VirtualService %s, instance accessible at %s", result, accessURLPathBased(instance.Name, r.DomainSuffix)) + metav1.ConditionFalse, "VirtualServiceFailed", err.Error()) + if reconciledSandbox { + instance.Status.AccessURL = "" + instance.Status.Phase = cetirunv1alpha1.PhaseProvisioning + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionReady, + metav1.ConditionFalse, "VirtualServiceFailed", "Current Sandbox ingress is not established") + return ctrl.Result{RequeueAfter: 15 * time.Second}, stderrors.Join(err, r.updateStatus(ctx, instance)) + } + } else { + logger.V(1).Info("VirtualService ensured", "alias", alias, "result", result) + ingress := meta.FindStatusCondition(instance.Status.Conditions, cetirunv1alpha1.ConditionIngressReady) + if !reconciledSandbox || ingress == nil || ingress.Reason != "IngressDisabled" { + instance.Status.AccessURL = accessURLPathBased(instance.Name, r.DomainSuffix) + setCondition(&instance.Status.Conditions, cetirunv1alpha1.ConditionIngressReady, + metav1.ConditionTrue, "VirtualServiceCreated", "Istio ingress configured") + } + if result != controllerutil.OperationResultNone { + r.EventRecorder.Eventf(instance, corev1.EventTypeNormal, "IngressConfigured", + "Istio VirtualService %s, instance accessible at %s", result, accessURLPathBased(instance.Name, r.DomainSuffix)) + } } - } + } // 11. Verify StatefulSet pod readiness before marking Ready. prerequisitesComplete = true setCondition(&instance.Status.Conditions, builtInPrerequisitesReady, diff --git a/app/cetirun-operator/internal/controller/ai_gateway.go b/app/cetirun-operator/internal/controller/ai_gateway.go index 6d7b382ba..9635f95b5 100644 --- a/app/cetirun-operator/internal/controller/ai_gateway.go +++ b/app/cetirun-operator/internal/controller/ai_gateway.go @@ -1331,9 +1331,29 @@ func (r *AgentReconciler) applyAIGatewayValues(values map[string]any, instance * return nil } -// applyCopilotResponsesModels tells the Agent's Copilot proxy which of its -// registered models GitHub Copilot serves only through the Responses API, so -// the proxy bridges the chat completion requests agents send for them. +func (r *AgentReconciler) applyCopilotChartValues(values map[string]any, instance *cetirunv1alpha1.Agent, prepared chartValuePaths) { + if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartResponsesValue) { + r.applyCopilotResponsesModels(values, instance) + } + if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartProxyKeyValue) { + applyCopilotProxyKeyID(values, instance) + } + if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, aiGatewayChartSignInValue) { + applyCopilotSignInGeneration(values, instance) + } + if prepared.SupportsValuePath(aiGatewayChartValue, aiGatewayChartCopilotValue, "replicaCount") { + gateway, _ := values[aiGatewayChartValue].(map[string]any) + if proxy, ok := gateway[aiGatewayChartCopilotValue].(map[string]any); ok && proxy["enabled"] == true { + proxy["replicaCount"] = 1 + if instance.Spec.Suspended { + proxy["replicaCount"] = 0 + } + } + } +} + +// applyCopilotResponsesModels tells the proxy which registered models need +// the Responses API bridge for chat-completion requests. func (r *AgentReconciler) applyCopilotResponsesModels(values map[string]any, instance *cetirunv1alpha1.Agent) { gateway, _ := values["aiGateway"].(map[string]any) proxy, _ := gateway["copilotProxy"].(map[string]any) diff --git a/app/cetirun-operator/internal/controller/custom_terminal.go b/app/cetirun-operator/internal/controller/custom_terminal.go index 41389cfb8..f30c6e42a 100644 --- a/app/cetirun-operator/internal/controller/custom_terminal.go +++ b/app/cetirun-operator/internal/controller/custom_terminal.go @@ -12,6 +12,7 @@ import ( api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" "github.com/Azure/CetiRun/app/cetirun-operator/internal/runtimebindings" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxpolicy" "github.com/Azure/CetiRun/app/cetirun-operator/internal/terminal" "github.com/Azure/CetiRun/app/internal/terminalpolicy" appsv1 "k8s.io/api/apps/v1" @@ -30,6 +31,39 @@ func customTerminalRequested(values map[string]any) bool { return settings["enabled"] != false } +func (r *AgentReconciler) ensureCommonTerminalReaderBinding(ctx context.Context, instance *api.Agent) error { + if err := r.checkAgentGeneration(ctx, instance); err != nil { + return err + } + _, reader := terminal.ReadRoles(instanceNamespace(instance.Name), instanceServiceName(instance.Name), instance.Name, string(instance.UID)) + desired := &rbacv1.ClusterRoleBinding{ + ObjectMeta: *reader.ObjectMeta.DeepCopy(), + Subjects: []rbacv1.Subject{{ + Kind: "ServiceAccount", Namespace: instanceNamespace(instance.Name), + Name: terminalpolicy.WorkloadName(instanceServiceName(instance.Name)), + }}, + RoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: reader.Name}, + } + current := &rbacv1.ClusterRoleBinding{} + err := r.customReader().Get(ctx, client.ObjectKeyFromObject(desired), current) + if apierrors.IsNotFound(err) { + return r.Create(ctx, desired) + } + if err != nil { + return err + } + if !hasAgentOwner(current, instance) || current.Annotations[customAgentUID] != string(instance.UID) || + current.RoleRef != desired.RoleRef || !current.DeletionTimestamp.IsZero() { + return fmt.Errorf("terminal Agent reader binding ownership or role is not confirmed") + } + if equality.Semantic.DeepEqual(current.Subjects, desired.Subjects) { + return nil + } + before := current.DeepCopy() + current.Subjects = desired.Subjects + return r.Patch(ctx, current, client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})) +} + func (r *AgentReconciler) ensureTerminalReadRoles(ctx context.Context, instance *api.Agent) error { if err := r.checkAgentGeneration(ctx, instance); err != nil { return err @@ -164,7 +198,12 @@ func (r *AgentReconciler) stopCustomTerminal(ctx context.Context, instance *api. } return err } - if !hasCustomWorkloadOwner(deployment, instance) || deployment.Annotations[customAgentUID] != string(instance.UID) { + common, err := r.recordedReconciledSandbox(ctx, instance) + if err != nil { + return err + } + if (common && !commonCustomTerminalOwned(deployment, instance)) || + (!common && (!hasCustomWorkloadOwner(deployment, instance) || deployment.Annotations[customAgentUID] != string(instance.UID))) { return fmt.Errorf("Custom terminal owner is not confirmed") } if ptr.Deref(deployment.Spec.Replicas, 0) == 0 { @@ -184,10 +223,33 @@ func (r *AgentReconciler) customTerminalReady(ctx context.Context, instance *api } return false, err } - if !hasAgentOwner(deployment, instance) || deployment.Annotations[customAgentUID] != string(instance.UID) { + common, err := r.recordedReconciledSandbox(ctx, instance) + if err != nil { + return false, err + } + if common { + if !commonCustomTerminalOwned(deployment, instance) { + return false, fmt.Errorf("Custom terminal owner is not confirmed") + } + _, expected, err := r.readReconciledSandboxExpectation(ctx, instance) + if err != nil { + return false, err + } + if expected.Terminal == nil || expected.Terminal.ServiceAccountName != deployment.Name || expected.Binding.AgentUID != instance.UID { + return false, fmt.Errorf("Custom terminal common Sandbox expectation is not confirmed") + } + } else if !hasAgentOwner(deployment, instance) || deployment.Annotations[customAgentUID] != string(instance.UID) { return false, fmt.Errorf("Custom terminal owner is not confirmed") } return deployment.DeletionTimestamp.IsZero() && ptr.Deref(deployment.Spec.Replicas, 0) == 1 && deployment.Status.ObservedGeneration >= deployment.Generation && deployment.Status.AvailableReplicas > 0, nil } + +func commonCustomTerminalOwned(deployment *appsv1.Deployment, instance *api.Agent) bool { + return deployment != nil && instance != nil && sandboxBuiltinOwned(deployment, instance) && + deployment.Name == terminalpolicy.WorkloadName(instanceServiceName(instance.Name)) && + deployment.Namespace == instanceNamespace(instance.Name) && + deployment.Labels[sandboxpolicy.AgentUIDLabel] == string(instance.UID) && + deployment.Labels["cetirun.microsoft.com/terminal"] == "true" +} diff --git a/app/cetirun-operator/internal/controller/migration_test.go b/app/cetirun-operator/internal/controller/migration_test.go index e76d50ed8..774896215 100644 --- a/app/cetirun-operator/internal/controller/migration_test.go +++ b/app/cetirun-operator/internal/controller/migration_test.go @@ -316,7 +316,11 @@ func TestPlannedMigrationRetainsHOMEAcrossRepeatedMoves(t *testing.T) { } func testPlannedMigrationRetainsHOME(t *testing.T, setup ...func(*AgentReconciler, client.Client)) { - for _, kind := range []string{"openclaw", "hermes"} { + testPlannedMigrationRetainsHOMEForHarnesses(t, []string{"openclaw", "hermes"}, setup...) +} + +func testPlannedMigrationRetainsHOMEForHarnesses(t *testing.T, harnesses []string, setup ...func(*AgentReconciler, client.Client)) { + for _, kind := range harnesses { for _, coordinated := range []bool{false, true} { for _, mode := range []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOncePod, corev1.ReadWriteOnce} { t.Run(fmt.Sprintf("%s/coordination=%t/%s", kind, coordinated, mode), func(t *testing.T) { diff --git a/app/cetirun-operator/internal/controller/policy.go b/app/cetirun-operator/internal/controller/policy.go index 0c66dbc9c..d42862a4b 100644 --- a/app/cetirun-operator/internal/controller/policy.go +++ b/app/cetirun-operator/internal/controller/policy.go @@ -281,13 +281,15 @@ func (r *AgentReconciler) resolvePolicy(ctx context.Context, agent *api.Agent) ( if !slices.Contains(policy.Spec.Harnesses.Allowed, agent.Spec.Agent.Type) { return nil, fmt.Errorf("Agent harness %q is not allowed by policy", agent.Spec.Agent.Type) } - // A Custom workload has a typed Gateway binding, but not the protected - // Sandbox preparation/execution adapter required for complete Policy - // enforcement. Keep it held until every required domain has an adapter. if agent.Spec.Agent.Type == api.AgentTypeCustom { - return nil, fmt.Errorf("Agent harness %q has no typed Sandbox execution adapter", agent.Spec.Agent.Type) + if r.SandboxPreparation == nil || !r.SandboxPreparation.NativeExecution || !r.customGatewaySelected(agent) { + return nil, fmt.Errorf("Custom policy execution requires the common executor and a Gateway-qualified image") + } + if policy.Spec.Network.Ingress.RequireMTLS { + return nil, fmt.Errorf("managed ingress mTLS does not yet support the Custom endpoint contract") + } } - if !aiGatewayHarnessSupported(agent.Spec.Agent.Type) { + if !aiGatewayHarnessSupported(agent.Spec.Agent.Type) && !r.customGatewaySelected(agent) { return nil, fmt.Errorf("Agent harness %q has no typed AI Gateway enforcement adapter", agent.Spec.Agent.Type) } if !r.AIGateway.Enabled || !r.AIGateway.configured() { @@ -455,11 +457,25 @@ func (r *AgentReconciler) desiredSandboxPolicyRevision(ctx context.Context, agen if err != nil { return "", policyDependency("resolve native Connections destination: %w", err) } + var customIngress *sandboxpolicy.CustomIngress + var terminalIngress *sandboxpolicy.TerminalIngress + if agent.Spec.Agent.Type == api.AgentTypeCustom { + values, user, err := r.sandboxHelmValues(agent, team) + if err != nil { + return "", err + } + terminal, err := customSandboxTerminalInput(values, user, instanceServiceName(agent.Name)) + if err != nil { + return "", err + } + customIngress, terminalIngress = r.customSandboxIngress(agent), terminalSandboxIngress(terminal) + } plan, err := sandboxpolicy.Compile(sandboxpolicy.CompileInput{ ConnectionsMCP: connections, NativeExecution: r.SandboxPreparation.NativeExecution, Resolution: *resolution, AgentName: agent.Name, Namespace: instanceNamespace(agent.Name), ServiceName: instanceServiceName(agent.Name), Platform: platform, + CustomIngress: customIngress, TerminalIngress: terminalIngress, }) if err != nil { if errors.Is(err, sandboxpolicy.ErrUnavailable) { diff --git a/app/cetirun-operator/internal/controller/reconciled_custom_access.go b/app/cetirun-operator/internal/controller/reconciled_custom_access.go new file mode 100644 index 000000000..ea5390562 --- /dev/null +++ b/app/cetirun-operator/internal/controller/reconciled_custom_access.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package controller + +import ( + "context" + "fmt" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/helm" + "github.com/Azure/CetiRun/app/internal/chataccess" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func (r *AgentReconciler) configureReconciledCustomRuntime(ctx context.Context, instance *api.Agent, prepared *helm.PreparedRelease) error { + access, err := reconciledCustomAccess(instance, prepared) + if err != nil { + return err + } + resolution, err := r.resolvePolicy(ctx, instance) + if err != nil { + return err + } + disabled := resolution.policy.Spec.Network.Ingress.Mode == api.AgentPolicyIngressDisabled + chat := !disabled && r.ChatAccess.Enabled && len(r.ChatAccess.Callers) != 0 && + instance.Spec.Agent.Port != nil && !instance.Spec.Agent.WebUI + if chat && !prepared.SupportsPortalChat() { + return fmt.Errorf("the Custom chart does not support private Portal Chat") + } + if err := r.reconcileChatRoute(ctx, instance, chat); err != nil { + setCondition(&instance.Status.Conditions, chataccess.Condition, metav1.ConditionFalse, + "ChatRouteUnavailable", "The private Chat route could not be reconciled") + return err + } + status, reason := metav1.ConditionFalse, "ChatAccessDisabled" + if chat { + status, reason = metav1.ConditionTrue, "ChatAccessConfigured" + } + setCondition(&instance.Status.Conditions, chataccess.Condition, status, reason, + "Reports private Chat configuration, not model or network qualification") + if disabled { + if err := r.withdrawKubernetesSandboxRoute(ctx, instance); err != nil { + return err + } + instance.Status.AccessURL = "" + setCondition(&instance.Status.Conditions, api.ConditionIngressReady, metav1.ConditionTrue, + "IngressDisabled", "Sandbox ingress is disabled") + setCustomServiceConditions(instance, access, metav1.ConditionFalse, "IngressDisabled") + return nil + } + if !access.terminal && !instance.Spec.Agent.WebUI { + if err := r.removeCustomPlatformRoute(ctx, instance); err != nil { + return err + } + instance.Status.AccessURL = "" + setCondition(&instance.Status.Conditions, api.ConditionIngressReady, metav1.ConditionFalse, + "PlatformAccessDisabled", "Custom terminal and Web UI are disabled") + setCustomServiceConditions(instance, access, metav1.ConditionFalse, "PlatformAccessDisabled") + return nil + } + if _, err := r.ensureVirtualService(ctx, instance, access); err != nil { + return err + } + instance.Status.AccessURL = "" + if instance.Spec.Agent.WebUI { + instance.Status.AccessURL = accessURLPathBased(instance.Name, r.DomainSuffix) + } + setCondition(&instance.Status.Conditions, api.ConditionIngressReady, metav1.ConditionTrue, + "PlatformServicesConfigured", "Approved Custom Web UI and terminal routes are configured") + setCustomServiceConditions(instance, access, metav1.ConditionTrue, "PlatformServicesConfigured") + if access.terminal { + ready, err := r.customTerminalReady(ctx, instance) + if err != nil { + return err + } + if !ready { + setCondition(&instance.Status.Conditions, api.ConditionTerminalConfigured, metav1.ConditionFalse, + "PlatformTerminalPending", "Waiting for the owned terminal Deployment") + return fmt.Errorf("common Custom terminal is not ready") + } + } + return nil +} + +func reconciledCustomAccess(instance *api.Agent, prepared *helm.PreparedRelease) (customAccess, error) { + if prepared == nil { + return customAccess{}, fmt.Errorf("common Custom release is unavailable") + } + runtime, _ := prepared.Values["runtime"].(map[string]any) + agent, _ := runtime["agent"].(map[string]any) + if agent["type"] != "custom" || agent["webUI"] != instance.Spec.Agent.WebUI { + return customAccess{}, fmt.Errorf("common Custom runtime differs from its Harness contract") + } + access := customAccess{} + control, _ := prepared.Values["sandboxWorkload"].(map[string]any) + terminal, _ := control["terminal"].(map[string]any) + if terminal["enabled"] == true { + port, err := customSandboxNumber(terminal["port"], 0, 1024, 65535) + if err != nil || port == 0 { + return customAccess{}, fmt.Errorf("common Custom terminal contract has an invalid port") + } + access.terminal, access.terminalPort = true, uint32(port) + } + return access, nil +} diff --git a/app/cetirun-operator/internal/controller/sandbox_bootstrap.go b/app/cetirun-operator/internal/controller/sandbox_bootstrap.go index c32bf6393..d94ffe871 100644 --- a/app/cetirun-operator/internal/controller/sandbox_bootstrap.go +++ b/app/cetirun-operator/internal/controller/sandbox_bootstrap.go @@ -83,7 +83,8 @@ func (r *AgentReconciler) readSandboxBootstrap(ctx context.Context, agent *api.A !equality.Semantic.DeepEqual(object.OwnerReferences, owner) || object.Annotations[sandboxworkload.AgentUIDAnnotation] != string(agent.UID) || receipt.AgentName != agent.Name || receipt.AgentUID != agent.UID || - (receipt.AgentType != api.AgentTypeOpenClaw && receipt.AgentType != api.AgentTypeHermes) || + (receipt.AgentType != api.AgentTypeOpenClaw && receipt.AgentType != api.AgentTypeHermes && receipt.AgentType != api.AgentTypeCustom) || + (receipt.AgentType == api.AgentTypeCustom && !receipt.Reconciled) || receipt.Namespace != instanceNamespace(agent.Name) || receipt.Namespace == r.OperatorNamespace || len(validation.IsDNS1123Label(receipt.Namespace)) != 0 || receipt.ChartVersion == "" || !((receipt.Version == "v1" && receipt.Skills == nil && len(receipt.Objects) == 5) || @@ -179,11 +180,12 @@ func (r *AgentReconciler) bootstrapSandboxOwned(ctx context.Context, attempt *sa return err } if (!attempt.reconciled && agent.Spec.Helm.Version != config.ChartVersion) || agent.Spec.Helm.Version == "" || agent.Spec.Agent.Image == nil || *agent.Spec.Agent.Image == "" || - agent.Spec.Agent.Port == nil || *agent.Spec.Agent.Port < 1 || *agent.Spec.Agent.Port > 65535 { + (agent.Spec.Agent.Type != api.AgentTypeCustom && agent.Spec.Agent.Port == nil) || + (agent.Spec.Agent.Port != nil && (*agent.Spec.Agent.Port < 1 || *agent.Spec.Agent.Port > 65535)) { return fmt.Errorf("Sandbox bootstrap requires explicit approved chart version, native image and port; controller spec defaulting is not authorized") } if len(validation.IsDNS1123Label(instanceNamespace(agent.Name))) != 0 || instanceNamespace(agent.Name) == r.OperatorNamespace || - len(validation.IsDNS1123Subdomain(agent.Spec.GatewayTokenSecretRef)) != 0 || + len(validation.IsDNS1123Subdomain(sandboxRuntimeSecretName(agent))) != 0 || len(validation.IsDNS1123Subdomain(r.OperatorSAName)) != 0 { return fmt.Errorf("Sandbox bootstrap requires valid isolated namespace, runtime Secret and operator identities") } @@ -199,7 +201,7 @@ func (r *AgentReconciler) bootstrapSandboxOwned(ctx context.Context, attempt *sa {Kind: "Namespace", Name: instanceNamespace(agent.Name)}, {Kind: "Role", Name: role.Name}, {Kind: "RoleBinding", Name: binding.Name}, {Kind: "PersistentVolumeClaim", Name: config.HomeClaimName}, - {Kind: "Secret", Name: agent.Spec.GatewayTokenSecretRef}, + {Kind: "Secret", Name: sandboxRuntimeSecretName(agent)}, }, } if config.SkillsCatalogConfigMapName != "" { @@ -238,7 +240,7 @@ func (r *AgentReconciler) bootstrapSandboxOwned(ctx context.Context, attempt *sa return fmt.Errorf("Sandbox bootstrap receipt is no longer protected for writes") } if receipt.Home != profile || receipt.Objects[3].Name != config.HomeClaimName || - receipt.Objects[4].Name != agent.Spec.GatewayTokenSecretRef || (!receipt.Reconciled && receipt.ChartVersion != config.ChartVersion) || + receipt.Objects[4].Name != sandboxRuntimeSecretName(agent) || (!receipt.Reconciled && receipt.ChartVersion != config.ChartVersion) || receipt.AgentType != agent.Spec.Agent.Type || receipt.Reconciled != attempt.reconciled { return fmt.Errorf("%w: changing bootstrap storage, native type, Secret or chart requires an explicit handoff", sandboxworkload.ErrStorageTransitionRequired) } diff --git a/app/cetirun-operator/internal/controller/sandbox_custom.go b/app/cetirun-operator/internal/controller/sandbox_custom.go new file mode 100644 index 000000000..e3fa7e38c --- /dev/null +++ b/app/cetirun-operator/internal/controller/sandbox_custom.go @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package controller + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "math" + "strings" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/agents" + customharness "github.com/Azure/CetiRun/app/cetirun-operator/internal/agents/custom" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxpolicy" + w "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" + "github.com/Azure/CetiRun/app/internal/terminalpolicy" + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func sandboxRuntimeSecretName(agent *api.Agent) string { + if agent.Spec.Agent.Type == api.AgentTypeCustom { + return "custom-runtime" + } + return agent.Spec.GatewayTokenSecretRef +} + +func sandboxGatewayProjectionReadyForLifecycle(agent *api.Agent) bool { + return sandboxGatewayProjectionReady(agent) || agent.Spec.Suspended && agent.Status.AIGateway != nil && + agent.Status.Policy != nil && agent.Status.AIGateway.Phase == api.AIGatewayPhaseReady && + agent.Status.AIGateway.Blocked && agent.Status.AIGateway.Reason == aiGatewayReasonSuspended && + agent.Status.AIGateway.PolicyRevision == agent.Status.Policy.Enforcement.Gateway.DesiredRevision +} + +func (r *AgentReconciler) ensureCommonCustomRuntimeAuthentication(ctx context.Context, agent *api.Agent, logger logr.Logger) error { + state, receipt, err := r.readSandboxBootstrap(ctx, agent) + if err != nil { + return fmt.Errorf("read Custom bootstrap receipt: %w", err) + } + if agent.Spec.Agent.Type != api.AgentTypeCustom || !receipt.Reconciled || len(receipt.Objects) < 5 || + receipt.Objects[4].Kind != "Secret" || receipt.Objects[4].Name != sandboxRuntimeSecretName(agent) || receipt.Objects[4].UID == "" { + return fmt.Errorf("Custom bootstrap receipt does not identify its runtime Secret") + } + desired := r.sandboxBootstrapObjects(agent, state, receipt) + secret := &corev1.Secret{} + if err := r.customReader().Get(ctx, client.ObjectKeyFromObject(desired[4]), secret); err != nil { + return err + } + if err := validateSandboxBootstrapObject(secret, desired[4], receipt.Objects[4].UID, false); err != nil { + return err + } + return r.ensureCetiRunAuthKey(ctx, logger, secret) +} + +func (r *AgentReconciler) configureCustomSandboxInput(ctx context.Context, attempt *sandboxPreparationAttempt) error { + agent := attempt.agent + if !attempt.reconciled || !r.customGatewaySelected(agent) || agent.Spec.Agent.Image == nil { + return fmt.Errorf("Custom Sandbox execution requires an explicitly Gateway-qualified image and common execution") + } + request := agents.Request{Type: "custom", Image: *agent.Spec.Agent.Image, Port: agent.Spec.Agent.Port, WebUI: agent.Spec.Agent.WebUI} + if agent.Spec.Agent.Username != nil { + request.Username = *agent.Spec.Agent.Username + } + resolved, err := agents.ResolveCustom(request) + if err != nil { + return err + } + baseURL := strings.TrimSuffix(r.AIGateway.URL, "/") + "/v1" + contribution, err := (customharness.Harness{}).Build(resolved, agents.Bindings{ + ContextRevision: attempt.prerequisites.Revision, + Model: agents.ModelBinding{BaseURL: baseURL, CredentialSlot: "model", + Revision: string(attempt.prerequisites.RuntimeSecret.UID)}, + WebBasePath: "/ui/" + agent.Name + "/", WebInstance: string(agent.UID), + }) + if err != nil { + return err + } + custom := &w.CustomAgent{ + Image: resolved.Image, Username: resolved.Username, Home: resolved.HomeDir, Port: resolved.Port, WebUI: resolved.WebUI, + WebBasePath: "/ui/" + agent.Name + "/", WebInstance: string(agent.UID), + } + for _, value := range contribution.Environment { + custom.Environment = append(custom.Environment, w.CustomEnvironment{ + Name: value.Name, Value: value.Value, CredentialSlot: value.CredentialSlot, + }) + } + for _, value := range contribution.Ports { + custom.Ports = append(custom.Ports, w.CustomPort{Name: value.Name, Number: value.Number}) + } + if h := contribution.HTTP; h != nil { + custom.HTTP = &w.CustomHTTP{PortName: h.PortName, HealthPath: h.HealthPath, ReadinessPath: h.ReadinessPath, + StartupPath: h.StartupPath, ChatPath: h.ChatPath, ModelsPath: h.ModelsPath} + } + attempt.input.CustomAgent, attempt.input.GatewayAPIBase = custom, baseURL + snapshot, err := r.ensureCustomSandboxContext(ctx, agent, attempt.team, attempt.input.Namespace.Name) + if err != nil { + return err + } + attempt.input.Context = &w.Context{ObjectIdentity: w.ObjectIdentity{Name: snapshot.Name, UID: snapshot.UID}, + Files: map[string]string{"AGENTS.md": "AGENTS.md"}} + attempt.sources = append(attempt.sources, sandboxSource(snapshot, "v1", "ConfigMap")) + platform, user, err := r.sandboxHelmValues(agent, attempt.team) + if err != nil { + return err + } + attempt.input.Terminal, err = customSandboxTerminalInput(platform, user, attempt.input.WorkloadName) + if err != nil { + return err + } + if custom.HTTP != nil { + image, err := customSandboxHelperImage(platform) + if err != nil { + return err + } + attempt.input.LoopbackProbe = &w.LoopbackProbe{Image: image} + } + return nil +} + +func (r *AgentReconciler) ensureCustomSandboxContext(ctx context.Context, agent *api.Agent, team *api.Team, namespace string) (*corev1.ConfigMap, error) { + if team == nil { + return nil, fmt.Errorf("Custom Sandbox requires a resolved Team context") + } + data := map[string]string{"AGENTS.md": "# CetiRun Team Context\n\n## Role\n" + team.Spec.MemberContext.Role + + "\n\n## Context\n" + strings.Join(team.Spec.MemberContext.Description, "\n") + "\n"} + raw, err := json.Marshal(struct { + AgentUID string `json:"agentUID"` + TeamUID string `json:"teamUID"` + Files map[string]string `json:"files"` + }{string(agent.UID), string(team.UID), data}) + if err != nil { + return nil, err + } + sum := sha256.Sum256(raw) + name := "custom-context-" + hex.EncodeToString(sum[:16]) + owner := []metav1.OwnerReference{w.AgentOwner(agent.Name, agent.UID)} + snapshot := &corev1.ConfigMap{} + err = r.customReader().Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, snapshot) + if apierrors.IsNotFound(err) { + snapshot = &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, OwnerReferences: owner}, + Immutable: ptr.To(true), Data: data} + if err := r.Create(ctx, snapshot); err != nil { + return nil, err + } + if err := r.customReader().Get(ctx, client.ObjectKeyFromObject(snapshot), snapshot); err != nil { + return nil, err + } + } else if err != nil { + return nil, err + } + if snapshot.UID == "" || snapshot.ResourceVersion == "" || !snapshot.DeletionTimestamp.IsZero() || + !ptr.Deref(snapshot.Immutable, false) || !equality.Semantic.DeepEqual(snapshot.OwnerReferences, owner) || + !equality.Semantic.DeepEqual(snapshot.Data, data) || len(snapshot.BinaryData) != 0 { + return nil, fmt.Errorf("Custom context snapshot has changed or has foreign ownership") + } + return snapshot, nil +} + +func customSandboxHelperImage(platform map[string]any) (string, error) { + settings, _ := platform["ttyd"].(map[string]any) + image, _ := settings["image"].(map[string]any) + repository, _ := image["repository"].(string) + if global, ok := platform["global"].(map[string]any); ok { + if registry, ok := global["registry"].(string); ok && strings.TrimSuffix(registry, "/") != "" { + repository = strings.TrimSuffix(registry, "/") + "/cetirun-terminal" + } + } + digest, _ := image["digest"].(string) + if repository == "" || len(digest) != len("sha256:")+64 || !strings.HasPrefix(digest, "sha256:") { + return "", fmt.Errorf("Custom terminal and HTTP probes require an immutable platform terminal image") + } + if _, err := hex.DecodeString(strings.TrimPrefix(digest, "sha256:")); err != nil { + return "", fmt.Errorf("Custom platform terminal image digest is invalid") + } + return repository + "@" + digest, nil +} + +func customSandboxTerminalInput(platform, user map[string]any, workload string) (*w.Terminal, error) { + settings, _ := platform["ttyd"].(map[string]any) + requested, _ := user["ttyd"].(map[string]any) + if settings["enabled"] == false || requested["enabled"] == false { + return nil, nil + } + image, err := customSandboxHelperImage(platform) + if err != nil { + return nil, err + } + port, err := customSandboxNumber(settings["port"], 7681, 1024, 65535) + if err != nil { + return nil, fmt.Errorf("Custom terminal port: %w", err) + } + session, err := customSandboxNumber(settings["sessionSeconds"], 1800, 60, 3600) + if err != nil { + return nil, fmt.Errorf("Custom terminal session: %w", err) + } + return &w.Terminal{Image: image, Port: port, SessionSeconds: session, ServiceAccountName: terminalpolicy.WorkloadName(workload)}, nil +} + +func customSandboxNumber(value any, defaultValue, minimum, maximum int32) (int32, error) { + if value == nil { + return defaultValue, nil + } + var number float64 + switch value := value.(type) { + case int: + number = float64(value) + case int32: + number = float64(value) + case int64: + number = float64(value) + case float64: + number = value + default: + return 0, fmt.Errorf("must be an integer between %d and %d", minimum, maximum) + } + if math.IsNaN(number) || math.IsInf(number, 0) || number < float64(minimum) || number > float64(maximum) || math.Trunc(number) != number { + return 0, fmt.Errorf("must be an integer between %d and %d", minimum, maximum) + } + return int32(number), nil +} + +func (r *AgentReconciler) customSandboxIngress(agent *api.Agent) *sandboxpolicy.CustomIngress { + if agent.Spec.Agent.Port == nil { + return nil + } + ingress := &sandboxpolicy.CustomIngress{Port: *agent.Spec.Agent.Port, WebUI: agent.Spec.Agent.WebUI} + if !ingress.WebUI && r.ChatAccess.Enabled { + for _, caller := range r.ChatAccess.Callers { + ingress.ChatCallers = append(ingress.ChatCallers, sandboxpolicy.IngressCaller{Namespace: caller.Namespace, PodLabels: caller.PodLabels}) + } + } + if !ingress.WebUI && len(ingress.ChatCallers) == 0 { + return nil + } + return ingress +} + +func terminalSandboxIngress(terminal *w.Terminal) *sandboxpolicy.TerminalIngress { + if terminal == nil { + return nil + } + return &sandboxpolicy.TerminalIngress{Port: terminal.Port} +} diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go new file mode 100644 index 000000000..1ed57562c --- /dev/null +++ b/app/cetirun-operator/internal/controller/sandbox_custom_envtest_test.go @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//go:build envtest + +package controller + +import ( + "slices" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxpolicy" + w "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" + appsv1 "k8s.io/api/apps/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/client-go/rest" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func TestCommonCustomTerminalAPIServer(t *testing.T) { + for _, backend := range []api.SandboxType{api.SandboxKata, api.SandboxContainer} { + t.Run(string(backend), func(t *testing.T) { + h := newNativeStartAPIHarnessWithRuntime(t, true, true, corev1.ReadWriteOnce, "custom", backend, nil, + api.AgentPolicyNetwork{Ingress: api.AgentPolicyIngress{Mode: api.AgentPolicyIngressDisabled}}) + h.r.CetiRunHelmValues["ttyd"].(map[string]any)["enabled"] = true + updateContainerPlatformForTest(t, h.r, h.admin, func(document *SandboxPlatformConfiguration) { + platform := document.Platforms[backend] + platform.Topology.KubernetesAPI = []sandboxpolicy.Destination{{ + Peer: sandboxpolicy.Peer{Name: "api", UID: "synthetic-api", IPs: []string{"203.0.113.10"}}, + Ports: []api.AgentPolicyPort{{Port: 6443, Protocol: corev1.ProtocolTCP}}, + }} + document.Platforms[backend] = platform + }) + h = startReconciledAPIHarness(t, h) + expected := reconciledExpectationForTest(t, h.nativeSandboxFixture) + if expected.Terminal == nil || len(expected.Workloads) != 2 { + t.Fatal("served common terminal did not join the protected workload inventory") + } + observed := *h.nativeSandboxFixture + observed.kube = h.admin + for _, workload := range expected.Workloads { + pod := reconciledPodForTest(t, &observed, workload) + pod.Spec.Overhead = nil + h.create(t, pod) + if workload.Kind == "Deployment" { + if pod.Spec.ServiceAccountName != expected.Terminal.ServiceAccountName || + (backend == api.SandboxKata) != (len(pod.Spec.Overhead) != 0) { + t.Fatal("served terminal lost its identity or RuntimeClass overhead") + } + changed := pod.DeepCopy() + changed.ResourceVersion, changed.UID = "", "" + changed.Name += "-changed" + changed.Spec.Volumes = append(changed.Spec.Volumes, corev1.Volume{ + Name: "foreign-home", VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: expected.Home.Name}, + }, + }) + if err := h.admin.Create(h.ctx, changed, client.DryRunAll); err == nil { + t.Fatal("terminal was allowed to mount Agent HOME") + } + } + } + config := rest.CopyConfig(h.localHelm.config) + config.Impersonate = rest.ImpersonationConfig{ + UserName: "system:serviceaccount:" + expected.Namespace.Name + ":" + expected.Terminal.ServiceAccountName, + Groups: []string{"system:serviceaccounts", "system:serviceaccounts:" + expected.Namespace.Name, "system:authenticated"}, + } + reader, err := client.New(config, client.Options{Scheme: h.admin.Scheme()}) + if err != nil { + t.Fatal(err) + } + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Group: api.GroupVersion.Group, Resource: "agents", Verb: "get", Name: h.agent.Name, + }, true) + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Group: api.GroupVersion.Group, Resource: "agents", Verb: "get", Name: "foreign-agent", + }, false) + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Resource: "secrets", Verb: "get", Namespace: expected.Namespace.Name, Name: sandboxRuntimeSecretName(h.agent), + }, false) + }) + } +} + +func TestCommonCustomAPIServer(t *testing.T) { + for _, backend := range []api.SandboxType{api.SandboxKata, api.SandboxContainer} { + for _, endpoint := range []string{"headless", "chat", "web-ui"} { + t.Run(string(backend)+"/"+endpoint, func(t *testing.T) { + mode := corev1.ReadWriteOnce + if endpoint == "headless" { + mode = corev1.ReadWriteOncePod + } + h := newNativeStartAPIHarnessWithRuntime(t, true, true, mode, "custom", backend, nil) + if endpoint != "chat" { + agent := h.current(t) + before := agent.DeepCopy() + if endpoint == "headless" { + agent.Spec.Agent.Port = nil + } else { + agent.Spec.Agent.WebUI = true + } + if err := h.member.Patch(h.ctx, agent, client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})); err != nil { + t.Fatal("served Custom endpoint request:", err) + } + } + h = startReconciledAPIHarness(t, h) + current := h.current(t) + if current.Spec.GatewayTokenSecretRef != "" { + t.Fatal("Custom persisted a caller-controlled runtime Secret reference") + } + expected := reconciledExpectationForTest(t, h.nativeSandboxFixture) + workload := h.workload(t) + main := workload.Spec.Template.Spec.Containers[0] + if len(main.Command) != 0 || len(main.Args) != 0 || !ptr.Deref(main.SecurityContext.RunAsNonRoot, false) || + main.SecurityContext.RunAsUser != nil { + t.Fatal("served Custom template changed the image entrypoint or inherited non-root UID") + } + secret := &corev1.Secret{} + if err := h.admin.Get(h.ctx, client.ObjectKey{ + Namespace: expected.Namespace.Name, Name: sandboxRuntimeSecretName(current), + }, secret); err != nil { + t.Fatal(err) + } + if !hasAgentOwner(secret, current) || len(secret.Data["CETIRUN_AUTH_KEY"]) == 0 { + t.Fatal("runtime authentication was not provisioned into the owned bootstrap Secret") + } + sources := w.PodSourceReferences(workload.Spec.Template.Spec, workload.Namespace) + if slices.ContainsFunc(sources, func(source w.SourceReference) bool { + return source.Kind == "Secret" && source.Name == secret.Name + }) { + t.Fatal("Custom main received its controller-only runtime authentication") + } + var contextSource *corev1.ConfigMap + for _, volume := range workload.Spec.Template.Spec.Volumes { + if volume.Name == "context" && volume.ConfigMap != nil { + contextSource = &corev1.ConfigMap{} + if err := h.admin.Get(h.ctx, client.ObjectKey{Namespace: workload.Namespace, Name: volume.ConfigMap.Name}, contextSource); err != nil { + t.Fatal(err) + } + } + } + if contextSource == nil || !hasAgentOwner(contextSource, current) || !ptr.Deref(contextSource.Immutable, false) || + contextSource.Data["AGENTS.md"] == "" || len(contextSource.Data) != 1 { + t.Fatal("Custom canonical context was not an immutable owned snapshot") + } + config := rest.CopyConfig(h.localHelm.config) + config.Impersonate = rest.ImpersonationConfig{ + UserName: "system:serviceaccount:cetirun-system:cetirun-sandbox-admission", + Groups: []string{"system:serviceaccounts", "system:serviceaccounts:cetirun-system", "system:authenticated"}, + } + reader, err := client.New(config, client.Options{Scheme: h.admin.Scheme()}) + if err != nil { + t.Fatal(err) + } + if err := reader.Get(h.ctx, client.ObjectKeyFromObject(contextSource), &corev1.ConfigMap{}); err != nil { + t.Fatal("admission cannot read its pinned Custom context:", err) + } + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Resource: "configmaps", Verb: "get", Namespace: workload.Namespace, Name: "unrelated-context", + }, false) + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Resource: "secrets", Verb: "get", Namespace: workload.Namespace, Name: secret.Name, + }, true) + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Resource: "secrets", Verb: "get", Namespace: workload.Namespace, Name: "unrelated-secret", + }, false) + h.assertAccess(t, reader, authorizationv1.ResourceAttributes{ + Resource: "secrets", Verb: "list", Namespace: workload.Namespace, + }, false) + service := &corev1.Service{} + if err := h.admin.Get(h.ctx, client.ObjectKeyFromObject(workload), service); err != nil { + t.Fatal(err) + } + if endpoint == "headless" && (service.Spec.ClusterIP != corev1.ClusterIPNone || len(service.Spec.Ports) != 0) { + t.Fatal("headless Custom did not retain its portless governing Service") + } + observed := *h.nativeSandboxFixture + observed.kube = h.admin + pod := reconciledPodForTest(t, &observed, expected.Workloads[0]) + pod.Spec.Overhead = nil + for _, mutate := range []func(*corev1.Pod){ + func(p *corev1.Pod) { p.Spec.Containers[0].Command = []string{"changed"} }, + func(p *corev1.Pod) { p.Spec.Containers[0].SecurityContext.RunAsUser = ptr.To[int64](0) }, + func(p *corev1.Pod) { p.Spec.RuntimeClassName = ptr.To("unapproved-runtime") }, + } { + changed := pod.DeepCopy() + mutate(changed) + if err := h.admin.Create(h.ctx, changed, client.DryRunAll); err == nil { + t.Fatal("served Custom Pod admission accepted a changed runtime contract") + } + } + h.create(t, pod) + h.observeReadyPod(t, pod) + workload = h.workload(t) + workload.Status = appsv1.StatefulSetStatus{ + ObservedGeneration: workload.Generation, Replicas: 1, ReadyReplicas: 1, UpdatedReplicas: 1, + UpdateRevision: workload.Status.UpdateRevision, + } + if err := h.admin.Status().Update(h.ctx, workload); err != nil { + t.Fatal(err) + } + h.reconcileOK(t) + h.reconcileOK(t) + if h.current(t).Status.Phase != api.PhaseReady || !isConditionTrue(h.current(t).Status.Conditions, api.ConditionPolicyApplied) { + t.Fatal("served Custom did not reach current Ready and applied policy") + } + changed := contextSource.DeepCopy() + changed.Data["AGENTS.md"] = "changed" + if err := h.admin.Update(h.ctx, changed); !apierrors.IsInvalid(err) { + t.Fatal("served API allowed immutable context mutation:", err) + } + assertNativeHomeAccessMode(t, h.nativeSandboxFixture, mode) + if err := h.admin.Delete(h.ctx, pod, client.GracePeriodSeconds(0)); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_integrations_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_integrations_test.go new file mode 100644 index 000000000..e29c018b8 --- /dev/null +++ b/app/cetirun-operator/internal/controller/sandbox_custom_integrations_test.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package controller + +import ( + "context" + "reflect" + "slices" + "strings" + "sync" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/internal/registryauth" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +func TestCommonCustomPrivateRegistryUsesItsActualServiceAccount(t *testing.T) { + for _, mode := range []string{"headless", "chat"} { + t.Run(mode, func(t *testing.T) { + f, source := reconciledRegistryFixture(t, "custom", withCommonCustom(t, mode)) + var subjects []string + var subjectsMu sync.Mutex + audit := interceptor.NewClient(f.kube, interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, object client.Object, options ...client.CreateOption) error { + if review, ok := object.(*authorizationv1.SubjectAccessReview); ok { + subjectsMu.Lock() + subjects = append(subjects, review.Spec.User) + subjectsMu.Unlock() + review.Status.Denied = true + return nil + } + return c.Create(ctx, object, options...) + }, + }) + f.r.Client, f.r.APIReader = audit, audit + for range 4 { + f.reconcileOK(t) + } + workload := f.workload(t) + subject := "system:serviceaccount:" + workload.Namespace + ":" + workload.Spec.Template.Spec.ServiceAccountName + if !slices.Contains(subjects, subject) { + t.Fatal("registry isolation checked a different identity from the actual Custom Pod") + } + name, err := registryauth.PullSecretName(f.agent.UID) + if err != nil { + t.Fatal(err) + } + pull := &corev1.Secret{} + if err := f.kube.Get(context.Background(), client.ObjectKey{Namespace: workload.Namespace, Name: name}, pull); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(pull.Data, source.Data) || + !slices.Equal(workload.Spec.Template.Spec.ImagePullSecrets, []corev1.LocalObjectReference{{Name: name}}) { + t.Fatal("Custom lost its owned registry projection") + } + source.Data[corev1.DockerConfigJsonKey], err = registryauth.Encode(*f.current(t).Spec.Agent.Image, + registryauth.Credentials{Username: "example", Password: "rotated-synthetic-token"}) + if err != nil { + t.Fatal(err) + } + if err := f.kube.Update(context.Background(), source); err != nil { + t.Fatal(err) + } + f.reconcileOK(t) + if !reflect.DeepEqual(f.workload(t).Spec, workload.Spec) { + t.Fatal("registry credential rotation restarted Custom") + } + }) + } +} + +func TestCommonCustomCopilotProjectionsUseChartCapabilities(t *testing.T) { + f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, "custom", true, true, withCommonCustom(t, "headless")) + for range 2 { + f.reconcileOK(t) + } + agent := f.current(t) + if agent.Status.AIGateway == nil || agent.Status.AIGateway.Copilot == nil { + t.Fatal("fixture did not prepare a Copilot projection") + } + agent.Annotations[api.AnnotationCopilotSignInGeneration] = "0123abcd" + agent.Annotations[api.AnnotationCopilotModels] = `[{"id":"gpt-5.5","responsesOnly":true}]` + if err := f.kube.Update(context.Background(), agent); err != nil { + t.Fatal(err) + } + agent.Status.AIGateway.Copilot.ProxyKeyID = strings.Repeat("c", 64) + agent.Status.AIGateway.Copilot.Models = []string{"copilot/gpt-5.5"} + if err := f.kube.Status().Update(context.Background(), agent); err != nil { + t.Fatal(err) + } + prepared, err := f.r.prepareReconciledSandbox(context.Background(), f.current(t), nil, nil) + if err != nil { + t.Fatal(err) + } + proxy := prepared.Values["aiGateway"].(map[string]any)["copilotProxy"].(map[string]any) + if proxy[aiGatewayChartProxyKeyValue] != strings.Repeat("c", 64) || + proxy[aiGatewayChartSignInValue] != "0123abcd" || + !reflect.DeepEqual(proxy["responsesModels"], []any{"gpt-5.5"}) { + t.Fatal("Custom omitted the current Copilot key, sign-in or Responses projection:", proxy) + } +} diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go new file mode 100644 index 000000000..e0f0f1422 --- /dev/null +++ b/app/cetirun-operator/internal/controller/sandbox_custom_terminal_test.go @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package controller + +import ( + "context" + "encoding/json" + "strings" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + sandboxadmission "github.com/Azure/CetiRun/app/cetirun-operator/internal/admission" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxpolicy" + "github.com/Azure/CetiRun/app/internal/terminalpolicy" + admissionv1 "k8s.io/api/admission/v1" + appsv1 "k8s.io/api/apps/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func customTerminalFixture(t *testing.T, backend string) *nativeSandboxFixture { + t.Helper() + setup := []func(*AgentReconciler, client.Client){ + withCommonCustom(t, "chat"), withReconciledCoordination(t), + func(r *AgentReconciler, kube client.Client) { + updateContainerPlatformForTest(t, r, kube, func(document *SandboxPlatformConfiguration) { + platform := document.Platforms[api.SandboxKata] + platform.Topology.KubernetesAPI = []sandboxpolicy.Destination{{ + Peer: sandboxpolicy.Peer{Name: "api", UID: "example-api-uid", IPs: []string{"203.0.113.10"}}, + Ports: []api.AgentPolicyPort{{Port: 6443, Protocol: corev1.ProtocolTCP}}, + }} + document.Platforms[api.SandboxKata] = platform + }) + }, + } + if backend == "container" { + setup = append(setup, withContainerRuntime(t)) + } + f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, "custom", true, false, setup...) + f.r.CetiRunHelmValues["ttyd"].(map[string]any)["enabled"] = true + if err := f.kube.Create(context.Background(), &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: instanceNamespace(f.agent.Name), Name: "kube-root-ca.crt"}, + Data: map[string]string{"ca.crt": "synthetic-ca"}, + }); err != nil { + t.Fatal(err) + } + for range 6 { + _, err := f.reconcile() + if err != nil && !strings.Contains(err.Error(), "common Custom terminal is not ready") { + t.Fatal("prepare terminal:", err) + } + terminal := &appsv1.Deployment{} + if err := f.kube.Get(context.Background(), client.ObjectKey{ + Namespace: instanceNamespace(f.agent.Name), Name: terminalpolicy.WorkloadName(instanceServiceName(f.agent.Name)), + }, terminal); err == nil { + return f + } else if client.IgnoreNotFound(err) != nil { + t.Fatal(err) + } + } + t.Fatal("Custom terminal was not created") + return nil +} + +func customTerminalDeployment(t *testing.T, f *nativeSandboxFixture) *appsv1.Deployment { + t.Helper() + deployment := &appsv1.Deployment{} + if err := f.kube.Get(context.Background(), client.ObjectKey{ + Namespace: instanceNamespace(f.agent.Name), Name: terminalpolicy.WorkloadName(instanceServiceName(f.agent.Name)), + }, deployment); err != nil { + t.Fatal(err) + } + return deployment +} + +func readyCustomWorkload(t *testing.T, f *nativeSandboxFixture) { + t.Helper() + main := f.workload(t) + main.Status.ObservedGeneration = main.Generation + main.Status.Replicas, main.Status.ReadyReplicas, main.Status.UpdatedReplicas = 1, 1, 1 + if err := f.kube.Status().Update(context.Background(), main); err != nil { + t.Fatal(err) + } +} + +func TestCommonCustomTerminalReadinessAndSuspension(t *testing.T) { + for _, backend := range []string{"kata", "container"} { + t.Run(backend, func(t *testing.T) { + f := customTerminalFixture(t, backend) + readyCustomWorkload(t, f) + if _, err := f.reconcile(); err == nil || !strings.Contains(err.Error(), "common Custom terminal is not ready") { + t.Fatal("terminal rollout was not reported:", err) + } + if ptr.Deref(f.workload(t).Spec.Replicas, 0) != 1 || ptr.Deref(customTerminalDeployment(t, f).Spec.Replicas, 0) != 1 { + t.Fatal("waiting for the terminal stopped the rollout") + } + terminal := customTerminalDeployment(t, f) + terminal.Status.ObservedGeneration = terminal.Generation + terminal.Status.Replicas, terminal.Status.ReadyReplicas, terminal.Status.AvailableReplicas = 1, 1, 1 + if err := f.kube.Status().Update(context.Background(), terminal); err != nil { + t.Fatal(err) + } + for range 2 { + f.reconcileOK(t) + } + if f.current(t).Status.Phase != api.PhaseReady || !isConditionTrue(f.current(t).Status.Conditions, api.ConditionTerminalConfigured) { + t.Fatal("current terminal did not become available") + } + expected := reconciledExpectationForTest(t, f) + if expected.Terminal == nil || len(expected.Workloads) != 2 { + t.Fatal("terminal was not included in common execution authority") + } + for _, workload := range expected.Workloads { + if workload.Kind == "Deployment" && (backend == "kata") != (len(workload.Overhead) != 0) { + t.Fatal("terminal did not retain the selected RuntimeClass overhead") + } + } + key, stages := f.current(t).Status.AIGateway.KeyID, f.installer.stages + f.reconcileOK(t) + if f.installer.stages != stages { + t.Fatal("steady terminal reconciliation reapplied resources") + } + agent := f.current(t) + agent.Spec.Suspended, agent.Generation = true, agent.Generation+1 + if err := f.kube.Update(context.Background(), agent); err != nil { + t.Fatal(err) + } + if _, err := f.reconcile(); err == nil || !strings.Contains(err.Error(), "waits for acknowledged controller shutdown") { + t.Fatal("suspension did not wait for controller acknowledgement:", err) + } + if ptr.Deref(f.workload(t).Spec.Replicas, -1) != 0 || + ptr.Deref(customTerminalDeployment(t, f).Spec.Replicas, -1) != 0 || + !f.current(t).Status.AIGateway.Blocked || f.current(t).Status.AIGateway.KeyID != key { + t.Fatal("suspension failed to stop both workloads and retain the blocked accounting identity") + } + main := f.workload(t) + main.Status = appsv1.StatefulSetStatus{ObservedGeneration: main.Generation} + if err := f.kube.Status().Update(context.Background(), main); err != nil { + t.Fatal(err) + } + terminal = customTerminalDeployment(t, f) + terminal.Status = appsv1.DeploymentStatus{ObservedGeneration: terminal.Generation} + if err := f.kube.Status().Update(context.Background(), terminal); err != nil { + t.Fatal(err) + } + f.reconcileOK(t) + if f.current(t).Status.Phase != api.PhaseSuspended { + t.Fatal("acknowledged shutdown did not finish retained suspension") + } + }) + } +} + +func TestCommonCustomTerminalConnectUsesRenderedAuthority(t *testing.T) { + ctx := context.Background() + f := customTerminalFixture(t, "kata") + readyCustomWorkload(t, f) + expected := reconciledExpectationForTest(t, f) + var pod *corev1.Pod + for _, workload := range expected.Workloads { + candidate := reconciledPodForTest(t, f, workload) + handler, err := sandboxadmission.NewPodHandler(f.kube, sandboxadmission.PodConfig{ + StateNamespace: f.r.OperatorNamespace, CoordinationConfigMapName: f.r.SandboxNativeCoordination.Identity.Name, + CoordinationConfigMapUID: string(f.r.SandboxNativeCoordination.Identity.UID), + }) + if err != nil { + t.Fatal(err) + } + if response := handler.Validate(ctx, reconciledPodRequest(t, candidate)); !response.Allowed { + t.Fatal("rendered workload failed Pod admission:", response.Result) + } + if workload.Kind == "StatefulSet" { + pod = candidate + } + } + pod.Spec.NodeName = "node-a" + pod.Status = corev1.PodStatus{Phase: corev1.PodRunning, ContainerStatuses: []corev1.ContainerStatus{{ + Name: "cetirun", Ready: true, ContainerID: "containerd://synthetic-main", + State: corev1.ContainerState{Running: &corev1.ContainerStateRunning{}}, + }}} + if err := f.kube.Create(ctx, pod); err != nil { + t.Fatal(err) + } + handler, err := sandboxadmission.NewPodHandler(f.kube, sandboxadmission.PodConfig{ + StateNamespace: f.r.OperatorNamespace, CoordinationConfigMapName: f.r.SandboxNativeCoordination.Identity.Name, + CoordinationConfigMapUID: string(f.r.SandboxNativeCoordination.Identity.UID), + }) + if err != nil { + t.Fatal(err) + } + options, err := json.Marshal(corev1.PodExecOptions{ + Container: "cetirun", Command: []string{"sh", "-i"}, Stdout: true, Stdin: true, TTY: true, + }) + if err != nil { + t.Fatal(err) + } + request := admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: admissionv1.Connect, Namespace: pod.Namespace, Name: pod.Name, SubResource: "exec", RequestSubResource: "exec", + Resource: metav1.GroupVersionResource{Version: "v1", Resource: "pods"}, Object: runtime.RawExtension{Raw: options}, + UserInfo: authenticationv1.UserInfo{Username: "system:serviceaccount:" + pod.Namespace + ":" + expected.Terminal.ServiceAccountName}, + }} + if response := handler.Validate(ctx, request); !response.Allowed { + t.Fatal("current terminal was denied:", response.Result) + } + for _, mutate := range []func(*admission.Request){ + func(r *admission.Request) { + r.UserInfo.Username = "system:serviceaccount:" + pod.Namespace + ":foreign" + }, + func(r *admission.Request) { r.Name = "other-0" }, + func(r *admission.Request) { r.SubResource = "attach" }, + func(r *admission.Request) { r.SubResource = "portforward" }, + func(r *admission.Request) { + r.Object.Raw = []byte(`{"container":"other","command":["sh","-i"],"stdin":true,"stdout":true,"tty":true}`) + }, + func(r *admission.Request) { + r.Object.Raw = []byte(`{"container":"cetirun","command":["sh","-c","id"],"stdout":true}`) + }, + } { + changed := request + mutate(&changed) + if response := handler.Validate(ctx, changed); response.Allowed { + t.Fatal("terminal authority admitted a different caller, target or protocol") + } + } + agent := f.current(t) + agent.Spec.Suspended, agent.Generation = true, agent.Generation+1 + if err := f.kube.Update(ctx, agent); err != nil { + t.Fatal(err) + } + if response := handler.Validate(ctx, request); response.Allowed { + t.Fatal("terminal CONNECT survived a lifecycle change") + } +} diff --git a/app/cetirun-operator/internal/controller/sandbox_custom_test.go b/app/cetirun-operator/internal/controller/sandbox_custom_test.go new file mode 100644 index 000000000..a3ae5af9f --- /dev/null +++ b/app/cetirun-operator/internal/controller/sandbox_custom_test.go @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package controller + +import ( + "context" + "reflect" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/internal/chataccess" + appsv1 "k8s.io/api/apps/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func withCommonCustom(t *testing.T, mode string) func(*AgentReconciler, client.Client) { + t.Helper() + return func(r *AgentReconciler, kube client.Client) { + ctx := context.Background() + agent := &api.Agent{} + if err := kube.Get(ctx, client.ObjectKey{Name: "example"}, agent); err != nil { + t.Fatal(err) + } + agent.Spec.Agent.Type = api.AgentTypeCustom + agent.Spec.Agent.Image = ptr.To("registry.example.com/custom-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + agent.Spec.Agent.Port = ptr.To[int32](8080) + agent.Spec.GatewayTokenSecretRef = "" + if mode == "headless" { + agent.Spec.Agent.Port = nil + } + agent.Spec.Agent.WebUI = mode == "web-ui" + if err := kube.Update(ctx, agent); err != nil { + t.Fatal(err) + } + policy := &api.AgentPolicy{} + if err := kube.Get(ctx, client.ObjectKey{Name: "policy-example"}, policy); err != nil { + t.Fatal(err) + } + policy.Spec.Harnesses.Allowed = []api.AgentType{api.AgentTypeCustom} + if err := kube.Update(ctx, policy); err != nil { + t.Fatal(err) + } + r.CustomBindings = NewKubernetesCustomBindings(r, CustomRuntimeConfig{ + Enabled: true, ApprovedImages: []string{*agent.Spec.Agent.Image}, GatewayImages: []string{*agent.Spec.Agent.Image}, + StorageClass: "unused-legacy-storage", StorageSize: "1Gi", AccessMode: "ReadWriteOnce", FSGroup: 1024, + Context: map[string]string{"AGENTS.md": "unused legacy context", "skills/cetirun-memory/SKILL.md": "synthetic"}, + }) + r.CetiRunHelmValues = map[string]any{"ttyd": map[string]any{ + "enabled": false, "image": map[string]any{ + "repository": "registry.example.com/cetirun-terminal", + "digest": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + }, + }} + r.ChatAccess = chataccess.Config{Enabled: true, Callers: []chataccess.Caller{{ + Namespace: "portal-system", PodLabels: map[string]string{"app": "portal"}, + }}} + } +} + +func TestCommonCustomCreatesReadyWithoutLegacyBindings(t *testing.T) { + for _, mode := range []string{"headless", "chat", "web-ui"} { + for _, container := range []bool{false, true} { + t.Run(mode+map[bool]string{false: "/kata", true: "/container"}[container], func(t *testing.T) { + options := []func(*AgentReconciler, client.Client){withCommonCustom(t, mode)} + if container { + options = append(options, withContainerRuntime(t)) + } + + f, _ := newUnreconciledSandboxRuntimeFixture(t, true, nil, true, "custom", true, false, options...) + for range 5 { + f.reconcileOK(t) + } + workload := f.workload(t) + if len(workload.Spec.VolumeClaimTemplates) != 0 || !ptr.Deref(workload.Spec.Template.Spec.Containers[0].SecurityContext.RunAsNonRoot, false) { + t.Fatal("Custom bypassed common retained storage or non-root constraints") + } + workload.Status.ObservedGeneration = workload.Generation + workload.Status.Replicas, workload.Status.ReadyReplicas, workload.Status.UpdatedReplicas = 1, 1, 1 + if err := f.kube.Status().Update(context.Background(), workload); err != nil { + t.Fatal(err) + } + f.reconcileOK(t) + f.reconcileOK(t) + current := f.current(t) + if current.Status.Phase != api.PhaseReady || !isConditionTrue(current.Status.Conditions, api.ConditionPolicyApplied) { + t.Fatalf("Custom did not reach current Ready: %+v", current.Status) + } + expected := reconciledExpectationForTest(t, f) + if expected.Home.Name != f.r.SandboxPreparation.bootstrap.HomeClaimName { + t.Fatal("Custom used its unrelated legacy HOME configuration") + } + stages, key := f.installer.stages, current.Status.AIGateway.KeyID + before := workload.Spec.DeepCopy() + f.reconcileOK(t) + if f.installer.stages != stages || f.current(t).Status.AIGateway.KeyID != key || + !reflect.DeepEqual(f.workload(t).Spec, *before) { + t.Fatal("unchanged Custom reconciliation replaced workload or accounting identity") + } + }) + } + } +} + +func TestCommonCustomRetainedLifecycle(t *testing.T) { + for _, backend := range []string{"kata", "container"} { + t.Run(backend, func(t *testing.T) { + setup := []func(*AgentReconciler, client.Client){withCommonCustom(t, "headless")} + if backend == "container" { + setup = append(setup, withContainerRuntime(t)) + } + t.Run("restart", func(t *testing.T) { + testReconciledSandboxRetainedRestartForHarnesses(t, []string{"custom"}, setup...) + }) + t.Run("suspend-resume", func(t *testing.T) { + testReconciledSandboxSuspensionForHarnesses(t, []string{"custom"}, setup...) + }) + t.Run("migration", func(t *testing.T) { + testPlannedMigrationRetainsHOMEForHarnesses(t, []string{"custom"}, setup...) + }) + t.Run("deletion", func(t *testing.T) { + testReconciledSandboxDeletionForHarnesses(t, []string{"custom"}, setup...) + }) + }) + } +} + +func TestCommonCustomRejectsUnqualifiedInputsWithoutFallback(t *testing.T) { + for name, change := range map[string]func(*AgentReconciler, client.Client){ + "no approval provider": func(r *AgentReconciler, _ client.Client) { r.CustomBindings = nil }, + "legacy-only executor": func(r *AgentReconciler, _ client.Client) { r.SandboxPreparation.NativeExecution = false }, + "image-owned model mode": func(r *AgentReconciler, _ client.Client) { + r.CustomBindings = NewKubernetesCustomBindings(r, CustomRuntimeConfig{ + Enabled: true, AgentManagedModel: true, + ApprovedImages: []string{"registry.example.com/custom-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, + }) + }, + "desktop": func(_ *AgentReconciler, kube client.Client) { + agent := &api.Agent{} + if err := kube.Get(context.Background(), client.ObjectKey{Name: "example"}, agent); err != nil { + t.Fatal(err) + } + agent.Spec.Helm.Values = map[string]runtime.RawExtension{"desktop": {Raw: []byte(`{"enabled":true}`)}} + if err := kube.Update(context.Background(), agent); err != nil { + t.Fatal(err) + } + }, + } { + t.Run(name, func(t *testing.T) { + f, _ := newUnreconciledSandboxRuntimeFixture(t, true, nil, true, "custom", true, false, + withCommonCustom(t, "chat"), change) + for range 3 { + _, _ = f.reconcile() + } + f.assertNotReady(t) + var workloads appsv1.StatefulSetList + if err := f.kube.List(context.Background(), &workloads); err != nil || len(workloads.Items) != 0 { + t.Fatal("unqualified Custom inputs created compute:", err) + } + if f.installer.stages != 0 { + t.Fatal("unqualified Custom inputs fell back to another executor") + } + }) + } +} diff --git a/app/cetirun-operator/internal/controller/sandbox_home_access_envtest_test.go b/app/cetirun-operator/internal/controller/sandbox_home_access_envtest_test.go index 9a301cfd5..4ad6eac0f 100644 --- a/app/cetirun-operator/internal/controller/sandbox_home_access_envtest_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_home_access_envtest_test.go @@ -40,9 +40,17 @@ func startReconciledAPIHarness(t *testing.T, h *nativeStartAPIHarness) *nativeSt return err } if namespace, ok := object.(*corev1.Namespace); ok { - return h.admin.Create(ctx, &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{ + if err := h.admin.Create(ctx, &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{ Namespace: namespace.Name, Name: "default", - }}) + }}); err != nil { + return err + } + if h.agent.Spec.Agent.Type == api.AgentTypeCustom { + return h.admin.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace.Name, Name: "kube-root-ca.crt"}, + Data: map[string]string{"ca.crt": "synthetic-ca"}, + }) + } } return nil }, diff --git a/app/cetirun-operator/internal/controller/sandbox_kubernetes_prerequisites.go b/app/cetirun-operator/internal/controller/sandbox_kubernetes_prerequisites.go index f537fd780..500bde91a 100644 --- a/app/cetirun-operator/internal/controller/sandbox_kubernetes_prerequisites.go +++ b/app/cetirun-operator/internal/controller/sandbox_kubernetes_prerequisites.go @@ -121,6 +121,9 @@ func (p *KubernetesSandboxPrerequisites) resolveCurrent(ctx context.Context, req if agent.Spec.Agent.Type != api.AgentTypeOpenClaw { source.Helpers.Doctor = false } + if agent.Spec.Agent.Type == api.AgentTypeCustom { + source.Helpers = sandboxworkload.Helpers{} + } if reconciled { if _, err := semver.StrictNewVersion(agent.Spec.Helm.Version); err != nil { return empty, fmt.Errorf("Sandbox reconciliation requires a pinned native chart version") @@ -132,7 +135,7 @@ func (p *KubernetesSandboxPrerequisites) resolveCurrent(ctx context.Context, req } namespaceName := instanceNamespace(agent.Name) if len(validation.IsDNS1123Label(namespaceName)) != 0 || - len(validation.IsDNS1123Subdomain(agent.Spec.GatewayTokenSecretRef)) != 0 { + len(validation.IsDNS1123Subdomain(sandboxRuntimeSecretName(agent))) != 0 { return empty, fmt.Errorf("Sandbox prerequisites require a valid derived namespace and explicit runtime Secret name") } @@ -217,7 +220,7 @@ func (p *KubernetesSandboxPrerequisites) resolveCurrent(ctx context.Context, req return empty, fmt.Errorf("Sandbox skills require a distinct current filesystem PVC without foreign ownership") } secret := &metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Secret"}} - if err := source.readPrerequisite(ctx, client.ObjectKey{Namespace: namespace.Name, Name: agent.Spec.GatewayTokenSecretRef}, secret); err != nil { + if err := source.readPrerequisite(ctx, client.ObjectKey{Namespace: namespace.Name, Name: sandboxRuntimeSecretName(agent)}, secret); err != nil { return empty, err } if !sandboxBuiltinOwned(secret, agent) || !sandboxPrerequisiteOwnersMatch(secret, agent, nil) { diff --git a/app/cetirun-operator/internal/controller/sandbox_native_execution_test.go b/app/cetirun-operator/internal/controller/sandbox_native_execution_test.go index 2ee56d826..8ebf58aad 100644 --- a/app/cetirun-operator/internal/controller/sandbox_native_execution_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_native_execution_test.go @@ -751,6 +751,11 @@ func newUnreconciledSandboxRuntimeFixture(t *testing.T, native bool, skills []st if kind == "hermes" { input.Agent.Spec.Agent.Port = ptr.To[int32](8642) } + if kind == "custom" { + input.Agent.Spec.Agent.Image = ptr.To("registry.example.com/custom-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + input.Agent.Spec.Agent.Port = ptr.To[int32](8080) + input.Agent.Spec.GatewayTokenSecretRef = "" + } input.Agent.Status.Policy = &api.PolicyStatus{} input.Team.Status = api.TeamStatus{ObservedGeneration: 1, Conditions: []metav1.Condition{{ Type: api.ConditionTeamAccepted, Status: metav1.ConditionTrue, ObservedGeneration: 1, diff --git a/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go b/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go index 1668cf384..f932607d7 100644 --- a/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_native_start_envtest_test.go @@ -527,6 +527,20 @@ func newNativeStartAPIHarnessWithRuntime(t *testing.T, admissionNative, coordina if kind == "hermes" { agent.Spec.Agent.Port = ptr.To[int32](8642) } + if kind == "custom" { + agent.Spec.GatewayTokenSecretRef = "" + agent.Spec.Agent.Image = ptr.To("registry.example.com/custom-agent@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + agent.Spec.Agent.Port = ptr.To[int32](8080) + r.CustomBindings = NewKubernetesCustomBindings(r, CustomRuntimeConfig{ + Enabled: true, ApprovedImages: []string{*agent.Spec.Agent.Image}, GatewayImages: []string{*agent.Spec.Agent.Image}, + }) + r.CetiRunHelmValues = map[string]any{"ttyd": map[string]any{ + "enabled": false, "image": map[string]any{ + "repository": "registry.example.com/cetirun-terminal", + "digest": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + }, + }} + } var lastErr error if err := wait.PollUntilContextTimeout(h.ctx, 100*time.Millisecond, 20*time.Second, true, func(ctx context.Context) (bool, error) { probe := agent.DeepCopy() diff --git a/app/cetirun-operator/internal/controller/sandbox_preparation.go b/app/cetirun-operator/internal/controller/sandbox_preparation.go index ac9acf92b..ba0850fb0 100644 --- a/app/cetirun-operator/internal/controller/sandbox_preparation.go +++ b/app/cetirun-operator/internal/controller/sandbox_preparation.go @@ -498,6 +498,45 @@ func sandboxPreparationDigest(value any) (string, error) { } func (r *AgentReconciler) sandboxHelmValues(agent *api.Agent, team *api.Team) (map[string]any, map[string]any, error) { + if agent.Spec.Agent.Type == api.AgentTypeCustom { + if !r.customGatewaySelected(agent) { + return nil, nil, fmt.Errorf("Custom Sandbox execution requires an explicitly Gateway-qualified image") + } + if _, err := r.customOverrides(agent, team); err != nil { + return nil, nil, err + } + base := agent.DeepCopy() + base.Spec.Helm.Values = nil + platform, err := r.customOverrides(base, team) + if err != nil { + return nil, nil, err + } + if err := r.applyAIGatewayValues(platform, agent); err != nil { + return nil, nil, err + } + platform["secrets"] = deepMerge(platform["secrets"], map[string]any{"existingSecret": sandboxRuntimeSecretName(agent)}) + platform["agentType"] = "custom" + platform["agentRequest"] = runtimeRequest(agent, "") + platform["agentRequest"].(map[string]any)["releaseName"] = helmReleaseName(agent.Name) + platform["desktop"] = map[string]any{"enabled": false} + if agent.Spec.RestartRequestID != "" { + platform["podAnnotations"] = deepMerge(platform["podAnnotations"], map[string]any{ + api.AnnotationRestartRequestID: agent.Spec.RestartRequestID, + }) + } + user := map[string]any{} + for name, raw := range agent.Spec.Helm.Values { + var value any + if err := json.Unmarshal(raw.Raw, &value); err != nil { + return nil, nil, fmt.Errorf("invalid Custom Sandbox Helm override %q", name) + } + user[name] = value + } + if desktop, ok := user["desktop"].(map[string]any); ok && desktop["enabled"] == true { + return nil, nil, fmt.Errorf("common Custom desktop requires a qualified helper; use its Web UI, private Chat or terminal") + } + return platform, user, nil + } copy := agent.DeepCopy() copy.Spec.Helm.Values = nil platform, err := buildHelmValues(copy, team, r.DomainSuffix, r.SkillsStorageAccount, r.CetiRunHelmValues, r.ChartRegistry, r.DefaultModel) diff --git a/app/cetirun-operator/internal/controller/sandbox_preparation_access.go b/app/cetirun-operator/internal/controller/sandbox_preparation_access.go index 46e531ad8..ea46e8e69 100644 --- a/app/cetirun-operator/internal/controller/sandbox_preparation_access.go +++ b/app/cetirun-operator/internal/controller/sandbox_preparation_access.go @@ -9,6 +9,7 @@ import ( "slices" api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/ingressmtls" "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandbox" "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxpolicy" "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" @@ -73,6 +74,32 @@ func (r *AgentReconciler) sandboxSourceAccess(attempt *sandboxPreparationAttempt return nil, nil, sandboxpolicy.BindingReference{}, fmt.Errorf("Sandbox admission source access requires an explicit separate platform ServiceAccount") } names := map[string][]string{} + // Pinned bootstrap authentication is rechecked by admission even when the + // Custom main does not mount it. Grant only the approved, exact sources. + for _, source := range attempt.sources { + if source.Kind != "Secret" { + continue + } + matchesTLSReference := func(ref ingressmtls.Reference) bool { + return source.APIVersion == "v1" && source.ValidIdentity() && + source.Namespace == ref.Namespace && source.Name == ref.Name && + source.UID == ref.UID && source.ResourceVersion == ref.ResourceVersion + } + endpointSecret := false + if plan := attempt.input.Controls.IngressMTLS; plan != nil { + if matchesTLSReference(plan.ClientSecret) { + continue // The Gateway client key has its own namespace-scoped read grant. + } + endpointSecret = matchesTLSReference(plan.ServerSecret) + } + approved := slices.Contains(attempt.input.AuthorizedSecrets, source.Name) || + (attempt.input.ImagePullSecret != nil && source.Name == attempt.input.ImagePullSecret.Name && + source.UID == attempt.input.ImagePullSecret.UID) || endpointSecret + if source.APIVersion != "v1" || source.Namespace != attempt.input.Namespace.Name || !source.ValidIdentity() || !approved { + return nil, nil, sandboxpolicy.BindingReference{}, fmt.Errorf("Sandbox source-read grant contains an unapproved Secret source") + } + names["secrets"] = append(names["secrets"], source.Name) + } for _, pod := range pods { for _, source := range sandboxworkload.PodSourceReferences(pod, attempt.input.Namespace.Name) { switch source.Kind { diff --git a/app/cetirun-operator/internal/controller/sandbox_preparation_sources.go b/app/cetirun-operator/internal/controller/sandbox_preparation_sources.go index cadfa67b5..796bd4c93 100644 --- a/app/cetirun-operator/internal/controller/sandbox_preparation_sources.go +++ b/app/cetirun-operator/internal/controller/sandbox_preparation_sources.go @@ -39,7 +39,7 @@ func (r *AgentReconciler) sandboxPreparationInput(ctx context.Context, attempt * if inputs.AgentUID != agent.UID || inputs.AgentGeneration != agent.Generation || inputs.Revision == "" || inputs.ChartVersion == "" || (agent.Spec.Helm.Version != "" && agent.Spec.Helm.Version != inputs.ChartVersion) || inputs.NamespaceUID == "" || inputs.RuntimeSecret.Name == "" || inputs.RuntimeSecret.UID == "" || - agent.Spec.GatewayTokenSecretRef != inputs.RuntimeSecret.Name { + sandboxRuntimeSecretName(agent) != inputs.RuntimeSecret.Name { return fmt.Errorf("Sandbox prerequisites must authorize this Agent generation, chart and runtime Secret") } namespace := &corev1.Namespace{} @@ -118,6 +118,11 @@ func (r *AgentReconciler) sandboxPreparationInput(ctx context.Context, attempt * Home: home, Skills: skills, SkillsMode: inputs.SkillsMode, RuntimeClass: runtimeClass, Helpers: inputs.Helpers, AuthorizedSecrets: []string{inputs.RuntimeSecret.Name}, } + if agent.Spec.Agent.Type == api.AgentTypeCustom { + if err := r.configureCustomSandboxInput(ctx, attempt); err != nil { + return err + } + } if state := agent.Status.PlannedMigration; state.CanStart() { attempt.input.PlannedMigration = &state.PlannedMigrationRequest } @@ -135,11 +140,7 @@ func (r *AgentReconciler) sandboxPreparationInput(ctx context.Context, attempt * ) attempt.sources = append(attempt.sources, inputs.PublicationSources...) if config.NativeExecution { - suspendedProjection := attempt.reconciled && agent.Spec.Suspended && agent.Status.AIGateway != nil && - agent.Status.Policy != nil && agent.Status.AIGateway.Phase == api.AIGatewayPhaseReady && - agent.Status.AIGateway.Blocked && agent.Status.AIGateway.Reason == aiGatewayReasonSuspended && - agent.Status.AIGateway.PolicyRevision == agent.Status.Policy.Enforcement.Gateway.DesiredRevision - if !sandboxGatewayProjectionReady(agent) && !suspendedProjection { + if !sandboxGatewayProjectionReady(agent) && !(attempt.reconciled && sandboxGatewayProjectionReadyForLifecycle(agent)) { return fmt.Errorf("%w: current Gateway projection is required for native execution", sandboxpolicy.ErrUnavailable) } key := &corev1.Secret{} diff --git a/app/cetirun-operator/internal/controller/sandbox_reconcile.go b/app/cetirun-operator/internal/controller/sandbox_reconcile.go index b4a4a9e04..8044a9710 100644 --- a/app/cetirun-operator/internal/controller/sandbox_reconcile.go +++ b/app/cetirun-operator/internal/controller/sandbox_reconcile.go @@ -42,7 +42,7 @@ const ( ) func (r *AgentReconciler) usesReconciledSandbox(ctx context.Context, agent *api.Agent) (bool, error) { - if !sandboxRequested(agent, nil) || agent.Spec.Agent.Type == api.AgentTypeCustom || + if !sandboxRequested(agent, nil) || r.SandboxPreparation == nil || !r.SandboxPreparation.NativeExecution || controllerutil.ContainsFinalizer(agent, sandbox.PreparationFinalizer) { return false, nil @@ -109,6 +109,17 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a if err := r.sandboxPreparationInput(ctx, attempt); err != nil { return nil, err } + if attempt.input.Terminal != nil && !attempt.agent.Spec.Suspended { + if err := r.ensureTerminalReadRoles(ctx, attempt.agent); err != nil { + return nil, err + } + if err := r.ensureCommonTerminalReaderBinding(ctx, attempt.agent); err != nil { + return nil, err + } + } + if attempt.input.CustomAgent != nil { + agent = attempt.agent + } if err := r.sandboxIngressMTLSInputs(ctx, attempt); err != nil { return nil, fmt.Errorf("%w: %w", errSandboxIngressMTLS, err) } @@ -137,13 +148,24 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a attempt.input.ImagePullSecret = &w.ObjectIdentity{Name: secret.Name, UID: secret.UID} attempt.sources = append(attempt.sources, sandboxSource(secret, "v1", "Secret")) } - _, user, err := r.sandboxHelmValues(agent, attempt.team) + platformValues, user, err := r.sandboxHelmValues(agent, attempt.team) if err != nil { return nil, err } if err := w.ValidateReconciledUserValues(user, attempt.input.AuthorizedSecrets); err != nil { return nil, err } + if attempt.input.CustomAgent != nil { + values = platformValues + if len(user) != 0 { + values = deepMerge(values, user).(map[string]any) + } + values["memoryOptions"] = r.memoryOptions() + if agent.Spec.Suspended { + values["replicaCount"] = 0 + values["ttyd"] = map[string]any{"enabled": false} + } + } configuration, ok := r.SandboxPreparation.Configuration.(*sandboxplatform.KubernetesSource) if !ok { return nil, fmt.Errorf("common Sandbox reconciliation requires the configured Kubernetes authority") @@ -160,10 +182,15 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a return nil, err } platform := attempt.configuration.Platforms[attempt.resolution.Sandbox.Type] + var customIngress *sandboxpolicy.CustomIngress + if attempt.input.CustomAgent != nil { + customIngress = r.customSandboxIngress(agent) + } attempt.plan, err = sandboxpolicy.Compile(sandboxpolicy.CompileInput{ ConnectionsMCP: connections, NativeExecution: true, Resolution: *attempt.resolution, AgentName: agent.Name, Namespace: attempt.input.Namespace.Name, ServiceName: attempt.input.WorkloadName, Platform: platform, + CustomIngress: customIngress, TerminalIngress: terminalSandboxIngress(attempt.input.Terminal), }) if err != nil { return nil, err @@ -176,6 +203,15 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a if err != nil { return nil, err } + if prepared == nil { + prepared, err = r.SandboxPreparation.Installer.PrepareSandbox(attempt.input.Namespace.Name, values, nil, agent.Spec.Helm.Version, bundle) + if err != nil { + return nil, err + } + } + if attempt.input.CustomAgent != nil { + r.applyCopilotChartValues(values, agent, prepared) + } sources := selectedSandboxExecutionSources(attempt.sources, attempt.resolution.Binding) agentSource, err := w.AgentSourceReference(agent) if err != nil { @@ -337,7 +373,9 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a return nil, err } defaultAccount := source.Kind == "ServiceAccount" && source.Name == "default" - if (!defaultAccount && !sandboxBuiltinOwned(object, agent)) || !object.DeletionTimestamp.IsZero() { + terminalCA := attempt.input.Terminal != nil && source.Kind == "ConfigMap" && + source.Name == "kube-root-ca.crt" && source.Namespace == expected.Namespace.Name + if (!defaultAccount && !terminalCA && !sandboxBuiltinOwned(object, agent)) || !object.DeletionTimestamp.IsZero() { return nil, fmt.Errorf("Sandbox component source is not owned by the current Agent") } source = sandboxSource(object, "v1", source.Kind) @@ -500,6 +538,37 @@ func (r *AgentReconciler) prepareReconciledSandbox(ctx context.Context, agent *a return result, guard(ctx) } +func (r *AgentReconciler) readReconciledSandboxExpectation(ctx context.Context, agent *api.Agent) (*corev1.ConfigMap, w.ReconcileExpectation, error) { + var empty w.ReconcileExpectation + namespace := &corev1.Namespace{} + if err := r.customReader().Get(ctx, client.ObjectKey{Name: instanceNamespace(agent.Name)}, namespace); err != nil { + return nil, empty, err + } + if !sandboxBuiltinOwned(namespace, agent) || !namespace.DeletionTimestamp.IsZero() { + return nil, empty, fmt.Errorf("common Sandbox namespace is not current and owned") + } + state := &corev1.ConfigMap{} + if err := r.customReader().Get(ctx, client.ObjectKey{ + Namespace: r.OperatorNamespace, Name: w.PodExpectationName(namespace.Name, namespace.UID), + }, state); err != nil { + return nil, empty, err + } + if state.Annotations[w.AgentUIDAnnotation] != string(agent.UID) || + !reflect.DeepEqual(state.OwnerReferences, []metav1.OwnerReference{w.AgentOwner(agent.Name, agent.UID)}) { + return nil, empty, fmt.Errorf("common Sandbox expectation ownership changed") + } + expected, err := w.ReadReconcileExpectation(state) + if err != nil { + return nil, empty, err + } + if expected.Agent != (w.ObjectIdentity{Name: agent.Name, UID: agent.UID}) || + expected.AgentGeneration != agent.Generation || + expected.Namespace != (w.ObjectIdentity{Name: namespace.Name, UID: namespace.UID}) { + return nil, empty, fmt.Errorf("common Sandbox expectation differs from the current Agent") + } + return state, expected, nil +} + func (r *AgentReconciler) observeReconciledSandbox(ctx context.Context, agent *api.Agent, prepared *helm.PreparedRelease) error { expected, err := prepared.ReconcileExpectation() if err != nil { diff --git a/app/cetirun-operator/internal/controller/sandbox_reconcile_test.go b/app/cetirun-operator/internal/controller/sandbox_reconcile_test.go index 7e943dcd7..f32d956cb 100644 --- a/app/cetirun-operator/internal/controller/sandbox_reconcile_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_reconcile_test.go @@ -453,7 +453,11 @@ func TestReconciledSandboxSuspensionKeepsHomeAndKey(t *testing.T) { } func testReconciledSandboxSuspension(t *testing.T, setup ...func(*AgentReconciler, client.Client)) { - for _, kind := range []string{"openclaw", "hermes"} { + testReconciledSandboxSuspensionForHarnesses(t, []string{"openclaw", "hermes"}, setup...) +} + +func testReconciledSandboxSuspensionForHarnesses(t *testing.T, harnesses []string, setup ...func(*AgentReconciler, client.Client)) { + for _, kind := range harnesses { for _, mode := range []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOncePod, corev1.ReadWriteOnce} { t.Run(fmt.Sprintf("%s/%s", kind, mode), func(t *testing.T) { f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, kind, true, true, @@ -510,7 +514,11 @@ func TestReconciledSandboxRetainedRestartUsesCommonApply(t *testing.T) { } func testReconciledSandboxRetainedRestart(t *testing.T, setup ...func(*AgentReconciler, client.Client)) { - for _, kind := range []string{"openclaw", "hermes"} { + testReconciledSandboxRetainedRestartForHarnesses(t, []string{"openclaw", "hermes"}, setup...) +} + +func testReconciledSandboxRetainedRestartForHarnesses(t *testing.T, harnesses []string, setup ...func(*AgentReconciler, client.Client)) { + for _, kind := range harnesses { for _, mode := range []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOncePod, corev1.ReadWriteOnce} { t.Run(fmt.Sprintf("%s/%s", kind, mode), func(t *testing.T) { f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, kind, true, false, @@ -1116,12 +1124,16 @@ func TestReconciledSandboxDeletionCancelsBeforeFirstApply(t *testing.T) { } func TestReconciledSandboxDeletionReleasesGrantJournal(t *testing.T) { - for _, kind := range []string{"openclaw", "hermes"} { + testReconciledSandboxDeletionForHarnesses(t, []string{"openclaw", "hermes"}) +} + +func testReconciledSandboxDeletionForHarnesses(t *testing.T, harnesses []string, setup ...func(*AgentReconciler, client.Client)) { + for _, kind := range harnesses { for _, foreground := range []bool{false, true} { for _, sourcesEnabled := range []bool{false, true} { t.Run(fmt.Sprintf("%s/foreground=%t/sources=%t", kind, foreground, sourcesEnabled), func(t *testing.T) { ctx := context.Background() - f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, kind, true, true) + f := newSandboxRuntimeFixtureForAgent(t, true, nil, true, kind, true, true, setup...) agent := f.current(t) journal := &corev1.ConfigMap{} journalKey := client.ObjectKey{Namespace: f.r.OperatorNamespace, Name: sandboxpolicy.GrantJournalName(agent.UID)} diff --git a/app/cetirun-operator/internal/controller/sandbox_registry_test.go b/app/cetirun-operator/internal/controller/sandbox_registry_test.go index b19c11ab6..de4872fe4 100644 --- a/app/cetirun-operator/internal/controller/sandbox_registry_test.go +++ b/app/cetirun-operator/internal/controller/sandbox_registry_test.go @@ -18,9 +18,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -func reconciledRegistryFixture(t *testing.T, kind string) (*nativeSandboxFixture, *corev1.Secret) { +func reconciledRegistryFixture(t *testing.T, kind string, setup ...func(*AgentReconciler, client.Client)) (*nativeSandboxFixture, *corev1.Secret) { t.Helper() - f, _ := newUnreconciledSandboxRuntimeFixture(t, true, nil, true, kind, true, false) + f, _ := newUnreconciledSandboxRuntimeFixture(t, true, nil, true, kind, true, false, setup...) ctx := context.Background() agent := f.current(t) agent.Spec.Agent.RegistrySecretRef = &api.RegistrySecretRef{Name: "registry-source-example"} diff --git a/app/cetirun-operator/internal/helm/agent.go b/app/cetirun-operator/internal/helm/agent.go index ed35901ea..de618cab8 100644 --- a/app/cetirun-operator/internal/helm/agent.go +++ b/app/cetirun-operator/internal/helm/agent.go @@ -162,13 +162,13 @@ func prepareChart(chrt *chart.Chart, input map[string]any, validateRender bool) if input[sandboxworkload.ValuesKey] != nil { return nil, fmt.Errorf("sandboxWorkload is reserved for the protected Sandbox renderer") } + if input["runtime"] != nil { + return nil, fmt.Errorf("runtime is reserved for the platform") + } return prepareRuntimeChart(chrt, input, validateRender) } func prepareRuntimeChart(chrt *chart.Chart, input map[string]any, validateRender bool) (*PreparedRelease, error) { - if input["runtime"] != nil { - return nil, fmt.Errorf("runtime is reserved for the platform") - } var request AgentRequest requestJSON, err := json.Marshal(input["agentRequest"]) if err != nil { @@ -185,10 +185,14 @@ func prepareRuntimeChart(chrt *chart.Chart, input map[string]any, validateRender return nil, err } descriptor := harness.Describe() - if descriptor.Type == "custom" { + if descriptor.Type == "custom" && input[sandboxworkload.ValuesKey] == nil { return prepareCustomChart(chrt, input, request, validateRender) } - if memory, configured, err := resolveMemory(input, chrt, "/home/vibe"); err != nil { + memoryHome := "/home/vibe" + if descriptor.Type == "custom" { + memoryHome = text(object(object(input["runtime"])["agent"])["home"]) + } + if memory, configured, err := resolveMemory(input, chrt, memoryHome); err != nil { return nil, err } else if configured { inputCopy := make(map[string]any, len(input)) @@ -202,6 +206,9 @@ func prepareRuntimeChart(chrt *chart.Chart, input map[string]any, validateRender } input = inputCopy } + if descriptor.Type == "custom" { + return prepareSandboxCustomChart(chrt, input) + } profile, err := loadRuntimeProfile(chrt, descriptor, request.Registry) if err != nil { return nil, err diff --git a/app/cetirun-operator/internal/helm/client.go b/app/cetirun-operator/internal/helm/client.go index 004dde15b..28a11fdc0 100644 --- a/app/cetirun-operator/internal/helm/client.go +++ b/app/cetirun-operator/internal/helm/client.go @@ -246,11 +246,14 @@ func (c *Client) installOrUpgrade(namespace, releaseName string, prepared *Prepa return sandboxworkload.ErrExecutionHeld } if prepared.sandboxReconcile != nil { + if prepared.sandboxBundle == nil || namespace != prepared.sandboxBundle.Identity().Namespace.Name || + releaseName != prepared.sandboxBundle.Identity().ReleaseName { + return fmt.Errorf("Sandbox namespace or release mismatch") + } if err := prepared.CheckSandboxApply(context.Background()); err != nil { return err } - } - if err := prepared.ValidateCustom(namespace, releaseName); err != nil { + } else if err := prepared.ValidateCustom(namespace, releaseName); err != nil { return err } if prepared.custom && !prepared.apiValidated { diff --git a/app/cetirun-operator/internal/helm/sandbox.go b/app/cetirun-operator/internal/helm/sandbox.go index d835dd0ab..cf7547ffb 100644 --- a/app/cetirun-operator/internal/helm/sandbox.go +++ b/app/cetirun-operator/internal/helm/sandbox.go @@ -186,6 +186,12 @@ func (p *PreparedRelease) prepareAndValidateSandboxRender() error { Home: sandboxworkload.ObjectIdentity{Name: input.Home.Name, UID: input.Home.UID}, Controls: slices.Clone(input.Controls.Objects), } + terminalValues := object(object(p.Values[sandboxworkload.ValuesKey])["terminal"]) + if terminal := input.Terminal; terminal != nil && terminalValues["enabled"] == true { + p.sandboxReconcile.Terminal = &sandboxworkload.TerminalTarget{ + ServiceAccountName: terminal.ServiceAccountName, TargetWorkload: input.WorkloadName, Container: "cetirun", + } + } } values, err := chartutil.ToRenderValues(p.chart, p.Values, chartutil.ReleaseOptions{ Name: input.ReleaseName, Namespace: input.Namespace.Name, IsInstall: true, Revision: 1, @@ -273,7 +279,7 @@ func (p *PreparedRelease) prepareAndValidateSandboxRender() error { if err := validate(object); err != nil { return err } - if input.Reconciled && (object.GetKind() == "ConfigMap" || object.GetKind() == "ServiceAccount" || object.GetKind() == "NetworkPolicy" || object.GetKind() == "Service") { + if input.Reconciled && (object.GetKind() == "ConfigMap" || object.GetKind() == "ServiceAccount" || object.GetKind() == "NetworkPolicy" || object.GetKind() == "Service" || object.GetKind() == "RoleBinding") { p.sandboxReconcile.Controls = append(p.sandboxReconcile.Controls, *object.DeepCopy()) } native[object.GetKind()] = true diff --git a/app/cetirun-operator/internal/helm/sandbox_custom.go b/app/cetirun-operator/internal/helm/sandbox_custom.go new file mode 100644 index 000000000..f21f6e10f --- /dev/null +++ b/app/cetirun-operator/internal/helm/sandbox_custom.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package helm + +import ( + "fmt" + + "github.com/Azure/CetiRun/app/cetirun-operator/internal/agents" + w "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" + "helm.sh/helm/v3/pkg/chart" + "k8s.io/utils/ptr" +) + +func prepareSandboxCustomChart(chrt *chart.Chart, input map[string]any) (*PreparedRelease, error) { + values, err := prepareRuntimeValues(chrt, input) + if err != nil { + return nil, err + } + protected := object(values[w.ValuesKey]) + runtime := object(values["runtime"]) + identity := object(runtime["agent"]) + request := agents.Request{ + Type: "custom", Image: text(identity["image"]), Username: text(identity["username"]), + WebUI: identity["webUI"] == true, + } + if raw, present := identity["port"]; present && raw != nil { + request.Port = ptr.To(number(raw)) + } + agent, err := agents.ResolveCustom(request) + if err != nil { + return nil, err + } + if values["agentType"] != "custom" || protected["reconciled"] != true || + text(identity["home"]) != agent.HomeDir || text(object(runtime["model"])["apiBase"]) == "" || + text(object(runtime["model"])["keySecretName"]) == "" || text(object(runtime["model"])["keySecretKey"]) != "api-key" { + return nil, fmt.Errorf("Custom requires a complete reconciled Sandbox runtime contribution") + } + return &PreparedRelease{Values: values, Agent: agent, ChartVersion: chrt.Metadata.Version, chart: chrt}, nil +} diff --git a/app/cetirun-operator/internal/helm/sandbox_custom_test.go b/app/cetirun-operator/internal/helm/sandbox_custom_test.go new file mode 100644 index 000000000..295240588 --- /dev/null +++ b/app/cetirun-operator/internal/helm/sandbox_custom_test.go @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package helm + +import ( + "slices" + "strings" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + w "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload" + "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxworkload/testfixture" + corev1 "k8s.io/api/core/v1" + "k8s.io/utils/ptr" +) + +func customSandboxRenderInput(port *int32, webUI bool) (w.Input, map[string]any) { + fixture := testfixture.New("openclaw") + input := fixture.Input + input.AgentType, input.Reconciled = "custom", true + input.Helpers = w.Helpers{} + input.Skills, input.SkillsMode = nil, w.SkillsModeEmpty + input.Resolution.AgentPolicy.Harnesses.Allowed = append(input.Resolution.AgentPolicy.Harnesses.Allowed, api.AgentTypeCustom) + input.GatewayKey = &w.ObjectIdentity{Name: "gateway-key", UID: "key-uid"} + input.AuthorizedSecrets = append(input.AuthorizedSecrets, input.GatewayKey.Name) + input.GatewayAPIBase = "http://gateway.example.svc.cluster.local:4000/v1" + custom := &w.CustomAgent{ + Image: "registry.example.com/worker@sha256:" + strings.Repeat("a", 64), + Username: "worker", Home: "/home/worker", Port: port, WebUI: webUI, + Environment: []w.CustomEnvironment{ + {Name: "HOME", Value: "/home/worker"}, + {Name: "OPENAI_BASE_URL", Value: input.GatewayAPIBase}, + {Name: "OPENAI_API_KEY", CredentialSlot: "model"}, + }, + } + if port != nil { + custom.Environment = append(custom.Environment, w.CustomEnvironment{Name: "PORT", Value: "8080"}) + custom.Ports = []w.CustomPort{{Name: "http", Number: *port}} + custom.HTTP = &w.CustomHTTP{PortName: "http", HealthPath: "/healthz", ReadinessPath: "/healthz", StartupPath: "/healthz"} + input.LoopbackProbe = &w.LoopbackProbe{Image: "registry.example.com/cetirun-terminal@sha256:" + strings.Repeat("b", 64)} + } + if webUI { + custom.WebBasePath, custom.WebInstance = "/ui/example/", "agent-uid" + custom.Environment = append(custom.Environment, + w.CustomEnvironment{Name: "CETIRUN_WEB_BASE_PATH", Value: custom.WebBasePath}, + w.CustomEnvironment{Name: "CETIRUN_WEB_INSTANCE", Value: custom.WebInstance}) + } else if custom.HTTP != nil { + custom.HTTP.ChatPath, custom.HTTP.ModelsPath = "/v1/chat/completions", "/v1/models" + } + input.CustomAgent = custom + input.Context = &w.Context{ObjectIdentity: w.ObjectIdentity{Name: "custom-context-example", UID: "context-uid"}, + Files: map[string]string{"AGENTS.md": "AGENTS.md"}} + values := sampleInput("custom", "openai", false) + values["agentRequest"] = map[string]any{"type": "custom", "image": custom.Image} + values["secrets"] = map[string]any{"existingSecret": "runtime-secret"} + values["aiGateway"] = map[string]any{ + "enabled": true, "keySecretName": input.GatewayKey.Name, "keySecretKey": "api-key", + "models": []any{map[string]any{"id": "example-model", "name": "Example"}}, + } + values["ttyd"] = map[string]any{"enabled": false} + values["desktop"] = map[string]any{"enabled": false} + return input, values +} + +func TestCustomSandboxRenderPreservesHarnessAndGatewayContract(t *testing.T) { + for _, scenario := range []string{"headless", "chat", "web-ui"} { + t.Run(scenario, func(t *testing.T) { + var port *int32 + if scenario != "headless" { + port = ptr.To[int32](8080) + } + input, values := customSandboxRenderInput(port, scenario == "web-ui") + bundle, err := w.Build(input) + if err != nil { + t.Fatal(err) + } + prepared, err := PrepareSandboxChart(testChart(t), values, nil, bundle) + if err != nil { + t.Fatal(err) + } + template, err := prepared.SandboxTemplate() + if err != nil { + t.Fatal(err) + } + main := template.Spec.Containers[0] + if len(main.Command) != 0 || len(main.Args) != 0 || main.Image != input.CustomAgent.Image || + main.SecurityContext.RunAsUser != nil || template.Spec.SecurityContext.RunAsUser != nil || + !ptr.Deref(main.SecurityContext.RunAsNonRoot, false) { + t.Fatal("Custom rendering changed its approved image entrypoint or non-root image user") + } + if !slices.ContainsFunc(main.Env, func(value corev1.EnvVar) bool { + return value.Name == "OPENAI_API_KEY" && value.ValueFrom != nil && value.ValueFrom.SecretKeyRef != nil && + value.ValueFrom.SecretKeyRef.Name == input.GatewayKey.Name && value.ValueFrom.SecretKeyRef.Key == "api-key" + }) { + t.Fatal("Custom did not receive only its approved Gateway key") + } + if !slices.ContainsFunc(main.VolumeMounts, func(mount corev1.VolumeMount) bool { + return mount.Name == "context-view" && mount.MountPath == "/home/worker/.agents" && mount.ReadOnly + }) { + t.Fatal("Custom did not receive its canonical read-only context") + } + for _, mutate := range []func(*corev1.PodTemplateSpec){ + func(p *corev1.PodTemplateSpec) { p.Spec.Containers[0].Command = []string{"/bin/sh"} }, + func(p *corev1.PodTemplateSpec) { p.Spec.Containers[0].SecurityContext.RunAsUser = ptr.To[int64](0) }, + func(p *corev1.PodTemplateSpec) { + p.Spec.Containers[0].Env[2].ValueFrom.SecretKeyRef.Name = "foreign-key" + }, + } { + bad := template.DeepCopy() + mutate(bad) + if err := bundle.ValidateReconciledTemplate(bad, prepared.Agent.Image, false); err == nil { + t.Fatal("Custom render validation accepted a changed runtime contract") + } + } + }) + } +} diff --git a/app/cetirun-operator/internal/helm/sandbox_reconcile.go b/app/cetirun-operator/internal/helm/sandbox_reconcile.go index 398ab9531..ceb3b5acb 100644 --- a/app/cetirun-operator/internal/helm/sandbox_reconcile.go +++ b/app/cetirun-operator/internal/helm/sandbox_reconcile.go @@ -45,7 +45,8 @@ func (p *PreparedRelease) validateReconciledObject(object unstructured.Unstructu stateful.Spec.ServiceName != stateful.Name || stateful.Spec.Selector == nil { return fmt.Errorf("reconciled Sandbox must use the owned Agent workload and existing HOME") } - if err := p.sandboxBundle.ValidateReconciledTemplate(&stateful.Spec.Template, p.Agent.Image); err != nil { + memory, _ := p.Values["memoryContext"].(map[string]any) + if err := p.sandboxBundle.ValidateReconciledTemplate(&stateful.Spec.Template, p.Agent.Image, memory["enabled"] == true); err != nil { return err } if request := input.PlannedMigration; request != nil { @@ -88,7 +89,12 @@ func (p *PreparedRelease) validateReconciledObject(object unstructured.Unstructu len(spec.Containers) == 0 || deployment.Spec.Selector == nil { return fmt.Errorf("Sandbox auxiliary workload has unapproved host or identity access") } - if err := w.ValidateReconciledVolumes(spec, nil, nil, input.Resolution.Sandbox.Storage.Scratch.SizeLimit); err != nil { + terminal := input.Terminal != nil && deployment.Name == input.Terminal.ServiceAccountName + if terminal { + if err := p.validateTerminalDeployment(&deployment); err != nil { + return err + } + } else if err := w.ValidateReconciledVolumes(spec, nil, nil, input.Resolution.Sandbox.Storage.Scratch.SizeLimit); err != nil { return err } for _, source := range w.PodSourceReferences(spec, input.Namespace.Name) { @@ -113,6 +119,9 @@ func (p *PreparedRelease) validateReconciledObject(object unstructured.Unstructu Kind: "Deployment", Identity: w.ObjectIdentity{Name: deployment.Name}, Replicas: ptr.Deref(deployment.Spec.Replicas, 1), Template: deployment.Spec.Template, } + if terminal { + workload.Overhead = p.sandboxBundle.Overhead() + } case "v1/Service": var service corev1.Service if err := decodeObject(object.Object, &service); err != nil { @@ -136,6 +145,10 @@ func (p *PreparedRelease) validateReconciledObject(object unstructured.Unstructu return err } } + case "rbac.authorization.k8s.io/v1/RoleBinding": + if err := p.validateTerminalRoleBinding(object); err != nil { + return err + } case "v1/ConfigMap", "v1/ServiceAccount", "networking.k8s.io/v1/NetworkPolicy", "networking.istio.io/v1beta1/Sidecar", "security.istio.io/v1beta1/AuthorizationPolicy", "security.istio.io/v1beta1/PeerAuthentication": diff --git a/app/cetirun-operator/internal/helm/sandbox_reconcile_test.go b/app/cetirun-operator/internal/helm/sandbox_reconcile_test.go index 520c0221b..48b248061 100644 --- a/app/cetirun-operator/internal/helm/sandbox_reconcile_test.go +++ b/app/cetirun-operator/internal/helm/sandbox_reconcile_test.go @@ -223,7 +223,7 @@ func TestReconciledSandboxPullSecretIsKubeletOnly(t *testing.T) { changed := template.DeepCopy() mutate(changed) before := changed.DeepCopy() - if err := bundle.ValidateReconciledTemplate(changed, prepared.Agent.Image); err == nil { + if err := bundle.ValidateReconciledTemplate(changed, prepared.Agent.Image, false); err == nil { t.Fatal("pull credential escaped its approved kubelet-only use") } if !equality.Semantic.DeepEqual(changed, before) { diff --git a/app/cetirun-operator/internal/helm/sandbox_terminal.go b/app/cetirun-operator/internal/helm/sandbox_terminal.go new file mode 100644 index 000000000..877e9d1b2 --- /dev/null +++ b/app/cetirun-operator/internal/helm/sandbox_terminal.go @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package helm + +import ( + "fmt" + "slices" + "strconv" + + "github.com/Azure/CetiRun/app/cetirun-operator/internal/terminal" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/utils/ptr" +) + +func (p *PreparedRelease) validateTerminalRoleBinding(object unstructured.Unstructured) error { + input := p.sandboxBundle.Identity() + terminalInput := input.Terminal + if terminalInput == nil { + return fmt.Errorf("Sandbox RoleBindings require a platform terminal plan") + } + var binding rbacv1.RoleBinding + if err := decodeObject(object.Object, &binding); err != nil { + return err + } + account := terminalInput.ServiceAccountName + if binding.Namespace != input.Namespace.Name || len(binding.Subjects) != 1 || + binding.Subjects[0] != (rbacv1.Subject{Kind: "ServiceAccount", Name: account, Namespace: input.Namespace.Name}) { + return fmt.Errorf("Sandbox terminal RoleBinding subject differs from the platform plan") + } + want := rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "Role", Name: account} + switch binding.Name { + case account: + case account + "-exec": + want = rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: terminal.ExecRole} + default: + return fmt.Errorf("Sandbox RoleBinding is not an approved terminal binding") + } + if binding.RoleRef != want { + return fmt.Errorf("Sandbox terminal RoleBinding role differs from the platform plan") + } + return nil +} + +func (p *PreparedRelease) validateTerminalDeployment(deployment *appsv1.Deployment) error { + input := p.sandboxBundle.Identity() + settings := input.Terminal + if settings == nil || deployment.Name != settings.ServiceAccountName || deployment.Spec.Strategy.Type != appsv1.RecreateDeploymentStrategyType || + deployment.Spec.Selector == nil || ptr.Deref(deployment.Spec.Replicas, 0) != 1 { + return fmt.Errorf("Sandbox terminal deployment differs from its platform plan") + } + labels := map[string]string{ + "app.kubernetes.io/name": "cetirun-terminal", "app.kubernetes.io/instance": p.releaseName, + "cetirun.microsoft.com/terminal": "true", + "sandbox.cetirun.microsoft.com/agent-uid": string(input.Resolution.Binding.AgentUID), + } + spec := deployment.Spec.Template.Spec + var selectors map[string]string + var tolerations []corev1.Toleration + if input.RuntimeClass.Scheduling != nil { + selectors, tolerations = input.RuntimeClass.Scheduling.NodeSelector, input.RuntimeClass.Scheduling.Tolerations + } + podSecurity := &corev1.PodSecurityContext{ + RunAsUser: ptr.To[int64](65532), RunAsGroup: ptr.To[int64](65532), RunAsNonRoot: ptr.To(true), + FSGroup: ptr.To[int64](65532), FSGroupChangePolicy: ptr.To(corev1.FSGroupChangeOnRootMismatch), + SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, + } + if !equality.Semantic.DeepEqual(deployment.Spec.Selector.MatchLabels, labels) || !equality.Semantic.DeepEqual(deployment.Spec.Template.Labels, labels) || + deployment.Spec.Selector.MatchExpressions != nil || spec.ServiceAccountName != settings.ServiceAccountName || + ptr.Deref(spec.AutomountServiceAccountToken, true) || ptr.Deref(spec.EnableServiceLinks, true) || + ptr.Deref(spec.RuntimeClassName, "") != input.RuntimeClass.Name || spec.DNSPolicy != corev1.DNSNone || + !equality.Semantic.DeepEqual(spec.DNSConfig, p.sandboxBundle.DNSConfig()) || len(spec.InitContainers) != 0 || len(spec.Containers) != 1 || + len(spec.ImagePullSecrets) != 0 || !equality.Semantic.DeepEqual(spec.NodeSelector, selectors) || + !equality.Semantic.DeepEqual(spec.Tolerations, tolerations) || !equality.Semantic.DeepEqual(spec.SecurityContext, podSecurity) { + return fmt.Errorf("Sandbox terminal runtime, identity or scheduling differs from the platform plan") + } + container := spec.Containers[0] + resources := corev1.ResourceRequirements{Requests: input.Resolution.Sandbox.Resources.Helpers.Requests, Limits: input.Resolution.Sandbox.Resources.Helpers.Limits} + security := &corev1.SecurityContext{RunAsUser: ptr.To[int64](65532), RunAsGroup: ptr.To[int64](65532), RunAsNonRoot: ptr.To(true), + ReadOnlyRootFilesystem: ptr.To(true), AllowPrivilegeEscalation: ptr.To(false), Capabilities: &corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}, + SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}} + env := []corev1.EnvVar{ + {Name: "PORT", Value: strconv.Itoa(int(settings.Port))}, + {Name: "CETIRUN_TERMINAL_AGENT_NAME", Value: input.AgentName}, + {Name: "CETIRUN_TERMINAL_AGENT_UID", Value: string(input.Resolution.Binding.AgentUID)}, + {Name: "CETIRUN_TERMINAL_NAMESPACE", Value: input.Namespace.Name}, + {Name: "CETIRUN_TERMINAL_STATEFULSET", Value: input.WorkloadName}, + {Name: "CETIRUN_TERMINAL_CONTAINER", Value: "cetirun"}, + {Name: "CETIRUN_TERMINAL_SESSION_SECONDS", Value: strconv.Itoa(int(settings.SessionSeconds))}, + } + if container.Name != "terminal" || container.Image != settings.Image || container.ImagePullPolicy != corev1.PullIfNotPresent || + !slices.Equal(container.Command, []string{"/terminal"}) || !slices.Equal(container.Args, []string{"serve"}) || + !equality.Semantic.DeepEqual(container.SecurityContext, security) || !equality.Semantic.DeepEqual(container.Resources, resources) || + !equality.Semantic.DeepEqual(container.Env, env) || !equality.Semantic.DeepEqual(container.Ports, []corev1.ContainerPort{{Name: "terminal", ContainerPort: settings.Port, Protocol: corev1.ProtocolTCP}}) || + len(container.EnvFrom) != 0 || len(container.VolumeDevices) != 0 || !terminalProbesMatch(container) { + return fmt.Errorf("Sandbox terminal container differs from the platform plan") + } + volumes := []corev1.Volume{ + {Name: "tmp", VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{SizeLimit: ptr.To(input.Resolution.Sandbox.Storage.Scratch.SizeLimit.DeepCopy())}}}, + {Name: "api-access", VolumeSource: corev1.VolumeSource{Projected: &corev1.ProjectedVolumeSource{DefaultMode: ptr.To[int32](0440), Sources: []corev1.VolumeProjection{ + // Kubernetes supplies its configured API audience when it is omitted. + {ServiceAccountToken: &corev1.ServiceAccountTokenProjection{Path: "token", ExpirationSeconds: ptr.To[int64](3600)}}, + {ConfigMap: &corev1.ConfigMapProjection{LocalObjectReference: corev1.LocalObjectReference{Name: "kube-root-ca.crt"}, Items: []corev1.KeyToPath{{Key: "ca.crt", Path: "ca.crt"}}}}, + {DownwardAPI: &corev1.DownwardAPIProjection{Items: []corev1.DownwardAPIVolumeFile{{Path: "namespace", FieldRef: &corev1.ObjectFieldSelector{APIVersion: "v1", FieldPath: "metadata.namespace"}}}}}, + }}}}, + } + if !equality.Semantic.DeepEqual(spec.Volumes, volumes) || !equality.Semantic.DeepEqual(container.VolumeMounts, []corev1.VolumeMount{ + {Name: "tmp", MountPath: "/tmp"}, {Name: "api-access", MountPath: "/var/run/secrets/kubernetes.io/serviceaccount", ReadOnly: true}, + }) { + return fmt.Errorf("Sandbox terminal must only mount its scratch and Kubernetes API projections") + } + return nil +} + +func terminalProbesMatch(container corev1.Container) bool { + probe := func(path string) *corev1.Probe { + return &corev1.Probe{ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{Path: path, Port: intstr.FromString("terminal")}}, + PeriodSeconds: 5, TimeoutSeconds: 2, FailureThreshold: 3} + } + return equality.Semantic.DeepEqual(container.ReadinessProbe, probe("/healthz")) && + equality.Semantic.DeepEqual(container.LivenessProbe, probe("/livez")) && container.StartupProbe == nil +} diff --git a/app/cetirun-operator/internal/helm/testfixture/pre_proxy.go b/app/cetirun-operator/internal/helm/testfixture/pre_proxy.go index 13d3e294f..cc62a88f8 100644 --- a/app/cetirun-operator/internal/helm/testfixture/pre_proxy.go +++ b/app/cetirun-operator/internal/helm/testfixture/pre_proxy.go @@ -41,6 +41,20 @@ var laterAdditions = map[string][]string{ {{- end }} `}, "values.schema.json": {` "ingressMTLS": {"const": true, "description": "Internal common-executor managed Envoy endpoint; absent for ordinary ingress"}, +`, ` "context": { + "type": "object", "additionalProperties": false, + "properties": {"name": {"type": "string", "minLength": 1}, "files": {"type": "object", "additionalProperties": false, "properties": {"AGENTS.md": {"const": "AGENTS.md"}}, "required": ["AGENTS.md"]}}, + "required": ["name", "files"] + }, + "loopbackProbe": { + "type": "object", "additionalProperties": false, + "properties": {"image": {"type": "string", "pattern": "^[^\\s@]+@sha256:[a-f0-9]{64}$"}}, "required": ["image"] + }, + "terminal": { + "type": "object", "additionalProperties": false, + "properties": {"enabled": {"type": "boolean"}, "image": {"type": "string", "pattern": "^[^\\s@]+@sha256:[a-f0-9]{64}$"}, "port": {"type": "integer", "minimum": 1024, "maximum": 65535}, "sessionSeconds": {"type": "integer", "minimum": 60, "maximum": 3600}, "serviceAccountName": {"type": "string", "minLength": 1}}, + "required": ["enabled", "image", "port", "sessionSeconds", "serviceAccountName"] + }, `, ` "portalSignIn": { "type": "object", "description": "Sign the owner in to the Control UI with their Portal sign-in (OpenClaw trusted-proxy mode)", @@ -116,7 +130,7 @@ func RestorePreProxyContract(chrt *chart.Chart) error { {" \"replicaCount\": {\"type\": [\"integer\", \"null\"], \"minimum\": 0, \"maximum\": 1, \"default\": null},\n", ""}, {`"executionHeld": {"type": "boolean"}, "reconciled": {"const": true}`, `"executionHeld": {"const": true}`}, - {`"agentType": {"enum": ["openclaw", "hermes"]}`, `"agentType": {"const": "openclaw"}`}, + {`"agentType": {"enum": ["openclaw", "hermes", "custom"]}`, `"agentType": {"const": "openclaw"}`}, {`"sandboxWorkload": { "anyOf": [ {"required": ["podFinalizers"]}, @@ -125,6 +139,10 @@ func RestorePreProxyContract(chrt *chart.Chart) error { }`, `"sandboxWorkload": {"required": ["podFinalizers"]}`}, }, "templates/_sandbox.tpl": { + {`{{- if and (eq (include "cetirun.agent.type" .) "custom") (not $reconciled) -}} +{{- fail "Custom requires common reconciled Sandbox execution" -}}`, + `{{- if eq (include "cetirun.agent.type" .) "custom" -}} +{{- fail "governed Custom rendering is unsupported" -}}`}, {`{{- $reconciled := $s.reconciled | default false -}} {{- if or (ne $s.contractVersion "v1") (and (not $reconciled) (or (ne $s.executionHeld true) (ne (int .Values.replicaCount) 0))) (and $reconciled (or $s.executionHeld (gt (int .Values.replicaCount) 1) (lt (int .Values.replicaCount) 0))) -}}`, `{{- if or (ne $s.contractVersion "v1") (ne $s.executionHeld true) (ne (int .Values.replicaCount) 0) -}}`}, diff --git a/app/cetirun-operator/internal/sandbox/capabilities.go b/app/cetirun-operator/internal/sandbox/capabilities.go index 37c83f141..a09600f76 100644 --- a/app/cetirun-operator/internal/sandbox/capabilities.go +++ b/app/cetirun-operator/internal/sandbox/capabilities.go @@ -68,8 +68,8 @@ func CheckAgentProfile(capabilities Capabilities, agentType cetirunv1alpha1.Agen return errs.ToAggregate() } if capabilities.Profile == ProfileNativeSingleStart && agentType != cetirunv1alpha1.AgentTypeOpenClaw && - agentType != cetirunv1alpha1.AgentTypeHermes { - return fmt.Errorf("native execution requires a built-in Agent") + agentType != cetirunv1alpha1.AgentTypeHermes && agentType != cetirunv1alpha1.AgentTypeCustom { + return fmt.Errorf("native execution requires a supported Agent harness") } return nil } @@ -176,8 +176,8 @@ func CheckNativePolicy(policy cetirunv1alpha1.AgentPolicySpec) field.ErrorList { root := field.NewPath("spec") var errs field.ErrorList for _, kind := range policy.Harnesses.Allowed { - if kind != cetirunv1alpha1.AgentTypeOpenClaw && kind != cetirunv1alpha1.AgentTypeHermes { - errs = append(errs, field.Forbidden(root.Child("harnesses", "allowed"), "native execution requires built-in harnesses")) + if kind != cetirunv1alpha1.AgentTypeOpenClaw && kind != cetirunv1alpha1.AgentTypeHermes && kind != cetirunv1alpha1.AgentTypeCustom { + errs = append(errs, field.Forbidden(root.Child("harnesses", "allowed"), "native execution requires supported harnesses")) } } errs = append(errs, CheckNativeNetworkPolicy(policy.Network)...) diff --git a/app/cetirun-operator/internal/sandbox/capabilities_test.go b/app/cetirun-operator/internal/sandbox/capabilities_test.go index f9fa0a4a4..1f0a657e5 100644 --- a/app/cetirun-operator/internal/sandbox/capabilities_test.go +++ b/app/cetirun-operator/internal/sandbox/capabilities_test.go @@ -340,8 +340,8 @@ func TestNativeCompatibilityKeepsBaselineWithoutFencingClaims(t *testing.T) { }) } for name, mutate := range map[string]func(*cetirunv1alpha1.AgentPolicySpec){ - "Custom": func(p *cetirunv1alpha1.AgentPolicySpec) { - p.Harnesses.Allowed = append(p.Harnesses.Allowed, cetirunv1alpha1.AgentTypeCustom) + "Unknown harness": func(p *cetirunv1alpha1.AgentPolicySpec) { + p.Harnesses.Allowed = append(p.Harnesses.Allowed, cetirunv1alpha1.AgentType("unknown")) }, "FQDN": func(p *cetirunv1alpha1.AgentPolicySpec) { p.Network.BlockedFQDNs = []string{"blocked.example.com"} }, "port": func(p *cetirunv1alpha1.AgentPolicySpec) { diff --git a/app/cetirun-operator/internal/sandbox/container_test.go b/app/cetirun-operator/internal/sandbox/container_test.go index e079a1a43..9dbb39a68 100644 --- a/app/cetirun-operator/internal/sandbox/container_test.go +++ b/app/cetirun-operator/internal/sandbox/container_test.go @@ -30,7 +30,7 @@ func containerResolveInput() ResolveInput { } func TestContainerRuntimeResolution(t *testing.T) { - for _, kind := range []api.AgentType{api.AgentTypeOpenClaw, api.AgentTypeHermes} { + for _, kind := range []api.AgentType{api.AgentTypeOpenClaw, api.AgentTypeHermes, api.AgentTypeCustom} { for _, mode := range []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce, corev1.ReadWriteOncePod} { t.Run(string(kind)+"/"+string(mode), func(t *testing.T) { input := containerResolveInput() @@ -64,7 +64,7 @@ func TestContainerRuntimeFailsClosed(t *testing.T) { "missing registration": func(i *ResolveInput) { delete(i.Registrations, api.SandboxContainer) }, "no AgentPolicy": func(i *ResolveInput) { delete(i.Resources.AgentPolicies, "normal") }, "unauthorized binding": func(i *ResolveInput) { i.AuthorizedBinding.AgentPolicyUID = "another-policy" }, - "Custom harness": func(i *ResolveInput) { i.Agent.Spec.Agent.Type = api.AgentTypeCustom }, + "unknown harness": func(i *ResolveInput) { i.Agent.Spec.Agent.Type = api.AgentType("unknown") }, "unregistered HOME mode": func(i *ResolveInput) { i.Resources.Sandboxes["standard"].Spec.Storage.Home.AccessMode = corev1.ReadWriteOnce }, diff --git a/app/cetirun-operator/internal/sandbox/normalize.go b/app/cetirun-operator/internal/sandbox/normalize.go index 94e53aecb..2b8a1bad2 100644 --- a/app/cetirun-operator/internal/sandbox/normalize.go +++ b/app/cetirun-operator/internal/sandbox/normalize.go @@ -210,11 +210,9 @@ func normalizePolicyConstraints(policy *v1alpha1.AgentPolicySpec, path *field.Pa policy.Harnesses.Allowed = slices.Compact(policy.Harnesses.Allowed) for i, harness := range policy.Harnesses.Allowed { switch harness { - case v1alpha1.AgentTypeOpenClaw, v1alpha1.AgentTypeHermes: - case v1alpha1.AgentTypeCustom: - errs = append(errs, field.NotSupported(harnessPath.Index(i), harness, []string{string(v1alpha1.AgentTypeOpenClaw), string(v1alpha1.AgentTypeHermes)})) + case v1alpha1.AgentTypeOpenClaw, v1alpha1.AgentTypeHermes, v1alpha1.AgentTypeCustom: default: - errs = append(errs, field.NotSupported(harnessPath.Index(i), harness, []string{string(v1alpha1.AgentTypeOpenClaw), string(v1alpha1.AgentTypeHermes)})) + errs = append(errs, field.NotSupported(harnessPath.Index(i), harness, []string{string(v1alpha1.AgentTypeOpenClaw), string(v1alpha1.AgentTypeHermes), string(v1alpha1.AgentTypeCustom)})) } } } diff --git a/app/cetirun-operator/internal/sandbox/policy_selection.go b/app/cetirun-operator/internal/sandbox/policy_selection.go index 480f13c86..d33187d47 100644 --- a/app/cetirun-operator/internal/sandbox/policy_selection.go +++ b/app/cetirun-operator/internal/sandbox/policy_selection.go @@ -11,9 +11,9 @@ import ( ) const ( - HoldFinalizer = "cetirun.microsoft.com/sandbox-hold" + HoldFinalizer = api.SandboxHoldFinalizer PreparationFinalizer = api.SandboxPreparationFinalizer - BootstrapFinalizer = "cetirun.microsoft.com/sandbox-bootstrap" + BootstrapFinalizer = api.SandboxBootstrapFinalizer ) // Requested detects policy assignment intent, not a valid or enforced binding. diff --git a/app/cetirun-operator/internal/sandbox/resolver_test.go b/app/cetirun-operator/internal/sandbox/resolver_test.go index 824fc88dd..e498b0be8 100644 --- a/app/cetirun-operator/internal/sandbox/resolver_test.go +++ b/app/cetirun-operator/internal/sandbox/resolver_test.go @@ -110,7 +110,7 @@ func mustResolve(t *testing.T, input ResolveInput) *Resolution { return result } -func TestNativeResolveRequiresExplicitModeAndOpenClaw(t *testing.T) { +func TestNativeResolveRequiresExplicitModeAndSupportedHarness(t *testing.T) { fixture := func() ResolveInput { input := resolverFixture() input.NativeExecution = true @@ -126,7 +126,7 @@ func TestNativeResolveRequiresExplicitModeAndOpenClaw(t *testing.T) { } for name, mutate := range map[string]func(*ResolveInput){ "default mode": func(i *ResolveInput) { i.NativeExecution = false }, - "Custom": func(i *ResolveInput) { i.Agent.Spec.Agent.Type = cetirunv1alpha1.AgentTypeCustom }, + "unknown": func(i *ResolveInput) { i.Agent.Spec.Agent.Type = cetirunv1alpha1.AgentType("unknown") }, "Kubernetes access": func(i *ResolveInput) { i.Resources.AgentPolicies["normal"].Spec.KubernetesAccess = &cetirunv1alpha1.AgentPolicyAdminKubernetesAccess{ ServiceAccountName: "operations", diff --git a/app/cetirun-operator/internal/sandboxbinding/authorization.go b/app/cetirun-operator/internal/sandboxbinding/authorization.go index df0ccf2e8..a14a33579 100644 --- a/app/cetirun-operator/internal/sandboxbinding/authorization.go +++ b/app/cetirun-operator/internal/sandboxbinding/authorization.go @@ -23,8 +23,8 @@ import ( ) const ( - AuthorizationAnnotation = "cetirun.microsoft.com/sandbox-authorization" - ReauthorizeAnnotation = "cetirun.microsoft.com/sandbox-reauthorize" + AuthorizationAnnotation = api.AnnotationSandboxAuthorization + ReauthorizeAnnotation = api.AnnotationSandboxReauthorize recordVersion = "v1" ) diff --git a/app/cetirun-operator/internal/sandboxpolicy/compiler.go b/app/cetirun-operator/internal/sandboxpolicy/compiler.go index 78bc5aab4..a2bceee8a 100644 --- a/app/cetirun-operator/internal/sandboxpolicy/compiler.go +++ b/app/cetirun-operator/internal/sandboxpolicy/compiler.go @@ -81,6 +81,15 @@ func Compile(input CompileInput) (*Plan, error) { } input.ConnectionsMCP = &Destination{Peer: *found, Ports: ports} } + customIngress, err := canonicalCustomIngress(input.CustomIngress) + if err != nil { + return nil, err + } + terminalIngress, err := canonicalTerminalIngress(input.TerminalIngress) + if err != nil { + return nil, err + } + input.Resolution, input.Platform, input.CustomIngress, input.TerminalIngress = resolution, platform, customIngress, terminalIngress var mtls *ingressmtls.Plan if resolution.AgentPolicy.Network.Ingress.RequireMTLS { if !input.NativeExecution || platform.IngressMTLS == nil { @@ -116,24 +125,26 @@ func Compile(input CompileInput) (*Plan, error) { revisionNetwork := network revisionNetwork.TrustedProxyIPs = nil plan.Revision, err = digest(struct { - Version string - Binding sandbox.Binding - AgentName string - Namespace string - Sandbox api.SandboxSpec - Policy sandbox.PolicyProjection - Capabilities sandbox.Capabilities - Adapter AdapterRegistration - Topology Topology - Grants []ApprovedGrant - Approval *ApprovedIdentity - Identity IdentityPlan - Network NetworkPlan - IngressMTLS *ingressmtls.Plan `json:",omitempty"` + Version string + Binding sandbox.Binding + AgentName string + Namespace string + Sandbox api.SandboxSpec + Policy sandbox.PolicyProjection + Capabilities sandbox.Capabilities + Adapter AdapterRegistration + Topology Topology + Grants []ApprovedGrant + Approval *ApprovedIdentity + Identity IdentityPlan + Network NetworkPlan + CustomIngress *CustomIngress `json:"customIngress,omitempty"` + TerminalIngress *TerminalIngress `json:"terminalIngress,omitempty"` + IngressMTLS *ingressmtls.Plan `json:",omitempty"` }{ "sandbox-controls-v1", binding, input.AgentName, input.Namespace, resolution.Sandbox, sandbox.ProjectPolicy(resolution.AgentPolicy), capabilities, platform.Adapter, - platform.Topology, grants, approval, identity, revisionNetwork, mtls, + platform.Topology, grants, approval, identity, revisionNetwork, input.CustomIngress, input.TerminalIngress, mtls, }) if err != nil { return nil, err @@ -147,6 +158,17 @@ func Compile(input CompileInput) (*Plan, error) { return nil, err } plan.Resources = append(plan.Resources, resource) + if plan.Network.TerminalPolicy != nil { + plan.Network.TerminalPolicy.Annotations[RevisionAnnotation] = plan.Revision + if err := validateNetworkPolicySize(*plan.Network.TerminalPolicy); err != nil { + return nil, err + } + resource, err = manifest(*plan.Network.TerminalPolicy) + if err != nil { + return nil, err + } + plan.Resources = append(plan.Resources, resource) + } if mtls != nil { resources, err := IngressMTLSResources(input, *mtls, plan.Revision) if err != nil { diff --git a/app/cetirun-operator/internal/sandboxpolicy/custom_test.go b/app/cetirun-operator/internal/sandboxpolicy/custom_test.go new file mode 100644 index 000000000..aaa1085c6 --- /dev/null +++ b/app/cetirun-operator/internal/sandboxpolicy/custom_test.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sandboxpolicy + +import ( + "errors" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + corev1 "k8s.io/api/core/v1" +) + +func TestCompileCustomIngressBindsEndpointAndCaller(t *testing.T) { + input := compilerFixture() + input.CustomIngress = &CustomIngress{ + Port: 8088, WebUI: true, + ChatCallers: []IngressCaller{{Namespace: "portal-system", PodLabels: map[string]string{"app": "portal"}}}, + } + plan := mustCompile(t, input) + gateway := map[string]string{"k8s:io.kubernetes.pod.namespace": "platform", "k8s:" + PeerUIDLabel: "example-ingress-uid"} + caller := map[string]string{"k8s:io.kubernetes.pod.namespace": "portal-system", "k8s:app": "portal"} + if !syntheticIngressAllowed(plan.Network.Policy.Spec, gateway, "", 8088, corev1.ProtocolTCP) || + !syntheticIngressAllowed(plan.Network.Policy.Spec, caller, "", 8088, corev1.ProtocolTCP) { + t.Fatal("declared Custom callers cannot reach the requested endpoint") + } + if syntheticIngressAllowed(plan.Network.Policy.Spec, caller, "", 8089, corev1.ProtocolTCP) || + syntheticIngressAllowed(plan.Network.Policy.Spec, map[string]string{"k8s:io.kubernetes.pod.namespace": "portal-system", "k8s:app": "foreign"}, "", 8088, corev1.ProtocolTCP) { + t.Fatal("Custom ingress widened its caller or port") + } + if plan.Revision == mustCompile(t, compilerFixture()).Revision { + t.Fatal("Custom ingress was omitted from the control revision") + } + input.Resolution.AgentPolicy.Network.Ingress.Mode = api.AgentPolicyIngressDisabled + if got := mustCompile(t, input).Network.Policy.Spec.Ingress; len(got) != 0 { + t.Fatal("disabled ingress retained Custom exposure") + } + invalid := compilerFixture() + invalid.CustomIngress = &CustomIngress{Port: 8088, ChatCallers: []IngressCaller{{Namespace: "portal-system"}}} + if _, err := Compile(invalid); !errors.Is(err, ErrUnsupportedControl) { + t.Fatal("unselected Custom Chat caller accepted:", err) + } +} + +func TestCompileCustomTerminalIsSeparateFromAgentPrivileges(t *testing.T) { + input := compilerFixture() + input.TerminalIngress = &TerminalIngress{Port: 7681} + plan := mustCompile(t, input) + terminal := plan.Network.TerminalPolicy + if terminal == nil || len(plan.Resources) != 2 { + t.Fatal("terminal did not receive a separate compiled policy") + } + labels := map[string]string{ + "k8s:" + AgentUIDLabel: "example-agent-uid", "k8s:io.kubernetes.pod.namespace": "cetirun-example-agent", + "k8s:cetirun.microsoft.com/terminal": "true", + } + if syntheticSelectorMatches(plan.Network.Policy.Spec.EndpointSelector, labels) || + !syntheticSelectorMatches(terminal.Spec.EndpointSelector, labels) { + t.Fatal("main policy would union its privileges into the terminal") + } + gateway := map[string]string{"k8s:" + PeerUIDLabel: "example-ingress-uid", "k8s:io.kubernetes.pod.namespace": "platform"} + if !syntheticIngressAllowed(terminal.Spec, gateway, "", 7681, corev1.ProtocolTCP) || + syntheticIngressAllowed(terminal.Spec, gateway, "", 7682, corev1.ProtocolTCP) { + t.Fatal("terminal ingress did not preserve the exact authenticated port") + } + dns := input.Platform.Topology.DNS[0] + if !syntheticEgressAllowed(terminal.Spec, "10.96.0.10", &dns, 53, corev1.ProtocolUDP) || + !syntheticEgressAllowed(terminal.Spec, "203.0.113.10", nil, 6443, corev1.ProtocolTCP) || + syntheticEgressAllowed(terminal.Spec, "198.51.100.10", nil, 443, corev1.ProtocolTCP) { + t.Fatal("terminal egress exceeded DNS and Kubernetes API authority") + } + if plan.Revision == mustCompile(t, compilerFixture()).Revision { + t.Fatal("terminal exposure was omitted from the control revision") + } + input.Resolution.AgentPolicy.Network.Ingress.Mode = api.AgentPolicyIngressDisabled + if got := mustCompile(t, input).Network.TerminalPolicy.Spec.Ingress; len(got) != 0 { + t.Fatal("disabled ingress retained terminal exposure") + } + input.Platform.Topology.KubernetesAPI = nil + if _, err := Compile(input); !errors.Is(err, ErrUnavailable) { + t.Fatal("terminal without registered API endpoints compiled:", err) + } +} diff --git a/app/cetirun-operator/internal/sandboxpolicy/network.go b/app/cetirun-operator/internal/sandboxpolicy/network.go index 2bf19c0ce..df3f3b6dd 100644 --- a/app/cetirun-operator/internal/sandboxpolicy/network.go +++ b/app/cetirun-operator/internal/sandboxpolicy/network.go @@ -13,6 +13,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation" api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" @@ -44,6 +45,46 @@ type addressGrant struct { // Cilium validates both allow and deny toPorts[].ports arrays against this limit. const maxPortsPerRule = 40 +func canonicalCustomIngress(input *CustomIngress) (*CustomIngress, error) { + if input == nil { + return nil, nil + } + if input.Port < 1 || input.Port > 65535 || (!input.WebUI && len(input.ChatCallers) == 0) { + return nil, fmt.Errorf("%w: Custom ingress requires a typed HTTP port and an exposure mode", ErrUnsupportedControl) + } + copy := *input + copy.ChatCallers = nil + for _, caller := range input.ChatCallers { + if len(validation.IsDNS1123Label(caller.Namespace)) != 0 || len(caller.PodLabels) == 0 || len(caller.PodLabels) > 16 { + return nil, fmt.Errorf("%w: Custom Chat callers require a bounded namespace and Pod selector", ErrUnsupportedControl) + } + labels := make(map[string]string, len(caller.PodLabels)) + for key, value := range caller.PodLabels { + if len(validation.IsQualifiedName(key)) != 0 || len(validation.IsValidLabelValue(value)) != 0 || value == "" || key == "io.kubernetes.pod.namespace" { + return nil, fmt.Errorf("%w: Custom Chat caller selector is invalid", ErrUnsupportedControl) + } + labels[key] = value + } + copy.ChatCallers = append(copy.ChatCallers, IngressCaller{Namespace: caller.Namespace, PodLabels: labels}) + } + var err error + copy.ChatCallers, err = canonicalObjects(copy.ChatCallers) + if err != nil { + return nil, err + } + return ©, nil +} + +func canonicalTerminalIngress(input *TerminalIngress) (*TerminalIngress, error) { + if input == nil { + return nil, nil + } + if input.Port < 1024 || input.Port > 65535 { + return nil, fmt.Errorf("%w: Custom terminal requires an unprivileged TCP port", ErrUnsupportedControl) + } + return &TerminalIngress{Port: input.Port}, nil +} + func canonicalPlatform(input Platform, capabilities sandbox.Capabilities) (Platform, error) { var platform Platform if err := validateControlInput(api.AgentPolicySpec{}, input); err != nil { @@ -465,6 +506,15 @@ func compileNetwork(input CompileInput, tlsPlan ...*ingressmtls.Plan) (NetworkPl EnableDefaultDeny: DefaultDeny{Ingress: true, Egress: true}, Ingress: []IngressRule{}, IngressDeny: []IngressRule{}, Egress: []EgressRule{}, EgressDeny: []EgressRule{}, } + // The terminal has the same Agent and namespace labels as the primary + // workload. Exclude it from this policy when its isolated policy exists, + // otherwise Cilium unions the main workload's model and internet grants into + // the terminal's default-deny policy. + if input.TerminalIngress != nil { + spec.EndpointSelector.MatchExpressions = []metav1.LabelSelectorRequirement{{ + Key: "k8s:cetirun.microsoft.com/terminal", Operator: metav1.LabelSelectorOpDoesNotExist, + }} + } budget := networkRuleBudget{} // Public-internet egress is intentionally permitted except for explicit // exclusions/denies below. Default-deny is not an internet allow-list; only @@ -602,14 +652,37 @@ func compileNetwork(input CompileInput, tlsPlan ...*ingressmtls.Plan) (NetworkPl } } ingressPeers = append(ingressPeers, destination.Peer) + ports := destination.Ports + if custom := input.CustomIngress; custom != nil && custom.WebUI { + ports = append(slices.Clone(ports), api.AgentPolicyPort{Port: custom.Port, Protocol: corev1.ProtocolTCP}) + ports, err = canonicalObjects(ports) + if err != nil { + return plan, err + } + } selector := []metav1.LabelSelector{peerSelector(destination.Peer)} - if err := budget.ingress(&spec.Ingress, IngressRule{FromEndpoints: selector, ToPorts: portRules(destination.Ports)}); err != nil { + if err := budget.ingress(&spec.Ingress, IngressRule{FromEndpoints: selector, ToPorts: portRules(ports)}); err != nil { return plan, err } - if err := budget.ingress(&spec.IngressDeny, IngressRule{FromEndpoints: selector, ToPorts: deniedPorts(destination.Ports)}); err != nil { + if err := budget.ingress(&spec.IngressDeny, IngressRule{FromEndpoints: selector, ToPorts: deniedPorts(ports)}); err != nil { return plan, err } } + if custom := input.CustomIngress; custom != nil { + for index, caller := range custom.ChatCallers { + peer := Peer{Name: fmt.Sprintf("portal-chat-%d", index), UID: types.UID(fmt.Sprintf("portal-chat-%d", index)), + Namespace: caller.Namespace, PodSelector: caller.PodLabels} + ingressPeers = append(ingressPeers, peer) + selector := []metav1.LabelSelector{peerSelector(peer)} + ports := []api.AgentPolicyPort{{Port: custom.Port, Protocol: corev1.ProtocolTCP}} + if err := budget.ingress(&spec.Ingress, IngressRule{FromEndpoints: selector, ToPorts: portRules(ports)}); err != nil { + return plan, err + } + if err := budget.ingress(&spec.IngressDeny, IngressRule{FromEndpoints: selector, ToPorts: deniedPorts(ports)}); err != nil { + return plan, err + } + } + } selectors, err := excludingPeers(ingressPeers) if err != nil { return plan, err @@ -648,9 +721,105 @@ func compileNetwork(input CompileInput, tlsPlan ...*ingressmtls.Plan) (NetworkPl TypeMeta: metav1.TypeMeta{APIVersion: "cilium.io/v2", Kind: "CiliumNetworkPolicy"}, ObjectMeta: metadata, Spec: spec, } + if terminal := input.TerminalIngress; terminal != nil { + policy, err := compileTerminalNetwork(input, *terminal) + if err != nil { + return plan, err + } + plan.TerminalPolicy = policy + } return plan, validateNetworkPolicySize(plan.Policy) } +// compileTerminalNetwork gives the isolated terminal no model, Agent, or +// internet authority. Its sole peers are registered DNS, the Kubernetes API, +// and the authenticated ingress endpoints on its fixed TCP listener. +func compileTerminalNetwork(input CompileInput, terminal TerminalIngress) (*CiliumNetworkPolicy, error) { + topology := input.Platform.Topology + // The terminal needs its narrowly scoped API connection to use the + // controller-issued ServiceAccount token. Do not render a terminal policy + // until the platform snapshot has explicitly resolved that destination. + if len(topology.KubernetesAPI) == 0 { + return nil, fmt.Errorf("%w: terminal requires resolved Kubernetes API destinations", ErrUnavailable) + } + spec := CiliumPolicySpec{ + EndpointSelector: metav1.LabelSelector{MatchLabels: map[string]string{ + "k8s:cetirun.microsoft.com/terminal": "true", + "k8s:" + AgentUIDLabel: string(input.Resolution.Binding.AgentUID), + "k8s:io.kubernetes.pod.namespace": input.Namespace, + }}, + EnableDefaultDeny: DefaultDeny{Ingress: true, Egress: true}, + Ingress: []IngressRule{}, IngressDeny: []IngressRule{}, Egress: []EgressRule{}, EgressDeny: []EgressRule{}, + } + dnsPorts := portRules([]api.AgentPolicyPort{{Port: 53, Protocol: corev1.ProtocolTCP}, {Port: 53, Protocol: corev1.ProtocolUDP}}) + for _, peer := range topology.DNS { + if err := appendTerminalEgress(&spec, peer, dnsPorts); err != nil { + return nil, err + } + } + for _, destination := range topology.KubernetesAPI { + if err := appendTerminalEgress(&spec, destination.Peer, portRules(destination.Ports)); err != nil { + return nil, err + } + } + if input.Resolution.AgentPolicy.Network.Ingress.Mode != api.AgentPolicyIngressDisabled { + ports := portRules([]api.AgentPolicyPort{{Port: terminal.Port, Protocol: corev1.ProtocolTCP}}) + for _, destination := range topology.Ingress { + if destination.Peer.Namespace != "" { + spec.Ingress = append(spec.Ingress, IngressRule{FromEndpoints: []metav1.LabelSelector{peerSelector(destination.Peer)}, ToPorts: ports}) + continue + } + cidrs := peerCIDRs(destination.Peer) + if len(cidrs) == 0 { + return nil, fmt.Errorf("%w: terminal ingress requires resolved Gateway addresses", ErrUnavailable) + } + spec.Ingress = append(spec.Ingress, IngressRule{FromCIDRSet: cidrRules(cidrs), ToPorts: ports}) + } + } + var err error + for _, rules := range []*[]EgressRule{&spec.Egress, &spec.EgressDeny} { + *rules, err = canonicalObjects(*rules) + if err != nil { + return nil, err + } + } + for _, rules := range []*[]IngressRule{&spec.Ingress, &spec.IngressDeny} { + *rules, err = canonicalObjects(*rules) + if err != nil { + return nil, err + } + } + name, err := digest(string(input.Resolution.Binding.AgentUID) + "/terminal") + if err != nil { + return nil, err + } + metadata, err := ownedMetadata(input, "sandbox-terminal-"+name[:24], input.Namespace) + if err != nil { + return nil, err + } + policy := &CiliumNetworkPolicy{TypeMeta: metav1.TypeMeta{APIVersion: "cilium.io/v2", Kind: "CiliumNetworkPolicy"}, ObjectMeta: metadata, Spec: spec} + if err := validateNetworkPolicySize(*policy); err != nil { + return nil, err + } + return policy, nil +} + +func appendTerminalEgress(spec *CiliumPolicySpec, peer Peer, ports []PortRule) error { + if len(ports) == 0 { + return fmt.Errorf("terminal egress requires resolved peers and ports") + } + if peer.Namespace != "" { + spec.Egress = append(spec.Egress, EgressRule{ToEndpoints: []metav1.LabelSelector{peerSelector(peer)}, ToPorts: ports}) + return nil + } + cidrs := peerCIDRs(peer) + if len(cidrs) == 0 { + return fmt.Errorf("terminal egress requires resolved peers and ports") + } + spec.Egress = append(spec.Egress, EgressRule{ToCIDRSet: cidrRules(cidrs), ToPorts: ports}) + return nil +} + func parsePrefix(raw string, capabilities sandbox.Capabilities) (netip.Prefix, error) { prefix, err := netip.ParsePrefix(raw) if err != nil || prefix.Addr().Is4In6() { diff --git a/app/cetirun-operator/internal/sandboxpolicy/types.go b/app/cetirun-operator/internal/sandboxpolicy/types.go index dd1395455..30ecd60c3 100644 --- a/app/cetirun-operator/internal/sandboxpolicy/types.go +++ b/app/cetirun-operator/internal/sandboxpolicy/types.go @@ -143,6 +143,27 @@ type CompileInput struct { Namespace string ServiceName string Platform Platform + // CustomIngress is an operator-derived Custom Harness HTTP contract. It is + // deliberately separate from AgentPolicy so callers cannot request a port + // or peer through an Agent-owned object. + CustomIngress *CustomIngress + // TerminalIngress is the controller-derived port of the isolated Custom + // terminal. It is separate from CustomIngress because its endpoint selector + // and egress authority must not apply to the Agent workload. + TerminalIngress *TerminalIngress +} + +type CustomIngress struct { + Port int32 `json:"port"` + WebUI bool `json:"webUI,omitempty"` + ChatCallers []IngressCaller `json:"chatCallers,omitempty"` +} +type IngressCaller struct { + Namespace string `json:"namespace"` + PodLabels map[string]string `json:"podLabels"` +} +type TerminalIngress struct { + Port int32 `json:"port"` } // Plan contains desired resources, never observed status. Render Resources @@ -165,8 +186,9 @@ type NetworkPlan struct { IngressMode api.AgentPolicyIngressMode `json:"ingressMode"` DNSIPs []string `json:"dnsIPs"` // The existing wire field also carries explicitly registered ingress Pod CIDRs. - TrustedProxyIPs []string `json:"trustedProxyIPs,omitempty"` - Policy CiliumNetworkPolicy `json:"policy"` + TrustedProxyIPs []string `json:"trustedProxyIPs,omitempty"` + Policy CiliumNetworkPolicy `json:"policy"` + TerminalPolicy *CiliumNetworkPolicy `json:"terminalPolicy,omitempty"` } type IdentityPlan struct { diff --git a/app/cetirun-operator/internal/sandboxworkload/build.go b/app/cetirun-operator/internal/sandboxworkload/build.go index 0e5913e12..12d1ce1c1 100644 --- a/app/cetirun-operator/internal/sandboxworkload/build.go +++ b/app/cetirun-operator/internal/sandboxworkload/build.go @@ -30,7 +30,7 @@ func Build(input Input) (*Bundle, error) { if binding.AgentUID == "" || binding.TeamUID == "" || binding.SandboxUID == "" || binding.AgentPolicyUID == "" { return nil, fmt.Errorf("the resolved UID binding is incomplete") } - if input.AgentType != "openclaw" && input.AgentType != "hermes" { + if input.AgentType != "openclaw" && input.AgentType != "hermes" && input.AgentType != "custom" { return nil, fmt.Errorf("policy-bound %q rendering is unsupported; legacy fallback is forbidden", input.AgentType) } if input.ConnectionsMCP != nil { @@ -41,6 +41,12 @@ func Build(input Input) (*Bundle, error) { return nil, err } } + if err := validateCustomAgent(input); err != nil { + return nil, err + } + if err := validateTerminal(input); err != nil { + return nil, err + } if request := input.PlannedMigration; request != nil && (!input.Reconciled || !api.ValidRestartRequestID(request.RequestID) || request.Target.UID == "" || len(validation.IsDNS1123Subdomain(request.Target.Name)) != 0) { @@ -94,7 +100,7 @@ func Build(input Input) (*Bundle, error) { return nil, err } if tls := input.Controls.IngressMTLS; tls != nil { - if !input.Reconciled || tls.AgentUID != binding.AgentUID || tls.Namespace != input.Namespace.Name || + if input.AgentType == "custom" || !input.Reconciled || tls.AgentUID != binding.AgentUID || tls.Namespace != input.Namespace.Name || tls.Harness != input.AgentType || slices.Contains(input.AuthorizedSecrets, tls.ServerSecret.Name) || (input.ImagePullSecret != nil && input.ImagePullSecret.Name == tls.ServerSecret.Name) || tls.ServiceHost != input.WorkloadName+"."+input.Namespace.Name+".svc.cluster.local" { @@ -141,10 +147,13 @@ func Build(input Input) (*Bundle, error) { spec.Containers = append(spec.Containers, corev1.Container{Resources: b.helperResources()}) } spec.InitContainers = []corev1.Container{{Resources: b.helperResources()}} + if input.CustomAgent != nil && input.CustomAgent.HTTP != nil { + spec.InitContainers = append(spec.InitContainers, corev1.Container{Resources: b.helperResources()}) + } if input.Helpers.Doctor { spec.InitContainers = append(spec.InitContainers, corev1.Container{Resources: b.helperResources()}) } - if input.GatewayKey != nil { + if input.GatewayKey != nil && input.AgentType != "custom" { spec.InitContainers = append(spec.InitContainers, corev1.Container{Resources: b.helperResources()}, corev1.Container{Resources: b.helperResources()}) } @@ -204,7 +213,7 @@ func validateControls(input Input) error { } volumes := map[string]bool{} for _, volume := range c.Volumes { - if volume.Name == "" || volumes[volume.Name] || slices.Contains([]string{"data", "tmp", "tmp-desktop", "config", "secrets", "shared-skills", "empty-skills"}, volume.Name) { + if volume.Name == "" || volumes[volume.Name] || slices.Contains([]string{"data", "tmp", "tmp-desktop", "config", "secrets", "shared-skills", "empty-skills", "context", "context-view", "memory-assets", "loopback-probe"}, volume.Name) { return fmt.Errorf("identity volumes conflict with protected mounts") } volumes[volume.Name] = true diff --git a/app/cetirun-operator/internal/sandboxworkload/contract.go b/app/cetirun-operator/internal/sandboxworkload/contract.go index f447ee87f..7a287da77 100644 --- a/app/cetirun-operator/internal/sandboxworkload/contract.go +++ b/app/cetirun-operator/internal/sandboxworkload/contract.go @@ -79,6 +79,8 @@ type Input struct { AgentName string AgentGeneration int64 AgentType string + CustomAgent *CustomAgent `json:",omitempty"` + GatewayAPIBase string `json:",omitempty"` Namespace ObjectIdentity WorkloadName string ReleaseName string @@ -91,6 +93,9 @@ type Input struct { AuthorizedSecrets []string GatewayKey *ObjectIdentity ImagePullSecret *ObjectIdentity `json:",omitempty"` + Context *Context `json:",omitempty"` + Terminal *Terminal `json:",omitempty"` + LoopbackProbe *LoopbackProbe `json:",omitempty"` } // Accounting uses Kubernetes effective init/sidecar accounting. Pod contains diff --git a/app/cetirun-operator/internal/sandboxworkload/custom.go b/app/cetirun-operator/internal/sandboxworkload/custom.go new file mode 100644 index 000000000..52c9f0322 --- /dev/null +++ b/app/cetirun-operator/internal/sandboxworkload/custom.go @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sandboxworkload + +import ( + "fmt" + "path" + "regexp" + "slices" + + "github.com/Azure/CetiRun/app/cetirun-operator/internal/runtimebindings" + "github.com/Azure/CetiRun/app/internal/terminalpolicy" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/utils/ptr" +) + +type Context struct { + ObjectIdentity + Files map[string]string `json:"files"` +} + +type Terminal struct { + Image string `json:"image"` + Port int32 `json:"port"` + SessionSeconds int32 `json:"sessionSeconds"` + ServiceAccountName string `json:"serviceAccountName"` +} + +type LoopbackProbe struct { + Image string `json:"image"` +} + +// CustomAgent is a Harness-validated contribution, not an arbitrary Pod spec. +// Command and arguments remain owned by the approved image. +type CustomAgent struct { + Image string `json:"image"` + Username string `json:"username"` + Home string `json:"home"` + Port *int32 `json:"port,omitempty"` + WebUI bool `json:"webUI,omitempty"` + WebBasePath string `json:"webBasePath,omitempty"` + WebInstance string `json:"webInstance,omitempty"` + Environment []CustomEnvironment `json:"environment,omitempty"` + Ports []CustomPort `json:"ports,omitempty"` + HTTP *CustomHTTP `json:"http,omitempty"` +} + +type CustomEnvironment struct { + Name string `json:"name"` + Value string `json:"value,omitempty"` + CredentialSlot string `json:"credentialSlot,omitempty"` +} + +type CustomPort struct { + Name string `json:"name"` + Number int32 `json:"number"` +} + +type CustomHTTP struct { + PortName string `json:"portName"` + HealthPath string `json:"healthPath"` + ReadinessPath string `json:"readinessPath"` + StartupPath string `json:"startupPath"` + ChatPath string `json:"chatPath,omitempty"` + ModelsPath string `json:"modelsPath,omitempty"` +} + +var customUsername = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}$`) +var terminalImage = regexp.MustCompile(`^[^[:space:]@]+@sha256:[a-f0-9]{64}$`) + +func validateCustomAgent(input Input) error { + if input.AgentType != "custom" { + if input.CustomAgent != nil || input.GatewayAPIBase != "" || input.Context != nil || input.LoopbackProbe != nil { + return fmt.Errorf("only Custom workloads may set a portable runtime identity") + } + return nil + } + custom := input.CustomAgent + if !input.Reconciled || custom == nil || custom.Image == "" || !customUsername.MatchString(custom.Username) || + custom.Home != path.Join("/home", custom.Username) || custom.Username == "root" || + (custom.Port != nil && (*custom.Port < 1 || *custom.Port > 65535)) || + (custom.WebUI && custom.Port == nil) { + return fmt.Errorf("Custom requires common execution and an approved image, user, HOME and port mode") + } + if (custom.HTTP == nil) != (custom.Port == nil) { + return fmt.Errorf("Custom HTTP bindings must match the configured port mode") + } + if input.GatewayKey == nil || input.GatewayAPIBase == "" || input.Context == nil || + input.Context.Name == "" || input.Context.UID == "" || + len(validation.IsDNS1123Subdomain(input.Context.Name)) != 0 || + len(input.Context.Files) != 1 || input.Context.Files["AGENTS.md"] != "AGENTS.md" { + return fmt.Errorf("Custom requires typed AI Gateway and canonical context bindings") + } + if custom.HTTP != nil && (input.LoopbackProbe == nil || !terminalImage.MatchString(input.LoopbackProbe.Image)) { + return fmt.Errorf("Custom HTTP requires an immutable platform loopback probe image") + } + if custom.HTTP == nil && input.LoopbackProbe != nil { + return fmt.Errorf("headless Custom cannot configure a loopback probe") + } + return nil +} + +func validateTerminal(input Input) error { + terminal := input.Terminal + if terminal == nil { + return nil + } + if input.AgentType != "custom" || !input.Reconciled || !terminalImage.MatchString(terminal.Image) || + terminal.Port < 1024 || terminal.Port > 65535 || terminal.SessionSeconds < 60 || terminal.SessionSeconds > 3600 || + len(validation.IsDNS1123Label(terminal.ServiceAccountName)) != 0 || + terminal.ServiceAccountName != terminalpolicy.WorkloadName(input.WorkloadName) { + return fmt.Errorf("Custom terminal requires a platform image, port, session and service account") + } + return nil +} + +func customEnvironmentValues(values []CustomEnvironment) []any { + out := make([]any, 0, len(values)) + for _, value := range values { + out = append(out, map[string]any{"name": value.Name, "value": value.Value, "credentialSlot": value.CredentialSlot}) + } + return out +} + +func customPortValues(values []CustomPort) []any { + out := make([]any, 0, len(values)) + for _, value := range values { + out = append(out, map[string]any{"name": value.Name, "number": value.Number}) + } + return out +} + +func customHTTPValues(value *CustomHTTP) any { + if value == nil { + return nil + } + return map[string]any{"portName": value.PortName, "healthPath": value.HealthPath, + "readinessPath": value.ReadinessPath, "startupPath": value.StartupPath, + "chatPath": value.ChatPath, "modelsPath": value.ModelsPath} +} + +func (b *Bundle) validateCustomReconciledTemplate(spec *corev1.PodSpec, memoryEnabled bool) error { + custom, context := b.input.CustomAgent, b.input.Context + if custom == nil || context == nil || b.input.GatewayKey == nil || len(spec.Containers) == 0 || len(spec.InitContainers) == 0 { + return fmt.Errorf("Custom runtime lacks its approved Harness or AI Gateway identity") + } + main := spec.Containers[0] + var init *corev1.Container + for index := range spec.InitContainers { + if spec.InitContainers[index].Name == "init-home-data" { + init = &spec.InitContainers[index] + break + } + } + if init == nil || main.Name != "cetirun" || main.Image != custom.Image || len(main.Command) != 0 || len(main.Args) != 0 || + init.Image != custom.Image || + !slices.Equal(init.Command, []string{"/bin/sh", "/etc/cetirun/custom-init-home.sh"}) || len(init.Args) != 0 { + return fmt.Errorf("Custom runtime rewrites an approved image entrypoint or HOME initializer") + } + for _, expected := range custom.Environment { + want := corev1.EnvVar{Name: expected.Name, Value: expected.Value} + if expected.CredentialSlot != "" { + if expected.CredentialSlot != "model" { + return fmt.Errorf("Custom runtime contains an unsupported credential slot") + } + want.Value = "" + want.ValueFrom = &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: b.input.GatewayKey.Name}, Key: "api-key", + }} + } + if !slices.ContainsFunc(main.Env, func(actual corev1.EnvVar) bool { return equality.Semantic.DeepEqual(actual, want) }) { + return fmt.Errorf("Custom runtime is missing a Harness or typed AI Gateway environment value") + } + } + if !slices.Equal(main.Ports, customContainerPorts(custom.Ports)) { + return fmt.Errorf("Custom runtime ports differ from the Harness contract") + } + if custom.HTTP == nil { + if main.StartupProbe != nil || main.ReadinessProbe != nil || main.LivenessProbe != nil { + return fmt.Errorf("headless Custom cannot define HTTP probes") + } + } else if !customHTTPProbesMatch(main, custom.HTTP, *custom.Port) { + return fmt.Errorf("Custom probes differ from the Harness contract") + } + if custom.HTTP != nil { + probe := b.input.LoopbackProbe + index := slices.IndexFunc(spec.InitContainers, func(container corev1.Container) bool { return container.Name == "install-loopback-probe" }) + if probe == nil || index < 0 || !equality.Semantic.DeepEqual(spec.InitContainers[index], corev1.Container{ + Name: "install-loopback-probe", Image: probe.Image, ImagePullPolicy: corev1.PullIfNotPresent, + Command: []string{"/loopback-probe", "install", "/cetirun-probe/http-probe"}, SecurityContext: b.SecurityContext(), + Resources: b.helperResources(), VolumeMounts: []corev1.VolumeMount{{Name: "loopback-probe", MountPath: "/cetirun-probe"}}, + }) { + return fmt.Errorf("Custom loopback probe installer differs from the platform contract") + } + } + mainMounts := []corev1.VolumeMount{ + {Name: "data", MountPath: custom.Home}, {Name: "tmp", MountPath: "/tmp"}, + {Name: "config", MountPath: "/etc/cetirun", ReadOnly: true}, + {Name: "context-view", MountPath: custom.Home + "/.agents", SubPath: "current", ReadOnly: true}, + } + if custom.HTTP != nil { + mainMounts = append(mainMounts, corev1.VolumeMount{Name: "loopback-probe", MountPath: "/cetirun-probe", ReadOnly: true}) + } + if memoryEnabled { + mainMounts = append(mainMounts, runtimebindings.MemoryMounts()...) + } + mainMounts = append(mainMounts, b.input.Controls.VolumeMounts...) + initMounts := []corev1.VolumeMount{ + {Name: "data", MountPath: "/home-data"}, {Name: "tmp", MountPath: "/tmp"}, + {Name: "config", MountPath: "/etc/cetirun", ReadOnly: true}, + {Name: "context", MountPath: "/etc/cetirun-context", ReadOnly: true}, + {Name: "context-view", MountPath: "/etc/cetirun-context-view"}, + } + initEnv := []corev1.EnvVar{ + {Name: "SOURCE_HOME", Value: custom.Home}, {Name: "TARGET_HOME", Value: "/home-data"}, + {Name: "CETIRUN_INIT_IMAGE", Value: custom.Image}, {Name: "CETIRUN_INIT_COMMON", Value: "/etc/cetirun/init-home-common.sh"}, + {Name: "CETIRUN_CONTEXT_DIR", Value: "/etc/cetirun-context"}, + {Name: "CETIRUN_CONTEXT_VIEW", Value: "/etc/cetirun-context-view"}, + } + if b.input.SkillsMode != SkillsModeEmpty { + initMounts = append(initMounts, corev1.VolumeMount{Name: "shared-skills", MountPath: "/etc/cetirun-shared-skills", ReadOnly: true}) + initEnv = append(initEnv, corev1.EnvVar{Name: "CETIRUN_SHARED_SKILLS_DIR", Value: "/etc/cetirun-shared-skills"}) + } + if memoryEnabled { + initMounts = append(initMounts, runtimebindings.MemoryMounts()...) + initEnv = append(initEnv, corev1.EnvVar{Name: "CETIRUN_MEMORY_ASSETS", Value: runtimebindings.MemoryAssetsDir}) + } + initMounts = append(initMounts, b.input.Controls.VolumeMounts...) + if !equalCustomMounts(main.VolumeMounts, mainMounts) || !equalCustomMounts(init.VolumeMounts, initMounts) || + !equality.Semantic.DeepEqual(init.Env, initEnv) { + return fmt.Errorf("Custom mounts or initialization environment differ from the common contract") + } + contextVolume := corev1.Volume{Name: "context", VolumeSource: corev1.VolumeSource{ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{Name: context.Name}, DefaultMode: ptr.To[int32](0444), + Items: []corev1.KeyToPath{{Key: "AGENTS.md", Path: "AGENTS.md"}}, + }}} + if !hasExactCustomVolume(*spec, contextVolume) { + return fmt.Errorf("Custom context source differs from the controller snapshot") + } + names := []string{"context-view"} + if custom.HTTP != nil { + names = append(names, "loopback-probe") + } + for _, name := range names { + if !hasExactCustomVolume(*spec, corev1.Volume{Name: name, VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{ + SizeLimit: ptr.To(b.input.Resolution.Sandbox.Storage.Scratch.SizeLimit), + }}}) { + return fmt.Errorf("Custom volume %q differs from the Sandbox scratch limit", name) + } + } + return nil +} + +func hasExactCustomVolume(spec corev1.PodSpec, expected corev1.Volume) bool { + return slices.ContainsFunc(spec.Volumes, func(actual corev1.Volume) bool { + return equality.Semantic.DeepEqual(actual, expected) + }) +} + +func customContainerPorts(ports []CustomPort) []corev1.ContainerPort { + result := make([]corev1.ContainerPort, 0, len(ports)) + for _, port := range ports { + result = append(result, corev1.ContainerPort{Name: port.Name, ContainerPort: port.Number, Protocol: corev1.ProtocolTCP}) + } + return result +} + +func customHTTPProbesMatch(container corev1.Container, http *CustomHTTP, port int32) bool { + probe := func(path string, period, failures int32) *corev1.Probe { + return &corev1.Probe{ProbeHandler: corev1.ProbeHandler{Exec: &corev1.ExecAction{Command: []string{ + "/cetirun-probe/http-probe", "--url", fmt.Sprintf("http://127.0.0.1:%d%s", port, path), + }}}, PeriodSeconds: period, TimeoutSeconds: 3, FailureThreshold: failures} + } + return container.LivenessProbe == nil && container.StartupProbe != nil && container.ReadinessProbe != nil && + equality.Semantic.DeepEqual(container.StartupProbe, probe(http.StartupPath, 5, 60)) && + equality.Semantic.DeepEqual(container.ReadinessProbe, probe(http.HealthPath, 10, 0)) +} + +func equalCustomMounts(actual, expected []corev1.VolumeMount) bool { + actual, expected = slices.Clone(actual), slices.Clone(expected) + sortMounts(actual) + sortMounts(expected) + return equality.Semantic.DeepEqual(actual, expected) +} diff --git a/app/cetirun-operator/internal/sandboxworkload/finalpod.go b/app/cetirun-operator/internal/sandboxworkload/finalpod.go index eaa858286..f4b63e0c5 100644 --- a/app/cetirun-operator/internal/sandboxworkload/finalpod.go +++ b/app/cetirun-operator/internal/sandboxworkload/finalpod.go @@ -10,9 +10,9 @@ import ( "slices" "strings" + "github.com/Azure/CetiRun/app/internal/podtemplate" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" ) @@ -290,20 +290,8 @@ func SamePodTemplate(actual, expected corev1.PodTemplateSpec) bool { } func defaultPod(spec *corev1.PodSpec) error { - if spec.RestartPolicy == "" { - spec.RestartPolicy = corev1.RestartPolicyAlways - } - if spec.DNSPolicy == "" { - spec.DNSPolicy = corev1.DNSClusterFirst - } - if spec.SchedulerName == "" { - spec.SchedulerName = corev1.DefaultSchedulerName - } - if spec.TerminationGracePeriodSeconds == nil { - spec.TerminationGracePeriodSeconds = ptr.To(int64(30)) - } - if spec.DeprecatedServiceAccount == "" { - spec.DeprecatedServiceAccount = spec.ServiceAccountName + if err := podtemplate.DefaultSpec(spec); err != nil { + return err } if spec.Priority == nil { spec.Priority = ptr.To(int32(0)) @@ -311,37 +299,6 @@ func defaultPod(spec *corev1.PodSpec) error { if spec.PreemptionPolicy == nil { spec.PreemptionPolicy = ptr.To(corev1.PreemptLowerPriority) } - for i := range spec.Containers { - defaultContainer(&spec.Containers[i]) - } - for i := range spec.InitContainers { - defaultContainer(&spec.InitContainers[i]) - } - for i := range spec.Volumes { - source := &spec.Volumes[i].VolumeSource - if source.ConfigMap != nil && source.ConfigMap.DefaultMode == nil { - source.ConfigMap.DefaultMode = ptr.To(int32(0644)) - } - if source.Secret != nil && source.Secret.DefaultMode == nil { - source.Secret.DefaultMode = ptr.To(int32(0644)) - } - if source.Projected != nil && source.Projected.DefaultMode == nil { - source.Projected.DefaultMode = ptr.To(int32(0644)) - } - if source.DownwardAPI != nil { - if source.DownwardAPI.DefaultMode == nil { - source.DownwardAPI.DefaultMode = ptr.To(int32(0644)) - } - defaultDownwardItems(source.DownwardAPI.Items) - } - if source.Projected != nil { - for _, projection := range source.Projected.Sources { - if projection.DownwardAPI != nil { - defaultDownwardItems(projection.DownwardAPI.Items) - } - } - } - } for _, key := range []string{"node.kubernetes.io/not-ready", "node.kubernetes.io/unreachable"} { defaultToleration(spec, corev1.Toleration{ Key: key, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoExecute, TolerationSeconds: ptr.To(int64(300)), @@ -386,69 +343,3 @@ func defaultToleration(spec *corev1.PodSpec, expected corev1.Toleration) { } spec.Tolerations = append(spec.Tolerations, expected) } - -func defaultDownwardItems(items []corev1.DownwardAPIVolumeFile) { - for i := range items { - defaultFieldSelectors(items[i].FieldRef, items[i].ResourceFieldRef) - } -} - -func defaultFieldSelectors(field *corev1.ObjectFieldSelector, resourceField *corev1.ResourceFieldSelector) { - if field != nil && field.APIVersion == "" { - field.APIVersion = "v1" - } - if resourceField != nil && resourceField.Divisor.IsZero() { - resourceField.Divisor = resource.MustParse("1") - } -} - -func defaultContainer(container *corev1.Container) { - if container.ImagePullPolicy == "" { - container.ImagePullPolicy = corev1.PullIfNotPresent - tag := container.Image[strings.LastIndex(container.Image, "/")+1:] - if !strings.Contains(container.Image, "@") && (!strings.Contains(tag, ":") || strings.HasSuffix(tag, ":latest")) { - container.ImagePullPolicy = corev1.PullAlways - } - } - if container.TerminationMessagePath == "" { - container.TerminationMessagePath = corev1.TerminationMessagePathDefault - } - if container.TerminationMessagePolicy == "" { - container.TerminationMessagePolicy = corev1.TerminationMessageReadFile - } - for _, env := range container.Env { - if env.ValueFrom != nil { - defaultFieldSelectors(env.ValueFrom.FieldRef, env.ValueFrom.ResourceFieldRef) - } - } - for i := range container.Ports { - if container.Ports[i].Protocol == "" { - container.Ports[i].Protocol = corev1.ProtocolTCP - } - } - for _, probe := range []*corev1.Probe{container.LivenessProbe, container.ReadinessProbe, container.StartupProbe} { - if probe == nil { - continue - } - if probe.TimeoutSeconds == 0 { - probe.TimeoutSeconds = 1 - } - if probe.PeriodSeconds == 0 { - probe.PeriodSeconds = 10 - } - if probe.SuccessThreshold == 0 { - probe.SuccessThreshold = 1 - } - if probe.FailureThreshold == 0 { - probe.FailureThreshold = 3 - } - if probe.HTTPGet != nil { - if probe.HTTPGet.Scheme == "" { - probe.HTTPGet.Scheme = corev1.URISchemeHTTP - } - if probe.HTTPGet.Path == "" { - probe.HTTPGet.Path = "/" - } - } - } -} diff --git a/app/cetirun-operator/internal/sandboxworkload/objects.go b/app/cetirun-operator/internal/sandboxworkload/objects.go index 6908cec7e..cc757a6ca 100644 --- a/app/cetirun-operator/internal/sandboxworkload/objects.go +++ b/app/cetirun-operator/internal/sandboxworkload/objects.go @@ -48,7 +48,19 @@ func validateObjects(input Input) error { } owner := []metav1.OwnerReference{AgentOwner(input.AgentName, c.Binding.AgentUID)} objects := map[string]bool{} - network, serviceAccounts := 0, 0 + network, terminalNetwork, serviceAccounts := 0, 0, 0 + mainSelector := metav1.LabelSelector{MatchLabels: map[string]string{ + "k8s:" + sandboxpolicy.AgentUIDLabel: string(c.Binding.AgentUID), "k8s:io.kubernetes.pod.namespace": input.Namespace.Name, + }} + terminalSelector := metav1.LabelSelector{MatchLabels: map[string]string{ + "k8s:cetirun.microsoft.com/terminal": "true", + "k8s:" + sandboxpolicy.AgentUIDLabel: string(c.Binding.AgentUID), "k8s:io.kubernetes.pod.namespace": input.Namespace.Name, + }} + if input.Terminal != nil { + mainSelector.MatchExpressions = []metav1.LabelSelectorRequirement{{ + Key: "k8s:cetirun.microsoft.com/terminal", Operator: metav1.LabelSelectorOpDoesNotExist, + }} + } tlsObjects := map[string][]byte{} if c.IngressMTLS != nil { expected, err := sandboxpolicy.IngressMTLSResources(sandboxpolicy.CompileInput{ @@ -88,13 +100,17 @@ func validateObjects(input Input) error { if err := runtime.DefaultUnstructuredConverter.FromUnstructuredWithValidation(object.Object, &policy, true); err != nil { return fmt.Errorf("invalid compiler network resource: %w", err) } - if policy.Namespace != input.Namespace.Name || - !equality.Semantic.DeepEqual(policy.Spec.EndpointSelector, metav1.LabelSelector{MatchLabels: map[string]string{ - "k8s:" + sandboxpolicy.AgentUIDLabel: string(c.Binding.AgentUID), "k8s:io.kubernetes.pod.namespace": input.Namespace.Name, - }}) { + if policy.Namespace != input.Namespace.Name { + return fmt.Errorf("compiler network scope must select only the bound workload") + } + switch { + case equality.Semantic.DeepEqual(policy.Spec.EndpointSelector, mainSelector): + network++ + case input.Terminal != nil && equality.Semantic.DeepEqual(policy.Spec.EndpointSelector, terminalSelector): + terminalNetwork++ + default: return fmt.Errorf("compiler network scope must select only the bound workload") } - network++ case "v1/ServiceAccount": var account corev1.ServiceAccount if err := runtime.DefaultUnstructuredConverter.FromUnstructuredWithValidation(object.Object, &account, true); err != nil { @@ -133,7 +149,8 @@ func validateObjects(input Input) error { } objects[key] = true } - if network != 1 || (dedicated && serviceAccounts != 1) || len(tlsObjects) != 0 { + if network != 1 || (input.Terminal != nil && terminalNetwork != 1) || (input.Terminal == nil && terminalNetwork != 0) || + (dedicated && serviceAccounts != 1) || len(tlsObjects) != 0 { return fmt.Errorf("compiler resource inventory is incomplete or duplicated") } for _, present := range grants { diff --git a/app/cetirun-operator/internal/sandboxworkload/reconcile.go b/app/cetirun-operator/internal/sandboxworkload/reconcile.go index 7c247f255..cad7bc94e 100644 --- a/app/cetirun-operator/internal/sandboxworkload/reconcile.go +++ b/app/cetirun-operator/internal/sandboxworkload/reconcile.go @@ -13,11 +13,13 @@ import ( api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" "github.com/Azure/CetiRun/app/cetirun-operator/internal/ingressmtls" "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandbox" + "github.com/Azure/CetiRun/app/internal/terminalpolicy" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/validation" "k8s.io/utils/ptr" strictjson "sigs.k8s.io/json" ) @@ -42,6 +44,14 @@ type ReconcileExpectation struct { Sources []SourceReference `json:"sources"` SourceDigests map[string]string `json:"sourceDigests"` Controls []unstructured.Unstructured `json:"controls"` + Terminal *TerminalTarget `json:"terminal,omitempty"` +} + +// TerminalTarget is the controller-owned CONNECT target, never caller input. +type TerminalTarget struct { + ServiceAccountName string `json:"serviceAccountName"` + TargetWorkload string `json:"targetWorkload"` + Container string `json:"container"` } type RenderedWorkload struct { @@ -141,6 +151,18 @@ func (e ReconcileExpectation) Validate() error { if main == nil { return fmt.Errorf("Sandbox has no retained HOME workload") } + if terminal := e.Terminal; terminal != nil { + if len(validation.IsDNS1123Label(terminal.ServiceAccountName)) != 0 || + terminal.ServiceAccountName != terminalpolicy.WorkloadName(main.Identity.Name) || + terminal.TargetWorkload != main.Identity.Name || terminal.Container != "cetirun" { + return fmt.Errorf("Sandbox terminal target is invalid") + } + if !slices.ContainsFunc(e.Workloads, func(workload RenderedWorkload) bool { + return workload.Kind == "Deployment" && workload.Identity.Name == terminal.ServiceAccountName && workload.Replicas == 1 + }) { + return fmt.Errorf("Sandbox terminal workload is absent") + } + } sources := map[string]bool{} required := map[string]bool{} effective := 0 @@ -205,6 +227,10 @@ func (e ReconcileExpectation) Validate() error { } controls[key] = true switch object.GetAPIVersion() + "/" + object.GetKind() { + case "rbac.authorization.k8s.io/v1/RoleBinding": + if e.Terminal == nil { + return fmt.Errorf("Sandbox RoleBindings require a terminal target") + } case "v1/ConfigMap", "v1/Service", "v1/ServiceAccount", "networking.k8s.io/v1/NetworkPolicy", "cilium.io/v2/CiliumNetworkPolicy", "networking.istio.io/v1beta1/DestinationRule": default: @@ -217,6 +243,17 @@ func (e ReconcileExpectation) Validate() error { return fmt.Errorf("Sandbox control inventory is missing %s", kind) } } + if terminal := e.Terminal; terminal != nil { + for _, source := range []SourceReference{ + {APIVersion: "v1", Kind: "ServiceAccount", Namespace: e.Namespace.Name, Name: terminal.ServiceAccountName}, + {APIVersion: "rbac.authorization.k8s.io/v1", Kind: "RoleBinding", Namespace: e.Namespace.Name, Name: terminal.ServiceAccountName}, + {APIVersion: "rbac.authorization.k8s.io/v1", Kind: "RoleBinding", Namespace: e.Namespace.Name, Name: terminal.ServiceAccountName + "-exec"}, + } { + if !controls[SourceKey(source)] { + return fmt.Errorf("Sandbox terminal identity controls are absent") + } + } + } for _, workload := range e.Workloads { for _, source := range PodSourceReferences(workload.Template.Spec, e.Namespace.Name) { if !sources[SourceKey(source)] && !controls[SourceKey(source)] { @@ -337,7 +374,7 @@ func ValidateRenderedPod(pod *corev1.Pod, workload RenderedWorkload, owner metav return nil } -func (b *Bundle) ValidateReconciledTemplate(template *corev1.PodTemplateSpec, image string) error { +func (b *Bundle) ValidateReconciledTemplate(template *corev1.PodTemplateSpec, image string, memoryEnabled bool) error { spec := template.Spec if err := b.validateIngressTemplate(spec); err != nil { return err @@ -403,14 +440,18 @@ func (b *Bundle) ValidateReconciledTemplate(template *corev1.PodTemplateSpec, im for _, group := range [][]corev1.Container{spec.Containers, spec.InitContainers} { for _, container := range group { sc := container.SecurityContext + imageUser := b.input.CustomAgent != nil && sc != nil && sc.RunAsUser == nil && spec.SecurityContext.RunAsUser == nil if sc == nil || ptr.Deref(sc.Privileged, false) || ptr.Deref(sc.AllowPrivilegeEscalation, true) || !ptr.Deref(sc.RunAsNonRoot, ptr.Deref(spec.SecurityContext.RunAsNonRoot, false)) || - ptr.Deref(sc.RunAsUser, ptr.Deref(spec.SecurityContext.RunAsUser, 0)) <= 0 || + !imageUser && ptr.Deref(sc.RunAsUser, ptr.Deref(spec.SecurityContext.RunAsUser, 0)) <= 0 || sc.Capabilities == nil || len(sc.Capabilities.Add) != 0 || !slices.Contains(sc.Capabilities.Drop, corev1.Capability("ALL")) || !ptr.Deref(sc.ReadOnlyRootFilesystem, false) && *b.input.Resolution.AgentPolicy.Security.ReadOnlyRootFilesystem { return fmt.Errorf("reconciled Sandbox container violates the selected security constraints") } } } + if b.input.CustomAgent != nil { + return b.validateCustomReconciledTemplate(&spec, memoryEnabled) + } return nil } diff --git a/app/cetirun-operator/internal/sandboxworkload/sources.go b/app/cetirun-operator/internal/sandboxworkload/sources.go index ef247657f..bb11ea2a9 100644 --- a/app/cetirun-operator/internal/sandboxworkload/sources.go +++ b/app/cetirun-operator/internal/sandboxworkload/sources.go @@ -6,12 +6,9 @@ package sandboxworkload import ( "crypto/sha256" "encoding/hex" - "encoding/json" "fmt" - "slices" api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" - "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandbox" "github.com/Azure/CetiRun/app/cetirun-operator/internal/sandboxbinding" ) @@ -40,31 +37,12 @@ func AgentSourceReference(agent *api.Agent) (SourceReference, error) { if agent.Generation < 1 || agent.ResourceVersion == "" { return SourceReference{}, fmt.Errorf("Sandbox Agent intent requires a persisted generation and resource version") } - annotations := make(map[string]string, 2) - for _, key := range []string{sandboxbinding.AuthorizationAnnotation, sandboxbinding.ReauthorizeAnnotation} { - if value, found := agent.Annotations[key]; found { - annotations[key] = value - } - } - intent := struct { - Spec api.AgentSpec - Annotations map[string]string - Held bool - Prepared bool - Bootstrapped bool `json:",omitempty"` - }{ - Spec: agent.Spec, Annotations: annotations, - Held: slices.Contains(agent.Finalizers, sandbox.HoldFinalizer), - Prepared: slices.Contains(agent.Finalizers, sandbox.PreparationFinalizer), - Bootstrapped: slices.Contains(agent.Finalizers, sandbox.BootstrapFinalizer), - } - raw, err := json.Marshal(intent) + digest, err := agent.SandboxExecutionIntentDigest() if err != nil { - return SourceReference{}, fmt.Errorf("encode Sandbox Agent intent: %w", err) + return SourceReference{}, err } - digest := sha256.Sum256(raw) return SourceReference{ APIVersion: api.GroupVersion.String(), Kind: "Agent", Name: agent.Name, UID: agent.UID, - Generation: agent.Generation, IntentDigest: hex.EncodeToString(digest[:]), + Generation: agent.Generation, IntentDigest: digest, }, nil } diff --git a/app/cetirun-operator/internal/sandboxworkload/testfixture/fixture.go b/app/cetirun-operator/internal/sandboxworkload/testfixture/fixture.go index 15119abce..fcefc5f72 100644 --- a/app/cetirun-operator/internal/sandboxworkload/testfixture/fixture.go +++ b/app/cetirun-operator/internal/sandboxworkload/testfixture/fixture.go @@ -60,6 +60,9 @@ func New(agentType string) Fixture { Network: api.AgentPolicyNetwork{Ingress: api.AgentPolicyIngress{Mode: api.AgentPolicyIngressDisabled}}, }, } + if agentType == "custom" { + policy.Spec.Harnesses.Allowed = append(policy.Spec.Harnesses.Allowed, api.AgentTypeCustom) + } team := &api.Team{ ObjectMeta: metav1.ObjectMeta{Name: "team-example", UID: "team-uid", ResourceVersion: "1", Generation: 1}, Spec: api.TeamSpec{SandboxRefs: []string{box.Name}, DefaultSandboxRef: box.Name, AgentPolicyRef: policy.Name}, diff --git a/app/cetirun-operator/internal/sandboxworkload/values.go b/app/cetirun-operator/internal/sandboxworkload/values.go index 3faae3c11..aa842052c 100644 --- a/app/cetirun-operator/internal/sandboxworkload/values.go +++ b/app/cetirun-operator/internal/sandboxworkload/values.go @@ -104,21 +104,29 @@ func protectedEnvironment(name string) bool { } func (b *Bundle) SecurityContext() *corev1.SecurityContext { - return &corev1.SecurityContext{ + context := &corev1.SecurityContext{ RunAsUser: ptr.To(int64(1024)), RunAsGroup: ptr.To(int64(1024)), RunAsNonRoot: ptr.To(true), AllowPrivilegeEscalation: ptr.To(false), Privileged: ptr.To(false), ReadOnlyRootFilesystem: ptr.To(*b.input.Resolution.AgentPolicy.Security.ReadOnlyRootFilesystem), Capabilities: &corev1.Capabilities{Drop: []corev1.Capability{"ALL"}}, SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, } + if b.input.CustomAgent != nil { + context.RunAsUser, context.RunAsGroup = nil, nil + } + return context } func (b *Bundle) PodSecurityContext() *corev1.PodSecurityContext { - return &corev1.PodSecurityContext{ + context := &corev1.PodSecurityContext{ RunAsUser: ptr.To(int64(1024)), RunAsGroup: ptr.To(int64(1024)), RunAsNonRoot: ptr.To(true), FSGroup: ptr.To(int64(1024)), FSGroupChangePolicy: ptr.To(corev1.FSGroupChangeOnRootMismatch), SeccompProfile: &corev1.SeccompProfile{Type: corev1.SeccompProfileTypeRuntimeDefault}, } + if b.input.CustomAgent != nil { + context.RunAsUser, context.RunAsGroup = nil, nil + } + return context } func (b *Bundle) DNSConfig() *corev1.PodDNSConfig { @@ -168,6 +176,12 @@ func (b *Bundle) Apply(values map[string]any) (map[string]any, error) { } security, _ := jsonValue(b.SecurityContext()) podSecurity, _ := jsonValue(b.PodSecurityContext()) + if b.input.CustomAgent != nil { + for _, context := range []any{security, podSecurity} { + values := context.(map[string]any) + values["runAsUser"], values["runAsGroup"] = nil, nil + } + } dnsConfig, _ := jsonValue(b.DNSConfig()) agent, _ := jsonValue(b.agentResources()) helper, _ := jsonValue(b.helperResources()) @@ -234,6 +248,51 @@ func (b *Bundle) Apply(values map[string]any) (map[string]any, error) { if b.input.GatewayKey != nil { overlay[ValuesKey].(map[string]any)["podFinalizers"] = []any{NativePodFinalizer} } + if custom := b.input.CustomAgent; custom != nil { + terminalEnabled := b.input.Terminal != nil + if settings, ok := out["ttyd"].(map[string]any); ok { + if enabled, ok := settings["enabled"].(bool); ok { + terminalEnabled = terminalEnabled && enabled + } + } + overlay["ttyd"] = map[string]any{"enabled": terminalEnabled} + contextFiles := map[string]any{} + for destination, source := range b.input.Context.Files { + contextFiles[destination] = source + } + control := overlay[ValuesKey].(map[string]any) + control["context"] = map[string]any{"name": b.input.Context.Name, "files": contextFiles} + if probe := b.input.LoopbackProbe; probe != nil { + control["loopbackProbe"] = map[string]any{"image": probe.Image} + } + if terminal := b.input.Terminal; terminal != nil { + control["terminal"] = map[string]any{ + "enabled": terminalEnabled, "image": terminal.Image, "port": terminal.Port, + "sessionSeconds": terminal.SessionSeconds, "serviceAccountName": terminal.ServiceAccountName, + } + } + port := any(nil) + if custom.Port != nil { + port = *custom.Port + } + overlay["runtime"] = map[string]any{ + "contractVersion": ContractVersion, + "agent": map[string]any{ + "type": "custom", "image": custom.Image, "username": custom.Username, + "home": custom.Home, "port": port, "webUI": custom.WebUI, + "webBasePath": custom.WebBasePath, "webInstance": custom.WebInstance, + }, + "model": map[string]any{ + "apiBase": b.input.GatewayAPIBase, "keySecretName": b.input.GatewayKey.Name, "keySecretKey": "api-key", + }, + "environment": customEnvironmentValues(custom.Environment), + "ports": customPortValues(custom.Ports), + "http": customHTTPValues(custom.HTTP), + } + if secret := b.input.ImagePullSecret; secret != nil { + overlay["runtime"].(map[string]any)["imagePullSecrets"] = []any{map[string]any{"name": secret.Name}} + } + } if b.input.Reconciled { if err := b.input.ConnectionsMCP.Validate(); err != nil { return nil, err diff --git a/app/cetirun-portal/chart/templates/chat-rbac.yaml b/app/cetirun-portal/chart/templates/chat-rbac.yaml index dafd4f82c..c799f51b2 100644 --- a/app/cetirun-portal/chart/templates/chat-rbac.yaml +++ b/app/cetirun-portal/chart/templates/chat-rbac.yaml @@ -12,6 +12,9 @@ rules: - apiGroups: ["networking.k8s.io"] resources: ["networkpolicies"] verbs: ["get"] + - apiGroups: ["cilium.io"] + resources: ["ciliumnetworkpolicies"] + verbs: ["get"] - apiGroups: ["networking.istio.io"] resources: ["virtualservices"] verbs: ["get"] @@ -30,4 +33,32 @@ subjects: - kind: ServiceAccount name: {{ .Values.serviceAccount.name }} namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "cetirun-portal.fullname" . }}-chat-sandbox-state + namespace: {{ default .Values.aiGateway.catalogNamespace .Values.chat.sandboxStateNamespace | quote }} + labels: + {{- include "cetirun-portal.labels" . | nindent 4 }} +rules: + - apiGroups: [""] + resources: ["configmaps"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "cetirun-portal.fullname" . }}-chat-sandbox-state + namespace: {{ default .Values.aiGateway.catalogNamespace .Values.chat.sandboxStateNamespace | quote }} + labels: + {{- include "cetirun-portal.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "cetirun-portal.fullname" . }}-chat-sandbox-state +subjects: + - kind: ServiceAccount + name: {{ .Values.serviceAccount.name }} + namespace: {{ .Release.Namespace }} {{- end }} diff --git a/app/cetirun-portal/chart/templates/deployment.yaml b/app/cetirun-portal/chart/templates/deployment.yaml index 65834c94d..55fd0e722 100644 --- a/app/cetirun-portal/chart/templates/deployment.yaml +++ b/app/cetirun-portal/chart/templates/deployment.yaml @@ -64,6 +64,8 @@ spec: value: {{ include "cetirun-portal.selectorLabels" . | fromYaml | toJson | quote }} - name: REGISTRY_CREDENTIAL_NAMESPACE value: {{ default .Values.registryCredentials.namespace .Values.global.registryCredentialNamespace | quote }} + - name: SANDBOX_STATE_NAMESPACE + value: {{ default .Values.aiGateway.catalogNamespace .Values.chat.sandboxStateNamespace | quote }} {{- if .Values.istio.host }} - name: PORTAL_ORIGIN value: {{ printf "https://%s" .Values.istio.host | quote }} diff --git a/app/cetirun-portal/chart/values.yaml b/app/cetirun-portal/chart/values.yaml index 5def243b3..1e4360f7f 100644 --- a/app/cetirun-portal/chart/values.yaml +++ b/app/cetirun-portal/chart/values.yaml @@ -20,6 +20,8 @@ replicaCount: 2 chat: enabled: false identityRealm: "" + # Empty uses aiGateway.catalogNamespace, the operator namespace. + sandboxStateNamespace: "" # -- Portal container image. image: diff --git a/app/cetirun-portal/go.mod b/app/cetirun-portal/go.mod index a95625749..c81cc1ac1 100644 --- a/app/cetirun-portal/go.mod +++ b/app/cetirun-portal/go.mod @@ -16,6 +16,10 @@ require ( ) require ( + dario.cat/mergo v1.0.2 // indirect + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.5.0 // indirect + github.com/Masterminds/sprig/v3 v3.3.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect @@ -38,7 +42,10 @@ require ( github.com/go-openapi/swag/yamlutils v0.29.2 // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/huandu/xstrings v1.6.3 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/mitchellh/copystructure v1.2.0 // indirect + github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect @@ -49,10 +56,13 @@ require ( github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.1 // indirect github.com/prometheus/procfs v0.23.0 // indirect + github.com/shopspring/decimal v1.6.0 // indirect + github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/x448/float16 v0.8.4 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/net v0.61.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect golang.org/x/sync v0.24.0 // indirect diff --git a/app/cetirun-portal/internal/config/config.go b/app/cetirun-portal/internal/config/config.go index c560faeb7..4d028b4b5 100644 --- a/app/cetirun-portal/internal/config/config.go +++ b/app/cetirun-portal/internal/config/config.go @@ -63,6 +63,7 @@ type Config struct { // AIGatewayCatalogNamespace is the operator namespace, where the operator // publishes the shared models. AIGatewayCatalogNamespace string + SandboxStateNamespace string // ConfigurationCoordination pins the authority shared with strict Sandbox // admission for protected Team, Sandbox and AgentPolicy mutations. ConfigurationCoordinationNamespace string @@ -103,6 +104,7 @@ func Load() Config { RegistryCredentialNamespace: envOrDefault("REGISTRY_CREDENTIAL_NAMESPACE", "cetirun-registry-credentials"), AIGatewayEnabled: os.Getenv("FEATURE_AI_GATEWAY_ENABLED") == "true", AIGatewayCatalogNamespace: envOrDefault("AI_GATEWAY_CATALOG_NAMESPACE", "cetirun-system"), + SandboxStateNamespace: envOrDefault("SANDBOX_STATE_NAMESPACE", "cetirun-system"), ConfigurationCoordinationNamespace: envOrDefault("CONFIGURATION_COORDINATION_NAMESPACE", ""), ConfigurationCoordinationName: envOrDefault("CONFIGURATION_COORDINATION_NAME", ""), ConfigurationCoordinationUID: envOrDefault("CONFIGURATION_COORDINATION_UID", ""), diff --git a/app/cetirun-portal/internal/handler/admin_policy.go b/app/cetirun-portal/internal/handler/admin_policy.go index cd1b70e10..141016265 100644 --- a/app/cetirun-portal/internal/handler/admin_policy.go +++ b/app/cetirun-portal/internal/handler/admin_policy.go @@ -366,8 +366,9 @@ func validateAgentPolicyRequest(req AgentPolicyUpsertRequest) string { } seenHarness := map[cetirunv1alpha1.AgentType]bool{} for _, harness := range req.Harnesses.Allowed { - if harness != cetirunv1alpha1.AgentTypeOpenClaw && harness != cetirunv1alpha1.AgentTypeHermes { - return "harnesses.allowed may contain only openclaw or hermes" + if harness != cetirunv1alpha1.AgentTypeOpenClaw && harness != cetirunv1alpha1.AgentTypeHermes && + harness != cetirunv1alpha1.AgentTypeCustom { + return "harnesses.allowed may contain only openclaw, hermes or custom" } if seenHarness[harness] { return "harnesses.allowed must not contain duplicate entries" diff --git a/app/cetirun-portal/internal/handler/sandbox_runtime_test.go b/app/cetirun-portal/internal/handler/sandbox_runtime_test.go index 9455f913e..7c1b21d66 100644 --- a/app/cetirun-portal/internal/handler/sandbox_runtime_test.go +++ b/app/cetirun-portal/internal/handler/sandbox_runtime_test.go @@ -33,6 +33,32 @@ func TestSandboxCreatePinsRuntimeBeforeFirstWrite(t *testing.T) { } } +func TestSandboxCreatePreservesCustomContracts(t *testing.T) { + for _, endpoint := range []string{"", `,"port":8080`, `,"port":8080,"webUI":true`} { + team, policy := creationPolicy() + policy.Spec.Harnesses.Allowed = []api.AgentType{api.AgentTypeCustom} + h, _ := creationPolicyHandler(team, policy) + h.Config.SandboxRuntimes = nil + h.Config.SandboxControllerDefaults = true + w := httptest.NewRecorder() + h.CreateInstance(w, managementRequest(http.MethodPost, + `{"agent":{"type":"custom","image":"registry.example.com/custom@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`+ + endpoint+`},"team":"policy-team","modelAccess":{"sharedModels":true,"githubCopilot":false}}`)) + if w.Code != http.StatusCreated { + t.Fatalf("Custom create: %d %s", w.Code, w.Body.String()) + } + agent, err := h.Kube.GetInstance(context.Background(), "alice") + if err != nil { + t.Fatal(err) + } + if agent.Spec.Agent.Type != api.AgentTypeCustom || agent.Spec.Agent.Image == nil || + agent.Spec.SandboxRef != team.Spec.DefaultSandboxRef || agent.Spec.GatewayTokenSecretRef != "" || + (endpoint == "") != (agent.Spec.Agent.Port == nil) { + t.Fatal("Portal changed the Custom contract or lost policy selection") + } + } +} + func TestSandboxCreateUsesCommonControllerDefaults(t *testing.T) { for _, kind := range []api.AgentType{api.AgentTypeOpenClaw, api.AgentTypeHermes} { t.Run(string(kind), func(t *testing.T) { diff --git a/app/cetirun-portal/internal/kube/chat.go b/app/cetirun-portal/internal/kube/chat.go index bbeb3dad7..e15238883 100644 --- a/app/cetirun-portal/internal/kube/chat.go +++ b/app/cetirun-portal/internal/kube/chat.go @@ -60,9 +60,10 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata } team = observed } - if agent.Spec.SandboxRef != "" || agent.Status.Sandbox != nil || meta.FindStatusCondition(agent.Status.Conditions, api.ConditionSandboxReady) != nil || + common := commonChatCandidate(agent, team) + if (agent.Spec.SandboxRef != "" || agent.Status.Sandbox != nil || meta.FindStatusCondition(agent.Status.Conditions, api.ConditionSandboxReady) != nil || slices.Contains(agent.Finalizers, "cetirun.microsoft.com/sandbox-hold") || slices.Contains(agent.Finalizers, "cetirun.microsoft.com/sandbox-preparation") || - team.Spec.PolicyConfigured() { + team.Spec.PolicyConfigured()) && !common { target.Reason = "sandbox_held" return target, nil } @@ -99,7 +100,21 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata } owner := metav1.GetControllerOf(sts) if owner == nil || owner.Kind != "Agent" || owner.UID != agent.UID || sts.UID == "" || !sts.DeletionTimestamp.IsZero() || ptr.Deref(sts.Spec.Replicas, 0) != 1 || - sts.Annotations[chataccess.AgentUIDAnnotation] != string(agent.UID) || sts.Annotations[chataccess.WorkloadAnnotation] == "" || sts.Spec.Selector == nil || len(sts.Spec.Selector.MatchLabels) == 0 || len(sts.Spec.Selector.MatchExpressions) != 0 { + sts.Spec.Selector == nil || len(sts.Spec.Selector.MatchLabels) == 0 || len(sts.Spec.Selector.MatchExpressions) != 0 { + return target, nil + } + var commonExpectation commonChatExpectation + if common { + var verified bool + var err error + commonExpectation, verified, err = c.verifyCommonChatExpectation(ctx, agent, ns, sts, caller) + if err != nil { + return target, err + } + if !verified { + return target, nil + } + } else if sts.Annotations[chataccess.AgentUIDAnnotation] != string(agent.UID) || sts.Annotations[chataccess.WorkloadAnnotation] == "" { return target, nil } pod := &corev1.Pod{} @@ -107,7 +122,10 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata return target, err } owner = metav1.GetControllerOf(pod) - if owner == nil || owner.Kind != "StatefulSet" || owner.UID != sts.UID || pod.UID == "" || !pod.DeletionTimestamp.IsZero() || pod.Annotations[chataccess.WorkloadAnnotation] != sts.Annotations[chataccess.WorkloadAnnotation] { + if owner == nil || owner.Kind != "StatefulSet" || owner.UID != sts.UID || pod.UID == "" || !pod.DeletionTimestamp.IsZero() || + (!common && pod.Annotations[chataccess.WorkloadAnnotation] != sts.Annotations[chataccess.WorkloadAnnotation]) || + (common && (pod.Annotations[commonReconciledAnnotation] != "true" || pod.Annotations[commonWorkloadRevisionAnnotation] != commonExpectation.Revision || + pod.Annotations[chataccess.AgentUIDAnnotation] != string(agent.UID))) { return target, nil } ready := false @@ -152,7 +170,8 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata return target, err } if svc.UID == "" || !svc.DeletionTimestamp.IsZero() || svc.Spec.Type != corev1.ServiceTypeClusterIP || net.ParseIP(svc.Spec.ClusterIP) == nil || - svc.Spec.ExternalName != "" || len(svc.Spec.ExternalIPs) != 0 || !maps.Equal(svc.Spec.Selector, sts.Spec.Selector.MatchLabels) || !chatReleaseOwned(svc, agent) { + svc.Spec.ExternalName != "" || len(svc.Spec.ExternalIPs) != 0 || !maps.Equal(svc.Spec.Selector, sts.Spec.Selector.MatchLabels) || + (!common && !chatReleaseOwned(svc, agent)) || (common && !commonChatOwned(svc, agent)) { return target, nil } for k, v := range svc.Spec.Selector { @@ -169,13 +188,19 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata if !portFound { return target, nil } - policy := &networkv1.NetworkPolicy{} - if err := c.client.Get(ctx, key, policy); err != nil { - return target, err - } target.Reason = "network_unavailable" - if !policy.DeletionTimestamp.IsZero() || !chatReleaseOwned(policy, agent) || !maps.Equal(policy.Spec.PodSelector.MatchLabels, svc.Spec.Selector) || len(policy.Spec.PodSelector.MatchExpressions) != 0 || !slices.Contains(policy.Spec.PolicyTypes, networkv1.PolicyTypeIngress) || !chataccess.Allows(policy, caller, *agent.Spec.Agent.Port) { - return target, nil + var network any + if common { + network = commonExpectation.Revision + } else { + policy := &networkv1.NetworkPolicy{} + if err := c.client.Get(ctx, key, policy); err != nil { + return target, err + } + if !policy.DeletionTimestamp.IsZero() || !chatReleaseOwned(policy, agent) || !maps.Equal(policy.Spec.PodSelector.MatchLabels, svc.Spec.Selector) || len(policy.Spec.PodSelector.MatchExpressions) != 0 || !slices.Contains(policy.Spec.PolicyTypes, networkv1.PolicyTypeIngress) || !chataccess.Allows(policy, caller, *agent.Spec.Agent.Port) { + return target, nil + } + network = policy.Spec } route := &unstructured.Unstructured{} route.SetGroupVersionKind(chataccess.RouteGVK) @@ -190,9 +215,9 @@ func (c *Client) resolveChat(ctx context.Context, agent *api.Agent, caller chata Route types.UID Container, Workload string Restarts, Port int32 - Network networkv1.NetworkPolicySpec + Network any RouteSpec any - }{agent.UID, ns.UID, svc.UID, sts.UID, pod.UID, route.GetUID(), containerID, sts.Annotations[chataccess.WorkloadAnnotation], restartCount, *agent.Spec.Agent.Port, policy.Spec, route.Object["spec"]}) + }{agent.UID, ns.UID, svc.UID, sts.UID, pod.UID, route.GetUID(), containerID, sts.Annotations[chataccess.WorkloadAnnotation], restartCount, *agent.Spec.Agent.Port, network, route.Object["spec"]}) target.BaseURL = "http://" + net.JoinHostPort(name+"."+namespace+".svc.cluster.local", strconv.Itoa(int(*agent.Spec.Agent.Port))) target.Available = true target.Reason = "ready" diff --git a/app/cetirun-portal/internal/kube/chat_common.go b/app/cetirun-portal/internal/kube/chat_common.go new file mode 100644 index 000000000..74862e667 --- /dev/null +++ b/app/cetirun-portal/internal/kube/chat_common.go @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package kube + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "maps" + "slices" + "strconv" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/internal/chataccess" + "github.com/Azure/CetiRun/app/internal/podtemplate" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const ( + commonExpectationKey = "expectation.json" + commonReconciledAnnotation = "sandbox.cetirun.microsoft.com/reconciled" + commonWorkloadRevisionAnnotation = "cetirun.microsoft.com/sandbox-revision" + commonPolicyRevisionAnnotation = "sandbox.cetirun.microsoft.com/revision" +) + +type commonChatIdentity struct { + Name string `json:"name"` + UID types.UID `json:"uid"` +} + +type commonChatBinding struct { + AgentUID types.UID `json:"agentUID"` + TeamUID types.UID `json:"teamUID"` + SandboxUID types.UID `json:"sandboxUID"` + AgentPolicyUID types.UID `json:"agentPolicyUID"` +} + +type commonChatWorkload struct { + Kind string `json:"kind"` + Identity commonChatIdentity `json:"identity"` + Replicas int32 `json:"replicas"` + Template corev1.PodTemplateSpec `json:"template"` +} + +type commonChatSource struct { + APIVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Namespace string `json:"namespace,omitempty"` + Name string `json:"name"` + UID types.UID `json:"uid"` + ResourceVersion string `json:"resourceVersion,omitempty"` + Generation int64 `json:"generation,omitempty"` + IntentDigest string `json:"intentDigest,omitempty"` +} + +type commonChatExpectation struct { + Version string `json:"version"` + Agent commonChatIdentity `json:"agent"` + AgentGeneration int64 `json:"agentGeneration"` + Namespace commonChatIdentity `json:"namespace"` + Binding commonChatBinding `json:"binding"` + Revision string `json:"revision"` + PlanHash string `json:"planHash"` + Workloads []commonChatWorkload `json:"workloads"` + Sources []commonChatSource `json:"sources"` + Controls []unstructured.Unstructured `json:"controls"` +} + +func commonExpectationName(namespace string, uid types.UID) string { + sum := sha256.Sum256([]byte(namespace + "\x00" + string(uid))) + return "sandbox-pod-" + hex.EncodeToString(sum[:20]) +} + +func commonChatCandidate(agent *api.Agent, team *api.Team) bool { + if agent.Spec.SandboxRef == "" || agent.Status.Sandbox == nil || team == nil || !team.Spec.PolicyConfigured() || + team.UID == "" || team.UID != agent.Status.Sandbox.TeamUID || + slices.Contains(agent.Finalizers, api.SandboxHoldFinalizer) || slices.Contains(agent.Finalizers, api.SandboxPreparationFinalizer) { + return false + } + condition := meta.FindStatusCondition(agent.Status.Conditions, api.ConditionSandboxReady) + return condition != nil && condition.Status == metav1.ConditionTrue && condition.ObservedGeneration == agent.Generation && + agent.Status.Sandbox.SandboxUID != "" && agent.Status.Sandbox.AgentPolicyUID != "" && agent.Status.Sandbox.AppliedRevision != "" && + meta.IsStatusConditionTrue(agent.Status.Conditions, api.ConditionPolicyApplied) +} + +func commonChatOwned(object client.Object, agent *api.Agent) bool { + owner := metav1.GetControllerOf(object) + return len(object.GetOwnerReferences()) == 1 && owner != nil && + owner.APIVersion == api.GroupVersion.String() && owner.Kind == "Agent" && owner.Name == agent.Name && owner.UID == agent.UID +} + +func (c *Client) verifyCommonChatExpectation(ctx context.Context, agent *api.Agent, namespace *corev1.Namespace, + sts *appsv1.StatefulSet, caller chataccess.Caller, +) (commonChatExpectation, bool, error) { + var expected commonChatExpectation + state := &corev1.ConfigMap{} + if err := c.client.Get(ctx, client.ObjectKey{Namespace: c.sandboxStateNamespace, Name: commonExpectationName(namespace.Name, namespace.UID)}, state); err != nil { + return expected, false, err + } + if state.UID == "" || !state.DeletionTimestamp.IsZero() || len(state.Data) != 1 || len(state.BinaryData) != 0 || + state.Annotations[chataccess.AgentUIDAnnotation] != string(agent.UID) || !commonChatOwned(state, agent) || + !commonChatOwned(namespace, agent) || !commonChatOwned(sts, agent) { + return expected, false, nil + } + raw := state.Data[commonExpectationKey] + intentDigest, err := agent.SandboxExecutionIntentDigest() + if err != nil { + return expected, false, err + } + if len(raw) == 0 || len(raw) > 512*1024 || json.Unmarshal([]byte(raw), &expected) != nil || + expected.Version != "v2" || expected.Agent != (commonChatIdentity{Name: agent.Name, UID: agent.UID}) || + expected.AgentGeneration != agent.Generation || expected.Namespace != (commonChatIdentity{Name: namespace.Name, UID: namespace.UID}) || + expected.Revision == "" || expected.Revision != state.Annotations[commonWorkloadRevisionAnnotation] || + expected.Revision != agent.Status.Sandbox.AppliedRevision || expected.PlanHash == "" || + expected.Binding != (commonChatBinding{AgentUID: agent.UID, TeamUID: agent.Status.Sandbox.TeamUID, + SandboxUID: agent.Status.Sandbox.SandboxUID, AgentPolicyUID: agent.Status.Sandbox.AgentPolicyUID}) { + return expected, false, nil + } + agentSources := 0 + for _, source := range expected.Sources { + if source.APIVersion == api.GroupVersion.String() && source.Kind == "Agent" { + if source.Namespace != "" || source.ResourceVersion != "" || source.Name != agent.Name || source.UID != agent.UID || + source.Generation != agent.Generation || source.IntentDigest != intentDigest { + return expected, false, nil + } + agentSources++ + } + } + if agentSources != 1 || !slices.ContainsFunc(expected.Workloads, func(workload commonChatWorkload) bool { + return workload.Kind == "StatefulSet" && workload.Identity == (commonChatIdentity{Name: sts.Name, UID: sts.UID}) && + workload.Replicas == 1 && workload.Template.Annotations[commonReconciledAnnotation] == "true" && + workload.Template.Annotations[chataccess.AgentUIDAnnotation] == string(agent.UID) && + podtemplate.Same(workload.Template, sts.Spec.Template) + }) { + return expected, false, nil + } + for _, control := range expected.Controls { + if !commonChatCiliumAllows(control, agent, namespace.Name, caller, *agent.Spec.Agent.Port) { + continue + } + actual := &unstructured.Unstructured{} + actual.SetGroupVersionKind(control.GroupVersionKind()) + if err := c.client.Get(ctx, client.ObjectKeyFromObject(&control), actual); err != nil { + return expected, false, err + } + if actual.GetUID() == "" || !actual.GetDeletionTimestamp().IsZero() || !commonChatOwned(actual, agent) || + actual.GetAnnotations()[commonPolicyRevisionAnnotation] != expected.Revision || + !equality.Semantic.DeepEqual(actual.Object["spec"], control.Object["spec"]) { + return expected, false, nil + } + return expected, true, nil + } + return expected, false, nil +} + +func commonChatCiliumAllows(control unstructured.Unstructured, agent *api.Agent, namespace string, caller chataccess.Caller, port int32) bool { + if control.GetAPIVersion() != "cilium.io/v2" || control.GetKind() != "CiliumNetworkPolicy" || control.GetNamespace() != namespace || + control.GetAnnotations()[commonPolicyRevisionAnnotation] != agent.Status.Sandbox.AppliedRevision || !commonChatOwned(&control, agent) { + return false + } + selector, _, err := unstructured.NestedStringMap(control.Object, "spec", "endpointSelector", "matchLabels") + if err != nil || selector["k8s:sandbox.cetirun.microsoft.com/agent-uid"] != string(agent.UID) || + selector["k8s:io.kubernetes.pod.namespace"] != namespace { + return false + } + rules, _, err := unstructured.NestedSlice(control.Object, "spec", "ingress") + if err != nil { + return false + } + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if ok && commonChatRuleAllows(rule, caller, port) { + return true + } + } + return false +} + +func commonChatRuleAllows(rule map[string]any, caller chataccess.Caller, port int32) bool { + endpoints, _, err := unstructured.NestedSlice(rule, "fromEndpoints") + if err != nil { + return false + } + want := map[string]string{"k8s:io.kubernetes.pod.namespace": caller.Namespace} + for key, value := range caller.PodLabels { + want["k8s:"+key] = value + } + matched := false + for _, raw := range endpoints { + selector, ok := raw.(map[string]any) + if !ok { + continue + } + labels, _, err := unstructured.NestedStringMap(selector, "matchLabels") + if err == nil && maps.Equal(labels, want) { + matched = true + } + } + if !matched { + return false + } + toPorts, _, err := unstructured.NestedSlice(rule, "toPorts") + if err != nil { + return false + } + for _, raw := range toPorts { + entry, ok := raw.(map[string]any) + if !ok { + continue + } + ports, _, err := unstructured.NestedSlice(entry, "ports") + if err != nil { + continue + } + for _, raw := range ports { + item, ok := raw.(map[string]any) + if ok && item["port"] == strconv.Itoa(int(port)) && item["protocol"] == "TCP" { + return true + } + } + } + return false +} diff --git a/app/cetirun-portal/internal/kube/chat_common_test.go b/app/cetirun-portal/internal/kube/chat_common_test.go new file mode 100644 index 000000000..533247dcd --- /dev/null +++ b/app/cetirun-portal/internal/kube/chat_common_test.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package kube + +import ( + "context" + "encoding/json" + "maps" + "testing" + + api "github.com/Azure/CetiRun/app/cetirun-operator/api/v1alpha1" + "github.com/Azure/CetiRun/app/cetirun-portal/internal/chattest" + "github.com/Azure/CetiRun/app/internal/chataccess" + "github.com/Azure/CetiRun/app/internal/podtemplate" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func commonChatObjects(t *testing.T) (*api.Agent, []client.Object, *corev1.ConfigMap, commonChatExpectation) { + t.Helper() + agent, objects := chattest.Objects() + agent.Spec.SandboxRef = "sandbox-example" + agent.Status.Sandbox = &api.SandboxStatus{ + TeamUID: "synthetic-team", SandboxUID: "synthetic-sandbox", AgentPolicyUID: "synthetic-policy", AppliedRevision: "current-revision", + } + for _, kind := range []string{api.ConditionSandboxReady, api.ConditionPolicyApplied} { + agent.Status.Conditions = append(agent.Status.Conditions, metav1.Condition{ + Type: kind, Status: metav1.ConditionTrue, ObservedGeneration: agent.Generation, Reason: "SyntheticReady", LastTransitionTime: metav1.Now(), + }) + } + team := objects[6].(*api.Team) + team.Spec.AgentPolicyRef = "example-policy" + team.Spec.SandboxRefs, team.Spec.DefaultSandboxRef = []string{"sandbox-example"}, "sandbox-example" + owner := *metav1.NewControllerRef(agent, api.GroupVersion.WithKind("Agent")) + ns := objects[1].(*corev1.Namespace) + ns.OwnerReferences = []metav1.OwnerReference{owner} + objects[4].(*corev1.Service).OwnerReferences = []metav1.OwnerReference{owner} + sts := objects[2].(*appsv1.StatefulSet) + sts.Spec.Template.Annotations = map[string]string{ + commonReconciledAnnotation: "true", commonWorkloadRevisionAnnotation: agent.Status.Sandbox.AppliedRevision, + chataccess.AgentUIDAnnotation: string(agent.UID), + } + pod := objects[3].(*corev1.Pod) + sts.Spec.Template.Spec = *pod.Spec.DeepCopy() + pod.Annotations = maps.Clone(sts.Spec.Template.Annotations) + control := unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "cilium.io/v2", "kind": "CiliumNetworkPolicy", + "spec": map[string]any{ + "endpointSelector": map[string]any{"matchLabels": map[string]any{ + "k8s:sandbox.cetirun.microsoft.com/agent-uid": string(agent.UID), "k8s:io.kubernetes.pod.namespace": ns.Name, + }}, + "ingress": []any{map[string]any{ + "fromEndpoints": []any{map[string]any{"matchLabels": map[string]any{ + "k8s:io.kubernetes.pod.namespace": chattest.Caller.Namespace, "k8s:app": "test-portal", + }}}, + "toPorts": []any{map[string]any{"ports": []any{map[string]any{"port": "8080", "protocol": "TCP"}}}}, + }}, + }, + }} + control.SetName("chat-network") + control.SetNamespace(ns.Name) + control.SetUID("synthetic-policy-object") + control.SetOwnerReferences([]metav1.OwnerReference{owner}) + control.SetAnnotations(map[string]string{commonPolicyRevisionAnnotation: agent.Status.Sandbox.AppliedRevision}) + digest, err := agent.SandboxExecutionIntentDigest() + if err != nil { + t.Fatal(err) + } + expected := commonChatExpectation{ + Version: "v2", Agent: commonChatIdentity{Name: agent.Name, UID: agent.UID}, AgentGeneration: agent.Generation, + Namespace: commonChatIdentity{Name: ns.Name, UID: ns.UID}, + Binding: commonChatBinding{AgentUID: agent.UID, TeamUID: agent.Status.Sandbox.TeamUID, + SandboxUID: agent.Status.Sandbox.SandboxUID, AgentPolicyUID: agent.Status.Sandbox.AgentPolicyUID}, + Revision: agent.Status.Sandbox.AppliedRevision, PlanHash: "synthetic-plan", + Workloads: []commonChatWorkload{{Kind: "StatefulSet", Identity: commonChatIdentity{Name: sts.Name, UID: sts.UID}, + Replicas: 1, Template: *sts.Spec.Template.DeepCopy()}}, + Sources: []commonChatSource{{APIVersion: api.GroupVersion.String(), Kind: "Agent", Name: agent.Name, + UID: agent.UID, Generation: agent.Generation, IntentDigest: digest}}, + Controls: []unstructured.Unstructured{*control.DeepCopy()}, + } + state := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ + Name: commonExpectationName(ns.Name, ns.UID), Namespace: "cetirun-system", UID: "synthetic-expectation", + Annotations: map[string]string{chataccess.AgentUIDAnnotation: string(agent.UID), + commonWorkloadRevisionAnnotation: agent.Status.Sandbox.AppliedRevision}, + OwnerReferences: []metav1.OwnerReference{owner}, + }} + writeCommonChatExpectation(t, state, expected) + return agent, append(objects, state, &control), state, expected +} + +func writeCommonChatExpectation(t *testing.T, state *corev1.ConfigMap, expected commonChatExpectation) { + t.Helper() + raw, err := json.Marshal(expected) + if err != nil { + t.Fatal(err) + } + state.Data = map[string]string{commonExpectationKey: string(raw)} +} + +func TestCommonChatRequiresCurrentOwnedExecution(t *testing.T) { + for name, mutate := range map[string]func(*api.Agent, []client.Object, *commonChatExpectation){ + "current": func(*api.Agent, []client.Object, *commonChatExpectation) {}, + "old generation": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { e.AgentGeneration-- }, + "foreign binding": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { e.Binding.TeamUID = "other" }, + "missing intent": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { e.Sources[0].IntentDigest = "" }, + "namespaced Agent": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { + e.Sources[0].Namespace = "foreign" + }, + "duplicate Agent": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { + e.Sources = append(e.Sources, e.Sources[0]) + }, + "reauthorization changed": func(a *api.Agent, _ []client.Object, _ *commonChatExpectation) { + a.Annotations = map[string]string{api.AnnotationSandboxReauthorize: "changed"} + }, + "foreign namespace": func(_ *api.Agent, o []client.Object, _ *commonChatExpectation) { + o[1].SetOwnerReferences(nil) + }, + "replaced Team": func(_ *api.Agent, o []client.Object, _ *commonChatExpectation) { o[6].SetUID("other") }, + "foreign service": func(_ *api.Agent, o []client.Object, _ *commonChatExpectation) { o[4].SetOwnerReferences(nil) }, + "unready policy": func(a *api.Agent, _ []client.Object, _ *commonChatExpectation) { + for i := range a.Status.Conditions { + if a.Status.Conditions[i].Type == api.ConditionPolicyApplied { + a.Status.Conditions[i].Status = metav1.ConditionFalse + } + } + }, + "live policy drift": func(_ *api.Agent, o []client.Object, _ *commonChatExpectation) { + o[len(o)-1].(*unstructured.Unstructured).Object["spec"].(map[string]any)["ingress"] = []any{} + }, + "wrong workload revision": func(_ *api.Agent, o []client.Object, _ *commonChatExpectation) { + o[3].(*corev1.Pod).Annotations[commonWorkloadRevisionAnnotation] = "old-revision" + }, + "wrong caller": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { + rule := e.Controls[0].Object["spec"].(map[string]any)["ingress"].([]any)[0].(map[string]any) + rule["fromEndpoints"] = []any{map[string]any{"matchLabels": map[string]any{"k8s:io.kubernetes.pod.namespace": "foreign"}}} + }, + "wrong port": func(_ *api.Agent, _ []client.Object, e *commonChatExpectation) { + rule := e.Controls[0].Object["spec"].(map[string]any)["ingress"].([]any)[0].(map[string]any) + rule["toPorts"] = []any{map[string]any{"ports": []any{map[string]any{"port": "9000", "protocol": "TCP"}}}} + }, + } { + t.Run(name, func(t *testing.T) { + agent, objects, state, expected := commonChatObjects(t) + mutate(agent, objects, &expected) + writeCommonChatExpectation(t, state, expected) + target, err := NewClient(newFakeClient(objects...)).ResolveChat(context.Background(), agent, chattest.Caller) + if err != nil || target.Available != (name == "current") { + t.Fatalf("available=%v reason=%s err=%v", target.Available, target.Reason, err) + } + }) + } +} + +func TestCommonChatTemplateAllowsOnlyAPIDefaults(t *testing.T) { + for name, mutate := range map[string]func(*corev1.PodTemplateSpec){ + "defaults": func(*corev1.PodTemplateSpec) {}, + "image": func(p *corev1.PodTemplateSpec) { p.Spec.Containers[0].Image = "registry.example.com/changed:1" }, + "command": func(p *corev1.PodTemplateSpec) { p.Spec.Containers[0].Command = []string{"changed"} }, + "privilege": func(p *corev1.PodTemplateSpec) { + p.Spec.Containers[0].SecurityContext = &corev1.SecurityContext{Privileged: ptr.To(true)} + }, + "environment": func(p *corev1.PodTemplateSpec) { + p.Spec.Containers[0].Env = []corev1.EnvVar{{Name: "CHANGED", Value: "true"}} + }, + } { + t.Run(name, func(t *testing.T) { + agent, objects, _, _ := commonChatObjects(t) + template := &objects[2].(*appsv1.StatefulSet).Spec.Template + if err := podtemplate.DefaultSpec(&template.Spec); err != nil { + t.Fatal(err) + } + mutate(template) + target, err := NewClient(newFakeClient(objects...)).ResolveChat(context.Background(), agent, chattest.Caller) + if err != nil || target.Available != (name == "defaults") { + t.Fatalf("available=%v err=%v", target.Available, err) + } + }) + } +} diff --git a/app/cetirun-portal/internal/kube/client.go b/app/cetirun-portal/internal/kube/client.go index 47cc5e5c6..1b74f42b3 100644 --- a/app/cetirun-portal/internal/kube/client.go +++ b/app/cetirun-portal/internal/kube/client.go @@ -127,6 +127,7 @@ type Client struct { chartVersionExp time.Time operatorDomain string registryCredentialNamespace string + sandboxStateNamespace string } // ConfigurationCoordination serializes writes protected by the optional @@ -139,7 +140,14 @@ type ConfigurationCoordination interface { // NewClient creates a new kube Client. func NewClient(c client.Client) *Client { - return &Client{client: c} + return &Client{client: c, sandboxStateNamespace: "cetirun-system"} +} + +// SetSandboxStateNamespace selects the operator-owned common execution state. +func (c *Client) SetSandboxStateNamespace(namespace string) { + if namespace != "" { + c.sandboxStateNamespace = namespace + } } // SetConfigurationCoordination enables coordinated Team, Sandbox and diff --git a/app/cetirun-portal/main.go b/app/cetirun-portal/main.go index 342bd5bbb..16aa342d9 100644 --- a/app/cetirun-portal/main.go +++ b/app/cetirun-portal/main.go @@ -98,6 +98,7 @@ func main() { // Create handlers. kubeClient := kube.NewClient(k8sClient) + kubeClient.SetSandboxStateNamespace(cfg.SandboxStateNamespace) if cfg.ConfigurationCoordinationName != "" || cfg.ConfigurationCoordinationNamespace != "" || cfg.ConfigurationCoordinationUID != "" { coordination, err := configurationcoordination.New(k8sClient, k8sClient, configurationcoordination.Authority{ Namespace: cfg.ConfigurationCoordinationNamespace, diff --git a/app/cetirun-portal/web/src/api/adminPolicy.ts b/app/cetirun-portal/web/src/api/adminPolicy.ts index 78ba4d3c3..56defb4be 100644 --- a/app/cetirun-portal/web/src/api/adminPolicy.ts +++ b/app/cetirun-portal/web/src/api/adminPolicy.ts @@ -4,7 +4,7 @@ import { apiFetch } from "./fetch"; import type { AgentPolicyRateLimits } from "../types/rateLimits"; -export type PolicyHarness = "openclaw" | "hermes"; +export type PolicyHarness = "openclaw" | "hermes" | "custom"; export interface AgentPolicyGatewayBudget { defaultMonthlyUSD: string; diff --git a/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.test.tsx b/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.test.tsx index 96016d041..fcb300155 100644 --- a/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.test.tsx +++ b/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.test.tsx @@ -59,6 +59,17 @@ describe("PolicyEditPage", () => { vi.mocked(policyAPI.updatePolicy).mockReset(); }); + it("preserves Custom policy permission and supports explicit removal", async () => { + const policy: policyAPI.AgentPolicyDTO = { ...cachedPolicy, harnesses: { allowed: ["custom"] } }; + expect(toPolicyRequest(fromPolicyDTO(policy)).harnesses.allowed).toEqual(["custom"]); + renderCachedPolicy(policy); + const custom = screen.getByRole("switch", { name: "Custom" }); + expect(custom).toBeChecked(); + expect(screen.getByRole("switch", { name: "OpenClaw" })).not.toBeChecked(); + await userEvent.setup().click(custom); + expect(custom).not.toBeChecked(); + }); + it("shows one-per-line examples for list fields", () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); render( diff --git a/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.tsx b/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.tsx index 97dbd626e..ef55f71c2 100644 --- a/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.tsx +++ b/app/cetirun-portal/web/src/pages/admin/PolicyEditPage.tsx @@ -7,7 +7,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Button, Divider, Field, Input, MessageBar, Select, Spinner, Switch, Text, Textarea, Title2 } from "@fluentui/react-components"; import { createPolicy, getPolicy, updatePolicy, PolicyConflictError, type AgentPolicyDTO, - type AgentPolicyPort, type AgentPolicyProtocol, type AgentPolicyUpsertRequest, + type AgentPolicyPort, type AgentPolicyProtocol, type AgentPolicyUpsertRequest, type PolicyHarness, } from "../../api/adminPolicy"; import { emptyRateLimitForm, @@ -21,14 +21,14 @@ import { import { InternalNetworkRules, formatInternalNetworkRules, parseInternalNetworkRules, validCIDR, type InternalNetworkRule } from "./InternalNetworkRules"; export interface PolicyFormState { - name: string; uid: string; resourceVersion: string; openclaw: boolean; hermes: boolean; skills: string; + name: string; uid: string; resourceVersion: string; openclaw: boolean; hermes: boolean; custom: boolean; skills: string; copilot: boolean; sharedModels: string; budgetEnabled: boolean; defaultMonthlyUSD: string; maxMonthlyUSD: string; allowMultiple: boolean; readOnlyRootFilesystem: boolean; blockedCIDRs: string; blockedPorts: AgentPolicyPort[]; allowedInternalCIDRs: InternalNetworkRule[]; ingressMode: "authenticated" | "disabled"; limits: RateLimitForm; } const emptyForm: PolicyFormState = { - name: "", uid: "", resourceVersion: "", openclaw: true, hermes: false, skills: "", copilot: false, + name: "", uid: "", resourceVersion: "", openclaw: true, hermes: false, custom: false, skills: "", copilot: false, sharedModels: "", budgetEnabled: false, defaultMonthlyUSD: "", maxMonthlyUSD: "", allowMultiple: false, readOnlyRootFilesystem: true, blockedCIDRs: "", blockedPorts: [], allowedInternalCIDRs: [], ingressMode: "authenticated", limits: emptyRateLimitForm, }; @@ -39,6 +39,7 @@ export function fromPolicyDTO(policy: AgentPolicyDTO): PolicyFormState { return { name: policy.name, uid: policy.uid, resourceVersion: policy.resourceVersion, openclaw: policy.harnesses.allowed.includes("openclaw"), hermes: policy.harnesses.allowed.includes("hermes"), + custom: policy.harnesses.allowed.includes("custom"), skills: (policy.skills?.allowed || []).join("\n"), copilot: !!policy.modelAccess?.copilot?.allowed, sharedModels: (policy.modelAccess?.sharedModels?.allowed || []).join("\n"), budgetEnabled: !!policy.modelAccess?.gatewayBudget, defaultMonthlyUSD: policy.modelAccess?.gatewayBudget?.defaultMonthlyUSD || "", maxMonthlyUSD: policy.modelAccess?.gatewayBudget?.maxMonthlyUSD || "", @@ -50,9 +51,10 @@ export function fromPolicyDTO(policy: AgentPolicyDTO): PolicyFormState { } export function toPolicyRequest(form: PolicyFormState, baseline?: PolicyFormState): AgentPolicyUpsertRequest { - const allowed = [] as ("openclaw" | "hermes")[]; + const allowed: PolicyHarness[] = []; if (form.openclaw) allowed.push("openclaw"); if (form.hermes) allowed.push("hermes"); + if (form.custom) allowed.push("custom"); const request: AgentPolicyUpsertRequest = { name: form.name.trim(), uid: form.uid || undefined, resourceVersion: form.resourceVersion || undefined, harnesses: { allowed }, skills: { allowed: lines(form.skills) }, @@ -189,6 +191,7 @@ export function PolicyEditPage() { Allowed harnesses setForm({ ...form, openclaw: data.checked })} /> setForm({ ...form, hermes: data.checked })} /> + setForm({ ...form, custom: data.checked })} />