diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c68386b5b..df9cd9518 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -321,6 +321,7 @@ jobs: - 'scripts/tests/test-oauth2-proxy-sso-redirects.sh' - 'scripts/tests/longhorn-ui-readonly/**' - 'scripts/tests/test-dex-theme-mount.sh' + - 'scripts/tests/customer-agent/**' - 'scripts/tests/test-umami-tracking-probe.sh' - 'scripts/tests/fixtures/umami-curl-stub.sh' - 'scripts/verify-umami-tracking.sh' @@ -3707,6 +3708,12 @@ jobs: env: LONGHORN_UI_NATIVE_TEST: "1" run: go test -race -count=1 -v ./scripts/tests/longhorn-ui-readonly + - name: 🔐 Prove native portal machine token boundaries + if: matrix.suite == 'native' + timeout-minutes: 5 + env: + CUSTOMER_AGENT_NATIVE_TEST: "1" + run: go test -count=1 -timeout=4m -v ./scripts/tests/customer-agent - name: 🐤 Validate staged OpenBao standby repair if: matrix.suite == 'contracts' run: | diff --git a/docs/portal-machine-identity.md b/docs/portal-machine-identity.md new file mode 100644 index 000000000..8c283f121 --- /dev/null +++ b/docs/portal-machine-identity.md @@ -0,0 +1,89 @@ +# Portal machine identity + +The customer Dex is prepared with a confidential client `business-portal-agent` +for portal automation. Its client-credentials grant is disabled in production. +The client has no browser redirect and no cross-client trust. It is separate +from the `business-portal` browser client and represents no human user. + +The native vault-seed Password generator creates its credential once in a durable +Kubernetes Secret. Its create-only PushSecret stores it at +`apps/customer-identity/portal-agent-client`, property `client-secret`, in OpenBao. +An ExternalSecret projects that value into customer Dex through +`CUSTOMER_PORTAL_AGENT_CLIENT_SECRET`. The portal needs only the issuer's public +signing keys. Agents must never read, print, copy or transmit the credential or +production tokens. A future caller receives the credential through its own +reviewed native workload projection. + +After a separate reviewed activation, request `grant_type=client_credentials` +and `scope=openid` at the issuer's token endpoint. The explicitly activated native +fixture of the pinned Dex distribution returns both `access_token` and `id_token` +as signed JWTs with these claims: + +| Claim | Value | +| --- | --- | +| `iss` | `https://login.devantler.tech` | +| `aud` | `business-portal-agent` (one string) | +| `sub` | `ChVidXNpbmVzcy1wb3J0YWwtYWdlbnQ` | +| `exp - iat` | 300 seconds | + +The subject encodes the client ID and an empty connector. The browser sign-in +verifier must refuse that subject. Dex's grant list is global: after activation, +the browser client's credential can also obtain client-credentials tokens, but those have the +browser audience and its own empty-connector subject. Neither token belongs to +the portal's machine allow-list or its human sign-in flow. Refresh tokens and +`offline_access` are unavailable for client credentials. + +## Activation and acceptance + +The production grant list contains only `authorization_code`, so both the +browser and machine clients are refused client-credentials issuance. Preparing +the static client and its credential does not enable that grant or portal API +access. + +Activation is tracked separately in [#6448](https://github.com/devantler-tech/platform/issues/6448). +It requires a reviewed Git change after a signed business-site +release supporting the strict machine verifier and rejecting empty-connector +subjects in browser sign-in is deployed and verified. The supporting source is +[business-site #665](https://github.com/devantler-tech/business-site/pull/665); +source merge alone does not establish deployment. Only then enable the Dex grant +and add the following non-secret settings to the platform's portal-settings +projection, starting with no write grants: + +```dotenv +PORTAL_AGENT_AUDIENCE=business-portal-agent +PORTAL_AGENT_SUBJECTS=[{"issuer":"https://login.devantler.tech","subject":"ChVidXNpbmVzcy1wb3J0YWwtYWdlbnQ","grants":[]}] +``` + +The native regression exercises the exact first-party image selected by the +customer Dex HelmRelease with disposable synthetic credentials and memory +storage. It first proves the actual production grant configuration refuses both +clients with `unsupported_grant_type` and emits no tokens. Only after that proof +passes does it add `client_credentials` to a copied configuration in memory for +an explicitly activated test-only fixture. That fixture verifies both +signatures, the identity and lifetime of both tokens, wrong-credential and +offline-access refusals, the browser client's separate identity, and rejection +of a browser redirect for the machine client: + +```sh +CUSTOMER_AGENT_NATIVE_TEST=1 go test -count=1 -v ./scripts/tests/customer-agent +``` + +Production acceptance still requires normal protected GitOps deployment, +metadata-only readback of generation, PushSecret and projection readiness, and +an approved native verifier that obtains a token internally and calls the live +portal API without exposing credentials, tokens, or response data to logs. +Verify a read succeeds, an ungranted write fails, and browser/machine credentials +cannot cross either authentication boundary. Synthetic native proof does not +establish this production outcome. + +## Pinned source + +The deployed image's build record names Dex revision +`75eb19238e10fc4750e7efb05a4031b254b04029`. Its +[client-credentials handler](https://github.com/dexidp/dex/blob/75eb19238e10fc4750e7efb05a4031b254b04029/server/grants/clientcredentials.go) +uses the client ID with an empty connector. Its +[token issuer](https://github.com/dexidp/dex/blob/75eb19238e10fc4750e7efb05a4031b254b04029/server/tokens/issuer.go) +signs both token types with the configured ID-token lifetime. The +[claims implementation](https://github.com/dexidp/dex/blob/75eb19238e10fc4750e7efb05a4031b254b04029/server/tokens/claims.go) +encodes that subject and uses the requesting client as the sole audience when no +cross-client scope is requested. diff --git a/k8s/bases/infrastructure/vault-config/job.yaml b/k8s/bases/infrastructure/vault-config/job.yaml index 78ff4fbe7..e43585cba 100644 --- a/k8s/bases/infrastructure/vault-config/job.yaml +++ b/k8s/bases/infrastructure/vault-config/job.yaml @@ -1131,6 +1131,9 @@ spec: path "secret/data/apps/customer-identity/portal-client" { capabilities = ["create", "update", "read"] } + path "secret/data/apps/customer-identity/portal-agent-client" { + capabilities = ["create", "update", "read"] + } # The portal database's two login passwords (create-only seed) # and its CA certificate, pushed from the business-site # namespace for the portal's projected Secret. Exact keys only. @@ -1212,6 +1215,9 @@ spec: path "secret/metadata/apps/customer-identity/portal-client" { capabilities = ["create", "update", "read"] } + path "secret/metadata/apps/customer-identity/portal-agent-client" { + capabilities = ["create", "update", "read"] + } path "secret/metadata/apps/business-site/portal-db" { capabilities = ["create", "update", "read"] } diff --git a/k8s/bases/infrastructure/vault-seed/external-secret-generated-customer-identity-portal-agent-client.yaml b/k8s/bases/infrastructure/vault-seed/external-secret-generated-customer-identity-portal-agent-client.yaml new file mode 100644 index 000000000..2782ab71e --- /dev/null +++ b/k8s/bases/infrastructure/vault-seed/external-secret-generated-customer-identity-portal-agent-client.yaml @@ -0,0 +1,16 @@ +apiVersion: external-secrets.io/v1 +kind: ExternalSecret +metadata: + name: generated-customer-identity-portal-agent-client + namespace: openbao +spec: + refreshInterval: "0" + target: + name: generated-customer-identity-portal-agent-client + creationPolicy: Owner + dataFrom: + - sourceRef: + generatorRef: + apiVersion: generators.external-secrets.io/v1alpha1 + kind: Password + name: customer-identity-portal-agent-client diff --git a/k8s/bases/infrastructure/vault-seed/kustomization.yaml b/k8s/bases/infrastructure/vault-seed/kustomization.yaml index 4917c6f2a..350f7fe7b 100644 --- a/k8s/bases/infrastructure/vault-seed/kustomization.yaml +++ b/k8s/bases/infrastructure/vault-seed/kustomization.yaml @@ -32,6 +32,9 @@ resources: - password-customer-identity-portal-client.yaml - external-secret-generated-customer-identity-portal-client.yaml - push-secret-push-customer-identity-portal-client.yaml + - password-customer-identity-portal-agent-client.yaml + - external-secret-generated-customer-identity-portal-agent-client.yaml + - push-secret-push-customer-identity-portal-agent-client.yaml - password-business-site-portal-db-migrator.yaml - password-business-site-portal-db-web.yaml - external-secret-generated-business-site-portal-db-migrator.yaml diff --git a/k8s/bases/infrastructure/vault-seed/password-customer-identity-portal-agent-client.yaml b/k8s/bases/infrastructure/vault-seed/password-customer-identity-portal-agent-client.yaml new file mode 100644 index 000000000..f4196a253 --- /dev/null +++ b/k8s/bases/infrastructure/vault-seed/password-customer-identity-portal-agent-client.yaml @@ -0,0 +1,11 @@ +apiVersion: generators.external-secrets.io/v1alpha1 +kind: Password +metadata: + name: customer-identity-portal-agent-client + namespace: openbao +spec: + length: 48 + digits: 12 + symbols: 0 + noUpper: false + allowRepeat: true diff --git a/k8s/bases/infrastructure/vault-seed/push-secret-push-customer-identity-portal-agent-client.yaml b/k8s/bases/infrastructure/vault-seed/push-secret-push-customer-identity-portal-agent-client.yaml new file mode 100644 index 000000000..46efaac9b --- /dev/null +++ b/k8s/bases/infrastructure/vault-seed/push-secret-push-customer-identity-portal-agent-client.yaml @@ -0,0 +1,22 @@ +# Native generation and durable custody, separate from the browser client. +# Create-only preserves the restored OpenBao credential after a cluster rebuild. +apiVersion: external-secrets.io/v1alpha1 +kind: PushSecret +metadata: + name: push-customer-identity-portal-agent-client + namespace: openbao +spec: + refreshInterval: 1h + updatePolicy: IfNotExists + secretStoreRefs: + - name: openbao + kind: ClusterSecretStore + selector: + secret: + name: generated-customer-identity-portal-agent-client + data: + - match: + secretKey: password + remoteRef: + remoteKey: apps/customer-identity/portal-agent-client + property: client-secret diff --git a/k8s/providers/hetzner/apps/customer-identity/external-secret-dex-portal-agent-client.yaml b/k8s/providers/hetzner/apps/customer-identity/external-secret-dex-portal-agent-client.yaml new file mode 100644 index 000000000..ccd0f3d0e --- /dev/null +++ b/k8s/providers/hetzner/apps/customer-identity/external-secret-dex-portal-agent-client.yaml @@ -0,0 +1,20 @@ +# The machine client's own credential, generated and retained by vault-seed. +# Projected only into customer Dex; the portal verifies signed JWTs using JWKS. +apiVersion: external-secrets.io/v1 +kind: ExternalSecret +metadata: + name: customer-dex-portal-agent-client + namespace: customer-identity +spec: + refreshInterval: 1h + secretStoreRef: + name: openbao + kind: ClusterSecretStore + target: + name: customer-dex-portal-agent-client + creationPolicy: Owner + data: + - secretKey: client-secret + remoteRef: + key: apps/customer-identity/portal-agent-client + property: client-secret diff --git a/k8s/providers/hetzner/apps/customer-identity/helm-release-dex.yaml b/k8s/providers/hetzner/apps/customer-identity/helm-release-dex.yaml index f4a486d16..c35676525 100644 --- a/k8s/providers/hetzner/apps/customer-identity/helm-release-dex.yaml +++ b/k8s/providers/hetzner/apps/customer-identity/helm-release-dex.yaml @@ -124,6 +124,11 @@ spec: secretKeyRef: name: customer-dex-portal-client key: client-secret + - name: CUSTOMER_PORTAL_AGENT_CLIENT_SECRET + valueFrom: + secretKeyRef: + name: customer-dex-portal-agent-client + key: client-secret config: issuer: https://login.devantler.tech # The Devantler Tech theme, as on the platform Dex: the wordmark as the @@ -199,3 +204,10 @@ spec: # The portal is served at the root of its own host. redirectURIs: - https://portal.devantler.tech/callback + # No redirect or cross-client trust: this client represents itself only. + # Portal authorization is a separate, initially disabled allow-list. + - id: business-portal-agent + name: Devantler Tech portal agent + public: false + secretEnv: CUSTOMER_PORTAL_AGENT_CLIENT_SECRET + redirectURIs: [] diff --git a/k8s/providers/hetzner/apps/customer-identity/kustomization.yaml b/k8s/providers/hetzner/apps/customer-identity/kustomization.yaml index 9230ebc88..85505d94d 100644 --- a/k8s/providers/hetzner/apps/customer-identity/kustomization.yaml +++ b/k8s/providers/hetzner/apps/customer-identity/kustomization.yaml @@ -29,6 +29,7 @@ resources: - external-secret-db-dex.yaml - database-dex.yaml - external-secret-dex-portal-client.yaml + - external-secret-dex-portal-agent-client.yaml - helm-repository-dex.yaml - config-map-dex-theme.yaml - helm-release-dex.yaml diff --git a/scripts/tests/customer-agent/fixture_test.go b/scripts/tests/customer-agent/fixture_test.go new file mode 100644 index 000000000..6250600dc --- /dev/null +++ b/scripts/tests/customer-agent/fixture_test.go @@ -0,0 +1,123 @@ +package customeragent_test + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "os/exec" + "regexp" + "strings" + "testing" + "time" +) + +type nativeFixture struct { + client *http.Client + baseURL string +} + +func nativeDockerOutput(t *testing.T, args ...string) []byte { + t.Helper() + output, err := exec.CommandContext(t.Context(), "docker", args...).Output() + if err != nil { + t.Fatalf("owned native fixture Docker operation %s failed: %v", args[0], err) + } + return output +} + +func ownedNativeContainer(t *testing.T, args ...string) string { + t.Helper() + id := bytes.TrimSpace(nativeDockerOutput(t, args...)) + if !regexp.MustCompile(`^[a-f0-9]{64}$`).Match(id) { + t.Fatal("owned native fixture did not return a container ID") + } + containerID := string(id) + t.Cleanup(func() { + // The test context is cancelled before cleanups; cleanup needs its own bound. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := exec.CommandContext(ctx, "docker", "rm", "--force", containerID).Run(); err != nil { + t.Error("owned native fixture container cleanup failed") + } + }) + return containerID +} + +func nativeFixtureEndpoint(t *testing.T, containerID, port string) nativeFixture { + t.Helper() + endpoint := strings.TrimSpace(string(nativeDockerOutput(t, "port", containerID, port))) + if !strings.HasPrefix(endpoint, "127.0.0.1:") { + t.Fatal("could not resolve the fixture's loopback-only endpoint") + } + return nativeFixture{ + baseURL: "http://" + endpoint, + client: &http.Client{Timeout: 2 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }}, + } +} + +func (fixture nativeFixture) get(t *testing.T, path string) (*http.Response, error) { + t.Helper() + request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fixture.baseURL+path, nil) + if err != nil { + t.Fatal(err) + } + return fixture.client.Do(request) +} + +func (fixture nativeFixture) waitReady(t *testing.T, path string) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + response, err := fixture.get(t, path) + ready := err == nil && response.StatusCode == http.StatusOK + if response != nil { + _ = response.Body.Close() + } + if ready { + return + } + if time.Now().After(deadline) { + t.Fatal("isolated native fixture did not become ready") + } + time.Sleep(100 * time.Millisecond) + } +} + +func (fixture nativeFixture) jsonRequest(t *testing.T, token, method, path string, payload any) (int, map[string]any) { + t.Helper() + var input io.Reader + if payload != nil { + data, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + input = bytes.NewReader(data) + } + request, err := http.NewRequestWithContext(t.Context(), method, fixture.baseURL+"/v1/"+path, input) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-Vault-Token", token) + response, err := fixture.client.Do(request) + if err != nil { + t.Fatal("native synthetic ACL request failed") + } + defer closeFixtureResponse(t, response) + result := map[string]any{} + if response.StatusCode != http.StatusNoContent && json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&result) != nil { + t.Fatal("native ACL response was invalid") + } + return response.StatusCode, result +} + +func closeFixtureResponse(t *testing.T, response *http.Response) { + t.Helper() + if err := response.Body.Close(); err != nil { + t.Error("native fixture response could not close") + } +} diff --git a/scripts/tests/customer-agent/native_test.go b/scripts/tests/customer-agent/native_test.go new file mode 100644 index 000000000..ae9312d2a --- /dev/null +++ b/scripts/tests/customer-agent/native_test.go @@ -0,0 +1,269 @@ +package customeragent_test + +import ( + "crypto" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "maps" + "math/big" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "sigs.k8s.io/yaml" +) + +// Preparation must refuse issuance before a test-only activation characterizes +// the pinned distribution's token claims. Production activation is separate. +func TestNativeCustomerAgentTokens(t *testing.T) { + if os.Getenv("CUSTOMER_AGENT_NATIVE_TEST") != "1" { + t.Skip("set CUSTOMER_AGENT_NATIVE_TEST=1 for the isolated native Dex proof") + } + image, production := nativeDexConfiguration(t) + if !t.Run("production grant stays disabled", func(t *testing.T) { + fixture := nativeDexFixture(t, image, production) + for _, client := range []struct{ id, secret string }{ + {"business-portal-agent", "synthetic-agent-fixture"}, + {"business-portal", "synthetic-browser-fixture"}, + } { + status, body := fixture.tokens(t, client.id, client.secret, "openid") + if status != http.StatusBadRequest || body["error"] != "unsupported_grant_type" || + body["access_token"] != nil || body["id_token"] != nil || body["refresh_token"] != nil { + t.Errorf("production must refuse client credentials for %s: status=%d error=%v", client.id, status, body["error"]) + } + } + }) { + return + } + t.Run("explicit test-only activation", func(t *testing.T) { + activated := activatedFixtureGrant(t, production) + fixture := nativeDexFixture(t, image, activated) + assertActivatedCustomerAgentTokens(t, fixture) + }) +} + +func assertActivatedCustomerAgentTokens(t *testing.T, fixture nativeFixture) { + t.Helper() + key := fixtureSigningKey(t, fixture) + status, body := fixture.tokens(t, "business-portal-agent", "synthetic-agent-fixture", "openid") + if status != http.StatusOK { + t.Fatalf("native agent grant failed: status=%d error=%v", status, body["error"]) + } + for _, field := range []string{"access_token", "id_token"} { + claims := verifiedFixtureClaims(t, key, body[field]) + if claims["iss"] != "https://login.devantler.tech" || claims["sub"] != "ChVidXNpbmVzcy1wb3J0YWwtYWdlbnQ" || claims["aud"] != "business-portal-agent" { + t.Fatalf("%s has an unexpected native identity", field) + } + iat, iatOK := claims["iat"].(float64) + exp, expOK := claims["exp"].(float64) + if !iatOK || !expOK || exp-iat != 300 || exp <= float64(time.Now().Unix()) { + t.Fatalf("%s does not have the required five-minute native lifetime", field) + } + } + if body["refresh_token"] != nil { + t.Fatal("machine grant unexpectedly issued a refresh token") + } + if status, body := fixture.tokens(t, "business-portal-agent", "wrong-synthetic-secret", "openid"); status == http.StatusOK || body["error"] != "invalid_client" { + t.Fatal("wrong machine credential was not rejected") + } + if status, body := fixture.tokens(t, "business-portal-agent", "synthetic-agent-fixture", "openid offline_access"); status == http.StatusOK || body["error"] != "invalid_scope" { + t.Fatal("machine grant did not refuse offline access") + } + // oauth2.grantTypes is global. The browser client's credential can therefore + // mint only its own identity; the portal must reject both tokens at its agent + // boundary and reject the empty-connector subject at its human boundary. + status, browser := fixture.tokens(t, "business-portal", "synthetic-browser-fixture", "openid") + if status != http.StatusOK { + t.Fatal("browser-client negative control could not obtain its own native token") + } + for _, field := range []string{"access_token", "id_token"} { + claims := verifiedFixtureClaims(t, key, browser[field]) + if claims["aud"] != "business-portal" || claims["sub"] != "Cg9idXNpbmVzcy1wb3J0YWw" { + t.Fatal("browser credential crossed the native machine identity boundary") + } + } + if fixture.browserAuthStatus(t) != http.StatusBadRequest { + t.Fatal("machine client unexpectedly accepted a browser redirect") + } + t.Log("activated fixture: native signature, issuer, audience, subject and 300-second lifetime passed for both token types; credential, refresh and browser-flow refusals passed") +} + +func nativeDexConfiguration(t *testing.T) (string, map[string]any) { + t.Helper() + manifest, err := os.ReadFile("../../../k8s/providers/hetzner/apps/customer-identity/helm-release-dex.yaml") + if err != nil { + t.Fatal(err) + } + var release struct { + Spec struct { + Values struct { + Image struct{ Repository, Tag string } + Config map[string]any + } + } + } + if err := yaml.Unmarshal(manifest, &release); err != nil { + t.Fatal(err) + } + values := release.Spec.Values + image := values.Image.Repository + ":" + values.Image.Tag + if !strings.HasPrefix(image, "ghcr.io/devantler-tech/platform-dex:") || !strings.Contains(image, "@sha256:") { + t.Fatal("the native proof requires the pinned first-party Dex distribution") + } + return image, values.Config +} + +// The positive issuance proof is explicitly activated in memory only after the +// unchanged production grant configuration has refused both client credentials. +func activatedFixtureGrant(t *testing.T, production map[string]any) map[string]any { + t.Helper() + oauth2, ok := production["oauth2"].(map[string]any) + if !ok { + t.Fatal("the declared OAuth2 policy is missing") + } + grants, ok := oauth2["grantTypes"].([]any) + if !ok || slices.Contains(grants, any("client_credentials")) { + t.Fatal("test-only activation requires the explicit disabled production grant list") + } + activated := maps.Clone(production) + activated["oauth2"] = maps.Clone(oauth2) + activated["oauth2"].(map[string]any)["grantTypes"] = append(slices.Clone(grants), "client_credentials") + return activated +} + +func fixtureDexConfiguration(t *testing.T, production map[string]any) []byte { + t.Helper() + // Only persistence, listening and upstream human login are fixture-specific. + // Issuer, clients, supplied grant policy and expiry remain unchanged. + config := maps.Clone(production) + config["storage"] = map[string]any{"type": "memory"} + config["web"] = map[string]any{"http": "0.0.0.0:5556"} + config["enablePasswordDB"] = true + delete(config, "connectors") + delete(config, "frontend") + configBytes, err := yaml.Marshal(config) + if err != nil { + t.Fatal(err) + } + return configBytes +} + +func nativeDexFixture(t *testing.T, image string, configuration map[string]any) nativeFixture { + t.Helper() + config := fixtureDexConfiguration(t, configuration) + path := filepath.Join(t.TempDir(), "config.yaml") + // This contains only synthetic fixture references; the non-root image must + // read the copied file. Its parent is the test's private temporary directory. + if err := os.WriteFile(path, config, 0644); err != nil { + t.Fatal(err) + } + // These literal credentials exist only in this disposable memory-backed Dex. + id := ownedNativeContainer(t, "create", "--platform=linux/amd64", + "--cap-drop=ALL", "--security-opt=no-new-privileges", "--memory=256m", "--pids-limit=128", + "--publish", "127.0.0.1::5556", + "--env", "CUSTOMER_PORTAL_CLIENT_SECRET=synthetic-browser-fixture", + "--env", "CUSTOMER_PORTAL_AGENT_CLIENT_SECRET=synthetic-agent-fixture", + image, "dex", "serve", "/tmp/config.yaml") + // Copy through Docker: bind mounts would read the remote daemon's paths. + nativeDockerOutput(t, "cp", path, id+":/tmp/config.yaml") + nativeDockerOutput(t, "start", id) + fixture := nativeFixtureEndpoint(t, id, "5556/tcp") + fixture.waitReady(t, "/.well-known/openid-configuration") + return fixture +} + +func (fixture nativeFixture) tokens(t *testing.T, clientID, secret, scope string) (int, map[string]any) { + t.Helper() + form := url.Values{"grant_type": {"client_credentials"}, "scope": {scope}} + request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fixture.baseURL+"/token", strings.NewReader(form.Encode())) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + request.SetBasicAuth(clientID, secret) + response, err := fixture.client.Do(request) + if err != nil { + t.Fatal("native synthetic token request failed") + } + defer closeFixtureResponse(t, response) + var body map[string]any + if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&body); err != nil { + t.Fatal("native token response was invalid") + } + return response.StatusCode, body +} + +func (fixture nativeFixture) browserAuthStatus(t *testing.T) int { + t.Helper() + response, err := fixture.get(t, "/auth?"+url.Values{"client_id": {"business-portal-agent"}, "response_type": {"code"}, "scope": {"openid"}, "redirect_uri": {"https://portal.devantler.tech/callback"}}.Encode()) + if err != nil { + t.Fatal("machine browser-flow negative control failed") + } + // Dex selects the connector before it validates the redirect. Follow only + // relative auth routes on this owned fixture, never an upstream or callback. + for hops := 0; hops < 3 && response.StatusCode == http.StatusFound; hops++ { + location := response.Header.Get("Location") + if !strings.HasPrefix(location, "/auth/") { + break + } + _ = response.Body.Close() + response, err = fixture.get(t, location) + if err != nil { + t.Fatal("machine browser-flow connector refusal failed") + } + } + defer closeFixtureResponse(t, response) + return response.StatusCode +} + +func fixtureSigningKey(t *testing.T, fixture nativeFixture) *rsa.PublicKey { + t.Helper() + response, err := fixture.get(t, "/keys") + if err != nil { + t.Fatal("native signing-key read failed") + } + defer closeFixtureResponse(t, response) + var set struct{ Keys []struct{ Kty, N, E string } } + if response.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&set) != nil || len(set.Keys) != 1 || set.Keys[0].Kty != "RSA" { + t.Fatal("unexpected native signing-key set") + } + n, nErr := base64.RawURLEncoding.DecodeString(set.Keys[0].N) + e, eErr := base64.RawURLEncoding.DecodeString(set.Keys[0].E) + if nErr != nil || eErr != nil || len(n) < 256 { + t.Fatal("invalid native signing key") + } + return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())} +} + +func verifiedFixtureClaims(t *testing.T, key *rsa.PublicKey, value any) map[string]any { + t.Helper() + token, ok := value.(string) + parts := strings.Split(token, ".") + if !ok || len(parts) != 3 { + t.Fatal("native response does not contain a signed JWT") + } + header, hErr := base64.RawURLEncoding.DecodeString(parts[0]) + signature, sErr := base64.RawURLEncoding.DecodeString(parts[2]) + var metadata struct{ Alg string } + if hErr != nil || sErr != nil || json.Unmarshal(header, &metadata) != nil || metadata.Alg != "RS256" { + t.Fatal("unexpected native JWT signing algorithm") + } + digest := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + if rsa.VerifyPKCS1v15(key, crypto.SHA256, digest[:], signature) != nil { + t.Fatal("native JWT signature verification failed") + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + var claims map[string]any + if err != nil || json.Unmarshal(payload, &claims) != nil { + t.Fatal("native JWT claims could not be decoded") + } + return claims +} diff --git a/scripts/tests/customer-agent/seed_policy_test.go b/scripts/tests/customer-agent/seed_policy_test.go new file mode 100644 index 000000000..423f99e72 --- /dev/null +++ b/scripts/tests/customer-agent/seed_policy_test.go @@ -0,0 +1,116 @@ +package customeragent_test + +import ( + "net/http" + "os" + "regexp" + "strings" + "testing" + + "sigs.k8s.io/yaml" +) + +// TestNativePortalAgentSeedPolicy catches an undeployable credential chain: +// the declared ESO seed writer must create this exact key despite the app's +// more-specific read-only policy, without acquiring sibling write permission. +func TestNativePortalAgentSeedPolicy(t *testing.T) { + if os.Getenv("CUSTOMER_AGENT_NATIVE_TEST") != "1" { + t.Skip("set CUSTOMER_AGENT_NATIVE_TEST=1 for the isolated native ACL proof") + } + manifest, err := os.ReadFile("../../../k8s/bases/infrastructure/vault-config/job.yaml") + if err != nil { + t.Fatal(err) + } + fixture := nativeSeedPolicyFixture(t, manifest) + token := nativeSeedWriter(t, fixture, manifest) + const key = "apps/customer-identity/portal-agent-client" + payload := map[string]any{"data": map[string]string{"client-secret": "synthetic-agent-credential"}} + for range 2 { + status, _ := fixture.jsonRequest(t, token, http.MethodPost, "secret/data/"+key, payload) + if status != http.StatusOK { + t.Fatal("the declared seed writer cannot create and update the portal agent credential") + } + } + status, _ := fixture.jsonRequest(t, token, http.MethodGet, "secret/metadata/"+key, nil) + if status != http.StatusOK { + t.Fatal("the declared seed writer cannot read portal agent credential metadata") + } + status, _ = fixture.jsonRequest(t, token, http.MethodPost, "secret/metadata/"+key, map[string]any{"custom_metadata": map[string]string{"fixture": "synthetic"}}) + if status != http.StatusNoContent { + t.Fatal("the declared seed writer cannot update portal agent credential metadata") + } + for _, check := range []struct{ method, path string }{ + {http.MethodPost, "secret/data/" + key + "-other"}, + {http.MethodPost, "secret/data/" + key + "/child"}, + {http.MethodPost, "secret/metadata/" + key + "-other"}, + {http.MethodDelete, "secret/data/" + key}, + } { + status, _ = fixture.jsonRequest(t, token, check.method, check.path, payload) + if status != http.StatusForbidden { + t.Fatal("seed writer gained a sibling, descendant or delete permission") + } + } + status, _ = fixture.jsonRequest(t, token, http.MethodGet, "secret/data/"+key, nil) + if status != http.StatusOK { + t.Fatal("positive credential read failed after the native ACL refusal controls") + } + t.Log("native portal-agent seed grant is exact; sibling, descendant and delete refusals passed") +} + +const syntheticSeedRootToken = "synthetic-portal-agent-policy-root" + +func nativeSeedPolicyFixture(t *testing.T, manifest []byte) nativeFixture { + t.Helper() + var job struct { + Spec struct { + Template struct { + Spec struct { + Containers []struct{ Name, Image string } + } + } + } + } + if err := yaml.Unmarshal(manifest, &job); err != nil { + t.Fatal(err) + } + image := "" + for _, container := range job.Spec.Template.Spec.Containers { + if container.Name == "vault-config" && strings.HasPrefix(container.Image, "quay.io/openbao/openbao:") && strings.Contains(container.Image, "@sha256:") { + image = container.Image + } + } + if image == "" { + t.Fatal("the ACL proof requires the declared pinned OpenBao distribution") + } + id := ownedNativeContainer(t, "run", "--detach", "--rm", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges", + "--memory=256m", "--pids-limit=128", "--tmpfs", "/tmp:rw,nosuid,size=32m", "--env", "HOME=/tmp", + "--publish", "127.0.0.1::8200", "--entrypoint", "bao", image, + "server", "-dev", "-dev-root-token-id="+syntheticSeedRootToken, "-dev-listen-address=0.0.0.0:8200", "-dev-no-store-token") + fixture := nativeFixtureEndpoint(t, id, "8200/tcp") + fixture.waitReady(t, "/v1/sys/health") + return fixture +} + +func nativeSeedWriter(t *testing.T, fixture nativeFixture, manifest []byte) string { + t.Helper() + for _, name := range []string{"vault-seed-write", "app-customer-identity-readonly"} { + pattern := `(?ms)^ +bao policy write ` + regexp.QuoteMeta(name) + ` - <<'POLICY'\n(.*?)^ +POLICY\n` + matches := regexp.MustCompile(pattern).FindAllSubmatch(manifest, -1) + if len(matches) != 1 { + t.Fatal("the actual declared seed or customer reader ACL is missing or ambiguous") + } + status, _ := fixture.jsonRequest(t, syntheticSeedRootToken, http.MethodPut, "sys/policies/acl/"+name, map[string]string{"policy": string(matches[0][1])}) + if status != http.StatusNoContent { + t.Fatal("the actual declared ACL could not be installed in the pinned server") + } + } + status, result := fixture.jsonRequest(t, syntheticSeedRootToken, http.MethodPost, "auth/token/create", map[string]any{ + "policies": []string{"vault-seed-write", "app-customer-identity-readonly"}, "no_default_policy": true, "ttl": "5m", + }) + auth, _ := result["auth"].(map[string]any) + token, _ := auth["client_token"].(string) + if status != http.StatusOK || token == "" { + t.Fatal("the synthetic seed writer could not be created") + } + return token +} diff --git a/scripts/validate-eks-ci-role-policy/approved-surface.txt b/scripts/validate-eks-ci-role-policy/approved-surface.txt index eebc03033..6f2955c99 100644 --- a/scripts/validate-eks-ci-role-policy/approved-surface.txt +++ b/scripts/validate-eks-ci-role-policy/approved-surface.txt @@ -60,7 +60,7 @@ helm.toolkit.fluxcd.io/v2|HelmRelease|cnpg-system|plugin-barman-cloud 74682cb45a helm.toolkit.fluxcd.io/v2|HelmRelease|crossplane-system|crossplane fb717f7c9adb21b0f772e6a84554900e568a2675c91d375d1bb6ee76c2a0b1f3 -helm.toolkit.fluxcd.io/v2|HelmRelease|customer-identity|customer-dex 4c568faea9557d01783d606255b6aab07af01519caeca91a8349f62ceff873f5 +helm.toolkit.fluxcd.io/v2|HelmRelease|customer-identity|customer-dex 2630636e47e062cccd59b7792b71f9f7dc1d5812d60258d84649d264a6b9e595 helm.toolkit.fluxcd.io/v2|HelmRelease|customer-identity|zitadel eeb9881018664637cdefc9c5c0afd6953aa958e5dbfbc9cd8c5d521501e52431