From 9749dcbaedd65fc92d87669a6ad43571f17ede6a Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:21:03 +0100 Subject: [PATCH 01/27] feat(agent-platform): make governance a typed input that survives a reconcile The platform's governance mode and the servers muster governs become inputs of the agent-platform definition (governance.mode, governance.governedServers), rendered into the meta chart's top-level governance and governedServers and read back from the configmap patch on record, so a reconcile no longer drops them. Validation follows what muster refuses to start on and what the meta chart refuses to render. Every governance choice is refused while no meta chart release renders muster's governance configuration (GovernanceChart unset), so no installation reads as governed while its muster is not. --- definitions/agent-platform/README.md | 3 +- definitions/agent-platform/features.yaml | 1 + definitions/agent-platform/schema.json | 42 ++++ .../installations/governance_readback_test.go | 56 +++++ internal/installations/readback_test.go | 1 + internal/verify/verify_test.go | 5 +- render/agentplatform/governance.go | 200 ++++++++++++++++++ render/agentplatform/governance_test.go | 189 +++++++++++++++++ render/agentplatform/input.go | 13 +- render/agentplatform/render.go | 1 + 10 files changed, 506 insertions(+), 5 deletions(-) create mode 100644 internal/installations/governance_readback_test.go create mode 100644 render/agentplatform/governance.go create mode 100644 render/agentplatform/governance_test.go diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 60511ee6..ba98fedc 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -5,7 +5,7 @@ policy decides once, and what the definition drops. The render library reads it. | File | What it is | |---|---| -| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | +| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), the platform's governance, `governance.mode` (`trusted`, the default, or `governed`) and `governance.governedServers` (default none, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | @@ -55,6 +55,7 @@ policy decides once, and what the definition drops. The render library reads it. | The Dev Portal's Organizations pages for everyone: `agentPlatform.organizations.enabled: true` in the Component's fragment (giantswarm/backstage#3393; an object-shaped key, which merges, so on a hand-kept portal too) | `organizations.portal.enabled`, or `organizations.enabled` on this installation; the choice read back from the fragment on record, else from the portal's own app-config, so every plan that renders a shared portal's fragment keeps the pages one installation turned on; off again only typed `false` where no installation of the portal has the switch on. Refused where no portal carries a section for the installation | | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | +| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's top-level `governance` (written only as `governed`; `trusted` is the chart's default) and `governedServers`, the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on: a role it does not know (the schema), a floor of the source's role on its safe list (the typed role, else the chart's for the source), an empty or repeated safe entry, an entry with neither role nor safe list. A commit that changes either is an Action a second person approves, on Giant Swarm's test installations too; the review shows the change old → new and what loosens ([docs/governance.md](../../docs/governance.md)) | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/definitions/agent-platform/features.yaml b/definitions/agent-platform/features.yaml index 22c45b7c..94489cbc 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -93,6 +93,7 @@ features: - {id: agent-manager-route, kind: configmap, key: "agentManager.route (agent-manager's REST API on the gateway behind its JWT policy, for the credential form's backend; derived from agent-manager.credentials.uiURL)"} - {id: live-agent-manager-route-protected, kind: live, key: "https://agentgateway./agent-manager/api/v1/info answered 401 by the route's JWT policy, where agent-manager.credentials.uiURL is set"} - {id: platform-tenant-bindings, kind: configmap, key: "tenants / musterMcpServerViewers (who the platform tenant binds in the kagent namespace, and who lists muster's MCP servers)"} + - {id: governance, kind: configmap, key: "governance / governedServers (the platform's governance mode and the servers muster governs with their safe lists; changed only through an Action a second person approves)"} - {id: own-mcp-servers, kind: configmap, key: "agent-platform-mcps.mcpServers[http://.svc:8080/mcp] / agent-platform-mcps.mcpServers[://mcp-./mcp] (the installation's own: at the in-cluster Service, or on its own base domain)"} - {id: own-mcp-kubernetes-url, kind: configmap, key: "agent-platform-mcps.mcpServers[http://mcp-kubernetes.mcp-kubernetes.svc:8080/mcp].url"} - {id: muster-private-exchange, kind: configmap, key: muster.muster.oauth.mcpClient.tokenExchange.allowPrivateIP} diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index 7010e17a..f33c667f 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -853,6 +853,48 @@ } } }, + "governance": { + "type": "object", + "additionalProperties": false, + "description": "The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the mode and the servers muster governs with their safe lists, the meta chart's top-level governance and governedServers. Only admins change it, never an agent: a commit that changes either is an Action a second person approves, on Giant Swarm's test installations too, its review showing the change old -> new and naming what loosens. Refused while no meta chart release renders muster's governance configuration (the definition's GovernanceChart is unset until that release exists, giantswarm/giantswarm#38902 decision #89), off the 4 chart line and under a hold of the meta chart below that release. Read back from the configmap patch on record, so a reconcile keeps it.", + "properties": { + "mode": { + "title": "the platform's governance mode", + "type": "string", + "enum": ["trusted", "governed"], + "default": "trusted", + "x-source": "person", + "x-readback": {"file": "configmap", "key": "governance"}, + "x-feature": "tool-access", + "x-renders": ["configmap:governance"], + "description": "The platform's governance mode (the meta chart's governance): trusted, the default and not written, lets agents run what the connectors' own settings allow; governed asks a person before an agent runs any tool of a governed server not on that server's safe list, and before any of muster's own tools but its reads. muster's floors ask in both modes. governed under a hold of muster below the release that reads the governance configuration is refused, since the meta chart refuses the render there. Read back from the configmap patch on record, so a reconcile keeps it; typed (--input governance.mode=governed), it replaces it." + }, + "governedServers": { + "title": "the servers muster governs", + "type": ["object", "null"], + "default": {}, + "propertyNames": {"minLength": 1}, + "additionalProperties": { + "anyOf": [ + {"type": "null"}, + { + "type": "object", + "additionalProperties": false, + "properties": { + "role": {"type": "string", "enum": ["agentManager", "platformManager", "connectorManager", "sessionManager", "modelManager", "clusterManager", "vmManager", "workspaceManager", "toolchainManager", "skillManager", "infrastructure"], "description": "The role whose floors hold on the source's servers in both modes; left out, the meta chart's role for the source stands."}, + "safe": {"type": "array", "items": {"type": "string"}, "description": "The source's own tool names agents call unasked on governed: reads only, never a floor of its role. It replaces the meta chart's list; left out, the chart's list stands."} + } + } + ] + }, + "x-source": "person", + "x-readback": {"file": "configmap", "key": "governedServers"}, + "x-feature": "tool-access", + "x-renders": ["configmap:governedServers"], + "description": "Overrides of the meta chart's governedServers, by source: a source the chart knows (agent-manager, kagent, model-manager, cluster-manager, vm-manager, toolchain-manager, workspace-manager, skill-manager, mcp-kubernetes, giantswarm-platform-manager) or a muster server key (, /), each {role, safe} or null, which drops the source (muster governs nothing for it). Helm merges the maps: a source left out keeps the chart's entry, a role or safe list left out the chart's, a safe list typed replaces the chart's. Refused as muster refuses to start on it: an unknown role, a floor of the source's role on its safe list (typed, or the chart's role for the source), an empty or repeated safe entry, and an entry with neither role nor safe list. None, the default, the key is not written. Read back from the configmap patch on record, so a reconcile keeps it; typed (--input 'governance.governedServers={\"giantswarm-platform-manager\": {\"safe\": [\"get_info\"]}}'), it replaces it." + } + } + }, "versions": { "type": "object", "additionalProperties": false, diff --git a/internal/installations/governance_readback_test.go b/internal/installations/governance_readback_test.go new file mode 100644 index 00000000..4f5965e0 --- /dev/null +++ b/internal/installations/governance_readback_test.go @@ -0,0 +1,56 @@ +package installations + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/giantswarm/giantswarm-platform-manager/render" + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" +) + +// governanceOnRecord appends the platform's governance to a configmap patch, +// as a commit of governance.* writes it. +func governanceOnRecord(patch string) string { + return patch + "governance: governed\ngovernedServers:\n giantswarm-platform-manager:\n safe:\n - get_info\n mcp-kubernetes: null\n" +} + +// The governance on record is read back as governance.mode and +// governance.governedServers, a dropped source as null, so a reconcile +// that types nothing renders it again: it is no drift a reconcile removes. +// With the meta chart release that renders it cut, the patch read back and +// rendered again carries it byte for byte. +func TestGovernanceSurvivesAReconcile(t *testing.T) { + chart, muster := agentplatform.GovernanceChart, agentplatform.GovernanceMuster + agentplatform.GovernanceChart, agentplatform.GovernanceMuster = "4.190.0", "5.70.0" + t.Cleanup(func() { agentplatform.GovernanceChart, agentplatform.GovernanceMuster = chart, muster }) + definition, found := FindCapability(AgentPlatform) + require.True(t, found) + + patch, read, doc, marker := inputFromTheRecord(t, "platform-tenant-retired", governanceOnRecord) + require.Equal(t, agentplatform.GovernanceGoverned, read["governance.mode"]) + require.Equal(t, map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"get_info"}}, "mcp-kubernetes": nil}, read["governance.governedServers"]) + result, err := definition.Render(doc, nil, render.ModeCommit) + require.NoError(t, err) + again := string(result.Tree()["giantswarm/giantswarm-configs/"+marker]) + require.Contains(t, again, "governance: governed\n") + require.Contains(t, again, " giantswarm-platform-manager:\n safe:\n - get_info\n mcp-kubernetes: null\n") + _, _, doc, _ = inputFromTheRecord(t, "platform-tenant-retired", func(string) string { return again }) + result, err = definition.Render(doc, nil, render.ModeCommit) + require.NoError(t, err) + require.Equal(t, again, string(result.Tree()["giantswarm/giantswarm-configs/"+marker]), "rendered from %s", patch) +} + +// While no meta chart release renders the governance, a governance written +// by hand into the record is read back and refused at the reconcile, as +// when it is typed: the definition never carries a governance the +// installation's chart cannot enforce (fail closed). +func TestGovernanceOnRecordIsRefusedUntilItsReleaseExists(t *testing.T) { + require.Empty(t, agentplatform.GovernanceChart, "the governance release is unset until it is cut") + definition, found := FindCapability(AgentPlatform) + require.True(t, found) + _, read, doc, _ := inputFromTheRecord(t, "platform-tenant-retired", governanceOnRecord) + require.Equal(t, agentplatform.GovernanceGoverned, read["governance.mode"]) + _, err := definition.Render(doc, nil, render.ModeCommit) + require.ErrorContains(t, err, "(governance.mode) needs the meta chart release that renders muster's governance configuration") +} diff --git a/internal/installations/readback_test.go b/internal/installations/readback_test.go index d73ca7c3..2c3fa804 100644 --- a/internal/installations/readback_test.go +++ b/internal/installations/readback_test.go @@ -336,6 +336,7 @@ func TestDefaults(t *testing.T) { "versions": map[string]any{"chart": "", "components": holds, "reasons": map[string]any{"chart": "", "components": holds}}} want["organizations"] = map[string]any{keyEnabled: false, "apiHostnames": []any{}, "commit": map[string]any{keyEnabled: false}, "portal": map[string]any{keyEnabled: false}} + want["governance"] = map[string]any{"mode": "trusted", "governedServers": map[string]any{}} if !reflect.DeepEqual(got, want) { t.Errorf("defaults %v, want %v", got, want) } diff --git a/internal/verify/verify_test.go b/internal/verify/verify_test.go index 3f1880da..83e2edf9 100644 --- a/internal/verify/verify_test.go +++ b/internal/verify/verify_test.go @@ -670,12 +670,13 @@ func TestDrivenInputsAreThePersonsAndTheTyped(t *testing.T) { "versions.reasons.chart", "versions.reasons.components.agent-manager", "versions.reasons.components.cluster-manager", "versions.reasons.components.kagent", "versions.reasons.components.klaus-gateway", "versions.reasons.components.model-manager", "versions.reasons.components.muster", "versions.reasons.components.skill-manager", "versions.reasons.components.valkey"} organizationsInputs := []string{"organizations.apiHostnames", "organizations.commit.enabled", "organizations.enabled", "organizations.portal.enabled"} tenantInputs := []string{"tenants.platform.editors", "tenants.platform.users", "tenants.platformTeam"} + governanceInputs := []string{"governance.governedServers", "governance.mode"} got, err := drivenInputs(def, Inputs{Values: doc("a.test", "acme", true)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, hiveInputs, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("from the record: %v %v", got, err) } got, err = drivenInputs(def, Inputs{Values: doc("a.test", "acme", true), Typed: doc("b.test", "acme", false)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, hiveInputs, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("with facts typed: %v %v", got, err) } } diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go new file mode 100644 index 00000000..304f2ea8 --- /dev/null +++ b/render/agentplatform/governance.go @@ -0,0 +1,200 @@ +package agentplatform + +import ( + "fmt" + "maps" + "slices" + "strings" + + "k8s.io/apimachinery/pkg/util/validation" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +// Governance is the person's choice of the platform's governance (Governing +// tool calls, giantswarm/giantswarm#38902): the mode (governance.mode, the +// meta chart's top-level governance) and the servers muster governs with +// their safe lists (governance.governedServers, the meta chart's top-level +// governedServers), each read back from the configmap patch on record so a +// reconcile keeps it. Only admins change it, through an Action a second +// person approves, on test installations too (internal/tools). +type Governance struct { + // Mode is trusted, the default and not written, or governed. + Mode string `json:"mode"` + // GovernedServers override the meta chart's governedServers by source: + // a nil entry drops the source (written as null, so the chart governs + // nothing for it); an entry's role or safe list left out keeps the + // chart's (Helm merges the maps, a list replaces). + GovernedServers map[string]*GovernedServer `json:"governedServers"` +} + +// GovernedServer is one source of the meta chart's governedServers: the +// role whose floors hold on its servers and the safe list, the tools agents +// call unasked on governed. +type GovernedServer struct { + Role string `json:"role,omitempty"` + Safe *[]string `json:"safe,omitempty"` +} + +// The governance modes. +const ( + GovernanceTrusted = "trusted" + GovernanceGoverned = "governed" +) + +// GovernanceChart is the first meta chart that takes governance and +// governedServers and renders muster's governance configuration from them +// (giantswarm/agent-platform's tool-approval work). UNSET until that release +// exists (giantswarm/giantswarm#38902 decision #89): a guessed floor would +// write the keys for a chart that refuses or ignores them, so a governed +// platform would not be governed. While it is unset every governance input +// is refused (fail closed). Set it to the release once it is cut; tests set +// it to exercise the render. +var GovernanceChart = "" + +// GovernanceMuster is the first muster release that reads the governance +// configuration (the meta chart's agent-platform.muster.governanceFloor). +// UNSET for the same reason: governed with a muster hold is refused while it +// is unset, since the meta chart fails the render below it. +var GovernanceMuster = "" + +// The inputs, by their schema paths. +const ( + inputGovernanceMode = "governance.mode" + inputGovernanceServers = "governance.governedServers" +) + +// governanceRoleFloors are the floors of each role (muster's roleFloors): a +// floor asks agents in both modes, and muster refuses to start on one listed +// as safe on a server of its role. +var governanceRoleFloors = map[string][]string{ + "agentManager": {"set_agent_approval", "set_organization_connector", "add_organization_member", "set_organization_model", "set_organization_egress_policy", "replace_organization_credential"}, + "platformManager": {"approve_action", "merge_action"}, + "connectorManager": {"mcpserver_create", "mcpserver_connect", "mcpserver_set_approval"}, + "toolchainManager": {"approve_source"}, + "modelManager": {"add_backend"}, +} + +// governanceSourceRoles are the roles the meta chart's own governedServers +// give its sources; an override that names no role keeps it, so a safe +// entry is checked against the floors of the role it ends up with. +var governanceSourceRoles = map[string]string{ + "agent-manager": "agentManager", "kagent": "sessionManager", "model-manager": "modelManager", + "cluster-manager": "clusterManager", "vm-manager": "vmManager", "toolchain-manager": "toolchainManager", + "workspace-manager": "workspaceManager", "skill-manager": "skillManager", "mcp-kubernetes": "infrastructure", + "giantswarm-platform-manager": "platformManager", +} + +// governs says whether the person chose anything of the governance: the +// governed mode or a governedServers override. +func (g Governance) governs() bool { + return g.Mode == GovernanceGoverned || len(g.GovernedServers) > 0 +} + +// governanceValues appends the chosen governance to the configmap patch: +// governance: governed (trusted, the chart's default, is not written) and +// the governedServers overrides by source, a dropped one as null. +func (in *Input) governanceValues(m render.Map) render.Map { + g := in.Governance + if g.Mode == GovernanceGoverned { + m = append(m, render.Entry{Key: "governance", Value: GovernanceGoverned, Comment: "The platform's governance mode: the input governance.mode, read back so a\nreconcile keeps it. Changed only through an Action a second person approves."}) + } + if len(g.GovernedServers) > 0 { + var servers render.Map + for _, source := range slices.Sorted(maps.Keys(g.GovernedServers)) { + s := g.GovernedServers[source] + if s == nil { + servers = append(servers, e(source, nil)) + continue + } + var entry render.Map + if s.Role != "" { + entry = append(entry, e("role", s.Role)) + } + if s.Safe != nil { + entry = append(entry, e("safe", slices.Clone(*s.Safe))) + } + servers = append(servers, e(source, entry)) + } + m = append(m, render.Entry{Key: "governedServers", Value: servers, Comment: "The servers muster governs, over the meta chart's: the input\ngovernance.governedServers, read back so a reconcile keeps it. Changed only\nthrough an Action a second person approves; null drops a source."}) + } + return m +} + +// checkGovernance refuses the governance the installation cannot run as +// chosen: any choice while no meta chart release takes it (GovernanceChart +// unset), off the 4 chart line, under a hold of the meta chart before that +// release, governed under a muster hold before the release that reads the +// configuration, and what muster refuses to start on or the meta chart +// refuses to render — a source key that names no MCPServer, an entry +// without role or safe list, a floor of the entry's role on its safe list, +// an empty or repeated safe entry. The schema refuses a role muster does +// not know (muster's api.GovernanceRoles). +func (in *Input) checkGovernance() error { + g := in.Governance + if !g.governs() { + return nil + } + input := inputGovernanceMode + if g.Mode != GovernanceGoverned { + input = inputGovernanceServers + } + if GovernanceChart == "" { + return refuse(fmt.Sprintf("%s needs the meta chart release that renders muster's governance configuration, and none is released yet: until it is, the definition writes no governance, so no installation reads as governed while its muster is not", describe(input))) + } + if in.Installation.ChartLine != lineFour { + return in.refuseOffLineFour(input) + } + if !holdAdmits(in.Versions.Chart, GovernanceChart) { + return refuse(fmt.Sprintf("%s needs the meta chart %s or later, which renders muster's governance configuration, and %s holds it at %s; move or lift the hold first", describe(input), GovernanceChart, describe("versions.chart"), in.Versions.Chart)) + } + if hold := in.Versions.Components[componentMuster]; g.Mode == GovernanceGoverned && hold != "" && (GovernanceMuster == "" || !floorAtLeast(hold, GovernanceMuster)) { + floor := GovernanceMuster + if floor == "" { + floor = "the release that reads the governance configuration (not released yet)" + } + return refuse(fmt.Sprintf("%s governed needs muster %s or later, and %s holds it at %s, below which nothing asks agents and the meta chart refuses the render; move or lift the hold first", describe(inputGovernanceMode), floor, describe("versions.components.muster"), hold)) + } + for _, source := range slices.Sorted(maps.Keys(g.GovernedServers)) { + if err := checkGovernedSource(source, g.GovernedServers[source]); err != "" { + return refuse(fmt.Sprintf("%s %s: %s", describe(inputGovernanceServers), source, err)) + } + } + return nil +} + +// checkGovernedSource is what muster or the meta chart refuses of one +// governedServers source; empty when it is accepted. +func checkGovernedSource(source string, s *GovernedServer) string { + for _, part := range strings.SplitN(source, "/", 2) { + if errs := validation.IsDNS1123Subdomain(part); len(errs) > 0 { + return fmt.Sprintf("is no source or muster server key ( or /): %s", errs[0]) + } + } + if s == nil { + return "" + } + if s.Role == "" && s.Safe == nil { + return "names neither role nor safe; type the source null to drop it, or leave it out to keep the meta chart's" + } + if s.Safe == nil { + return "" + } + role := s.Role + if role == "" { + role = governanceSourceRoles[source] + } + seen := map[string]bool{} + for i, tool := range *s.Safe { + switch { + case strings.TrimSpace(tool) == "": + return fmt.Sprintf("safe entry %d is empty", i) + case seen[tool]: + return fmt.Sprintf("safe entry %d, %s, is listed twice", i, tool) + case slices.Contains(governanceRoleFloors[role], tool): + return fmt.Sprintf("safe entry %d, %s, is a floor of role %s, which asks agents in both modes; muster refuses to start on it", i, tool, role) + } + seen[tool] = true + } + return "" +} diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go new file mode 100644 index 00000000..8b3224c3 --- /dev/null +++ b/render/agentplatform/governance_test.go @@ -0,0 +1,189 @@ +package agentplatform + +import ( + "errors" + "strings" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +// The governance releases the tests take as released. +const ( + testGovernanceChart = "4.190.0" + testGovernanceMuster = "5.70.0" + keyGovernance = "governance" +) + +// withGovernanceReleases takes the governance releases as cut for the test. +// The tests that call it are not parallel: they run before every parallel +// test of the package and restore the unset floors. +func withGovernanceReleases(t *testing.T) { + t.Helper() + chart, muster := GovernanceChart, GovernanceMuster + GovernanceChart, GovernanceMuster = testGovernanceChart, testGovernanceMuster + t.Cleanup(func() { GovernanceChart, GovernanceMuster = chart, muster }) +} + +// governanceInput is the retired platform tenant's input with governance. +func governanceInput(t *testing.T, governance map[string]any) (map[string]any, map[string]string) { + t.Helper() + input, secrets := loadInput(t, shapePlatformTenantRetired) + input[keyGovernance] = governance + return input, secrets +} + +// governanceOf is the governance and governedServers of a rendered patch. +func governanceOf(t *testing.T, patch string) (any, any) { + t.Helper() + var values map[string]any + if err := yaml.Unmarshal([]byte(patch), &values); err != nil { + t.Fatal(err) + } + return values["governance"], values["governedServers"] +} + +// While no meta chart release takes governance (GovernanceChart unset, the +// shipped state), every governance choice is refused, naming the input: +// fail closed, so no installation reads as governed while its muster is not. +// No choice, or the default typed, renders as before with no key written. +func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { + for _, c := range []struct { + name string + governance map[string]any + names string + }{ + {"governed", map[string]any{"mode": GovernanceGoverned}, "(governance.mode) needs the meta chart release that renders muster's governance configuration, and none is released yet"}, + {"a server override", map[string]any{"governedServers": map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"list_actions"}}}}, "(governance.governedServers) needs the meta chart release"}, + } { + t.Run(c.name, func(t *testing.T) { + input, secrets := governanceInput(t, c.governance) + _, err := Render(input, secrets, render.ModeCommit) + if !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), c.names) { + t.Fatalf("got %v, want ErrInput naming %s", err, c.names) + } + }) + } + input, secrets := governanceInput(t, map[string]any{"mode": GovernanceTrusted}) + mode, servers := governanceOf(t, renderedPatch(t, input, secrets)) + if mode != nil || servers != nil { + t.Fatalf("trusted writes governance %v, governedServers %v", mode, servers) + } +} + +// With the release cut, governed renders the meta chart's top-level +// governance and the overrides its governedServers by source, in key +// order, a dropped source as null, an entry's role and safe list as typed; +// what is rendered reads back as the same input and renders the same patch +// again (a reconcile keeps it). Trusted is the chart's default and is not +// written. +func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { + withGovernanceReleases(t) + governance := map[string]any{"mode": GovernanceGoverned, "governedServers": map[string]any{ + "giantswarm-platform-manager": map[string]any{"safe": []any{"get_info", "list_actions"}}, + "mcp-kubernetes": nil, + "agent-platform/pro": map[string]any{"role": "infrastructure", "safe": []any{}}, + }} + input, secrets := governanceInput(t, governance) + patch := renderedPatch(t, input, secrets) + for _, want := range []string{ + "\ngovernance: governed\n", + "\ngovernedServers:\n agent-platform/pro:\n role: infrastructure\n safe: []\n giantswarm-platform-manager:\n safe:\n - get_info\n - list_actions\n mcp-kubernetes: null\n", + "Changed only through an Action a second person approves", + } { + if !strings.Contains(patch, want) { + t.Fatalf("the patch carries no %q:\n%s", want, patch) + } + } + mode, servers := governanceOf(t, patch) + again, secrets := governanceInput(t, map[string]any{"mode": mode, "governedServers": servers}) + if got := renderedPatch(t, again, secrets); got != patch { + t.Fatalf("read back and rendered again:\n%s\nwant\n%s", got, patch) + } + + trusted, secrets := governanceInput(t, map[string]any{"mode": GovernanceTrusted}) + if mode, _ := governanceOf(t, renderedPatch(t, trusted, secrets)); mode != nil { + t.Fatalf("trusted writes governance: %v", mode) + } +} + +// What the meta chart or muster would refuse is refused first, naming the +// input and the source: an unknown role (muster does not start), a floor of +// the source's role on its safe list (muster does not start), whether the +// role is typed or the chart's for the source, an empty or repeated safe +// entry, an entry with neither role nor safe list, an unknown key or mode +// (the schema), a source key no MCPServer can have, the 3 chart line, a +// meta chart hold before the release, and governed under a muster hold +// before the release that reads the configuration. +func TestGovernanceRefusals(t *testing.T) { + withGovernanceReleases(t) + server := func(source string, entry any) map[string]any { + return map[string]any{"governedServers": map[string]any{source: entry}} + } + for _, c := range []struct { + name string + governance map[string]any + mutate func(m map[string]any) + names string + }{ + {"an unknown role", server("agent-manager", map[string]any{"role": "admin"}), nil, "/governance/governedServers/agent-manager/role"}, + {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{"role": "platformManager", "safe": []any{"list_actions", "approve_action"}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, + {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{"safe": []any{"set_agent_approval"}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, + {"an empty safe entry", server("skill-manager", map[string]any{"safe": []any{" "}}), nil, "safe entry 0 is empty"}, + {"a repeated safe entry", server("skill-manager", map[string]any{"safe": []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, + {"neither role nor safe", server("skill-manager", map[string]any{}), nil, "names neither role nor safe"}, + {"an unknown key", server("skill-manager", map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, + {"an unknown mode", map[string]any{"mode": "strict"}, nil, "governance/mode"}, + {"a source key no server has", server("Agent_Manager", map[string]any{"role": "agentManager"}), nil, "Agent_Manager: is no source or muster server key"}, + {"the 3 line", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + delete(m, keyOrganizations) + delete(m, keyViewers) + delete(m, keyTenants) + m["installation"].(map[string]any)["customer"] = testOrganisation + m["installation"].(map[string]any)["chartLine"] = lineThree + }, "(governance.mode) is the 4 chart line's"}, + {"a chart hold before the release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + m["versions"] = map[string]any{keyChart: "4.189.0"} + }, "(governance.mode) needs the meta chart " + testGovernanceChart}, + {"governed under a muster hold before its release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.69.0 <6.0.0"}} + }, "governed needs muster " + testGovernanceMuster}, + } { + t.Run(c.name, func(t *testing.T) { + input, secrets := governanceInput(t, c.governance) + if c.mutate != nil { + c.mutate(input) + } + _, err := Render(input, secrets, render.ModeCommit) + if !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), c.names) { + t.Fatalf("got %v, want ErrInput naming %s", err, c.names) + } + }) + } + for _, c := range []struct { + name string + governance map[string]any + mutate func(m map[string]any) + }{ + {"a hold on the release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyChart: testGovernanceChart} }}, + {"a muster hold on its release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=" + testGovernanceMuster + " <6.0.0"}} + }}, + {"a server override on trusted under an old muster", server("giantswarm-platform-manager", map[string]any{"safe": []any{"list_actions"}}), func(m map[string]any) { + m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.60.0 <6.0.0"}} + }}, + {"the floor of another role", server("agent-manager", map[string]any{"safe": []any{"approve_action"}}), nil}, + } { + t.Run(c.name, func(t *testing.T) { + input, secrets := governanceInput(t, c.governance) + if c.mutate != nil { + c.mutate(input) + } + if _, err := Render(input, secrets, render.ModeCommit); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/render/agentplatform/input.go b/render/agentplatform/input.go index 8f9fa488..eaf751c1 100644 --- a/render/agentplatform/input.go +++ b/render/agentplatform/input.go @@ -194,6 +194,10 @@ type Input struct { // (musterMcpServerViewers), read back from the configmap patch on record // so a reconcile keeps them (tenants.go). PlatformTenant PlatformTenant + // Governance is the person's choice of the platform's governance mode + // and the servers muster governs (governance.*), read back from the + // configmap patch on record so a reconcile keeps it (governance.go). + Governance Governance // Components are the components the policy gives the installation, by // name: its organisation's list and, where the policy names a Slack app // for the installation, the chat gateway. @@ -737,7 +741,8 @@ type document struct { } `json:"platform"` PlatformTeam *[]Subject `json:"platformTeam"` } `json:"tenants"` - Versions Versions `json:"versions"` + Governance Governance `json:"governance"` + Versions Versions `json:"versions"` } // MCPBackend is one in-cluster MCP backend the meta chart's network policy @@ -897,7 +902,7 @@ type managerGitHubChoice struct { // the cluster does not serve PodCertificateRequest, the chat or skill // repositories on an installation whose organisation hosts no portal for // them, the chat without a model, or on Vertex without its Google project or -// location, the Hive where the installation cannot serve it, the MCP backends' network policy or the LLM listener's rate limits on the 3 line, the rate limits or the session idle TTL where no kagent runs, the session idle TTL on the 3 line, the default agent turned off or its model override on the 3 line, where kagent and the agent-manager do not both run or with a chart hold below the release that ships it, the skill-manager's sources or GitHub App on the 3 line, where no agent-manager runs or with a chart hold below the release with the skill-manager, a source naming the platform's own skill repository, the agent-manager's skill repositories where it may take its skills from the skill-manager or beside the skill-manager's sources, the cluster-manager's commit mode where no cluster-manager runs, context bots where no chat gateway runs) +// location, the Hive where the installation cannot serve it, the MCP backends' network policy or the LLM listener's rate limits on the 3 line, the rate limits or the session idle TTL where no kagent runs, the session idle TTL on the 3 line, the default agent turned off or its model override on the 3 line, where kagent and the agent-manager do not both run or with a chart hold below the release that ships it, the skill-manager's sources or GitHub App on the 3 line, where no agent-manager runs or with a chart hold below the release with the skill-manager, a source naming the platform's own skill repository, the agent-manager's skill repositories where it may take its skills from the skill-manager or beside the skill-manager's sources, the cluster-manager's commit mode where no cluster-manager runs, context bots where no chat gateway runs, the governance where it cannot be enforced as chosen: checkGovernance) // is ErrInput too. func Parse(raw any) (*Input, error) { schema, err := render.DefinitionSchema("agent-platform/schema.json") @@ -951,6 +956,7 @@ func Parse(raw any) (*Input, error) { pol.browseOnly(in.Installation.Federation.Targets) in.Organizations, in.organizationsPolicy = d.Organizations, pol.Organizations in.PlatformTenant = PlatformTenant{Users: d.Tenants.Platform.Users, Editors: d.Tenants.Platform.Editors, PlatformTeam: d.Tenants.PlatformTeam, Viewers: d.MusterMcpServerViewers} + in.Governance = d.Governance in.selectLine(pol.targetLine(in.Installation)) if err := in.checkRecord(); err != nil { return nil, err @@ -1152,6 +1158,9 @@ func (in *Input) checkRecord() error { if err := in.checkPlatformTenant(); err != nil { return err } + if err := in.checkGovernance(); err != nil { + return err + } if in.Installation.Private && in.klausGateway() && !holdAdmits(in.Versions.Components[componentMuster], "5.64.0") { return refuse(describe("versions.components.muster") + " excludes Muster 5.64.0 or later, required for the pinned gateway client document; move or lift the hold before applying the pins") } diff --git a/render/agentplatform/render.go b/render/agentplatform/render.go index b9f820c5..576e5a2f 100644 --- a/render/agentplatform/render.go +++ b/render/agentplatform/render.go @@ -340,6 +340,7 @@ func (in *Input) configmapPatch() render.Map { } m = in.organizationsValues(m) m = in.platformTenantValues(m) + m = in.governanceValues(m) if len(in.MCPBackends) > 0 { m = append(m, e("networkPolicy", render.Map{e("mcpBackends", in.mcpBackends())})) } From f87631df78d6f70783eaddc1cafc519a04c80e7a Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:22:36 +0100 Subject: [PATCH 02/27] feat(plan): read a plan's governance change old to new and name what loosens GovernanceOf compares the governance and governedServers of an installation's agent-platform values on record and as rendered, with their values, and names the changes that loosen it (governed to trusted, a source no longer governed or back to the chart's entry, a role changed, a safe entry added, one named like a write marked). Values that cannot be read on either side count as a loosening change. The summary reads the governance on a line of its own instead of among the values keys. --- internal/plan/governance.go | 220 +++++++++++++++++++++++++++++++ internal/plan/governance_test.go | 109 +++++++++++++++ internal/plan/summary.go | 19 ++- 3 files changed, 347 insertions(+), 1 deletion(-) create mode 100644 internal/plan/governance.go create mode 100644 internal/plan/governance_test.go diff --git a/internal/plan/governance.go b/internal/plan/governance.go new file mode 100644 index 00000000..10049dda --- /dev/null +++ b/internal/plan/governance.go @@ -0,0 +1,220 @@ +package plan + +import ( + "fmt" + "maps" + "slices" + "strings" +) + +// GovernanceChange is what a plan changes of the platform's governance +// (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's +// top-level governance and governedServers in the installation's +// agent-platform values. Such a change is an Action a second person +// approves, on test installations too (internal/tools); its review reads +// these lines. +type GovernanceChange struct { + // Lines are the changes, old → new with their values. + Lines []string `json:"lines"` + // Loosens are the lines that loosen the governance, or may: the mode + // leaving governed, a source no longer governed or put back to the + // chart's entry, a role changed or left to the chart's, a safe entry + // added or a safe list replaced or put back to the chart's. The plan does + // not know the chart's own entries, so a change against them counts. + Loosens []string `json:"loosens,omitempty"` +} + +// The values keys of the governance, top-level in the agent-platform values. +const ( + keyGovernance = "governance" + keyGovernedServers = "governedServers" +) + +// governanceUnreadable is the line of a plan whose agent-platform values +// cannot be read on either side: counted as a change that loosens, so a +// file nobody can compare never passes without a second person. +const governanceUnreadable = "the agent-platform values could not be read: counted as a governance change that loosens" + +// governanceFile says whether path is an installation's agent-platform +// values, the configmap patch that carries the governance. +func governanceFile(path string) bool { + return strings.HasSuffix(path, "/apps/agent-platform/configmap-values.yaml.patch") +} + +// GovernanceOf is the governance p changes, false when it changes none. +func GovernanceOf(p Installation) (GovernanceChange, bool) { + for _, f := range p.Files { + if !governanceFile(f.Path) || (f.Change != ChangeCreate && f.Change != ChangeUpdate) { + continue + } + old, err1 := governanceValues(f.Current) + next, err2 := governanceValues(f.Content) + // A side the plan does not carry (an answer of paths only) is read as + // unreadable, never as a file without governance. + missing := f.Content == "" || (f.Change == ChangeUpdate && f.Current == "") + if err1 != nil || err2 != nil || missing { + return GovernanceChange{Lines: []string{governanceUnreadable}, Loosens: []string{governanceUnreadable}}, true + } + var g GovernanceChange + g.mode(old[keyGovernance], next[keyGovernance]) + g.servers(old[keyGovernedServers], next[keyGovernedServers]) + if len(g.Lines) > 0 { + return g, true + } + } + return GovernanceChange{}, false +} + +// governanceValues reads the governance keys of a values file; an empty +// file (a fresh enable's side on record) carries none. +func governanceValues(content string) (map[string]any, error) { + docs, err := yamlDocs(content) + if err != nil { + return nil, err + } + out := map[string]any{} + for _, d := range docs { + for _, k := range []string{keyGovernance, keyGovernedServers} { + if v, ok := d[k]; ok { + out[k] = v + } + } + } + return out, nil +} + +// Summary is the change as the review's line reads it. +func (g GovernanceChange) Summary() string { + s := "governance (a second person approves): " + strings.Join(g.Lines, "; ") + if len(g.Loosens) > 0 { + s += " — loosens: " + strings.Join(g.Loosens, "; ") + } + return s +} + +func (g *GovernanceChange) add(line string, loosens bool) { + g.Lines = append(g.Lines, line) + if loosens { + g.Loosens = append(g.Loosens, line) + } +} + +// mode compares the mode; absent is the chart's default, trusted. +func (g *GovernanceChange) mode(old, next any) { + if fmt.Sprint(old) == fmt.Sprint(next) { + return + } + read := func(v any) string { + if v == nil { + return "trusted (the chart's default)" + } + return fmt.Sprint(v) + } + g.add(fmt.Sprintf("mode %s → %s", read(old), read(next)), fmt.Sprint(old) == "governed" && fmt.Sprint(next) != "governed") +} + +// servers compares the governedServers overrides by source. +func (g *GovernanceChange) servers(oldV, nextV any) { + old, _ := oldV.(map[string]any) + next, _ := nextV.(map[string]any) + for _, source := range sortedKeys(old, next) { + o, inOld := old[source] + n, inNext := next[source] + at := keyGovernedServers + "." + source + switch { + case inOld && inNext && o != nil && n != nil: + g.entry(at, o, n) + case fmt.Sprint(inOld, o) != fmt.Sprint(inNext, n): + // Anything but null → null-or-absent the other way round loosens: + // the source leaves the governed servers or its typed entry gives + // way to the chart's, which the plan does not know. + tightens := inOld && o == nil + g.add(fmt.Sprintf("%s %s → %s", at, serverEntry(inOld, o), serverEntry(inNext, n)), !tightens) + } + } +} + +// entry compares one source's typed entries: its role and its safe list. +func (g *GovernanceChange) entry(at string, oldV, nextV any) { + old, _ := oldV.(map[string]any) + next, _ := nextV.(map[string]any) + if fmt.Sprint(old["role"]) != fmt.Sprint(next["role"]) { + g.add(fmt.Sprintf("%s.role %s → %s", at, orChart(old["role"], "role"), orChart(next["role"], "role")), true) + } + o, inOld := old["safe"] + n, inNext := next["safe"] + switch { + case !inOld && !inNext: + case !inOld || !inNext: + g.add(fmt.Sprintf("%s.safe %s → %s", at, orChart(o, "list"), orChart(n, "list")), true) + default: + ol, nl := strs(asList(o)), strs(asList(n)) + var added, removed []string + for _, v := range nl { + if !slices.Contains(ol, v) { + added = append(added, "+"+v+writeNote(v)) + } + } + for _, v := range ol { + if !slices.Contains(nl, v) { + removed = append(removed, "−"+v) + } + } + if len(added)+len(removed) == 0 { + return + } + g.Lines = append(g.Lines, fmt.Sprintf("%s.safe %s", at, strings.Join(slices.Concat(added, removed), " "))) + if len(added) > 0 { + g.Loosens = append(g.Loosens, fmt.Sprintf("%s.safe %s", at, strings.Join(added, " "))) + } + } +} + +// serverEntry reads one source's state: the chart's entry (absent), not +// governed (null), or the typed entry. +func serverEntry(present bool, v any) string { + switch { + case !present: + return "the chart's entry" + case v == nil: + return "null (not governed)" + } + m, _ := v.(map[string]any) + var parts []string + for _, k := range slices.Sorted(maps.Keys(m)) { + val := m[k] + if l, ok := val.([]any); ok { + val = "[" + strings.Join(strs(l), ", ") + "]" + } + parts = append(parts, fmt.Sprintf("%s: %v", k, val)) + } + return "{" + strings.Join(parts, ", ") + "}" +} + +// orChart reads a role or safe list, absent as the chart's. +func orChart(v any, what string) string { + if v == nil { + return "the chart's " + what + } + if l, ok := v.([]any); ok { + return "[" + strings.Join(strs(l), ", ") + "]" + } + return fmt.Sprint(v) +} + +func asList(v any) []any { + l, _ := v.([]any) + return l +} + +// writeVerbs are the leading words of a tool name that changes something: +// a safe entry named so is marked, so the second person looks twice. +var writeVerbs = []string{"add", "apply", "approve", "authorize", "cancel", "connect", "create", "delete", "deny", "deploy", "disable", "enable", "exec", "fork", "grant", "invoke", "kill", "merge", "patch", "push", "remove", "replace", "restart", "revoke", "rotate", "run", "scale", "set", "start", "stop", "sync", "update", "write"} + +func writeNote(tool string) string { + verb, _, _ := strings.Cut(tool, "_") + if slices.Contains(writeVerbs, verb) { + return " (named like a write)" + } + return "" +} diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go new file mode 100644 index 00000000..363959a7 --- /dev/null +++ b/internal/plan/governance_test.go @@ -0,0 +1,109 @@ +package plan + +import ( + "slices" + "strings" + "testing" +) + +const govPatch = "giantswarm/acme-configs/installations/jackal/apps/agent-platform/configmap-values.yaml.patch" + +// govPlan is an installation whose agent-platform values move from current +// to next. +func govPlan(current, next string) Installation { + change := ChangeUpdate + if current == "" { + change = ChangeCreate + } + return govPlanOf(change, current, next) +} + +func govPlanOf(change Change, current, next string) Installation { + return Installation{Name: "jackal", Files: []File{{Path: govPatch, Change: change, Current: current, Content: next}}} +} + +// The governance a plan changes reads old → new with its values, and every +// change that loosens it — governed to trusted (or to the chart's default, +// trusted), a source dropped or put back to the chart's entry, a role +// changed or left to the chart's, a safe entry added (one named like a +// write marked) — is named apart; a change that only tightens loosens +// nothing. +func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { + for _, c := range []struct { + name string + current, next string + lines, loosens []string + }{ + {"trusted to governed tightens", "global: {}\n", "global: {}\ngovernance: governed\n", + []string{"mode trusted (the chart's default) → governed"}, nil}, + {"governed to the chart's default loosens", "governance: governed\n", "global: {}\n", + []string{"mode governed → trusted (the chart's default)"}, []string{"mode governed → trusted (the chart's default)"}}, + {"a safe entry added and one removed", "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_actions]\n", + "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, create_thing, list_installations]\n", + []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_installations −list_actions"}, + []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_installations"}}, + {"only a safe entry removed", "governedServers:\n agent-manager:\n safe: [get_info, list_agents]\n", "governedServers:\n agent-manager:\n safe: [get_info]\n", + []string{"governedServers.agent-manager.safe −list_agents"}, nil}, + {"a source dropped", "governance: governed\n", "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", + []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}, []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}}, + {"a dropped source governed again", "governedServers:\n mcp-kubernetes: null\n", "global: {}\n", + []string{"governedServers.mcp-kubernetes null (not governed) → the chart's entry"}, nil}, + {"an override over the chart's entry", "global: {}\n", "governedServers:\n kagent:\n role: sessionManager\n safe: [list_sessions]\n", + []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}, + []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}}, + {"a role changed", "governedServers:\n x:\n role: platformManager\n", "governedServers:\n x:\n role: infrastructure\n", + []string{"governedServers.x.role platformManager → infrastructure"}, []string{"governedServers.x.role platformManager → infrastructure"}}, + {"a safe list back to the chart's", "governedServers:\n x:\n role: infrastructure\n safe: [a]\n", "governedServers:\n x:\n role: infrastructure\n", + []string{"governedServers.x.safe [a] → the chart's list"}, []string{"governedServers.x.safe [a] → the chart's list"}}, + {"a fresh enable with governed", "", "governance: governed\n", + []string{"mode trusted (the chart's default) → governed"}, nil}, + {"values that do not parse are a change that loosens", "governance: [\n", "governance: governed\n", + []string{governanceUnreadable}, []string{governanceUnreadable}}, + } { + t.Run(c.name, func(t *testing.T) { + g, ok := GovernanceOf(govPlan(c.current, c.next)) + if !ok { + t.Fatal("no governance change") + } + if !slices.Equal(g.Lines, c.lines) || !slices.Equal(g.Loosens, c.loosens) { + t.Fatalf("lines %q loosens %q, want %q and %q", g.Lines, g.Loosens, c.lines, c.loosens) + } + }) + } + // An update whose side on record the plan does not carry (an answer of + // paths only) is no file without governance: it counts, as loosening. + for _, p := range []Installation{govPlanOf(ChangeUpdate, "", "global: {}\n"), govPlanOf(ChangeUpdate, "governance: governed\n", "")} { + if g, ok := GovernanceOf(p); !ok || !slices.Equal(g.Loosens, []string{governanceUnreadable}) { + t.Fatalf("an update without a side: %v %+v", ok, g) + } + } +} + +// A plan that leaves the governance as it is, or does not touch the +// agent-platform values, changes no governance, whatever else it changes. +func TestNoGovernanceChange(t *testing.T) { + for _, p := range []Installation{ + govPlan("governance: governed\nglobal: {domain: a}\n", "governance: governed\nglobal: {domain: b}\n"), + govPlan("", "global: {}\n"), + {Files: []File{{Path: govPatch, Change: ChangeUnchanged}}}, + {Files: []File{{Path: "giantswarm/acme-configs/installations/jackal/apps/dex-app/configmap-values.yaml.patch", Change: ChangeUpdate, Current: "a: 1\n", Content: "governance: governed\n"}}}, + } { + if g, ok := GovernanceOf(p); ok { + t.Fatalf("a governance change: %+v", g) + } + } +} + +// The summary reads the governance with its values on a line of its own, +// first after the switch-off warning, and does not name its keys again +// among the agent-platform values. +func TestSummaryReadsTheGovernanceWithItsValues(t *testing.T) { + got := Summary(govPlan("global:\n domain: a\n", "global:\n domain: b\ngovernance: governed\ngovernedServers:\n x:\n safe: [get_info]\n")) + want := []string{ + "governance (a second person approves): mode trusted (the chart's default) → governed; governedServers.x the chart's entry → {safe: [get_info]} — loosens: governedServers.x the chart's entry → {safe: [get_info]}", + "agent-platform: values global.domain", + } + if !slices.Equal(got, want) { + t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} diff --git a/internal/plan/summary.go b/internal/plan/summary.go index be56cb8c..c4be266d 100644 --- a/internal/plan/summary.go +++ b/internal/plan/summary.go @@ -19,7 +19,9 @@ import ( // entries added and removed, the keys of a Secret added and removed, and the // credentials that rotate (by name, the installation and component dropped). // The running components the plan switches off lead, as one warning line -// (SwitchOff.Warning), so the summary never hides them among the rest. +// (SwitchOff.Warning), so the summary never hides them among the rest; the +// governance the plan changes follows, old → new with its values +// (GovernanceOf), never among the agent-platform values' keys. // A file whose shape cannot be read reads "rewritten". Never a secret value: // a Secret's values and an encrypted file's leaves are not compared. func Summary(p Installation) []string { @@ -76,6 +78,9 @@ func Summary(p Installation) []string { if w := p.SwitchOff.Warning(); w != "" { out = append(out, w) } + if g, ok := GovernanceOf(p); ok { + out = append(out, g.Summary()) + } for _, name := range order { c := comps[name] items := joinAdds(uniq(c.items)) @@ -174,6 +179,10 @@ func fileChanges(f File) []string { items = append(items, "adds "+id) continue } + if governanceFile(f.Path) { + // The governance reads on a line of its own, with its values. + old, d = withoutGovernance(old), withoutGovernance(d) + } items = append(items, docChanges(id, old, d, secret || kindOf(d) == kindSecret)...) } for _, d := range current { @@ -602,3 +611,11 @@ func uniq(in []string) []string { } return out } + +// withoutGovernance is a values document without the governance keys. +func withoutGovernance(d map[string]any) map[string]any { + out := maps.Clone(d) + delete(out, keyGovernance) + delete(out, keyGovernedServers) + return out +} From 6cdb0b4fbca77c578c18e2b32a45183ae1f34bd3 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:28:03 +0100 Subject: [PATCH 03/27] test: name the governance tests' repeated literals for goconst --- .../installations/governance_readback_test.go | 2 +- internal/plan/governance_test.go | 29 +++++---- render/agentplatform/governance.go | 7 ++- render/agentplatform/governance_test.go | 60 ++++++++++--------- 4 files changed, 56 insertions(+), 42 deletions(-) diff --git a/internal/installations/governance_readback_test.go b/internal/installations/governance_readback_test.go index 4f5965e0..09ef3d3a 100644 --- a/internal/installations/governance_readback_test.go +++ b/internal/installations/governance_readback_test.go @@ -29,7 +29,7 @@ func TestGovernanceSurvivesAReconcile(t *testing.T) { patch, read, doc, marker := inputFromTheRecord(t, "platform-tenant-retired", governanceOnRecord) require.Equal(t, agentplatform.GovernanceGoverned, read["governance.mode"]) - require.Equal(t, map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"get_info"}}, "mcp-kubernetes": nil}, read["governance.governedServers"]) + require.Equal(t, map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"get_info"}}, clusterMCPServersMarkerServer: nil}, read["governance.governedServers"]) result, err := definition.Render(doc, nil, render.ModeCommit) require.NoError(t, err) again := string(result.Tree()["giantswarm/giantswarm-configs/"+marker]) diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index 363959a7..9e050f8b 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -6,7 +6,12 @@ import ( "testing" ) -const govPatch = "giantswarm/acme-configs/installations/jackal/apps/agent-platform/configmap-values.yaml.patch" +const ( + govInstallation = "lynx" + govPatch = "giantswarm/acme-configs/installations/lynx/apps/agent-platform/configmap-values.yaml.patch" + govEmpty = "global: {}\n" + govGoverned = "governance: governed\n" +) // govPlan is an installation whose agent-platform values move from current // to next. @@ -19,7 +24,7 @@ func govPlan(current, next string) Installation { } func govPlanOf(change Change, current, next string) Installation { - return Installation{Name: "jackal", Files: []File{{Path: govPatch, Change: change, Current: current, Content: next}}} + return Installation{Name: govInstallation, Files: []File{{Path: govPatch, Change: change, Current: current, Content: next}}} } // The governance a plan changes reads old → new with its values, and every @@ -34,9 +39,9 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { current, next string lines, loosens []string }{ - {"trusted to governed tightens", "global: {}\n", "global: {}\ngovernance: governed\n", + {"trusted to governed tightens", govEmpty, "global: {}\ngovernance: governed\n", []string{"mode trusted (the chart's default) → governed"}, nil}, - {"governed to the chart's default loosens", "governance: governed\n", "global: {}\n", + {"governed to the chart's default loosens", govGoverned, govEmpty, []string{"mode governed → trusted (the chart's default)"}, []string{"mode governed → trusted (the chart's default)"}}, {"a safe entry added and one removed", "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_actions]\n", "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, create_thing, list_installations]\n", @@ -44,20 +49,20 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_installations"}}, {"only a safe entry removed", "governedServers:\n agent-manager:\n safe: [get_info, list_agents]\n", "governedServers:\n agent-manager:\n safe: [get_info]\n", []string{"governedServers.agent-manager.safe −list_agents"}, nil}, - {"a source dropped", "governance: governed\n", "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", + {"a source dropped", govGoverned, "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}, []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}}, - {"a dropped source governed again", "governedServers:\n mcp-kubernetes: null\n", "global: {}\n", + {"a dropped source governed again", "governedServers:\n mcp-kubernetes: null\n", govEmpty, []string{"governedServers.mcp-kubernetes null (not governed) → the chart's entry"}, nil}, - {"an override over the chart's entry", "global: {}\n", "governedServers:\n kagent:\n role: sessionManager\n safe: [list_sessions]\n", + {"an override over the chart's entry", govEmpty, "governedServers:\n kagent:\n role: sessionManager\n safe: [list_sessions]\n", []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}, []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}}, {"a role changed", "governedServers:\n x:\n role: platformManager\n", "governedServers:\n x:\n role: infrastructure\n", []string{"governedServers.x.role platformManager → infrastructure"}, []string{"governedServers.x.role platformManager → infrastructure"}}, {"a safe list back to the chart's", "governedServers:\n x:\n role: infrastructure\n safe: [a]\n", "governedServers:\n x:\n role: infrastructure\n", []string{"governedServers.x.safe [a] → the chart's list"}, []string{"governedServers.x.safe [a] → the chart's list"}}, - {"a fresh enable with governed", "", "governance: governed\n", + {"a fresh enable with governed", "", govGoverned, []string{"mode trusted (the chart's default) → governed"}, nil}, - {"values that do not parse are a change that loosens", "governance: [\n", "governance: governed\n", + {"values that do not parse are a change that loosens", "governance: [\n", govGoverned, []string{governanceUnreadable}, []string{governanceUnreadable}}, } { t.Run(c.name, func(t *testing.T) { @@ -72,7 +77,7 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { } // An update whose side on record the plan does not carry (an answer of // paths only) is no file without governance: it counts, as loosening. - for _, p := range []Installation{govPlanOf(ChangeUpdate, "", "global: {}\n"), govPlanOf(ChangeUpdate, "governance: governed\n", "")} { + for _, p := range []Installation{govPlanOf(ChangeUpdate, "", govEmpty), govPlanOf(ChangeUpdate, govGoverned, "")} { if g, ok := GovernanceOf(p); !ok || !slices.Equal(g.Loosens, []string{governanceUnreadable}) { t.Fatalf("an update without a side: %v %+v", ok, g) } @@ -84,9 +89,9 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { func TestNoGovernanceChange(t *testing.T) { for _, p := range []Installation{ govPlan("governance: governed\nglobal: {domain: a}\n", "governance: governed\nglobal: {domain: b}\n"), - govPlan("", "global: {}\n"), + govPlan("", govEmpty), {Files: []File{{Path: govPatch, Change: ChangeUnchanged}}}, - {Files: []File{{Path: "giantswarm/acme-configs/installations/jackal/apps/dex-app/configmap-values.yaml.patch", Change: ChangeUpdate, Current: "a: 1\n", Content: "governance: governed\n"}}}, + {Files: []File{{Path: "giantswarm/acme-configs/installations/jackal/apps/dex-app/configmap-values.yaml.patch", Change: ChangeUpdate, Current: "b: 2\n", Content: govGoverned}}}, } { if g, ok := GovernanceOf(p); ok { t.Fatalf("a governance change: %+v", g) diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go index 304f2ea8..129f647c 100644 --- a/render/agentplatform/governance.go +++ b/render/agentplatform/governance.go @@ -64,6 +64,9 @@ const ( inputGovernanceServers = "governance.governedServers" ) +// roleModelManager is the model-manager's governance role. +const roleModelManager = "modelManager" + // governanceRoleFloors are the floors of each role (muster's roleFloors): a // floor asks agents in both modes, and muster refuses to start on one listed // as safe on a server of its role. @@ -72,14 +75,14 @@ var governanceRoleFloors = map[string][]string{ "platformManager": {"approve_action", "merge_action"}, "connectorManager": {"mcpserver_create", "mcpserver_connect", "mcpserver_set_approval"}, "toolchainManager": {"approve_source"}, - "modelManager": {"add_backend"}, + roleModelManager: {"add_backend"}, } // governanceSourceRoles are the roles the meta chart's own governedServers // give its sources; an override that names no role keeps it, so a safe // entry is checked against the floors of the role it ends up with. var governanceSourceRoles = map[string]string{ - "agent-manager": "agentManager", "kagent": "sessionManager", "model-manager": "modelManager", + "agent-manager": "agentManager", "kagent": "sessionManager", "model-manager": roleModelManager, "cluster-manager": "clusterManager", "vm-manager": "vmManager", "toolchain-manager": "toolchainManager", "workspace-manager": "workspaceManager", "skill-manager": "skillManager", "mcp-kubernetes": "infrastructure", "giantswarm-platform-manager": "platformManager", diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index 8b3224c3..e9bb6a08 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -12,9 +12,15 @@ import ( // The governance releases the tests take as released. const ( - testGovernanceChart = "4.190.0" - testGovernanceMuster = "5.70.0" - keyGovernance = "governance" + testGovernanceChart = "4.190.0" + testGovernanceMuster = "5.70.0" + keyGovernance = "governance" + keyMode = "mode" + keyGovernedServers = "governedServers" + keyRole = "role" + toolListActions = "list_actions" + keySafe = "safe" + sourcePlatformManager = "giantswarm-platform-manager" ) // withGovernanceReleases takes the governance releases as cut for the test. @@ -55,8 +61,8 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { governance map[string]any names string }{ - {"governed", map[string]any{"mode": GovernanceGoverned}, "(governance.mode) needs the meta chart release that renders muster's governance configuration, and none is released yet"}, - {"a server override", map[string]any{"governedServers": map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"list_actions"}}}}, "(governance.governedServers) needs the meta chart release"}, + {"governed", map[string]any{keyMode: GovernanceGoverned}, "(governance.mode) needs the meta chart release that renders muster's governance configuration, and none is released yet"}, + {"a server override", map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: map[string]any{keySafe: []any{toolListActions}}}}, "(governance.governedServers) needs the meta chart release"}, } { t.Run(c.name, func(t *testing.T) { input, secrets := governanceInput(t, c.governance) @@ -66,7 +72,7 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { } }) } - input, secrets := governanceInput(t, map[string]any{"mode": GovernanceTrusted}) + input, secrets := governanceInput(t, map[string]any{keyMode: GovernanceTrusted}) mode, servers := governanceOf(t, renderedPatch(t, input, secrets)) if mode != nil || servers != nil { t.Fatalf("trusted writes governance %v, governedServers %v", mode, servers) @@ -81,10 +87,10 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { // written. func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { withGovernanceReleases(t) - governance := map[string]any{"mode": GovernanceGoverned, "governedServers": map[string]any{ - "giantswarm-platform-manager": map[string]any{"safe": []any{"get_info", "list_actions"}}, - "mcp-kubernetes": nil, - "agent-platform/pro": map[string]any{"role": "infrastructure", "safe": []any{}}, + governance := map[string]any{keyMode: GovernanceGoverned, keyGovernedServers: map[string]any{ + sourcePlatformManager: map[string]any{keySafe: []any{"get_info", toolListActions}}, + "mcp-kubernetes": nil, + "agent-platform/pro": map[string]any{keyRole: "infrastructure", keySafe: []any{}}, }} input, secrets := governanceInput(t, governance) patch := renderedPatch(t, input, secrets) @@ -98,12 +104,12 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { } } mode, servers := governanceOf(t, patch) - again, secrets := governanceInput(t, map[string]any{"mode": mode, "governedServers": servers}) + again, secrets := governanceInput(t, map[string]any{keyMode: mode, keyGovernedServers: servers}) if got := renderedPatch(t, again, secrets); got != patch { t.Fatalf("read back and rendered again:\n%s\nwant\n%s", got, patch) } - trusted, secrets := governanceInput(t, map[string]any{"mode": GovernanceTrusted}) + trusted, secrets := governanceInput(t, map[string]any{keyMode: GovernanceTrusted}) if mode, _ := governanceOf(t, renderedPatch(t, trusted, secrets)); mode != nil { t.Fatalf("trusted writes governance: %v", mode) } @@ -120,7 +126,7 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { func TestGovernanceRefusals(t *testing.T) { withGovernanceReleases(t) server := func(source string, entry any) map[string]any { - return map[string]any{"governedServers": map[string]any{source: entry}} + return map[string]any{keyGovernedServers: map[string]any{source: entry}} } for _, c := range []struct { name string @@ -128,26 +134,26 @@ func TestGovernanceRefusals(t *testing.T) { mutate func(m map[string]any) names string }{ - {"an unknown role", server("agent-manager", map[string]any{"role": "admin"}), nil, "/governance/governedServers/agent-manager/role"}, - {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{"role": "platformManager", "safe": []any{"list_actions", "approve_action"}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, - {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{"safe": []any{"set_agent_approval"}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, - {"an empty safe entry", server("skill-manager", map[string]any{"safe": []any{" "}}), nil, "safe entry 0 is empty"}, - {"a repeated safe entry", server("skill-manager", map[string]any{"safe": []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, + {"an unknown role", server("agent-manager", map[string]any{keyRole: "admin"}), nil, "/governance/governedServers/agent-manager/role"}, + {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{keyRole: "platformManager", keySafe: []any{toolListActions, "approve_action"}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, + {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{keySafe: []any{"set_agent_approval"}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, + {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, "safe entry 0 is empty"}, + {"a repeated safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, {"neither role nor safe", server("skill-manager", map[string]any{}), nil, "names neither role nor safe"}, {"an unknown key", server("skill-manager", map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, - {"an unknown mode", map[string]any{"mode": "strict"}, nil, "governance/mode"}, - {"a source key no server has", server("Agent_Manager", map[string]any{"role": "agentManager"}), nil, "Agent_Manager: is no source or muster server key"}, - {"the 3 line", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + {"an unknown mode", map[string]any{keyMode: "strict"}, nil, "governance/mode"}, + {"a source key no server has", server("Agent_Manager", map[string]any{keyRole: "agentManager"}), nil, "Agent_Manager: is no source or muster server key"}, + {caseLineThree, map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { delete(m, keyOrganizations) delete(m, keyViewers) delete(m, keyTenants) m["installation"].(map[string]any)["customer"] = testOrganisation m["installation"].(map[string]any)["chartLine"] = lineThree }, "(governance.mode) is the 4 chart line's"}, - {"a chart hold before the release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + {"a chart hold before the release", map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyChart: "4.189.0"} }, "(governance.mode) needs the meta chart " + testGovernanceChart}, - {"governed under a muster hold before its release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + {"governed under a muster hold before its release", map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.69.0 <6.0.0"}} }, "governed needs muster " + testGovernanceMuster}, } { @@ -167,14 +173,14 @@ func TestGovernanceRefusals(t *testing.T) { governance map[string]any mutate func(m map[string]any) }{ - {"a hold on the release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyChart: testGovernanceChart} }}, - {"a muster hold on its release", map[string]any{"mode": GovernanceGoverned}, func(m map[string]any) { + {"a chart hold on the release", map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyChart: testGovernanceChart} }}, + {"a muster hold on its release", map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=" + testGovernanceMuster + " <6.0.0"}} }}, - {"a server override on trusted under an old muster", server("giantswarm-platform-manager", map[string]any{"safe": []any{"list_actions"}}), func(m map[string]any) { + {"a server override on trusted under an old muster", server(sourcePlatformManager, map[string]any{keySafe: []any{toolListActions}}), func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.60.0 <6.0.0"}} }}, - {"the floor of another role", server("agent-manager", map[string]any{"safe": []any{"approve_action"}}), nil}, + {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{"approve_action"}}), nil}, } { t.Run(c.name, func(t *testing.T) { input, secrets := governanceInput(t, c.governance) From 888334b2e584064fcde5ba4cf9ee3c39fb87b60c Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:28:03 +0100 Subject: [PATCH 04/27] feat(tools): have a second person approve every governance change, on test installations too A commit or wave whose plan changes an installation's governance records the change on the Action (spec.governance) and always asks for the Team review, also where every target is a test installation; requestApproval never records such an action as not requiring review. approve_action keeps refusing the actor, so a second person of the team decides. The review leads with the governance old to new and what loosens it. Every step is audited: committed, self-approval refused, approved, merged, and merged outside the manager without a decision. docs/governance.md describes the input, the rule, the audit lines and the proposed safe list for this manager. --- README.md | 6 +- docs/governance.md | 140 ++++++++++++++++ .../templates/crd-actions.yaml | 12 ++ internal/actions/actions.go | 5 + internal/e2e/governance_test.go | 151 ++++++++++++++++++ internal/tools/approval.go | 15 +- internal/tools/commit.go | 7 + internal/tools/governance.go | 79 +++++++++ internal/tools/governance_test.go | 64 ++++++++ internal/tools/resync.go | 7 + internal/tools/wave.go | 12 ++ 11 files changed, 493 insertions(+), 5 deletions(-) create mode 100644 docs/governance.md create mode 100644 internal/e2e/governance_test.go create mode 100644 internal/tools/governance.go create mode 100644 internal/tools/governance_test.go diff --git a/README.md b/README.md index 4d67fb1c..a292c902 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,8 @@ this order, writing nothing before the gate: and each resulting pull request before the next opens. Approval and merge wait until creation finishes. The Action stays in *pending approval*: the approval, the merge and the rollout follow. An action on Giant Swarm's test installations alone — the hub's customer's, not the - hub: the wave's first stage — needs no Team review: the approval is recorded *not required*, the Action reads *ready to merge*, the actor merges + hub: the wave's first stage — needs no Team review unless it changes the platform's governance + ([docs/governance.md](docs/governance.md)): the approval is recorded *not required*, the Action reads *ready to merge*, the actor merges with `merge_action` once green, and the merge is told to the team's standup channel — who, what, why and what changed (`approvals.standupChannel`; unset, such a commit is refused). The hub and every customer installation keep the review. A failure on the way moves the Action to *failed* and closes the pull requests @@ -172,7 +173,8 @@ Slack alone: who asks to enable or reconcile which capability on which installat account engineer the catalog records), the reason quoted, and *what changes* — a line per component from the comparison (`spec.changes`, `plan.Summary`): a component created whole reads *new*, versions read old → new, list entries added and removed, a kustomization's patches by their target with the JSON patch -operations they add, drop or change (op and path), values keys by path without their values, a Secret's keys +operations they add, drop or change (op and path), values keys by path without their values — except the +platform's governance, which reads first with its values old → new and what loosens it —, a Secret's keys added and removed, the credentials that rotate (the ones asked for marked *on request*) — with the pull requests as links; a wave whose installations change alike reads once, else per installation. The Account Engineers' channel (`approvals.noticeChannel`) never sees the review: once a stage on a customer installation reaches diff --git a/docs/governance.md b/docs/governance.md new file mode 100644 index 00000000..58331e58 --- /dev/null +++ b/docs/governance.md @@ -0,0 +1,140 @@ +# Governance + +How the manager writes an installation's governance for the agent platform (Governing tool calls, +[giantswarm/giantswarm#38902](https://github.com/giantswarm/giantswarm/issues/38902)) and why one person never +changes it alone. + +## What muster enforces + +muster asks a person before an agent runs a tool the platform governs. Its governance configuration has two +parts, both rendered by the agent-platform meta chart: + +- the mode: `trusted` (the default) runs what the connectors' own settings allow; `governed` asks a person + before an agent runs any tool of a governed server that is not on that server's safe list, new and renamed + tools included, and before any of muster's own tools except its reads; +- the governed servers, each with a role and a safe list. A role's floors ask agents in both modes, for + example this manager's `approve_action` and `merge_action` (role `platformManager`). + +## The inputs + +The agent-platform definition takes both as inputs. Both are read back from the configmap patch on record +(`installations//apps/agent-platform/configmap-values.yaml.patch`), so a reconcile keeps them. + +| Input | Renders | Default | +|---|---|---| +| `governance.mode` | the meta chart's top-level `governance`, written only as `governed` | `trusted`, the chart's default, not written | +| `governance.governedServers` | the meta chart's top-level `governedServers`: overrides by source, each `{role, safe}` or `null` | none: the chart's servers and safe lists apply | + +A source is one the meta chart knows (`agent-manager`, `kagent`, `model-manager`, `cluster-manager`, +`vm-manager`, `toolchain-manager`, `workspace-manager`, `skill-manager`, `mcp-kubernetes`, +`giantswarm-platform-manager`) or a muster server key (`` or `/`). Helm merges the maps: + +- a source you leave out keeps the chart's entry; +- a role or safe list you leave out keeps the chart's; +- a safe list you type replaces the chart's list; +- `null` drops the source, and muster governs nothing for it. + +```sh +--input governance.mode=governed +--input 'governance.governedServers={"giantswarm-platform-manager": {"safe": ["get_info", "list_installations"]}}' +``` + +The definition refuses, typed or read back: + +- any governance choice while no meta chart release renders muster's governance configuration. `GovernanceChart` + in `render/agentplatform/governance.go` stays unset until that release is cut: a guessed version would write + keys a chart ignores, so an installation would read as governed while its muster is not (decision #89 of the + epic). Set it, and `GovernanceMuster`, when the releases exist. +- an installation off the 4 chart line; +- a `versions.chart` hold below `GovernanceChart`; +- `governed` under a `versions.components.muster` hold below `GovernanceMuster`, where the meta chart fails the + render; +- whatever muster refuses to start on: + - a role muster does not know (the schema); + - a floor of the source's role on its safe list (the typed role, else the chart's role for the source); + - an empty or repeated safe entry; + - an entry with neither role nor safe list. + +## A second person approves every change + +A commit whose plan changes either key is recorded with the change on the Action (`spec.governance`, per +installation: `lines` old → new and `loosens`). The change rules are: + +- such an action always asks for the Team review, also where every target is one of Giant Swarm's test + installations, which otherwise need none; +- `approve_action` refuses the actor, as for every action, so a second person of the team decides; +- `merge_action` merges nothing before that decision; +- an agent can propose such a change but never approve or merge it: muster asks a person before an agent's + `approve_action` and `merge_action`. + +The review leads with the governance, before the reason: + +```text +*Governance:* this changes the platform's governance; a second person approves it, on test installations too. +• rowan: mode governed → trusted (the chart's default) +*It loosens governance:* rowan: mode governed → trusted (the chart's default) +``` + +The same change also reads in *What changes*, with its values, as its own line. A change loosens governance, or +may, when any of these hold: + +- the mode leaves `governed`; +- a source is dropped or put back to the chart's entry; +- a role changes or is left to the chart's; +- a safe entry is added (one named like a write, such as `create_…` or `set_…`, is marked); +- a safe list is replaced or put back to the chart's. + +The manager does not know the chart's own entries, so a change against them counts as loosening. If the +agent-platform values cannot be read on either side, the plan counts it as a loosening change. + +## Audit + +Each step logs one line per installation whose governance the action changes. Every line carries the action, +the installation, the actor, the caller, the decision and who decided it, the change and whether it loosens. + +| Event | When | +|---|---| +| `governance_change_committed` | the commit opened the pull requests | +| `governance_change_self_approval_refused` | the actor tried to approve their own change | +| `governance_change_approved` | a second person approved it | +| `governance_change_merged` | `merge_action` merged pull requests of it | +| `governance_change_merged_without_approval` | the pull requests were merged outside the manager before any decision; only the repositories' branch protection stood in the way | + +## What the manager does not cover + +These limits are outside the manager: + +- someone with write access to `giantswarm/-configs` can merge a change to the values outside the + manager. Branch protection on those repositories (enforced for admins, re-approval after a new push, required + CODEOWNERS review) is asked of their owners. The manager audits such a merge but cannot prevent it. +- whoever holds Kubernetes write rights on muster's HelmRelease or ConfigMap can change the configuration + directly. +- `disable_capability` removes the whole platform, muster included, and keeps its own review rules: no agent + path is left to govern. + +## This manager's own safe list + +The meta chart governs this manager (`giantswarm-platform-manager`, role `platformManager`) with an empty safe +list, so on `governed` every tool but the floors asks agents. The tools that only read, and are proposed for its +safe list, are: + +| Tool | Why it is safe | +|---|---| +| `get_info` | who the caller is, the definitions and their schemas | +| `list_installations` | the installations and their capability states, read as the caller | +| `list_actions` | the Action records | +| `get_action` | one Action record | +| `verify_capability` | compares the repositories with a definition and writes nothing | + +`get_action` and `list_actions` bring an Action's status up to date with GitHub as they read it. They change no +decision. + +These tools stay asking: + +- `enable_capability`, `reconcile_capability` and `disable_capability` ask agents even for a dry run: muster + matches tool names, and the same tool commits with `mode: commit`. A separate plan tool would let agents + plan unasked. +- `verify_installation` records its result on the Action. +- `watch_action` moves stages and posts to the review thread. +- `deny_action` closes pull requests. +- `approve_action` and `merge_action` are floors and are never safe. diff --git a/helm/giantswarm-platform-manager/templates/crd-actions.yaml b/helm/giantswarm-platform-manager/templates/crd-actions.yaml index 95b20e8a..0fa83df7 100644 --- a/helm/giantswarm-platform-manager/templates/crd-actions.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-actions.yaml @@ -143,6 +143,18 @@ spec: description: Per installation, the definition's enabled marker resolved to the installation's repository (owner/repo:path), whose absence from the default branch after the merge means the fileset was reverted. type: object additionalProperties: {type: string} + governance: + description: Per installation, the platform's governance the commit changes, old -> new with the changes that loosen it; such an action is approved by a second person, on test installations too. Values of governance and governedServers only, never a secret. + type: object + additionalProperties: + type: object + properties: + lines: + type: array + items: {type: string} + loosens: + type: array + items: {type: string} status: type: object properties: diff --git a/internal/actions/actions.go b/internal/actions/actions.go index 7ce166f1..2fa6f96e 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -119,6 +119,11 @@ type Spec struct { // Skipped are the installations of the set a wave left out, and why: // never a target, no pull request. Skipped []Skipped `json:"skipped,omitempty"` + // Governance is, per installation, the platform's governance the commit + // changes (plan.GovernanceOf), old → new with what loosens: such an + // action is approved by a second person, on test installations too, and + // its approval and merge are audited. Recorded at commit. + Governance map[string]plan.GovernanceChange `json:"governance,omitempty"` } // Skipped is an installation of a wave's set that is not a target. diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go new file mode 100644 index 00000000..40168a02 --- /dev/null +++ b/internal/e2e/governance_test.go @@ -0,0 +1,151 @@ +package e2e + +// Governing tool calls (giantswarm/giantswarm#38902): one person never +// changes an installation's governance alone. A commit that changes the +// governance is an Action a second person approves, on Giant Swarm's test +// installations too, where any other commit needs no review; the review +// reads the governance old → new and what loosens; the actor cannot approve +// it, and nothing merges before a member did. + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/giantswarm/gitops-commit/commit" + + "github.com/giantswarm/giantswarm-platform-manager/internal/actions" + "github.com/giantswarm/giantswarm-platform-manager/internal/installations" + "github.com/giantswarm/giantswarm-platform-manager/internal/tools" + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" +) + +// The governance input's keys. +const ( + keyGovernanceInput = "governance" + keyMode = "mode" +) + +// withGovernanceReleases takes the meta chart and muster releases that +// render and read the governance as cut, for the test. Not parallel. +func withGovernanceReleases(t *testing.T) { + t.Helper() + chart, muster := agentplatform.GovernanceChart, agentplatform.GovernanceMuster + agentplatform.GovernanceChart, agentplatform.GovernanceMuster = "4.0.0", "5.0.0" + t.Cleanup(func() { agentplatform.GovernanceChart, agentplatform.GovernanceMuster = chart, muster }) +} + +// rowanOnLineFour puts rowan's record on the 4 chart line, the line that +// takes the governance, on a cluster that serves what kagent needs there. +func rowanOnLineFour(g *fakeGitHub) { + g.addFile(acmeConfigs, installations.ConfigPatchPath(rowan), "codename: rowan\nbase: acme.test\nservices:\n muster:\n clientId: muster-rowan\ngatewayApi:\n clusterIssuer: private-example\nagentPlatform:\n kagentApiV2: true\n") + g.addFile(acmeMCs, installations.ClusterAppManifestPath(rowan), clusterAppManifest(rowan, "cluster-aws", "10.3.0", true)) +} + +func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { + withGovernanceReleases(t) + st := newStack(t) + fixtures(st.ghs) + sopsFixtures(t, st.ghs) + rowanAsTestInstallation(t, st.ghs) + rowanOnLineFour(st.ghs) + seedRemote(t, st) + aliceC, carolC := st.mcpClient(t, aliceToken), st.mcpClient(t, carolToken) + + governance := map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}} + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: governance})}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + a := out.Action + if a.Status.State != actions.StatePendingApproval || a.Status.Approval == nil || a.Status.Approval.Decision != "" || a.Status.Approval.ReviewID == "" || strings.Contains(out.Next, "no Team review") { + t.Fatalf("a governance change on a test installation went without the review: %+v; next %q", a.Status.Approval, out.Next) + } + g, ok := a.Spec.Governance[rowan] + if !ok || len(g.Lines) != 2 || len(g.Loosens) != 1 || !strings.Contains(g.Loosens[0], "mcp-kubernetes") { + t.Fatalf("the action's governance: %+v", a.Spec.Governance) + } + posted := st.gateway.posted() + if len(posted) != 1 { + t.Fatalf("%d review(s) posted", len(posted)) + } + review := fmt.Sprint(posted[0].Body["text"]) + for _, want := range []string{"*Governance:* this changes the platform's governance", "mode trusted (the chart's default) → governed", "governedServers.mcp-kubernetes the chart's entry → null (not governed)", "*It loosens governance:*"} { + if !strings.Contains(review, want) { + t.Fatalf("the review carries no %q:\n%s", want, review) + } + } + + // The actor cannot approve it, nor merge it before a member did. + if _, text, isErr := decide(t, aliceC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "yours") { + t.Fatalf("the actor's approve: %v %s", isErr, text) + } + for _, pr := range st.remote.PullRequests() { + st.remote.SetChecks(pr.PullRequest, commit.ChecksSuccess) + } + if m, text, isErr := mergeCall(t, aliceC, a.Name); isErr || len(m.Merged) != 0 || !strings.Contains(m.Message, "waits for the team's approval") { + t.Fatalf("merge before the approval: %v %s", isErr, text) + } + if d, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); isErr || d.Action == nil || d.Action.Status.Approval.DecidedBy != carol { + t.Fatalf("carol's approve: %v %s", isErr, text) + } + if m, text, isErr := mergeCall(t, aliceC, a.Name); isErr || len(m.Merged) == 0 { + t.Fatalf("merge after the approval: %v %s", isErr, text) + } + if noticed := st.gateway.noticed(); len(noticed) != 0 { + t.Fatalf("a reviewed action told the standup channel: %+v", noticed) + } +} + +// A commit on a test installation that leaves the governance as it is still +// needs no review. +func TestTestInstallationWithoutGovernanceChangeNeedsNoReview(t *testing.T) { + withGovernanceReleases(t) + st := newStack(t) + fixtures(st.ghs) + sopsFixtures(t, st.ghs) + rowanAsTestInstallation(t, st.ghs) + rowanOnLineFour(st.ghs) + seedRemote(t, st) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}})}) + if isErr || out.Action == nil || out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision != actions.DecisionNotRequired || len(out.Action.Spec.Governance) != 0 { + t.Fatalf("commit: %v %s", isErr, text) + } +} + +// A wave that takes a test installation from governed back to trusted is +// the loosening the rule is for: it pends the team's review like any other +// governance change, the review naming what loosens, and the actor cannot +// approve it. +func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing.T) { + withGovernanceReleases(t) + st := newStack(t) + fixtures(st.ghs) + sopsFixtures(t, st.ghs) + rowanAsTestInstallation(t, st.ghs) + rowanOnLineFour(st.ghs) + st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), "muster: {}\ngovernance: governed\n") + seedRemote(t, st) + aliceC := st.mcpClient(t, aliceToken) + inputs := minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}}) + text, isErr := call(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallations: []string{rowan}, tools.ArgInputs: inputs, tools.ArgReason: commitReason, tools.ArgMode: string(tools.ModeCommit)}) + var w tools.WaveResult + if isErr || json.Unmarshal([]byte(text), &w) != nil || w.Action == nil { + t.Fatalf("wave commit: %v %s", isErr, text) + } + a := w.Action + if a.Status.State != actions.StatePendingApproval || a.Status.Approval == nil || a.Status.Approval.ReviewID == "" || a.Status.Approval.Decision != "" { + t.Fatalf("a loosening wave on a test installation went without the review: %s %+v", a.Status.State, a.Status.Approval) + } + if g := a.Spec.Governance[rowan]; len(g.Loosens) != 1 || g.Loosens[0] != "mode governed → trusted (the chart's default)" { + t.Fatalf("the wave's governance: %+v", a.Spec.Governance) + } + if posted := st.gateway.posted(); len(posted) != 1 || !strings.Contains(fmt.Sprint(posted[0].Body["text"]), "*It loosens governance:* rowan: mode governed → trusted") { + t.Fatalf("the review: %+v", posted) + } + if _, text, isErr := decide(t, aliceC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "yours") { + t.Fatalf("the actor's approve: %v %s", isErr, text) + } +} diff --git a/internal/tools/approval.go b/internal/tools/approval.go index 1265fd7b..cd1d1649 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -139,6 +139,7 @@ func (t *Tools) approve(ctx context.Context, args map[string]any) (any, error) { } if id.Login == a.Spec.Actor.Login { t.d.Log.Info("action_approval_actor_refused", identity.LogAttr(ctx), "action", a.Name) + t.auditGovernance(ctx, "governance_change_self_approval_refused", a) return nil, fmt.Errorf("%s: action %s is yours (%s): a second person of the team decides; Deny withdraws it", ToolApproveAction, a.Name, id.Login) } if a.Status.Approval != nil && a.Status.Approval.Decision != "" { @@ -171,6 +172,7 @@ func (t *Tools) approve(ctx context.Context, args map[string]any) (any, error) { return nil, fmt.Errorf("%s: the approving reviews are submitted and the action could not record the decision: %w", ToolApproveAction, err) } t.d.Log.Info("action_approved", identity.LogAttr(ctx), "action", a.Name, "pullRequests", len(a.Status.PullRequests)) + t.auditGovernance(ctx, "governance_change_approved", a) return Decision{Action: a, Message: fmt.Sprintf("%s approved action %s: approving reviews submitted on %d pull request(s) (%s); %s merges them as the actor with %s once the checks are green.", id.Login, a.Name, len(a.Status.PullRequests), prList(a.Status.PullRequests), a.Spec.Actor.Login, ToolMergeAction)}, nil } @@ -355,6 +357,9 @@ func (t *Tools) merge(ctx context.Context, args map[string]any) (any, error) { } res.Action = a t.d.Log.Info("action_merge", identity.LogAttr(ctx), "action", a.Name, "state", a.Status.State, "merged", len(res.Merged), "waiting", res.Waiting, "stage", res.Stage) + if len(res.Merged) > 0 { + t.auditGovernance(ctx, "governance_change_merged", a) + } if res.Waiting != "" { res.Message = fmt.Sprintf("%d pull request(s) merged as %s (%s); the merge stopped at %s — call %s again once it is green.", len(res.Merged), id.Login, prList(res.Merged), res.Waiting, ToolMergeAction) return res, nil @@ -512,8 +517,9 @@ func (t *Tools) awaitApproval(ctx context.Context, a *actions.Action) (any, erro const reviewNotRequired = "every target is a test installation: no Team review, the merge is told to the team's standup channel" // requestApproval is the commit's last step: the review posted, or — every -// target a test installation — recorded as not required and the action ready -// to merge, nothing posted until the merge tells the standup channel. +// target a test installation and the governance unchanged — recorded as not +// required and the action ready to merge, nothing posted until the merge +// tells the standup channel. func (t *Tools) requestApproval(ctx context.Context, a *actions.Action, tool string, test bool) (*actions.Action, error) { latest, err := t.d.Actions.Get(ctx, a.Name) if err != nil { @@ -523,7 +529,9 @@ func (t *Tools) requestApproval(ctx context.Context, a *actions.Action, tool str return nil, err } *a = *latest - if !test { + // A governance change is never one person's: the review stands on test + // installations too, whatever the caller says. + if !test || len(a.Spec.Governance) > 0 { return t.askApproval(ctx, a, tool) } status := a.Status @@ -702,6 +710,7 @@ func reviewText(a *actions.Action) string { } b.WriteString(skippedClause(a.Spec.Skipped)) b.WriteString(".") + b.WriteString(governanceText(a)) b.WriteString(whyAndWhat(a, "What changes", a.Spec.Installations)) return b.String() } diff --git a/internal/tools/commit.go b/internal/tools/commit.go index 459e24ae..8aaaa58b 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -154,6 +154,12 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri } spec.Change = changeSummary(p) spec.Changes = map[string][]string{one: plan.Summary(p)} + if g, ok := plan.GovernanceOf(p); ok { + // One person never changes the governance alone: the Team review, + // on a test installation too. + spec.Governance = map[string]plan.GovernanceChange{one: g} + test = false + } spec.KeptByInstallation = keptByInstallation(nil, p) if n := p.Diff[plan.ChangeUnknown]; n > 0 { return nil, fmt.Errorf("%s: %d file(s) of %s could not be compared against the repository as you (%s); nothing is committed blind", tool, n, one, unknownFiles(p)) @@ -201,6 +207,7 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "installation", one, "state", a.Status.State, "pullRequests", len(prs)) + t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) if err != nil { return nil, fmt.Errorf("%w — the pull requests are open (%s) and the action pends approval; %s posts the review", err, prList(prs), ToolMergeAction) diff --git a/internal/tools/governance.go b/internal/tools/governance.go new file mode 100644 index 00000000..7c33f00c --- /dev/null +++ b/internal/tools/governance.go @@ -0,0 +1,79 @@ +package tools + +import ( + "context" + "maps" + "slices" + "strings" + + "github.com/giantswarm/giantswarm-platform-manager/internal/actions" + "github.com/giantswarm/giantswarm-platform-manager/internal/identity" +) + +// Governing tool calls (giantswarm/giantswarm#38902): one person never +// changes an installation's governance alone. A commit whose plan changes +// the governance (plan.GovernanceOf) records the change on the Action +// (spec.governance) and asks the team's review even where every target is a +// test installation; approve_action refuses the actor as for any action, so +// a second person of the team decides, and merge_action waits for that +// decision. Each step is audited (auditGovernance). Agents may propose such +// a change and never approve or merge it: muster asks a person before an +// agent's approve_action and merge_action (a floor of the platformManager +// role). + +// governanceText is the review's governance block: that the action changes +// the governance and a second person approves it, each installation's +// change old → new, and what loosens it, so the approver reads it before +// anything else. Empty for an action that changes none. +func governanceText(a *actions.Action) string { + if len(a.Spec.Governance) == 0 { + return "" + } + var b strings.Builder + b.WriteString("\n*Governance:* this changes the platform's governance; a second person approves it, on test installations too.") + var loosens []string + for _, n := range governedInstallations(a) { + g := a.Spec.Governance[n] + b.WriteString("\n• " + n + ": " + strings.Join(g.Lines, "; ")) + if len(g.Loosens) > 0 { + loosens = append(loosens, n+": "+strings.Join(g.Loosens, "; ")) + } + } + if len(loosens) > 0 { + b.WriteString("\n*It loosens governance:* " + strings.Join(loosens, " — ")) + } + return b.String() +} + +// governedInstallations are the installations whose governance a changes, +// in the action's order, then any other on record by name. +func governedInstallations(a *actions.Action) []string { + var out []string + for _, n := range a.Spec.Installations { + if _, ok := a.Spec.Governance[n]; ok { + out = append(out, n) + } + } + for _, n := range slices.Sorted(maps.Keys(a.Spec.Governance)) { + if !slices.Contains(out, n) { + out = append(out, n) + } + } + return out +} + +// auditGovernance logs event once per installation whose governance a +// changes: the action, the actor, the caller, who decided where someone +// did, the change and whether it loosens. Nothing for an action that +// changes none. +func (t *Tools) auditGovernance(ctx context.Context, event string, a *actions.Action) { + decidedBy, decision := "", "" + if a.Status.Approval != nil { + decidedBy, decision = a.Status.Approval.DecidedBy, a.Status.Approval.Decision + } + for _, n := range governedInstallations(a) { + g := a.Spec.Governance[n] + t.d.Log.Info(event, identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", n, "actor", a.Spec.Actor.Login, + "decision", decision, "decidedBy", decidedBy, "governance", strings.Join(g.Lines, "; "), "loosens", len(g.Loosens) > 0) + } +} diff --git a/internal/tools/governance_test.go b/internal/tools/governance_test.go new file mode 100644 index 00000000..3466e1b6 --- /dev/null +++ b/internal/tools/governance_test.go @@ -0,0 +1,64 @@ +package tools + +import ( + "bytes" + "context" + "log/slog" + "strings" + "testing" + + "github.com/giantswarm/giantswarm-platform-manager/internal/actions" + "github.com/giantswarm/giantswarm-platform-manager/internal/installations" + "github.com/giantswarm/giantswarm-platform-manager/internal/plan" +) + +// governedAction is an action on garm whose commit makes the platform +// governed and drops a source from the governed servers. +func governedAction() *actions.Action { + return &actions.Action{Spec: actions.Spec{Kind: actions.KindReconcile, Capability: installations.AgentPlatform, Installations: []string{rtGarm}, Actor: actions.Actor{Login: stAlice}, + Governance: map[string]plan.GovernanceChange{rtGarm: { + Lines: []string{"mode trusted (the chart's default) → governed", "governedServers.mcp-kubernetes the chart's entry → null (not governed)"}, + Loosens: []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}, + }}}} +} + +// The review of an action that changes the governance says so first, that a +// second person approves it, the change old → new and what loosens it; one +// that changes none says nothing of it. +func TestReviewTextLeadsWithTheGovernance(t *testing.T) { + text := reviewText(governedAction()) + for _, want := range []string{ + "\n*Governance:* this changes the platform's governance; a second person approves it, on test installations too.", + "\n• garm: mode trusted (the chart's default) → governed; governedServers.mcp-kubernetes the chart's entry → null (not governed)", + "\n*It loosens governance:* garm: governedServers.mcp-kubernetes the chart's entry → null (not governed)", + } { + if !strings.Contains(text, want) { + t.Fatalf("the review carries no %q:\n%s", want, text) + } + } + if text := reviewText(&actions.Action{Spec: actions.Spec{Kind: actions.KindReconcile, Capability: installations.AgentPlatform, Installations: []string{rtGarm}}}); strings.Contains(text, "Governance") { + t.Fatalf("a review without a governance change names it:\n%s", text) + } +} + +// Every step of a governance change is audited, one line per installation +// with the change, what loosens, the actor and, once decided, who approved. +func TestGovernanceChangeIsAudited(t *testing.T) { + var buf bytes.Buffer + tl := &Tools{d: Deps{Log: slog.New(slog.NewTextHandler(&buf, nil))}} + a := governedAction() + a.Name = "reconcile-x" + a.Status.Approval = &actions.Approval{Decision: actions.DecisionApproved, DecidedBy: "carol"} + tl.auditGovernance(context.Background(), "governance_change_approved", a) + line := buf.String() + for _, want := range []string{"msg=governance_change_approved", "action=reconcile-x", "installation=garm", "actor=alice", "decidedBy=carol", "loosens=true", "mode trusted (the chart's default) → governed"} { + if !strings.Contains(line, want) { + t.Fatalf("the audit line carries no %q: %s", want, line) + } + } + buf.Reset() + tl.auditGovernance(context.Background(), "governance_change_approved", &actions.Action{}) + if buf.Len() != 0 { + t.Fatalf("an action without a governance change is audited: %s", buf.String()) + } +} diff --git a/internal/tools/resync.go b/internal/tools/resync.go index 27b8660b..5a6565a2 100644 --- a/internal/tools/resync.go +++ b/internal/tools/resync.go @@ -209,6 +209,13 @@ func (t *Tools) resync(ctx context.Context, c *gh.Client, id *identity.Identity, approval := *approvalOf(&status) approval.Decision, approval.DecidedBy, approval.At = actions.DecisionMergedWithoutApproval, by, now() status.Approval = &approval + // The repositories' merge path let a governance change + // through without the team's decision: audited apart, since + // only their branch protection stood between one person + // and the change. + merged := fresh + merged.Status = status + t.auditGovernance(ctx, "governance_change_merged_without_approval", &merged) } posts = append(posts, fmt.Sprintf("Merged outside the manager by %s: %s. *%s* is rolling out — the rollout and the probes follow here.", by, prLinks(stagePRs(status.PullRequests, idx)), st.Name)) if noReview(&fresh) { diff --git a/internal/tools/wave.go b/internal/tools/wave.go index 24338912..558d32c1 100644 --- a/internal/tools/wave.go +++ b/internal/tools/wave.go @@ -110,10 +110,18 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string spec.CapabilityByInstallation[n] = d.Name } } + governs := false for _, p := range targets { spec.InputsByInstallation[p.Name] = p.Inputs spec.Changes[p.Name] = plan.Summary(p) spec.KeptByInstallation = keptByInstallation(spec.KeptByInstallation, p) + if g, ok := plan.GovernanceOf(p); ok { + if spec.Governance == nil { + spec.Governance = map[string]plan.GovernanceChange{} + } + spec.Governance[p.Name] = g + governs = true + } } changes := make([]string, 0, len(targets)) var rotated []string @@ -131,6 +139,9 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string rollout.Installations = append(rollout.Installations, actions.InstallationRollout{Name: p.Name, State: actions.StatePendingApproval, Message: fmt.Sprintf("stage %d of %d", i+1, len(targets))}) } spec.Change = strings.Join(changes, "; ") + // One person never changes the governance alone: the Team review, on + // test installations too. + test = test && !governs if err := t.standupRefusal(tool, test); err != nil { return nil, err } @@ -180,6 +191,7 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "wave", strings.Join(res.Order, ","), "skipped", len(res.Skipped), "pullRequests", len(prs)) + t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) if err != nil { return nil, fmt.Errorf("%w — the pull requests are open (%s) and the action pends approval; %s posts the review", err, prList(prs), ToolMergeAction) From c65535974cd4852fc33c84f7cc460f69f8b9a730 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:54:39 +0100 Subject: [PATCH 05/27] fix(agent-platform): refuse governance overrides that drop floors or carry markup A server's role is fixed by the meta chart for its own sources, so an override may no longer change it (muster applies a role's floors by the server's role); a server key of its own must name its role and may not stand for one of the chart's sources. No floor of any role may be safe, safe entries must be tool names and a list holds at most 64. muster's roles and floors and the chart's governedServers now live in definitions/agent-platform/governance.yaml, held to muster and the chart by a test that reads sibling checkouts where present (review S9-02, S9-03, S9-13). --- definitions/agent-platform/governance.yaml | 52 ++++++++ definitions/agent-platform/schema.json | 6 +- definitions/governance.go | 59 +++++++++ definitions/governance_test.go | 143 +++++++++++++++++++++ render/agentplatform/governance.go | 93 +++++++++----- render/agentplatform/governance_test.go | 30 ++++- 6 files changed, 343 insertions(+), 40 deletions(-) create mode 100644 definitions/agent-platform/governance.yaml create mode 100644 definitions/governance.go create mode 100644 definitions/governance_test.go diff --git a/definitions/agent-platform/governance.yaml b/definitions/agent-platform/governance.yaml new file mode 100644 index 00000000..3827a150 --- /dev/null +++ b/definitions/agent-platform/governance.yaml @@ -0,0 +1,52 @@ +# The governance the agent-platform definition writes against (Governing tool +# calls, giantswarm/giantswarm#38902), copied from the releases that render and +# read it and held to them by definitions' TestGovernanceMatchesMusterAndTheChart +# (which reads sibling checkouts of muster and agent-platform where present). +# +# muster: the roles muster knows and the floors of each (muster +# internal/api/governance.go, GovernanceRoles and roleFloors). A floor asks agents +# in both modes; muster refuses to start on one listed as safe on a server of its +# role, and the definition refuses a floor of any role on any safe list. +muster: + roles: [agentManager, platformManager, connectorManager, sessionManager, modelManager, clusterManager, vmManager, workspaceManager, toolchainManager, skillManager, infrastructure] + floors: + agentManager: [set_agent_approval, set_organization_connector, add_organization_member, set_organization_model, set_organization_egress_policy, replace_organization_credential] + platformManager: [approve_action, merge_action] + connectorManager: [mcpserver_create, mcpserver_connect, mcpserver_set_approval] + toolchainManager: [approve_source] + modelManager: [add_backend] +# chart: the meta chart's own governedServers by source (agent-platform +# helm/agent-platform/values.yaml, top-level governedServers). A source's role is +# what the server is: an override may not change it. The plan diffs an override +# against these entries, so a first override reads old -> new. +chart: + agent-manager: + role: agentManager + safe: [get_info, list_agents, get_agent, get_agent_status, validate_agent, list_model_configs, list_egress_policies, list_skills, list_sessions, get_session, get_session_turn, toolchain_users, list_organizations, get_organization, list_organization_members, list_organization_connectors] + kagent: + role: sessionManager + safe: [list_sessions, list_session_checkpoints, list_sandbox_templates, list_sandboxes, get_sandbox, get_sandbox_process, read_sandbox_outputs, read_sandbox_file] + model-manager: + role: modelManager + safe: [get_info, get_backend, list_backends, list_models, get_model, list_loaded_models, list_presets, search_models, check_fit, list_nodes, list_jobs, get_job] + cluster-manager: + role: clusterManager + safe: [get_info, list_clusters, list_releases, list_node_pools] + vm-manager: + role: vmManager + safe: [get_info, get_host, list_images, get_image, list_networks, get_network, list_vms, get_vm, get_vm_metrics, get_vm_attestation] + toolchain-manager: + role: toolchainManager + safe: [list_sources, list_toolchains, describe_toolchain, toolchain_build_status, search_packages] + workspace-manager: + role: workspaceManager + safe: [list_providers, list_owners, list_workspaces, get_workspace, list_repositories, preview_workspace] + skill-manager: + role: skillManager + safe: [list_skill_sources, list_skills, resolve_skills, get_skill, get_skill_file] + mcp-kubernetes: + role: infrastructure + safe: [logs, list_port_forward_sessions, context_list, context_get_current, can_i, api_resources, cluster_health, capi_list_clusters, capi_get_cluster, capi_resolve_cluster, capi_cluster_health, get, list, describe] + giantswarm-platform-manager: + role: platformManager + safe: [get_info, list_installations, list_actions, get_action, verify_capability] diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index f33c667f..e4eb8762 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -881,8 +881,8 @@ "type": "object", "additionalProperties": false, "properties": { - "role": {"type": "string", "enum": ["agentManager", "platformManager", "connectorManager", "sessionManager", "modelManager", "clusterManager", "vmManager", "workspaceManager", "toolchainManager", "skillManager", "infrastructure"], "description": "The role whose floors hold on the source's servers in both modes; left out, the meta chart's role for the source stands."}, - "safe": {"type": "array", "items": {"type": "string"}, "description": "The source's own tool names agents call unasked on governed: reads only, never a floor of its role. It replaces the meta chart's list; left out, the chart's list stands."} + "role": {"type": "string", "enum": ["agentManager", "platformManager", "connectorManager", "sessionManager", "modelManager", "clusterManager", "vmManager", "workspaceManager", "toolchainManager", "skillManager", "infrastructure"], "description": "The role whose floors hold on the source's servers in both modes: for a source of the meta chart its own role (an override may not change it), required for any other server key."}, + "safe": {"type": "array", "maxItems": 64, "items": {"type": "string", "pattern": "^[A-Za-z0-9_.-]{1,128}$"}, "description": "The source's own tool names agents call unasked on governed: reads only, never a floor of any role. It replaces the meta chart's list; left out, the chart's list stands."} } } ] @@ -891,7 +891,7 @@ "x-readback": {"file": "configmap", "key": "governedServers"}, "x-feature": "tool-access", "x-renders": ["configmap:governedServers"], - "description": "Overrides of the meta chart's governedServers, by source: a source the chart knows (agent-manager, kagent, model-manager, cluster-manager, vm-manager, toolchain-manager, workspace-manager, skill-manager, mcp-kubernetes, giantswarm-platform-manager) or a muster server key (, /), each {role, safe} or null, which drops the source (muster governs nothing for it). Helm merges the maps: a source left out keeps the chart's entry, a role or safe list left out the chart's, a safe list typed replaces the chart's. Refused as muster refuses to start on it: an unknown role, a floor of the source's role on its safe list (typed, or the chart's role for the source), an empty or repeated safe entry, and an entry with neither role nor safe list. None, the default, the key is not written. Read back from the configmap patch on record, so a reconcile keeps it; typed (--input 'governance.governedServers={\"giantswarm-platform-manager\": {\"safe\": [\"get_info\"]}}'), it replaces it." + "description": "Overrides of the meta chart's governedServers, by source: a source the chart knows (agent-manager, kagent, model-manager, cluster-manager, vm-manager, toolchain-manager, workspace-manager, skill-manager, mcp-kubernetes, giantswarm-platform-manager) or a muster server key (, /), each {role, safe} or null, which drops the source (muster governs nothing for it). Helm merges the maps: a source left out keeps the chart's entry, a role or safe list left out the chart's, a safe list typed replaces the chart's. Refused: an unknown role; a role other than the meta chart's for one of its sources (muster applies floors by a server's role, so a new role would drop them); a server key without role, or one naming a chart source under another key; a floor of any role on a safe list; a safe entry that is no tool name or is repeated; more than 64 safe entries; an entry with neither role nor safe list. None, the default, the key is not written. Read back from the configmap patch on record, so a reconcile keeps it; typed (--input 'governance.governedServers={\"giantswarm-platform-manager\": {\"safe\": [\"get_info\"]}}'), it replaces it." } } }, diff --git a/definitions/governance.go b/definitions/governance.go new file mode 100644 index 00000000..31eabbbf --- /dev/null +++ b/definitions/governance.go @@ -0,0 +1,59 @@ +package definitions + +import ( + "fmt" + "slices" + "sync" + + "gopkg.in/yaml.v3" +) + +// GovernedServer is one source of the meta chart's governedServers: the role +// whose floors hold on its servers and its safe list. +type GovernedServer struct { + Role string `yaml:"role" json:"role"` + Safe []string `yaml:"safe" json:"safe"` +} + +// GovernanceData is the governance the agent-platform definition writes +// against (agent-platform/governance.yaml): muster's roles and floors, and the +// meta chart's own governedServers by source. +type GovernanceData struct { + Muster struct { + Roles []string `yaml:"roles"` + Floors map[string][]string `yaml:"floors"` + } `yaml:"muster"` + Chart map[string]GovernedServer `yaml:"chart"` +} + +var governance = sync.OnceValues(func() (GovernanceData, error) { + raw, err := FS.ReadFile("agent-platform/governance.yaml") + if err != nil { + return GovernanceData{}, err + } + var g GovernanceData + if err := yaml.Unmarshal(raw, &g); err != nil { + return GovernanceData{}, fmt.Errorf("agent-platform/governance.yaml: %w", err) + } + return g, nil +}) + +// Governance is agent-platform/governance.yaml, read once. The file is +// embedded and tested, so a read failure panics. +func Governance() GovernanceData { + g, err := governance() + if err != nil { + panic(err) + } + return g +} + +// FloorRole is the role whose floor tool is, empty when it is no floor. +func (g GovernanceData) FloorRole(tool string) string { + for _, role := range g.Muster.Roles { + if slices.Contains(g.Muster.Floors[role], tool) { + return role + } + } + return "" +} diff --git a/definitions/governance_test.go b/definitions/governance_test.go new file mode 100644 index 00000000..aa71edce --- /dev/null +++ b/definitions/governance_test.go @@ -0,0 +1,143 @@ +package definitions_test + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "slices" + "strconv" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/giantswarm/giantswarm-platform-manager/definitions" +) + +// checkout is a sibling repository's file: env names its checkout, else the +// repository next to this one; the test skips where neither is present (CI). +func checkout(t *testing.T, env, repo, path string) []byte { + t.Helper() + dir := os.Getenv(env) + if dir == "" { + dir = filepath.Join("..", "..", repo) + } + raw, err := os.ReadFile(filepath.Join(dir, path)) + if err != nil { + t.Skipf("no %s checkout (%s, or set %s): %v", repo, dir, env, err) + } + return raw +} + +// musterGovernance reads muster's roles and floors from its source: the +// string constants, GovernanceRoles' list and the roleFloors map. +func musterGovernance(t *testing.T, src []byte) ([]string, map[string][]string) { + t.Helper() + f, err := parser.ParseFile(token.NewFileSet(), "governance.go", src, 0) + if err != nil { + t.Fatal(err) + } + consts := map[string]string{} + value := func(e ast.Expr) string { + switch v := e.(type) { + case *ast.BasicLit: + s, _ := strconv.Unquote(v.Value) + return s + case *ast.Ident: + return consts[v.Name] + } + return "" + } + var roles []string + floors := map[string][]string{} + ast.Inspect(f, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.ValueSpec: + for i, name := range n.Names { + if i < len(n.Values) { + if lit, ok := n.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING { + consts[name.Name] = value(lit) + } + if name.Name == "roleFloors" { + for _, el := range n.Values[i].(*ast.CompositeLit).Elts { + kv := el.(*ast.KeyValueExpr) + for _, tool := range kv.Value.(*ast.CompositeLit).Elts { + floors[value(kv.Key)] = append(floors[value(kv.Key)], value(tool)) + } + } + } + } + } + case *ast.FuncDecl: + if n.Name.Name == "GovernanceRoles" { + ast.Inspect(n.Body, func(m ast.Node) bool { + if lit, ok := m.(*ast.CompositeLit); ok { + for _, el := range lit.Elts { + roles = append(roles, value(el)) + } + return false + } + return true + }) + } + } + return true + }) + return roles, floors +} + +// The governance data the definition writes against matches the releases +// it copies: muster's roles and every role's floors, and the meta chart's +// own governedServers (role and safe list per source). A floor muster adds, +// or a source the chart adds or reassigns, fails here before a reviewed +// merge stops muster at start. +func TestGovernanceMatchesMusterAndTheChart(t *testing.T) { + g := definitions.Governance() + t.Run("muster", func(t *testing.T) { + roles, floors := musterGovernance(t, checkout(t, "MUSTER_CHECKOUT", "muster", "internal/api/governance.go")) + if !slices.Equal(roles, g.Muster.Roles) { + t.Errorf("roles %v, muster's %v", g.Muster.Roles, roles) + } + if !reflect.DeepEqual(floors, g.Muster.Floors) { + t.Errorf("floors %v, muster's %v", g.Muster.Floors, floors) + } + }) + t.Run("chart", func(t *testing.T) { + var values struct { + GovernedServers map[string]definitions.GovernedServer `yaml:"governedServers"` + } + if err := yaml.Unmarshal(checkout(t, "AGENT_PLATFORM_CHECKOUT", "agent-platform", "helm/agent-platform/values.yaml"), &values); err != nil { + t.Fatal(err) + } + for source, s := range values.GovernedServers { + if s.Safe == nil { + values.GovernedServers[source] = definitions.GovernedServer{Role: s.Role, Safe: []string{}} + } + } + if !reflect.DeepEqual(values.GovernedServers, g.Chart) { + t.Errorf("chart %v, the meta chart's %v", g.Chart, values.GovernedServers) + } + }) +} + +// No floor is on the chart's safe lists, every source's role is muster's. +func TestGovernanceDataIsConsistent(t *testing.T) { + g := definitions.Governance() + for source, s := range g.Chart { + if !slices.Contains(g.Muster.Roles, s.Role) { + t.Errorf("%s: role %q is none of muster's", source, s.Role) + } + for _, tool := range s.Safe { + if role := g.FloorRole(tool); role != "" { + t.Errorf("%s: safe %s is a floor of %s", source, tool, role) + } + } + } + for role := range g.Muster.Floors { + if !slices.Contains(g.Muster.Roles, role) { + t.Errorf("floors of unknown role %s", role) + } + } +} diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go index 129f647c..feef1867 100644 --- a/render/agentplatform/governance.go +++ b/render/agentplatform/governance.go @@ -3,11 +3,13 @@ package agentplatform import ( "fmt" "maps" + "regexp" "slices" "strings" "k8s.io/apimachinery/pkg/util/validation" + "github.com/giantswarm/giantswarm-platform-manager/definitions" "github.com/giantswarm/giantswarm-platform-manager/render" ) @@ -64,28 +66,27 @@ const ( inputGovernanceServers = "governance.governedServers" ) -// roleModelManager is the model-manager's governance role. -const roleModelManager = "modelManager" - -// governanceRoleFloors are the floors of each role (muster's roleFloors): a -// floor asks agents in both modes, and muster refuses to start on one listed -// as safe on a server of its role. -var governanceRoleFloors = map[string][]string{ - "agentManager": {"set_agent_approval", "set_organization_connector", "add_organization_member", "set_organization_model", "set_organization_egress_policy", "replace_organization_credential"}, - "platformManager": {"approve_action", "merge_action"}, - "connectorManager": {"mcpserver_create", "mcpserver_connect", "mcpserver_set_approval"}, - "toolchainManager": {"approve_source"}, - roleModelManager: {"add_backend"}, -} - -// governanceSourceRoles are the roles the meta chart's own governedServers -// give its sources; an override that names no role keeps it, so a safe -// entry is checked against the floors of the role it ends up with. -var governanceSourceRoles = map[string]string{ - "agent-manager": "agentManager", "kagent": "sessionManager", "model-manager": roleModelManager, - "cluster-manager": "clusterManager", "vm-manager": "vmManager", "toolchain-manager": "toolchainManager", - "workspace-manager": "workspaceManager", "skill-manager": "skillManager", "mcp-kubernetes": "infrastructure", - "giantswarm-platform-manager": "platformManager", +// maxSafeEntries bounds one source's safe list, as the schema does: the +// review shows every entry, and Slack shows a bounded message. +const maxSafeEntries = 64 + +// toolName is what a safe entry may be: an MCP tool name. Anything else +// (spaces, newlines, Slack markup) would also reach the review as text. +var toolName = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`) + +// chartSourceAlias matches a server key that names one of the meta chart's +// sources under another key: /, or a kubernetes family +// member -mcp-kubernetes. +func chartSourceAlias(key string) string { + name := key[strings.LastIndex(key, "/")+1:] + chart := definitions.Governance().Chart + if _, ok := chart[name]; ok && name != key { + return name + } + if strings.HasSuffix(name, "-mcp-kubernetes") { + return "mcp-kubernetes" + } + return "" } // governs says whether the person chose anything of the governance: the @@ -129,10 +130,8 @@ func (in *Input) governanceValues(m render.Map) render.Map { // unset), off the 4 chart line, under a hold of the meta chart before that // release, governed under a muster hold before the release that reads the // configuration, and what muster refuses to start on or the meta chart -// refuses to render — a source key that names no MCPServer, an entry -// without role or safe list, a floor of the entry's role on its safe list, -// an empty or repeated safe entry. The schema refuses a role muster does -// not know (muster's api.GovernanceRoles). +// refuses to render, and what would drop floors (checkGovernedSource). The +// schema refuses a role muster does not know (muster's api.GovernanceRoles). func (in *Input) checkGovernance() error { g := in.Governance if !g.governs() { @@ -167,37 +166,61 @@ func (in *Input) checkGovernance() error { } // checkGovernedSource is what muster or the meta chart refuses of one -// governedServers source; empty when it is accepted. +// governedServers source, and what would switch governance off past the +// floors; empty when it is accepted. A server's role is what the server is, +// fixed by the meta chart for its own sources: an override may not change it, +// since muster applies a role's floors by the server's role and a new role +// would drop them. An entry under a server key of its own names its role, +// and may not name one of the chart's sources under another key. No floor +// of any role is ever safe, and a safe entry is a tool name. func checkGovernedSource(source string, s *GovernedServer) string { for _, part := range strings.SplitN(source, "/", 2) { if errs := validation.IsDNS1123Subdomain(part); len(errs) > 0 { return fmt.Sprintf("is no source or muster server key ( or /): %s", errs[0]) } } + if alias := chartSourceAlias(source); alias != "" { + return fmt.Sprintf("names the meta chart's source %s under a server key; override it as %s, whose role the chart fixes", alias, alias) + } if s == nil { return "" } - if s.Role == "" && s.Safe == nil { + g := definitions.Governance() + chart, known := g.Chart[source] + switch { + case known && s.Role != "" && s.Role != chart.Role: + return fmt.Sprintf("role %s: the meta chart governs %s as %s, and an override may not change a server's role, whose floors muster applies by it", s.Role, source, chart.Role) + case !known && s.Role == "": + return "names no role: a server key the meta chart does not govern names the role of the server it is (its floors follow from it)" + case s.Role == "" && s.Safe == nil: return "names neither role nor safe; type the source null to drop it, or leave it out to keep the meta chart's" } if s.Safe == nil { return "" } - role := s.Role - if role == "" { - role = governanceSourceRoles[source] + if len(*s.Safe) > maxSafeEntries { + return fmt.Sprintf("safe lists %d entries, more than %d", len(*s.Safe), maxSafeEntries) } seen := map[string]bool{} for i, tool := range *s.Safe { switch { - case strings.TrimSpace(tool) == "": - return fmt.Sprintf("safe entry %d is empty", i) + case !toolName.MatchString(tool): + return fmt.Sprintf("safe entry %d, %q, is no tool name (letters, digits, _ . -, at most 128)", i, tool) case seen[tool]: return fmt.Sprintf("safe entry %d, %s, is listed twice", i, tool) - case slices.Contains(governanceRoleFloors[role], tool): - return fmt.Sprintf("safe entry %d, %s, is a floor of role %s, which asks agents in both modes; muster refuses to start on it", i, tool, role) + case g.FloorRole(tool) != "": + return fmt.Sprintf("safe entry %d, %s, is a floor of role %s, which asks agents in both modes; no floor is ever safe", i, tool, g.FloorRole(tool)) } seen[tool] = true } return "" } + +// MusterHoldBelowGovernance says whether a muster version hold +// (components.muster.versionRange) lets an installation run a muster before +// GovernanceMuster, the release that reads the governance configuration and +// enforces its floors: such a hold switches governance off there. False while +// the gate is unset (no muster enforces it yet) and for no hold. +func MusterHoldBelowGovernance(hold string) bool { + return GovernanceMuster != "" && hold != "" && !floorAtLeast(hold, GovernanceMuster) +} diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index e9bb6a08..2520f494 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -2,6 +2,7 @@ package agentplatform import ( "errors" + "fmt" "strings" "testing" @@ -137,7 +138,22 @@ func TestGovernanceRefusals(t *testing.T) { {"an unknown role", server("agent-manager", map[string]any{keyRole: "admin"}), nil, "/governance/governedServers/agent-manager/role"}, {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{keyRole: "platformManager", keySafe: []any{toolListActions, "approve_action"}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{keySafe: []any{"set_agent_approval"}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, - {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, "safe entry 0 is empty"}, + {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, "/governance/governedServers/skill-manager/safe/0"}, + // S9-02: a role override drops the floors muster applies by a + // server's role, so it is refused, as is any floor on any safe list + // and a server key standing for a chart source. + {"a chart source's role changed", server("agent-manager", map[string]any{keyRole: "infrastructure", keySafe: []any{"set_agent_approval", "create_agent"}}), nil, "role infrastructure: the meta chart governs agent-manager as agentManager"}, + {"the platform manager's role changed alone", server(sourcePlatformManager, map[string]any{keyRole: "infrastructure"}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, + {"the platform manager's role changed to list its floors", server(sourcePlatformManager, map[string]any{keyRole: "skillManager", keySafe: []any{"approve_action", "merge_action"}}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, + {"a chart source under a server key", server("agent-platform/agent-manager", map[string]any{keySafe: []any{"set_agent_approval"}}), nil, "names the meta chart's source agent-manager under a server key"}, + {"a kubernetes family member under a server key", server("mcp/alder-mcp-kubernetes", map[string]any{keyRole: "infrastructure", keySafe: []any{"get"}}), nil, "names the meta chart's source mcp-kubernetes"}, + {"a server key without role", server("agent-platform/pro", map[string]any{keySafe: []any{"get_info"}}), nil, "names no role"}, + {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{"approve_action"}}), nil, "safe entry 0, approve_action, is a floor of role platformManager"}, + // S9-03: a safe entry is a tool name, so it cannot carry Slack + // markup or a line of its own into the review, and a list is bounded. + {"markup in a safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill\n*It loosens governance:* nothing"}}), nil, "/governance/governedServers/skill-manager/safe/0"}, + {"a link in a safe entry", server("skill-manager", map[string]any{keySafe: []any{""}}), nil, "/governance/governedServers/skill-manager/safe/0"}, + {"too many safe entries", server("skill-manager", map[string]any{keySafe: manyTools(65)}), nil, "/governance/governedServers/skill-manager/safe"}, {"a repeated safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, {"neither role nor safe", server("skill-manager", map[string]any{}), nil, "names neither role nor safe"}, {"an unknown key", server("skill-manager", map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, @@ -180,7 +196,8 @@ func TestGovernanceRefusals(t *testing.T) { {"a server override on trusted under an old muster", server(sourcePlatformManager, map[string]any{keySafe: []any{toolListActions}}), func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.60.0 <6.0.0"}} }}, - {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{"approve_action"}}), nil}, + {"the chart's own role typed", server("agent-manager", map[string]any{keyRole: "agentManager", keySafe: []any{"get_info"}}), nil}, + {"the most safe entries", server("skill-manager", map[string]any{keySafe: manyTools(64)}), nil}, } { t.Run(c.name, func(t *testing.T) { input, secrets := governanceInput(t, c.governance) @@ -193,3 +210,12 @@ func TestGovernanceRefusals(t *testing.T) { }) } } + +// manyTools is n distinct read-looking tool names. +func manyTools(n int) []any { + out := make([]any, 0, n) + for i := range n { + out = append(out, fmt.Sprintf("list_items_%03d", i)) + } + return out +} From 6ec0eb0a830c11ca64ac859c5525b3095bda4e9f Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 10:54:39 +0100 Subject: [PATCH 06/27] fix(plan): compare the effective governance, with muster's own and a muster hold A plan's governance change now compares what muster governs on both sides, a source left to the meta chart read as the chart's entry, so a first override shows what it adds and removes and an explicit trusted dropped is no change. Write verbs anywhere in a tool name and floors of any role are marked, values from the record are escaped for Slack, muster's own muster.muster.governance and a muster hold below the release that enforces the governance count, and a disable deleting governed values is a loosening change. Snapshots let an Action record the governance it leaves (review S9-01, S9-03, S9-04, S9-09, S9-10, S9-14). --- internal/plan/governance.go | 473 ++++++++++++++++++++++--------- internal/plan/governance_test.go | 117 ++++++-- internal/plan/plan.go | 10 +- internal/plan/summary.go | 5 +- 4 files changed, 440 insertions(+), 165 deletions(-) diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 10049dda..9c2586cd 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -1,33 +1,42 @@ package plan import ( + "encoding/json" "fmt" - "maps" "slices" "strings" + + "github.com/giantswarm/giantswarm-platform-manager/definitions" + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" ) // GovernanceChange is what a plan changes of the platform's governance -// (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's -// top-level governance and governedServers in the installation's -// agent-platform values. Such a change is an Action a second person -// approves, on test installations too (internal/tools); its review reads -// these lines. +// (Governing tool calls, giantswarm/giantswarm#38902): in the installation's +// agent-platform values the meta chart's top-level governance and +// governedServers, muster's own muster.muster.governance, and a muster hold +// below the release that enforces it. Such a change is an Action a second +// person approves, on test installations too (internal/tools); its review +// reads these lines. type GovernanceChange struct { - // Lines are the changes, old → new with their values. + // Lines are the changes, old → new with their values, the effective + // governance on both sides: a source left to the meta chart reads as the + // chart's entry (definitions/agent-platform/governance.yaml). Lines []string `json:"lines"` // Loosens are the lines that loosen the governance, or may: the mode - // leaving governed, a source no longer governed or put back to the - // chart's entry, a role changed or left to the chart's, a safe entry - // added or a safe list replaced or put back to the chart's. The plan does - // not know the chart's own entries, so a change against them counts. + // leaving governed, a source no longer governed, a role changed, a safe + // entry added, muster's own governance changed, a muster hold below the + // release that enforces it, values that cannot be read. Loosens []string `json:"loosens,omitempty"` } -// The values keys of the governance, top-level in the agent-platform values. +// The values keys that carry the governance, and the snapshot's keys. const ( - keyGovernance = "governance" - keyGovernedServers = "governedServers" + keyGovernance = "governance" + keyGovernedServers = "governedServers" + keyMusterGovernance = "musterGovernance" + keyMusterHold = "musterHold" + modeGoverned = "governed" + modeTrusted = "trusted" ) // governanceUnreadable is the line of a plan whose agent-platform values @@ -35,55 +44,126 @@ const ( // file nobody can compare never passes without a second person. const governanceUnreadable = "the agent-platform values could not be read: counted as a governance change that loosens" +// governanceDeleted leads the change of a disable that deletes the values. +const governanceDeleted = "the agent-platform values are deleted with the platform, and the governance on record with them" + // governanceFile says whether path is an installation's agent-platform // values, the configmap patch that carries the governance. func governanceFile(path string) bool { return strings.HasSuffix(path, "/apps/agent-platform/configmap-values.yaml.patch") } -// GovernanceOf is the governance p changes, false when it changes none. -func GovernanceOf(p Installation) (GovernanceChange, bool) { - for _, f := range p.Files { - if !governanceFile(f.Path) || (f.Change != ChangeCreate && f.Change != ChangeUpdate) { - continue +// GovernanceSnapshot is the governance an installation's agent-platform +// values carry, by the snapshot's keys; absent keys are the chart's +// defaults. It is what an Action records as the governance its commit +// leaves (spec.governanceAfter), so the next plan compares against it. +type GovernanceSnapshot map[string]any + +// GovernanceSnapshotOf reads the governance of a values file; an empty file +// (a fresh enable's side on record) carries none. +func GovernanceSnapshotOf(content string) (GovernanceSnapshot, error) { + docs, err := yamlDocs(content) + if err != nil { + return nil, err + } + out := GovernanceSnapshot{} + for _, d := range docs { + if v, ok := d[keyGovernance]; ok { + out[keyGovernance] = v } - old, err1 := governanceValues(f.Current) - next, err2 := governanceValues(f.Content) - // A side the plan does not carry (an answer of paths only) is read as - // unreadable, never as a file without governance. - missing := f.Content == "" || (f.Change == ChangeUpdate && f.Current == "") - if err1 != nil || err2 != nil || missing { - return GovernanceChange{Lines: []string{governanceUnreadable}, Loosens: []string{governanceUnreadable}}, true + if v, ok := d[keyGovernedServers]; ok { + out[keyGovernedServers] = v } - var g GovernanceChange - g.mode(old[keyGovernance], next[keyGovernance]) - g.servers(old[keyGovernedServers], next[keyGovernedServers]) - if len(g.Lines) > 0 { - return g, true + if v := dig(d, "muster", "muster", "governance"); v != nil { + out[keyMusterGovernance] = v + } + if v := dig(d, "components", "muster", "versionRange"); v != nil { + out[keyMusterHold] = v } } - return GovernanceChange{}, false + return out, nil } -// governanceValues reads the governance keys of a values file; an empty -// file (a fresh enable's side on record) carries none. -func governanceValues(content string) (map[string]any, error) { - docs, err := yamlDocs(content) - if err != nil { +// ParseGovernanceSnapshot reads a snapshot an Action recorded. +func ParseGovernanceSnapshot(s string) (GovernanceSnapshot, error) { + var out GovernanceSnapshot + if err := json.Unmarshal([]byte(s), &out); err != nil { return nil, err } - out := map[string]any{} - for _, d := range docs { - for _, k := range []string{keyGovernance, keyGovernedServers} { - if v, ok := d[k]; ok { - out[k] = v - } - } + if out == nil { + out = GovernanceSnapshot{} } return out, nil } -// Summary is the change as the review's line reads it. +// JSON is the snapshot as an Action records it, keys sorted. +func (s GovernanceSnapshot) JSON() string { + b, _ := json.Marshal(map[string]any(s)) + return string(b) +} + +func dig(m map[string]any, keys ...string) any { + var v any = m + for _, k := range keys { + mm, ok := v.(map[string]any) + if !ok { + return nil + } + v = mm[k] + } + return v +} + +// GovernanceFile is p's agent-platform values on record and as rendered, +// false when p does not create or update them. unreadable: a side does not +// parse or the plan does not carry it (an answer of paths only), which is +// never read as a file without governance. +func GovernanceFile(p Installation) (current, next GovernanceSnapshot, ok, unreadable bool) { + for _, f := range p.Files { + if !governanceFile(f.Path) || (f.Change != ChangeCreate && f.Change != ChangeUpdate) { + continue + } + cur, err1 := GovernanceSnapshotOf(f.Current) + nxt, err2 := GovernanceSnapshotOf(f.Content) + missing := f.Content == "" || (f.Change == ChangeUpdate && f.Current == "") + return cur, nxt, true, err1 != nil || err2 != nil || missing + } + return nil, nil, false, false +} + +// GovernanceOf is the governance p changes against the record, false when +// it changes none. +func GovernanceOf(p Installation) (GovernanceChange, bool) { + current, next, ok, unreadable := GovernanceFile(p) + switch { + case !ok: + return GovernanceChange{}, false + case unreadable: + return GovernanceUnreadable(), true + } + g := GovernanceBetween(current, next) + return g, len(g.Lines) > 0 +} + +// GovernanceUnreadable is the change of values that cannot be read. +func GovernanceUnreadable() GovernanceChange { + return GovernanceChange{Lines: []string{governanceUnreadable}, Loosens: []string{governanceUnreadable}} +} + +// GovernanceDeleted is the change of a disable that deletes values carrying +// old: every governance the record held goes, a loosening; none when the +// record held only the chart's defaults. +func GovernanceDeleted(old GovernanceSnapshot) (GovernanceChange, bool) { + g := GovernanceBetween(old, GovernanceSnapshot{}) + if len(g.Lines) == 0 { + return g, false + } + g.Lines = append([]string{governanceDeleted}, g.Lines...) + g.Loosens = append([]string{governanceDeleted}, g.Loosens...) + return g, true +} + +// Summary is the change as the summary's line reads it. func (g GovernanceChange) Summary() string { s := "governance (a second person approves): " + strings.Join(g.Lines, "; ") if len(g.Loosens) > 0 { @@ -99,122 +179,247 @@ func (g *GovernanceChange) add(line string, loosens bool) { } } -// mode compares the mode; absent is the chart's default, trusted. -func (g *GovernanceChange) mode(old, next any) { - if fmt.Sprint(old) == fmt.Sprint(next) { - return +// GovernanceBetween compares the effective governance of two snapshots: the +// mode (absent is trusted), each server as muster governs it (the meta +// chart's entry where the values leave a source alone), muster's own +// governance and the muster hold. +func GovernanceBetween(old, next GovernanceSnapshot) GovernanceChange { + var g GovernanceChange + om, nm := effectiveMode(old[keyGovernance]), effectiveMode(next[keyGovernance]) + if om != nm { + g.add(fmt.Sprintf("mode %s → %s", om, nm), om == modeGoverned) + } + g.servers(effectiveServers(old[keyGovernedServers]), effectiveServers(next[keyGovernedServers])) + if o, n := canonical(old[keyMusterGovernance]), canonical(next[keyMusterGovernance]); o != n { + g.add(fmt.Sprintf("muster.muster.governance %s → %s", short(o), short(n)), true) + } + oh, nh := fmt.Sprint(orEmpty(old[keyMusterHold])), fmt.Sprint(orEmpty(next[keyMusterHold])) + if oh != nh && (agentplatform.MusterHoldBelowGovernance(oh) || agentplatform.MusterHoldBelowGovernance(nh)) { + g.add(fmt.Sprintf("muster hold %s → %s (below muster %s, which enforces the governance)", quoteOr(oh, "none"), quoteOr(nh, "none"), agentplatform.GovernanceMuster), agentplatform.MusterHoldBelowGovernance(nh)) + } + return g +} + +func effectiveMode(v any) string { + if v == nil { + return modeTrusted + } + return clean(fmt.Sprint(v)) +} + +// server is a source as muster governs it: its role and safe list. +type server struct { + role string + safe []string + // odd: the values' entry is no map, nor null; read as loosening. + odd string +} + +// effectiveServers are the governed servers by source: the meta chart's, +// each override over its source's entry (Helm merges the maps, a list +// replaces), a null source not governed (nil). +func effectiveServers(v any) map[string]*server { + out := map[string]*server{} + for source, s := range definitions.Governance().Chart { + out[source] = &server{role: s.Role, safe: slices.Clone(s.Safe)} } - read := func(v any) string { - if v == nil { - return "trusted (the chart's default)" + overrides, _ := v.(map[string]any) + if v != nil && overrides == nil { + out[""] = &server{odd: fmt.Sprint(v)} + } + for source, o := range overrides { + if o == nil { + out[source] = nil + continue } - return fmt.Sprint(v) + m, ok := o.(map[string]any) + if !ok { + out[source] = &server{odd: fmt.Sprint(o)} + continue + } + s := &server{} + if base := out[source]; base != nil { + *s = *base + } + if r, ok := m["role"]; ok { + s.role = fmt.Sprint(r) + } + if l, ok := m["safe"]; ok { + list, _ := l.([]any) + s.safe = strs(list) + } + out[source] = s } - g.add(fmt.Sprintf("mode %s → %s", read(old), read(next)), fmt.Sprint(old) == "governed" && fmt.Sprint(next) != "governed") + return out } -// servers compares the governedServers overrides by source. -func (g *GovernanceChange) servers(oldV, nextV any) { - old, _ := oldV.(map[string]any) - next, _ := nextV.(map[string]any) +// servers compares the governed servers by source. +func (g *GovernanceChange) servers(old, next map[string]*server) { + chart := definitions.Governance().Chart for _, source := range sortedKeys(old, next) { - o, inOld := old[source] - n, inNext := next[source] - at := keyGovernedServers + "." + source + o, n := old[source], next[source] + at := keyGovernedServers + "." + clean(source) switch { - case inOld && inNext && o != nil && n != nil: - g.entry(at, o, n) - case fmt.Sprint(inOld, o) != fmt.Sprint(inNext, n): - // Anything but null → null-or-absent the other way round loosens: - // the source leaves the governed servers or its typed entry gives - // way to the chart's, which the plan does not know. - tightens := inOld && o == nil - g.add(fmt.Sprintf("%s %s → %s", at, serverEntry(inOld, o), serverEntry(inNext, n)), !tightens) + case o == nil && n == nil: + case n != nil && n.odd != "": + if o == nil || o.odd != n.odd { + g.add(fmt.Sprintf("%s is no {role, safe} entry: %s", at, short(n.odd)), true) + } + case o != nil && o.odd != "": + g.add(fmt.Sprintf("%s was no {role, safe} entry: %s", at, short(o.odd)), true) + if n != nil { + g.add(fmt.Sprintf("%s → %s", at, n.describe()), false) + } + case n == nil: + g.add(fmt.Sprintf("%s %s → not governed (null)", at, o.brief()), true) + case o == nil: + // Governed again, or newly: it loosens only against what the chart + // governs the source as, a server key of its own tightens. + base, known := chart[source] + var added []string + if known { + added = notIn(n.safe, base.Safe) + } + line := fmt.Sprintf("%s not governed → %s", at, n.describe()) + if len(added) > 0 { + line += "; against the chart's list " + strings.Join(marked(added), " ") + } + g.add(line, known && (n.role != base.Role || len(added) > 0) || floorsIn(n.safe)) + default: + if o.role != n.role { + g.add(fmt.Sprintf("%s.role %s → %s", at, quoteOr(o.role, "none"), quoteOr(n.role, "none")), true) + } + added, removed := notIn(n.safe, o.safe), notIn(o.safe, n.safe) + if len(added)+len(removed) == 0 { + continue + } + parts := marked(added) + for _, r := range removed { + parts = append(parts, "−"+clean(r)) + } + g.Lines = append(g.Lines, fmt.Sprintf("%s.safe %s", at, strings.Join(parts, " "))) + if len(added) > 0 { + g.Loosens = append(g.Loosens, fmt.Sprintf("%s.safe %s", at, strings.Join(marked(added), " "))) + } } } } -// entry compares one source's typed entries: its role and its safe list. -func (g *GovernanceChange) entry(at string, oldV, nextV any) { - old, _ := oldV.(map[string]any) - next, _ := nextV.(map[string]any) - if fmt.Sprint(old["role"]) != fmt.Sprint(next["role"]) { - g.add(fmt.Sprintf("%s.role %s → %s", at, orChart(old["role"], "role"), orChart(next["role"], "role")), true) +// brief is a server that goes, as its role and the size of its safe list. +func (s *server) brief() string { + if s.odd != "" { + return short(s.odd) } - o, inOld := old["safe"] - n, inNext := next["safe"] - switch { - case !inOld && !inNext: - case !inOld || !inNext: - g.add(fmt.Sprintf("%s.safe %s → %s", at, orChart(o, "list"), orChart(n, "list")), true) - default: - ol, nl := strs(asList(o)), strs(asList(n)) - var added, removed []string - for _, v := range nl { - if !slices.Contains(ol, v) { - added = append(added, "+"+v+writeNote(v)) - } - } - for _, v := range ol { - if !slices.Contains(nl, v) { - removed = append(removed, "−"+v) - } - } - if len(added)+len(removed) == 0 { - return + return fmt.Sprintf("{role: %s, %d safe}", quoteOr(s.role, "none"), len(s.safe)) +} + +func (s *server) describe() string { + if s.odd != "" { + return s.odd + } + safe := make([]string, 0, len(s.safe)) + for _, t := range s.safe { + safe = append(safe, clean(t)) + } + return fmt.Sprintf("{role: %s, safe: [%s]}", quoteOr(clean(s.role), "none"), strings.Join(safe, ", ")) +} + +// notIn are the entries of a not in b, in a's order. +func notIn(a, b []string) []string { + var out []string + for _, v := range a { + if !slices.Contains(b, v) { + out = append(out, v) } - g.Lines = append(g.Lines, fmt.Sprintf("%s.safe %s", at, strings.Join(slices.Concat(added, removed), " "))) - if len(added) > 0 { - g.Loosens = append(g.Loosens, fmt.Sprintf("%s.safe %s", at, strings.Join(added, " "))) + } + return out +} + +// marked are added safe entries as the review reads them: +name, marked +// where it is a floor of any role or named like a write. +func marked(added []string) []string { + out := make([]string, 0, len(added)) + for _, v := range added { + out = append(out, "+"+clean(v)+entryNote(v)) + } + return out +} + +func floorsIn(safe []string) bool { + return slices.ContainsFunc(safe, func(t string) bool { return definitions.Governance().FloorRole(t) != "" }) +} + +// writeVerbs are the words of a tool name that changes something: a safe +// entry with one anywhere in its name is marked, so the second person looks +// twice. +var writeVerbs = []string{"add", "apply", "approve", "authorize", "cancel", "connect", "create", "delete", "deny", "deploy", "disable", "enable", "exec", "fork", "forward", "grant", "invoke", "kill", "merge", "patch", "push", "remove", "replace", "restart", "revoke", "rotate", "run", "scale", "set", "start", "stop", "sync", "update", "use", "write"} + +func entryNote(tool string) string { + if role := definitions.Governance().FloorRole(tool); role != "" { + return " (a floor of " + role + ")" + } + for _, word := range strings.FieldsFunc(strings.ToLower(tool), func(r rune) bool { return r == '_' || r == '-' || r == '.' }) { + if slices.Contains(writeVerbs, word) { + return " (named like a write)" } } + return "" } -// serverEntry reads one source's state: the chart's entry (absent), not -// governed (null), or the typed entry. -func serverEntry(present bool, v any) string { - switch { - case !present: - return "the chart's entry" - case v == nil: - return "null (not governed)" - } - m, _ := v.(map[string]any) - var parts []string - for _, k := range slices.Sorted(maps.Keys(m)) { - val := m[k] - if l, ok := val.([]any); ok { - val = "[" + strings.Join(strs(l), ", ") + "]" +// clean keeps a value from the values safe to show in Slack's markup: a +// character outside a tool or key name's and a value's punctuation +// (letters, digits, _ . - / : @ space { } [ ] , " =), and < > & as +// Slack's escapes is written as its code point, so no value carries a line, markup +// or a link of its own into the review. +func clean(s string) string { + var b strings.Builder + for _, r := range s { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', strings.ContainsRune("_.-/:@ {}[],\"=", r): + b.WriteRune(r) + case r == '<': + b.WriteString("<") + case r == '>': + b.WriteString(">") + case r == '&': + b.WriteString("&") + default: + fmt.Fprintf(&b, "\\u%04X", r) } - parts = append(parts, fmt.Sprintf("%s: %v", k, val)) } - return "{" + strings.Join(parts, ", ") + "}" + return b.String() } -// orChart reads a role or safe list, absent as the chart's. -func orChart(v any, what string) string { +func canonical(v any) string { if v == nil { - return "the chart's " + what - } - if l, ok := v.([]any); ok { - return "[" + strings.Join(strs(l), ", ") + "]" + return "" } - return fmt.Sprint(v) + b, _ := json.Marshal(v) + return string(b) } -func asList(v any) []any { - l, _ := v.([]any) - return l +// short is a value cut for a line; the pull requests carry it in full. +func short(s string) string { + if s == "" { + return "none" + } + s = clean(s) + if r := []rune(s); len(r) > 200 { + return string(r[:200]) + "… (in full in the configs pull request)" + } + return s } -// writeVerbs are the leading words of a tool name that changes something: -// a safe entry named so is marked, so the second person looks twice. -var writeVerbs = []string{"add", "apply", "approve", "authorize", "cancel", "connect", "create", "delete", "deny", "deploy", "disable", "enable", "exec", "fork", "grant", "invoke", "kill", "merge", "patch", "push", "remove", "replace", "restart", "revoke", "rotate", "run", "scale", "set", "start", "stop", "sync", "update", "write"} +func orEmpty(v any) any { + if v == nil { + return "" + } + return v +} -func writeNote(tool string) string { - verb, _, _ := strings.Cut(tool, "_") - if slices.Contains(writeVerbs, verb) { - return " (named like a write)" +func quoteOr(s, none string) string { + if s == "" { + return none } - return "" + return clean(s) } diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index 9e050f8b..719e4066 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -4,6 +4,8 @@ import ( "slices" "strings" "testing" + + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" ) const ( @@ -27,43 +29,55 @@ func govPlanOf(change Change, current, next string) Installation { return Installation{Name: govInstallation, Files: []File{{Path: govPatch, Change: change, Current: current, Content: next}}} } -// The governance a plan changes reads old → new with its values, and every -// change that loosens it — governed to trusted (or to the chart's default, -// trusted), a source dropped or put back to the chart's entry, a role -// changed or left to the chart's, a safe entry added (one named like a -// write marked) — is named apart; a change that only tightens loosens -// nothing. +// The governance a plan changes reads old → new with its values, the +// effective governance on both sides (a source left to the meta chart is +// the chart's entry, so a first override reads what it adds and removes), +// and every change that loosens it is named apart; a change that only +// tightens loosens nothing, and one that changes nothing effective (an +// explicit trusted dropped) is no change. func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { + const pm = "governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_things −list_actions" + const dropped = "governedServers.mcp-kubernetes {role: infrastructure, 14 safe} → not governed (null)" for _, c := range []struct { name string current, next string lines, loosens []string }{ - {"trusted to governed tightens", govEmpty, "global: {}\ngovernance: governed\n", - []string{"mode trusted (the chart's default) → governed"}, nil}, - {"governed to the chart's default loosens", govGoverned, govEmpty, - []string{"mode governed → trusted (the chart's default)"}, []string{"mode governed → trusted (the chart's default)"}}, - {"a safe entry added and one removed", "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_actions]\n", - "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, create_thing, list_installations]\n", - []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_installations −list_actions"}, - []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_installations"}}, + {"trusted to governed tightens", govEmpty, "global: {}\ngovernance: governed\n", []string{"mode trusted → governed"}, nil}, + {"governed to the chart's default loosens", govGoverned, govEmpty, []string{"mode governed → trusted"}, []string{"mode governed → trusted"}}, + {"a safe entry added and one removed", govEmpty, "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_installations, get_action, verify_capability, create_thing, list_things]\n", + []string{pm}, []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_things"}}, {"only a safe entry removed", "governedServers:\n agent-manager:\n safe: [get_info, list_agents]\n", "governedServers:\n agent-manager:\n safe: [get_info]\n", []string{"governedServers.agent-manager.safe −list_agents"}, nil}, - {"a source dropped", govGoverned, "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", - []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}, []string{"governedServers.mcp-kubernetes the chart's entry → null (not governed)"}}, - {"a dropped source governed again", "governedServers:\n mcp-kubernetes: null\n", govEmpty, - []string{"governedServers.mcp-kubernetes null (not governed) → the chart's entry"}, nil}, - {"an override over the chart's entry", govEmpty, "governedServers:\n kagent:\n role: sessionManager\n safe: [list_sessions]\n", - []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}, - []string{"governedServers.kagent the chart's entry → {role: sessionManager, safe: [list_sessions]}"}}, + {"a source dropped", govGoverned, "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", []string{dropped}, []string{dropped}}, + {"a dropped source governed again by the chart", "governedServers:\n mcp-kubernetes: null\n", govEmpty, + []string{"governedServers.mcp-kubernetes not governed → {role: infrastructure, safe: [logs, list_port_forward_sessions, context_list, context_get_current, can_i, api_resources, cluster_health, capi_list_clusters, capi_get_cluster, capi_resolve_cluster, capi_cluster_health, get, list, describe]}"}, nil}, + {"an override that narrows the chart's list", govEmpty, "governedServers:\n kagent:\n role: sessionManager\n safe: [list_sessions, list_sandboxes]\n", + []string{"governedServers.kagent.safe −list_session_checkpoints −list_sandbox_templates −get_sandbox −get_sandbox_process −read_sandbox_outputs −read_sandbox_file"}, nil}, {"a role changed", "governedServers:\n x:\n role: platformManager\n", "governedServers:\n x:\n role: infrastructure\n", []string{"governedServers.x.role platformManager → infrastructure"}, []string{"governedServers.x.role platformManager → infrastructure"}}, - {"a safe list back to the chart's", "governedServers:\n x:\n role: infrastructure\n safe: [a]\n", "governedServers:\n x:\n role: infrastructure\n", - []string{"governedServers.x.safe [a] → the chart's list"}, []string{"governedServers.x.safe [a] → the chart's list"}}, - {"a fresh enable with governed", "", govGoverned, - []string{"mode trusted (the chart's default) → governed"}, nil}, - {"values that do not parse are a change that loosens", "governance: [\n", govGoverned, - []string{governanceUnreadable}, []string{governanceUnreadable}}, + {"a fresh enable with governed", "", govGoverned, []string{"mode trusted → governed"}, nil}, + {"values that do not parse are a change that loosens", "governance: [\n", govGoverned, []string{governanceUnreadable}, []string{governanceUnreadable}}, + // S9-04: a first override reads what it adds against the chart's list. + {"a first override shows what it adds", govGoverned, "governance: governed\ngovernedServers:\n agent-manager:\n safe: [get_info, create_agent, update_agent_access]\n", + []string{"governedServers.agent-manager.safe +create_agent (named like a write) +update_agent_access (named like a write) −list_agents −get_agent −get_agent_status −validate_agent −list_model_configs −list_egress_policies −list_skills −list_sessions −get_session −get_session_turn −toolchain_users −list_organizations −get_organization −list_organization_members −list_organization_connectors"}, + []string{"governedServers.agent-manager.safe +create_agent (named like a write) +update_agent_access (named like a write)"}}, + // S9-09: governed again with another role and a floor loosens; a + // write verb anywhere in a name and a floor of any role are marked. + {"governed again with another role and a floor", "governedServers:\n agent-manager: null\n", "governedServers:\n agent-manager:\n role: infrastructure\n safe: [set_agent_approval]\n", + []string{"governedServers.agent-manager not governed → {role: infrastructure, safe: [set_agent_approval]}; against the chart's list +set_agent_approval (a floor of agentManager)"}, + []string{"governedServers.agent-manager not governed → {role: infrastructure, safe: [set_agent_approval]}; against the chart's list +set_agent_approval (a floor of agentManager)"}}, + {"write verbs anywhere in a name", "governedServers:\n x:\n role: infrastructure\n safe: [a]\n", "governedServers:\n x:\n role: infrastructure\n safe: [a, kubernetes_delete, port_forward, mcpserver_create, context_use]\n", + []string{"governedServers.x.safe +kubernetes_delete (named like a write) +port_forward (named like a write) +mcpserver_create (a floor of connectorManager) +context_use (named like a write)"}, + []string{"governedServers.x.safe +kubernetes_delete (named like a write) +port_forward (named like a write) +mcpserver_create (a floor of connectorManager) +context_use (named like a write)"}}, + // S9-03: a value read from the record never carries a line or markup. + {"markup in a value on record", "governedServers:\n x:\n role: infrastructure\n safe: [a]\n", "governedServers:\n x:\n role: infrastructure\n safe: [a, \"b\\n*It tightens governance* \"]\n", + []string{`governedServers.x.safe +b\u000A\u002AIt tightens governance\u002A <https://x\u007Cy>`}, + []string{`governedServers.x.safe +b\u000A\u002AIt tightens governance\u002A <https://x\u007Cy>`}}, + // S9-10: muster's own governance on record is governance too. + {"muster's own governance dropped", "governance: governed\nmuster:\n muster:\n governance:\n governedServers:\n - {server: agent-manager, role: agentManager, safe: []}\n", govGoverned, + []string{`muster.muster.governance {"governedServers":[{"role":"agentManager","safe":[],"server":"agent-manager"}]} → none`}, + []string{`muster.muster.governance {"governedServers":[{"role":"agentManager","safe":[],"server":"agent-manager"}]} → none`}}, } { t.Run(c.name, func(t *testing.T) { g, ok := GovernanceOf(govPlan(c.current, c.next)) @@ -75,6 +89,10 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { } }) } + // S9-14: what changes nothing effective is no change. + if g, ok := GovernanceOf(govPlan("governance: trusted\n", govEmpty)); ok { + t.Fatalf("an explicit trusted dropped: %+v", g) + } // An update whose side on record the plan does not carry (an answer of // paths only) is no file without governance: it counts, as loosening. for _, p := range []Installation{govPlanOf(ChangeUpdate, "", govEmpty), govPlanOf(ChangeUpdate, govGoverned, "")} { @@ -105,10 +123,53 @@ func TestNoGovernanceChange(t *testing.T) { func TestSummaryReadsTheGovernanceWithItsValues(t *testing.T) { got := Summary(govPlan("global:\n domain: a\n", "global:\n domain: b\ngovernance: governed\ngovernedServers:\n x:\n safe: [get_info]\n")) want := []string{ - "governance (a second person approves): mode trusted (the chart's default) → governed; governedServers.x the chart's entry → {safe: [get_info]} — loosens: governedServers.x the chart's entry → {safe: [get_info]}", + "governance (a second person approves): mode trusted → governed; governedServers.x not governed → {role: none, safe: [get_info]}", "agent-platform: values global.domain", } if !slices.Equal(got, want) { t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) } } + +// S9-01: a disable that deletes values carrying a governance is a loosening +// governance change; values with the chart's defaults alone are none. +func TestGovernanceDeleted(t *testing.T) { + old, err := GovernanceSnapshotOf("governance: governed\ngovernedServers:\n agent-manager:\n safe: [get_info]\n") + if err != nil { + t.Fatal(err) + } + g, ok := GovernanceDeleted(old) + if !ok || g.Lines[0] != governanceDeleted || !slices.Contains(g.Loosens, "mode governed → trusted") || len(g.Loosens) != len(g.Lines) { + t.Fatalf("a governed record deleted: %v %+v", ok, g) + } + if g, ok := GovernanceDeleted(GovernanceSnapshot{}); ok { + t.Fatalf("a record with the chart's defaults deleted: %+v", g) + } + again, err := ParseGovernanceSnapshot(old.JSON()) + if err != nil || len(GovernanceBetween(old, again).Lines) != 0 { + t.Fatalf("a snapshot recorded and read again: %v %+v", err, GovernanceBetween(old, again)) + } +} + +// S9-10: once muster's release that enforces the governance is known, a +// muster hold below it is a loosening governance change, lifting it a +// tightening one; while it is unset a hold changes no governance. +func TestMusterHoldBelowTheGovernanceRelease(t *testing.T) { + hold := func(r string) GovernanceSnapshot { return GovernanceSnapshot{keyMusterHold: r} } + if g := GovernanceBetween(GovernanceSnapshot{}, hold(">=5.60.0 <6.0.0")); len(g.Lines) != 0 { + t.Fatalf("a hold with the gate unset: %+v", g) + } + gate := agentplatform.GovernanceMuster + agentplatform.GovernanceMuster = "5.70.0" + t.Cleanup(func() { agentplatform.GovernanceMuster = gate }) + g := GovernanceBetween(GovernanceSnapshot{}, hold(">=5.60.0 <6.0.0")) + if len(g.Loosens) != 1 || !strings.Contains(g.Loosens[0], "muster hold none → >=5.60.0 <6.0.0") { + t.Fatalf("a hold below the gate: %+v", g) + } + if g := GovernanceBetween(hold(">=5.60.0 <6.0.0"), GovernanceSnapshot{}); len(g.Lines) != 1 || len(g.Loosens) != 0 { + t.Fatalf("the hold lifted: %+v", g) + } + if g := GovernanceBetween(GovernanceSnapshot{}, hold(">=5.71.0 <6.0.0")); len(g.Lines) != 0 { + t.Fatalf("a hold above the gate: %+v", g) + } +} diff --git a/internal/plan/plan.go b/internal/plan/plan.go index 5ef1c29e..1add6d68 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -358,8 +358,14 @@ type Installation struct { // agent-platform values patch switches off, with what depends on each: // the warning the dry run prints first, apart from the drift lines; nil // where it switches nothing off (SwitchOffRefusal). - SwitchOff *SwitchOff `json:"switchOff,omitempty"` - DexClients []DexClient `json:"dexClients"` + SwitchOff *SwitchOff `json:"switchOff,omitempty"` + // Governance is the platform's governance a commit of the plan changes, + // old → new, against the governance the last reviewed action left + // where the manager knows it, else the record (internal/tools sets it): + // a commit carrying one is approved by a second person, on test + // installations too. + Governance *GovernanceChange `json:"governance,omitempty"` + DexClients []DexClient `json:"dexClients"` // DexConnectors and DexStaffConnectors are the ids of the hubs' // connectors the rendered Dex patch declares under // oidc.customer.connectors and oidc.giantswarm.connectors diff --git a/internal/plan/summary.go b/internal/plan/summary.go index c4be266d..a58ad32b 100644 --- a/internal/plan/summary.go +++ b/internal/plan/summary.go @@ -78,7 +78,10 @@ func Summary(p Installation) []string { if w := p.SwitchOff.Warning(); w != "" { out = append(out, w) } - if g, ok := GovernanceOf(p); ok { + switch g, ok := GovernanceOf(p); { + case p.Governance != nil: + out = append(out, p.Governance.Summary()) + case ok: out = append(out, g.Summary()) } for _, name := range order { From ea37b12cba2e8c2c5c900a6ffdf788896a7ecd9d Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:10:19 +0100 Subject: [PATCH 07/27] fix(tools): compare governance with the last reviewed action and check the second person's team Every Action records the governance its commit leaves (spec.governanceAfter; a disable records the governance before it), and a plan compares against the newest reviewed one: a disable followed by an enable, or a change made in the configs repository directly, is a governance change again and asks the review, the outside change named and logged. A disable deleting governed values asks the review on test installations too. Before recording that a test installation needs no review, the commit reads the values on the default branch again. approve_action refuses the actor by GitHub id too, and for a governance change anyone who is not an active member of the approvals.governanceTeam GitHub team or no person, read as the approver and failing closed. A stage merged outside the manager decides nothing for a governance change; such merges are audited in any state, merges per stage with their pull requests and heads. The review puts what loosens first and never cuts it, refusing a change whose loosening lines do not fit, and an Action stored without its governance is refused (review S9-01, S9-03, S9-05, S9-06, S9-07, S9-08, S9-11, S9-15, S9-16). --- definitions/governance_test.go | 2 +- helm/giantswarm-platform-manager/README.md | 1 + .../templates/crd-actions.yaml | 4 + .../templates/deployment.yaml | 2 + .../values.schema.json | 5 + helm/giantswarm-platform-manager/values.yaml | 5 + internal/actions/actions.go | 6 + internal/approvals/approvals.go | 7 + internal/e2e/fakes_test.go | 62 +++- internal/e2e/governance_test.go | 230 +++++++++++- internal/e2e/identity_chain_test.go | 13 +- internal/tools/approval.go | 40 ++- internal/tools/capability.go | 6 + internal/tools/commit.go | 32 +- internal/tools/disable.go | 24 ++ internal/tools/governance.go | 338 ++++++++++++++++-- internal/tools/governance_test.go | 85 ++++- internal/tools/resync.go | 14 +- internal/tools/server.go | 3 +- internal/tools/wave.go | 35 +- main.go | 5 +- render/agentplatform/governance_test.go | 55 ++- 22 files changed, 881 insertions(+), 93 deletions(-) diff --git a/definitions/governance_test.go b/definitions/governance_test.go index aa71edce..5e13d9e2 100644 --- a/definitions/governance_test.go +++ b/definitions/governance_test.go @@ -24,7 +24,7 @@ func checkout(t *testing.T, env, repo, path string) []byte { if dir == "" { dir = filepath.Join("..", "..", repo) } - raw, err := os.ReadFile(filepath.Join(dir, path)) + raw, err := os.ReadFile(filepath.Join(dir, path)) // #nosec G304 G703 -- a test reading a sibling checkout the developer names if err != nil { t.Skipf("no %s checkout (%s, or set %s): %v", repo, dir, env, err) } diff --git a/helm/giantswarm-platform-manager/README.md b/helm/giantswarm-platform-manager/README.md index 21237776..9e24a39a 100644 --- a/helm/giantswarm-platform-manager/README.md +++ b/helm/giantswarm-platform-manager/README.md @@ -49,6 +49,7 @@ header; every other tool answers with the user token alone. | approvals.channel | string | `""` | The capability-owning team's channel the reviews land in (a Slack channel ID). | | approvals.noticeChannel | string | `""` | The channel told, without buttons, once an action's change is applied on a customer installation: who, what, why and the account engineer (the Account Engineers' channel ID); it never sees the review. Must differ from `channel`; empty sends no notice. | | approvals.standupChannel | string | `""` | The owning team's standup channel (a Slack channel ID): an action on Giant Swarm's test installations alone (the hub's customer's, not the hub) needs no review, and its merge is told here in one sentence. Empty refuses `mode: commit` on test installations; the hub and customer installations keep the review. | +| approvals.governanceTeam | string | `""` | The GitHub team whose active members approve an action that changes an installation's governance (`org/team`): approve_action checks the approver's membership as the approver and refuses when it cannot read it. Empty: no governance change can be approved. | | approvals.audience | string | `"klaus-gateway"` | Audience of the projected ServiceAccount token the requests carry: the gateway's TokenReview audience. | | live.enabled | bool | `false` | Serve the live tools `verify_installation` and `watch_action` on `mcp.path`, beside every other tool: they read an installation through muster as the person the platform ID token muster forwards next to the bearer names (`X-Muster-Id-Token`). The chart's `MCPServer` then sets `auth.forwardIdentity: true`, which needs muster ≥ 5.31.0 and `oauth.enabled`. A call without a valid identity token is refused by the live tools, naming the header; the GitHub tools answer as before. Off: the live tools are not served, the live dimensions of every verify read not checked, and `get_info` reports `live.configured: false`. | | live.issuer | string | `""` | Issuer of the forwarded tokens: the platform identity provider's, `https://dex./dex` on an installation. Required with `live.enabled`. | diff --git a/helm/giantswarm-platform-manager/templates/crd-actions.yaml b/helm/giantswarm-platform-manager/templates/crd-actions.yaml index 0fa83df7..db1a934d 100644 --- a/helm/giantswarm-platform-manager/templates/crd-actions.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-actions.yaml @@ -155,6 +155,10 @@ spec: loosens: type: array items: {type: string} + governanceAfter: + description: Per installation, the governance the commit leaves on record (a disable's is the governance before it), as JSON of the governance values; the next plan compares against the newest reviewed one. Values only, never a secret. + type: object + additionalProperties: {type: string} status: type: object properties: diff --git a/helm/giantswarm-platform-manager/templates/deployment.yaml b/helm/giantswarm-platform-manager/templates/deployment.yaml index 2c6f3962..9751cfb4 100644 --- a/helm/giantswarm-platform-manager/templates/deployment.yaml +++ b/helm/giantswarm-platform-manager/templates/deployment.yaml @@ -112,6 +112,8 @@ spec: value: {{ .Values.approvals.noticeChannel | quote }} - name: APPROVALS_STANDUP_CHANNEL value: {{ .Values.approvals.standupChannel | quote }} + - name: APPROVALS_GOVERNANCE_TEAM + value: {{ .Values.approvals.governanceTeam | quote }} - name: APPROVALS_TOKEN_FILE value: /var/run/secrets/klaus-gateway/token {{- end }} diff --git a/helm/giantswarm-platform-manager/values.schema.json b/helm/giantswarm-platform-manager/values.schema.json index 0d2c5e1b..2d0c4c08 100644 --- a/helm/giantswarm-platform-manager/values.schema.json +++ b/helm/giantswarm-platform-manager/values.schema.json @@ -38,6 +38,11 @@ "type": "string", "description": "klaus-gateway's base URL as reached from the pod (for example `http://klaus-gateway.agent-platform.svc:8080`): the team-review endpoint an action's approval request goes to. Empty refuses `mode: commit` (nothing is committed that no one can approve); `get_info` reports `approvals.configured: false`. The requests carry the pod's projected ServiceAccount token in the gateway's audience; the gateway's `reviews.allowedCallers` must name this ServiceAccount." }, + "governanceTeam": { + "type": "string", + "description": "The GitHub team whose active members approve an action that changes an installation's governance (`org/team`): approve_action checks the approver's membership as the approver and refuses when it cannot read it. Empty: no governance change can be approved.", + "pattern": "^([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)?$" + }, "noticeChannel": { "type": "string", "description": "The channel told, without buttons, once an action's change is applied on a customer installation: who, what, why and the account engineer (the Account Engineers' channel ID); it never sees the review. Must differ from `channel`; empty sends no notice." diff --git a/helm/giantswarm-platform-manager/values.yaml b/helm/giantswarm-platform-manager/values.yaml index 8c70d2c3..e1468d52 100644 --- a/helm/giantswarm-platform-manager/values.yaml +++ b/helm/giantswarm-platform-manager/values.yaml @@ -90,6 +90,11 @@ approvals: # `mode: commit` on test installations; the hub and customer installations # keep the review. standupChannel: "" + # -- The GitHub team whose active members approve an action that changes + # an installation's governance (`org/team`): approve_action checks the + # approver's membership as the approver and refuses when it cannot read + # it. Empty: no governance change can be approved. + governanceTeam: "" # @schema pattern: ^([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)?$ # -- Audience of the projected ServiceAccount token the requests carry: the # gateway's TokenReview audience. audience: klaus-gateway diff --git a/internal/actions/actions.go b/internal/actions/actions.go index 2fa6f96e..76d193cf 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -124,6 +124,12 @@ type Spec struct { // action is approved by a second person, on test installations too, and // its approval and merge are audited. Recorded at commit. Governance map[string]plan.GovernanceChange `json:"governance,omitempty"` + // GovernanceAfter is, per installation, the governance the commit leaves + // on record (plan.GovernanceSnapshot as JSON; a disable's is the + // governance before it): the next plan compares against the newest + // reviewed one, so a change made outside the manager, or a disable + // followed by an enable, is a governance change again. Values only. + GovernanceAfter map[string]string `json:"governanceAfter,omitempty"` } // Skipped is an installation of a wave's set that is not a target. diff --git a/internal/approvals/approvals.go b/internal/approvals/approvals.go index 2a204373..4a0e5148 100644 --- a/internal/approvals/approvals.go +++ b/internal/approvals/approvals.go @@ -38,6 +38,10 @@ type Config struct { // Giant Swarm's test installations needs no review and is told there, // one sentence without buttons. Empty: such an action is refused. StandupChannel string + // GovernanceTeam is the GitHub team (org/team) whose active members + // approve an action that changes an installation's governance; empty, + // no such action can be approved. + GovernanceTeam string // TokenFile holds the projected ServiceAccount token (audience: the // gateway's) the requests carry as the bearer. TokenFile string @@ -60,6 +64,9 @@ func (c Config) Validate() error { if len(missing) > 0 { return fmt.Errorf("approvals: a gateway URL is set and %s is not", strings.Join(sorted(missing), ", ")) } + if org, team, ok := strings.Cut(c.GovernanceTeam, "/"); c.GovernanceTeam != "" && (!ok || org == "" || team == "" || strings.Contains(team, "/")) { + return fmt.Errorf("approvals: governance team %q is no org/team", c.GovernanceTeam) + } if c.NoticeChannel != "" && c.NoticeChannel == c.Channel { return errors.New("approvals: the notice channel must differ from the review channel") } diff --git a/internal/e2e/fakes_test.go b/internal/e2e/fakes_test.go index caabf6a2..ec0555f8 100644 --- a/internal/e2e/fakes_test.go +++ b/internal/e2e/fakes_test.go @@ -43,7 +43,13 @@ type fakeGitHub struct { // has it; nil answers none. pull func(repo string, number int) (fakePull, bool) - mu sync.Mutex + mu sync.Mutex + // teams are the GitHub teams by org/slug, each login's membership state + // (active, pending); teamsFailing answers memberships with a 502. + teams map[string]map[string]string + teamsFailing bool + // userTypes are the accounts' GitHub types where not User (Bot). + userTypes map[string]string files map[string]map[string]string // owner/repo → path → content forbidden map[string]bool // hidden holds the owner/repo GitHub answers with a 404 on every read, @@ -101,6 +107,12 @@ const ( filenameKey = "filename" ) +// GitHub's keys of a team membership's state and an account's login. +const ( + ghState = "state" + ghLogin = "login" +) + // defaultBranch is every fixture repository's default branch. const defaultBranch = "main" @@ -116,7 +128,7 @@ const ( func newFakeGitHub(t *testing.T, logins map[string]string) *fakeGitHub { t.Helper() - g := &fakeGitHub{logins: logins, files: map[string]map[string]string{}, forbidden: map[string]bool{}, hidden: map[string]bool{}, failingCompare: map[string]bool{}, failing: map[string]bool{}, releases: map[string][]fakeRelease{}, failingReleases: map[string]bool{}, contentsCalls: map[string]int{}, treeCalls: map[string]int{}, treeChecks: map[string]int{}, + g := &fakeGitHub{logins: logins, teams: map[string]map[string]string{}, userTypes: map[string]string{}, files: map[string]map[string]string{}, forbidden: map[string]bool{}, hidden: map[string]bool{}, failingCompare: map[string]bool{}, failing: map[string]bool{}, releases: map[string][]fakeRelease{}, failingReleases: map[string]bool{}, contentsCalls: map[string]int{}, treeCalls: map[string]int{}, treeChecks: map[string]int{}, history: map[string][]fakeCommit{}, commitCalls: map[string]int{}} mux := http.NewServeMux() mux.HandleFunc("GET /api/v3/user", func(w http.ResponseWriter, r *http.Request) { @@ -126,7 +138,38 @@ func newFakeGitHub(t *testing.T, logins map[string]string) *fakeGitHub { writeJSON(w, http.StatusUnauthorized, map[string]any{message: badCredentials}) return } - writeJSON(w, http.StatusOK, map[string]any{"login": login, "id": userID(login), "email": login + "@example.test"}) + writeJSON(w, http.StatusOK, map[string]any{ghLogin: login, "id": userID(login), "email": login + "@example.test"}) + }) + mux.HandleFunc("GET /api/v3/orgs/{org}/teams/{slug}/memberships/{user}", func(w http.ResponseWriter, r *http.Request) { + if _, ok := g.logins[bearer(r)]; !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{message: badCredentials}) + return + } + g.mu.Lock() + failing, state := g.teamsFailing, g.teams[r.PathValue("org")+"/"+r.PathValue("slug")][r.PathValue("user")] + g.mu.Unlock() + switch { + case failing: + writeJSON(w, http.StatusBadGateway, map[string]any{message: serverError}) + case state == "": + writeJSON(w, http.StatusNotFound, map[string]any{message: notFound}) + default: + writeJSON(w, http.StatusOK, map[string]any{ghState: state, "role": "member"}) + } + }) + mux.HandleFunc("GET /api/v3/users/{login}", func(w http.ResponseWriter, r *http.Request) { + if _, ok := g.logins[bearer(r)]; !ok { + writeJSON(w, http.StatusUnauthorized, map[string]any{message: badCredentials}) + return + } + login := r.PathValue("login") + g.mu.Lock() + kind := g.userTypes[login] + g.mu.Unlock() + if kind == "" { + kind = "User" + } + writeJSON(w, http.StatusOK, map[string]any{ghLogin: login, "id": userID(login), "type": kind}) }) mux.HandleFunc("GET /api/v3/repos/{owner}/{repo}", func(w http.ResponseWriter, r *http.Request) { if _, ok := g.logins[bearer(r)]; !ok { @@ -935,6 +978,19 @@ type asRemote struct { st *stack } +// OpenPullRequest runs the stack's beforeOpen hook once, then opens: what +// another person merges between a plan and its pull requests. +func (r asRemote) OpenPullRequest(ctx context.Context, repo commit.Repository, head, base, title, body string) (commit.PullRequest, error) { + r.st.mu.Lock() + hook := r.st.beforeOpen + r.st.beforeOpen = nil + r.st.mu.Unlock() + if hook != nil { + hook() + } + return r.Remote.OpenPullRequest(ctx, repo, head, base, title, body) +} + func (r asRemote) Approve(ctx context.Context, pr commit.PullRequest, body string) error { r.st.record(r.login, commit.OpApprove, pr) return r.Remote.Approve(ctx, pr, body) diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index 40168a02..1736cbbe 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -10,6 +10,7 @@ package e2e import ( "encoding/json" "fmt" + "slices" "strings" "testing" @@ -19,6 +20,7 @@ import ( "github.com/giantswarm/giantswarm-platform-manager/internal/installations" "github.com/giantswarm/giantswarm-platform-manager/internal/tools" "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" + "github.com/giantswarm/giantswarm-platform-manager/render/clustermcpservers" ) // The governance input's keys. @@ -43,7 +45,10 @@ func rowanOnLineFour(g *fakeGitHub) { g.addFile(acmeMCs, installations.ClusterAppManifestPath(rowan), clusterAppManifest(rowan, "cluster-aws", "10.3.0", true)) } -func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { +// governedTestRowan is the stack with rowan one of the test installations, +// on the 4 line, with the governance releases cut. +func governedTestRowan(t *testing.T) *stack { + t.Helper() withGovernanceReleases(t) st := newStack(t) fixtures(st.ghs) @@ -51,10 +56,49 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { rowanAsTestInstallation(t, st.ghs) rowanOnLineFour(st.ghs) seedRemote(t, st) + return st +} + +// governedInputs make rowan governed and drop mcp-kubernetes from the +// governed servers. +func governedInputs() map[string]any { + return minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}}}) +} + +// approveAndMerge has carol approve the action and alice merge it once green. +func approveAndMerge(t *testing.T, st *stack, name string) actions.Action { + t.Helper() + if _, text, isErr := decide(t, st.mcpClient(t, carolToken), tools.ToolApproveAction, map[string]any{tools.ArgAction: name}); isErr { + t.Fatalf("carol's approve: %s", text) + } + for _, pr := range st.remote.PullRequests() { + st.remote.SetChecks(pr.PullRequest, commit.ChecksSuccess) + } + m, text, isErr := mergeCall(t, st.mcpClient(t, aliceToken), name) + if isErr || len(m.Merged) == 0 || m.Action == nil { + t.Fatalf("merge: %v %s", isErr, text) + } + return *m.Action +} + +// requireLog fails unless the server logged a line carrying every part. +func requireLog(t *testing.T, st *stack, parts ...string) { + t.Helper() + for _, line := range strings.Split(st.logs.String(), "\n") { + if !slices.ContainsFunc(parts, func(p string) bool { return !strings.Contains(line, p) }) { + return + } + } + t.Fatalf("no log line carries %q:\n%s", parts, st.logs.String()) +} + +const droppedKubernetes = "governedServers.mcp-kubernetes {role: infrastructure, 14 safe} → not governed (null)" + +func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { + st := governedTestRowan(t) aliceC, carolC := st.mcpClient(t, aliceToken), st.mcpClient(t, carolToken) - governance := map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}} - out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: governance})}) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) if isErr || out.Action == nil { t.Fatalf("commit: %v %s", isErr, text) } @@ -63,51 +107,177 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { t.Fatalf("a governance change on a test installation went without the review: %+v; next %q", a.Status.Approval, out.Next) } g, ok := a.Spec.Governance[rowan] - if !ok || len(g.Lines) != 2 || len(g.Loosens) != 1 || !strings.Contains(g.Loosens[0], "mcp-kubernetes") { + if !ok || len(g.Lines) != 2 || len(g.Loosens) != 1 || g.Loosens[0] != droppedKubernetes { t.Fatalf("the action's governance: %+v", a.Spec.Governance) } + if after := a.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"governance":"governed"`) { + t.Fatalf("the governance the action leaves: %q", after) + } posted := st.gateway.posted() if len(posted) != 1 { t.Fatalf("%d review(s) posted", len(posted)) } review := fmt.Sprint(posted[0].Body["text"]) - for _, want := range []string{"*Governance:* this changes the platform's governance", "mode trusted (the chart's default) → governed", "governedServers.mcp-kubernetes the chart's entry → null (not governed)", "*It loosens governance:*"} { - if !strings.Contains(review, want) { - t.Fatalf("the review carries no %q:\n%s", want, review) - } + loosens := strings.Index(review, "*It loosens governance:* rowan: "+droppedKubernetes) + if loosens < 0 || loosens > strings.Index(review, "• rowan: mode trusted → governed") || !strings.Contains(review, "*Governance:* this changes the platform's governance") { + t.Fatalf("the review leads with what loosens, then the change:\n%s", review) } + requireLog(t, st, "governance_change_committed", "action="+a.Name, "actor=alice", "loosens=true") // The actor cannot approve it, nor merge it before a member did. if _, text, isErr := decide(t, aliceC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "yours") { t.Fatalf("the actor's approve: %v %s", isErr, text) } + requireLog(t, st, "governance_change_self_approval_refused", "action="+a.Name) for _, pr := range st.remote.PullRequests() { st.remote.SetChecks(pr.PullRequest, commit.ChecksSuccess) } if m, text, isErr := mergeCall(t, aliceC, a.Name); isErr || len(m.Merged) != 0 || !strings.Contains(m.Message, "waits for the team's approval") { t.Fatalf("merge before the approval: %v %s", isErr, text) } + + // S9-05: the second person is an active member of the governance + // reviewers' team, read as them; unreadable or not active, nothing is + // approved. + st.ghs.mu.Lock() + st.ghs.teamsFailing = true + st.ghs.mu.Unlock() + if _, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "your membership could not be read") { + t.Fatalf("an approve while the membership cannot be read: %v %s", isErr, text) + } + st.ghs.mu.Lock() + st.ghs.teamsFailing = false + st.ghs.teams[governanceTeam][carol] = "pending" + st.ghs.mu.Unlock() + if _, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, `carol is "pending" there`) { + t.Fatalf("an approve by a pending member: %v %s", isErr, text) + } + st.ghs.mu.Lock() + st.ghs.teams[governanceTeam][carol] = memberActive + st.ghs.userTypes[carol] = "Bot" + st.ghs.mu.Unlock() + if _, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "carol is a GitHub Bot") { + t.Fatalf("an approve by a bot: %v %s", isErr, text) + } + requireLog(t, st, "governance_change_approval_refused", "approver=carol") + st.ghs.mu.Lock() + delete(st.ghs.userTypes, carol) + st.ghs.mu.Unlock() if d, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); isErr || d.Action == nil || d.Action.Status.Approval.DecidedBy != carol { t.Fatalf("carol's approve: %v %s", isErr, text) } - if m, text, isErr := mergeCall(t, aliceC, a.Name); isErr || len(m.Merged) == 0 { + requireLog(t, st, "governance_change_approved", "approver=carol", "membership=\"active member of "+governanceTeam) + m, text, isErr := mergeCall(t, aliceC, a.Name) + if isErr || len(m.Merged) == 0 { t.Fatalf("merge after the approval: %v %s", isErr, text) } + requireLog(t, st, "governance_change_merged", "installation=rowan", "pullRequests="+m.Merged[0].Repository) if noticed := st.gateway.noticed(); len(noticed) != 0 { t.Fatalf("a reviewed action told the standup channel: %+v", noticed) } } +// S9-01: a disable that deletes a governed installation's values is a +// governance change a second person approves, on a test installation too, +// and what it records as left is the governance before it: an enable after +// it that brings the platform back trusted is a loosening change again. +func TestDisableThenEnableOfAGovernedTestInstallationNeedsASecondPerson(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + approveAndMerge(t, st, out.Action.Name) + + st.ghs.addFile(acmeMCs, installations.CollectionsKustomizationPath(rowan), collectionsKustomization(clustermcpservers.DexAppRotation)) + st.ghs.addRepo(fleetBasesRepo, platformBaseFiles) + d, text, isErr := disableCall(t, aliceC, map[string]any{tools.ArgInstallation: rowan, tools.ArgCapability: installations.AgentPlatform, tools.ArgMode: string(tools.ModeCommit), tools.ArgReason: commitReason}) + if isErr || d.Action == nil { + t.Fatalf("disable: %v %s", isErr, text) + } + g := d.Action.Spec.Governance[rowan] + if d.Action.Status.State != actions.StatePendingApproval || d.Action.Status.Approval.ReviewID == "" || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "deleted with the platform") || !slices.Contains(g.Loosens, "mode governed → trusted") { + t.Fatalf("the disable of a governed test installation: %+v %+v", d.Action.Status.Approval, g) + } + if after := d.Action.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"governance":"governed"`) { + t.Fatalf("the governance the disable records: %q", after) + } + approveAndMerge(t, st, d.Action.Name) + if got := getAction(t, aliceC, d.Action.Name); got.Status.State != actions.StateDisabled { + t.Fatalf("the disable after its merge: %s", got.Status.State) + } + + st.ghs.addFile(acmeMCs, installations.CollectionsKustomizationPath(rowan), collectionsKustomization(platformDexApp)) + again, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || again.Action == nil { + t.Fatalf("enable again: %v %s", isErr, text) + } + g = again.Action.Spec.Governance[rowan] + if again.Action.Status.Approval == nil || again.Action.Status.Approval.Decision == actions.DecisionNotRequired || !slices.Contains(g.Loosens, "mode governed → trusted") { + t.Fatalf("an enable that brings the platform back trusted went without the review: %+v %+v", again.Action.Status.Approval, g) + } +} + +// S9-06: a governance changed in the configs repository directly is not +// adopted unseen: the next commit compares against what the last reviewed +// action left, logs the record changed outside and asks the review, even +// where the commit types the governance back. +func TestGovernanceChangedOutsideTheManagerNeedsTheReview(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + merged := approveAndMerge(t, st, out.Action.Name) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + values, ok := st.ghs.file(acmeConfigs, marker) + if !ok || !strings.Contains(values, "\ngovernance: governed\n") { + t.Fatalf("the governed values on record: %v\n%s", ok, values) + } + // Someone takes governed out in the repository, past the manager. + st.ghs.addFile(acmeConfigs, marker, strings.Replace(values, "\ngovernance: governed\n", "\n", 1)) + + // Typing governed again changes no governance against the reviewed + // action, yet the record moved: the review stands, the outside change + // named first. + again, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || again.Action == nil { + t.Fatalf("reconcile: %v %s", isErr, text) + } + g := again.Action.Spec.Governance[rowan] + if again.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.HasPrefix(g.Lines[0], "the governance on record differs from what action "+merged.Name+" left") { + t.Fatalf("a reconcile over an outside change went without the review: %+v %+v", again.Action.Status.Approval, g) + } + requireLog(t, st, "governance_on_record_changed_outside", "installation=rowan", "action="+merged.Name) +} + +// S9-08: a governance merged between the plan and the pull requests is +// written over by them unseen; the commit reads the record again and asks +// the review. +func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, "governance: governed\n") } + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + if v, _ := st.ghs.file(acmeConfigs, marker); st.beforeOpen != nil || v != "governance: governed\n" { + t.Fatalf("the hook did not run: %q", v) + } + if out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision == actions.DecisionNotRequired || out.Action.Status.Approval.ReviewID == "" { + t.Fatalf("a commit whose record moved went without the review: %+v\n%s", out.Action.Status.Approval, st.logs.String()) + } + requireLog(t, st, "governance_record_moved", "installation=rowan") +} + // A commit on a test installation that leaves the governance as it is still // needs no review. func TestTestInstallationWithoutGovernanceChangeNeedsNoReview(t *testing.T) { - withGovernanceReleases(t) - st := newStack(t) - fixtures(st.ghs) - sopsFixtures(t, st.ghs) - rowanAsTestInstallation(t, st.ghs) - rowanOnLineFour(st.ghs) - seedRemote(t, st) + st := governedTestRowan(t) aliceC := st.mcpClient(t, aliceToken) out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}})}) if isErr || out.Action == nil || out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision != actions.DecisionNotRequired || len(out.Action.Spec.Governance) != 0 { @@ -139,7 +309,7 @@ func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing if a.Status.State != actions.StatePendingApproval || a.Status.Approval == nil || a.Status.Approval.ReviewID == "" || a.Status.Approval.Decision != "" { t.Fatalf("a loosening wave on a test installation went without the review: %s %+v", a.Status.State, a.Status.Approval) } - if g := a.Spec.Governance[rowan]; len(g.Loosens) != 1 || g.Loosens[0] != "mode governed → trusted (the chart's default)" { + if g := a.Spec.Governance[rowan]; len(g.Loosens) != 1 || g.Loosens[0] != "mode governed → trusted" { t.Fatalf("the wave's governance: %+v", a.Spec.Governance) } if posted := st.gateway.posted(); len(posted) != 1 || !strings.Contains(fmt.Sprint(posted[0].Body["text"]), "*It loosens governance:* rowan: mode governed → trusted") { @@ -149,3 +319,29 @@ func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing t.Fatalf("the actor's approve: %v %s", isErr, text) } } + +// S9-07: a pull request of a governance change merged outside the manager +// before the team decided is audited at the next read of the action, even +// when the rest of the stage is still open; it decides nothing. +func TestGovernanceMergedOutsideTheManagerIsAudited(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + var configs commit.PullRequest + for _, pr := range st.remote.PullRequests() { + if pr.Repository.String() == acmeConfigs { + configs = pr.PullRequest + } + } + if err := st.merge(t.Context(), st.remote, configs, alice); err != nil { + t.Fatal(err) + } + got := getAction(t, aliceC, out.Action.Name) + if got.Status.Approval != nil && got.Status.Approval.Decision != "" { + t.Fatalf("a merge outside the manager decided the governance change: %+v", got.Status.Approval) + } + requireLog(t, st, "governance_change_merged_without_approval", "action="+out.Action.Name, "pullRequests="+acmeConfigs) +} diff --git a/internal/e2e/identity_chain_test.go b/internal/e2e/identity_chain_test.go index c1f40921..7b33c02b 100644 --- a/internal/e2e/identity_chain_test.go +++ b/internal/e2e/identity_chain_test.go @@ -49,7 +49,12 @@ const ( aliceToken = "alice-token" bobToken = "bob-token" carol = "carol" - carolToken = "carol-token" + // governanceTeam is the GitHub team whose active members approve a + // governance change. + governanceTeam = "example/platform-reviewers" + // memberActive is an active team membership's state. + memberActive = "active" + carolToken = "carol-token" // stranger has authorized the App and has no account on the // installation. stranger = "stranger" @@ -94,6 +99,8 @@ type stack struct { // pulls are who merged or closed each pull request of the remote, and // when — what the fake GitHub answers for it. pulls map[string]pullFacts + // beforeOpen runs once, before the next pull request opens. + beforeOpen func() } // syncBuffer is a bytes.Buffer the server's log handler and the test share. @@ -127,6 +134,8 @@ func newStack(t *testing.T, options ...func(*tools.Deps)) *stack { dyn: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{actions.GVR: actions.Kind + "List"}), dex: newFakeDex(t), inst: newFakeInstallation(), pulls: map[string]pullFacts{}} st.ghs.pull = st.pullState + // carol reviews governance changes; alice, the actor of the tests, too. + st.ghs.teams[governanceTeam] = map[string]string{carol: memberActive, alice: memberActive} st.muster = newFakeMuster(t, st.inst, rowan) lc, err := live.New(live.Config{Issuer: st.dex.issuer, Audiences: []string{liveAudience, liveRequiredAudience}, JWKSURL: st.dex.issuer + "/keys", HTTPClient: st.dex.Client(), MusterURL: st.muster.URL + "/mcp", KubernetesFamily: kubernetesFamily, KubernetesInstanceArg: instanceArg, KubernetesMember: memberTemplate, Version: testVersion}, log) @@ -145,7 +154,7 @@ func newStack(t *testing.T, options ...func(*tools.Deps)) *stack { Remote: func(token string) (commit.Remote, error) { return asRemote{Remote: st.remote, login: logins[token], st: st}, nil }, - Approvals: approvals.Config{GatewayURL: st.gateway.URL, Team: reviewTeam, Channel: reviewChannel, NoticeChannel: noticeChannel, StandupChannel: standupChannel, TokenFile: tokenFile}, + Approvals: approvals.Config{GatewayURL: st.gateway.URL, Team: reviewTeam, Channel: reviewChannel, NoticeChannel: noticeChannel, StandupChannel: standupChannel, GovernanceTeam: governanceTeam, TokenFile: tokenFile}, Registry: registrySources} for _, option := range options { option(&dependencies) diff --git a/internal/tools/approval.go b/internal/tools/approval.go index cd1d1649..36608ec7 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -137,11 +137,22 @@ func (t *Tools) approve(ctx context.Context, args map[string]any) (any, error) { if noReview(a) { return nil, fmt.Errorf("%s: action %s targets test installations alone and needs no review: %s merges it with %s", ToolApproveAction, a.Name, a.Spec.Actor.Login, ToolMergeAction) } - if id.Login == a.Spec.Actor.Login { + // The actor by login, and by GitHub's id where both are known: a login + // can be renamed, the id stays. + if id.Login == a.Spec.Actor.Login || (id.ID != 0 && id.ID == a.Spec.Actor.ID) { t.d.Log.Info("action_approval_actor_refused", identity.LogAttr(ctx), "action", a.Name) t.auditGovernance(ctx, "governance_change_self_approval_refused", a) return nil, fmt.Errorf("%s: action %s is yours (%s): a second person of the team decides; Deny withdraws it", ToolApproveAction, a.Name, id.Login) } + membership := "" + if len(a.Spec.Governance) > 0 { + m, err := t.governanceReviewer(ctx, id) + if err != nil { + t.auditGovernance(ctx, "governance_change_approval_refused", a, "approver", id.Login, "reason", err.Error()) + return nil, err + } + membership = m + } if a.Status.Approval != nil && a.Status.Approval.Decision != "" { return nil, fmt.Errorf("%s: action %s is already %s by %s", ToolApproveAction, a.Name, a.Status.Approval.Decision, a.Status.Approval.DecidedBy) } @@ -172,7 +183,7 @@ func (t *Tools) approve(ctx context.Context, args map[string]any) (any, error) { return nil, fmt.Errorf("%s: the approving reviews are submitted and the action could not record the decision: %w", ToolApproveAction, err) } t.d.Log.Info("action_approved", identity.LogAttr(ctx), "action", a.Name, "pullRequests", len(a.Status.PullRequests)) - t.auditGovernance(ctx, "governance_change_approved", a) + t.auditGovernance(ctx, "governance_change_approved", a, "approver", id.Login, "approverId", id.ID, "membership", membership) return Decision{Action: a, Message: fmt.Sprintf("%s approved action %s: approving reviews submitted on %d pull request(s) (%s); %s merges them as the actor with %s once the checks are green.", id.Login, a.Name, len(a.Status.PullRequests), prList(a.Status.PullRequests), a.Spec.Actor.Login, ToolMergeAction)}, nil } @@ -358,7 +369,7 @@ func (t *Tools) merge(ctx context.Context, args map[string]any) (any, error) { res.Action = a t.d.Log.Info("action_merge", identity.LogAttr(ctx), "action", a.Name, "state", a.Status.State, "merged", len(res.Merged), "waiting", res.Waiting, "stage", res.Stage) if len(res.Merged) > 0 { - t.auditGovernance(ctx, "governance_change_merged", a) + t.auditGovernanceStage(ctx, "governance_change_merged", a, mergedStage(a, res.Merged), res.Merged) } if res.Waiting != "" { res.Message = fmt.Sprintf("%d pull request(s) merged as %s (%s); the merge stopped at %s — call %s again once it is green.", len(res.Merged), id.Login, prList(res.Merged), res.Waiting, ToolMergeAction) @@ -377,18 +388,39 @@ func (t *Tools) merge(ctx context.Context, args map[string]any) (any, error) { return res, nil } +// mergedStage is the installation whose stage the merged pull requests +// belong to. +func mergedStage(a *actions.Action, merged []actions.PullRequest) string { + for _, n := range a.Spec.Installations { + for _, k := range a.StagePullRequests(n) { + pr := a.Status.PullRequests[k] + for _, m := range merged { + if m.Repository == pr.Repository && m.Number == pr.Number { + return n + } + } + } + } + return "" +} + // decided says whether the action's merge may go ahead: the team approved // it, it needs no review (test installations alone), or every pull request // of its stage in flight was merged outside the manager already — the // repositories' own merge path let it through, and the manager does not // second-guess it for the stages that follow. +// +// A governance change is decided by the team's approval alone: a stage +// merged outside the manager does not carry the stages after it. func decided(a *actions.Action) bool { if a.Status.Approval == nil { return false } switch a.Status.Approval.Decision { - case actions.DecisionApproved, actions.DecisionMergedWithoutApproval, actions.DecisionNotRequired: + case actions.DecisionApproved, actions.DecisionNotRequired: return true + case actions.DecisionMergedWithoutApproval: + return len(a.Spec.Governance) == 0 } return false } diff --git a/internal/tools/capability.go b/internal/tools/capability.go index cea3b3cc..50b20016 100644 --- a/internal/tools/capability.go +++ b/internal/tools/capability.go @@ -333,6 +333,12 @@ func (t *Tools) capabilityPlan(ctx context.Context, tool string, args map[string if (slices.Contains(changed, e.Name) || len(e.VaultCopies) > 0) && e.Refused == "" && len(e.MissingInputs) == 0 { e.CommitRefused = commitRefusal(e.Installation, env.reports[e.Name].Record) } + // The governance a commit of the plan changes, against what the last + // reviewed action left: the dry run names it, and a record changed + // outside the manager, before anyone commits. + if content && e.Refused == "" && env.defOf(e.Name, def).Name == installations.AgentPlatform { + e.Governance, _ = t.governanceChange(ctx, e.Installation) + } } if unknown := unknownRotations(rotate, out.Installations); len(unknown) > 0 { where := "no plan of the set lists" diff --git a/internal/tools/commit.go b/internal/tools/commit.go index 8aaaa58b..dca78b5e 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -152,14 +152,23 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri if len(p.MissingInputs) > 0 { return nil, fmt.Errorf("%s: %s: %s; nothing is committed", tool, one, missingInputs(p.MissingInputs)) } - spec.Change = changeSummary(p) - spec.Changes = map[string][]string{one: plan.Summary(p)} - if g, ok := plan.GovernanceOf(p); ok { + // The plan carries the governance it changes (capabilityPlan, against + // what the last reviewed action left). + g, after := p.Governance, governanceAfter(p) + if after != "" { + spec.GovernanceAfter = map[string]string{one: after} + } + if g != nil { // One person never changes the governance alone: the Team review, // on a test installation too. - spec.Governance = map[string]plan.GovernanceChange{one: g} + spec.Governance = map[string]plan.GovernanceChange{one: *g} test = false + if err := governanceTooLarge(tool, &actions.Action{Spec: spec}); err != nil { + return nil, err + } } + spec.Change = changeSummary(p) + spec.Changes = map[string][]string{one: plan.Summary(p)} spec.KeptByInstallation = keptByInstallation(nil, p) if n := p.Diff[plan.ChangeUnknown]; n > 0 { return nil, fmt.Errorf("%s: %d file(s) of %s could not be compared against the repository as you (%s); nothing is committed blind", tool, n, one, unknownFiles(p)) @@ -186,6 +195,9 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri res := CommitResult{Caller: identity.Caller(ctx), Tool: tool, Capability: out.Capability, Hub: out.Hub, Installation: one, Plan: p, PullRequests: []actions.PullRequest{}} if len(p.Files)-p.Diff[plan.ChangeUnchanged] == 0 { res.Next = "every file is on record as the definition renders it: nothing to commit, no action recorded" + if g != nil { + res.Next += "; the governance on record is not what the last reviewed action left (" + strings.Join(g.Lines, "; ") + "): a reviewed change that types the governance confirms or reverts it" + } return res, nil } @@ -193,6 +205,9 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri if err != nil { return nil, fmt.Errorf("%s: %w", tool, err) } + if err := governanceStored(tool, spec.Governance, a); err != nil { + return nil, t.fail(ctx, tool, a, nil, nil, err) + } remote, err := t.d.Remote(token) if err != nil { return nil, t.fail(ctx, tool, a, nil, nil, err) @@ -207,6 +222,15 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "installation", one, "state", a.Status.State, "pullRequests", len(prs)) + if test { + // The plan read the record moments ago and the branch was cut from + // the default branch since: a governance merged in between would be + // written over without anyone seeing it, so it asks the review. + if moved, what := t.governanceRecordMoved(ctx, p); moved { + t.d.Log.Warn("governance_record_moved", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", one, "governance", what) + test = false + } + } t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) if err != nil { diff --git a/internal/tools/disable.go b/internal/tools/disable.go index 6264b7e1..ef823240 100644 --- a/internal/tools/disable.go +++ b/internal/tools/disable.go @@ -401,6 +401,16 @@ func (t *Tools) disableCommit(ctx context.Context, args map[string]any) (any, er def, _ := installations.FindCapability(out.Capability) one := out.Installation test := installations.TestInstallation(one, env.byName[one].Customer, env.hub) + // Deleting governed values takes the governance away with the platform: + // a second person approves it, and the governance before the disable is + // what a later enable is compared with. + governance, after, err := t.governanceOfDisable(ctx, env.c, out.Plan) + if err != nil { + return nil, fmt.Errorf("%s: %w; nothing is committed", tool, err) + } + if governance != nil { + test = false + } if err := t.standupRefusal(tool, test); err != nil { return nil, err } @@ -408,10 +418,23 @@ func (t *Tools) disableCommit(ctx context.Context, args map[string]any) (any, er spec := actions.Spec{Actor: actions.Actor{Login: id.Login, ID: id.ID, Email: id.Email}, Capability: out.Capability, Installations: []string{one}, Inputs: env.inputs[one], Kind: actions.KindDisable, InputsByInstallation: map[string]map[string]any{one: env.inputs[one]}, Customer: env.byName[one].Customer != env.hub.Customer, AccountEngineers: accountEngineers(env, one), AccountEngineerOf: accountEngineerOf(env, one), Reason: reason, Markers: markersOf(def, env, one), Change: fmt.Sprintf("%d file(s) to delete, %d to update", deleted, updated), Changes: map[string][]string{one: disableSummary(out.Plan)}} + if after != "" { + spec.GovernanceAfter = map[string]string{one: after} + } + if governance != nil { + spec.Governance = map[string]plan.GovernanceChange{one: *governance} + spec.Changes[one] = append([]string{governance.Summary()}, spec.Changes[one]...) + if err := governanceTooLarge(tool, &actions.Action{Spec: spec}); err != nil { + return nil, err + } + } a, err := t.record(ctx, spec, actions.Status{State: actions.StatePendingApproval, Orphans: orphansFrom(one, out.Plan.Checklist), Commit: &actions.CommitStatus{}}) if err != nil { return nil, fmt.Errorf("%s: %w", tool, err) } + if err := governanceStored(tool, spec.Governance, a); err != nil { + return nil, t.fail(ctx, tool, a, nil, nil, err) + } remote, err := t.d.Remote(token) if err != nil { return nil, t.fail(ctx, tool, a, nil, nil, err) @@ -424,6 +447,7 @@ func (t *Tools) disableCommit(ctx context.Context, args map[string]any) (any, er return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "installation", one, "state", a.Status.State, "pullRequests", len(prs)) + t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) if err != nil { return nil, fmt.Errorf("%w — the pull requests are open (%s) and the action pends approval; %s posts the review", err, prList(prs), ToolMergeAction) diff --git a/internal/tools/governance.go b/internal/tools/governance.go index 7c33f00c..a4beea2c 100644 --- a/internal/tools/governance.go +++ b/internal/tools/governance.go @@ -2,49 +2,315 @@ package tools import ( "context" + "errors" + "fmt" "maps" "slices" "strings" + "unicode/utf8" "github.com/giantswarm/giantswarm-platform-manager/internal/actions" + "github.com/giantswarm/giantswarm-platform-manager/internal/gh" "github.com/giantswarm/giantswarm-platform-manager/internal/identity" + "github.com/giantswarm/giantswarm-platform-manager/internal/installations" + "github.com/giantswarm/giantswarm-platform-manager/internal/plan" ) // Governing tool calls (giantswarm/giantswarm#38902): one person never // changes an installation's governance alone. A commit whose plan changes -// the governance (plan.GovernanceOf) records the change on the Action +// the governance (governanceChange) records the change on the Action // (spec.governance) and asks the team's review even where every target is a -// test installation; approve_action refuses the actor as for any action, so -// a second person of the team decides, and merge_action waits for that -// decision. Each step is audited (auditGovernance). Agents may propose such -// a change and never approve or merge it: muster asks a person before an +// test installation; approve_action refuses the actor and anyone who is not +// an active member of the governance reviewers' team (approvals.governanceTeam), +// and merge_action waits for that decision. Every Action records the +// governance its commit leaves (spec.governanceAfter): the next plan compares +// against it, so a disable followed by an enable, or a change made in the +// configs repository directly, is a governance change again and needs the +// review. Each step is audited (auditGovernance). Agents may propose such a +// change and never approve or merge it: muster asks a person before an // agent's approve_action and merge_action (a floor of the platformManager // role). -// governanceText is the review's governance block: that the action changes -// the governance and a second person approves it, each installation's -// change old → new, and what loosens it, so the approver reads it before -// anything else. Empty for an action that changes none. +// baselineStates are the states of an Action whose stage is on record: its +// pull requests merged, not taken back. +var baselineStates = []string{actions.StateRollingOut, actions.StateWaitingForCustomer, actions.StateEnabled, actions.StateDrifted, actions.StateDisabled, actions.StateFailed} + +// governanceBaseline is the governance the newest reviewed action left on +// installation: an agent-platform action whose stage there is merged and on +// record, approved by the team or needing no review, with a recorded +// governance. An action merged without the team's decision is skipped, so +// what it left counts as changed outside the manager. None (false) before +// the first action that records one, or without the records. +func (t *Tools) governanceBaseline(ctx context.Context, installation string) (plan.GovernanceSnapshot, string, bool) { + if t.d.Actions == nil { + return nil, "", false + } + list, err := t.d.Actions.List(ctx, actions.Filter{Installation: installation}) + if err != nil { + t.d.Log.Warn("governance_baseline_unread", identity.LogAttr(ctx), "installation", installation, "error", err.Error()) + return nil, "", false + } + for _, a := range list { + if a.CapabilityOf(installation) != installations.AgentPlatform || !slices.Contains(baselineStates, a.Status.State) || !allMerged(&a, installation) || len(a.StagePullRequests(installation)) == 0 { + continue + } + if a.Status.Approval == nil || (a.Status.Approval.Decision != actions.DecisionApproved && a.Status.Approval.Decision != actions.DecisionNotRequired) { + continue + } + raw, ok := a.Spec.GovernanceAfter[installation] + if !ok { + return nil, "", false + } + snap, err := plan.ParseGovernanceSnapshot(raw) + if err != nil { + return nil, "", false + } + return snap, a.Name, true + } + return nil, "", false +} + +// governanceOutside is the line of a plan whose record differs from what +// the last reviewed action left: the change is shown against that action. +func governanceOutside(action string) string { + return "the governance on record differs from what action " + action + " left (changed outside the manager); the change is shown against " + action +} + +// governanceChange is the governance a commit of p changes, against what +// the last reviewed action left where it is known, else against the record, +// and the snapshot the commit leaves; nil for a plan that changes none or +// writes no agent-platform values. A record that differs from the last +// reviewed action's is logged (governance_on_record_changed_outside) and +// shown, as a loosening line, ahead of the change. +func (t *Tools) governanceChange(ctx context.Context, p plan.Installation) (*plan.GovernanceChange, string) { + current, next, ok, unreadable := plan.GovernanceFile(p) + if !ok { + return nil, "" + } + if unreadable { + g := plan.GovernanceUnreadable() + return &g, "" + } + g := plan.GovernanceBetween(current, next) + if base, from, has := t.governanceBaseline(ctx, p.Name); has { + if outside := plan.GovernanceBetween(base, current); len(outside.Lines) > 0 { + t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", p.Name, "action", from, "governance", strings.Join(outside.Lines, "; ")) + g = plan.GovernanceBetween(base, next) + line := governanceOutside(from) + g.Lines = append([]string{line}, g.Lines...) + g.Loosens = append([]string{line}, g.Loosens...) + } + } + if len(g.Lines) == 0 { + return nil, next.JSON() + } + return &g, next.JSON() +} + +// governanceAfter is the snapshot a commit of p leaves: the agent-platform +// values it writes; empty where it writes none or they cannot be read. +func governanceAfter(p plan.Installation) string { + _, next, ok, unreadable := plan.GovernanceFile(p) + if !ok || unreadable { + return "" + } + return next.JSON() +} + +// governanceOfDisable is the governance a disable removes with the values: +// what the record carries (against the last reviewed action's where they +// differ), and the snapshot the disable records as what it leaves — the +// governance before it, so a later enable is compared with that. +func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Disablement) (*plan.GovernanceChange, string, error) { + for _, f := range d.Files { + if f.Change != plan.ChangeDelete || !strings.HasSuffix(f.Path, "/apps/agent-platform/configmap-values.yaml.patch") { + continue + } + owner, repo, err := gh.SplitRepo(f.Repository) + if err != nil { + return nil, "", err + } + content, err := gh.ReadFile(ctx, c, owner, repo, f.Path) + if err != nil { + return nil, "", fmt.Errorf("the agent-platform values on record could not be read as you to see the governance they carry: %w", err) + } + current, err := plan.GovernanceSnapshotOf(content) + if err != nil { + g := plan.GovernanceUnreadable() + return &g, "", nil + } + old, outside := current, "" + if base, from, has := t.governanceBaseline(ctx, d.Name); has && len(plan.GovernanceBetween(base, current).Lines) > 0 { + t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", d.Name, "action", from) + old, outside = base, governanceOutside(from) + } + g, changes := plan.GovernanceDeleted(old) + if outside != "" { + g.Lines = append([]string{outside}, g.Lines...) + g.Loosens = append([]string{outside}, g.Loosens...) + changes = true + } + if !changes { + return nil, old.JSON(), nil + } + return &g, old.JSON(), nil + } + return nil, "", nil +} + +// governanceRecordMoved says whether the agent-platform values on the +// default branch carry another governance than p read (someone merged one +// between the plan and the branch): read again past the cache, as the +// caller with a client of its own (a call's client keeps the tree it read +// for the plan). An error counts as moved (fail closed). +func (t *Tools) governanceRecordMoved(ctx context.Context, p plan.Installation) (bool, string) { + token, _ := identity.TokenFromContext(ctx) + c, err := t.person(token) + if err != nil { + return true, err.Error() + } + for _, f := range p.Files { + if !strings.HasSuffix(f.Path, "/apps/agent-platform/configmap-values.yaml.patch") || (f.Change != plan.ChangeCreate && f.Change != plan.ChangeUpdate) { + continue + } + read, err := plan.GovernanceSnapshotOf(f.Current) + if err != nil { + return true, "the values the plan read do not parse" + } + owner, repo, err := gh.SplitRepo(f.Repository) + if err != nil { + return true, err.Error() + } + t.d.Files.Invalidate(f.Repository) + now, err := gh.ReadFile(ctx, c, owner, repo, f.Path) + switch { + case errors.Is(err, gh.ErrNotFound) && f.Change == plan.ChangeCreate: + return false, "" + case err != nil: + return true, "the values on the default branch could not be read again: " + err.Error() + } + snap, err := plan.GovernanceSnapshotOf(now) + if err != nil { + return true, "the values on the default branch do not parse" + } + if moved := plan.GovernanceBetween(read, snap); len(moved.Lines) > 0 { + return true, strings.Join(moved.Lines, "; ") + } + } + return false, "" +} + +// governanceReviewer refuses an approver of a governance change who is not +// an active member of the governance reviewers' team (approvals.governanceTeam, +// org/team), or not a person (a GitHub account of type User), read as the +// approver: fail closed when the team is unset or the membership cannot be +// read. It answers how the membership was established, for the audit line. +func (t *Tools) governanceReviewer(ctx context.Context, id *identity.Identity) (string, error) { + team := "" + if t.approvals != nil { + team = t.approvals.Config().GovernanceTeam + } + org, slug, ok := strings.Cut(team, "/") + if !ok || org == "" || slug == "" { + return "", fmt.Errorf("%s: the action changes the platform's governance, and no governance reviewers' team is configured (chart approvals.governanceTeam, org/team): nobody can approve it", ToolApproveAction) + } + token, _ := identity.TokenFromContext(ctx) + c, err := t.person(token) + if err != nil { + return "", fmt.Errorf("%s: %w", ToolApproveAction, err) + } + m, _, err := c.Teams.GetTeamMembershipBySlug(ctx, org, slug, id.Login) + if err != nil { + return "", fmt.Errorf("%s: the action changes the platform's governance, which a member of %s approves, and your membership could not be read as you (%v): nothing is approved", ToolApproveAction, team, err) + } + if m.GetState() != "active" { + return "", fmt.Errorf("%s: the action changes the platform's governance, which an active member of %s approves, and %s is %q there", ToolApproveAction, team, id.Login, m.GetState()) + } + u, _, err := c.Users.Get(ctx, id.Login) + if err != nil { + return "", fmt.Errorf("%s: %s could not be read as you (%v): nothing is approved", ToolApproveAction, id.Login, err) + } + if u.GetType() != "User" { + return "", fmt.Errorf("%s: the action changes the platform's governance, which a person approves, and %s is a GitHub %s", ToolApproveAction, id.Login, u.GetType()) + } + return "active member of " + team + ", read as the approver", nil +} + +// governanceReviewMax bounds the review's governance block: Slack shows a +// section of 3000 characters, and the header, the reason and what changes +// follow. governanceLoosensMax bounds its first part, what loosens, which is +// never cut: a commit whose loosening lines do not fit is refused. +const ( + governanceReviewMax = 1400 + governanceLoosensMax = 1000 +) + +// governanceLoosens is the review's loosening part of a: per installation +// the lines that loosen, in full. +func governanceLoosens(a *actions.Action) string { + var loosens []string + for _, n := range governedInstallations(a) { + if g := a.Spec.Governance[n]; len(g.Loosens) > 0 { + loosens = append(loosens, n+": "+strings.Join(g.Loosens, "; ")) + } + } + if len(loosens) == 0 { + return "" + } + return "\n*It loosens governance:* " + strings.Join(loosens, " — ") +} + +// governanceTooLarge refuses a governance change whose loosening lines do +// not fit the review: they are never cut, so the change is split. +func governanceTooLarge(tool string, a *actions.Action) error { + if n := utf8.RuneCountInString(governanceLoosens(a)); n > governanceLoosensMax { + return fmt.Errorf("%s: what the change loosens in the platform's governance reads %d characters, more than the review shows in full (%d): split it into smaller changes; nothing is committed", tool, n, governanceLoosensMax) + } + return nil +} + +// governanceText is the review's governance block, first after the header: +// that the action changes the governance and a second person approves it, +// what loosens it (never cut), then each installation's change old → new, +// cut at governanceReviewMax with the configs pull request named for the +// rest. Empty for an action that changes none. func governanceText(a *actions.Action) string { if len(a.Spec.Governance) == 0 { return "" } var b strings.Builder b.WriteString("\n*Governance:* this changes the platform's governance; a second person approves it, on test installations too.") - var loosens []string + b.WriteString(governanceLoosens(a)) + cut := 0 for _, n := range governedInstallations(a) { - g := a.Spec.Governance[n] - b.WriteString("\n• " + n + ": " + strings.Join(g.Lines, "; ")) - if len(g.Loosens) > 0 { - loosens = append(loosens, n+": "+strings.Join(g.Loosens, "; ")) + line := "\n• " + n + ": " + strings.Join(a.Spec.Governance[n].Lines, "; ") + if utf8.RuneCountInString(b.String())+utf8.RuneCountInString(line) > governanceReviewMax { + cut++ + continue } + b.WriteString(line) } - if len(loosens) > 0 { - b.WriteString("\n*It loosens governance:* " + strings.Join(loosens, " — ")) + if cut > 0 { + fmt.Fprintf(&b, "\n• … the change on %d more installation(s) is in full in the configs pull request%s", cut, configsLinks(a)) } return b.String() } +// configsLinks names the action's configs pull requests, which carry the +// agent-platform values in full. +func configsLinks(a *actions.Action) string { + var links []string + for _, pr := range a.Status.PullRequests { + if strings.HasSuffix(pr.Repository, "-configs") { + links = append(links, fmt.Sprintf("<%s|%s#%d>", pr.URL, pr.Repository, pr.Number)) + } + } + if len(links) == 0 { + return "" + } + return ": " + strings.Join(links, ", ") +} + // governedInstallations are the installations whose governance a changes, // in the action's order, then any other on record by name. func governedInstallations(a *actions.Action) []string { @@ -64,16 +330,46 @@ func governedInstallations(a *actions.Action) []string { // auditGovernance logs event once per installation whose governance a // changes: the action, the actor, the caller, who decided where someone -// did, the change and whether it loosens. Nothing for an action that -// changes none. -func (t *Tools) auditGovernance(ctx context.Context, event string, a *actions.Action) { +// did, the change and whether it loosens, and extra attributes. Nothing for +// an action that changes none. +func (t *Tools) auditGovernance(ctx context.Context, event string, a *actions.Action, extra ...any) { decidedBy, decision := "", "" if a.Status.Approval != nil { decidedBy, decision = a.Status.Approval.DecidedBy, a.Status.Approval.Decision } for _, n := range governedInstallations(a) { g := a.Spec.Governance[n] - t.d.Log.Info(event, identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", n, "actor", a.Spec.Actor.Login, - "decision", decision, "decidedBy", decidedBy, "governance", strings.Join(g.Lines, "; "), "loosens", len(g.Loosens) > 0) + args := []any{identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", n, "actor", a.Spec.Actor.Login, + "decision", decision, "decidedBy", decidedBy, "governance", strings.Join(g.Lines, "; "), "loosens", len(g.Loosens) > 0} + t.d.Log.Info(event, append(args, extra...)...) + } +} + +// auditGovernanceStage logs event for one installation of a, with the pull +// requests of its stage and their heads: a merge is audited per stage. +func (t *Tools) auditGovernanceStage(ctx context.Context, event string, a *actions.Action, installation string, prs []actions.PullRequest) { + g, ok := a.Spec.Governance[installation] + if !ok { + return + } + refs := make([]string, 0, len(prs)) + for _, pr := range prs { + refs = append(refs, fmt.Sprintf("%s#%d@%s", pr.Repository, pr.Number, pr.HeadSHA)) + } + decidedBy, decision := "", "" + if a.Status.Approval != nil { + decidedBy, decision = a.Status.Approval.DecidedBy, a.Status.Approval.Decision + } + t.d.Log.Info(event, identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "actor", a.Spec.Actor.Login, + "decision", decision, "decidedBy", decidedBy, "pullRequests", strings.Join(refs, ","), "governance", strings.Join(g.Lines, "; "), "loosens", len(g.Loosens) > 0) +} + +// governanceStored refuses an Action the hub stored without the governance +// it was created with: a CRD older than spec.governance prunes the field, +// and the review would then show no change and nothing would be audited. +func governanceStored(tool string, want map[string]plan.GovernanceChange, a *actions.Action) error { + if len(want) > 0 && len(a.Spec.Governance) != len(want) { + return fmt.Errorf("%s: action %s was stored without the governance it changes (the hub's Action CRD lacks spec.governance; upgrade the manager's chart): nothing is committed", tool, a.Name) } + return nil } diff --git a/internal/tools/governance_test.go b/internal/tools/governance_test.go index 3466e1b6..7a0fe40f 100644 --- a/internal/tools/governance_test.go +++ b/internal/tools/governance_test.go @@ -3,6 +3,7 @@ package tools import ( "bytes" "context" + "fmt" "log/slog" "strings" "testing" @@ -23,18 +24,15 @@ func governedAction() *actions.Action { } // The review of an action that changes the governance says so first, that a -// second person approves it, the change old → new and what loosens it; one -// that changes none says nothing of it. +// second person approves it, then what loosens it and only then the change +// old → new; one that changes none says nothing of it. func TestReviewTextLeadsWithTheGovernance(t *testing.T) { text := reviewText(governedAction()) - for _, want := range []string{ - "\n*Governance:* this changes the platform's governance; a second person approves it, on test installations too.", - "\n• garm: mode trusted (the chart's default) → governed; governedServers.mcp-kubernetes the chart's entry → null (not governed)", - "\n*It loosens governance:* garm: governedServers.mcp-kubernetes the chart's entry → null (not governed)", - } { - if !strings.Contains(text, want) { - t.Fatalf("the review carries no %q:\n%s", want, text) - } + head := "\n*Governance:* this changes the platform's governance; a second person approves it, on test installations too." + + "\n*It loosens governance:* garm: governedServers.mcp-kubernetes the chart's entry → null (not governed)" + + "\n• garm: mode trusted (the chart's default) → governed; governedServers.mcp-kubernetes the chart's entry → null (not governed)" + if !strings.Contains(text, head) { + t.Fatalf("the review carries no %q:\n%s", head, text) } if text := reviewText(&actions.Action{Spec: actions.Spec{Kind: actions.KindReconcile, Capability: installations.AgentPlatform, Installations: []string{rtGarm}}}); strings.Contains(text, "Governance") { t.Fatalf("a review without a governance change names it:\n%s", text) @@ -62,3 +60,70 @@ func TestGovernanceChangeIsAudited(t *testing.T) { t.Fatalf("an action without a governance change is audited: %s", buf.String()) } } + +// S9-03: what loosens comes first and is never cut, within what Slack shows +// of a section, however long the rest of the change; the rest is cut with +// the configs pull request named. A change whose loosening lines alone do +// not fit is refused. +func TestReviewTextKeepsWhatLoosensWhole(t *testing.T) { + var pad []string + for i := range 130 { + pad = append(pad, fmt.Sprintf("list_inventory_items_%03d", i)) + } + current := "governance: governed\ngovernedServers:\n agent-manager:\n safe: [get_info]\n" + next := "governance: governed\ngovernedServers:\n a-inventory:\n role: infrastructure\n safe: [" + strings.Join(pad, ", ") + "]\n agent-manager:\n safe: [get_info, create_agent, update_agent_access]\n" + p := plan.Installation{Name: rowan, Files: []plan.File{{Path: "installations/rowan/apps/agent-platform/configmap-values.yaml.patch", Change: plan.ChangeUpdate, Current: current, Content: next}}} + g, ok := plan.GovernanceOf(p) + if !ok { + t.Fatal("no change") + } + a := &actions.Action{Spec: actions.Spec{Actor: actions.Actor{Login: stAlice}, Kind: actions.KindReconcile, Capability: installations.AgentPlatform, Installations: []string{rowan}, Reason: "inventory server", + Governance: map[string]plan.GovernanceChange{rowan: g}, Changes: map[string][]string{rowan: plan.Summary(p)}}, + Status: actions.Status{PullRequests: []actions.PullRequest{{Repository: "giantswarm/acme-configs", Number: 7, URL: "https://github.com/giantswarm/acme-configs/pull/7"}}}} + text := []rune("*Review for team*\n" + reviewText(a)) + shown := string(text[:min(len(text), 3000)]) + for _, want := range []string{"*It loosens governance:* rowan: governedServers.agent-manager.safe +create_agent (named like a write) +update_agent_access (named like a write)", "in full in the configs pull request: "} { + if !strings.Contains(shown, want) { + t.Fatalf("what Slack shows carries no %q:\n%s", want, shown) + } + } + if err := governanceTooLarge(ToolReconcileCapability, a); err != nil { + t.Fatalf("a change whose loosening lines fit: %v", err) + } + big := plan.GovernanceChange{Lines: []string{"x"}} + for i := range 60 { + big.Loosens = append(big.Loosens, fmt.Sprintf("governedServers.s%02d.safe +list_items", i)) + } + if err := governanceTooLarge(ToolReconcileCapability, &actions.Action{Spec: actions.Spec{Governance: map[string]plan.GovernanceChange{rowan: big}}}); err == nil || !strings.Contains(err.Error(), "split it") { + t.Fatalf("a change whose loosening lines do not fit: %v", err) + } +} + +// S9-07: a stage merged outside the manager decides nothing for a +// governance change; for any other change it carries the stages after it. +func TestMergedWithoutApprovalDecidesNoGovernanceChange(t *testing.T) { + a := governedAction() + a.Status.Approval = &actions.Approval{Decision: actions.DecisionMergedWithoutApproval} + if decided(a) { + t.Fatal("a governance change merged outside the manager counts as decided") + } + a.Spec.Governance = nil + if !decided(a) { + t.Fatal("a change merged outside the manager no longer carries its later stages") + } +} + +// S9-15: an Action the hub stored without the governance it was created +// with is refused. +func TestGovernanceStoredOrRefused(t *testing.T) { + want := governedAction().Spec.Governance + if err := governanceStored(ToolEnableCapability, want, &actions.Action{}); err == nil || !strings.Contains(err.Error(), "lacks spec.governance") { + t.Fatalf("an action stored without its governance: %v", err) + } + if err := governanceStored(ToolEnableCapability, want, governedAction()); err != nil { + t.Fatal(err) + } + if err := governanceStored(ToolEnableCapability, nil, &actions.Action{}); err != nil { + t.Fatal(err) + } +} diff --git a/internal/tools/resync.go b/internal/tools/resync.go index 5a6565a2..32c73aad 100644 --- a/internal/tools/resync.go +++ b/internal/tools/resync.go @@ -171,6 +171,13 @@ func (t *Tools) resync(ctx context.Context, c *gh.Client, id *identity.Identity, // states as GitHub has them now. fresh := *a fresh.Status = status + // A pull request of a governance change merged outside merge_action + // without the team's approval, in any state of the action, whoever + // merged it: the repositories' merge path let it through, and only their + // branch protection stood between one person and the change. + if len(merged) > 0 && len(a.Spec.Governance) > 0 && (status.Approval == nil || status.Approval.Decision != actions.DecisionApproved) { + t.auditGovernanceStage(ctx, "governance_change_merged_without_approval", &fresh, mergedStage(&fresh, merged), merged) + } var posts []string // told is the stage an action that needs no review started outside // merge_action: the standup channel hears of it as of a merge. @@ -209,13 +216,6 @@ func (t *Tools) resync(ctx context.Context, c *gh.Client, id *identity.Identity, approval := *approvalOf(&status) approval.Decision, approval.DecidedBy, approval.At = actions.DecisionMergedWithoutApproval, by, now() status.Approval = &approval - // The repositories' merge path let a governance change - // through without the team's decision: audited apart, since - // only their branch protection stood between one person - // and the change. - merged := fresh - merged.Status = status - t.auditGovernance(ctx, "governance_change_merged_without_approval", &merged) } posts = append(posts, fmt.Sprintf("Merged outside the manager by %s: %s. *%s* is rolling out — the rollout and the probes follow here.", by, prLinks(stagePRs(status.PullRequests, idx)), st.Name)) if noReview(&fresh) { diff --git a/internal/tools/server.go b/internal/tools/server.go index 0e94a60e..0602749b 100644 --- a/internal/tools/server.go +++ b/internal/tools/server.go @@ -282,6 +282,7 @@ type ApprovalsInfo struct { Channel string `json:"channel,omitempty"` NoticeChannel string `json:"noticeChannel,omitempty"` StandupChannel string `json:"standupChannel,omitempty"` + GovernanceTeam string `json:"governanceTeam,omitempty"` } func (t *Tools) getInfo(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) { @@ -299,7 +300,7 @@ func (t *Tools) getInfo(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallTo GitHub: GitHubInfo{APIURL: apiURL(t.d.GitHubAPIURL)}, Definitions: defs, Capabilities: Capabilities{Commit: true, Modes: []string{string(ModeCommit)}, ApplyRefused: true, WriteTools: names}, - Approvals: ApprovalsInfo{Configured: t.d.Approvals.Configured(), GatewayURL: t.d.Approvals.GatewayURL, Team: t.d.Approvals.Team, Channel: t.d.Approvals.Channel, NoticeChannel: t.d.Approvals.NoticeChannel, StandupChannel: t.d.Approvals.StandupChannel}, + Approvals: ApprovalsInfo{Configured: t.d.Approvals.Configured(), GatewayURL: t.d.Approvals.GatewayURL, Team: t.d.Approvals.Team, Channel: t.d.Approvals.Channel, NoticeChannel: t.d.Approvals.NoticeChannel, StandupChannel: t.d.Approvals.StandupChannel, GovernanceTeam: t.d.Approvals.GovernanceTeam}, Registry: RegistryConfig{Catalog: t.d.Registry.Catalog, Hub: t.d.Registry.Hub, Configured: t.d.Registry.Hub != ""}, Actions: t.actionsInfo(), Live: t.liveInfo(ctx), diff --git a/internal/tools/wave.go b/internal/tools/wave.go index 558d32c1..78809ce1 100644 --- a/internal/tools/wave.go +++ b/internal/tools/wave.go @@ -111,17 +111,28 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string } } governs := false - for _, p := range targets { + for i := range targets { + p := &targets[i] spec.InputsByInstallation[p.Name] = p.Inputs - spec.Changes[p.Name] = plan.Summary(p) - spec.KeptByInstallation = keptByInstallation(spec.KeptByInstallation, p) - if g, ok := plan.GovernanceOf(p); ok { + g, after := p.Governance, governanceAfter(*p) + if after != "" { + if spec.GovernanceAfter == nil { + spec.GovernanceAfter = map[string]string{} + } + spec.GovernanceAfter[p.Name] = after + } + if g != nil { if spec.Governance == nil { spec.Governance = map[string]plan.GovernanceChange{} } - spec.Governance[p.Name] = g + spec.Governance[p.Name] = *g governs = true } + spec.Changes[p.Name] = plan.Summary(*p) + spec.KeptByInstallation = keptByInstallation(spec.KeptByInstallation, *p) + } + if err := governanceTooLarge(tool, &actions.Action{Spec: spec}); err != nil { + return nil, err } changes := make([]string, 0, len(targets)) var rotated []string @@ -153,6 +164,9 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string if err != nil { return nil, fmt.Errorf("%s: %w", tool, err) } + if err := governanceStored(tool, spec.Governance, a); err != nil { + return nil, t.fail(ctx, tool, a, nil, nil, err) + } remote, err := t.d.Remote(token) if err != nil { return nil, t.fail(ctx, tool, a, nil, nil, err) @@ -191,6 +205,17 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "wave", strings.Join(res.Order, ","), "skipped", len(res.Skipped), "pullRequests", len(prs)) + for _, p := range targets { + if !test { + break + } + // A governance merged between a stage's plan and its branch asks the + // review (commit.go). + if moved, what := t.governanceRecordMoved(ctx, p); moved { + t.d.Log.Warn("governance_record_moved", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", p.Name, "governance", what) + test = false + } + } t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) if err != nil { diff --git a/main.go b/main.go index 2f40dc79..f63e2989 100644 --- a/main.go +++ b/main.go @@ -32,7 +32,7 @@ import ( type options struct { listen, mcpPath, githubAPIURL string - approvalsURL, approvalsTeam, approvalsChannel, approvalsNoticeChannel, approvalsStandupChannel, approvalsTokenFile string + approvalsURL, approvalsTeam, approvalsChannel, approvalsNoticeChannel, approvalsStandupChannel, approvalsGovernanceTeam, approvalsTokenFile string registryRepository, registryPath, hub string @@ -55,6 +55,7 @@ func parseFlags(args []string) (*options, error) { f.StringVar(&o.approvalsTeam, "approvals-team", envOr("APPROVALS_TEAM", ""), "The team whose members decide, as the gateway names it (APPROVALS_TEAM)") f.StringVar(&o.approvalsChannel, "approvals-channel", envOr("APPROVALS_CHANNEL", ""), "The capability-owning team's channel the reviews land in (APPROVALS_CHANNEL)") f.StringVar(&o.approvalsNoticeChannel, "approvals-notice-channel", envOr("APPROVALS_NOTICE_CHANNEL", ""), "The channel told of a review that targets a customer installation, without buttons (APPROVALS_NOTICE_CHANNEL)") + f.StringVar(&o.approvalsGovernanceTeam, "approvals-governance-team", envOr("APPROVALS_GOVERNANCE_TEAM", ""), "The GitHub team (org/team) whose active members approve a governance change (APPROVALS_GOVERNANCE_TEAM)") f.StringVar(&o.approvalsStandupChannel, "approvals-standup-channel", envOr("APPROVALS_STANDUP_CHANNEL", ""), "The team's standup channel, told of an action on test installations, which needs no review (APPROVALS_STANDUP_CHANNEL)") f.StringVar(&o.approvalsTokenFile, "approvals-token-file", envOr("APPROVALS_TOKEN_FILE", ""), "File with the projected ServiceAccount token, in the gateway's audience, the review requests carry (APPROVALS_TOKEN_FILE)") f.StringVar(&o.registryRepository, "registry-repository", envOr("REGISTRY_REPOSITORY", installations.DefaultCatalog.Repository), "Repository (owner/repo) holding the installations catalog, read as the caller (REGISTRY_REPOSITORY)") @@ -97,7 +98,7 @@ func main() { func run(ctx context.Context, o *options, log *slog.Logger) error { warnDeprecated(o, log) deps := tools.Deps{Version: version.String(), GitHubAPIURL: o.githubAPIURL, Files: gh.NewFiles(gh.DefaultFreshness), Log: log, Remote: tools.GitHubRemote(o.githubAPIURL), - Approvals: approvals.Config{GatewayURL: o.approvalsURL, Team: o.approvalsTeam, Channel: o.approvalsChannel, NoticeChannel: o.approvalsNoticeChannel, StandupChannel: o.approvalsStandupChannel, TokenFile: o.approvalsTokenFile}, + Approvals: approvals.Config{GatewayURL: o.approvalsURL, Team: o.approvalsTeam, Channel: o.approvalsChannel, NoticeChannel: o.approvalsNoticeChannel, StandupChannel: o.approvalsStandupChannel, GovernanceTeam: o.approvalsGovernanceTeam, TokenFile: o.approvalsTokenFile}, Registry: installations.Sources{Catalog: installations.Location{Repository: o.registryRepository, Path: o.registryPath}, Hub: o.hub}} if o.actionsNamespace != "" { store, err := actions.InCluster(o.actionsNamespace) diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index 2520f494..2c5b5eb6 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -22,6 +22,13 @@ const ( toolListActions = "list_actions" keySafe = "safe" sourcePlatformManager = "giantswarm-platform-manager" + toolGetInfo = "get_info" + toolApproveAction = "approve_action" + toolSetAgentApproval = "set_agent_approval" + roleInfrastructure = "infrastructure" + roleSkillManager = "skillManager" + roleAgentManager = "agentManager" + pathSkillSafe0 = "/governance/governedServers/skill-manager/safe/0" ) // withGovernanceReleases takes the governance releases as cut for the test. @@ -89,9 +96,9 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { withGovernanceReleases(t) governance := map[string]any{keyMode: GovernanceGoverned, keyGovernedServers: map[string]any{ - sourcePlatformManager: map[string]any{keySafe: []any{"get_info", toolListActions}}, + sourcePlatformManager: map[string]any{keySafe: []any{toolGetInfo, toolListActions}}, "mcp-kubernetes": nil, - "agent-platform/pro": map[string]any{keyRole: "infrastructure", keySafe: []any{}}, + "agent-platform/pro": map[string]any{keyRole: roleInfrastructure, keySafe: []any{}}, }} input, secrets := governanceInput(t, governance) patch := renderedPatch(t, input, secrets) @@ -136,29 +143,29 @@ func TestGovernanceRefusals(t *testing.T) { names string }{ {"an unknown role", server("agent-manager", map[string]any{keyRole: "admin"}), nil, "/governance/governedServers/agent-manager/role"}, - {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{keyRole: "platformManager", keySafe: []any{toolListActions, "approve_action"}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, - {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{keySafe: []any{"set_agent_approval"}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, - {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, "/governance/governedServers/skill-manager/safe/0"}, + {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{keyRole: "platformManager", keySafe: []any{toolListActions, toolApproveAction}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, + {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{keySafe: []any{toolSetAgentApproval}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, + {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, pathSkillSafe0}, // S9-02: a role override drops the floors muster applies by a // server's role, so it is refused, as is any floor on any safe list // and a server key standing for a chart source. - {"a chart source's role changed", server("agent-manager", map[string]any{keyRole: "infrastructure", keySafe: []any{"set_agent_approval", "create_agent"}}), nil, "role infrastructure: the meta chart governs agent-manager as agentManager"}, - {"the platform manager's role changed alone", server(sourcePlatformManager, map[string]any{keyRole: "infrastructure"}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, - {"the platform manager's role changed to list its floors", server(sourcePlatformManager, map[string]any{keyRole: "skillManager", keySafe: []any{"approve_action", "merge_action"}}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, - {"a chart source under a server key", server("agent-platform/agent-manager", map[string]any{keySafe: []any{"set_agent_approval"}}), nil, "names the meta chart's source agent-manager under a server key"}, - {"a kubernetes family member under a server key", server("mcp/alder-mcp-kubernetes", map[string]any{keyRole: "infrastructure", keySafe: []any{"get"}}), nil, "names the meta chart's source mcp-kubernetes"}, - {"a server key without role", server("agent-platform/pro", map[string]any{keySafe: []any{"get_info"}}), nil, "names no role"}, - {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{"approve_action"}}), nil, "safe entry 0, approve_action, is a floor of role platformManager"}, + {"a chart source's role changed", server("agent-manager", map[string]any{keyRole: roleInfrastructure, keySafe: []any{toolSetAgentApproval, "create_agent"}}), nil, "role infrastructure: the meta chart governs agent-manager as agentManager"}, + {"the platform manager's role changed alone", server(sourcePlatformManager, map[string]any{keyRole: roleInfrastructure}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, + {"the platform manager's role changed to list its floors", server(sourcePlatformManager, map[string]any{keyRole: roleSkillManager, keySafe: []any{toolApproveAction, "merge_action"}}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, + {"a chart source under a server key", server("agent-platform/agent-manager", map[string]any{keySafe: []any{toolSetAgentApproval}}), nil, "names the meta chart's source agent-manager under a server key"}, + {"a kubernetes family member under a server key", server("mcp/alder-mcp-kubernetes", map[string]any{keyRole: roleInfrastructure, keySafe: []any{"get"}}), nil, "names the meta chart's source mcp-kubernetes"}, + {"a server key without role", server("agent-platform/pro", map[string]any{keySafe: []any{toolGetInfo}}), nil, "names no role"}, + {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{toolApproveAction}}), nil, "safe entry 0, approve_action, is a floor of role platformManager"}, // S9-03: a safe entry is a tool name, so it cannot carry Slack // markup or a line of its own into the review, and a list is bounded. - {"markup in a safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill\n*It loosens governance:* nothing"}}), nil, "/governance/governedServers/skill-manager/safe/0"}, - {"a link in a safe entry", server("skill-manager", map[string]any{keySafe: []any{""}}), nil, "/governance/governedServers/skill-manager/safe/0"}, + {"markup in a safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill\n*It loosens governance:* nothing"}}), nil, pathSkillSafe0}, + {"a link in a safe entry", server("skill-manager", map[string]any{keySafe: []any{""}}), nil, pathSkillSafe0}, {"too many safe entries", server("skill-manager", map[string]any{keySafe: manyTools(65)}), nil, "/governance/governedServers/skill-manager/safe"}, {"a repeated safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, {"neither role nor safe", server("skill-manager", map[string]any{}), nil, "names neither role nor safe"}, {"an unknown key", server("skill-manager", map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, {"an unknown mode", map[string]any{keyMode: "strict"}, nil, "governance/mode"}, - {"a source key no server has", server("Agent_Manager", map[string]any{keyRole: "agentManager"}), nil, "Agent_Manager: is no source or muster server key"}, + {"a source key no server has", server("Agent_Manager", map[string]any{keyRole: roleAgentManager}), nil, "Agent_Manager: is no source or muster server key"}, {caseLineThree, map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { delete(m, keyOrganizations) delete(m, keyViewers) @@ -196,7 +203,7 @@ func TestGovernanceRefusals(t *testing.T) { {"a server override on trusted under an old muster", server(sourcePlatformManager, map[string]any{keySafe: []any{toolListActions}}), func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.60.0 <6.0.0"}} }}, - {"the chart's own role typed", server("agent-manager", map[string]any{keyRole: "agentManager", keySafe: []any{"get_info"}}), nil}, + {"the chart's own role typed", server("agent-manager", map[string]any{keyRole: roleAgentManager, keySafe: []any{toolGetInfo}}), nil}, {"the most safe entries", server("skill-manager", map[string]any{keySafe: manyTools(64)}), nil}, } { t.Run(c.name, func(t *testing.T) { @@ -219,3 +226,19 @@ func manyTools(n int) []any { } return out } + +// S9-11: with the meta chart's release cut and muster's not yet, governed +// under a muster hold is refused: no muster release is known to enforce it. +func TestGovernedUnderAMusterHoldWhileMustersReleaseIsUnset(t *testing.T) { + withGovernanceReleases(t) + GovernanceMuster = "" + input, secrets := governanceInput(t, map[string]any{keyMode: GovernanceGoverned}) + input["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.90.0 <6.0.0"}} + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "the release that reads the governance configuration (not released yet)") { + t.Fatalf("got %v, want the unset muster release named", err) + } + delete(input, "versions") + if _, err := Render(input, secrets, render.ModeCommit); err != nil { + t.Fatalf("governed without a muster hold: %v", err) + } +} From ed3196fb18b5d86d433c8ead895dfdc024a74cd6 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:10:19 +0100 Subject: [PATCH 08/27] docs: describe the governance baseline, the reviewers' team and the safe list's side effects docs/governance.md now says how a change is compared (effective governance, against the last reviewed action), what the definition refuses, who may approve, what the review shows first, every audit line, that a direct edit of the configs repository is detected at the next plan rather than prevented, and that three of the Platform Manager's safe tools bring Action records up to date and post the facts (review S9-06, S9-12). --- README.md | 4 +- definitions/agent-platform/README.md | 3 +- docs/governance.md | 111 +++++++++++++++++++-------- 3 files changed, 83 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index a292c902..1ac8569d 100644 --- a/README.md +++ b/README.md @@ -152,8 +152,8 @@ this order, writing nothing before the gate: and each resulting pull request before the next opens. Approval and merge wait until creation finishes. The Action stays in *pending approval*: the approval, the merge and the rollout follow. An action on Giant Swarm's test installations alone — the hub's customer's, not the - hub: the wave's first stage — needs no Team review unless it changes the platform's governance - ([docs/governance.md](docs/governance.md)): the approval is recorded *not required*, the Action reads *ready to merge*, the actor merges + hub: the wave's first stage — needs no Team review unless it changes the platform's governance, which an + active member of `approvals.governanceTeam` other than the actor approves ([docs/governance.md](docs/governance.md)): the approval is recorded *not required*, the Action reads *ready to merge*, the actor merges with `merge_action` once green, and the merge is told to the team's standup channel — who, what, why and what changed (`approvals.standupChannel`; unset, such a commit is refused). The hub and every customer installation keep the review. A failure on the way moves the Action to *failed* and closes the pull requests diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index ba98fedc..58babdfb 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -9,6 +9,7 @@ policy decides once, and what the definition drops. The render library reads it. | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | +| `governance.yaml` | muster's governance roles and the floors of each, and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | | `features.yaml`, `probes.yaml` | The consistency features and their dimensions — a file dimension's key names the files and YAML paths it observes in the grammar the file's header documents, `catchAll: true` marks the kind's dimension for every other leaf, and what no dimension names the verify reports under the feature `other`; the live probes the verify runs. | ## What the definition derives, from where @@ -55,7 +56,7 @@ policy decides once, and what the definition drops. The render library reads it. | The Dev Portal's Organizations pages for everyone: `agentPlatform.organizations.enabled: true` in the Component's fragment (giantswarm/backstage#3393; an object-shaped key, which merges, so on a hand-kept portal too) | `organizations.portal.enabled`, or `organizations.enabled` on this installation; the choice read back from the fragment on record, else from the portal's own app-config, so every plan that renders a shared portal's fragment keeps the pages one installation turned on; off again only typed `false` where no installation of the portal has the switch on. Refused where no portal carries a section for the installation | | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | -| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's top-level `governance` (written only as `governed`; `trusted` is the chart's default) and `governedServers`, the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on: a role it does not know (the schema), a floor of the source's role on its safe list (the typed role, else the chart's for the source), an empty or repeated safe entry, an entry with neither role nor safe list. A commit that changes either is an Action a second person approves, on Giant Swarm's test installations too; the review shows the change old → new and what loosens ([docs/governance.md](../../docs/governance.md)) | +| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's top-level `governance` (written only as `governed`; `trusted` is the chart's default) and `governedServers`, the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/docs/governance.md b/docs/governance.md index 58331e58..82248f54 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -49,56 +49,101 @@ The definition refuses, typed or read back: - a `versions.chart` hold below `GovernanceChart`; - `governed` under a `versions.components.muster` hold below `GovernanceMuster`, where the meta chart fails the render; -- whatever muster refuses to start on: +- what muster refuses to start on, or what would drop floors past it: - a role muster does not know (the schema); - - a floor of the source's role on its safe list (the typed role, else the chart's role for the source); - - an empty or repeated safe entry; + - a role other than the meta chart's for one of its sources: muster applies a role's floors by the server's + role, so a server's role is what the server is and an override may not change it; + - a server key of its own without a role, or one naming a chart source under another key + (`/agent-manager`, `-mcp-kubernetes`); + - a floor of any role on any safe list; + - a safe entry that is no tool name (`^[A-Za-z0-9_.-]{1,128}$`), a repeated one, more than 64 per list; - an entry with neither role nor safe list. +muster's roles and floors and the chart's own `governedServers` are copied into +`definitions/agent-platform/governance.yaml`; `TestGovernanceMatchesMusterAndTheChart` compares them with sibling +checkouts of muster and agent-platform where present (`MUSTER_CHECKOUT`, `AGENT_PLATFORM_CHECKOUT`). + +## What counts as a governance change + +The plan compares the effective governance on both sides: the mode (absent is `trusted`), every server as muster +governs it (a source the values leave alone is the chart's entry), muster's own `muster.muster.governance`, and, +once `GovernanceMuster` is set, a `components.muster` hold below it. A change that leaves the effective +governance as it is, such as an explicit `trusted` dropped, is none. + +The plan compares against what the last reviewed action left, not against the record alone. Every Action +records the governance its commit leaves (`spec.governanceAfter`; a disable's is the governance before it). The +newest agent-platform action on the installation whose stage is merged and on record, approved by the team or +needing no review, is the baseline. When the record differs from it, the governance was changed outside the +manager: + +- the plan, the dry run included, shows the change against the baseline, led by a loosening line that names the + action; +- `governance_on_record_changed_outside` is logged; +- the next commit asks the review, even when it types the governance back. A record that only a reviewed change + can confirm cannot be adopted by a commit with nothing to write: that commit answers "nothing to commit" and + names the difference. + +A `disable_capability` that deletes values carrying a governance is a loosening governance change. A later enable +is compared with the governance before the disable, so bringing the platform back trusted asks the review too. +Between the plan and the pull requests the commit reads the values on the default branch again: a governance +merged in between asks the review (`governance_record_moved`). + ## A second person approves every change -A commit whose plan changes either key is recorded with the change on the Action (`spec.governance`, per -installation: `lines` old → new and `loosens`). The change rules are: +A commit whose plan changes the governance is recorded with the change on the Action (`spec.governance`, per +installation: `lines` old → new and `loosens`). The hub must store it; an Action CRD without the field is refused +before any pull request opens. The change rules are: - such an action always asks for the Team review, also where every target is one of Giant Swarm's test installations, which otherwise need none; -- `approve_action` refuses the actor, as for every action, so a second person of the team decides; -- `merge_action` merges nothing before that decision; +- `approve_action` refuses the actor, by login and by GitHub id; +- the approver must be an active member of the governance reviewers' team, a GitHub team the chart names + (`approvals.governanceTeam`, `org/team`), and a GitHub account of type `User`. The manager reads the membership + as the approver. When the team is unset or the membership cannot be read, nothing is approved; +- `merge_action` merges nothing before that decision; a stage merged outside the manager decides nothing for + the stages after it; - an agent can propose such a change but never approve or merge it: muster asks a person before an agent's `approve_action` and `merge_action`. -The review leads with the governance, before the reason: +The review leads with the governance, before the reason, and with what loosens it before the change itself: ```text *Governance:* this changes the platform's governance; a second person approves it, on test installations too. -• rowan: mode governed → trusted (the chart's default) -*It loosens governance:* rowan: mode governed → trusted (the chart's default) +*It loosens governance:* rowan: mode governed → trusted +• rowan: mode governed → trusted ``` -The same change also reads in *What changes*, with its values, as its own line. A change loosens governance, or -may, when any of these hold: +What loosens is never cut. A commit whose loosening lines do not fit in what Slack shows (1000 characters) is +refused: split it. The change lines that follow are cut at 1400 characters, the configs pull request named for the +rest. A change loosens governance, or may, when any of these hold: - the mode leaves `governed`; -- a source is dropped or put back to the chart's entry; -- a role changes or is left to the chart's; -- a safe entry is added (one named like a write, such as `create_…` or `set_…`, is marked); -- a safe list is replaced or put back to the chart's. +- a source is no longer governed; +- a role changes; +- a safe entry is added, against the chart's list for a first override; one named like a write anywhere in its + name (`kubernetes_delete`, `port_forward`) or a floor of any role is marked; +- muster's own governance changes, or a muster hold drops below the release that enforces it; +- the record differs from what the last reviewed action left; +- the agent-platform values cannot be read on either side. -The manager does not know the chart's own entries, so a change against them counts as loosening. If the -agent-platform values cannot be read on either side, the plan counts it as a loosening change. +Values from the record are escaped for Slack: no value carries a line, markup or a link into the review. ## Audit -Each step logs one line per installation whose governance the action changes. Every line carries the action, -the installation, the actor, the caller, the decision and who decided it, the change and whether it loosens. +Each step logs one line per installation whose governance the action changes (`audit=true`). Every line carries +the action, the installation, the actor, the caller, the decision and who decided it, the change and whether it +loosens. | Event | When | |---|---| -| `governance_change_committed` | the commit opened the pull requests | +| `governance_change_committed` | the commit, wave or disable opened the pull requests | | `governance_change_self_approval_refused` | the actor tried to approve their own change | -| `governance_change_approved` | a second person approved it | -| `governance_change_merged` | `merge_action` merged pull requests of it | -| `governance_change_merged_without_approval` | the pull requests were merged outside the manager before any decision; only the repositories' branch protection stood in the way | +| `governance_change_approval_refused` | the approver is no active member of the team, no person, or their membership could not be read | +| `governance_change_approved` | a second person approved it; with the approver's login and id and how their membership was read | +| `governance_change_merged` | `merge_action` merged a stage of it; with the pull requests and their heads | +| `governance_change_merged_without_approval` | a pull request of it was merged outside the manager before the team approved, in any state of the action; read at the next read of the action | +| `governance_on_record_changed_outside` | a plan found the record's governance other than what the last reviewed action left | +| `governance_record_moved` | the values on the default branch changed between the plan and the pull requests | ## What the manager does not cover @@ -106,17 +151,18 @@ These limits are outside the manager: - someone with write access to `giantswarm/-configs` can merge a change to the values outside the manager. Branch protection on those repositories (enforced for admins, re-approval after a new push, required - CODEOWNERS review) is asked of their owners. The manager audits such a merge but cannot prevent it. + CODEOWNERS review) is asked of their owners. The manager does not prevent such a change. It detects it at the + next plan of the installation and asks the review then; a merge of one of its own Actions' pull requests + outside it is audited when the action is read next. - whoever holds Kubernetes write rights on muster's HelmRelease or ConfigMap can change the configuration directly. -- `disable_capability` removes the whole platform, muster included, and keeps its own review rules: no agent - path is left to govern. +- a second GitHub account that a person holds and that the team lists counts as a second person: team + membership is the control. ## This manager's own safe list -The meta chart governs this manager (`giantswarm-platform-manager`, role `platformManager`) with an empty safe -list, so on `governed` every tool but the floors asks agents. The tools that only read, and are proposed for its -safe list, are: +The meta chart governs this manager (`giantswarm-platform-manager`, role `platformManager`). Its safe list, the +tools agents call unasked on `governed`, is: | Tool | Why it is safe | |---|---| @@ -126,8 +172,9 @@ safe list, are: | `get_action` | one Action record | | `verify_capability` | compares the repositories with a definition and writes nothing | -`get_action` and `list_actions` bring an Action's status up to date with GitHub as they read it. They change no -decision. +`get_action`, `list_actions` and `list_installations` bring the Action records up to date with GitHub as the +caller as they read them: an action can move to rolling out, failed or removed, and the facts are posted to its +review thread or the team's standup channel. They follow what GitHub says and decide nothing. These tools stay asking: From 1f2f32664b3e497528d4a2f07e189ef8a97b52b6 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:15:06 +0100 Subject: [PATCH 09/27] test(e2e): assert the governance audit of a wave and a disable, and the actor under a new login The actor approving under a renamed login with the same GitHub id is refused; the wave's and the disable's commit audit lines are asserted, so removing either call fails a test (review S9-11, S9-16). --- internal/e2e/fakes_test.go | 13 +++++++++++-- internal/e2e/governance_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/internal/e2e/fakes_test.go b/internal/e2e/fakes_test.go index ec0555f8..f7105fe0 100644 --- a/internal/e2e/fakes_test.go +++ b/internal/e2e/fakes_test.go @@ -50,6 +50,9 @@ type fakeGitHub struct { teamsFailing bool // userTypes are the accounts' GitHub types where not User (Bot). userTypes map[string]string + // ids are the accounts' GitHub ids where not userID's: a renamed login + // keeps its id. + ids map[string]int64 files map[string]map[string]string // owner/repo → path → content forbidden map[string]bool // hidden holds the owner/repo GitHub answers with a 404 on every read, @@ -128,7 +131,7 @@ const ( func newFakeGitHub(t *testing.T, logins map[string]string) *fakeGitHub { t.Helper() - g := &fakeGitHub{logins: logins, teams: map[string]map[string]string{}, userTypes: map[string]string{}, files: map[string]map[string]string{}, forbidden: map[string]bool{}, hidden: map[string]bool{}, failingCompare: map[string]bool{}, failing: map[string]bool{}, releases: map[string][]fakeRelease{}, failingReleases: map[string]bool{}, contentsCalls: map[string]int{}, treeCalls: map[string]int{}, treeChecks: map[string]int{}, + g := &fakeGitHub{logins: logins, teams: map[string]map[string]string{}, userTypes: map[string]string{}, ids: map[string]int64{}, files: map[string]map[string]string{}, forbidden: map[string]bool{}, hidden: map[string]bool{}, failingCompare: map[string]bool{}, failing: map[string]bool{}, releases: map[string][]fakeRelease{}, failingReleases: map[string]bool{}, contentsCalls: map[string]int{}, treeCalls: map[string]int{}, treeChecks: map[string]int{}, history: map[string][]fakeCommit{}, commitCalls: map[string]int{}} mux := http.NewServeMux() mux.HandleFunc("GET /api/v3/user", func(w http.ResponseWriter, r *http.Request) { @@ -138,7 +141,13 @@ func newFakeGitHub(t *testing.T, logins map[string]string) *fakeGitHub { writeJSON(w, http.StatusUnauthorized, map[string]any{message: badCredentials}) return } - writeJSON(w, http.StatusOK, map[string]any{ghLogin: login, "id": userID(login), "email": login + "@example.test"}) + id := userID(login) + g.mu.Lock() + if renamed, ok := g.ids[login]; ok { + id = renamed + } + g.mu.Unlock() + writeJSON(w, http.StatusOK, map[string]any{ghLogin: login, "id": id, "email": login + "@example.test"}) }) mux.HandleFunc("GET /api/v3/orgs/{org}/teams/{slug}/memberships/{user}", func(w http.ResponseWriter, r *http.Request) { if _, ok := g.logins[bearer(r)]; !ok { diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index 1736cbbe..d474f54a 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -129,6 +129,17 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { t.Fatalf("the actor's approve: %v %s", isErr, text) } requireLog(t, st, "governance_change_self_approval_refused", "action="+a.Name) + // S9-16: the actor under a new login is still the actor: GitHub's id + // stays. + const renamedToken = "alicia-token" + st.ghs.mu.Lock() + st.ghs.logins[renamedToken] = "alicia" + st.ghs.ids["alicia"] = userID(alice) + st.ghs.teams[governanceTeam]["alicia"] = memberActive + st.ghs.mu.Unlock() + if _, text, isErr := decide(t, st.mcpClient(t, renamedToken), tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "yours") { + t.Fatalf("the actor's approve under a new login: %v %s", isErr, text) + } for _, pr := range st.remote.PullRequests() { st.remote.SetChecks(pr.PullRequest, commit.ChecksSuccess) } @@ -203,6 +214,7 @@ func TestDisableThenEnableOfAGovernedTestInstallationNeedsASecondPerson(t *testi if after := d.Action.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"governance":"governed"`) { t.Fatalf("the governance the disable records: %q", after) } + requireLog(t, st, "governance_change_committed", "action="+d.Action.Name) approveAndMerge(t, st, d.Action.Name) if got := getAction(t, aliceC, d.Action.Name); got.Status.State != actions.StateDisabled { t.Fatalf("the disable after its merge: %s", got.Status.State) @@ -315,6 +327,7 @@ func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing if posted := st.gateway.posted(); len(posted) != 1 || !strings.Contains(fmt.Sprint(posted[0].Body["text"]), "*It loosens governance:* rowan: mode governed → trusted") { t.Fatalf("the review: %+v", posted) } + requireLog(t, st, "governance_change_committed", "action="+a.Name) if _, text, isErr := decide(t, aliceC, tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "yours") { t.Fatalf("the actor's approve: %v %s", isErr, text) } From 9c83a93f0cc3492bdc35f30e05acdf2ee4dd1803 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:35:36 +0100 Subject: [PATCH 10/27] feat(agent-platform): render Giant Swarm's own governance parts as fixed platform parts The open-source charts and muster no longer carry anything of Giant Swarm (decision #92), so the definition renders it on every installation it manages: the Platform Manager's role floors (governance.roleFloors: platformManager approve_action and merge_action), the Platform Manager as a governed server with its safe list, where the meta chart takes the governance, and the Giant Swarm admin groups as muster's connector admins (muster.rbac.mcpServerEditor.subjects) on the 4 line. The mode moves to governance.mode. No input changes these parts: an override of giantswarm-platform-manager is refused unless it is the platform's entry read back, and the plan reads a governance without roleFloors as having the platform's, so writing them changes nothing while a floor that goes loosens. --- definitions/agent-platform/features.yaml | 3 +- definitions/agent-platform/governance.yaml | 30 ++++- definitions/agent-platform/schema.json | 4 +- definitions/governance.go | 58 +++++++++- definitions/governance_test.go | 46 ++++++-- internal/e2e/governance_test.go | 14 +-- .../installations/governance_readback_test.go | 9 +- internal/plan/governance.go | 48 +++++++- internal/plan/governance_test.go | 31 ++++- render/agentplatform/governance.go | 109 ++++++++++++++---- render/agentplatform/governance_test.go | 94 +++++++++++---- render/agentplatform/input.go | 1 + render/agentplatform/render.go | 6 +- .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ .../configmap-values.yaml.patch | 11 ++ 29 files changed, 538 insertions(+), 91 deletions(-) diff --git a/definitions/agent-platform/features.yaml b/definitions/agent-platform/features.yaml index 94489cbc..f8458c67 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -93,7 +93,8 @@ features: - {id: agent-manager-route, kind: configmap, key: "agentManager.route (agent-manager's REST API on the gateway behind its JWT policy, for the credential form's backend; derived from agent-manager.credentials.uiURL)"} - {id: live-agent-manager-route-protected, kind: live, key: "https://agentgateway./agent-manager/api/v1/info answered 401 by the route's JWT policy, where agent-manager.credentials.uiURL is set"} - {id: platform-tenant-bindings, kind: configmap, key: "tenants / musterMcpServerViewers (who the platform tenant binds in the kagent namespace, and who lists muster's MCP servers)"} - - {id: governance, kind: configmap, key: "governance / governedServers (the platform's governance mode and the servers muster governs with their safe lists; changed only through an Action a second person approves)"} + - {id: governance, kind: configmap, key: "governance / governedServers (the platform's governance mode, Giant Swarm's role floors and the servers muster governs with their safe lists; changed only through an Action a second person approves)"} + - {id: connector-admins, kind: configmap, key: "muster.rbac.mcpServerEditor (Giant Swarm's connector admins: the admin groups bound to muster's mcpserver-editor Role)"} - {id: own-mcp-servers, kind: configmap, key: "agent-platform-mcps.mcpServers[http://.svc:8080/mcp] / agent-platform-mcps.mcpServers[://mcp-./mcp] (the installation's own: at the in-cluster Service, or on its own base domain)"} - {id: own-mcp-kubernetes-url, kind: configmap, key: "agent-platform-mcps.mcpServers[http://mcp-kubernetes.mcp-kubernetes.svc:8080/mcp].url"} - {id: muster-private-exchange, kind: configmap, key: muster.muster.oauth.mcpClient.tokenExchange.allowPrivateIP} diff --git a/definitions/agent-platform/governance.yaml b/definitions/agent-platform/governance.yaml index 3827a150..207df0df 100644 --- a/definitions/agent-platform/governance.yaml +++ b/definitions/agent-platform/governance.yaml @@ -3,18 +3,39 @@ # read it and held to them by definitions' TestGovernanceMatchesMusterAndTheChart # (which reads sibling checkouts of muster and agent-platform where present). # -# muster: the roles muster knows and the floors of each (muster +# muster: the roles muster builds in and the floors of each (muster # internal/api/governance.go, GovernanceRoles and roleFloors). A floor asks agents # in both modes; muster refuses to start on one listed as safe on a server of its # role, and the definition refuses a floor of any role on any safe list. muster: - roles: [agentManager, platformManager, connectorManager, sessionManager, modelManager, clusterManager, vmManager, workspaceManager, toolchainManager, skillManager, infrastructure] + roles: [agentManager, connectorManager, sessionManager, modelManager, clusterManager, vmManager, workspaceManager, toolchainManager, skillManager, infrastructure] floors: agentManager: [set_agent_approval, set_organization_connector, add_organization_member, set_organization_model, set_organization_egress_policy, replace_organization_credential] - platformManager: [approve_action, merge_action] connectorManager: [mcpserver_create, mcpserver_connect, mcpserver_set_approval] toolchainManager: [approve_source] modelManager: [add_backend] +# platform: Giant Swarm's own parts of the governance (decision #92: the open-source +# charts and muster carry none), which the definition renders on every installation +# whose meta chart takes the governance, fixed, never an input and never loosened by +# one: muster's role floors of the Platform Manager (the chart's governance.roleFloors, +# a union with muster's built-ins), the Platform Manager as a governed server with +# its safe list (its reads; docs/governance.md), and the connector admins, the Giant +# Swarm admin groups bound to muster's mcpserver-editor Role (the chart's +# muster.rbac.mcpServerEditor.subjects; the meta chart appends tenants.platformTeam). +platform: + roleFloors: + platformManager: [approve_action, merge_action] + governedServers: + giantswarm-platform-manager: + role: platformManager + safe: [get_info, list_installations, list_actions, get_action, verify_capability] + connectorAdmins: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins # chart: the meta chart's own governedServers by source (agent-platform # helm/agent-platform/values.yaml, top-level governedServers). A source's role is # what the server is: an override may not change it. The plan diffs an override @@ -47,6 +68,3 @@ chart: mcp-kubernetes: role: infrastructure safe: [logs, list_port_forward_sessions, context_list, context_get_current, can_i, api_resources, cluster_health, capi_list_clusters, capi_get_cluster, capi_resolve_cluster, capi_cluster_health, get, list, describe] - giantswarm-platform-manager: - role: platformManager - safe: [get_info, list_installations, list_actions, get_action, verify_capability] diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index e4eb8762..13aafbec 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -864,9 +864,9 @@ "enum": ["trusted", "governed"], "default": "trusted", "x-source": "person", - "x-readback": {"file": "configmap", "key": "governance"}, + "x-readback": {"file": "configmap", "key": "governance.mode"}, "x-feature": "tool-access", - "x-renders": ["configmap:governance"], + "x-renders": ["configmap:governance.mode"], "description": "The platform's governance mode (the meta chart's governance): trusted, the default and not written, lets agents run what the connectors' own settings allow; governed asks a person before an agent runs any tool of a governed server not on that server's safe list, and before any of muster's own tools but its reads. muster's floors ask in both modes. governed under a hold of muster below the release that reads the governance configuration is refused, since the meta chart refuses the render there. Read back from the configmap patch on record, so a reconcile keeps it; typed (--input governance.mode=governed), it replaces it." }, "governedServers": { diff --git a/definitions/governance.go b/definitions/governance.go index 31eabbbf..96368b54 100644 --- a/definitions/governance.go +++ b/definitions/governance.go @@ -2,6 +2,7 @@ package definitions import ( "fmt" + "maps" "slices" "sync" @@ -15,17 +16,66 @@ type GovernedServer struct { Safe []string `yaml:"safe" json:"safe"` } +// Subject is an RBAC subject in the meta chart's shape. +type Subject struct { + APIGroup string `yaml:"apiGroup" json:"apiGroup,omitempty"` + Kind string `yaml:"kind" json:"kind"` + Name string `yaml:"name" json:"name"` +} + // GovernanceData is the governance the agent-platform definition writes -// against (agent-platform/governance.yaml): muster's roles and floors, and the -// meta chart's own governedServers by source. +// against (agent-platform/governance.yaml): muster's built-in roles and +// floors, Giant Swarm's own platform parts the definition always renders +// (the Platform Manager's role floors, its governed server, the connector +// admins), and the meta chart's own governedServers by source. type GovernanceData struct { Muster struct { Roles []string `yaml:"roles"` Floors map[string][]string `yaml:"floors"` } `yaml:"muster"` + Platform struct { + RoleFloors map[string][]string `yaml:"roleFloors"` + GovernedServers map[string]GovernedServer `yaml:"governedServers"` + ConnectorAdmins []Subject `yaml:"connectorAdmins"` + } `yaml:"platform"` Chart map[string]GovernedServer `yaml:"chart"` } +// Roles are the roles muster knows with the platform's role floors: its +// built-ins and the roles the rendered governance.roleFloors add. +func (g GovernanceData) Roles() []string { + out := slices.Clone(g.Muster.Roles) + for _, role := range slices.Sorted(maps.Keys(g.Platform.RoleFloors)) { + if !slices.Contains(out, role) { + out = append(out, role) + } + } + return out +} + +// Floors are the floors of role: muster's built-ins and the platform's +// role floors, a union as muster takes them. +func (g GovernanceData) Floors(role string) []string { + out := slices.Clone(g.Muster.Floors[role]) + for _, t := range g.Platform.RoleFloors[role] { + if !slices.Contains(out, t) { + out = append(out, t) + } + } + return out +} + +// Servers are the governed servers by source as the definition renders +// them before any input: the meta chart's own and the platform's. +func (g GovernanceData) Servers() map[string]GovernedServer { + out := maps.Clone(g.Chart) + if out == nil { + out = map[string]GovernedServer{} + } + maps.Copy(out, g.Platform.GovernedServers) + return out +} + var governance = sync.OnceValues(func() (GovernanceData, error) { raw, err := FS.ReadFile("agent-platform/governance.yaml") if err != nil { @@ -50,8 +100,8 @@ func Governance() GovernanceData { // FloorRole is the role whose floor tool is, empty when it is no floor. func (g GovernanceData) FloorRole(tool string) string { - for _, role := range g.Muster.Roles { - if slices.Contains(g.Muster.Floors[role], tool) { + for _, role := range g.Roles() { + if slices.Contains(g.Floors(role), tool) { return role } } diff --git a/definitions/governance_test.go b/definitions/governance_test.go index 5e13d9e2..844ad9f1 100644 --- a/definitions/governance_test.go +++ b/definitions/governance_test.go @@ -60,7 +60,7 @@ func musterGovernance(t *testing.T, src []byte) ([]string, map[string][]string) if lit, ok := n.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING { consts[name.Name] = value(lit) } - if name.Name == "roleFloors" { + if name.Name == "roleFloors" || name.Name == "builtinRoleFloors" { for _, el := range n.Values[i].(*ast.CompositeLit).Elts { kv := el.(*ast.KeyValueExpr) for _, tool := range kv.Value.(*ast.CompositeLit).Elts { @@ -89,14 +89,23 @@ func musterGovernance(t *testing.T, src []byte) ([]string, map[string][]string) } // The governance data the definition writes against matches the releases -// it copies: muster's roles and every role's floors, and the meta chart's -// own governedServers (role and safe list per source). A floor muster adds, -// or a source the chart adds or reassigns, fails here before a reviewed -// merge stops muster at start. +// it copies: muster's built-in roles and floors, and the meta chart's own +// governedServers. Giant Swarm's platform parts are no longer theirs +// (decision #92): a muster or chart from before still carrying the Platform +// Manager's role or entry is read without it, and must agree with ours. A +// floor muster adds, or a source the chart adds or reassigns, fails here +// before a reviewed merge stops muster at start. func TestGovernanceMatchesMusterAndTheChart(t *testing.T) { g := definitions.Governance() t.Run("muster", func(t *testing.T) { roles, floors := musterGovernance(t, checkout(t, "MUSTER_CHECKOUT", "muster", "internal/api/governance.go")) + for role, ours := range g.Platform.RoleFloors { + if theirs, built := floors[role]; built && !reflect.DeepEqual(theirs, ours) { + t.Errorf("muster still builds in role %s with floors %v, the platform's are %v", role, theirs, ours) + } + delete(floors, role) + roles = slices.DeleteFunc(roles, func(r string) bool { return r == role }) + } if !slices.Equal(roles, g.Muster.Roles) { t.Errorf("roles %v, muster's %v", g.Muster.Roles, roles) } @@ -116,18 +125,26 @@ func TestGovernanceMatchesMusterAndTheChart(t *testing.T) { values.GovernedServers[source] = definitions.GovernedServer{Role: s.Role, Safe: []string{}} } } + for source, ours := range g.Platform.GovernedServers { + if theirs, ok := values.GovernedServers[source]; ok && !reflect.DeepEqual(theirs, ours) { + t.Errorf("the meta chart still ships %s as %v, the platform's is %v", source, theirs, ours) + } + delete(values.GovernedServers, source) + } if !reflect.DeepEqual(values.GovernedServers, g.Chart) { t.Errorf("chart %v, the meta chart's %v", g.Chart, values.GovernedServers) } }) } -// No floor is on the chart's safe lists, every source's role is muster's. +// No floor is on a safe list the definition renders, every source's role +// is one muster knows with the platform's role floors, the platform's role +// floors name no built-in role, and the connector admins are groups. func TestGovernanceDataIsConsistent(t *testing.T) { g := definitions.Governance() - for source, s := range g.Chart { - if !slices.Contains(g.Muster.Roles, s.Role) { - t.Errorf("%s: role %q is none of muster's", source, s.Role) + for source, s := range g.Servers() { + if !slices.Contains(g.Roles(), s.Role) { + t.Errorf("%s: role %q is none muster knows", source, s.Role) } for _, tool := range s.Safe { if role := g.FloorRole(tool); role != "" { @@ -140,4 +157,15 @@ func TestGovernanceDataIsConsistent(t *testing.T) { t.Errorf("floors of unknown role %s", role) } } + for role := range g.Platform.RoleFloors { + if slices.Contains(g.Muster.Roles, role) { + t.Errorf("the platform's role %s is one of muster's built-ins", role) + } + } + if len(g.Platform.ConnectorAdmins) == 0 || slices.ContainsFunc(g.Platform.ConnectorAdmins, func(s definitions.Subject) bool { return s.Kind != "Group" }) { + t.Errorf("connector admins: %+v", g.Platform.ConnectorAdmins) + } + if _, ok := g.Chart["giantswarm-platform-manager"]; ok { + t.Error("the Platform Manager is the platform's governed server, not the chart's") + } } diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index d474f54a..654d31e3 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -110,7 +110,7 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { if !ok || len(g.Lines) != 2 || len(g.Loosens) != 1 || g.Loosens[0] != droppedKubernetes { t.Fatalf("the action's governance: %+v", a.Spec.Governance) } - if after := a.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"governance":"governed"`) { + if after := a.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"mode":"governed"`) { t.Fatalf("the governance the action leaves: %q", after) } posted := st.gateway.posted() @@ -211,7 +211,7 @@ func TestDisableThenEnableOfAGovernedTestInstallationNeedsASecondPerson(t *testi if d.Action.Status.State != actions.StatePendingApproval || d.Action.Status.Approval.ReviewID == "" || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "deleted with the platform") || !slices.Contains(g.Loosens, "mode governed → trusted") { t.Fatalf("the disable of a governed test installation: %+v %+v", d.Action.Status.Approval, g) } - if after := d.Action.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"governance":"governed"`) { + if after := d.Action.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"mode":"governed"`) { t.Fatalf("the governance the disable records: %q", after) } requireLog(t, st, "governance_change_committed", "action="+d.Action.Name) @@ -245,11 +245,11 @@ func TestGovernanceChangedOutsideTheManagerNeedsTheReview(t *testing.T) { merged := approveAndMerge(t, st, out.Action.Name) marker := installations.Capabilities()[0].EnabledMarker(rowan) values, ok := st.ghs.file(acmeConfigs, marker) - if !ok || !strings.Contains(values, "\ngovernance: governed\n") { + if !ok || !strings.Contains(values, "\n mode: governed\n") { t.Fatalf("the governed values on record: %v\n%s", ok, values) } // Someone takes governed out in the repository, past the manager. - st.ghs.addFile(acmeConfigs, marker, strings.Replace(values, "\ngovernance: governed\n", "\n", 1)) + st.ghs.addFile(acmeConfigs, marker, strings.Replace(values, "\n mode: governed\n", "\n", 1)) // Typing governed again changes no governance against the reviewed // action, yet the record moved: the review stands, the outside change @@ -272,12 +272,12 @@ func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) st := governedTestRowan(t) aliceC := st.mcpClient(t, aliceToken) marker := installations.Capabilities()[0].EnabledMarker(rowan) - st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, "governance: governed\n") } + st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, "governance:\n mode: governed\n") } out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) if isErr || out.Action == nil { t.Fatalf("commit: %v %s", isErr, text) } - if v, _ := st.ghs.file(acmeConfigs, marker); st.beforeOpen != nil || v != "governance: governed\n" { + if v, _ := st.ghs.file(acmeConfigs, marker); st.beforeOpen != nil || v != "governance:\n mode: governed\n" { t.Fatalf("the hook did not run: %q", v) } if out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision == actions.DecisionNotRequired || out.Action.Status.Approval.ReviewID == "" { @@ -308,7 +308,7 @@ func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing sopsFixtures(t, st.ghs) rowanAsTestInstallation(t, st.ghs) rowanOnLineFour(st.ghs) - st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), "muster: {}\ngovernance: governed\n") + st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), "muster: {}\ngovernance:\n mode: governed\n") seedRemote(t, st) aliceC := st.mcpClient(t, aliceToken) inputs := minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}}) diff --git a/internal/installations/governance_readback_test.go b/internal/installations/governance_readback_test.go index 09ef3d3a..c1d22355 100644 --- a/internal/installations/governance_readback_test.go +++ b/internal/installations/governance_readback_test.go @@ -12,7 +12,7 @@ import ( // governanceOnRecord appends the platform's governance to a configmap patch, // as a commit of governance.* writes it. func governanceOnRecord(patch string) string { - return patch + "governance: governed\ngovernedServers:\n giantswarm-platform-manager:\n safe:\n - get_info\n mcp-kubernetes: null\n" + return patch + "governance:\n mode: governed\ngovernedServers:\n skill-manager:\n safe:\n - get_skill\n mcp-kubernetes: null\n" } // The governance on record is read back as governance.mode and @@ -29,12 +29,13 @@ func TestGovernanceSurvivesAReconcile(t *testing.T) { patch, read, doc, marker := inputFromTheRecord(t, "platform-tenant-retired", governanceOnRecord) require.Equal(t, agentplatform.GovernanceGoverned, read["governance.mode"]) - require.Equal(t, map[string]any{"giantswarm-platform-manager": map[string]any{"safe": []any{"get_info"}}, clusterMCPServersMarkerServer: nil}, read["governance.governedServers"]) + require.Equal(t, map[string]any{"skill-manager": map[string]any{"safe": []any{"get_skill"}}, clusterMCPServersMarkerServer: nil}, read["governance.governedServers"]) result, err := definition.Render(doc, nil, render.ModeCommit) require.NoError(t, err) again := string(result.Tree()["giantswarm/giantswarm-configs/"+marker]) - require.Contains(t, again, "governance: governed\n") - require.Contains(t, again, " giantswarm-platform-manager:\n safe:\n - get_info\n mcp-kubernetes: null\n") + require.Contains(t, again, "governance:\n mode: governed\n roleFloors:\n platformManager:\n") + require.Contains(t, again, " giantswarm-platform-manager:\n role: platformManager\n") + require.Contains(t, again, " mcp-kubernetes: null\n skill-manager:\n safe:\n - get_skill\n") _, _, doc, _ = inputFromTheRecord(t, "platform-tenant-retired", func(string) string { return again }) result, err = definition.Render(doc, nil, render.ModeCommit) require.NoError(t, err) diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 9c2586cd..4d40ac80 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -3,6 +3,7 @@ package plan import ( "encoding/json" "fmt" + "maps" "slices" "strings" @@ -189,6 +190,7 @@ func GovernanceBetween(old, next GovernanceSnapshot) GovernanceChange { if om != nm { g.add(fmt.Sprintf("mode %s → %s", om, nm), om == modeGoverned) } + g.roleFloors(roleFloorsOf(old[keyGovernance]), roleFloorsOf(next[keyGovernance])) g.servers(effectiveServers(old[keyGovernedServers]), effectiveServers(next[keyGovernedServers])) if o, n := canonical(old[keyMusterGovernance]), canonical(next[keyMusterGovernance]); o != n { g.add(fmt.Sprintf("muster.muster.governance %s → %s", short(o), short(n)), true) @@ -200,13 +202,36 @@ func GovernanceBetween(old, next GovernanceSnapshot) GovernanceChange { return g } +// effectiveMode is the mode of the meta chart's governance: the string of +// an earlier chart, or its mode key; absent is trusted. func effectiveMode(v any) string { + if m, ok := v.(map[string]any); ok { + v = m["mode"] + } if v == nil { return modeTrusted } return clean(fmt.Sprint(v)) } +// roleFloorsOf are the role floors the meta chart's governance carries; +// none written are the platform's (an earlier muster built them in, and the +// definition renders them wherever the chart takes them), so writing them +// changes nothing. +func roleFloorsOf(v any) map[string][]string { + m, _ := v.(map[string]any) + floors, ok := m["roleFloors"].(map[string]any) + if !ok { + return maps.Clone(definitions.Governance().Platform.RoleFloors) + } + out := map[string][]string{} + for role, tools := range floors { + list, _ := tools.([]any) + out[clean(role)] = strs(list) + } + return out +} + // server is a source as muster governs it: its role and safe list. type server struct { role string @@ -220,7 +245,7 @@ type server struct { // replaces), a null source not governed (nil). func effectiveServers(v any) map[string]*server { out := map[string]*server{} - for source, s := range definitions.Governance().Chart { + for source, s := range definitions.Governance().Servers() { out[source] = &server{role: s.Role, safe: slices.Clone(s.Safe)} } overrides, _ := v.(map[string]any) @@ -253,9 +278,28 @@ func effectiveServers(v any) map[string]*server { return out } +// roleFloors compares the role floors the governance adds to muster's: a +// floor that goes loosens, one that comes tightens. +func (g *GovernanceChange) roleFloors(old, next map[string][]string) { + for _, role := range sortedKeys(old, next) { + added, removed := notIn(next[role], old[role]), notIn(old[role], next[role]) + if len(added)+len(removed) == 0 { + continue + } + parts := make([]string, 0, len(added)+len(removed)) + for _, t := range added { + parts = append(parts, "+"+clean(t)) + } + for _, t := range removed { + parts = append(parts, "−"+clean(t)) + } + g.add(fmt.Sprintf("roleFloors.%s %s", role, strings.Join(parts, " ")), len(removed) > 0) + } +} + // servers compares the governed servers by source. func (g *GovernanceChange) servers(old, next map[string]*server) { - chart := definitions.Governance().Chart + chart := definitions.Governance().Servers() for _, source := range sortedKeys(old, next) { o, n := old[source], next[source] at := keyGovernedServers + "." + clean(source) diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index 719e4066..8ec1bb4e 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -9,10 +9,11 @@ import ( ) const ( - govInstallation = "lynx" - govPatch = "giantswarm/acme-configs/installations/lynx/apps/agent-platform/configmap-values.yaml.patch" - govEmpty = "global: {}\n" - govGoverned = "governance: governed\n" + modeGovernedToTrusted = "mode governed → trusted" + govInstallation = "lynx" + govPatch = "giantswarm/acme-configs/installations/lynx/apps/agent-platform/configmap-values.yaml.patch" + govEmpty = "global: {}\n" + govGoverned = "governance: governed\n" ) // govPlan is an installation whose agent-platform values move from current @@ -44,7 +45,7 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { lines, loosens []string }{ {"trusted to governed tightens", govEmpty, "global: {}\ngovernance: governed\n", []string{"mode trusted → governed"}, nil}, - {"governed to the chart's default loosens", govGoverned, govEmpty, []string{"mode governed → trusted"}, []string{"mode governed → trusted"}}, + {"governed to the chart's default loosens", govGoverned, govEmpty, []string{modeGovernedToTrusted}, []string{modeGovernedToTrusted}}, {"a safe entry added and one removed", govEmpty, "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_installations, get_action, verify_capability, create_thing, list_things]\n", []string{pm}, []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_things"}}, {"only a safe entry removed", "governedServers:\n agent-manager:\n safe: [get_info, list_agents]\n", "governedServers:\n agent-manager:\n safe: [get_info]\n", @@ -139,7 +140,7 @@ func TestGovernanceDeleted(t *testing.T) { t.Fatal(err) } g, ok := GovernanceDeleted(old) - if !ok || g.Lines[0] != governanceDeleted || !slices.Contains(g.Loosens, "mode governed → trusted") || len(g.Loosens) != len(g.Lines) { + if !ok || g.Lines[0] != governanceDeleted || !slices.Contains(g.Loosens, modeGovernedToTrusted) || len(g.Loosens) != len(g.Lines) { t.Fatalf("a governed record deleted: %v %+v", ok, g) } if g, ok := GovernanceDeleted(GovernanceSnapshot{}); ok { @@ -173,3 +174,21 @@ func TestMusterHoldBelowTheGovernanceRelease(t *testing.T) { t.Fatalf("a hold above the gate: %+v", g) } } + +// Decision #92: the meta chart's governance is a map with the mode and +// Giant Swarm's role floors; a floor that goes loosens, and the Platform +// Manager written explicitly is what the chart's default was (no change). +func TestGovernanceMapWithRoleFloors(t *testing.T) { + const floors = "governance:\n mode: governed\n roleFloors:\n platformManager: [approve_action, merge_action]\n" + if g, ok := GovernanceOf(govPlan(govGoverned, floors)); ok { + t.Fatalf("the string mode written as a map with the platform's floors: %+v", g) + } + g, ok := GovernanceOf(govPlan(floors, "governance:\n roleFloors:\n platformManager: [approve_action]\n")) + if !ok || !slices.Equal(g.Loosens, []string{modeGovernedToTrusted, "roleFloors.platformManager −merge_action"}) { + t.Fatalf("mode and a floor gone: %v %+v", ok, g) + } + explicit := "governedServers:\n giantswarm-platform-manager:\n role: platformManager\n safe: [get_info, list_installations, list_actions, get_action, verify_capability]\n" + if g, ok := GovernanceOf(govPlan(govEmpty, explicit)); ok { + t.Fatalf("the platform's server written explicitly: %+v", g) + } +} diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go index feef1867..ada6b68d 100644 --- a/render/agentplatform/governance.go +++ b/render/agentplatform/governance.go @@ -79,7 +79,7 @@ var toolName = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,128}$`) // member -mcp-kubernetes. func chartSourceAlias(key string) string { name := key[strings.LastIndex(key, "/")+1:] - chart := definitions.Governance().Chart + chart := definitions.Governance().Servers() if _, ok := chart[name]; ok && name != key { return name } @@ -95,34 +95,90 @@ func (g Governance) governs() bool { return g.Mode == GovernanceGoverned || len(g.GovernedServers) > 0 } -// governanceValues appends the chosen governance to the configmap patch: -// governance: governed (trusted, the chart's default, is not written) and -// the governedServers overrides by source, a dropped one as null. +// governanceRenders says whether the installation's meta chart takes the +// governance: the release is cut (GovernanceChart), the 4 line, no chart +// hold below it. Only then are the platform's parts and any choice written. +func (in *Input) governanceRenders() bool { + return GovernanceChart != "" && in.Installation.ChartLine == lineFour && holdAdmits(in.Versions.Chart, GovernanceChart) +} + +// withoutPlatformServers drops from the chosen governedServers the +// platform's own entries as the definition renders them: read back from the +// record they are no choice, and the render writes them again. An entry for +// a platform source that differs stays, and is refused (checkGovernedSource). +func (g *Governance) withoutPlatformServers() { + for source, ours := range definitions.Governance().Platform.GovernedServers { + if s, ok := g.GovernedServers[source]; ok && s != nil && s.Role == ours.Role && s.Safe != nil && slices.Equal(*s.Safe, ours.Safe) { + delete(g.GovernedServers, source) + } + } +} + +// governanceValues appends the governance to the configmap patch where the +// meta chart takes it (governanceRenders): the meta chart's governance with +// the platform's role floors (governance.roleFloors, Giant Swarm's own, +// decision #92) and the chosen mode (governance.mode, written only as +// governed), and governedServers with the platform's own servers and the +// chosen overrides by source, a dropped one as null. func (in *Input) governanceValues(m render.Map) render.Map { + if !in.governanceRenders() { + return m + } + data := definitions.Governance() g := in.Governance + var governance render.Map if g.Mode == GovernanceGoverned { - m = append(m, render.Entry{Key: "governance", Value: GovernanceGoverned, Comment: "The platform's governance mode: the input governance.mode, read back so a\nreconcile keeps it. Changed only through an Action a second person approves."}) - } - if len(g.GovernedServers) > 0 { - var servers render.Map - for _, source := range slices.Sorted(maps.Keys(g.GovernedServers)) { - s := g.GovernedServers[source] - if s == nil { - servers = append(servers, e(source, nil)) - continue - } - var entry render.Map - if s.Role != "" { - entry = append(entry, e("role", s.Role)) - } - if s.Safe != nil { - entry = append(entry, e("safe", slices.Clone(*s.Safe))) - } - servers = append(servers, e(source, entry)) + governance = append(governance, e("mode", GovernanceGoverned)) + } + floors := render.Map{} + for _, role := range slices.Sorted(maps.Keys(data.Platform.RoleFloors)) { + floors = append(floors, e(role, slices.Clone(data.Platform.RoleFloors[role]))) + } + governance = append(governance, e("roleFloors", floors)) + m = append(m, render.Entry{Key: "governance", Value: governance, Comment: "The platform's governance: Giant Swarm's role floors (roleFloors), rendered\nalways, and the input governance.mode, read back so a reconcile keeps it.\nChanged only through an Action a second person approves."}) + servers := render.Map{} + sources := slices.Collect(maps.Keys(g.GovernedServers)) + for source := range data.Platform.GovernedServers { + if !slices.Contains(sources, source) { + sources = append(sources, source) } - m = append(m, render.Entry{Key: "governedServers", Value: servers, Comment: "The servers muster governs, over the meta chart's: the input\ngovernance.governedServers, read back so a reconcile keeps it. Changed only\nthrough an Action a second person approves; null drops a source."}) } - return m + slices.Sort(sources) + for _, source := range sources { + if ours, ok := data.Platform.GovernedServers[source]; ok { + servers = append(servers, e(source, render.Map{e("role", ours.Role), e("safe", slices.Clone(ours.Safe))})) + continue + } + s := g.GovernedServers[source] + if s == nil { + servers = append(servers, e(source, nil)) + continue + } + var entry render.Map + if s.Role != "" { + entry = append(entry, e("role", s.Role)) + } + if s.Safe != nil { + entry = append(entry, e("safe", slices.Clone(*s.Safe))) + } + servers = append(servers, e(source, entry)) + } + return append(m, render.Entry{Key: "governedServers", Value: servers, Comment: "The servers muster governs, over the meta chart's: Giant Swarm's own\n(giantswarm-platform-manager), rendered always, and the input\ngovernance.governedServers, read back so a reconcile keeps it. Changed only\nthrough an Action a second person approves; null drops a source."}) +} + +// connectorAdmins are muster's connector admins, the Giant Swarm admin +// groups bound to its mcpserver-editor Role (muster.rbac.mcpServerEditor: +// the meta chart appends tenants.platformTeam), on the 4 line, every +// installation: Giant Swarm's own (decision #92), never an input. +func (in *Input) connectorAdmins() render.Map { + if in.Installation.ChartLine != lineFour { + return nil + } + var subjects []render.Map + for _, s := range definitions.Governance().Platform.ConnectorAdmins { + subjects = append(subjects, render.Map{e("apiGroup", s.APIGroup), e("kind", s.Kind), e("name", s.Name)}) + } + return render.Map{e("mcpServerEditor", render.Map{e("subjects", subjects)})} } // checkGovernance refuses the governance the installation cannot run as @@ -182,10 +238,13 @@ func checkGovernedSource(source string, s *GovernedServer) string { if alias := chartSourceAlias(source); alias != "" { return fmt.Sprintf("names the meta chart's source %s under a server key; override it as %s, whose role the chart fixes", alias, alias) } + g := definitions.Governance() + if _, ours := g.Platform.GovernedServers[source]; ours { + return "is Giant Swarm's own governed server, which the definition renders on every installation and no input changes" + } if s == nil { return "" } - g := definitions.Governance() chart, known := g.Chart[source] switch { case known && s.Role != "" && s.Role != chart.Role: diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index 2c5b5eb6..9651b8ee 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -23,6 +23,7 @@ const ( keySafe = "safe" sourcePlatformManager = "giantswarm-platform-manager" toolGetInfo = "get_info" + toolGetSkill = "get_skill" toolApproveAction = "approve_action" toolSetAgentApproval = "set_agent_approval" roleInfrastructure = "infrastructure" @@ -70,7 +71,7 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { names string }{ {"governed", map[string]any{keyMode: GovernanceGoverned}, "(governance.mode) needs the meta chart release that renders muster's governance configuration, and none is released yet"}, - {"a server override", map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: map[string]any{keySafe: []any{toolListActions}}}}, "(governance.governedServers) needs the meta chart release"}, + {"a server override", map[string]any{keyGovernedServers: map[string]any{componentSkillManager: map[string]any{keySafe: []any{toolGetSkill}}}}, "(governance.governedServers) needs the meta chart release"}, } { t.Run(c.name, func(t *testing.T) { input, secrets := governanceInput(t, c.governance) @@ -87,24 +88,25 @@ func TestGovernanceIsRefusedUntilItsReleaseExists(t *testing.T) { } } -// With the release cut, governed renders the meta chart's top-level -// governance and the overrides its governedServers by source, in key -// order, a dropped source as null, an entry's role and safe list as typed; -// what is rendered reads back as the same input and renders the same patch -// again (a reconcile keeps it). Trusted is the chart's default and is not -// written. +// With the release cut, every installation on the 4 line renders Giant +// Swarm's own parts (decision #92): the meta chart's governance.roleFloors +// with the Platform Manager's floors, and the Platform Manager as a governed +// server with its safe list; governed adds governance.mode and the overrides +// join governedServers by source, in key order, a dropped source as null. +// What is rendered reads back as the same input (the platform's own entry +// dropped from it) and renders the same patch again (a reconcile keeps it). func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { withGovernanceReleases(t) governance := map[string]any{keyMode: GovernanceGoverned, keyGovernedServers: map[string]any{ - sourcePlatformManager: map[string]any{keySafe: []any{toolGetInfo, toolListActions}}, + componentSkillManager: map[string]any{keySafe: []any{toolGetSkill, "list_skills"}}, "mcp-kubernetes": nil, "agent-platform/pro": map[string]any{keyRole: roleInfrastructure, keySafe: []any{}}, }} input, secrets := governanceInput(t, governance) patch := renderedPatch(t, input, secrets) for _, want := range []string{ - "\ngovernance: governed\n", - "\ngovernedServers:\n agent-platform/pro:\n role: infrastructure\n safe: []\n giantswarm-platform-manager:\n safe:\n - get_info\n - list_actions\n mcp-kubernetes: null\n", + "\ngovernance:\n mode: governed\n roleFloors:\n platformManager:\n - approve_action\n - merge_action\n", + "\ngovernedServers:\n agent-platform/pro:\n role: infrastructure\n safe: []\n giantswarm-platform-manager:\n role: platformManager\n safe:\n - get_info\n - list_installations\n - list_actions\n - get_action\n - verify_capability\n mcp-kubernetes: null\n skill-manager:\n safe:\n - get_skill\n - list_skills\n", "Changed only through an Action a second person approves", } { if !strings.Contains(patch, want) { @@ -112,14 +114,57 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { } } mode, servers := governanceOf(t, patch) - again, secrets := governanceInput(t, map[string]any{keyMode: mode, keyGovernedServers: servers}) + again, secrets := governanceInput(t, map[string]any{keyMode: mode.(map[string]any)[keyMode], keyGovernedServers: servers}) if got := renderedPatch(t, again, secrets); got != patch { t.Fatalf("read back and rendered again:\n%s\nwant\n%s", got, patch) } + // Trusted and no choice: the platform's parts alone, no mode. trusted, secrets := governanceInput(t, map[string]any{keyMode: GovernanceTrusted}) - if mode, _ := governanceOf(t, renderedPatch(t, trusted, secrets)); mode != nil { - t.Fatalf("trusted writes governance: %v", mode) + got := renderedPatch(t, trusted, secrets) + mode, servers = governanceOf(t, got) + if m := mode.(map[string]any); m[keyMode] != nil || m["roleFloors"] == nil { + t.Fatalf("trusted writes governance %v", mode) + } + if s := servers.(map[string]any); len(s) != 1 || s[sourcePlatformManager] == nil { + t.Fatalf("trusted writes governedServers %v", servers) + } + if !strings.Contains(got, "\n rbac:\n mcpServerEditor:\n subjects:\n - apiGroup: rbac.authorization.k8s.io\n kind: Group\n name: giantswarm-ad:giantswarm-admins\n") { + t.Fatalf("the connector admins are not rendered:\n%s", got) + } +} + +// Giant Swarm's own parts are not inputs: an override of the Platform +// Manager's governed server is refused unless it is the platform's entry as +// rendered (read back from the record, it is dropped and rendered again). +func TestPlatformGovernanceIsNoInput(t *testing.T) { + withGovernanceReleases(t) + input, secrets := governanceInput(t, map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: map[string]any{keySafe: []any{toolGetInfo}}}}) + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "is Giant Swarm's own governed server") { + t.Fatalf("an override of the platform's server: %v", err) + } + input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: nil}}) + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) { + t.Fatalf("the platform's server dropped: %v", err) + } + ours := []any{toolGetInfo, "list_installations", toolListActions, "get_action", "verify_capability"} + input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: map[string]any{keyRole: "platformManager", keySafe: ours}}}) + if _, err := Render(input, secrets, render.ModeCommit); err != nil { + t.Fatalf("the platform's entry read back: %v", err) + } +} + +// Off the governance's release the platform's parts are not written +// (only the connector admins, which every 4-line chart takes). +func TestPlatformGovernanceWaitsForItsRelease(t *testing.T) { + input, secrets := governanceInput(t, nil) + delete(input, keyGovernance) + got := renderedPatch(t, input, secrets) + if mode, servers := governanceOf(t, got); mode != nil || servers != nil { + t.Fatalf("the platform's governance without its release: %v %v", mode, servers) + } + if !strings.Contains(got, "mcpServerEditor") { + t.Fatalf("no connector admins:\n%s", got) } } @@ -145,25 +190,26 @@ func TestGovernanceRefusals(t *testing.T) { {"an unknown role", server("agent-manager", map[string]any{keyRole: "admin"}), nil, "/governance/governedServers/agent-manager/role"}, {"a typed role's floor on the safe list", server("agent-platform/pm", map[string]any{keyRole: "platformManager", keySafe: []any{toolListActions, toolApproveAction}}), nil, "safe entry 1, approve_action, is a floor of role platformManager"}, {"the chart's role's floor on the safe list", server("agent-manager", map[string]any{keySafe: []any{toolSetAgentApproval}}), nil, "safe entry 0, set_agent_approval, is a floor of role agentManager"}, - {"an empty safe entry", server("skill-manager", map[string]any{keySafe: []any{" "}}), nil, pathSkillSafe0}, + {"an empty safe entry", server(componentSkillManager, map[string]any{keySafe: []any{" "}}), nil, pathSkillSafe0}, // S9-02: a role override drops the floors muster applies by a // server's role, so it is refused, as is any floor on any safe list // and a server key standing for a chart source. {"a chart source's role changed", server("agent-manager", map[string]any{keyRole: roleInfrastructure, keySafe: []any{toolSetAgentApproval, "create_agent"}}), nil, "role infrastructure: the meta chart governs agent-manager as agentManager"}, - {"the platform manager's role changed alone", server(sourcePlatformManager, map[string]any{keyRole: roleInfrastructure}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, - {"the platform manager's role changed to list its floors", server(sourcePlatformManager, map[string]any{keyRole: roleSkillManager, keySafe: []any{toolApproveAction, "merge_action"}}), nil, "the meta chart governs giantswarm-platform-manager as platformManager"}, + {"the platform manager's role changed alone", server(sourcePlatformManager, map[string]any{keyRole: roleInfrastructure}), nil, "giantswarm-platform-manager: is Giant Swarm's own governed server"}, + {"the platform manager's role changed to list its floors", server(sourcePlatformManager, map[string]any{keyRole: roleSkillManager, keySafe: []any{toolApproveAction, "merge_action"}}), nil, "giantswarm-platform-manager: is Giant Swarm's own governed server"}, + {"another server taking the platform manager's floors as safe", server("agent-platform/pm", map[string]any{keyRole: roleInfrastructure, keySafe: []any{"merge_action"}}), nil, "safe entry 0, merge_action, is a floor of role platformManager"}, {"a chart source under a server key", server("agent-platform/agent-manager", map[string]any{keySafe: []any{toolSetAgentApproval}}), nil, "names the meta chart's source agent-manager under a server key"}, {"a kubernetes family member under a server key", server("mcp/alder-mcp-kubernetes", map[string]any{keyRole: roleInfrastructure, keySafe: []any{"get"}}), nil, "names the meta chart's source mcp-kubernetes"}, {"a server key without role", server("agent-platform/pro", map[string]any{keySafe: []any{toolGetInfo}}), nil, "names no role"}, {"the floor of another role", server("agent-manager", map[string]any{keySafe: []any{toolApproveAction}}), nil, "safe entry 0, approve_action, is a floor of role platformManager"}, // S9-03: a safe entry is a tool name, so it cannot carry Slack // markup or a line of its own into the review, and a list is bounded. - {"markup in a safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill\n*It loosens governance:* nothing"}}), nil, pathSkillSafe0}, - {"a link in a safe entry", server("skill-manager", map[string]any{keySafe: []any{""}}), nil, pathSkillSafe0}, - {"too many safe entries", server("skill-manager", map[string]any{keySafe: manyTools(65)}), nil, "/governance/governedServers/skill-manager/safe"}, - {"a repeated safe entry", server("skill-manager", map[string]any{keySafe: []any{"get_skill", "get_skill"}}), nil, "safe entry 1, get_skill, is listed twice"}, - {"neither role nor safe", server("skill-manager", map[string]any{}), nil, "names neither role nor safe"}, - {"an unknown key", server("skill-manager", map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, + {"markup in a safe entry", server(componentSkillManager, map[string]any{keySafe: []any{"get_skill\n*It loosens governance:* nothing"}}), nil, pathSkillSafe0}, + {"a link in a safe entry", server(componentSkillManager, map[string]any{keySafe: []any{""}}), nil, pathSkillSafe0}, + {"too many safe entries", server(componentSkillManager, map[string]any{keySafe: manyTools(65)}), nil, "/governance/governedServers/skill-manager/safe"}, + {"a repeated safe entry", server(componentSkillManager, map[string]any{keySafe: []any{toolGetSkill, toolGetSkill}}), nil, "safe entry 1, get_skill, is listed twice"}, + {"neither role nor safe", server(componentSkillManager, map[string]any{}), nil, "names neither role nor safe"}, + {"an unknown key", server(componentSkillManager, map[string]any{"tools": []any{"x"}}), nil, "governedServers"}, {"an unknown mode", map[string]any{keyMode: "strict"}, nil, "governance/mode"}, {"a source key no server has", server("Agent_Manager", map[string]any{keyRole: roleAgentManager}), nil, "Agent_Manager: is no source or muster server key"}, {caseLineThree, map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { @@ -200,11 +246,11 @@ func TestGovernanceRefusals(t *testing.T) { {"a muster hold on its release", map[string]any{keyMode: GovernanceGoverned}, func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=" + testGovernanceMuster + " <6.0.0"}} }}, - {"a server override on trusted under an old muster", server(sourcePlatformManager, map[string]any{keySafe: []any{toolListActions}}), func(m map[string]any) { + {"a server override on trusted under an old muster", server(componentSkillManager, map[string]any{keySafe: []any{toolGetSkill}}), func(m map[string]any) { m["versions"] = map[string]any{keyComponents: map[string]any{componentMuster: ">=5.60.0 <6.0.0"}} }}, {"the chart's own role typed", server("agent-manager", map[string]any{keyRole: roleAgentManager, keySafe: []any{toolGetInfo}}), nil}, - {"the most safe entries", server("skill-manager", map[string]any{keySafe: manyTools(64)}), nil}, + {"the most safe entries", server(componentSkillManager, map[string]any{keySafe: manyTools(64)}), nil}, } { t.Run(c.name, func(t *testing.T) { input, secrets := governanceInput(t, c.governance) diff --git a/render/agentplatform/input.go b/render/agentplatform/input.go index eaf751c1..ddd1ac85 100644 --- a/render/agentplatform/input.go +++ b/render/agentplatform/input.go @@ -957,6 +957,7 @@ func Parse(raw any) (*Input, error) { in.Organizations, in.organizationsPolicy = d.Organizations, pol.Organizations in.PlatformTenant = PlatformTenant{Users: d.Tenants.Platform.Users, Editors: d.Tenants.Platform.Editors, PlatformTeam: d.Tenants.PlatformTeam, Viewers: d.MusterMcpServerViewers} in.Governance = d.Governance + in.Governance.withoutPlatformServers() in.selectLine(pol.targetLine(in.Installation)) if err := in.checkRecord(); err != nil { return nil, err diff --git a/render/agentplatform/render.go b/render/agentplatform/render.go index 576e5a2f..fa63bdd6 100644 --- a/render/agentplatform/render.go +++ b/render/agentplatform/render.go @@ -529,7 +529,11 @@ func (in *Input) musterValues() render.Map { if in.hasPrivateTarget() { muster = append(muster, e("extraCaFile", extraCaFile())) } - return render.Map{e("muster", append(muster, e("oauth", oauth)))} + out := render.Map{e("muster", append(muster, e("oauth", oauth)))} + if admins := in.connectorAdmins(); admins != nil { + out = append(out, render.Entry{Key: "rbac", Value: admins, Comment: "Giant Swarm's connector admins: the admin groups bound to muster's\nmcpserver-editor Role (the meta chart appends the platform team)."}) + } + return out } // dexClientRef is the referenced-Secret form of a Dex client secret. diff --git a/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch index 59f6136e..806b8044 100644 --- a/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch @@ -70,6 +70,17 @@ muster: - staging-gateway trustedPublicRegistrationRedirectURIs: - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000a + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins valkey: valkey: auth: diff --git a/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch index 3eb817e4..28979a94 100644 --- a/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch @@ -73,6 +73,17 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index 889dadd4..ab271b20 100644 --- a/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -90,6 +90,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch index 88091a10..63e6a555 100644 --- a/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch @@ -95,6 +95,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch index 81dd693e..a95f938a 100644 --- a/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch @@ -116,6 +116,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index 419a40b3..615f25cc 100644 --- a/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index 817bd320..b1b5c2b0 100644 --- a/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -122,6 +122,17 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: marmot-token-exchange-credentials + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index e728f66f..9ffff4cb 100644 --- a/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 9b903ad6..0d8f29de 100644 --- a/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 0d37ad73..c3e4adb4 100644 --- a/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index a67a0d12..a560d13a 100644 --- a/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 34fb48d4..40dcfc3a 100644 --- a/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,6 +74,17 @@ muster: - dex-k8s-authenticator - kagent - backstage + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch index 0e73fc31..210e018c 100644 --- a/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch @@ -73,6 +73,17 @@ muster: trustedPublicRegistrationRedirectURIs: - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000a - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000b + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch index bb833002..de7446aa 100644 --- a/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch @@ -96,6 +96,17 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: vole-token-exchange-credentials + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch index 772a1901..1fa470d5 100644 --- a/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch @@ -73,6 +73,17 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins cluster-manager: installation: name: finch diff --git a/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch index 5027776f..e8dc26c6 100644 --- a/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch @@ -75,6 +75,17 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # Giant Swarm's connector admins: the admin groups bound to muster's + # mcpserver-editor Role (the meta chart appends the platform team). + rbac: + mcpServerEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins cluster-manager: installation: name: wren From 3eb427ae650dac4d4ae5b9f999bc333a36dc61c4 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:35:36 +0100 Subject: [PATCH 11/27] docs: the Giant Swarm governance flow lives in the Platform Manager docs/governance.md describes the fixed platform parts the definition renders (role floors, governed server, connector admins), why they are no inputs, the governance.mode input and the drift test against muster and the chart from before and after decision #92. --- definitions/agent-platform/README.md | 4 +- docs/governance.md | 64 ++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 58babdfb..0a5ac1b2 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -9,7 +9,7 @@ policy decides once, and what the definition drops. The render library reads it. | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | -| `governance.yaml` | muster's governance roles and the floors of each, and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | +| `governance.yaml` | muster's built-in governance roles and the floors of each, Giant Swarm's own platform parts the definition renders on every installation (`platform`: the Platform Manager's role floors, its governed server with its safe list, the connector admins; decision #92), and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | | `features.yaml`, `probes.yaml` | The consistency features and their dimensions — a file dimension's key names the files and YAML paths it observes in the grammar the file's header documents, `catchAll: true` marks the kind's dimension for every other leaf, and what no dimension names the verify reports under the feature `other`; the live probes the verify runs. | ## What the definition derives, from where @@ -56,7 +56,7 @@ policy decides once, and what the definition drops. The render library reads it. | The Dev Portal's Organizations pages for everyone: `agentPlatform.organizations.enabled: true` in the Component's fragment (giantswarm/backstage#3393; an object-shaped key, which merges, so on a hand-kept portal too) | `organizations.portal.enabled`, or `organizations.enabled` on this installation; the choice read back from the fragment on record, else from the portal's own app-config, so every plan that renders a shared portal's fragment keeps the pages one installation turned on; off again only typed `false` where no installation of the portal has the switch on. Refused where no portal carries a section for the installation | | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | -| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's top-level `governance` (written only as `governed`; `trusted` is the chart's default) and `governedServers`, the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | +| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`, `trusted` being the chart's default; and Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager`, always, and the overrides), the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, any override of `giantswarm-platform-manager`, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/docs/governance.md b/docs/governance.md index 82248f54..f03fe3a2 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -6,28 +6,52 @@ changes it alone. ## What muster enforces -muster asks a person before an agent runs a tool the platform governs. Its governance configuration has two -parts, both rendered by the agent-platform meta chart: +muster asks a person before an agent runs a tool the platform governs. Its governance configuration, rendered by +the agent-platform meta chart, has three parts: - the mode: `trusted` (the default) runs what the connectors' own settings allow; `governed` asks a person before an agent runs any tool of a governed server that is not on that server's safe list, new and renamed tools included, and before any of muster's own tools except its reads; -- the governed servers, each with a role and a safe list. A role's floors ask agents in both modes, for - example this manager's `approve_action` and `merge_action` (role `platformManager`). +- the role floors: tools that ask agents in both modes on a governed server of that role. muster builds in its + own roles' floors and takes more from the configuration (`governance.roleFloors`, a union: nothing removes a + built-in floor); +- the governed servers, each with a role and a safe list. + +## Giant Swarm's own parts + +muster and the agent-platform chart are open source and carry nothing of Giant Swarm (decision #92 of the epic). +This manager is Giant Swarm's, so the Giant Swarm flow lives here: the agent-platform definition renders these +parts on every installation it manages, as fixed platform parts. They are no inputs, and no input changes or +loosens them (`definitions/agent-platform/governance.yaml`, `platform`): + +| Part | Renders | What it does | +|---|---|---| +| The Platform Manager's role floors | `governance.roleFloors: {platformManager: [approve_action, merge_action]}` | muster asks a person before an agent approves or merges an Action of this manager, in both modes; the manager cannot tell an agent from a person, since muster forwards the person's identity | +| The Platform Manager as a governed server | `governedServers.giantswarm-platform-manager: {role: platformManager, safe: [...]}` | on `governed` every tool of this manager but its safe list asks agents; the floors hold in both modes | +| The connector admins | `muster.rbac.mcpServerEditor.subjects`: the groups `giantswarm-ad:giantswarm-admins` and `giantswarm-github:giantswarm:giantswarm-admins` | whoever holds muster's `mcpserver-editor` Role edits every connector in muster's namespace, sets its tool approval and alone lets an agent run a tool the connector asks for; the meta chart appends `tenants.platformTeam` | + +The role floors and the governed server are written where the meta chart takes the governance (the release +`GovernanceChart`, the 4 line, no chart hold below it); the connector admins on every installation on the 4 line, +which every chart there takes. A `governance.governedServers` input for `giantswarm-platform-manager` is +refused; read back from the record it is the platform's entry and is rendered again. A server key of an +installation's own may take the role `platformManager`, which only adds its floors. muster from before decision +#92 builds the same floors in, so the plan reads a governance without `roleFloors` as having the platform's: +writing them changes nothing. ## The inputs -The agent-platform definition takes both as inputs. Both are read back from the configmap patch on record -(`installations//apps/agent-platform/configmap-values.yaml.patch`), so a reconcile keeps them. +The agent-platform definition takes the mode and the overrides of the governed servers as inputs. Both are read +back from the configmap patch on record (`installations//apps/agent-platform/configmap-values.yaml.patch`), +so a reconcile keeps them. | Input | Renders | Default | |---|---|---| -| `governance.mode` | the meta chart's top-level `governance`, written only as `governed` | `trusted`, the chart's default, not written | +| `governance.mode` | the meta chart's `governance.mode`, written only as `governed` | `trusted`, the chart's default, not written | | `governance.governedServers` | the meta chart's top-level `governedServers`: overrides by source, each `{role, safe}` or `null` | none: the chart's servers and safe lists apply | A source is one the meta chart knows (`agent-manager`, `kagent`, `model-manager`, `cluster-manager`, -`vm-manager`, `toolchain-manager`, `workspace-manager`, `skill-manager`, `mcp-kubernetes`, -`giantswarm-platform-manager`) or a muster server key (`` or `/`). Helm merges the maps: +`vm-manager`, `toolchain-manager`, `workspace-manager`, `skill-manager`, `mcp-kubernetes`) or a muster server key +(`` or `/`). Helm merges the maps: - a source you leave out keeps the chart's entry; - a role or safe list you leave out keeps the chart's; @@ -36,7 +60,7 @@ A source is one the meta chart knows (`agent-manager`, `kagent`, `model-manager` ```sh --input governance.mode=governed ---input 'governance.governedServers={"giantswarm-platform-manager": {"safe": ["get_info", "list_installations"]}}' +--input 'governance.governedServers={"skill-manager": {"safe": ["list_skills", "get_skill"]}}' ``` The definition refuses, typed or read back: @@ -55,18 +79,21 @@ The definition refuses, typed or read back: role, so a server's role is what the server is and an override may not change it; - a server key of its own without a role, or one naming a chart source under another key (`/agent-manager`, `-mcp-kubernetes`); - - a floor of any role on any safe list; + - a floor of any role on any safe list, the platform's role floors included; + - any override of `giantswarm-platform-manager`, Giant Swarm's own; - a safe entry that is no tool name (`^[A-Za-z0-9_.-]{1,128}$`), a repeated one, more than 64 per list; - an entry with neither role nor safe list. -muster's roles and floors and the chart's own `governedServers` are copied into -`definitions/agent-platform/governance.yaml`; `TestGovernanceMatchesMusterAndTheChart` compares them with sibling -checkouts of muster and agent-platform where present (`MUSTER_CHECKOUT`, `AGENT_PLATFORM_CHECKOUT`). +muster's built-in roles and floors and the chart's own `governedServers` are copied into +`definitions/agent-platform/governance.yaml` beside Giant Swarm's platform parts; +`TestGovernanceMatchesMusterAndTheChart` compares them with sibling checkouts of muster and agent-platform where +present (`MUSTER_CHECKOUT`, `AGENT_PLATFORM_CHECKOUT`). A muster or chart from before decision #92 that still +carries the Platform Manager's role or entry must agree with the platform's. ## What counts as a governance change -The plan compares the effective governance on both sides: the mode (absent is `trusted`), every server as muster -governs it (a source the values leave alone is the chart's entry), muster's own `muster.muster.governance`, and, +The plan compares the effective governance on both sides: the mode (absent is `trusted`), the role floors (a +floor that goes loosens), every server as muster governs it (a source the values leave alone is the chart's entry), muster's own `muster.muster.governance`, and, once `GovernanceMuster` is set, a `components.muster` hold below it. A change that leaves the effective governance as it is, such as an explicit `trusted` dropped, is none. @@ -118,6 +145,7 @@ refused: split it. The change lines that follow are cut at 1400 characters, the rest. A change loosens governance, or may, when any of these hold: - the mode leaves `governed`; +- a role floor goes; - a source is no longer governed; - a role changes; - a safe entry is added, against the chart's list for a first override; one named like a write anywhere in its @@ -161,8 +189,8 @@ These limits are outside the manager: ## This manager's own safe list -The meta chart governs this manager (`giantswarm-platform-manager`, role `platformManager`). Its safe list, the -tools agents call unasked on `governed`, is: +The definition governs this manager (`giantswarm-platform-manager`, role `platformManager`, above). Its safe +list, the tools agents call unasked on `governed`, is: | Tool | Why it is safe | |---|---| From 2340c45988802466efc80512835830607cc2cb02 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 11:41:10 +0100 Subject: [PATCH 12/27] feat(agent-platform): render the Giant Swarm admin groups as muster's workflow editors The agent-platform chart drops them as defaults of muster.rbac.workflowEditor.subjects (decision #93), so the definition renders them on every installation on the 4 line beside the connector admins, fixed and never an input. --- definitions/agent-platform/README.md | 2 +- definitions/agent-platform/features.yaml | 2 +- definitions/agent-platform/governance.yaml | 11 +++++++++- definitions/governance.go | 1 + definitions/governance_test.go | 6 +++-- docs/governance.md | 3 ++- render/agentplatform/governance.go | 22 ++++++++++++------- render/agentplatform/governance_test.go | 3 ++- render/agentplatform/render.go | 2 +- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- .../configmap-values.yaml.patch | 13 +++++++++-- 25 files changed, 212 insertions(+), 48 deletions(-) diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 0a5ac1b2..65a01f10 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -9,7 +9,7 @@ policy decides once, and what the definition drops. The render library reads it. | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | -| `governance.yaml` | muster's built-in governance roles and the floors of each, Giant Swarm's own platform parts the definition renders on every installation (`platform`: the Platform Manager's role floors, its governed server with its safe list, the connector admins; decision #92), and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | +| `governance.yaml` | muster's built-in governance roles and the floors of each, Giant Swarm's own platform parts the definition renders on every installation (`platform`: the Platform Manager's role floors, its governed server with its safe list, the connector admins and workflow editors; decisions #92, #93), and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | | `features.yaml`, `probes.yaml` | The consistency features and their dimensions — a file dimension's key names the files and YAML paths it observes in the grammar the file's header documents, `catchAll: true` marks the kind's dimension for every other leaf, and what no dimension names the verify reports under the feature `other`; the live probes the verify runs. | ## What the definition derives, from where diff --git a/definitions/agent-platform/features.yaml b/definitions/agent-platform/features.yaml index f8458c67..8e8790d7 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -94,7 +94,7 @@ features: - {id: live-agent-manager-route-protected, kind: live, key: "https://agentgateway./agent-manager/api/v1/info answered 401 by the route's JWT policy, where agent-manager.credentials.uiURL is set"} - {id: platform-tenant-bindings, kind: configmap, key: "tenants / musterMcpServerViewers (who the platform tenant binds in the kagent namespace, and who lists muster's MCP servers)"} - {id: governance, kind: configmap, key: "governance / governedServers (the platform's governance mode, Giant Swarm's role floors and the servers muster governs with their safe lists; changed only through an Action a second person approves)"} - - {id: connector-admins, kind: configmap, key: "muster.rbac.mcpServerEditor (Giant Swarm's connector admins: the admin groups bound to muster's mcpserver-editor Role)"} + - {id: connector-admins, kind: configmap, key: "muster.rbac.mcpServerEditor / muster.rbac.workflowEditor (Giant Swarm's connector admins and workflow editors: the admin groups bound to muster's mcpserver-editor and workflow-editor Roles)"} - {id: own-mcp-servers, kind: configmap, key: "agent-platform-mcps.mcpServers[http://.svc:8080/mcp] / agent-platform-mcps.mcpServers[://mcp-./mcp] (the installation's own: at the in-cluster Service, or on its own base domain)"} - {id: own-mcp-kubernetes-url, kind: configmap, key: "agent-platform-mcps.mcpServers[http://mcp-kubernetes.mcp-kubernetes.svc:8080/mcp].url"} - {id: muster-private-exchange, kind: configmap, key: muster.muster.oauth.mcpClient.tokenExchange.allowPrivateIP} diff --git a/definitions/agent-platform/governance.yaml b/definitions/agent-platform/governance.yaml index 207df0df..cf9d9b7d 100644 --- a/definitions/agent-platform/governance.yaml +++ b/definitions/agent-platform/governance.yaml @@ -21,7 +21,9 @@ muster: # a union with muster's built-ins), the Platform Manager as a governed server with # its safe list (its reads; docs/governance.md), and the connector admins, the Giant # Swarm admin groups bound to muster's mcpserver-editor Role (the chart's -# muster.rbac.mcpServerEditor.subjects; the meta chart appends tenants.platformTeam). +# muster.rbac.mcpServerEditor.subjects), and the workflow editors, the same groups +# bound to muster's workflow-editor Role (muster.rbac.workflowEditor.subjects; the +# meta chart appends tenants.platformTeam to both). platform: roleFloors: platformManager: [approve_action, merge_action] @@ -36,6 +38,13 @@ platform: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditors: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins # chart: the meta chart's own governedServers by source (agent-platform # helm/agent-platform/values.yaml, top-level governedServers). A source's role is # what the server is: an override may not change it. The plan diffs an override diff --git a/definitions/governance.go b/definitions/governance.go index 96368b54..2aceebed 100644 --- a/definitions/governance.go +++ b/definitions/governance.go @@ -37,6 +37,7 @@ type GovernanceData struct { RoleFloors map[string][]string `yaml:"roleFloors"` GovernedServers map[string]GovernedServer `yaml:"governedServers"` ConnectorAdmins []Subject `yaml:"connectorAdmins"` + WorkflowEditors []Subject `yaml:"workflowEditors"` } `yaml:"platform"` Chart map[string]GovernedServer `yaml:"chart"` } diff --git a/definitions/governance_test.go b/definitions/governance_test.go index 844ad9f1..2c1ece85 100644 --- a/definitions/governance_test.go +++ b/definitions/governance_test.go @@ -162,8 +162,10 @@ func TestGovernanceDataIsConsistent(t *testing.T) { t.Errorf("the platform's role %s is one of muster's built-ins", role) } } - if len(g.Platform.ConnectorAdmins) == 0 || slices.ContainsFunc(g.Platform.ConnectorAdmins, func(s definitions.Subject) bool { return s.Kind != "Group" }) { - t.Errorf("connector admins: %+v", g.Platform.ConnectorAdmins) + for name, list := range map[string][]definitions.Subject{"connector admins": g.Platform.ConnectorAdmins, "workflow editors": g.Platform.WorkflowEditors} { + if len(list) == 0 || slices.ContainsFunc(list, func(s definitions.Subject) bool { return s.Kind != "Group" }) { + t.Errorf("%s: %+v", name, list) + } } if _, ok := g.Chart["giantswarm-platform-manager"]; ok { t.Error("the Platform Manager is the platform's governed server, not the chart's") diff --git a/docs/governance.md b/docs/governance.md index f03fe3a2..bd78c8b4 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -32,7 +32,8 @@ loosens them (`definitions/agent-platform/governance.yaml`, `platform`): The role floors and the governed server are written where the meta chart takes the governance (the release `GovernanceChart`, the 4 line, no chart hold below it); the connector admins on every installation on the 4 line, -which every chart there takes. A `governance.governedServers` input for `giantswarm-platform-manager` is +which every chart there takes, with the same groups as the workflow editors (`muster.rbac.workflowEditor.subjects`, +muster's `workflow-editor` Role, who create, change and delete muster's workflows; decision #93). A `governance.governedServers` input for `giantswarm-platform-manager` is refused; read back from the record it is the platform's entry and is rendered again. A server key of an installation's own may take the role `platformManager`, which only adds its floors. muster from before decision #92 builds the same floors in, so the plan reads a governance without `roleFloors` as having the platform's: diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go index ada6b68d..30438167 100644 --- a/render/agentplatform/governance.go +++ b/render/agentplatform/governance.go @@ -166,19 +166,25 @@ func (in *Input) governanceValues(m render.Map) render.Map { return append(m, render.Entry{Key: "governedServers", Value: servers, Comment: "The servers muster governs, over the meta chart's: Giant Swarm's own\n(giantswarm-platform-manager), rendered always, and the input\ngovernance.governedServers, read back so a reconcile keeps it. Changed only\nthrough an Action a second person approves; null drops a source."}) } -// connectorAdmins are muster's connector admins, the Giant Swarm admin -// groups bound to its mcpserver-editor Role (muster.rbac.mcpServerEditor: -// the meta chart appends tenants.platformTeam), on the 4 line, every -// installation: Giant Swarm's own (decision #92), never an input. +// connectorAdmins are muster's editor bindings: the connector admins, the +// Giant Swarm admin groups bound to its mcpserver-editor Role +// (muster.rbac.mcpServerEditor), and the workflow editors, bound to its +// workflow-editor Role (muster.rbac.workflowEditor); the meta chart appends +// the platform team to both. On the 4 line, every installation: Giant +// Swarm's own (decisions #92, #93), never an input. func (in *Input) connectorAdmins() render.Map { if in.Installation.ChartLine != lineFour { return nil } - var subjects []render.Map - for _, s := range definitions.Governance().Platform.ConnectorAdmins { - subjects = append(subjects, render.Map{e("apiGroup", s.APIGroup), e("kind", s.Kind), e("name", s.Name)}) + list := func(from []definitions.Subject) []render.Map { + var subjects []render.Map + for _, s := range from { + subjects = append(subjects, render.Map{e("apiGroup", s.APIGroup), e("kind", s.Kind), e("name", s.Name)}) + } + return subjects } - return render.Map{e("mcpServerEditor", render.Map{e("subjects", subjects)})} + p := definitions.Governance().Platform + return render.Map{e("mcpServerEditor", render.Map{e("subjects", list(p.ConnectorAdmins))}), e("workflowEditor", render.Map{e("subjects", list(p.WorkflowEditors))})} } // checkGovernance refuses the governance the installation cannot run as diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index 9651b8ee..9d56d6e5 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -129,7 +129,8 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { if s := servers.(map[string]any); len(s) != 1 || s[sourcePlatformManager] == nil { t.Fatalf("trusted writes governedServers %v", servers) } - if !strings.Contains(got, "\n rbac:\n mcpServerEditor:\n subjects:\n - apiGroup: rbac.authorization.k8s.io\n kind: Group\n name: giantswarm-ad:giantswarm-admins\n") { + if !strings.Contains(got, "\n rbac:\n mcpServerEditor:\n subjects:\n - apiGroup: rbac.authorization.k8s.io\n kind: Group\n name: giantswarm-ad:giantswarm-admins\n") || + !strings.Contains(got, "\n workflowEditor:\n subjects:\n - apiGroup: rbac.authorization.k8s.io\n kind: Group\n name: giantswarm-ad:giantswarm-admins\n") { t.Fatalf("the connector admins are not rendered:\n%s", got) } } diff --git a/render/agentplatform/render.go b/render/agentplatform/render.go index fa63bdd6..fcdaa9c8 100644 --- a/render/agentplatform/render.go +++ b/render/agentplatform/render.go @@ -531,7 +531,7 @@ func (in *Input) musterValues() render.Map { } out := render.Map{e("muster", append(muster, e("oauth", oauth)))} if admins := in.connectorAdmins(); admins != nil { - out = append(out, render.Entry{Key: "rbac", Value: admins, Comment: "Giant Swarm's connector admins: the admin groups bound to muster's\nmcpserver-editor Role (the meta chart appends the platform team)."}) + out = append(out, render.Entry{Key: "rbac", Value: admins, Comment: "Giant Swarm's connector admins and workflow editors: the admin groups\nbound to muster's mcpserver-editor and workflow-editor Roles (the meta chart\nappends the platform team)."}) } return out } diff --git a/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch index 806b8044..0f7cec65 100644 --- a/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/confidential-client/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch @@ -70,8 +70,9 @@ muster: - staging-gateway trustedPublicRegistrationRedirectURIs: - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000a - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -81,6 +82,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins valkey: valkey: auth: diff --git a/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch index 28979a94..f0a20f8b 100644 --- a/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/credential-form/golden/giantswarm/giantswarm-configs/installations/jasper/apps/agent-platform/configmap-values.yaml.patch @@ -73,8 +73,9 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -84,6 +85,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index ab271b20..e2391d90 100644 --- a/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-owned/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -90,8 +90,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -101,6 +102,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch index 63e6a555..098b2ca4 100644 --- a/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-slack-app-public/golden/giantswarm/giantswarm-configs/installations/graveler/apps/agent-platform/configmap-values.yaml.patch @@ -95,8 +95,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -106,6 +107,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch index a95f938a..5e6a83a7 100644 --- a/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/giantswarm-slack-app/golden/giantswarm/giantswarm-configs/installations/glean/apps/agent-platform/configmap-values.yaml.patch @@ -116,8 +116,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -127,6 +128,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index 615f25cc..df734721 100644 --- a/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/hand-kept-portal/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch index b1b5c2b0..d5f45982 100644 --- a/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/hub-private-target/golden/giantswarm/giantswarm-configs/installations/gopher/apps/agent-platform/configmap-values.yaml.patch @@ -122,8 +122,9 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: marmot-token-exchange-credentials - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -133,6 +134,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 9ffff4cb..587757af 100644 --- a/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-apply/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 0d8f29de..95f1f282 100644 --- a/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-commit/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index c3e4adb4..bfe90624 100644 --- a/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/organizations-portal/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index a560d13a..9e9ec0a7 100644 --- a/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/platform-tenant-retired/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch index 40dcfc3a..a1496a33 100644 --- a/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/platform-tenant-team/golden/giantswarm/giantswarm-configs/installations/garnet/apps/agent-platform/configmap-values.yaml.patch @@ -74,8 +74,9 @@ muster: - dex-k8s-authenticator - kagent - backstage - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -85,6 +86,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch index 210e018c..799f40f4 100644 --- a/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/registered-servers/golden/giantswarm/lakeside-configs/installations/heron/apps/agent-platform/configmap-values.yaml.patch @@ -73,8 +73,9 @@ muster: trustedPublicRegistrationRedirectURIs: - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000a - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000b - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -84,6 +85,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch index de7446aa..472c3d89 100644 --- a/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/second-hub/golden/giantswarm/giantswarm-configs/installations/warren/apps/agent-platform/configmap-values.yaml.patch @@ -96,8 +96,9 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: vole-token-exchange-credentials - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -107,6 +108,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins gateway: jwksEgress: enabled: true diff --git a/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch index 1fa470d5..98fe047a 100644 --- a/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/skill-manager-default-agent-model/golden/giantswarm/giantswarm-configs/installations/finch/apps/agent-platform/configmap-values.yaml.patch @@ -73,8 +73,9 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -84,6 +85,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins cluster-manager: installation: name: finch diff --git a/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch b/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch index e8dc26c6..b2cd94c8 100644 --- a/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch +++ b/render/agentplatform/testdata/skill-manager-default-agent-off/golden/giantswarm/giantswarm-configs/installations/wren/apps/agent-platform/configmap-values.yaml.patch @@ -75,8 +75,9 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent - # Giant Swarm's connector admins: the admin groups bound to muster's - # mcpserver-editor Role (the meta chart appends the platform team). + # Giant Swarm's connector admins and workflow editors: the admin groups + # bound to muster's mcpserver-editor and workflow-editor Roles (the meta chart + # appends the platform team). rbac: mcpServerEditor: subjects: @@ -86,6 +87,14 @@ muster: - apiGroup: rbac.authorization.k8s.io kind: Group name: giantswarm-github:giantswarm:giantswarm-admins + workflowEditor: + subjects: + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-ad:giantswarm-admins + - apiGroup: rbac.authorization.k8s.io + kind: Group + name: giantswarm-github:giantswarm:giantswarm-admins cluster-manager: installation: name: wren From 111f8c242229a2873c1ef6eee2e97502a459e116 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 12:01:24 +0100 Subject: [PATCH 13/27] fix(agent-platform): key the Platform Manager by its namespace and see its parts removed The Platform Manager's MCPServer runs in its release namespace, giantswarm-platform-manager, outside muster's: its governed entry is now giantswarm-platform-manager/giantswarm-platform-manager, and an input naming that server under any key is refused. The plan no longer reads absent role floors or a missing Platform Manager entry as the platform's, so removing them out of band is a loosening governance change. A drift test fails once the meta chart renders the governance while the definition's gates are not set to its floor, so the release order cannot leave Giant Swarm installations without the Platform Manager's floors (review F1, F2). --- definitions/agent-platform/governance.yaml | 5 ++- definitions/governance_test.go | 24 +++++++++++++ .../installations/governance_readback_test.go | 2 +- internal/plan/governance.go | 16 ++++----- internal/plan/governance_test.go | 34 ++++++++++++------- render/agentplatform/governance.go | 7 ++-- render/agentplatform/governance_test.go | 31 +++++++++++------ 7 files changed, 82 insertions(+), 37 deletions(-) diff --git a/definitions/agent-platform/governance.yaml b/definitions/agent-platform/governance.yaml index cf9d9b7d..9e88e22f 100644 --- a/definitions/agent-platform/governance.yaml +++ b/definitions/agent-platform/governance.yaml @@ -27,8 +27,11 @@ muster: platform: roleFloors: platformManager: [approve_action, merge_action] + # The Platform Manager's MCPServer is giantswarm-platform-manager in its release + # namespace, giantswarm-platform-manager, outside muster's (agent-platform): muster + # keys it namespace/name. A bare name would match no server. governedServers: - giantswarm-platform-manager: + giantswarm-platform-manager/giantswarm-platform-manager: role: platformManager safe: [get_info, list_installations, list_actions, get_action, verify_capability] connectorAdmins: diff --git a/definitions/governance_test.go b/definitions/governance_test.go index 2c1ece85..94894351 100644 --- a/definitions/governance_test.go +++ b/definitions/governance_test.go @@ -7,13 +7,16 @@ import ( "os" "path/filepath" "reflect" + "regexp" "slices" "strconv" + "strings" "testing" "gopkg.in/yaml.v3" "github.com/giantswarm/giantswarm-platform-manager/definitions" + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" ) // checkout is a sibling repository's file: env names its checkout, else the @@ -171,3 +174,24 @@ func TestGovernanceDataIsConsistent(t *testing.T) { t.Error("the Platform Manager is the platform's governed server, not the chart's") } } + +// governanceFloor reads the meta chart's governance floor, the muster +// release from which it renders muster's governance configuration (empty +// while unreleased). +var governanceFloor = regexp.MustCompile(`define "agent-platform.muster.governanceFloor" -}}(.*?){{- end -}}`) + +// Review F1: once the meta chart renders the governance (its floor set), +// the definition must render Giant Swarm's floors and governed server with +// the same release: otherwise a chart and muster with the governance reach +// an installation without the Platform Manager's floors, and agents approve +// and merge its Actions unasked. The definition's gates must be set to the +// chart's floor before the chart ships it. +func TestGovernanceGatesFollowTheChart(t *testing.T) { + m := governanceFloor.FindSubmatch(checkout(t, "AGENT_PLATFORM_CHECKOUT", "agent-platform", "helm/agent-platform/templates/_helpers.tpl")) + if m == nil { + t.Fatal("the meta chart defines no agent-platform.muster.governanceFloor") + } + if floor := strings.TrimSpace(string(m[1])); floor != "" && (agentplatform.GovernanceChart == "" || agentplatform.GovernanceMuster != floor) { + t.Errorf("the meta chart renders the governance from muster %s, and the definition's gates are GovernanceChart %q, GovernanceMuster %q: set them in the release that precedes the chart's, or Giant Swarm installations run without the Platform Manager's floors", floor, agentplatform.GovernanceChart, agentplatform.GovernanceMuster) + } +} diff --git a/internal/installations/governance_readback_test.go b/internal/installations/governance_readback_test.go index c1d22355..b86b926e 100644 --- a/internal/installations/governance_readback_test.go +++ b/internal/installations/governance_readback_test.go @@ -34,7 +34,7 @@ func TestGovernanceSurvivesAReconcile(t *testing.T) { require.NoError(t, err) again := string(result.Tree()["giantswarm/giantswarm-configs/"+marker]) require.Contains(t, again, "governance:\n mode: governed\n roleFloors:\n platformManager:\n") - require.Contains(t, again, " giantswarm-platform-manager:\n role: platformManager\n") + require.Contains(t, again, " giantswarm-platform-manager/giantswarm-platform-manager:\n role: platformManager\n") require.Contains(t, again, " mcp-kubernetes: null\n skill-manager:\n safe:\n - get_skill\n") _, _, doc, _ = inputFromTheRecord(t, "platform-tenant-retired", func(string) string { return again }) result, err = definition.Render(doc, nil, render.ModeCommit) diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 4d40ac80..54e7f7af 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -3,7 +3,6 @@ package plan import ( "encoding/json" "fmt" - "maps" "slices" "strings" @@ -215,15 +214,12 @@ func effectiveMode(v any) string { } // roleFloorsOf are the role floors the meta chart's governance carries; -// none written are the platform's (an earlier muster built them in, and the -// definition renders them wherever the chart takes them), so writing them -// changes nothing. +// none written are none: neither the open-source chart nor muster carries +// the platform's (decision #92), so a record without them has none, and +// removing them loosens (review F2). func roleFloorsOf(v any) map[string][]string { m, _ := v.(map[string]any) - floors, ok := m["roleFloors"].(map[string]any) - if !ok { - return maps.Clone(definitions.Governance().Platform.RoleFloors) - } + floors, _ := m["roleFloors"].(map[string]any) out := map[string][]string{} for role, tools := range floors { list, _ := tools.([]any) @@ -245,7 +241,9 @@ type server struct { // replaces), a null source not governed (nil). func effectiveServers(v any) map[string]*server { out := map[string]*server{} - for source, s := range definitions.Governance().Servers() { + // The meta chart's own servers; the platform's are governed only where + // the values name them (review F2). + for source, s := range definitions.Governance().Chart { out[source] = &server{role: s.Role, safe: slices.Clone(s.Safe)} } overrides, _ := v.(map[string]any) diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index 8ec1bb4e..e14b81d3 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -37,7 +37,7 @@ func govPlanOf(change Change, current, next string) Installation { // tightens loosens nothing, and one that changes nothing effective (an // explicit trusted dropped) is no change. func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { - const pm = "governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_things −list_actions" + const pm = "governedServers.skill-manager.safe +create_thing (named like a write) +list_things −list_skill_sources −resolve_skills −get_skill_file" const dropped = "governedServers.mcp-kubernetes {role: infrastructure, 14 safe} → not governed (null)" for _, c := range []struct { name string @@ -46,8 +46,8 @@ func TestGovernanceChangeReadsOldToNewAndWhatLoosens(t *testing.T) { }{ {"trusted to governed tightens", govEmpty, "global: {}\ngovernance: governed\n", []string{"mode trusted → governed"}, nil}, {"governed to the chart's default loosens", govGoverned, govEmpty, []string{modeGovernedToTrusted}, []string{modeGovernedToTrusted}}, - {"a safe entry added and one removed", govEmpty, "governedServers:\n giantswarm-platform-manager:\n safe: [get_info, list_installations, get_action, verify_capability, create_thing, list_things]\n", - []string{pm}, []string{"governedServers.giantswarm-platform-manager.safe +create_thing (named like a write) +list_things"}}, + {"a safe entry added and one removed", govEmpty, "governedServers:\n skill-manager:\n safe: [list_skills, get_skill, create_thing, list_things]\n", + []string{pm}, []string{"governedServers.skill-manager.safe +create_thing (named like a write) +list_things"}}, {"only a safe entry removed", "governedServers:\n agent-manager:\n safe: [get_info, list_agents]\n", "governedServers:\n agent-manager:\n safe: [get_info]\n", []string{"governedServers.agent-manager.safe −list_agents"}, nil}, {"a source dropped", govGoverned, "governance: governed\ngovernedServers:\n mcp-kubernetes: null\n", []string{dropped}, []string{dropped}}, @@ -176,19 +176,27 @@ func TestMusterHoldBelowTheGovernanceRelease(t *testing.T) { } // Decision #92: the meta chart's governance is a map with the mode and -// Giant Swarm's role floors; a floor that goes loosens, and the Platform -// Manager written explicitly is what the chart's default was (no change). +// Giant Swarm's role floors, and the Platform Manager is a governed server +// only where the values say so (neither the open-source chart nor muster +// carries it). Review F2: removing either part out of band is a loosening +// change; putting them on record is a tightening one. func TestGovernanceMapWithRoleFloors(t *testing.T) { - const floors = "governance:\n mode: governed\n roleFloors:\n platformManager: [approve_action, merge_action]\n" - if g, ok := GovernanceOf(govPlan(govGoverned, floors)); ok { - t.Fatalf("the string mode written as a map with the platform's floors: %+v", g) + const pm = " giantswarm-platform-manager/giantswarm-platform-manager:\n role: platformManager\n safe: [get_info, list_installations, list_actions, get_action, verify_capability]\n" + with := "governance:\n mode: governed\n roleFloors:\n platformManager: [approve_action, merge_action]\ngovernedServers:\n" + pm + g, ok := GovernanceOf(govPlan(with, govGoverned)) + if !ok || len(g.Loosens) != 2 || !slices.Contains(g.Loosens, "roleFloors.platformManager −approve_action −merge_action") || !strings.HasPrefix(g.Loosens[1], "governedServers.giantswarm-platform-manager/giantswarm-platform-manager {role: platformManager, 5 safe} → not governed") { + t.Fatalf("the platform's parts removed: %v %+v", ok, g) } - g, ok := GovernanceOf(govPlan(floors, "governance:\n roleFloors:\n platformManager: [approve_action]\n")) + g, ok = GovernanceOf(govPlan(with, "governance:\n mode: governed\ngovernedServers:\n"+pm)) + if !ok || !slices.Equal(g.Loosens, []string{"roleFloors.platformManager −approve_action −merge_action"}) { + t.Fatalf("the role floors alone removed: %v %+v", ok, g) + } + g, ok = GovernanceOf(govPlan(govGoverned, with)) + if !ok || len(g.Loosens) != 0 || len(g.Lines) != 2 { + t.Fatalf("the platform's parts put on record: %v %+v", ok, g) + } + g, ok = GovernanceOf(govPlan(with, "governance:\n roleFloors:\n platformManager: [approve_action]\ngovernedServers:\n"+pm)) if !ok || !slices.Equal(g.Loosens, []string{modeGovernedToTrusted, "roleFloors.platformManager −merge_action"}) { t.Fatalf("mode and a floor gone: %v %+v", ok, g) } - explicit := "governedServers:\n giantswarm-platform-manager:\n role: platformManager\n safe: [get_info, list_installations, list_actions, get_action, verify_capability]\n" - if g, ok := GovernanceOf(govPlan(govEmpty, explicit)); ok { - t.Fatalf("the platform's server written explicitly: %+v", g) - } } diff --git a/render/agentplatform/governance.go b/render/agentplatform/governance.go index 30438167..b3e353a5 100644 --- a/render/agentplatform/governance.go +++ b/render/agentplatform/governance.go @@ -245,8 +245,11 @@ func checkGovernedSource(source string, s *GovernedServer) string { return fmt.Sprintf("names the meta chart's source %s under a server key; override it as %s, whose role the chart fixes", alias, alias) } g := definitions.Governance() - if _, ours := g.Platform.GovernedServers[source]; ours { - return "is Giant Swarm's own governed server, which the definition renders on every installation and no input changes" + for key := range g.Platform.GovernedServers { + // Any key naming the platform's server, in its namespace or another. + if source == key || source[strings.LastIndex(source, "/")+1:] == key[strings.LastIndex(key, "/")+1:] { + return "is Giant Swarm's own governed server (" + key + "), which the definition renders on every installation and no input changes" + } } if s == nil { return "" diff --git a/render/agentplatform/governance_test.go b/render/agentplatform/governance_test.go index 9d56d6e5..2e1518f4 100644 --- a/render/agentplatform/governance_test.go +++ b/render/agentplatform/governance_test.go @@ -22,14 +22,17 @@ const ( toolListActions = "list_actions" keySafe = "safe" sourcePlatformManager = "giantswarm-platform-manager" - toolGetInfo = "get_info" - toolGetSkill = "get_skill" - toolApproveAction = "approve_action" - toolSetAgentApproval = "set_agent_approval" - roleInfrastructure = "infrastructure" - roleSkillManager = "skillManager" - roleAgentManager = "agentManager" - pathSkillSafe0 = "/governance/governedServers/skill-manager/safe/0" + // platformManagerKey is the Platform Manager's muster server key: its + // MCPServer in its own namespace, outside muster's. + platformManagerKey = "giantswarm-platform-manager/giantswarm-platform-manager" + toolGetInfo = "get_info" + toolGetSkill = "get_skill" + toolApproveAction = "approve_action" + toolSetAgentApproval = "set_agent_approval" + roleInfrastructure = "infrastructure" + roleSkillManager = "skillManager" + roleAgentManager = "agentManager" + pathSkillSafe0 = "/governance/governedServers/skill-manager/safe/0" ) // withGovernanceReleases takes the governance releases as cut for the test. @@ -106,7 +109,7 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { patch := renderedPatch(t, input, secrets) for _, want := range []string{ "\ngovernance:\n mode: governed\n roleFloors:\n platformManager:\n - approve_action\n - merge_action\n", - "\ngovernedServers:\n agent-platform/pro:\n role: infrastructure\n safe: []\n giantswarm-platform-manager:\n role: platformManager\n safe:\n - get_info\n - list_installations\n - list_actions\n - get_action\n - verify_capability\n mcp-kubernetes: null\n skill-manager:\n safe:\n - get_skill\n - list_skills\n", + "\ngovernedServers:\n agent-platform/pro:\n role: infrastructure\n safe: []\n giantswarm-platform-manager/giantswarm-platform-manager:\n role: platformManager\n safe:\n - get_info\n - list_installations\n - list_actions\n - get_action\n - verify_capability\n mcp-kubernetes: null\n skill-manager:\n safe:\n - get_skill\n - list_skills\n", "Changed only through an Action a second person approves", } { if !strings.Contains(patch, want) { @@ -126,7 +129,7 @@ func TestGovernanceRendersAndSurvivesAReconcile(t *testing.T) { if m := mode.(map[string]any); m[keyMode] != nil || m["roleFloors"] == nil { t.Fatalf("trusted writes governance %v", mode) } - if s := servers.(map[string]any); len(s) != 1 || s[sourcePlatformManager] == nil { + if s := servers.(map[string]any); len(s) != 1 || s[platformManagerKey] == nil { t.Fatalf("trusted writes governedServers %v", servers) } if !strings.Contains(got, "\n rbac:\n mcpServerEditor:\n subjects:\n - apiGroup: rbac.authorization.k8s.io\n kind: Group\n name: giantswarm-ad:giantswarm-admins\n") || @@ -144,12 +147,18 @@ func TestPlatformGovernanceIsNoInput(t *testing.T) { if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "is Giant Swarm's own governed server") { t.Fatalf("an override of the platform's server: %v", err) } + for _, key := range []string{platformManagerKey, "agent-platform/giantswarm-platform-manager"} { + input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{key: map[string]any{keyRole: roleInfrastructure, keySafe: []any{toolGetInfo}}}}) + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "is Giant Swarm's own governed server") { + t.Fatalf("an override of the platform's server as %s: %v", key, err) + } + } input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: nil}}) if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) { t.Fatalf("the platform's server dropped: %v", err) } ours := []any{toolGetInfo, "list_installations", toolListActions, "get_action", "verify_capability"} - input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{sourcePlatformManager: map[string]any{keyRole: "platformManager", keySafe: ours}}}) + input, secrets = governanceInput(t, map[string]any{keyGovernedServers: map[string]any{platformManagerKey: map[string]any{keyRole: "platformManager", keySafe: ours}}}) if _, err := Render(input, secrets, render.ModeCommit); err != nil { t.Fatalf("the platform's entry read back: %v", err) } From fae585b35fed8de474f8bed71dc409d8f46223bb Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 12:01:24 +0100 Subject: [PATCH 14/27] docs: the release order and the hand upgrade of Giant Swarm installations docs/governance.md now says that the definition's governance gates are set before the chart release that renders the governance, carries the Giant Swarm upgrade snippet agent-platform's UPGRADE.md no longer has (editor groups, role floors, the Platform Manager's governed entry), and names the Platform Manager's server key. --- definitions/agent-platform/README.md | 2 +- docs/governance.md | 54 ++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 65a01f10..5c4e90f9 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -56,7 +56,7 @@ policy decides once, and what the definition drops. The render library reads it. | The Dev Portal's Organizations pages for everyone: `agentPlatform.organizations.enabled: true` in the Component's fragment (giantswarm/backstage#3393; an object-shaped key, which merges, so on a hand-kept portal too) | `organizations.portal.enabled`, or `organizations.enabled` on this installation; the choice read back from the fragment on record, else from the portal's own app-config, so every plan that renders a shared portal's fragment keeps the pages one installation turned on; off again only typed `false` where no installation of the portal has the switch on. Refused where no portal carries a section for the installation | | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | -| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`, `trusted` being the chart's default; and Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager`, always, and the overrides), the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, any override of `giantswarm-platform-manager`, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | +| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`, `trusted` being the chart's default; and Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager/giantswarm-platform-manager`, always, and the overrides), the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, any override of `giantswarm-platform-manager`, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/docs/governance.md b/docs/governance.md index bd78c8b4..ed27caa4 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -27,17 +27,59 @@ loosens them (`definitions/agent-platform/governance.yaml`, `platform`): | Part | Renders | What it does | |---|---|---| | The Platform Manager's role floors | `governance.roleFloors: {platformManager: [approve_action, merge_action]}` | muster asks a person before an agent approves or merges an Action of this manager, in both modes; the manager cannot tell an agent from a person, since muster forwards the person's identity | -| The Platform Manager as a governed server | `governedServers.giantswarm-platform-manager: {role: platformManager, safe: [...]}` | on `governed` every tool of this manager but its safe list asks agents; the floors hold in both modes | +| The Platform Manager as a governed server | `governedServers.giantswarm-platform-manager/giantswarm-platform-manager: {role: platformManager, safe: [...]}`: muster's key for the MCPServer `giantswarm-platform-manager` in the manager's release namespace, `giantswarm-platform-manager`, outside muster's (`agent-platform`) | on `governed` every tool of this manager but its safe list asks agents; the floors hold in both modes | | The connector admins | `muster.rbac.mcpServerEditor.subjects`: the groups `giantswarm-ad:giantswarm-admins` and `giantswarm-github:giantswarm:giantswarm-admins` | whoever holds muster's `mcpserver-editor` Role edits every connector in muster's namespace, sets its tool approval and alone lets an agent run a tool the connector asks for; the meta chart appends `tenants.platformTeam` | The role floors and the governed server are written where the meta chart takes the governance (the release `GovernanceChart`, the 4 line, no chart hold below it); the connector admins on every installation on the 4 line, which every chart there takes, with the same groups as the workflow editors (`muster.rbac.workflowEditor.subjects`, -muster's `workflow-editor` Role, who create, change and delete muster's workflows; decision #93). A `governance.governedServers` input for `giantswarm-platform-manager` is -refused; read back from the record it is the platform's entry and is rendered again. A server key of an -installation's own may take the role `platformManager`, which only adds its floors. muster from before decision -#92 builds the same floors in, so the plan reads a governance without `roleFloors` as having the platform's: -writing them changes nothing. +muster's `workflow-editor` Role, who create, change and delete muster's workflows; decision #93). A +`governance.governedServers` input naming the Platform Manager's server, under any key, is refused; read back from +the record the platform's entry is rendered again. A server key of an installation's own may take the role +`platformManager`, which only adds its floors. + +Neither muster nor the chart builds these parts in, so the plan reads a record without them as without them: +removing `roleFloors` or the Platform Manager's entry out of band is a loosening governance change, and putting +them on record the first time is a tightening one that asks the review once. + +### Release order + +The open-source chart and muster no longer govern the Platform Manager by themselves: a chart and muster that take +the governance on an installation whose values lack these parts let agents approve and merge Actions unasked. So +`GovernanceChart` and `GovernanceMuster` are set in the manager's release that precedes the chart release whose +`agent-platform.muster.governanceFloor` is set, and every 4-line installation is reconciled before the chart's +version range admits that release. `TestGovernanceGatesFollowTheChart` fails while the sibling agent-platform +checkout sets the floor and the gates are not set to it. The drift tests skip without sibling checkouts; CI should +set `AGENT_PLATFORM_CHECKOUT` and `MUSTER_CHECKOUT`. + +### Upgrading an installation by hand + +An installation the manager does not reconcile (one enabled by hand) carries the same parts in its agent-platform +values when it moves to the chart with tool approval; the chart's own defaults are placeholder groups and no +governed server of Giant Swarm's: + +```yaml +muster: + rbac: + mcpServerEditor: + subjects: + - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-ad:giantswarm-admins} + - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-github:giantswarm:giantswarm-admins} + workflowEditor: + subjects: + - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-ad:giantswarm-admins} + - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-github:giantswarm:giantswarm-admins} +governance: + roleFloors: + platformManager: [approve_action, merge_action] +governedServers: + giantswarm-platform-manager/giantswarm-platform-manager: + role: platformManager + safe: [get_info, list_installations, list_actions, get_action, verify_capability] +``` + +Write `governance.mode: governed` where an installation wrote `governance: governed`. Keep the editor lists +non-empty: muster's chart fails the upgrade on an empty list while its old `system:authenticated` binding exists. ## The inputs From 723dfda27ca56416da650720ffb579ddd68654fd Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 12:10:23 +0100 Subject: [PATCH 15/27] test(e2e): expect the platform's governance parts on record as a change of their own With absent role floors read as none, the first commit that puts Giant Swarm's governance parts on record is a tightening governance change; the tests that need no governance change start from a record that carries them (review F2). --- internal/e2e/governance_test.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index 654d31e3..ec2e6dfe 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -92,6 +92,10 @@ func requireLog(t *testing.T, st *stack, parts ...string) { t.Fatalf("no log line carries %q:\n%s", parts, st.logs.String()) } +// platformOnRecord is rowan's agent-platform values with Giant Swarm's own +// governance parts on record, as an earlier commit wrote them. +const platformOnRecord = "muster: {}\ngovernance:\n roleFloors:\n platformManager: [approve_action, merge_action]\ngovernedServers:\n giantswarm-platform-manager/giantswarm-platform-manager:\n role: platformManager\n safe: [get_info, list_installations, list_actions, get_action, verify_capability]\n" + const droppedKubernetes = "governedServers.mcp-kubernetes {role: infrastructure, 14 safe} → not governed (null)" func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { @@ -107,7 +111,7 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { t.Fatalf("a governance change on a test installation went without the review: %+v; next %q", a.Status.Approval, out.Next) } g, ok := a.Spec.Governance[rowan] - if !ok || len(g.Lines) != 2 || len(g.Loosens) != 1 || g.Loosens[0] != droppedKubernetes { + if !ok || len(g.Lines) != 4 || g.Lines[0] != "mode trusted → governed" || len(g.Loosens) != 1 || g.Loosens[0] != droppedKubernetes { t.Fatalf("the action's governance: %+v", a.Spec.Governance) } if after := a.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"mode":"governed"`) { @@ -272,12 +276,14 @@ func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) st := governedTestRowan(t) aliceC := st.mcpClient(t, aliceToken) marker := installations.Capabilities()[0].EnabledMarker(rowan) - st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, "governance:\n mode: governed\n") } - out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + st.ghs.addFile(acmeConfigs, marker, platformOnRecord) + moved := strings.Replace(platformOnRecord, "governance:\n", "governance:\n mode: governed\n", 1) + st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, moved) } + out, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) if isErr || out.Action == nil { t.Fatalf("commit: %v %s", isErr, text) } - if v, _ := st.ghs.file(acmeConfigs, marker); st.beforeOpen != nil || v != "governance:\n mode: governed\n" { + if v, _ := st.ghs.file(acmeConfigs, marker); st.beforeOpen != nil || v != moved { t.Fatalf("the hook did not run: %q", v) } if out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision == actions.DecisionNotRequired || out.Action.Status.Approval.ReviewID == "" { @@ -290,8 +296,9 @@ func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) // needs no review. func TestTestInstallationWithoutGovernanceChangeNeedsNoReview(t *testing.T) { st := governedTestRowan(t) + st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), platformOnRecord) aliceC := st.mcpClient(t, aliceToken) - out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}})}) + out, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}})}) if isErr || out.Action == nil || out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision != actions.DecisionNotRequired || len(out.Action.Spec.Governance) != 0 { t.Fatalf("commit: %v %s", isErr, text) } From 9fc393861fd4994c03cc3e90bda4b0e6f448d5d5 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 13:16:19 +0100 Subject: [PATCH 16/27] fix(tools): keep the governance baseline through unchanged values and snapshot-less actions A plan now compares the record's governance with what the last reviewed action left also when it writes the agent-platform values as they are on record, so an outside edit is named and logged rather than adopted. Only an action that recorded the governance it leaves can be the baseline; one without a snapshot is skipped, and actions are ordered by their stage's merge, ties by name and logged. A governance merged between the plan and the pull requests is recorded on the action (status.governance) as a loosening change, so its review shows it and only a member of the reviewers' team approves it, for a commit and a wave alike (review D-GO-01, D-GO-02, D-GO-07, D-GO-11). --- .../templates/crd-actions.yaml | 12 ++ internal/actions/actions.go | 25 ++++ internal/e2e/governance_test.go | 119 ++++++++++++++++++ internal/plan/governance.go | 19 ++- internal/tools/approval.go | 6 +- internal/tools/commit.go | 16 +-- internal/tools/governance.go | 74 +++++++++-- internal/tools/governance_test.go | 36 +++++- internal/tools/resync.go | 2 +- internal/tools/wave.go | 11 +- 10 files changed, 288 insertions(+), 32 deletions(-) diff --git a/helm/giantswarm-platform-manager/templates/crd-actions.yaml b/helm/giantswarm-platform-manager/templates/crd-actions.yaml index db1a934d..61110b1a 100644 --- a/helm/giantswarm-platform-manager/templates/crd-actions.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-actions.yaml @@ -162,6 +162,18 @@ spec: status: type: object properties: + governance: + description: Per installation, a governance change found after the commit recorded the Action (the values on the default branch moved between the plan and the pull requests); it counts as spec.governance does. Values only. + type: object + additionalProperties: + type: object + properties: + lines: + type: array + items: {type: string} + loosens: + type: array + items: {type: string} keptByInstallation: description: Verification snapshots of legacy actions, read from committed values. Identifiers and hashes only. type: object diff --git a/internal/actions/actions.go b/internal/actions/actions.go index 76d193cf..e272c9ad 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -183,6 +183,11 @@ type Status struct { // reverted: who withdrew it, why and when (deny_action on a merged // action). The review's thread carries the same. Withdrawal *Withdrawal `json:"withdrawal,omitempty"` + // Governance is, per installation, a governance change found after the + // commit recorded the Action: the values on the default branch moved + // between the plan and the pull requests, which write over what was + // merged meanwhile. It counts as spec.governance does (GovernanceOf). + Governance map[string]plan.GovernanceChange `json:"governance,omitempty"` } // CommitStatus fences approval until creation finishes and retains uncertain remote writes. @@ -683,3 +688,23 @@ func NewName(kind, installation string) (string, error) { } return kind + "-" + installation + "-" + string(suffix), nil } + +// GovernanceOf is, per installation, every governance change of a: what +// the commit recorded (spec.governance) and what was found after it +// (status.governance), the lines of both. +func GovernanceOf(a *Action) map[string]plan.GovernanceChange { + if len(a.Status.Governance) == 0 { + return a.Spec.Governance + } + out := map[string]plan.GovernanceChange{} + for n, g := range a.Spec.Governance { + out[n] = g + } + for n, g := range a.Status.Governance { + have := out[n] + have.Lines = append(append([]string{}, have.Lines...), g.Lines...) + have.Loosens = append(append([]string{}, have.Loosens...), g.Loosens...) + out[n] = have + } + return out +} diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index ec2e6dfe..d53ca1bf 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -13,6 +13,7 @@ import ( "slices" "strings" "testing" + "time" "github.com/giantswarm/gitops-commit/commit" @@ -365,3 +366,121 @@ func TestGovernanceMergedOutsideTheManagerIsAudited(t *testing.T) { } requireLog(t, st, "governance_change_merged_without_approval", "action="+out.Action.Name, "pullRequests="+acmeConfigs) } + +// governedThenTrustedOutside commits rowan governed, has it approved and +// merged, then takes governed out of the values in the repository directly. +func governedThenTrustedOutside(t *testing.T, st *stack) actions.Action { + t.Helper() + out, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + merged := approveAndMerge(t, st, out.Action.Name) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + values, _ := st.ghs.file(acmeConfigs, marker) + st.ghs.addFile(acmeConfigs, marker, strings.Replace(values, "\n mode: governed\n", "\n", 1)) + return merged +} + +// D-GO-01: an outside edit is seen even when the next plan writes the +// values file as it is on record: the dry run and the commit name it +// against the last reviewed action, and it is logged; nothing is adopted. +func TestGovernanceChangedOutsideIsSeenWhenTheValuesStayAsTheyAre(t *testing.T) { + st := governedTestRowan(t) + merged := governedThenTrustedOutside(t, st) + again, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr { + t.Fatalf("reconcile: %s", text) + } + if again.Action != nil || !strings.Contains(again.Next, "is not what the last reviewed action left") || again.Plan.Governance == nil || !strings.HasPrefix(again.Plan.Governance.Lines[0], "the governance on record differs from what action "+merged.Name+" left") { + t.Fatalf("an outside edit with the values unchanged: action %v, next %q, governance %+v", again.Action != nil, again.Next, again.Plan.Governance) + } + requireLog(t, st, "governance_on_record_changed_outside", "action="+merged.Name) +} + +// D-GO-02: an action that recorded no governance snapshot is no baseline: +// the one before it stands, so after an outside edit a later commit still +// asks the review. +func TestAnActionWithoutASnapshotErasesNoBaseline(t *testing.T) { + st := governedTestRowan(t) + merged := governedThenTrustedOutside(t, st) + // A newer merged action that needed no review and recorded no snapshot. + store := actions.New(st.dyn, actionsNamespace) + later := merged + later.Name, later.ResourceVersion, later.CreatedAt = merged.Name+"-later", "", merged.CreatedAt.Add(time.Minute) + later.Spec.Governance, later.Spec.GovernanceAfter = nil, nil + stored, err := store.Create(t.Context(), later) + if err != nil { + t.Fatal(err) + } + status := merged.Status + status.Approval = &actions.Approval{Decision: actions.DecisionNotRequired} + if _, err := store.UpdateStatus(t.Context(), stored, status); err != nil { + t.Fatal(err) + } + last, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{"sessions": map[string]any{"idleTTL": "2h"}})}) + if isErr || last.Action == nil { + t.Fatalf("reconcile: %v %s", isErr, text) + } + g := last.Action.Spec.Governance[rowan] + if last.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what action "+merged.Name+" left") { + t.Fatalf("a commit after a snapshot-less action: %+v %+v", last.Action.Status.Approval, g) + } +} + +// D-GO-11: an action merged without the team's decision is no baseline: +// what it left counts as changed outside. +func TestAnActionMergedWithoutApprovalIsNoBaseline(t *testing.T) { + st := governedTestRowan(t) + merged := governedThenTrustedOutside(t, st) + store := actions.New(st.dyn, actionsNamespace) + later := merged + later.Name, later.ResourceVersion, later.CreatedAt = merged.Name+"-outside", "", merged.CreatedAt.Add(time.Minute) + later.Spec.GovernanceAfter = map[string]string{rowan: `{"governance":{"roleFloors":{"platformManager":["approve_action","merge_action"]}}}`} + stored, err := store.Create(t.Context(), later) + if err != nil { + t.Fatal(err) + } + status := merged.Status + status.Approval = &actions.Approval{Decision: actions.DecisionMergedWithoutApproval} + if _, err := store.UpdateStatus(t.Context(), stored, status); err != nil { + t.Fatal(err) + } + again, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || again.Plan.Governance == nil || !strings.Contains(again.Plan.Governance.Lines[0], "what action "+merged.Name+" left") { + t.Fatalf("an action merged without approval as the baseline: %v %s", isErr, text) + } +} + +// D-GO-07, D-GO-11: a governance merged between a wave's plan and its pull +// requests is a governance change of the action: the review shows it and +// only an active member of the reviewers' team approves it. +func TestGovernanceMovedUnderAWaveIsAGovernanceChange(t *testing.T) { + st := governedTestRowan(t) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + st.ghs.addFile(acmeConfigs, marker, platformOnRecord) + st.beforeOpen = func() { + st.ghs.addFile(acmeConfigs, marker, strings.Replace(platformOnRecord, "governance:\n", "governance:\n mode: governed\n", 1)) + } + aliceC := st.mcpClient(t, aliceToken) + text, isErr := call(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallations: []string{rowan}, tools.ArgInputs: minimalInputs(nil), tools.ArgReason: commitReason, tools.ArgMode: string(tools.ModeCommit)}) + var w tools.WaveResult + if isErr || json.Unmarshal([]byte(text), &w) != nil || w.Action == nil { + t.Fatalf("wave commit: %v %s", isErr, text) + } + a := w.Action + g := a.Status.Governance[rowan] + if a.Status.Approval == nil || a.Status.Approval.ReviewID == "" || len(g.Loosens) != 1 || !strings.Contains(g.Loosens[0], "the governance on the default branch changed after the plan read it") { + t.Fatalf("a wave whose record moved: %+v %+v", a.Status.Approval, a.Status.Governance) + } + if posted := st.gateway.posted(); len(posted) != 1 || !strings.Contains(fmt.Sprint(posted[0].Body["text"]), "*It loosens governance:* rowan: the governance on the default branch changed") { + t.Fatalf("the review: %+v", posted) + } + requireLog(t, st, "governance_record_moved", "installation=rowan") + st.ghs.mu.Lock() + st.ghs.teams[governanceTeam][carol] = "pending" + st.ghs.mu.Unlock() + if _, text, isErr := decide(t, st.mcpClient(t, carolToken), tools.ToolApproveAction, map[string]any{tools.ArgAction: a.Name}); !isErr || !strings.Contains(text, "pending") { + t.Fatalf("an approve by a pending member: %v %s", isErr, text) + } +} diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 54e7f7af..5013ca34 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -118,14 +118,27 @@ func dig(m map[string]any, keys ...string) any { // false when p does not create or update them. unreadable: a side does not // parse or the plan does not carry it (an answer of paths only), which is // never read as a file without governance. +// +// A file the plan leaves unchanged counts too, both sides the record: a +// governance changed outside the manager is compared with what the last +// reviewed action left whether or not this plan writes the file. func GovernanceFile(p Installation) (current, next GovernanceSnapshot, ok, unreadable bool) { for _, f := range p.Files { - if !governanceFile(f.Path) || (f.Change != ChangeCreate && f.Change != ChangeUpdate) { + if !governanceFile(f.Path) || (f.Change != ChangeCreate && f.Change != ChangeUpdate && f.Change != ChangeUnchanged) { continue } - cur, err1 := GovernanceSnapshotOf(f.Current) + onRecord := f.Current + if f.Change == ChangeUnchanged && onRecord == "" { + if f.Content == "" { + // An answer of paths only: nothing to compare, and nothing + // it writes. + continue + } + onRecord = f.Content + } + cur, err1 := GovernanceSnapshotOf(onRecord) nxt, err2 := GovernanceSnapshotOf(f.Content) - missing := f.Content == "" || (f.Change == ChangeUpdate && f.Current == "") + missing := f.Content == "" || (f.Change != ChangeCreate && onRecord == "") return cur, nxt, true, err1 != nil || err2 != nil || missing } return nil, nil, false, false diff --git a/internal/tools/approval.go b/internal/tools/approval.go index 36608ec7..093490ad 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -145,7 +145,7 @@ func (t *Tools) approve(ctx context.Context, args map[string]any) (any, error) { return nil, fmt.Errorf("%s: action %s is yours (%s): a second person of the team decides; Deny withdraws it", ToolApproveAction, a.Name, id.Login) } membership := "" - if len(a.Spec.Governance) > 0 { + if len(actions.GovernanceOf(a)) > 0 { m, err := t.governanceReviewer(ctx, id) if err != nil { t.auditGovernance(ctx, "governance_change_approval_refused", a, "approver", id.Login, "reason", err.Error()) @@ -420,7 +420,7 @@ func decided(a *actions.Action) bool { case actions.DecisionApproved, actions.DecisionNotRequired: return true case actions.DecisionMergedWithoutApproval: - return len(a.Spec.Governance) == 0 + return len(actions.GovernanceOf(a)) == 0 } return false } @@ -563,7 +563,7 @@ func (t *Tools) requestApproval(ctx context.Context, a *actions.Action, tool str *a = *latest // A governance change is never one person's: the review stands on test // installations too, whatever the caller says. - if !test || len(a.Spec.Governance) > 0 { + if !test || len(actions.GovernanceOf(a)) > 0 { return t.askApproval(ctx, a, tool) } status := a.Status diff --git a/internal/tools/commit.go b/internal/tools/commit.go index dca78b5e..6d1aeeb8 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -222,14 +222,16 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri return nil, t.fail(ctx, tool, a, remote, prs, err) } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "installation", one, "state", a.Status.State, "pullRequests", len(prs)) - if test { - // The plan read the record moments ago and the branch was cut from - // the default branch since: a governance merged in between would be - // written over without anyone seeing it, so it asks the review. - if moved, what := t.governanceRecordMoved(ctx, p); moved { - t.d.Log.Warn("governance_record_moved", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", one, "governance", what) - test = false + // The plan read the record moments ago and the branch was cut from the + // default branch since: a governance merged in between would be written + // over without anyone seeing it, so it is recorded as a governance change + // of the action (status.governance): the review, its governance block and + // the reviewers' team check follow. + if moved, what := t.governanceRecordMoved(ctx, p); moved { + if a, err = t.recordMoved(ctx, a, one, what); err != nil { + return nil, t.fail(ctx, tool, a, remote, prs, err) } + test = false } t.auditGovernance(ctx, "governance_change_committed", a) a, err = t.requestApproval(ctx, a, tool, test) diff --git a/internal/tools/governance.go b/internal/tools/governance.go index a4beea2c..9121156c 100644 --- a/internal/tools/governance.go +++ b/internal/tools/governance.go @@ -7,6 +7,7 @@ import ( "maps" "slices" "strings" + "time" "unicode/utf8" "github.com/giantswarm/giantswarm-platform-manager/internal/actions" @@ -50,6 +51,12 @@ func (t *Tools) governanceBaseline(ctx context.Context, installation string) (pl t.d.Log.Warn("governance_baseline_unread", identity.LogAttr(ctx), "installation", installation, "error", err.Error()) return nil, "", false } + type candidate struct { + name string + mergedAt time.Time + snap plan.GovernanceSnapshot + } + var found []candidate for _, a := range list { if a.CapabilityOf(installation) != installations.AgentPlatform || !slices.Contains(baselineStates, a.Status.State) || !allMerged(&a, installation) || len(a.StagePullRequests(installation)) == 0 { continue @@ -57,17 +64,40 @@ func (t *Tools) governanceBaseline(ctx context.Context, installation string) (pl if a.Status.Approval == nil || (a.Status.Approval.Decision != actions.DecisionApproved && a.Status.Approval.Decision != actions.DecisionNotRequired) { continue } + // Only an action that recorded the governance it leaves is a + // baseline; one without (from before the field) carries none, and + // the one before it stands. raw, ok := a.Spec.GovernanceAfter[installation] if !ok { - return nil, "", false + continue } snap, err := plan.ParseGovernanceSnapshot(raw) if err != nil { - return nil, "", false + continue + } + c := candidate{name: a.Name, mergedAt: a.CreatedAt, snap: snap} + for _, k := range a.StagePullRequests(installation) { + if at := a.Status.PullRequests[k].MergedAt; at != nil && at.After(c.mergedAt) { + c.mergedAt = *at + } } - return snap, a.Name, true + found = append(found, c) } - return nil, "", false + if len(found) == 0 { + return nil, "", false + } + // The newest merge is the baseline. Actions merged within one second are + // told apart by name; where they left different governance it is logged. + slices.SortStableFunc(found, func(x, y candidate) int { + if c := y.mergedAt.Compare(x.mergedAt); c != 0 { + return c + } + return strings.Compare(y.name, x.name) + }) + if len(found) > 1 && found[0].mergedAt.Equal(found[1].mergedAt) && len(plan.GovernanceBetween(found[0].snap, found[1].snap).Lines) > 0 { + t.d.Log.Warn("governance_baseline_ambiguous", identity.LogAttr(ctx), "installation", installation, "actions", found[0].name+","+found[1].name) + } + return found[0].snap, found[0].name, true } // governanceOutside is the line of a plan whose record differs from what @@ -200,6 +230,28 @@ func (t *Tools) governanceRecordMoved(ctx context.Context, p plan.Installation) return false, "" } +// governanceMoved leads the change found when the values on the default +// branch moved between the plan and the pull requests. +const governanceMoved = "the governance on the default branch changed after the plan read it, and the pull requests write over it: " + +// recordMoved logs governance_record_moved and records what moved as a +// loosening governance change of a on installation (status.governance). +func (t *Tools) recordMoved(ctx context.Context, a *actions.Action, installation, what string) (*actions.Action, error) { + t.d.Log.Warn("governance_record_moved", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "governance", what) + status := a.Status + status.Governance = maps.Clone(status.Governance) + if status.Governance == nil { + status.Governance = map[string]plan.GovernanceChange{} + } + line := governanceMoved + what + status.Governance[installation] = plan.GovernanceChange{Lines: []string{line}, Loosens: []string{line}} + out, err := t.d.Actions.UpdateStatus(ctx, a, status) + if err != nil { + return a, fmt.Errorf("the governance that moved under the plan could not be recorded on action %s: %w", a.Name, err) + } + return out, nil +} + // governanceReviewer refuses an approver of a governance change who is not // an active member of the governance reviewers' team (approvals.governanceTeam, // org/team), or not a person (a GitHub account of type User), read as the @@ -250,7 +302,7 @@ const ( func governanceLoosens(a *actions.Action) string { var loosens []string for _, n := range governedInstallations(a) { - if g := a.Spec.Governance[n]; len(g.Loosens) > 0 { + if g := actions.GovernanceOf(a)[n]; len(g.Loosens) > 0 { loosens = append(loosens, n+": "+strings.Join(g.Loosens, "; ")) } } @@ -275,7 +327,7 @@ func governanceTooLarge(tool string, a *actions.Action) error { // cut at governanceReviewMax with the configs pull request named for the // rest. Empty for an action that changes none. func governanceText(a *actions.Action) string { - if len(a.Spec.Governance) == 0 { + if len(actions.GovernanceOf(a)) == 0 { return "" } var b strings.Builder @@ -283,7 +335,7 @@ func governanceText(a *actions.Action) string { b.WriteString(governanceLoosens(a)) cut := 0 for _, n := range governedInstallations(a) { - line := "\n• " + n + ": " + strings.Join(a.Spec.Governance[n].Lines, "; ") + line := "\n• " + n + ": " + strings.Join(actions.GovernanceOf(a)[n].Lines, "; ") if utf8.RuneCountInString(b.String())+utf8.RuneCountInString(line) > governanceReviewMax { cut++ continue @@ -316,11 +368,11 @@ func configsLinks(a *actions.Action) string { func governedInstallations(a *actions.Action) []string { var out []string for _, n := range a.Spec.Installations { - if _, ok := a.Spec.Governance[n]; ok { + if _, ok := actions.GovernanceOf(a)[n]; ok { out = append(out, n) } } - for _, n := range slices.Sorted(maps.Keys(a.Spec.Governance)) { + for _, n := range slices.Sorted(maps.Keys(actions.GovernanceOf(a))) { if !slices.Contains(out, n) { out = append(out, n) } @@ -338,7 +390,7 @@ func (t *Tools) auditGovernance(ctx context.Context, event string, a *actions.Ac decidedBy, decision = a.Status.Approval.DecidedBy, a.Status.Approval.Decision } for _, n := range governedInstallations(a) { - g := a.Spec.Governance[n] + g := actions.GovernanceOf(a)[n] args := []any{identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", n, "actor", a.Spec.Actor.Login, "decision", decision, "decidedBy", decidedBy, "governance", strings.Join(g.Lines, "; "), "loosens", len(g.Loosens) > 0} t.d.Log.Info(event, append(args, extra...)...) @@ -348,7 +400,7 @@ func (t *Tools) auditGovernance(ctx context.Context, event string, a *actions.Ac // auditGovernanceStage logs event for one installation of a, with the pull // requests of its stage and their heads: a merge is audited per stage. func (t *Tools) auditGovernanceStage(ctx context.Context, event string, a *actions.Action, installation string, prs []actions.PullRequest) { - g, ok := a.Spec.Governance[installation] + g, ok := actions.GovernanceOf(a)[installation] if !ok { return } diff --git a/internal/tools/governance_test.go b/internal/tools/governance_test.go index 7a0fe40f..7ff4b8a1 100644 --- a/internal/tools/governance_test.go +++ b/internal/tools/governance_test.go @@ -5,14 +5,24 @@ import ( "context" "fmt" "log/slog" + "net/http" + "net/http/httptest" "strings" "testing" "github.com/giantswarm/giantswarm-platform-manager/internal/actions" + "github.com/giantswarm/giantswarm-platform-manager/internal/gh" + "github.com/giantswarm/giantswarm-platform-manager/internal/identity" "github.com/giantswarm/giantswarm-platform-manager/internal/installations" "github.com/giantswarm/giantswarm-platform-manager/internal/plan" ) +// rowan's agent-platform values and an empty values document. +const ( + rowanValues = "installations/rowan/apps/agent-platform/configmap-values.yaml.patch" + emptyValues = "global: {}\n" +) + // governedAction is an action on garm whose commit makes the platform // governed and drops a source from the governed servers. func governedAction() *actions.Action { @@ -72,7 +82,7 @@ func TestReviewTextKeepsWhatLoosensWhole(t *testing.T) { } current := "governance: governed\ngovernedServers:\n agent-manager:\n safe: [get_info]\n" next := "governance: governed\ngovernedServers:\n a-inventory:\n role: infrastructure\n safe: [" + strings.Join(pad, ", ") + "]\n agent-manager:\n safe: [get_info, create_agent, update_agent_access]\n" - p := plan.Installation{Name: rowan, Files: []plan.File{{Path: "installations/rowan/apps/agent-platform/configmap-values.yaml.patch", Change: plan.ChangeUpdate, Current: current, Content: next}}} + p := plan.Installation{Name: rowan, Files: []plan.File{{Path: rowanValues, Change: plan.ChangeUpdate, Current: current, Content: next}}} g, ok := plan.GovernanceOf(p) if !ok { t.Fatal("no change") @@ -127,3 +137,27 @@ func TestGovernanceStoredOrRefused(t *testing.T) { t.Fatal(err) } } + +// D-GO-11: agent-platform values that do not parse are a loosening +// governance change on the path commits use, never none. +func TestGovernanceChangeOfUnreadableValues(t *testing.T) { + tl := &Tools{d: Deps{Log: slog.New(slog.DiscardHandler)}} + p := plan.Installation{Name: rowan, Files: []plan.File{{Path: rowanValues, Change: plan.ChangeUpdate, Current: "governance: [\n", Content: emptyValues}}} + g, after := tl.governanceChange(context.Background(), p) + if g == nil || len(g.Loosens) != 1 || after != "" { + t.Fatalf("unreadable values: %+v %q", g, after) + } +} + +// D-GO-11: values on the default branch that cannot be read again count as +// moved (fail closed). +func TestGovernanceRecordMovedWhenTheValuesCannotBeRead(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusBadGateway) })) + t.Cleanup(srv.Close) + tl := &Tools{d: Deps{Log: slog.New(slog.DiscardHandler), GitHubAPIURL: srv.URL + "/api/v3", Files: gh.NewFiles(0)}} + p := plan.Installation{Name: rowan, Files: []plan.File{{Repository: "giantswarm/acme-configs", Path: rowanValues, Change: plan.ChangeUpdate, Current: emptyValues, Content: emptyValues}}} + ctx := identity.ContextWithToken(context.Background(), "token") + if moved, what := tl.governanceRecordMoved(ctx, p); !moved || !strings.Contains(what, "could not be read again") { + t.Fatalf("an unreadable default branch: %v %q", moved, what) + } +} diff --git a/internal/tools/resync.go b/internal/tools/resync.go index 32c73aad..5bc1ac96 100644 --- a/internal/tools/resync.go +++ b/internal/tools/resync.go @@ -175,7 +175,7 @@ func (t *Tools) resync(ctx context.Context, c *gh.Client, id *identity.Identity, // without the team's approval, in any state of the action, whoever // merged it: the repositories' merge path let it through, and only their // branch protection stood between one person and the change. - if len(merged) > 0 && len(a.Spec.Governance) > 0 && (status.Approval == nil || status.Approval.Decision != actions.DecisionApproved) { + if len(merged) > 0 && len(actions.GovernanceOf(a)) > 0 && (status.Approval == nil || status.Approval.Decision != actions.DecisionApproved) { t.auditGovernanceStage(ctx, "governance_change_merged_without_approval", &fresh, mergedStage(&fresh, merged), merged) } var posts []string diff --git a/internal/tools/wave.go b/internal/tools/wave.go index 78809ce1..d1e342c2 100644 --- a/internal/tools/wave.go +++ b/internal/tools/wave.go @@ -206,13 +206,12 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string } t.d.Log.Info(tool, identity.LogAttr(ctx), "action", a.Name, "wave", strings.Join(res.Order, ","), "skipped", len(res.Skipped), "pullRequests", len(prs)) for _, p := range targets { - if !test { - break - } - // A governance merged between a stage's plan and its branch asks the - // review (commit.go). + // A governance merged between a stage's plan and its branch is a + // governance change of the action (commit.go). if moved, what := t.governanceRecordMoved(ctx, p); moved { - t.d.Log.Warn("governance_record_moved", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", p.Name, "governance", what) + if a, err = t.recordMoved(ctx, a, p.Name, what); err != nil { + return nil, t.fail(ctx, tool, a, remote, prs, err) + } test = false } } From 79d3de1ea4ac3ce4bf544fa2e9334b61f2b4e48d Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 13:16:19 +0100 Subject: [PATCH 17/27] docs: the governance baseline skips actions without a snapshot and sees unchanged values docs/governance.md says which actions are a baseline, that an outside edit is shown when the values are written unchanged, that a governance moved under the plan becomes a change of the action, and the new governance_baseline_ambiguous line (review D-GO-01, D-GO-02, D-GO-07). --- docs/governance.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/governance.md b/docs/governance.md index ed27caa4..2bab03d0 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -143,10 +143,13 @@ governance as it is, such as an explicit `trusted` dropped, is none. The plan compares against what the last reviewed action left, not against the record alone. Every Action records the governance its commit leaves (`spec.governanceAfter`; a disable's is the governance before it). The newest agent-platform action on the installation whose stage is merged and on record, approved by the team or -needing no review, is the baseline. When the record differs from it, the governance was changed outside the +needing no review, and that recorded the governance it leaves, is the baseline: an action without a snapshot +(from before the field) is skipped and the one before it stands. Actions are ordered by their stage's merge; +two merged in the same second are told apart by name and logged (`governance_baseline_ambiguous`). When the record differs from it, the governance was changed outside the manager: -- the plan, the dry run included, shows the change against the baseline, led by a loosening line that names the +- the plan, the dry run included, shows the change against the baseline, also when the plan writes the values + file as it is on record, led by a loosening line that names the action; - `governance_on_record_changed_outside` is logged; - the next commit asks the review, even when it types the governance back. A record that only a reviewed change @@ -155,8 +158,9 @@ manager: A `disable_capability` that deletes values carrying a governance is a loosening governance change. A later enable is compared with the governance before the disable, so bringing the platform back trusted asks the review too. -Between the plan and the pull requests the commit reads the values on the default branch again: a governance -merged in between asks the review (`governance_record_moved`). +Between the plan and the pull requests the commit or wave reads the values on the default branch again: a +governance merged in between is recorded as a loosening governance change of the action (`status.governance`), +so the review shows it and only a member of the reviewers' team approves it (`governance_record_moved`). ## A second person approves every change @@ -215,6 +219,7 @@ loosens. | `governance_change_merged_without_approval` | a pull request of it was merged outside the manager before the team approved, in any state of the action; read at the next read of the action | | `governance_on_record_changed_outside` | a plan found the record's governance other than what the last reviewed action left | | `governance_record_moved` | the values on the default branch changed between the plan and the pull requests | +| `governance_baseline_ambiguous` | two reviewed actions merged in the same second left different governance | ## What the manager does not cover From 46e4ff8ca13cc4e461e6430f3f6f46b8d62d6757 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 13:58:16 +0100 Subject: [PATCH 18/27] fix(plan): count who may loosen approvals as governance and mark more write verbs The platform team and the subjects of muster's connector-admin and workflow-editor bindings are part of the governance snapshot: a subject added widens who may loosen approvals and is a loosening change the team reviews, on test installations too; absent editor subjects read as the Giant Swarm groups the definition renders. The write mark reads more verbs (drain, cordon, upgrade, install, terminate, rollout, label, ...) and the words of camelCase names (decision #97, review D-GO-20, D-GO-24). --- definitions/agent-platform/schema.json | 2 +- docs/governance.md | 9 ++- internal/plan/governance.go | 80 +++++++++++++++++++++++++- internal/plan/governance_test.go | 46 +++++++++++++++ 4 files changed, 132 insertions(+), 5 deletions(-) diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index 13aafbec..879503a9 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -849,7 +849,7 @@ "x-readback": {"file": "configmap", "key": "tenants.platformTeam"}, "x-feature": "tool-access", "x-renders": ["configmap:tenants.platformTeam"], - "description": "The customer's platform team (tenants.platformTeam): RBAC subjects bound to agent-platform:editor in the kagent namespace beside tenants.platform.editors, and added to muster's mcpserver-editor and workflow-editor subjects. Unset, the chart's default: none. With tenants.platform.editors empty, the agent-platform:editor binding stays for the platform team alone. A broad system group (system:authenticated, system:unauthenticated, system:serviceaccounts or system:serviceaccounts:) is refused, typed or read back. The 4 chart line only; a hold of the meta chart below 4.132.0-rc.1 is refused." + "description": "The customer's platform team (tenants.platformTeam): RBAC subjects bound to agent-platform:editor in the kagent namespace beside tenants.platform.editors, and added to muster's mcpserver-editor and workflow-editor subjects. Unset, the chart's default: none. With tenants.platform.editors empty, the agent-platform:editor binding stays for the platform team alone. A broad system group (system:authenticated, system:unauthenticated, system:serviceaccounts or system:serviceaccounts:) is refused, typed or read back. A change is a governance change a second person approves, on test installations too: the platform team may loosen approvals. The 4 chart line only; a hold of the meta chart below 4.132.0-rc.1 is refused." } } }, diff --git a/docs/governance.md b/docs/governance.md index 2bab03d0..9283b020 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -137,7 +137,9 @@ carries the Platform Manager's role or entry must agree with the platform's. The plan compares the effective governance on both sides: the mode (absent is `trusted`), the role floors (a floor that goes loosens), every server as muster governs it (a source the values leave alone is the chart's entry), muster's own `muster.muster.governance`, and, -once `GovernanceMuster` is set, a `components.muster` hold below it. A change that leaves the effective +once `GovernanceMuster` is set, a `components.muster` hold below it, and who may loosen approvals: the platform +team and the subjects of muster's editor bindings (absent editor subjects read as the Giant Swarm groups the +definition renders). A change that leaves the effective governance as it is, such as an explicit `trusted` dropped, is none. The plan compares against what the last reviewed action left, not against the record alone. Every Action @@ -196,8 +198,11 @@ rest. A change loosens governance, or may, when any of these hold: - a source is no longer governed; - a role changes; - a safe entry is added, against the chart's list for a first override; one named like a write anywhere in its - name (`kubernetes_delete`, `port_forward`) or a floor of any role is marked; + name, camelCase words included (`kubernetes_delete`, `port_forward`, `drainNode`) or a floor of any role is marked; - muster's own governance changes, or a muster hold drops below the release that enforces it; +- who may loosen approvals widens: a subject added to `tenants.platformTeam` (which the meta chart adds to the + connector-admin and workflow-editor bindings) or to `muster.rbac.mcpServerEditor.subjects` or + `muster.rbac.workflowEditor.subjects` (decision #97); a subject removed tightens; - the record differs from what the last reviewed action left; - the agent-platform values cannot be read on either side. diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 5013ca34..d94c4bfa 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -5,6 +5,7 @@ import ( "fmt" "slices" "strings" + "unicode" "github.com/giantswarm/giantswarm-platform-manager/definitions" "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" @@ -35,6 +36,12 @@ const ( keyGovernedServers = "governedServers" keyMusterGovernance = "musterGovernance" keyMusterHold = "musterHold" + // Who may loosen approvals: the platform team, which the meta chart adds + // to muster's connector-admin and workflow-editor bindings, and those + // bindings' own subjects (decision #97). + keyPlatformTeam = "platformTeam" + keyConnectorAdmins = "connectorAdmins" + keyWorkflowEditors = "workflowEditors" modeGoverned = "governed" modeTrusted = "trusted" ) @@ -80,6 +87,15 @@ func GovernanceSnapshotOf(content string) (GovernanceSnapshot, error) { if v := dig(d, "components", "muster", "versionRange"); v != nil { out[keyMusterHold] = v } + if v := dig(d, "tenants", "platformTeam"); v != nil { + out[keyPlatformTeam] = v + } + if v := dig(d, "muster", "rbac", "mcpServerEditor", "subjects"); v != nil { + out[keyConnectorAdmins] = v + } + if v := dig(d, "muster", "rbac", "workflowEditor", "subjects"); v != nil { + out[keyWorkflowEditors] = v + } } return out, nil } @@ -207,6 +223,10 @@ func GovernanceBetween(old, next GovernanceSnapshot) GovernanceChange { if o, n := canonical(old[keyMusterGovernance]), canonical(next[keyMusterGovernance]); o != n { g.add(fmt.Sprintf("muster.muster.governance %s → %s", short(o), short(n)), true) } + p := definitions.Governance().Platform + g.subjects("tenants.platformTeam", subjectsOf(old[keyPlatformTeam], nil), subjectsOf(next[keyPlatformTeam], nil)) + g.subjects("muster.rbac.mcpServerEditor.subjects", subjectsOf(old[keyConnectorAdmins], p.ConnectorAdmins), subjectsOf(next[keyConnectorAdmins], p.ConnectorAdmins)) + g.subjects("muster.rbac.workflowEditor.subjects", subjectsOf(old[keyWorkflowEditors], p.WorkflowEditors), subjectsOf(next[keyWorkflowEditors], p.WorkflowEditors)) oh, nh := fmt.Sprint(orEmpty(old[keyMusterHold])), fmt.Sprint(orEmpty(next[keyMusterHold])) if oh != nh && (agentplatform.MusterHoldBelowGovernance(oh) || agentplatform.MusterHoldBelowGovernance(nh)) { g.add(fmt.Sprintf("muster hold %s → %s (below muster %s, which enforces the governance)", quoteOr(oh, "none"), quoteOr(nh, "none"), agentplatform.GovernanceMuster), agentplatform.MusterHoldBelowGovernance(nh)) @@ -226,6 +246,47 @@ func effectiveMode(v any) string { return clean(fmt.Sprint(v)) } +// subjectsOf are the RBAC subjects of a list as Kind:name (namespace/name +// for a ServiceAccount); absent, the given default: none for the platform +// team, the platform's groups for the editor bindings, which the definition +// renders and the released charts bound by default. +func subjectsOf(v any, absent []definitions.Subject) []string { + var out []string + list, ok := v.([]any) + if v == nil || !ok { + for _, s := range absent { + out = append(out, s.Kind+":"+s.Name) + } + return out + } + for _, e := range list { + m, _ := e.(map[string]any) + name := fmt.Sprint(m["name"]) + if ns, ok := m["namespace"]; ok && ns != nil { + name = fmt.Sprint(ns) + "/" + name + } + out = append(out, clean(fmt.Sprint(m["kind"])+":"+name)) + } + return out +} + +// subjects compares who a binding names: a subject added widens who may +// loosen approvals and loosens; one removed tightens. +func (g *GovernanceChange) subjects(at string, old, next []string) { + added, removed := notIn(next, old), notIn(old, next) + if len(added)+len(removed) == 0 { + return + } + var parts []string + for _, s := range added { + parts = append(parts, "+"+s) + } + for _, s := range removed { + parts = append(parts, "−"+s) + } + g.add(at+" "+strings.Join(parts, " "), len(added) > 0) +} + // roleFloorsOf are the role floors the meta chart's governance carries; // none written are none: neither the open-source chart nor muster carries // the platform's (decision #92), so a record without them has none, and @@ -407,13 +468,13 @@ func floorsIn(safe []string) bool { // writeVerbs are the words of a tool name that changes something: a safe // entry with one anywhere in its name is marked, so the second person looks // twice. -var writeVerbs = []string{"add", "apply", "approve", "authorize", "cancel", "connect", "create", "delete", "deny", "deploy", "disable", "enable", "exec", "fork", "forward", "grant", "invoke", "kill", "merge", "patch", "push", "remove", "replace", "restart", "revoke", "rotate", "run", "scale", "set", "start", "stop", "sync", "update", "use", "write"} +var writeVerbs = []string{"add", "apply", "approve", "authorize", "cancel", "connect", "cordon", "create", "delete", "deny", "deploy", "destroy", "disable", "drain", "edit", "enable", "evict", "exec", "fork", "forward", "grant", "install", "invoke", "kill", "label", "merge", "modify", "patch", "purge", "push", "remove", "replace", "reset", "restart", "revoke", "rollback", "rollout", "rotate", "run", "scale", "set", "start", "stop", "suspend", "sync", "taint", "terminate", "uncordon", "uninstall", "update", "upgrade", "use", "write"} func entryNote(tool string) string { if role := definitions.Governance().FloorRole(tool); role != "" { return " (a floor of " + role + ")" } - for _, word := range strings.FieldsFunc(strings.ToLower(tool), func(r rune) bool { return r == '_' || r == '-' || r == '.' }) { + for _, word := range strings.FieldsFunc(strings.ToLower(splitCamel(tool)), func(r rune) bool { return r == '_' || r == '-' || r == '.' }) { if slices.Contains(writeVerbs, word) { return " (named like a write)" } @@ -421,6 +482,21 @@ func entryNote(tool string) string { return "" } +// splitCamel puts an underscore before each upper-case letter that follows +// a lower-case one or a digit: deleteNode reads delete_Node. +func splitCamel(s string) string { + var b strings.Builder + var prev rune + for i, r := range s { + if i > 0 && unicode.IsUpper(r) && (unicode.IsLower(prev) || unicode.IsDigit(prev)) { + b.WriteRune('_') + } + b.WriteRune(r) + prev = r + } + return b.String() +} + // clean keeps a value from the values safe to show in Slack's markup: a // character outside a tool or key name's and a value's punctuation // (letters, digits, _ . - / : @ space { } [ ] , " =), and < > & as diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index e14b81d3..416d4971 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -200,3 +200,49 @@ func TestGovernanceMapWithRoleFloors(t *testing.T) { t.Fatalf("mode and a floor gone: %v %+v", ok, g) } } + +// D-GO-20: the write mark reads every verb that changes a cluster, and the +// words of a camelCase name. +func TestWriteVerbsAreMarked(t *testing.T) { + for _, tool := range []string{"drain_node", "cordon_node", "edit_config", "upgrade_release", "install_chart", "uninstall_chart", "reset_password", "terminate_instance", "rollout_restart", "label_node", "evict_pod", "deleteNode", "createAgent", "kubernetesDrain"} { + if entryNote(tool) != " (named like a write)" { + t.Errorf("%s is not marked", tool) + } + } + for _, tool := range []string{"get_info", "listNodes", "describe"} { + if note := entryNote(tool); note != "" { + t.Errorf("%s is marked: %q", tool, note) + } + } +} + +// D-GO-24: who may loosen approvals is governance: the platform team (added +// to muster's connector-admin and workflow-editor bindings) and the editor +// subjects themselves. Widening loosens, narrowing tightens; the Giant Swarm +// groups written where nothing was are what the chart bound before (no +// change). +func TestWhoMayLoosenApprovalsIsGovernance(t *testing.T) { + const team = "tenants:\n platformTeam:\n - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: oidc:platform-team}\n" + g, ok := GovernanceOf(govPlan(govEmpty, team)) + if !ok || !slices.Equal(g.Loosens, []string{"tenants.platformTeam +Group:oidc:platform-team"}) { + t.Fatalf("a platform team added: %v %+v", ok, g) + } + g, ok = GovernanceOf(govPlan(team, govEmpty)) + if !ok || len(g.Loosens) != 0 || !slices.Equal(g.Lines, []string{"tenants.platformTeam −Group:oidc:platform-team"}) { + t.Fatalf("a platform team removed: %v %+v", ok, g) + } + const ours = "muster:\n rbac:\n mcpServerEditor:\n subjects:\n - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-ad:giantswarm-admins}\n - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: giantswarm-github:giantswarm:giantswarm-admins}\n" + if g, ok := GovernanceOf(govPlan(govEmpty, ours)); ok { + t.Fatalf("the platform's connector admins written: %+v", g) + } + wider := ours + " - {apiGroup: rbac.authorization.k8s.io, kind: Group, name: system:authenticated}\n" + g, ok = GovernanceOf(govPlan(ours, wider)) + if !ok || !slices.Equal(g.Loosens, []string{"muster.rbac.mcpServerEditor.subjects +Group:system:authenticated"}) { + t.Fatalf("a connector admin added: %v %+v", ok, g) + } + editors := "muster:\n rbac:\n workflowEditor:\n subjects:\n - {apiGroup: rbac.authorization.k8s.io, kind: User, name: mallory}\n" + g, ok = GovernanceOf(govPlan(govEmpty, editors)) + if !ok || len(g.Loosens) != 1 || !strings.HasPrefix(g.Loosens[0], "muster.rbac.workflowEditor.subjects +User:mallory −Group:giantswarm-ad:giantswarm-admins") { + t.Fatalf("a workflow editor added: %v %+v", ok, g) + } +} From 1d34eeb75ceb8070db2e6ba3f1f1785d0c368c2c Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 13:58:40 +0100 Subject: [PATCH 19/27] style(plan): align the governance constants as gofmt does --- internal/plan/governance.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/plan/governance.go b/internal/plan/governance.go index d94c4bfa..999876bf 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -42,8 +42,8 @@ const ( keyPlatformTeam = "platformTeam" keyConnectorAdmins = "connectorAdmins" keyWorkflowEditors = "workflowEditors" - modeGoverned = "governed" - modeTrusted = "trusted" + modeGoverned = "governed" + modeTrusted = "trusted" ) // governanceUnreadable is the line of a plan whose agent-platform values From aab6f081b40bc8b4a3305a7c38fee44693791f31 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 14:45:30 +0100 Subject: [PATCH 20/27] feat(tools): keep a reviewed-governance record per installation and compare every plan with it The governance a plan is compared with is no longer derived from the Actions' order or states. A GovernanceRecord per installation, in the manager's namespace and written only by its ServiceAccount, holds what the team last reviewed: merge_action writes it when it merges the stage of an approved governance change, with the approver and the configs pull request's merged head. Every plan compares the configs repository with it, so an edit outside the manager, a revert by hand or an older action merged after a newer one is an unreviewed change the next commit asks the team to confirm or restore. An installation without a record asks the review while its governance is in play (fail closed; its first reviewed commit records it), and a reviewed change reverted by hand is audited (decision #99, review D-GO-25, D-GO-26, D-GO-31). --- .../templates/crd-governancerecords.yaml | 62 +++++ .../templates/rbac.yaml | 5 + internal/actions/actions.go | 6 +- internal/actions/records.go | 99 ++++++++ internal/e2e/governance_test.go | 178 +++++++++++++- internal/e2e/identity_chain_test.go | 2 +- internal/plan/governance.go | 9 + internal/plan/governance_test.go | 12 + internal/tools/approval.go | 5 + internal/tools/commit.go | 2 +- internal/tools/governance.go | 221 +++++++++--------- internal/tools/governance_test.go | 56 +++++ internal/tools/resync.go | 1 + internal/tools/revert.go | 4 + internal/tools/server.go | 8 + 15 files changed, 550 insertions(+), 120 deletions(-) create mode 100644 helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml create mode 100644 internal/actions/records.go diff --git a/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml new file mode 100644 index 00000000..4d0e97b0 --- /dev/null +++ b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml @@ -0,0 +1,62 @@ +{{- if and .Values.actions.enabled .Values.actions.installCRD }} +# The reviewed-governance record (Governing tool calls, decision #99): one per +# installation, named after it, the governance the team last reviewed there. +# Written only by the manager's merge_action when an approved governance +# change is merged through the manager; every plan compares the configs +# repository's governance with it. No person holds a right on it. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: governancerecords.platform-manager.giantswarm.io + labels: + {{- include "giantswarm-platform-manager.labels" . | nindent 4 }} +spec: + group: platform-manager.giantswarm.io + scope: Namespaced + names: + kind: GovernanceRecord + listKind: GovernanceRecordList + plural: governancerecords + singular: governancerecord + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Action + type: string + jsonPath: .spec.action + - name: Approved by + type: string + jsonPath: .spec.approvedBy + - name: Recorded + type: string + jsonPath: .spec.recordedAt + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + spec: + type: object + required: [installation, governance, action, approvedBy, recordedAt] + properties: + installation: + description: The installation the record is for (the object's name). + type: string + governance: + description: The reviewed governance, as JSON of the governance values (mode, role floors, governed servers, muster's own governance, the muster hold, the platform team and the editor subjects). Values only, never a secret. + type: string + action: + description: The Action whose merge wrote it. + type: string + approvedBy: + description: The team member who approved that Action. + type: string + headSHA: + description: The merged head of that Action's configs pull request. + type: string + recordedAt: + description: When it was written (RFC 3339). + type: string +{{- end }} diff --git a/helm/giantswarm-platform-manager/templates/rbac.yaml b/helm/giantswarm-platform-manager/templates/rbac.yaml index e6a1e268..a254031e 100644 --- a/helm/giantswarm-platform-manager/templates/rbac.yaml +++ b/helm/giantswarm-platform-manager/templates/rbac.yaml @@ -14,6 +14,11 @@ rules: - apiGroups: ["platform-manager.giantswarm.io"] resources: ["actions/status"] verbs: ["get", "update", "patch"] + # The reviewed-governance records, one per installation, written only by + # merge_action when an approved governance change is merged. + - apiGroups: ["platform-manager.giantswarm.io"] + resources: ["governancerecords"] + verbs: ["get", "list", "watch", "create", "update"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/internal/actions/actions.go b/internal/actions/actions.go index e272c9ad..cd05e3e3 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -126,9 +126,9 @@ type Spec struct { Governance map[string]plan.GovernanceChange `json:"governance,omitempty"` // GovernanceAfter is, per installation, the governance the commit leaves // on record (plan.GovernanceSnapshot as JSON; a disable's is the - // governance before it): the next plan compares against the newest - // reviewed one, so a change made outside the manager, or a disable - // followed by an enable, is a governance change again. Values only. + // governance before it): what merge_action writes to the installation's + // reviewed-governance record (GovernanceRecord) once the team approved a + // governance change of the action. Values only. GovernanceAfter map[string]string `json:"governanceAfter,omitempty"` } diff --git a/internal/actions/records.go b/internal/actions/records.go new file mode 100644 index 00000000..391c5f23 --- /dev/null +++ b/internal/actions/records.go @@ -0,0 +1,99 @@ +package actions + +import ( + "context" + "fmt" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// The reviewed-governance record (decision #99): one per installation, the +// governance the team last reviewed there, written only by merge_action +// when an approved governance change of an Action is merged through the +// manager. It is never derived from the Actions' order or states: every plan +// compares the configs repository's governance with it, and a difference it +// does not explain (an edit outside the manager, a revert by hand, an action +// merged out of order) is an unreviewed change the next commit asks the team +// to confirm or restore. Only the manager's ServiceAccount writes it. +const ( + RecordKind = "GovernanceRecord" + RecordResource = "governancerecords" +) + +// RecordGVR is the reviewed-governance record's resource. +var RecordGVR = schema.GroupVersionResource{Group: Group, Version: Version, Resource: RecordResource} + +// GovernanceRecord is what the team last reviewed for an installation. +type GovernanceRecord struct { + ResourceVersion string `json:"-"` + // Installation names the record (the object's name). + Installation string `json:"installation"` + // Governance is the reviewed governance as plan.GovernanceSnapshot JSON. + Governance string `json:"governance"` + // Action is the Action whose merge wrote it, ApprovedBy who approved it, + // HeadSHA the configs pull request's merged head. + Action string `json:"action"` + ApprovedBy string `json:"approvedBy"` + HeadSHA string `json:"headSHA,omitempty"` + // RecordedAt is when it was written, RFC 3339. + RecordedAt string `json:"recordedAt"` +} + +// RecordStore reads and writes the reviewed-governance records. +type RecordStore interface { + // GetRecord answers ErrNotFound for an installation without a record. + GetRecord(ctx context.Context, installation string) (*GovernanceRecord, error) + // PutRecord creates or replaces an installation's record. + PutRecord(ctx context.Context, r GovernanceRecord) error +} + +// GetRecord reads installation's reviewed-governance record. +func (c *Client) GetRecord(ctx context.Context, installation string) (*GovernanceRecord, error) { + u, err := c.c.Resource(RecordGVR).Namespace(c.ns).Get(ctx, installation, metav1.GetOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + return nil, fmt.Errorf("%w: governance record %s/%s", ErrNotFound, c.ns, installation) + } + return nil, fmt.Errorf("actions: get governance record %s/%s: %w", c.ns, installation, err) + } + var r GovernanceRecord + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object["spec"].(map[string]any), &r); err != nil { + return nil, fmt.Errorf("actions: governance record %s/%s: %w", c.ns, installation, err) + } + r.ResourceVersion = u.GetResourceVersion() + return &r, nil +} + +// PutRecord creates installation's record, or replaces it. +func (c *Client) PutRecord(ctx context.Context, r GovernanceRecord) error { + if r.RecordedAt == "" { + r.RecordedAt = time.Now().UTC().Format(time.RFC3339) + } + spec, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&r) + if err != nil { + return err + } + u := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": Group + "/" + Version, "kind": RecordKind, + "metadata": map[string]any{"name": r.Installation, "namespace": c.ns}, + "spec": spec, + }} + res := c.c.Resource(RecordGVR).Namespace(c.ns) + old, err := res.Get(ctx, r.Installation, metav1.GetOptions{}) + switch { + case apierrors.IsNotFound(err): + _, err = res.Create(ctx, u, metav1.CreateOptions{}) + case err == nil: + u.SetResourceVersion(old.GetResourceVersion()) + _, err = res.Update(ctx, u, metav1.UpdateOptions{}) + } + if err != nil { + return fmt.Errorf("actions: write governance record %s/%s: %w", c.ns, r.Installation, err) + } + return nil +} diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index d53ca1bf..4bfc6703 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -19,6 +19,7 @@ import ( "github.com/giantswarm/giantswarm-platform-manager/internal/actions" "github.com/giantswarm/giantswarm-platform-manager/internal/installations" + "github.com/giantswarm/giantswarm-platform-manager/internal/plan" "github.com/giantswarm/giantswarm-platform-manager/internal/tools" "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" "github.com/giantswarm/giantswarm-platform-manager/render/clustermcpservers" @@ -28,6 +29,8 @@ import ( const ( keyGovernanceInput = "governance" keyMode = "mode" + keyIdleTTL = "idleTTL" + keySessions = "sessions" ) // withGovernanceReleases takes the meta chart and muster releases that @@ -97,6 +100,19 @@ func requireLog(t *testing.T, st *stack, parts ...string) { // governance parts on record, as an earlier commit wrote them. const platformOnRecord = "muster: {}\ngovernance:\n roleFloors:\n platformManager: [approve_action, merge_action]\ngovernedServers:\n giantswarm-platform-manager/giantswarm-platform-manager:\n role: platformManager\n safe: [get_info, list_installations, list_actions, get_action, verify_capability]\n" +// seedRecord writes rowan's reviewed-governance record as the governance +// values carries, as a reviewed merge through the manager would. +func seedRecord(t *testing.T, st *stack, values string) { + t.Helper() + snap, err := plan.GovernanceSnapshotOf(values) + if err != nil { + t.Fatal(err) + } + if err := actions.New(st.dyn, actionsNamespace).PutRecord(t.Context(), actions.GovernanceRecord{Installation: rowan, Governance: snap.JSON(), Action: "seeded", ApprovedBy: carol}); err != nil { + t.Fatal(err) + } +} + const droppedKubernetes = "governedServers.mcp-kubernetes {role: infrastructure, 14 safe} → not governed (null)" func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { @@ -112,7 +128,7 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { t.Fatalf("a governance change on a test installation went without the review: %+v; next %q", a.Status.Approval, out.Next) } g, ok := a.Spec.Governance[rowan] - if !ok || len(g.Lines) != 4 || g.Lines[0] != "mode trusted → governed" || len(g.Loosens) != 1 || g.Loosens[0] != droppedKubernetes { + if !ok || len(g.Lines) != 5 || !strings.HasPrefix(g.Lines[0], "no reviewed governance is on record for rowan") || g.Lines[1] != "mode trusted → governed" || len(g.Loosens) != 2 || g.Loosens[1] != droppedKubernetes { t.Fatalf("the action's governance: %+v", a.Spec.Governance) } if after := a.Spec.GovernanceAfter[rowan]; !strings.Contains(after, `"mode":"governed"`) { @@ -123,8 +139,8 @@ func TestGovernanceChangeOnATestInstallationNeedsASecondPerson(t *testing.T) { t.Fatalf("%d review(s) posted", len(posted)) } review := fmt.Sprint(posted[0].Body["text"]) - loosens := strings.Index(review, "*It loosens governance:* rowan: "+droppedKubernetes) - if loosens < 0 || loosens > strings.Index(review, "• rowan: mode trusted → governed") || !strings.Contains(review, "*Governance:* this changes the platform's governance") { + loosens := strings.Index(review, "*It loosens governance:* rowan: no reviewed governance is on record for rowan") + if loosens < 0 || !strings.Contains(review, droppedKubernetes) || loosens > strings.Index(review, "• rowan: no reviewed governance") || !strings.Contains(review, "*Governance:* this changes the platform's governance") { t.Fatalf("the review leads with what loosens, then the change:\n%s", review) } requireLog(t, st, "governance_change_committed", "action="+a.Name, "actor=alice", "loosens=true") @@ -264,7 +280,7 @@ func TestGovernanceChangedOutsideTheManagerNeedsTheReview(t *testing.T) { t.Fatalf("reconcile: %v %s", isErr, text) } g := again.Action.Spec.Governance[rowan] - if again.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.HasPrefix(g.Lines[0], "the governance on record differs from what action "+merged.Name+" left") { + if again.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.HasPrefix(g.Lines[0], "the governance on record differs from what the team reviewed in action "+merged.Name) { t.Fatalf("a reconcile over an outside change went without the review: %+v %+v", again.Action.Status.Approval, g) } requireLog(t, st, "governance_on_record_changed_outside", "installation=rowan", "action="+merged.Name) @@ -278,6 +294,7 @@ func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) aliceC := st.mcpClient(t, aliceToken) marker := installations.Capabilities()[0].EnabledMarker(rowan) st.ghs.addFile(acmeConfigs, marker, platformOnRecord) + seedRecord(t, st, platformOnRecord) moved := strings.Replace(platformOnRecord, "governance:\n", "governance:\n mode: governed\n", 1) st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, moved) } out, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) @@ -298,6 +315,7 @@ func TestGovernanceMergedBetweenThePlanAndTheBranchNeedsTheReview(t *testing.T) func TestTestInstallationWithoutGovernanceChangeNeedsNoReview(t *testing.T) { st := governedTestRowan(t) st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), platformOnRecord) + seedRecord(t, st, platformOnRecord) aliceC := st.mcpClient(t, aliceToken) out, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}})}) if isErr || out.Action == nil || out.Action.Status.Approval == nil || out.Action.Status.Approval.Decision != actions.DecisionNotRequired || len(out.Action.Spec.Governance) != 0 { @@ -317,6 +335,7 @@ func TestWaveLooseningGovernanceOnATestInstallationNeedsASecondPerson(t *testing rowanAsTestInstallation(t, st.ghs) rowanOnLineFour(st.ghs) st.ghs.addFile(acmeConfigs, installations.Capabilities()[0].EnabledMarker(rowan), "muster: {}\ngovernance:\n mode: governed\n") + seedRecord(t, st, "muster: {}\ngovernance:\n mode: governed\n") seedRemote(t, st) aliceC := st.mcpClient(t, aliceToken) inputs := minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceTrusted}}) @@ -392,7 +411,7 @@ func TestGovernanceChangedOutsideIsSeenWhenTheValuesStayAsTheyAre(t *testing.T) if isErr { t.Fatalf("reconcile: %s", text) } - if again.Action != nil || !strings.Contains(again.Next, "is not what the last reviewed action left") || again.Plan.Governance == nil || !strings.HasPrefix(again.Plan.Governance.Lines[0], "the governance on record differs from what action "+merged.Name+" left") { + if again.Action != nil || !strings.Contains(again.Next, "is not what the team reviewed") || again.Plan.Governance == nil || !strings.HasPrefix(again.Plan.Governance.Lines[0], "the governance on record differs from what the team reviewed in action "+merged.Name) { t.Fatalf("an outside edit with the values unchanged: action %v, next %q, governance %+v", again.Action != nil, again.Next, again.Plan.Governance) } requireLog(t, st, "governance_on_record_changed_outside", "action="+merged.Name) @@ -418,12 +437,12 @@ func TestAnActionWithoutASnapshotErasesNoBaseline(t *testing.T) { if _, err := store.UpdateStatus(t.Context(), stored, status); err != nil { t.Fatal(err) } - last, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{"sessions": map[string]any{"idleTTL": "2h"}})}) + last, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keySessions: map[string]any{keyIdleTTL: "2h"}})}) if isErr || last.Action == nil { t.Fatalf("reconcile: %v %s", isErr, text) } g := last.Action.Spec.Governance[rowan] - if last.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what action "+merged.Name+" left") { + if last.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what the team reviewed in action "+merged.Name) { t.Fatalf("a commit after a snapshot-less action: %+v %+v", last.Action.Status.Approval, g) } } @@ -447,7 +466,7 @@ func TestAnActionMergedWithoutApprovalIsNoBaseline(t *testing.T) { t.Fatal(err) } again, text, isErr := commitCall(t, st.mcpClient(t, aliceToken), tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) - if isErr || again.Plan.Governance == nil || !strings.Contains(again.Plan.Governance.Lines[0], "what action "+merged.Name+" left") { + if isErr || again.Plan.Governance == nil || !strings.Contains(again.Plan.Governance.Lines[0], "what the team reviewed in action "+merged.Name) { t.Fatalf("an action merged without approval as the baseline: %v %s", isErr, text) } } @@ -459,6 +478,7 @@ func TestGovernanceMovedUnderAWaveIsAGovernanceChange(t *testing.T) { st := governedTestRowan(t) marker := installations.Capabilities()[0].EnabledMarker(rowan) st.ghs.addFile(acmeConfigs, marker, platformOnRecord) + seedRecord(t, st, platformOnRecord) st.beforeOpen = func() { st.ghs.addFile(acmeConfigs, marker, strings.Replace(platformOnRecord, "governance:\n", "governance:\n mode: governed\n", 1)) } @@ -484,3 +504,145 @@ func TestGovernanceMovedUnderAWaveIsAGovernanceChange(t *testing.T) { t.Fatalf("an approve by a pending member: %v %s", isErr, text) } } + +// record is rowan's reviewed-governance record, nil without one. +func record(t *testing.T, st *stack) *actions.GovernanceRecord { + t.Helper() + r, err := actions.New(st.dyn, actionsNamespace).GetRecord(t.Context(), rowan) + if err != nil { + return nil + } + return r +} + +// Decision #99: the reviewed-governance record is written by merge_action +// when an approved governance change is merged through the manager, with +// the approver and the configs pull request's head; an action that needs +// no review writes none. +func TestTheReviewedGovernanceIsRecordedAtTheMerge(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + if record(t, st) != nil { + t.Fatal("a record before the merge") + } + merged := approveAndMerge(t, st, out.Action.Name) + r := record(t, st) + var head string + for _, pr := range merged.Status.PullRequests { + if pr.Repository == acmeConfigs { + head = pr.HeadSHA + } + } + if r == nil || r.Action != merged.Name || r.ApprovedBy != carol || r.HeadSHA == "" || r.HeadSHA != head || r.Governance != merged.Spec.GovernanceAfter[rowan] { + t.Fatalf("the record after the reviewed merge: %+v (head %s)", r, head) + } + requireLog(t, st, "governance_record_written", "action="+merged.Name) + + // A later change that needs no review leaves the record as it is. + next, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}}, keySessions: map[string]any{keyIdleTTL: "2h"}})}) + if isErr || next.Action == nil || next.Action.Status.Approval.Decision != actions.DecisionNotRequired { + t.Fatalf("a change without governance: %v %s", isErr, text) + } + for _, pr := range st.remote.PullRequests() { + st.remote.SetChecks(pr.PullRequest, commit.ChecksSuccess) + } + if _, text, isErr := mergeCall(t, aliceC, next.Action.Name); isErr { + t.Fatalf("merge: %s", text) + } + if again := record(t, st); again == nil || again.Action != merged.Name { + t.Fatalf("a merge needing no review rewrote the record: %+v", again) + } +} + +// D-GO-25: an action planned while the installation was trusted, merged +// after the team made it governed, is no baseline: the record is what the +// team reviewed, so a direct push back to trusted is seen and asks the +// review. +func TestAStaleActionMergedLateDoesNotDisplaceTheReviewedGovernance(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + first, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || first.Action == nil { + t.Fatalf("first: %v %s", isErr, text) + } + approveAndMerge(t, st, first.Action.Name) + stale, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keySessions: map[string]any{keyIdleTTL: "2h"}})}) + if isErr || stale.Action == nil || stale.Action.Status.Approval.Decision != actions.DecisionNotRequired { + t.Fatalf("stale: %v %s", isErr, text) + } + gov, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || gov.Action == nil { + t.Fatalf("governed: %v %s", isErr, text) + } + reviewed := approveAndMerge(t, st, gov.Action.Name) + governed, _ := st.ghs.file(acmeConfigs, marker) + if _, text, isErr := mergeCall(t, aliceC, stale.Action.Name); isErr { + t.Fatalf("merge stale: %s", text) + } + afterStale, _ := st.ghs.file(acmeConfigs, marker) + // git's three-way merge keeps the governed lines beside the stale change; + // then someone pushes the stale action's values directly. + st.ghs.addFile(acmeConfigs, marker, governed) + if r := record(t, st); r == nil || r.Action != reviewed.Name { + t.Fatalf("the stale merge displaced the record: %+v", r) + } + st.ghs.addFile(acmeConfigs, marker, afterStale) + again, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keySessions: map[string]any{keyIdleTTL: "3h"}})}) + if isErr || again.Action == nil { + t.Fatalf("again: %v %s", isErr, text) + } + g := again.Action.Spec.Governance[rowan] + if again.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what the team reviewed in action "+reviewed.Name) || !slices.Contains(g.Loosens, "mode governed → trusted") { + t.Fatalf("a push back to trusted after a stale merge: %+v %+v", again.Action.Status.Approval, g) + } + requireLog(t, st, "governance_on_record_changed_outside", "action="+reviewed.Name) +} + +// D-GO-26: the reviewed governance change reverted by hand and read by a +// watch keeps the record; the revert is audited and the next commit shows +// it against what the team reviewed and asks the review. +func TestAHandRevertOfAReviewedGovernanceChangeAsksTheReview(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + marker := installations.Capabilities()[0].EnabledMarker(rowan) + first, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || first.Action == nil { + t.Fatalf("first: %v %s", isErr, text) + } + approveAndMerge(t, st, first.Action.Name) + gov, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || gov.Action == nil { + t.Fatalf("governed: %v %s", isErr, text) + } + reviewed := approveAndMerge(t, st, gov.Action.Name) + for _, pr := range st.remote.PullRequests() { + for _, mine := range reviewed.Status.PullRequests { + if pr.Merged && pr.URL == mine.URL { + st.revertOutside(t, pr.PullRequest, dave) + } + } + } + if v, _ := st.ghs.file(acmeConfigs, marker); strings.Contains(v, "mode: governed") { + t.Fatal("setup: still governed after the revert") + } + if w, text, isErr := watchCall(t, adminLive(t, st), reviewed.Name); isErr || w.State != actions.StateReverted { + t.Fatalf("watch: %v %s %s", isErr, w.State, text) + } + requireLog(t, st, "governance_change_reverted", "action="+reviewed.Name) + if r := record(t, st); r == nil || r.Action != reviewed.Name { + t.Fatalf("the revert changed the record: %+v", r) + } + again, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keySessions: map[string]any{keyIdleTTL: "3h"}})}) + if isErr || again.Action == nil { + t.Fatalf("again: %v %s", isErr, text) + } + g := again.Action.Spec.Governance[rowan] + if again.Action.Status.Approval.Decision == actions.DecisionNotRequired || len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what the team reviewed in action "+reviewed.Name) { + t.Fatalf("a commit after a hand revert: %+v %+v", again.Action.Status.Approval, g) + } +} diff --git a/internal/e2e/identity_chain_test.go b/internal/e2e/identity_chain_test.go index 7b33c02b..0ae4fb7f 100644 --- a/internal/e2e/identity_chain_test.go +++ b/internal/e2e/identity_chain_test.go @@ -131,7 +131,7 @@ func newStack(t *testing.T, options ...func(*tools.Deps)) *stack { t.Fatal(err) } st := &stack{ghs: newFakeGitHub(t, logins), probes: newFakeProbes(t), remote: commit.NewFake(), logs: logs, gateway: newFakeGateway(t), - dyn: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{actions.GVR: actions.Kind + "List"}), + dyn: dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), map[schema.GroupVersionResource]string{actions.GVR: actions.Kind + "List", actions.RecordGVR: actions.RecordKind + "List"}), dex: newFakeDex(t), inst: newFakeInstallation(), pulls: map[string]pullFacts{}} st.ghs.pull = st.pullState // carol reviews governance changes; alice, the actor of the tests, too. diff --git a/internal/plan/governance.go b/internal/plan/governance.go index 999876bf..8cde0be8 100644 --- a/internal/plan/governance.go +++ b/internal/plan/governance.go @@ -112,6 +112,15 @@ func ParseGovernanceSnapshot(s string) (GovernanceSnapshot, error) { return out, nil } +// InPlay says whether the values carry the meta chart's governance: the +// definition renders it (with Giant Swarm's role floors) wherever the chart +// takes it, so its presence marks an installation whose governance muster +// enforces. +func (s GovernanceSnapshot) InPlay() bool { + _, ok := s[keyGovernance] + return ok +} + // JSON is the snapshot as an Action records it, keys sorted. func (s GovernanceSnapshot) JSON() string { b, _ := json.Marshal(map[string]any(s)) diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go index 416d4971..b91a3927 100644 --- a/internal/plan/governance_test.go +++ b/internal/plan/governance_test.go @@ -246,3 +246,15 @@ func TestWhoMayLoosenApprovalsIsGovernance(t *testing.T) { t.Fatalf("a workflow editor added: %v %+v", ok, g) } } + +// D-GO-31: a ServiceAccount subject is its namespace and name: the same +// name in another namespace is another subject. +func TestServiceAccountSubjectsKeepTheirNamespace(t *testing.T) { + sa := func(ns string) string { + return "tenants:\n platformTeam:\n - {kind: ServiceAccount, name: runner, namespace: " + ns + "}\n" + } + g, ok := GovernanceOf(govPlan(sa("team-a"), sa("team-b"))) + if !ok || !slices.Equal(g.Loosens, []string{"tenants.platformTeam +ServiceAccount:team-b/runner −ServiceAccount:team-a/runner"}) { + t.Fatalf("a ServiceAccount moved to another namespace: %v %+v", ok, g) + } +} diff --git a/internal/tools/approval.go b/internal/tools/approval.go index 093490ad..18540338 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -376,6 +376,11 @@ func (t *Tools) merge(ctx context.Context, args map[string]any) (any, error) { return res, nil } res.Message = fmt.Sprintf("the pull requests of %s are merged as %s (%s); %s is rolling out — %s reads its rollout and runs the probes as you, and carries it to enabled%s.", res.Stage, id.Login, prList(res.Merged), res.Stage, ToolWatchAction, nextStage(a, res.Stage)) + // The stage of an approved governance change is merged through the + // manager: what the team reviewed is the installation's record now. + if note := t.recordReviewed(ctx, a, res.Stage); note != "" { + res.Message += " " + note + } if noReview(a) { if note := t.tellStandup(ctx, a, stageMerge{by: id.Login, stage: res.Stage, pullRequests: res.Merged}); note != "" { res.Message += " " + note diff --git a/internal/tools/commit.go b/internal/tools/commit.go index 6d1aeeb8..8009954b 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -196,7 +196,7 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri if len(p.Files)-p.Diff[plan.ChangeUnchanged] == 0 { res.Next = "every file is on record as the definition renders it: nothing to commit, no action recorded" if g != nil { - res.Next += "; the governance on record is not what the last reviewed action left (" + strings.Join(g.Lines, "; ") + "): a reviewed change that types the governance confirms or reverts it" + res.Next += "; the governance on record is not what the team reviewed (" + strings.Join(g.Lines, "; ") + "): a reviewed change that types the governance confirms or reverts it" } return res, nil } diff --git a/internal/tools/governance.go b/internal/tools/governance.go index 9121156c..5c0b3f54 100644 --- a/internal/tools/governance.go +++ b/internal/tools/governance.go @@ -7,13 +7,11 @@ import ( "maps" "slices" "strings" - "time" "unicode/utf8" "github.com/giantswarm/giantswarm-platform-manager/internal/actions" "github.com/giantswarm/giantswarm-platform-manager/internal/gh" "github.com/giantswarm/giantswarm-platform-manager/internal/identity" - "github.com/giantswarm/giantswarm-platform-manager/internal/installations" "github.com/giantswarm/giantswarm-platform-manager/internal/plan" ) @@ -23,95 +21,84 @@ import ( // (spec.governance) and asks the team's review even where every target is a // test installation; approve_action refuses the actor and anyone who is not // an active member of the governance reviewers' team (approvals.governanceTeam), -// and merge_action waits for that decision. Every Action records the -// governance its commit leaves (spec.governanceAfter): the next plan compares -// against it, so a disable followed by an enable, or a change made in the -// configs repository directly, is a governance change again and needs the -// review. Each step is audited (auditGovernance). Agents may propose such a -// change and never approve or merge it: muster asks a person before an -// agent's approve_action and merge_action (a floor of the platformManager -// role). +// and merge_action waits for that decision. What the team reviewed is kept +// per installation in a reviewed-governance record (actions.GovernanceRecord, +// decision #99), written only when merge_action merges an approved +// governance change: every plan compares the configs repository's +// governance with it, never with the Actions' order or states, so an edit +// outside the manager, a revert by hand or an action merged out of order is +// an unreviewed change the next commit asks the team to confirm or restore. +// Each step is audited (auditGovernance). Agents may propose such a change +// and never approve or merge it: muster asks a person before an agent's +// approve_action and merge_action (a floor of the platformManager role). -// baselineStates are the states of an Action whose stage is on record: its -// pull requests merged, not taken back. -var baselineStates = []string{actions.StateRollingOut, actions.StateWaitingForCustomer, actions.StateEnabled, actions.StateDrifted, actions.StateDisabled, actions.StateFailed} - -// governanceBaseline is the governance the newest reviewed action left on -// installation: an agent-platform action whose stage there is merged and on -// record, approved by the team or needing no review, with a recorded -// governance. An action merged without the team's decision is skipped, so -// what it left counts as changed outside the manager. None (false) before -// the first action that records one, or without the records. -func (t *Tools) governanceBaseline(ctx context.Context, installation string) (plan.GovernanceSnapshot, string, bool) { - if t.d.Actions == nil { - return nil, "", false - } - list, err := t.d.Actions.List(ctx, actions.Filter{Installation: installation}) +// reviewedGovernance is installation's reviewed-governance record: the +// governance the team last reviewed there, and the record. found is false +// without one, or when it cannot be read or parsed (logged): fail closed, +// the governance in play then asks the review. +func (t *Tools) reviewedGovernance(ctx context.Context, installation string) (plan.GovernanceSnapshot, *actions.GovernanceRecord, bool) { + if t.d.Records == nil { + return nil, nil, false + } + r, err := t.d.Records.GetRecord(ctx, installation) if err != nil { - t.d.Log.Warn("governance_baseline_unread", identity.LogAttr(ctx), "installation", installation, "error", err.Error()) - return nil, "", false - } - type candidate struct { - name string - mergedAt time.Time - snap plan.GovernanceSnapshot - } - var found []candidate - for _, a := range list { - if a.CapabilityOf(installation) != installations.AgentPlatform || !slices.Contains(baselineStates, a.Status.State) || !allMerged(&a, installation) || len(a.StagePullRequests(installation)) == 0 { - continue - } - if a.Status.Approval == nil || (a.Status.Approval.Decision != actions.DecisionApproved && a.Status.Approval.Decision != actions.DecisionNotRequired) { - continue - } - // Only an action that recorded the governance it leaves is a - // baseline; one without (from before the field) carries none, and - // the one before it stands. - raw, ok := a.Spec.GovernanceAfter[installation] - if !ok { - continue + if !errors.Is(err, actions.ErrNotFound) { + t.d.Log.Warn("governance_record_unread", identity.LogAttr(ctx), "audit", true, "installation", installation, "error", err.Error()) } - snap, err := plan.ParseGovernanceSnapshot(raw) - if err != nil { - continue - } - c := candidate{name: a.Name, mergedAt: a.CreatedAt, snap: snap} - for _, k := range a.StagePullRequests(installation) { - if at := a.Status.PullRequests[k].MergedAt; at != nil && at.After(c.mergedAt) { - c.mergedAt = *at - } - } - found = append(found, c) - } - if len(found) == 0 { - return nil, "", false + return nil, nil, false } - // The newest merge is the baseline. Actions merged within one second are - // told apart by name; where they left different governance it is logged. - slices.SortStableFunc(found, func(x, y candidate) int { - if c := y.mergedAt.Compare(x.mergedAt); c != 0 { - return c - } - return strings.Compare(y.name, x.name) - }) - if len(found) > 1 && found[0].mergedAt.Equal(found[1].mergedAt) && len(plan.GovernanceBetween(found[0].snap, found[1].snap).Lines) > 0 { - t.d.Log.Warn("governance_baseline_ambiguous", identity.LogAttr(ctx), "installation", installation, "actions", found[0].name+","+found[1].name) + snap, err := plan.ParseGovernanceSnapshot(r.Governance) + if err != nil { + t.d.Log.Warn("governance_record_unread", identity.LogAttr(ctx), "audit", true, "installation", installation, "error", err.Error()) + return nil, nil, false } - return found[0].snap, found[0].name, true + return snap, r, true } -// governanceOutside is the line of a plan whose record differs from what -// the last reviewed action left: the change is shown against that action. -func governanceOutside(action string) string { - return "the governance on record differs from what action " + action + " left (changed outside the manager); the change is shown against " + action +// governanceOutside is the line of a plan whose configs repository carries +// another governance than the team reviewed: the change is shown against +// the reviewed one. +func governanceOutside(r *actions.GovernanceRecord) string { + return "the governance on record differs from what the team reviewed in action " + r.Action + " (changed outside the manager, reverted by hand or merged out of order); the change is shown against what was reviewed" } -// governanceChange is the governance a commit of p changes, against what -// the last reviewed action left where it is known, else against the record, -// and the snapshot the commit leaves; nil for a plan that changes none or -// writes no agent-platform values. A record that differs from the last -// reviewed action's is logged (governance_on_record_changed_outside) and -// shown, as a loosening line, ahead of the change. +// governanceUnrecorded is the line of a plan whose governance is in play +// on an installation without a reviewed-governance record: the team review +// confirms it (fail closed; installations from before the record get one +// with their first reviewed commit). +func governanceUnrecorded(installation string) string { + return "no reviewed governance is on record for " + installation + ": the team review confirms the governance this commit leaves" +} + +// against compares the configs repository's governance (current) and what +// a commit leaves (next) with the reviewed record: a difference between the +// record and current is logged as an unreviewed change and leads the +// change, which is shown against the record; without a record, governance +// in play leads with governanceUnrecorded. The lines from base to next +// follow, base the record or current. +func (t *Tools) against(ctx context.Context, installation string, current, next plan.GovernanceSnapshot) (plan.GovernanceChange, plan.GovernanceSnapshot) { + lead := "" + base := current + if reviewed, r, found := t.reviewedGovernance(ctx, installation); found { + if outside := plan.GovernanceBetween(reviewed, current); len(outside.Lines) > 0 { + t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", installation, "action", r.Action, "governance", strings.Join(outside.Lines, "; ")) + lead, base = governanceOutside(r), reviewed + } + } else if current.InPlay() || next.InPlay() { + t.d.Log.Warn("governance_unrecorded", identity.LogAttr(ctx), "audit", true, "installation", installation) + lead = governanceUnrecorded(installation) + } + g := plan.GovernanceBetween(base, next) + if lead != "" { + g.Lines = append([]string{lead}, g.Lines...) + g.Loosens = append([]string{lead}, g.Loosens...) + } + return g, base +} + +// governanceChange is the governance a commit of p changes, against the +// reviewed record (against), and the snapshot the commit leaves; nil for a +// plan that changes none or writes no agent-platform values. func (t *Tools) governanceChange(ctx context.Context, p plan.Installation) (*plan.GovernanceChange, string) { current, next, ok, unreadable := plan.GovernanceFile(p) if !ok { @@ -121,16 +108,7 @@ func (t *Tools) governanceChange(ctx context.Context, p plan.Installation) (*pla g := plan.GovernanceUnreadable() return &g, "" } - g := plan.GovernanceBetween(current, next) - if base, from, has := t.governanceBaseline(ctx, p.Name); has { - if outside := plan.GovernanceBetween(base, current); len(outside.Lines) > 0 { - t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", p.Name, "action", from, "governance", strings.Join(outside.Lines, "; ")) - g = plan.GovernanceBetween(base, next) - line := governanceOutside(from) - g.Lines = append([]string{line}, g.Lines...) - g.Loosens = append([]string{line}, g.Loosens...) - } - } + g, _ := t.against(ctx, p.Name, current, next) if len(g.Lines) == 0 { return nil, next.JSON() } @@ -147,10 +125,11 @@ func governanceAfter(p plan.Installation) string { return next.JSON() } -// governanceOfDisable is the governance a disable removes with the values: -// what the record carries (against the last reviewed action's where they -// differ), and the snapshot the disable records as what it leaves — the -// governance before it, so a later enable is compared with that. +// governanceOfDisable is the governance a disable removes with the values +// (against the reviewed record), and the snapshot the disable records as +// what it leaves: the governance before it (the record where the values +// differ from it), so a later enable is compared with that once the +// reviewed disable is merged. func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Disablement) (*plan.GovernanceChange, string, error) { for _, f := range d.Files { if f.Change != plan.ChangeDelete || !strings.HasSuffix(f.Path, "/apps/agent-platform/configmap-values.yaml.patch") { @@ -169,25 +148,53 @@ func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Di g := plan.GovernanceUnreadable() return &g, "", nil } - old, outside := current, "" - if base, from, has := t.governanceBaseline(ctx, d.Name); has && len(plan.GovernanceBetween(base, current).Lines) > 0 { - t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", d.Name, "action", from) - old, outside = base, governanceOutside(from) - } - g, changes := plan.GovernanceDeleted(old) - if outside != "" { - g.Lines = append([]string{outside}, g.Lines...) - g.Loosens = append([]string{outside}, g.Loosens...) + lead, base := t.against(ctx, d.Name, current, current) + g, changes := plan.GovernanceDeleted(base) + if len(lead.Lines) > 0 { + g.Lines = append(slices.Clone(lead.Lines), g.Lines...) + g.Loosens = append(slices.Clone(lead.Loosens), g.Loosens...) changes = true } if !changes { - return nil, old.JSON(), nil + return nil, base.JSON(), nil } - return &g, old.JSON(), nil + return &g, base.JSON(), nil } return nil, "", nil } +// recordReviewed writes installation's reviewed-governance record once +// merge_action merged the stage of an approved governance change there: the +// governance the action's commit leaves, the approver and the configs pull +// request's merged head. Never for an action the team did not approve, or +// one that changes no governance there. A write that fails is logged and +// answered: the next plan then asks the review again (fail closed). +func (t *Tools) recordReviewed(ctx context.Context, a *actions.Action, installation string) string { + if t.d.Records == nil || a.Status.Approval == nil || a.Status.Approval.Decision != actions.DecisionApproved { + return "" + } + if _, changes := actions.GovernanceOf(a)[installation]; !changes { + return "" + } + after, ok := a.Spec.GovernanceAfter[installation] + if !ok { + return "" + } + head := "" + for _, k := range a.StagePullRequests(installation) { + if pr := a.Status.PullRequests[k]; strings.HasSuffix(pr.Repository, "-configs") { + head = pr.HeadSHA + } + } + r := actions.GovernanceRecord{Installation: installation, Governance: after, Action: a.Name, ApprovedBy: a.Status.Approval.DecidedBy, HeadSHA: head} + if err := t.d.Records.PutRecord(ctx, r); err != nil { + t.d.Log.Warn("governance_record_not_written", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "error", err.Error()) + return fmt.Sprintf("(The reviewed governance of %s could not be recorded: %v; the next commit there asks the team's review again.)", installation, err) + } + t.d.Log.Info("governance_record_written", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "approvedBy", r.ApprovedBy, "headSHA", head) + return "" +} + // governanceRecordMoved says whether the agent-platform values on the // default branch carry another governance than p read (someone merged one // between the plan and the branch): read again past the cache, as the diff --git a/internal/tools/governance_test.go b/internal/tools/governance_test.go index 7ff4b8a1..6bc19235 100644 --- a/internal/tools/governance_test.go +++ b/internal/tools/governance_test.go @@ -161,3 +161,59 @@ func TestGovernanceRecordMovedWhenTheValuesCannotBeRead(t *testing.T) { t.Fatalf("an unreadable default branch: %v %q", moved, what) } } + +// fakeRecords is an in-memory RecordStore. +type fakeRecords struct{ put []actions.GovernanceRecord } + +func (f *fakeRecords) GetRecord(context.Context, string) (*actions.GovernanceRecord, error) { + return nil, actions.ErrNotFound +} + +func (f *fakeRecords) PutRecord(_ context.Context, r actions.GovernanceRecord) error { + f.put = append(f.put, r) + return nil +} + +// Decision #99: only a team-approved governance change writes the record; +// an approved action without one, or one without the team's approval, +// writes none. +func TestOnlyAnApprovedGovernanceChangeIsRecorded(t *testing.T) { + for _, c := range []struct { + name string + decision string + governs bool + writes bool + }{ + {"approved with a governance change", actions.DecisionApproved, true, true}, + {"approved without one", actions.DecisionApproved, false, false}, + {"not required, with one", actions.DecisionNotRequired, true, false}, + {"merged without approval, with one", actions.DecisionMergedWithoutApproval, true, false}, + } { + t.Run(c.name, func(t *testing.T) { + records := &fakeRecords{} + tl := &Tools{d: Deps{Log: slog.New(slog.DiscardHandler), Records: records}} + a := governedAction() + a.Spec.Installations = []string{rowan} + a.Spec.Governance = map[string]plan.GovernanceChange{rowan: a.Spec.Governance[rtGarm]} + if !c.governs { + a.Spec.Governance = nil + } + a.Spec.GovernanceAfter = map[string]string{rowan: `{"governance":{"mode":"governed"}}`} + a.Status.Approval = &actions.Approval{Decision: c.decision, DecidedBy: "carol"} + tl.recordReviewed(context.Background(), a, rowan) + if (len(records.put) == 1) != c.writes { + t.Fatalf("records written: %+v", records.put) + } + }) + } +} + +// D-GO-31: decided reads the governance found after the commit too: a +// stage merged outside the manager decides nothing for such an action. +func TestMergedWithoutApprovalDecidesNoGovernanceFoundAfterTheCommit(t *testing.T) { + a := &actions.Action{Status: actions.Status{Approval: &actions.Approval{Decision: actions.DecisionMergedWithoutApproval}, + Governance: map[string]plan.GovernanceChange{rowan: {Lines: []string{"moved"}, Loosens: []string{"moved"}}}}} + if decided(a) { + t.Fatal("a governance change found after the commit, merged outside the manager, counts as decided") + } +} diff --git a/internal/tools/resync.go b/internal/tools/resync.go index 5bc1ac96..01e1051b 100644 --- a/internal/tools/resync.go +++ b/internal/tools/resync.go @@ -235,6 +235,7 @@ func (t *Tools) resync(ctx context.Context, c *gh.Client, id *identity.Identity, unread = append(unread, errs...) if len(gone) > 0 && kept == 0 { posts = append(posts, remove(&status, &fresh, def, gone)) + t.auditGovernance(ctx, "governance_change_reverted", &fresh) } } } diff --git a/internal/tools/revert.go b/internal/tools/revert.go index 72bfac6e..42d71487 100644 --- a/internal/tools/revert.go +++ b/internal/tools/revert.go @@ -211,6 +211,9 @@ func (t *Tools) watchReverts(ctx context.Context, a *actions.Action, status *act if err != nil { return nil, fmt.Errorf("%s: %s is reverted and the action could not record it: %w", ToolWatchAction, st.Name, err) } + // A reviewed governance change taken back by hand: the record keeps + // what was reviewed, so the next plan shows the revert as unreviewed. + t.auditGovernance(ctx, "governance_change_reverted", a) st = a.Status.Rollout.Installations[i] out := &WatchResult{Action: a, Installation: st.Name, State: st.State, Objects: []actions.RolloutObject{}, Report: report, Next: fmt.Sprintf("the actor (%s) withdraws the action with %s and the reason; a new action commits the change again", a.Spec.Actor.Login, ToolDenyAction)} @@ -268,6 +271,7 @@ func (t *Tools) withdraw(ctx context.Context, a *actions.Action, id *identity.Id return nil, fmt.Errorf("%s: action %s is %s and every pull request it merged is on the default branch as merged (read now as you): nothing was taken back — revert the pull requests on the default branch first, then withdraw the action", ToolDenyAction, a.Name, was) } posts = append(posts, markReverted(&status, a, found)) + t.auditGovernance(ctx, "governance_change_reverted", a) } open := openPRs(status.PullRequests) if len(open) > 0 { diff --git a/internal/tools/server.go b/internal/tools/server.go index 0602749b..522d246b 100644 --- a/internal/tools/server.go +++ b/internal/tools/server.go @@ -87,6 +87,11 @@ type Deps struct { // manager runs without the hub's API server, and get_action, // list_actions and mode commit say so. Actions actions.Store + // Records reads and writes the reviewed-governance records (decision + // #99); nil takes them from Actions where it keeps them too, and without + // either no reviewed governance is known (every governance in play asks + // the review). + Records actions.RecordStore // Remote opens the git remote a commit lands on, with the caller's // token: GitHub in production (GitHubRemote), gitops-commit's Fake in // tests. nil refuses mode commit naming the configuration. @@ -154,6 +159,9 @@ func New(d Deps) *Tools { if d.Files == nil { d.Files = gh.NewFiles(gh.DefaultFreshness) } + if rs, ok := d.Actions.(actions.RecordStore); ok && d.Records == nil { + d.Records = rs + } t := &Tools{d: d} if d.Approvals.Configured() { t.approvals = approvals.New(d.Approvals, d.ApprovalsHTTP) From 7cf2c1212af576c51233b8e4e9469a3f1791e9dc Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 14:45:31 +0100 Subject: [PATCH 21/27] docs: describe the reviewed-governance record docs/governance.md replaces the baseline derived from the Actions with the GovernanceRecord: who writes it and when, what every plan compares, the fail-closed migration of installations without one, and the new audit lines (decision #99). --- docs/governance.md | 53 ++++++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/docs/governance.md b/docs/governance.md index 9283b020..1ff0f357 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -142,24 +142,38 @@ team and the subjects of muster's editor bindings (absent editor subjects read a definition renders). A change that leaves the effective governance as it is, such as an explicit `trusted` dropped, is none. -The plan compares against what the last reviewed action left, not against the record alone. Every Action -records the governance its commit leaves (`spec.governanceAfter`; a disable's is the governance before it). The -newest agent-platform action on the installation whose stage is merged and on record, approved by the team or -needing no review, and that recorded the governance it leaves, is the baseline: an action without a snapshot -(from before the field) is skipped and the one before it stands. Actions are ordered by their stage's merge; -two merged in the same second are told apart by name and logged (`governance_baseline_ambiguous`). When the record differs from it, the governance was changed outside the -manager: - -- the plan, the dry run included, shows the change against the baseline, also when the plan writes the values - file as it is on record, led by a loosening line that names the - action; +The plan compares the configs repository with what the team reviewed, kept per installation in a +reviewed-governance record (decision #99): a `GovernanceRecord` in the manager's namespace, named after the +installation, beside the Action records (`crd-governancerecords.yaml`; only the manager's ServiceAccount may write +it). It holds the reviewed governance (the snapshot of the governance values), the Action whose merge wrote it, +the approver and the configs pull request's merged head. `merge_action` writes it, and nothing else does: when it +merges an installation's stage of an Action that changes the governance there and that the team approved, the +governance that Action's commit leaves becomes the record (`governance_record_written`). An action that needs no +review, one merged outside the manager, a revert and the Actions' order or states never change it. + +Every plan, the dry run and the commit included, compares the governance in the configs repository with the +record, whether or not the plan writes the values file. A difference the record does not explain (an edit +outside the manager, a revert by hand, an older action merged after a newer one) is an unreviewed change: + +- the plan shows the change against the record, led by a loosening line that names the reviewed action; - `governance_on_record_changed_outside` is logged; -- the next commit asks the review, even when it types the governance back. A record that only a reviewed change - can confirm cannot be adopted by a commit with nothing to write: that commit answers "nothing to commit" and - names the difference. - -A `disable_capability` that deletes values carrying a governance is a loosening governance change. A later enable -is compared with the governance before the disable, so bringing the platform back trusted asks the review too. +- the next commit asks the team's review, even when it types the governance back; a commit with nothing to write + answers "nothing to commit" and names the difference. The reviewed commit, once merged, is the record. + +A revert of a reviewed governance change that a read of the Action finds (the watch, or `deny_action`'s +withdrawal) is audited (`governance_change_reverted`); the record keeps what was reviewed, so the next plan +shows the revert. + +An installation without a record is fail closed: where its governance is in play (the values carry the meta +chart's `governance`), every commit asks the team's review, led by "no reviewed governance is on record", until a +reviewed commit is merged and becomes the record (`governance_unrecorded`). That is the migration of the +installations from before the record: their first commit is reviewed. A record that cannot be read counts as +none (`governance_record_unread`), and a record that could not be written after a merge is logged +(`governance_record_not_written`) and leaves the next commit to ask the review again. + +A `disable_capability` that deletes values carrying a governance is a loosening governance change. Its record, +once reviewed and merged, is the governance before the disable, so an enable that brings the platform back trusted +asks the review too. Between the plan and the pull requests the commit or wave reads the values on the default branch again: a governance merged in between is recorded as a loosening governance change of the action (`status.governance`), so the review shows it and only a member of the reviewers' team approves it (`governance_record_moved`). @@ -224,7 +238,10 @@ loosens. | `governance_change_merged_without_approval` | a pull request of it was merged outside the manager before the team approved, in any state of the action; read at the next read of the action | | `governance_on_record_changed_outside` | a plan found the record's governance other than what the last reviewed action left | | `governance_record_moved` | the values on the default branch changed between the plan and the pull requests | -| `governance_baseline_ambiguous` | two reviewed actions merged in the same second left different governance | +| `governance_record_written` | `merge_action` merged an approved governance change: the installation's record now holds it | +| `governance_record_not_written`, `governance_record_unread` | the record could not be written or read; the next commit asks the review | +| `governance_unrecorded` | a plan found governance in play on an installation without a record | +| `governance_change_reverted` | a read of the Action found a reviewed governance change reverted on the default branch | ## What the manager does not cover From aba44eb277d3464f68864ff58164989bb805d1bb Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 15:38:55 +0100 Subject: [PATCH 22/27] fix(tools): compare-and-swap the reviewed-governance record and show unrecorded governance whole Each Action records which record its plan compared with (spec.governanceBase); merge_action merges a stage of an approved governance change, and writes the record, only while the installation's record is still that one, so an approval given against an older record no longer displaces a newer review. Without a record the review shows the governance the commit leaves whole, against the chart's defaults. A reviewed disable marks its record, and the enable after it is compared with the governance from before under its own line instead of reading as an outside change. A ValidatingAdmissionPolicy lets only the manager's ServiceAccount create, update or delete the records, and the CRD holds spec.installation to the object's name (review D-GO-33 to D-GO-36, D-GO-40). --- helm/giantswarm-platform-manager/README.md | 1 + .../admission-governancerecords.yaml | 35 ++++ .../templates/crd-actions.yaml | 4 + .../templates/crd-governancerecords.yaml | 6 + .../values.schema.json | 4 + helm/giantswarm-platform-manager/values.yaml | 6 + internal/actions/actions.go | 5 + internal/actions/records.go | 42 +++- internal/chart/chart_test.go | 37 ++++ internal/e2e/governance_test.go | 179 +++++++++++++++++- internal/plan/plan.go | 5 +- internal/tools/approval.go | 5 + internal/tools/capability.go | 2 +- internal/tools/commit.go | 3 + internal/tools/disable.go | 5 +- internal/tools/governance.go | 138 ++++++++++---- internal/tools/governance_test.go | 64 ++++++- internal/tools/wave.go | 6 + 18 files changed, 488 insertions(+), 59 deletions(-) create mode 100644 helm/giantswarm-platform-manager/templates/admission-governancerecords.yaml diff --git a/helm/giantswarm-platform-manager/README.md b/helm/giantswarm-platform-manager/README.md index 9e24a39a..d72c62f7 100644 --- a/helm/giantswarm-platform-manager/README.md +++ b/helm/giantswarm-platform-manager/README.md @@ -44,6 +44,7 @@ header; every other tool answers with the user token alone. | hub | string | `""` | Name of the hub installation this manager runs on. Its management-clusters repository holds the Dev Portal's app-config the registry also reads, and the hub side of every capability lands in its repositories. Empty leaves `list_installations` refusing with the reason; `get_info` reports `registry.configured: false`. | | actions.enabled | bool | `true` | Keep the Action records — one `Action` (`platform-manager.giantswarm.io/v1alpha1`) per enablement or reconcile a person commits: actor, installations, capability, inputs, pull requests, approval, rollout, probes, result — as custom resources in the release namespace, read and written with the pod's ServiceAccount (the CRD, a Role and its binding are rendered). Off: no ServiceAccount token is mounted, `get_action` and `list_actions` refuse with the reason and `get_info` reports `actions.configured: false`. | | actions.installCRD | bool | `true` | Render the `actions.platform-manager.giantswarm.io` CRD from the chart's templates (so upgrades follow the chart). Off when the CRD is delivered separately. | +| actions.governanceRecordPolicy | bool | `true` | Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount create, update or delete the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`, decision #99): a record written by anyone else would read as reviewed governance. Needs Kubernetes 1.30 or later. | | approvals.gatewayURL | string | `""` | klaus-gateway's base URL as reached from the pod (for example `http://klaus-gateway.agent-platform.svc:8080`): the team-review endpoint an action's approval request goes to. Empty refuses `mode: commit` (nothing is committed that no one can approve); `get_info` reports `approvals.configured: false`. The requests carry the pod's projected ServiceAccount token in the gateway's audience; the gateway's `reviews.allowedCallers` must name this ServiceAccount. | | approvals.team | string | `""` | The team whose members decide, as the gateway names it. | | approvals.channel | string | `""` | The capability-owning team's channel the reviews land in (a Slack channel ID). | diff --git a/helm/giantswarm-platform-manager/templates/admission-governancerecords.yaml b/helm/giantswarm-platform-manager/templates/admission-governancerecords.yaml new file mode 100644 index 00000000..ce9aa376 --- /dev/null +++ b/helm/giantswarm-platform-manager/templates/admission-governancerecords.yaml @@ -0,0 +1,35 @@ +{{- if and .Values.actions.enabled .Values.actions.governanceRecordPolicy }} +# Only the manager writes the reviewed-governance records (decision #99): a +# record written by anyone else would read as governance the team reviewed, +# and a deleted one makes every commit ask the review again. RBAC grants the +# writes to this ServiceAccount alone; this policy holds it against any other +# identity that may write the group (cluster admins, GitOps controllers). +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: {{ include "giantswarm-platform-manager.fullname" . }}-governance-records + labels: + {{- include "giantswarm-platform-manager.labels" . | nindent 4 }} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: ["platform-manager.giantswarm.io"] + apiVersions: ["*"] + operations: ["CREATE", "UPDATE", "DELETE"] + resources: ["governancerecords"] + validations: + - expression: request.userInfo.username == "system:serviceaccount:{{ .Release.Namespace }}:{{ include "giantswarm-platform-manager.serviceAccountName" . }}" + message: only the Platform Manager writes or deletes reviewed-governance records; a change of the governance is an Action the team reviews + reason: Forbidden +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: {{ include "giantswarm-platform-manager.fullname" . }}-governance-records + labels: + {{- include "giantswarm-platform-manager.labels" . | nindent 4 }} +spec: + policyName: {{ include "giantswarm-platform-manager.fullname" . }}-governance-records + validationActions: [Deny] +{{- end }} diff --git a/helm/giantswarm-platform-manager/templates/crd-actions.yaml b/helm/giantswarm-platform-manager/templates/crd-actions.yaml index 61110b1a..8194ba52 100644 --- a/helm/giantswarm-platform-manager/templates/crd-actions.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-actions.yaml @@ -155,6 +155,10 @@ spec: loosens: type: array items: {type: string} + governanceBase: + description: Per installation, the reviewed-governance record the plan compared with (action@recordedAt@version, or none); merge_action merges a stage of an approved governance change, and writes the record, only while the installation's record is still that one. + type: object + additionalProperties: {type: string} governanceAfter: description: Per installation, the governance the commit leaves on record (a disable's is the governance before it), as JSON of the governance values; the next plan compares against the newest reviewed one. Values only, never a secret. type: object diff --git a/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml index 4d0e97b0..02a1300b 100644 --- a/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml @@ -36,6 +36,9 @@ spec: openAPIV3Schema: type: object required: [spec] + x-kubernetes-validations: + - rule: self.spec.installation == self.metadata.name + message: spec.installation names the record's object properties: spec: type: object @@ -59,4 +62,7 @@ spec: recordedAt: description: When it was written (RFC 3339). type: string + disabled: + description: The Action that wrote it disabled the platform; governance is the governance from before the disable, which an enable is compared with. + type: boolean {{- end }} diff --git a/helm/giantswarm-platform-manager/values.schema.json b/helm/giantswarm-platform-manager/values.schema.json index 2d0c4c08..1cd23e06 100644 --- a/helm/giantswarm-platform-manager/values.schema.json +++ b/helm/giantswarm-platform-manager/values.schema.json @@ -11,6 +11,10 @@ "type": "boolean", "description": "Keep the Action records — one `Action` (`platform-manager.giantswarm.io/v1alpha1`) per enablement or reconcile a person commits: actor, installations, capability, inputs, pull requests, approval, rollout, probes, result — as custom resources in the release namespace, read and written with the pod's ServiceAccount (the CRD, a Role and its binding are rendered). Off: no ServiceAccount token is mounted, `get_action` and `list_actions` refuse with the reason and `get_info` reports `actions.configured: false`." }, + "governanceRecordPolicy": { + "type": "boolean", + "description": "Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount create, update or delete the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`, decision #99): a record written by anyone else would read as reviewed governance. Needs Kubernetes 1.30 or later." + }, "installCRD": { "type": "boolean", "description": "Render the `actions.platform-manager.giantswarm.io` CRD from the chart's templates (so upgrades follow the chart). Off when the CRD is delivered separately." diff --git a/helm/giantswarm-platform-manager/values.yaml b/helm/giantswarm-platform-manager/values.yaml index e1468d52..f4042cdc 100644 --- a/helm/giantswarm-platform-manager/values.yaml +++ b/helm/giantswarm-platform-manager/values.yaml @@ -64,6 +64,12 @@ actions: # templates (so upgrades follow the chart). Off when the CRD is delivered # separately. installCRD: true + # -- Render a ValidatingAdmissionPolicy and its binding that let only this + # release's ServiceAccount create, update or delete the reviewed-governance + # records (`governancerecords.platform-manager.giantswarm.io`, decision #99): + # a record written by anyone else would read as reviewed governance. Needs + # Kubernetes 1.30 or later. + governanceRecordPolicy: true approvals: # -- klaus-gateway's base URL as reached from the pod (for example diff --git a/internal/actions/actions.go b/internal/actions/actions.go index cd05e3e3..ffe7b3fd 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -130,6 +130,11 @@ type Spec struct { // reviewed-governance record (GovernanceRecord) once the team approved a // governance change of the action. Values only. GovernanceAfter map[string]string `json:"governanceAfter,omitempty"` + // GovernanceBase is, per installation, the reviewed-governance record the + // plan compared with (RecordIdentity, "none" for none): merge_action + // merges a stage of an approved governance change, and writes the record, + // only while the installation's record is still that one. + GovernanceBase map[string]string `json:"governanceBase,omitempty"` } // Skipped is an installation of a wave's set that is not a target. diff --git a/internal/actions/records.go b/internal/actions/records.go index 391c5f23..77bbddee 100644 --- a/internal/actions/records.go +++ b/internal/actions/records.go @@ -2,6 +2,7 @@ package actions import ( "context" + "errors" "fmt" "time" @@ -42,14 +43,36 @@ type GovernanceRecord struct { HeadSHA string `json:"headSHA,omitempty"` // RecordedAt is when it was written, RFC 3339. RecordedAt string `json:"recordedAt"` + // Disabled: the Action that wrote it disabled the platform; Governance + // is the governance from before the disable, which an enable is + // compared with. + Disabled bool `json:"disabled,omitempty"` } +// RecordNone is the identity of no record. +const RecordNone = "none" + +// RecordIdentity names a record as a plan compared with it, for the merge's +// compare-and-swap: the Action that wrote it, when, and its version; none +// for no record. +func RecordIdentity(r *GovernanceRecord) string { + if r == nil { + return RecordNone + } + return r.Action + "@" + r.RecordedAt + "@" + r.ResourceVersion +} + +// ErrRecordMoved is a record that is no longer the one a plan compared with. +var ErrRecordMoved = errors.New("the reviewed-governance record changed since the plan") + // RecordStore reads and writes the reviewed-governance records. type RecordStore interface { // GetRecord answers ErrNotFound for an installation without a record. GetRecord(ctx context.Context, installation string) (*GovernanceRecord, error) - // PutRecord creates or replaces an installation's record. - PutRecord(ctx context.Context, r GovernanceRecord) error + // PutRecord creates or replaces an installation's record, only while the + // record is still the one named expected (RecordIdentity; RecordNone for + // none): otherwise ErrRecordMoved. + PutRecord(ctx context.Context, r GovernanceRecord, expected string) error } // GetRecord reads installation's reviewed-governance record. @@ -70,7 +93,7 @@ func (c *Client) GetRecord(ctx context.Context, installation string) (*Governanc } // PutRecord creates installation's record, or replaces it. -func (c *Client) PutRecord(ctx context.Context, r GovernanceRecord) error { +func (c *Client) PutRecord(ctx context.Context, r GovernanceRecord, expected string) error { if r.RecordedAt == "" { r.RecordedAt = time.Now().UTC().Format(time.RFC3339) } @@ -84,12 +107,19 @@ func (c *Client) PutRecord(ctx context.Context, r GovernanceRecord) error { "spec": spec, }} res := c.c.Resource(RecordGVR).Namespace(c.ns) - old, err := res.Get(ctx, r.Installation, metav1.GetOptions{}) + current, err := c.GetRecord(ctx, r.Installation) switch { - case apierrors.IsNotFound(err): + case errors.Is(err, ErrNotFound): + if expected != RecordNone { + return fmt.Errorf("%w: %s has none now, the plan compared with %s", ErrRecordMoved, r.Installation, expected) + } _, err = res.Create(ctx, u, metav1.CreateOptions{}) case err == nil: - u.SetResourceVersion(old.GetResourceVersion()) + if RecordIdentity(current) != expected { + return fmt.Errorf("%w: %s holds %s now, the plan compared with %s", ErrRecordMoved, r.Installation, RecordIdentity(current), expected) + } + // The API server holds the version too: a write in between conflicts. + u.SetResourceVersion(current.ResourceVersion) _, err = res.Update(ctx, u, metav1.UpdateOptions{}) } if err != nil { diff --git a/internal/chart/chart_test.go b/internal/chart/chart_test.go index a78ab074..f04244bd 100644 --- a/internal/chart/chart_test.go +++ b/internal/chart/chart_test.go @@ -2,6 +2,7 @@ package chart import ( "bytes" + "fmt" "os/exec" "path/filepath" "reflect" @@ -249,3 +250,39 @@ func TestRegistrationDisplayName(t *testing.T) { }) } } + +// D-GO-35: only the release's ServiceAccount writes or deletes the +// reviewed-governance records: the policy names it and denies the rest; +// switched off, neither the policy nor its binding renders. +func TestOnlyTheManagerWritesGovernanceRecords(t *testing.T) { + objects, errText := render(t) + if objects == nil { + t.Fatal(errText) + } + var policy, binding map[string]any + for _, o := range objects { + switch o["kind"] { + case "ValidatingAdmissionPolicy": + policy = o + case "ValidatingAdmissionPolicyBinding": + binding = o + } + } + if policy == nil || binding == nil { + t.Fatalf("no admission policy for the governance records") + } + ops := fmt.Sprint(at(policy, "spec.matchConstraints.resourceRules")) + expr := fmt.Sprint(at(policy, "spec.validations")) + if !strings.Contains(ops, "governancerecords") || !strings.Contains(ops, "DELETE") || !strings.Contains(expr, `request.userInfo.username == "system:serviceaccount:default:giantswarm-platform-manager"`) || fmt.Sprint(at(binding, "spec.validationActions")) != "[Deny]" { + t.Fatalf("policy %v / %v, binding %v", ops, expr, at(binding, "spec.validationActions")) + } + off, errText := render(t, "--set", "actions.governanceRecordPolicy=false") + if off == nil { + t.Fatal(errText) + } + for _, o := range off { + if k := fmt.Sprint(o["kind"]); strings.HasPrefix(k, "ValidatingAdmissionPolicy") { + t.Fatalf("%s rendered with the policy off", k) + } + } +} diff --git a/internal/e2e/governance_test.go b/internal/e2e/governance_test.go index 4bfc6703..49f4bc92 100644 --- a/internal/e2e/governance_test.go +++ b/internal/e2e/governance_test.go @@ -31,6 +31,7 @@ const ( keyMode = "mode" keyIdleTTL = "idleTTL" keySessions = "sessions" + keyGovernedServers = "governedServers" ) // withGovernanceReleases takes the meta chart and muster releases that @@ -66,7 +67,7 @@ func governedTestRowan(t *testing.T) *stack { // governedInputs make rowan governed and drop mcp-kubernetes from the // governed servers. func governedInputs() map[string]any { - return minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}}}) + return minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, keyGovernedServers: map[string]any{"mcp-kubernetes": nil}}}) } // approveAndMerge has carol approve the action and alice merge it once green. @@ -108,7 +109,7 @@ func seedRecord(t *testing.T, st *stack, values string) { if err != nil { t.Fatal(err) } - if err := actions.New(st.dyn, actionsNamespace).PutRecord(t.Context(), actions.GovernanceRecord{Installation: rowan, Governance: snap.JSON(), Action: "seeded", ApprovedBy: carol}); err != nil { + if err := actions.New(st.dyn, actionsNamespace).PutRecord(t.Context(), actions.GovernanceRecord{Installation: rowan, Governance: snap.JSON(), Action: "seeded", ApprovedBy: carol}, actions.RecordNone); err != nil { t.Fatal(err) } } @@ -543,7 +544,7 @@ func TestTheReviewedGovernanceIsRecordedAtTheMerge(t *testing.T) { requireLog(t, st, "governance_record_written", "action="+merged.Name) // A later change that needs no review leaves the record as it is. - next, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, "governedServers": map[string]any{"mcp-kubernetes": nil}}, keySessions: map[string]any{keyIdleTTL: "2h"}})}) + next, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(map[string]any{keyGovernanceInput: map[string]any{keyMode: agentplatform.GovernanceGoverned, keyGovernedServers: map[string]any{"mcp-kubernetes": nil}}, keySessions: map[string]any{keyIdleTTL: "2h"}})}) if isErr || next.Action == nil || next.Action.Status.Approval.Decision != actions.DecisionNotRequired { t.Fatalf("a change without governance: %v %s", isErr, text) } @@ -646,3 +647,175 @@ func TestAHandRevertOfAReviewedGovernanceChangeAsksTheReview(t *testing.T) { t.Fatalf("a commit after a hand revert: %+v %+v", again.Action.Status.Approval, g) } } + +// D-GO-33: an approved governance action parked while the team reviewed and +// merged another one is not merged: its plan compared with a record that is +// no longer the installation's, so its approval does not cover it. The +// record stays the newer review's. +func TestAStaleApprovedGovernanceActionIsNotMergedOverANewerRecord(t *testing.T) { + st := governedTestRowan(t) + aliceC, carolC := st.mcpClient(t, aliceToken), st.mcpClient(t, carolToken) + first, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || first.Action == nil { + t.Fatalf("first: %v %s", isErr, text) + } + approveAndMerge(t, st, first.Action.Name) + safe := map[string]any{keyGovernanceInput: map[string]any{keyGovernedServers: map[string]any{"skill-manager": map[string]any{"safe": []any{"list_skills"}}}}} + parked, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(safe)}) + if isErr || parked.Action == nil || len(parked.Action.Spec.Governance) == 0 { + t.Fatalf("parked: %v %s", isErr, text) + } + if _, text, isErr := decide(t, carolC, tools.ToolApproveAction, map[string]any{tools.ArgAction: parked.Action.Name}); isErr { + t.Fatalf("approve parked: %s", text) + } + gov, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || gov.Action == nil { + t.Fatalf("governed: %v %s", isErr, text) + } + newer := approveAndMerge(t, st, gov.Action.Name) + if _, text, isErr := mergeCall(t, aliceC, parked.Action.Name); !isErr || !strings.Contains(text, "changed since action "+parked.Action.Name+" was planned") { + t.Fatalf("the parked action's merge: %v %s", isErr, text) + } + requireLog(t, st, "governance_record_moved_since_plan", "action="+parked.Action.Name) + if r := record(t, st); r == nil || r.Action != newer.Name { + t.Fatalf("the record after the refused merge: %+v", r) + } +} + +// D-GO-36: after a reviewed disable the record holds the governance from +// before it; the enable that brings the platform back is compared with it +// under its own line, and nothing is logged as changed outside. +func TestAnEnableAfterAReviewedDisableIsNoOutsideChange(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + approveAndMerge(t, st, out.Action.Name) + st.ghs.addFile(acmeMCs, installations.CollectionsKustomizationPath(rowan), collectionsKustomization(clustermcpservers.DexAppRotation)) + st.ghs.addRepo(fleetBasesRepo, platformBaseFiles) + d, text, isErr := disableCall(t, aliceC, map[string]any{tools.ArgInstallation: rowan, tools.ArgCapability: installations.AgentPlatform, tools.ArgMode: string(tools.ModeCommit), tools.ArgReason: commitReason}) + if isErr || d.Action == nil { + t.Fatalf("disable: %v %s", isErr, text) + } + disabled := approveAndMerge(t, st, d.Action.Name) + if r := record(t, st); r == nil || !r.Disabled || r.Action != disabled.Name { + t.Fatalf("the record after the reviewed disable: %+v", r) + } + st.ghs.addFile(acmeMCs, installations.CollectionsKustomizationPath(rowan), collectionsKustomization(platformDexApp)) + logs := len(st.logs.String()) + again, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || again.Action == nil { + t.Fatalf("enable again: %v %s", isErr, text) + } + g := again.Action.Spec.Governance[rowan] + if len(g.Lines) != 1 || !strings.HasPrefix(g.Lines[0], "the platform comes back after the reviewed disable "+disabled.Name) || again.Action.Status.Approval.Decision == actions.DecisionNotRequired { + t.Fatalf("the enable after the disable: %+v %+v", again.Action.Status.Approval, g) + } + if strings.Contains(st.logs.String()[logs:], "governance_on_record_changed_outside") { + t.Fatal("the enable after a reviewed disable logged an outside change") + } +} + +// D-GO-40: a disable of values that differ from the record shows the +// outside change and deletes the governance the team reviewed, not the +// values on record. +func TestADisableAfterAnOutsideEditIsComparedWithTheRecord(t *testing.T) { + st := governedTestRowan(t) + merged := governedThenTrustedOutside(t, st) + st.ghs.addFile(acmeMCs, installations.CollectionsKustomizationPath(rowan), collectionsKustomization(clustermcpservers.DexAppRotation)) + st.ghs.addRepo(fleetBasesRepo, platformBaseFiles) + d, text, isErr := disableCall(t, st.mcpClient(t, aliceToken), map[string]any{tools.ArgInstallation: rowan, tools.ArgCapability: installations.AgentPlatform, tools.ArgMode: string(tools.ModeCommit), tools.ArgReason: commitReason}) + if isErr || d.Action == nil { + t.Fatalf("disable: %v %s", isErr, text) + } + g := d.Action.Spec.Governance[rowan] + if len(g.Lines) == 0 || !strings.Contains(g.Lines[0], "what the team reviewed in action "+merged.Name) || !slices.Contains(g.Loosens, "mode governed → trusted") || !strings.Contains(d.Action.Spec.GovernanceAfter[rowan], `"mode":"governed"`) { + t.Fatalf("the disable after an outside edit: %+v after %q", g, d.Action.Spec.GovernanceAfter[rowan]) + } + // What the disable deletes is the reviewed governance: governed goes + // with it, after the line that says the values are deleted. + deleted := slices.IndexFunc(g.Lines, func(l string) bool { return strings.Contains(l, "deleted with the platform") }) + if deleted < 0 || !slices.Contains(g.Lines[deleted:], "mode governed → trusted") { + t.Fatalf("the disable deletes the values on record, not the reviewed governance: %+v", g.Lines) + } +} + +// D-GO-40: the record is written when the stage is merged, not while the +// merge waits on a check. +func TestTheRecordWaitsForTheWholeStage(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + if _, text, isErr := decide(t, st.mcpClient(t, carolToken), tools.ToolApproveAction, map[string]any{tools.ArgAction: out.Action.Name}); isErr { + t.Fatalf("approve: %s", text) + } + prs := st.remote.PullRequests() + st.remote.SetChecks(prs[0].PullRequest, commit.ChecksSuccess) + st.remote.SetChecks(prs[1].PullRequest, commit.ChecksPending) + if m, text, isErr := mergeCall(t, aliceC, out.Action.Name); isErr || m.Waiting == "" { + t.Fatalf("merge with a pending check: %v %s", isErr, text) + } + if r := record(t, st); r != nil { + t.Fatalf("a record while the stage waits: %+v", r) + } + st.remote.SetChecks(prs[1].PullRequest, commit.ChecksSuccess) + if _, text, isErr := mergeCall(t, aliceC, out.Action.Name); isErr { + t.Fatalf("merge: %s", text) + } + if r := record(t, st); r == nil || r.Action != out.Action.Name { + t.Fatalf("no record after the stage: %+v", r) + } +} + +// D-GO-40: a reviewed governance change taken back by hand is audited +// when its actor withdraws it, and when a read finds its fileset gone. +func TestTheRevertOfAGovernanceChangeIsAuditedOnEveryPath(t *testing.T) { + t.Run("withdrawn", func(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + first, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: minimalInputs(nil)}) + if isErr || first.Action == nil { + t.Fatalf("first: %v %s", isErr, text) + } + approveAndMerge(t, st, first.Action.Name) + gov, text, isErr := commitCall(t, aliceC, tools.ToolReconcileCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || gov.Action == nil { + t.Fatalf("governed: %v %s", isErr, text) + } + reviewed := approveAndMerge(t, st, gov.Action.Name) + for _, pr := range st.remote.PullRequests() { + for _, mine := range reviewed.Status.PullRequests { + if pr.Merged && pr.URL == mine.URL { + st.revertOutside(t, pr.PullRequest, dave) + } + } + } + if _, text, isErr := decide(t, aliceC, tools.ToolDenyAction, map[string]any{tools.ArgAction: reviewed.Name, tools.ArgReason: "taken back"}); isErr { + t.Fatalf("withdraw: %s", text) + } + requireLog(t, st, "governance_change_reverted", "action="+reviewed.Name) + }) + t.Run("fileset gone", func(t *testing.T) { + st := governedTestRowan(t) + aliceC := st.mcpClient(t, aliceToken) + out, text, isErr := commitCall(t, aliceC, tools.ToolEnableCapability, map[string]any{tools.ArgInstallation: rowan, tools.ArgInputs: governedInputs()}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + merged := approveAndMerge(t, st, out.Action.Name) + for _, pr := range st.remote.PullRequests() { + if pr.Merged { + st.revertOutside(t, pr.PullRequest, dave) + } + } + if got := getAction(t, aliceC, merged.Name); got.Status.State != actions.StateRemoved { + t.Fatalf("the action after its fileset left: %s", got.Status.State) + } + requireLog(t, st, "governance_change_reverted", "action="+merged.Name) + }) +} diff --git a/internal/plan/plan.go b/internal/plan/plan.go index 1add6d68..f4d26c0f 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -365,7 +365,10 @@ type Installation struct { // a commit carrying one is approved by a second person, on test // installations too. Governance *GovernanceChange `json:"governance,omitempty"` - DexClients []DexClient `json:"dexClients"` + // GovernanceRecord names the reviewed-governance record the plan + // compared with (actions.RecordIdentity); empty where none was read. + GovernanceRecord string `json:"governanceRecord,omitempty"` + DexClients []DexClient `json:"dexClients"` // DexConnectors and DexStaffConnectors are the ids of the hubs' // connectors the rendered Dex patch declares under // oidc.customer.connectors and oidc.giantswarm.connectors diff --git a/internal/tools/approval.go b/internal/tools/approval.go index 18540338..8bc6a887 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -315,6 +315,11 @@ func (t *Tools) merge(ctx context.Context, args map[string]any) (any, error) { if allMerged(a, st.Name) { return nil, stageNotEnabled(a, *st) } + // An approved governance change merges only onto the record its plan + // compared with. + if err := t.governanceRecordCurrent(ctx, a, st.Name); err != nil { + return nil, err + } // The releases running now, read before the stage's merges: Flux's // history may have dropped them by the first watch. running := t.runningReleases(ctx, a, st.Name) diff --git a/internal/tools/capability.go b/internal/tools/capability.go index 50b20016..10e267e9 100644 --- a/internal/tools/capability.go +++ b/internal/tools/capability.go @@ -337,7 +337,7 @@ func (t *Tools) capabilityPlan(ctx context.Context, tool string, args map[string // reviewed action left: the dry run names it, and a record changed // outside the manager, before anyone commits. if content && e.Refused == "" && env.defOf(e.Name, def).Name == installations.AgentPlatform { - e.Governance, _ = t.governanceChange(ctx, e.Installation) + e.Governance, _, e.GovernanceRecord = t.governanceChange(ctx, e.Installation) } } if unknown := unknownRotations(rotate, out.Installations); len(unknown) > 0 { diff --git a/internal/tools/commit.go b/internal/tools/commit.go index 8009954b..6ea3c201 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -158,6 +158,9 @@ func (t *Tools) capabilityCommit(ctx context.Context, tool string, args map[stri if after != "" { spec.GovernanceAfter = map[string]string{one: after} } + if p.GovernanceRecord != "" { + spec.GovernanceBase = map[string]string{one: p.GovernanceRecord} + } if g != nil { // One person never changes the governance alone: the Team review, // on a test installation too. diff --git a/internal/tools/disable.go b/internal/tools/disable.go index ef823240..e964bfa3 100644 --- a/internal/tools/disable.go +++ b/internal/tools/disable.go @@ -404,7 +404,7 @@ func (t *Tools) disableCommit(ctx context.Context, args map[string]any) (any, er // Deleting governed values takes the governance away with the platform: // a second person approves it, and the governance before the disable is // what a later enable is compared with. - governance, after, err := t.governanceOfDisable(ctx, env.c, out.Plan) + governance, after, record, err := t.governanceOfDisable(ctx, env.c, out.Plan) if err != nil { return nil, fmt.Errorf("%s: %w; nothing is committed", tool, err) } @@ -421,6 +421,9 @@ func (t *Tools) disableCommit(ctx context.Context, args map[string]any) (any, er if after != "" { spec.GovernanceAfter = map[string]string{one: after} } + if record != "" { + spec.GovernanceBase = map[string]string{one: record} + } if governance != nil { spec.Governance = map[string]plan.GovernanceChange{one: *governance} spec.Changes[one] = append([]string{governance.Summary()}, spec.Changes[one]...) diff --git a/internal/tools/governance.go b/internal/tools/governance.go index 5c0b3f54..ca6b43e5 100644 --- a/internal/tools/governance.go +++ b/internal/tools/governance.go @@ -62,57 +62,85 @@ func governanceOutside(r *actions.GovernanceRecord) string { return "the governance on record differs from what the team reviewed in action " + r.Action + " (changed outside the manager, reverted by hand or merged out of order); the change is shown against what was reviewed" } +// governanceReenabled is the line of a plan that brings back a platform a +// reviewed disable took away: the change is shown against the governance +// from before the disable. +func governanceReenabled(r *actions.GovernanceRecord) string { + return "the platform comes back after the reviewed disable " + r.Action + ": the change is shown against the governance from before it" +} + // governanceUnrecorded is the line of a plan whose governance is in play // on an installation without a reviewed-governance record: the team review -// confirms it (fail closed; installations from before the record get one -// with their first reviewed commit). +// confirms the governance this commit leaves, shown whole against the +// chart's defaults (fail closed; installations from before the record get +// one with their first reviewed commit). func governanceUnrecorded(installation string) string { - return "no reviewed governance is on record for " + installation + ": the team review confirms the governance this commit leaves" + return "no reviewed governance is on record for " + installation + ": the team review confirms the governance this commit leaves, shown whole against the chart's defaults" } // against compares the configs repository's governance (current) and what -// a commit leaves (next) with the reviewed record: a difference between the -// record and current is logged as an unreviewed change and leads the -// change, which is shown against the record; without a record, governance -// in play leads with governanceUnrecorded. The lines from base to next -// follow, base the record or current. -func (t *Tools) against(ctx context.Context, installation string, current, next plan.GovernanceSnapshot) (plan.GovernanceChange, plan.GovernanceSnapshot) { +// a commit leaves (next) with the reviewed record, and answers the change, +// its base and the record's identity the plan compared with (for the +// merge's compare-and-swap): +// - a record that current matches: the change from current to next; +// - a record of a reviewed disable while no values are on record: the +// change against the governance from before the disable, led by +// governanceReenabled; +// - any other difference: an unreviewed change, logged +// (governance_on_record_changed_outside), the change shown against the +// record and led by governanceOutside; +// - no record, with governance in play on either side: led by +// governanceUnrecorded and shown against an empty governance (the +// chart's defaults), so the review lists every value it confirms. +func (t *Tools) against(ctx context.Context, installation string, current, next plan.GovernanceSnapshot) (plan.GovernanceChange, plan.GovernanceSnapshot, string) { lead := "" base := current - if reviewed, r, found := t.reviewedGovernance(ctx, installation); found { + reviewed, r, found := t.reviewedGovernance(ctx, installation) + switch { + case found && r.Disabled && len(current) == 0: + lead, base = governanceReenabled(r), reviewed + case found: if outside := plan.GovernanceBetween(reviewed, current); len(outside.Lines) > 0 { t.d.Log.Warn("governance_on_record_changed_outside", identity.LogAttr(ctx), "audit", true, "installation", installation, "action", r.Action, "governance", strings.Join(outside.Lines, "; ")) lead, base = governanceOutside(r), reviewed } - } else if current.InPlay() || next.InPlay() { + case current.InPlay() || next.InPlay(): t.d.Log.Warn("governance_unrecorded", identity.LogAttr(ctx), "audit", true, "installation", installation) - lead = governanceUnrecorded(installation) + lead, base = governanceUnrecorded(installation), plan.GovernanceSnapshot{} } g := plan.GovernanceBetween(base, next) if lead != "" { g.Lines = append([]string{lead}, g.Lines...) g.Loosens = append([]string{lead}, g.Loosens...) } - return g, base + if !found { + r = nil + } + return g, base, actions.RecordIdentity(r) } // governanceChange is the governance a commit of p changes, against the -// reviewed record (against), and the snapshot the commit leaves; nil for a -// plan that changes none or writes no agent-platform values. -func (t *Tools) governanceChange(ctx context.Context, p plan.Installation) (*plan.GovernanceChange, string) { +// reviewed record (against), the snapshot the commit leaves and the +// record's identity the plan compared with; nil for a plan that changes +// none or writes no agent-platform values. +func (t *Tools) governanceChange(ctx context.Context, p plan.Installation) (*plan.GovernanceChange, string, string) { current, next, ok, unreadable := plan.GovernanceFile(p) if !ok { - return nil, "" + return nil, "", "" } if unreadable { g := plan.GovernanceUnreadable() - return &g, "" + _, r, found := t.reviewedGovernance(ctx, p.Name) + if !found { + r = nil + } + return &g, "", actions.RecordIdentity(r) } - g, _ := t.against(ctx, p.Name, current, next) + g, _, record := t.against(ctx, p.Name, current, next) if len(g.Lines) == 0 { - return nil, next.JSON() + return nil, next.JSON(), record } - return &g, next.JSON() + return &g, next.JSON(), record } // governanceAfter is the snapshot a commit of p leaves: the agent-platform @@ -126,29 +154,29 @@ func governanceAfter(p plan.Installation) string { } // governanceOfDisable is the governance a disable removes with the values -// (against the reviewed record), and the snapshot the disable records as -// what it leaves: the governance before it (the record where the values -// differ from it), so a later enable is compared with that once the -// reviewed disable is merged. -func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Disablement) (*plan.GovernanceChange, string, error) { +// (against the reviewed record), the snapshot the disable records as what +// it leaves — the governance before it (the record where the values differ +// from it), so a later enable is compared with that once the reviewed +// disable is merged — and the record's identity the plan compared with. +func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Disablement) (*plan.GovernanceChange, string, string, error) { for _, f := range d.Files { if f.Change != plan.ChangeDelete || !strings.HasSuffix(f.Path, "/apps/agent-platform/configmap-values.yaml.patch") { continue } owner, repo, err := gh.SplitRepo(f.Repository) if err != nil { - return nil, "", err + return nil, "", "", err } content, err := gh.ReadFile(ctx, c, owner, repo, f.Path) if err != nil { - return nil, "", fmt.Errorf("the agent-platform values on record could not be read as you to see the governance they carry: %w", err) + return nil, "", "", fmt.Errorf("the agent-platform values on record could not be read as you to see the governance they carry: %w", err) } current, err := plan.GovernanceSnapshotOf(content) if err != nil { g := plan.GovernanceUnreadable() - return &g, "", nil + return &g, "", actions.RecordNone, nil } - lead, base := t.against(ctx, d.Name, current, current) + lead, base, record := t.against(ctx, d.Name, current, current) g, changes := plan.GovernanceDeleted(base) if len(lead.Lines) > 0 { g.Lines = append(slices.Clone(lead.Lines), g.Lines...) @@ -156,19 +184,53 @@ func (t *Tools) governanceOfDisable(ctx context.Context, c *gh.Client, d plan.Di changes = true } if !changes { - return nil, base.JSON(), nil + return nil, base.JSON(), record, nil } - return &g, base.JSON(), nil + return &g, base.JSON(), record, nil + } + return nil, "", "", nil +} + +// governanceRecordCurrent refuses the merge of an installation's stage of +// an approved governance change whose plan compared with another record +// than the installation holds now (decision #99's compare-and-swap, review +// D-GO-33): what the team approved was a change from that record, and a +// stale approval must not displace a newer review. A new plan, against the +// record now, and its review follow. +func (t *Tools) governanceRecordCurrent(ctx context.Context, a *actions.Action, installation string) error { + if t.d.Records == nil || a.Status.Approval == nil || a.Status.Approval.Decision != actions.DecisionApproved { + return nil + } + if _, changes := actions.GovernanceOf(a)[installation]; !changes { + return nil + } + _, r, found := t.reviewedGovernance(ctx, installation) + if !found { + r = nil + } + want, ok := a.Spec.GovernanceBase[installation] + if now := actions.RecordIdentity(r); !ok || now != want { + t.d.Log.Warn("governance_record_moved_since_plan", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "planned", want, "now", now) + return fmt.Errorf("%s: the reviewed governance of %s changed since action %s was planned (the plan compared with %s, the record is %s now): its approval does not cover it; deny it with %s and commit the change again for a new review — nothing is merged", ToolMergeAction, installation, a.Name, orNone(want), now, ToolDenyAction) + } + return nil +} + +func orNone(s string) string { + if s == "" { + return "no record (an action from before the compare-and-swap)" } - return nil, "", nil + return s } // recordReviewed writes installation's reviewed-governance record once // merge_action merged the stage of an approved governance change there: the // governance the action's commit leaves, the approver and the configs pull -// request's merged head. Never for an action the team did not approve, or -// one that changes no governance there. A write that fails is logged and -// answered: the next plan then asks the review again (fail closed). +// request's merged head, only while the record is still the one the +// action's plan compared with (compare-and-swap). Never for an action the +// team did not approve, or one that changes no governance there. A write +// that fails is logged and answered: the next plan then asks the review +// again (fail closed). func (t *Tools) recordReviewed(ctx context.Context, a *actions.Action, installation string) string { if t.d.Records == nil || a.Status.Approval == nil || a.Status.Approval.Decision != actions.DecisionApproved { return "" @@ -186,8 +248,8 @@ func (t *Tools) recordReviewed(ctx context.Context, a *actions.Action, installat head = pr.HeadSHA } } - r := actions.GovernanceRecord{Installation: installation, Governance: after, Action: a.Name, ApprovedBy: a.Status.Approval.DecidedBy, HeadSHA: head} - if err := t.d.Records.PutRecord(ctx, r); err != nil { + r := actions.GovernanceRecord{Installation: installation, Governance: after, Action: a.Name, ApprovedBy: a.Status.Approval.DecidedBy, HeadSHA: head, Disabled: a.Spec.Kind == actions.KindDisable} + if err := t.d.Records.PutRecord(ctx, r, a.Spec.GovernanceBase[installation]); err != nil { t.d.Log.Warn("governance_record_not_written", identity.LogAttr(ctx), "audit", true, "action", a.Name, "installation", installation, "error", err.Error()) return fmt.Sprintf("(The reviewed governance of %s could not be recorded: %v; the next commit there asks the team's review again.)", installation, err) } diff --git a/internal/tools/governance_test.go b/internal/tools/governance_test.go index 6bc19235..bff3f76b 100644 --- a/internal/tools/governance_test.go +++ b/internal/tools/governance_test.go @@ -7,6 +7,7 @@ import ( "log/slog" "net/http" "net/http/httptest" + "slices" "strings" "testing" @@ -143,7 +144,7 @@ func TestGovernanceStoredOrRefused(t *testing.T) { func TestGovernanceChangeOfUnreadableValues(t *testing.T) { tl := &Tools{d: Deps{Log: slog.New(slog.DiscardHandler)}} p := plan.Installation{Name: rowan, Files: []plan.File{{Path: rowanValues, Change: plan.ChangeUpdate, Current: "governance: [\n", Content: emptyValues}}} - g, after := tl.governanceChange(context.Background(), p) + g, after, _ := tl.governanceChange(context.Background(), p) if g == nil || len(g.Loosens) != 1 || after != "" { t.Fatalf("unreadable values: %+v %q", g, after) } @@ -162,14 +163,23 @@ func TestGovernanceRecordMovedWhenTheValuesCannotBeRead(t *testing.T) { } } -// fakeRecords is an in-memory RecordStore. -type fakeRecords struct{ put []actions.GovernanceRecord } +// fakeRecords is an in-memory RecordStore holding at most one record. +type fakeRecords struct { + have *actions.GovernanceRecord + put []actions.GovernanceRecord +} func (f *fakeRecords) GetRecord(context.Context, string) (*actions.GovernanceRecord, error) { - return nil, actions.ErrNotFound + if f.have == nil { + return nil, actions.ErrNotFound + } + return f.have, nil } -func (f *fakeRecords) PutRecord(_ context.Context, r actions.GovernanceRecord) error { +func (f *fakeRecords) PutRecord(_ context.Context, r actions.GovernanceRecord, expected string) error { + if actions.RecordIdentity(f.have) != expected { + return actions.ErrRecordMoved + } f.put = append(f.put, r) return nil } @@ -183,11 +193,15 @@ func TestOnlyAnApprovedGovernanceChangeIsRecorded(t *testing.T) { decision string governs bool writes bool + noAfter bool + base string }{ - {"approved with a governance change", actions.DecisionApproved, true, true}, - {"approved without one", actions.DecisionApproved, false, false}, - {"not required, with one", actions.DecisionNotRequired, true, false}, - {"merged without approval, with one", actions.DecisionMergedWithoutApproval, true, false}, + {"approved with a governance change", actions.DecisionApproved, true, true, false, actions.RecordNone}, + {"approved without one", actions.DecisionApproved, false, false, false, actions.RecordNone}, + {"not required, with one", actions.DecisionNotRequired, true, false, false, actions.RecordNone}, + {"merged without approval, with one", actions.DecisionMergedWithoutApproval, true, false, false, actions.RecordNone}, + {"approved without the governance it leaves", actions.DecisionApproved, true, false, true, actions.RecordNone}, + {"approved over another record than its plan's", actions.DecisionApproved, true, false, false, "older@2026-11-26T00:00:00Z@1"}, } { t.Run(c.name, func(t *testing.T) { records := &fakeRecords{} @@ -199,6 +213,10 @@ func TestOnlyAnApprovedGovernanceChangeIsRecorded(t *testing.T) { a.Spec.Governance = nil } a.Spec.GovernanceAfter = map[string]string{rowan: `{"governance":{"mode":"governed"}}`} + if c.noAfter { + a.Spec.GovernanceAfter = nil + } + a.Spec.GovernanceBase = map[string]string{rowan: c.base} a.Status.Approval = &actions.Approval{Decision: c.decision, DecidedBy: "carol"} tl.recordReviewed(context.Background(), a, rowan) if (len(records.put) == 1) != c.writes { @@ -217,3 +235,31 @@ func TestMergedWithoutApprovalDecidesNoGovernanceFoundAfterTheCommit(t *testing. t.Fatal("a governance change found after the commit, merged outside the manager, counts as decided") } } + +// D-GO-34, D-GO-40: without a record (none, or one that does not parse), +// governance in play on either side leads with the unrecorded line and is +// shown whole against the chart's defaults, the platform's parts included. +func TestWithoutARecordTheReviewShowsTheWholeGovernance(t *testing.T) { + const parts = "governance:\n roleFloors:\n platformManager: [approve_action, merge_action]\n" + for _, c := range []struct { + name string + have *actions.GovernanceRecord + current, next string + }{ + {"no record", nil, parts, parts}, + {"a record that does not parse", &actions.GovernanceRecord{Action: "x", Governance: "{"}, parts, parts}, + {"only the values on record carry it", nil, parts, emptyValues}, + } { + t.Run(c.name, func(t *testing.T) { + tl := &Tools{d: Deps{Log: slog.New(slog.DiscardHandler), Records: &fakeRecords{have: c.have}}} + p := plan.Installation{Name: rowan, Files: []plan.File{{Path: rowanValues, Change: plan.ChangeUpdate, Current: c.current, Content: c.next}}} + g, _, record := tl.governanceChange(context.Background(), p) + if g == nil || !strings.HasPrefix(g.Lines[0], "no reviewed governance is on record for rowan") || record != actions.RecordNone { + t.Fatalf("got %+v, record %q", g, record) + } + if c.next == parts && !slices.Contains(g.Lines, "roleFloors.platformManager +approve_action +merge_action") { + t.Fatalf("the governance confirmed is not shown whole: %+v", g) + } + }) + } +} diff --git a/internal/tools/wave.go b/internal/tools/wave.go index d1e342c2..f2130146 100644 --- a/internal/tools/wave.go +++ b/internal/tools/wave.go @@ -121,6 +121,12 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string } spec.GovernanceAfter[p.Name] = after } + if p.GovernanceRecord != "" { + if spec.GovernanceBase == nil { + spec.GovernanceBase = map[string]string{} + } + spec.GovernanceBase[p.Name] = p.GovernanceRecord + } if g != nil { if spec.Governance == nil { spec.Governance = map[string]plan.GovernanceChange{} From a1ac13fe16578c43b73db8c58ac746d8df7d04c9 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 15:38:55 +0100 Subject: [PATCH 23/27] docs: the record's compare-and-swap, admission policy and disabled mark docs/governance.md describes the merge's compare-and-swap, the admission policy on the records, the whole-governance review without a record and the enable after a reviewed disable (review D-GO-33 to D-GO-36). --- docs/governance.md | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/docs/governance.md b/docs/governance.md index 1ff0f357..37563c52 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -144,11 +144,20 @@ governance as it is, such as an explicit `trusted` dropped, is none. The plan compares the configs repository with what the team reviewed, kept per installation in a reviewed-governance record (decision #99): a `GovernanceRecord` in the manager's namespace, named after the -installation, beside the Action records (`crd-governancerecords.yaml`; only the manager's ServiceAccount may write -it). It holds the reviewed governance (the snapshot of the governance values), the Action whose merge wrote it, +installation, beside the Action records (`crd-governancerecords.yaml`). Only the manager's ServiceAccount may +write it: RBAC grants no one else a right, and a ValidatingAdmissionPolicy (`actions.governanceRecordPolicy`, on by +default, Kubernetes 1.30 or later) refuses a create, update or delete by any other identity, cluster admins and +GitOps controllers included. It holds the reviewed governance (the snapshot of the governance values), the Action whose merge wrote it, the approver and the configs pull request's merged head. `merge_action` writes it, and nothing else does: when it merges an installation's stage of an Action that changes the governance there and that the team approved, the -governance that Action's commit leaves becomes the record (`governance_record_written`). An action that needs no +governance that Action's commit leaves becomes the record (`governance_record_written`). + +The merge is a compare-and-swap. Each Action records which record its plan compared with (`spec.governanceBase`: +the writing action, its time and version, or `none`). `merge_action` merges a stage of an approved governance +change only while the installation's record is still that one, and writes it with the same check: an approval +given against an older record does not cover a newer review, so such a merge is refused +(`governance_record_moved_since_plan`); the actor denies the action and commits the change again for a new +review. An action that needs no review, one merged outside the manager, a revert and the Actions' order or states never change it. Every plan, the dry run and the commit included, compares the governance in the configs repository with the @@ -164,16 +173,19 @@ A revert of a reviewed governance change that a read of the Action finds (the wa withdrawal) is audited (`governance_change_reverted`); the record keeps what was reviewed, so the next plan shows the revert. -An installation without a record is fail closed: where its governance is in play (the values carry the meta -chart's `governance`), every commit asks the team's review, led by "no reviewed governance is on record", until a -reviewed commit is merged and becomes the record (`governance_unrecorded`). That is the migration of the +An installation without a record is fail closed: where its governance is in play (the values on record or what +the commit leaves carry the meta chart's `governance`), every commit asks the team's review, led by "no reviewed +governance is on record", until a reviewed commit is merged and becomes the record (`governance_unrecorded`). That +review shows the governance the commit leaves whole, against the chart's defaults (an empty governance), with +the loosening marks, so the team confirms what it can see. That is the migration of the installations from before the record: their first commit is reviewed. A record that cannot be read counts as none (`governance_record_unread`), and a record that could not be written after a merge is logged (`governance_record_not_written`) and leaves the next commit to ask the review again. -A `disable_capability` that deletes values carrying a governance is a loosening governance change. Its record, -once reviewed and merged, is the governance before the disable, so an enable that brings the platform back trusted -asks the review too. +A `disable_capability` that deletes values carrying a governance is a loosening governance change, the deleted +governance being the reviewed one. Its record, once reviewed and merged, is the governance before the disable, +marked `disabled`: an enable that brings the platform back is compared with it under its own line ("the platform +comes back after the reviewed disable") and asks the review, and nothing is logged as changed outside. Between the plan and the pull requests the commit or wave reads the values on the default branch again: a governance merged in between is recorded as a loosening governance change of the action (`status.governance`), so the review shows it and only a member of the reviewers' team approves it (`governance_record_moved`). From ffe990fe224de503335eac5d347ca18b9244c15c Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Fri, 27 Nov 2026 00:14:35 +0100 Subject: [PATCH 24/27] docs: condense tool approval docs --- definitions/agent-platform/README.md | 4 +- docs/governance.md | 336 +++++++----------- helm/giantswarm-platform-manager/README.md | 4 +- .../values.schema.json | 4 +- helm/giantswarm-platform-manager/values.yaml | 13 +- 5 files changed, 137 insertions(+), 224 deletions(-) diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 5c4e90f9..966011d8 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -9,7 +9,7 @@ policy decides once, and what the definition drops. The render library reads it. | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | -| `governance.yaml` | muster's built-in governance roles and the floors of each, Giant Swarm's own platform parts the definition renders on every installation (`platform`: the Platform Manager's role floors, its governed server with its safe list, the connector admins and workflow editors; decisions #92, #93), and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | +| `governance.yaml` | muster's built-in governance roles and the floors of each, Giant Swarm's own platform parts the definition renders on every installation (`platform`: the Platform Manager's role floors, its governed server with its safe list, the connector admins and workflow editors), and the meta chart's own `governedServers` by source, copied from the releases and held to them by `TestGovernanceMatchesMusterAndTheChart` (sibling checkouts): the floors no safe list may name, the role an override may not change, and the chart's entries a first override is compared with. | | `features.yaml`, `probes.yaml` | The consistency features and their dimensions — a file dimension's key names the files and YAML paths it observes in the grammar the file's header documents, `catchAll: true` marks the kind's dimension for every other leaf, and what no dimension names the verify reports under the feature `other`; the live probes the verify runs. | ## What the definition derives, from where @@ -56,7 +56,7 @@ policy decides once, and what the definition drops. The render library reads it. | The Dev Portal's Organizations pages for everyone: `agentPlatform.organizations.enabled: true` in the Component's fragment (giantswarm/backstage#3393; an object-shaped key, which merges, so on a hand-kept portal too) | `organizations.portal.enabled`, or `organizations.enabled` on this installation; the choice read back from the fragment on record, else from the portal's own app-config, so every plan that renders a shared portal's fragment keeps the pages one installation turned on; off again only typed `false` where no installation of the portal has the switch on. Refused where no portal carries a section for the installation | | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | -| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`, `trusted` being the chart's default; and Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager/giantswarm-platform-manager`, always, and the overrides), the overrides of the chart's servers muster governs by source (a source the chart knows or a muster server key), each `{role, safe}` — Helm merges the maps, so a role or safe list left out keeps the chart's and a safe list typed replaces it — or `null`, which drops the source. The meta chart renders muster's governance configuration from both | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so a reconcile keeps them and no `kept` entry is needed. Refused, typed or read back, while no meta chart release renders the configuration (`GovernanceChart` in `render/agentplatform/governance.go` is unset until it is cut: a guessed floor would write keys a chart ignores, so an installation would read as governed while its muster is not); off the 4 chart line; under a `versions.chart` hold below that release; `governed` under a `versions.components.muster` hold below the muster release that reads it (`GovernanceMuster`), where the meta chart fails the render; and what muster refuses to start on or what would drop floors: a role it does not know (the schema), a role other than the chart's for one of its sources, any override of `giantswarm-platform-manager`, a server key without a role or naming a chart source under another key, a floor of any role on any safe list, a safe entry that is no tool name or is repeated, more than 64 per list, an entry with neither role nor safe list. muster's roles and floors and the chart's `governedServers` are in `governance.yaml`, held to both by a test. A commit that changes the governance against what the last reviewed action left is an Action that an active member of the governance reviewers' team other than the actor approves, on Giant Swarm's test installations too; the review shows what loosens first, then the change old → new ([docs/governance.md](../../docs/governance.md)) | +| The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`; Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager/giantswarm-platform-manager`, always, and the overrides of the chart's servers by source, each `{role, safe}` or `null` to drop it; Helm merges the maps, a typed safe list replaces the chart's) | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so no `kept` entry is needed. Refused, typed or read back, under the conditions in [docs/governance.md](../../docs/governance.md) (no chart release yet, off the 4 line, version holds, invalid roles or safe lists). A commit that changes the governance against what the last reviewed action left is an Action a second, active member of the governance reviewers' team approves, on Giant Swarm's test installations too | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/docs/governance.md b/docs/governance.md index 37563c52..c76ae9c5 100644 --- a/docs/governance.md +++ b/docs/governance.md @@ -6,57 +6,47 @@ changes it alone. ## What muster enforces -muster asks a person before an agent runs a tool the platform governs. Its governance configuration, rendered by -the agent-platform meta chart, has three parts: - -- the mode: `trusted` (the default) runs what the connectors' own settings allow; `governed` asks a person - before an agent runs any tool of a governed server that is not on that server's safe list, new and renamed - tools included, and before any of muster's own tools except its reads; -- the role floors: tools that ask agents in both modes on a governed server of that role. muster builds in its - own roles' floors and takes more from the configuration (`governance.roleFloors`, a union: nothing removes a - built-in floor); +muster asks a person before an agent runs a tool the platform governs. The agent-platform meta chart renders its +configuration: + +- the mode: `trusted` (default) runs what the connectors' own settings allow; `governed` asks before any tool of + a governed server that is not on its safe list (new and renamed tools included) and before any of muster's own + tools except its reads; +- the role floors: tools that ask agents in both modes on a governed server of that role (`governance.roleFloors`, + a union with muster's built-in floors); - the governed servers, each with a role and a safe list. ## Giant Swarm's own parts -muster and the agent-platform chart are open source and carry nothing of Giant Swarm (decision #92 of the epic). -This manager is Giant Swarm's, so the Giant Swarm flow lives here: the agent-platform definition renders these -parts on every installation it manages, as fixed platform parts. They are no inputs, and no input changes or -loosens them (`definitions/agent-platform/governance.yaml`, `platform`): +muster and the chart are open source and carry nothing of Giant Swarm. The definition renders these parts on every +installation as fixed platform parts, not inputs (`definitions/agent-platform/governance.yaml`, `platform`): -| Part | Renders | What it does | +| Part | Renders | Effect | |---|---|---| -| The Platform Manager's role floors | `governance.roleFloors: {platformManager: [approve_action, merge_action]}` | muster asks a person before an agent approves or merges an Action of this manager, in both modes; the manager cannot tell an agent from a person, since muster forwards the person's identity | -| The Platform Manager as a governed server | `governedServers.giantswarm-platform-manager/giantswarm-platform-manager: {role: platformManager, safe: [...]}`: muster's key for the MCPServer `giantswarm-platform-manager` in the manager's release namespace, `giantswarm-platform-manager`, outside muster's (`agent-platform`) | on `governed` every tool of this manager but its safe list asks agents; the floors hold in both modes | -| The connector admins | `muster.rbac.mcpServerEditor.subjects`: the groups `giantswarm-ad:giantswarm-admins` and `giantswarm-github:giantswarm:giantswarm-admins` | whoever holds muster's `mcpserver-editor` Role edits every connector in muster's namespace, sets its tool approval and alone lets an agent run a tool the connector asks for; the meta chart appends `tenants.platformTeam` | - -The role floors and the governed server are written where the meta chart takes the governance (the release -`GovernanceChart`, the 4 line, no chart hold below it); the connector admins on every installation on the 4 line, -which every chart there takes, with the same groups as the workflow editors (`muster.rbac.workflowEditor.subjects`, -muster's `workflow-editor` Role, who create, change and delete muster's workflows; decision #93). A -`governance.governedServers` input naming the Platform Manager's server, under any key, is refused; read back from -the record the platform's entry is rendered again. A server key of an installation's own may take the role -`platformManager`, which only adds its floors. - -Neither muster nor the chart builds these parts in, so the plan reads a record without them as without them: -removing `roleFloors` or the Platform Manager's entry out of band is a loosening governance change, and putting -them on record the first time is a tightening one that asks the review once. +| Platform Manager role floors | `governance.roleFloors: {platformManager: [approve_action, merge_action]}` | a person is asked before an agent approves or merges an Action, in both modes | +| Platform Manager as governed server | `governedServers.giantswarm-platform-manager/giantswarm-platform-manager: {role: platformManager, safe: [...]}` | on `governed` every tool but the safe list asks agents | +| Connector admins | `muster.rbac.mcpServerEditor.subjects`: groups `giantswarm-ad:giantswarm-admins`, `giantswarm-github:giantswarm:giantswarm-admins` | whoever holds muster's `mcpserver-editor` Role edits every connector and its tool approval; the meta chart appends `tenants.platformTeam` | + +The floors and the governed server are written where the meta chart takes governance (`GovernanceChart`, 4 line, +no chart hold below it); the connector admins on every 4-line installation, with the same groups as workflow +editors (`muster.rbac.workflowEditor.subjects`). A `governance.governedServers` input naming this manager's server +is refused; an installation's own server key may take the role `platformManager`, which only adds floors. Removing +`roleFloors` or the manager's entry out of band is a loosening change; recording them the first time is a +tightening one that asks the review once. ### Release order -The open-source chart and muster no longer govern the Platform Manager by themselves: a chart and muster that take -the governance on an installation whose values lack these parts let agents approve and merge Actions unasked. So -`GovernanceChart` and `GovernanceMuster` are set in the manager's release that precedes the chart release whose -`agent-platform.muster.governanceFloor` is set, and every 4-line installation is reconciled before the chart's -version range admits that release. `TestGovernanceGatesFollowTheChart` fails while the sibling agent-platform -checkout sets the floor and the gates are not set to it. The drift tests skip without sibling checkouts; CI should -set `AGENT_PLATFORM_CHECKOUT` and `MUSTER_CHECKOUT`. +A chart and muster that take governance on an installation without these parts let agents approve and merge +unasked. `GovernanceChart` and `GovernanceMuster` are set in the manager release that precedes the chart release +whose `agent-platform.muster.governanceFloor` is set, and every 4-line installation is reconciled before the +chart's version range admits it. `TestGovernanceGatesFollowTheChart` fails while the gates lag the sibling +agent-platform checkout. The drift tests skip without sibling checkouts; CI sets `AGENT_PLATFORM_CHECKOUT` and +`MUSTER_CHECKOUT`. ### Upgrading an installation by hand -An installation the manager does not reconcile (one enabled by hand) carries the same parts in its agent-platform -values when it moves to the chart with tool approval; the chart's own defaults are placeholder groups and no -governed server of Giant Swarm's: +An installation the manager does not reconcile carries the same parts in its agent-platform values when it moves +to the chart with tool approval (the chart's defaults are placeholders): ```yaml muster: @@ -81,133 +71,88 @@ governedServers: Write `governance.mode: governed` where an installation wrote `governance: governed`. Keep the editor lists non-empty: muster's chart fails the upgrade on an empty list while its old `system:authenticated` binding exists. -## The inputs +## Inputs -The agent-platform definition takes the mode and the overrides of the governed servers as inputs. Both are read -back from the configmap patch on record (`installations//apps/agent-platform/configmap-values.yaml.patch`), -so a reconcile keeps them. +Both are read back from the configmap patch on record +(`installations//apps/agent-platform/configmap-values.yaml.patch`), so a reconcile keeps them. | Input | Renders | Default | |---|---|---| -| `governance.mode` | the meta chart's `governance.mode`, written only as `governed` | `trusted`, the chart's default, not written | -| `governance.governedServers` | the meta chart's top-level `governedServers`: overrides by source, each `{role, safe}` or `null` | none: the chart's servers and safe lists apply | - -A source is one the meta chart knows (`agent-manager`, `kagent`, `model-manager`, `cluster-manager`, -`vm-manager`, `toolchain-manager`, `workspace-manager`, `skill-manager`, `mcp-kubernetes`) or a muster server key -(`` or `/`). Helm merges the maps: +| `governance.mode` | the meta chart's `governance.mode`, written only as `governed` | `trusted`, not written | +| `governance.governedServers` | top-level `governedServers`: overrides by source, each `{role, safe}` or `null` | none: the chart's servers apply | -- a source you leave out keeps the chart's entry; -- a role or safe list you leave out keeps the chart's; -- a safe list you type replaces the chart's list; -- `null` drops the source, and muster governs nothing for it. +A source is one the chart knows (`agent-manager`, `kagent`, `model-manager`, `cluster-manager`, `vm-manager`, +`toolchain-manager`, `workspace-manager`, `skill-manager`, `mcp-kubernetes`) or a muster server key (`` or +`/`). Helm merges the maps: an omitted source, role or safe list keeps the chart's; a typed safe +list replaces it; `null` drops the source. ```sh --input governance.mode=governed --input 'governance.governedServers={"skill-manager": {"safe": ["list_skills", "get_skill"]}}' ``` -The definition refuses, typed or read back: - -- any governance choice while no meta chart release renders muster's governance configuration. `GovernanceChart` - in `render/agentplatform/governance.go` stays unset until that release is cut: a guessed version would write - keys a chart ignores, so an installation would read as governed while its muster is not (decision #89 of the - epic). Set it, and `GovernanceMuster`, when the releases exist. -- an installation off the 4 chart line; -- a `versions.chart` hold below `GovernanceChart`; -- `governed` under a `versions.components.muster` hold below `GovernanceMuster`, where the meta chart fails the - render; -- what muster refuses to start on, or what would drop floors past it: - - a role muster does not know (the schema); - - a role other than the meta chart's for one of its sources: muster applies a role's floors by the server's - role, so a server's role is what the server is and an override may not change it; - - a server key of its own without a role, or one naming a chart source under another key - (`/agent-manager`, `-mcp-kubernetes`); - - a floor of any role on any safe list, the platform's role floors included; - - any override of `giantswarm-platform-manager`, Giant Swarm's own; - - a safe entry that is no tool name (`^[A-Za-z0-9_.-]{1,128}$`), a repeated one, more than 64 per list; - - an entry with neither role nor safe list. - -muster's built-in roles and floors and the chart's own `governedServers` are copied into -`definitions/agent-platform/governance.yaml` beside Giant Swarm's platform parts; -`TestGovernanceMatchesMusterAndTheChart` compares them with sibling checkouts of muster and agent-platform where -present (`MUSTER_CHECKOUT`, `AGENT_PLATFORM_CHECKOUT`). A muster or chart from before decision #92 that still -carries the Platform Manager's role or entry must agree with the platform's. +Refused, typed or read back: + +- any governance choice while `GovernanceChart` (`render/agentplatform/governance.go`) is unset, an installation + off the 4 chart line, or a `versions.chart` hold below it; +- `governed` under a `versions.components.muster` hold below `GovernanceMuster`; +- what muster refuses to start on or what would drop floors: an unknown role; a role other than the chart's for + one of its sources; a server key without a role or naming a chart source under another key; a floor of any role + on a safe list; any override of `giantswarm-platform-manager`; a safe entry that is no tool name + (`^[A-Za-z0-9_.-]{1,128}$`) or repeated, or more than 64 per list; an entry with neither role nor safe list. + +muster's built-in roles and floors and the chart's `governedServers` are copied into +`definitions/agent-platform/governance.yaml`; `TestGovernanceMatchesMusterAndTheChart` compares them with sibling +checkouts (`MUSTER_CHECKOUT`, `AGENT_PLATFORM_CHECKOUT`). ## What counts as a governance change -The plan compares the effective governance on both sides: the mode (absent is `trusted`), the role floors (a -floor that goes loosens), every server as muster governs it (a source the values leave alone is the chart's entry), muster's own `muster.muster.governance`, and, -once `GovernanceMuster` is set, a `components.muster` hold below it, and who may loosen approvals: the platform -team and the subjects of muster's editor bindings (absent editor subjects read as the Giant Swarm groups the -definition renders). A change that leaves the effective -governance as it is, such as an explicit `trusted` dropped, is none. - -The plan compares the configs repository with what the team reviewed, kept per installation in a -reviewed-governance record (decision #99): a `GovernanceRecord` in the manager's namespace, named after the -installation, beside the Action records (`crd-governancerecords.yaml`). Only the manager's ServiceAccount may -write it: RBAC grants no one else a right, and a ValidatingAdmissionPolicy (`actions.governanceRecordPolicy`, on by -default, Kubernetes 1.30 or later) refuses a create, update or delete by any other identity, cluster admins and -GitOps controllers included. It holds the reviewed governance (the snapshot of the governance values), the Action whose merge wrote it, -the approver and the configs pull request's merged head. `merge_action` writes it, and nothing else does: when it -merges an installation's stage of an Action that changes the governance there and that the team approved, the -governance that Action's commit leaves becomes the record (`governance_record_written`). - -The merge is a compare-and-swap. Each Action records which record its plan compared with (`spec.governanceBase`: -the writing action, its time and version, or `none`). `merge_action` merges a stage of an approved governance -change only while the installation's record is still that one, and writes it with the same check: an approval -given against an older record does not cover a newer review, so such a merge is refused -(`governance_record_moved_since_plan`); the actor denies the action and commits the change again for a new -review. An action that needs no -review, one merged outside the manager, a revert and the Actions' order or states never change it. - -Every plan, the dry run and the commit included, compares the governance in the configs repository with the -record, whether or not the plan writes the values file. A difference the record does not explain (an edit -outside the manager, a revert by hand, an older action merged after a newer one) is an unreviewed change: - -- the plan shows the change against the record, led by a loosening line that names the reviewed action; -- `governance_on_record_changed_outside` is logged; -- the next commit asks the team's review, even when it types the governance back; a commit with nothing to write - answers "nothing to commit" and names the difference. The reviewed commit, once merged, is the record. - -A revert of a reviewed governance change that a read of the Action finds (the watch, or `deny_action`'s -withdrawal) is audited (`governance_change_reverted`); the record keeps what was reviewed, so the next plan -shows the revert. - -An installation without a record is fail closed: where its governance is in play (the values on record or what -the commit leaves carry the meta chart's `governance`), every commit asks the team's review, led by "no reviewed -governance is on record", until a reviewed commit is merged and becomes the record (`governance_unrecorded`). That -review shows the governance the commit leaves whole, against the chart's defaults (an empty governance), with -the loosening marks, so the team confirms what it can see. That is the migration of the -installations from before the record: their first commit is reviewed. A record that cannot be read counts as -none (`governance_record_unread`), and a record that could not be written after a merge is logged -(`governance_record_not_written`) and leaves the next commit to ask the review again. - -A `disable_capability` that deletes values carrying a governance is a loosening governance change, the deleted -governance being the reviewed one. Its record, once reviewed and merged, is the governance before the disable, -marked `disabled`: an enable that brings the platform back is compared with it under its own line ("the platform -comes back after the reviewed disable") and asks the review, and nothing is logged as changed outside. -Between the plan and the pull requests the commit or wave reads the values on the default branch again: a -governance merged in between is recorded as a loosening governance change of the action (`status.governance`), -so the review shows it and only a member of the reviewers' team approves it (`governance_record_moved`). +The plan compares the effective governance on both sides: the mode (absent is `trusted`), role floors, every +server as muster governs it, `muster.muster.governance`, a `components.muster` hold below `GovernanceMuster`, and +who may loosen approvals (the platform team and the subjects of muster's editor bindings). A change that leaves +the effective governance as it is, such as an explicit `trusted` dropped, is none. + +### The reviewed-governance record + +The plan compares the configs repository with what the team reviewed: a `GovernanceRecord` per installation in +the manager's namespace (`governancerecords.platform-manager.giantswarm.io`). Only the manager's ServiceAccount +writes it; a ValidatingAdmissionPolicy (`actions.governanceRecordPolicy`, default on, Kubernetes 1.30+) refuses +every other identity, cluster admins and GitOps controllers included. `merge_action` writes it when it merges a +stage of an approved governance change (`governance_record_written`). + +- **Compare-and-swap.** Each Action records the record it was planned against (`spec.governanceBase`). + `merge_action` merges only while the record is still that one (`governance_record_moved_since_plan` + otherwise): deny the action and commit again for a new review. +- **Unreviewed difference.** Every plan, dry run included, compares the configs repository with the record. A + difference the record does not explain (edit outside the manager, revert by hand, older action merged late) + shows the change against the record led by a loosening line, logs `governance_on_record_changed_outside`, and + makes the next commit ask the review, even when it types the governance back. +- **No record fails closed.** Where governance is in play, every commit asks the review ("no reviewed + governance is on record"), showing the governance whole against the chart's defaults, until a reviewed commit + merges (`governance_unrecorded`). A record that cannot be read counts as none (`governance_record_unread`); one + that could not be written is logged (`governance_record_not_written`) and the next commit asks again. +- **Disable.** `disable_capability` that deletes governance is a loosening change; its record is the governance + before the disable, marked `disabled`, and a later enable is compared with it. +- **Moved between plan and pull requests.** The commit re-reads the default branch; governance merged meanwhile + becomes a loosening change of the action (`status.governance`, `governance_record_moved`). +- **Revert.** A revert of a reviewed change found by a read of the Action is audited + (`governance_change_reverted`); the record keeps what was reviewed. ## A second person approves every change -A commit whose plan changes the governance is recorded with the change on the Action (`spec.governance`, per -installation: `lines` old → new and `loosens`). The hub must store it; an Action CRD without the field is refused -before any pull request opens. The change rules are: +A plan that changes governance is recorded on the Action (`spec.governance`, per installation: `lines` old → new +and `loosens`). The hub's Action CRD must have the field, or the commit is refused before any pull request opens. -- such an action always asks for the Team review, also where every target is one of Giant Swarm's test - installations, which otherwise need none; -- `approve_action` refuses the actor, by login and by GitHub id; -- the approver must be an active member of the governance reviewers' team, a GitHub team the chart names - (`approvals.governanceTeam`, `org/team`), and a GitHub account of type `User`. The manager reads the membership - as the approver. When the team is unset or the membership cannot be read, nothing is approved; -- `merge_action` merges nothing before that decision; a stage merged outside the manager decides nothing for - the stages after it; -- an agent can propose such a change but never approve or merge it: muster asks a person before an agent's - `approve_action` and `merge_action`. +- The action always asks the Team review, on Giant Swarm's test installations too. +- `approve_action` refuses the actor, by login and GitHub id. +- The approver must be an active member of `approvals.governanceTeam` (`org/team`) and a GitHub account of type + `User`; the manager reads the membership as the approver. Team unset or membership unreadable: nothing is + approved. +- `merge_action` merges nothing before that decision; a stage merged outside the manager decides nothing for the + stages after it. +- An agent can propose such a change but never approve or merge it. -The review leads with the governance, before the reason, and with what loosens it before the change itself: +The review leads with the governance, loosening lines first: ```text *Governance:* this changes the platform's governance; a second person approves it, on test installations too. @@ -215,83 +160,54 @@ The review leads with the governance, before the reason, and with what loosens i • rowan: mode governed → trusted ``` -What loosens is never cut. A commit whose loosening lines do not fit in what Slack shows (1000 characters) is -refused: split it. The change lines that follow are cut at 1400 characters, the configs pull request named for the -rest. A change loosens governance, or may, when any of these hold: +Loosening lines are never cut: a commit whose lines exceed Slack's 1000 characters is refused, so split it. The +change lines are cut at 1400 characters with the configs pull request named. A change loosens governance, or may, +when: -- the mode leaves `governed`; -- a role floor goes; -- a source is no longer governed; -- a role changes; -- a safe entry is added, against the chart's list for a first override; one named like a write anywhere in its - name, camelCase words included (`kubernetes_delete`, `port_forward`, `drainNode`) or a floor of any role is marked; +- the mode leaves `governed`, a role floor goes, a source is no longer governed, or a role changes; +- a safe entry is added (against the chart's list for a first override); one named like a write anywhere in its + name, camelCase included (`kubernetes_delete`, `drainNode`), or a floor of any role is marked; - muster's own governance changes, or a muster hold drops below the release that enforces it; -- who may loosen approvals widens: a subject added to `tenants.platformTeam` (which the meta chart adds to the - connector-admin and workflow-editor bindings) or to `muster.rbac.mcpServerEditor.subjects` or - `muster.rbac.workflowEditor.subjects` (decision #97); a subject removed tightens; -- the record differs from what the last reviewed action left; -- the agent-platform values cannot be read on either side. - -Values from the record are escaped for Slack: no value carries a line, markup or a link into the review. +- who may loosen approvals widens: a subject added to `tenants.platformTeam`, + `muster.rbac.mcpServerEditor.subjects` or `muster.rbac.workflowEditor.subjects` (a removal tightens); +- the record differs from what the last reviewed action left, or the values cannot be read on either side. ## Audit -Each step logs one line per installation whose governance the action changes (`audit=true`). Every line carries -the action, the installation, the actor, the caller, the decision and who decided it, the change and whether it -loosens. +One line per installation whose governance the action changes (`audit=true`), with the action, installation, +actor, caller, decision, decider, change and whether it loosens. | Event | When | |---|---| | `governance_change_committed` | the commit, wave or disable opened the pull requests | | `governance_change_self_approval_refused` | the actor tried to approve their own change | -| `governance_change_approval_refused` | the approver is no active member of the team, no person, or their membership could not be read | -| `governance_change_approved` | a second person approved it; with the approver's login and id and how their membership was read | -| `governance_change_merged` | `merge_action` merged a stage of it; with the pull requests and their heads | -| `governance_change_merged_without_approval` | a pull request of it was merged outside the manager before the team approved, in any state of the action; read at the next read of the action | +| `governance_change_approval_refused` | approver not an active team member, no person, or membership unreadable | +| `governance_change_approved` | a second person approved (approver login and id, how membership was read) | +| `governance_change_merged` | `merge_action` merged a stage (pull requests and heads) | +| `governance_change_merged_without_approval` | a pull request merged outside the manager before approval; read at the next read of the action | | `governance_on_record_changed_outside` | a plan found the record's governance other than what the last reviewed action left | -| `governance_record_moved` | the values on the default branch changed between the plan and the pull requests | -| `governance_record_written` | `merge_action` merged an approved governance change: the installation's record now holds it | -| `governance_record_not_written`, `governance_record_unread` | the record could not be written or read; the next commit asks the review | -| `governance_unrecorded` | a plan found governance in play on an installation without a record | -| `governance_change_reverted` | a read of the Action found a reviewed governance change reverted on the default branch | +| `governance_record_moved` | the default branch changed between plan and pull requests | +| `governance_record_written` | the installation's record now holds an approved change | +| `governance_record_not_written`, `governance_record_unread` | the record could not be written or read | +| `governance_unrecorded` | governance in play on an installation without a record | +| `governance_change_reverted` | a reviewed change was found reverted on the default branch | ## What the manager does not cover -These limits are outside the manager: - -- someone with write access to `giantswarm/-configs` can merge a change to the values outside the - manager. Branch protection on those repositories (enforced for admins, re-approval after a new push, required - CODEOWNERS review) is asked of their owners. The manager does not prevent such a change. It detects it at the - next plan of the installation and asks the review then; a merge of one of its own Actions' pull requests - outside it is audited when the action is read next. -- whoever holds Kubernetes write rights on muster's HelmRelease or ConfigMap can change the configuration - directly. -- a second GitHub account that a person holds and that the team lists counts as a second person: team - membership is the control. +- Write access to `giantswarm/-configs` can merge a values change outside the manager. Branch + protection there (enforced for admins, re-approval after a push, required CODEOWNERS review) is asked of the + owners; the manager detects the change at the next plan and asks the review then. +- Kubernetes write rights on muster's HelmRelease or ConfigMap change the configuration directly. +- A second GitHub account a person holds and the team lists counts as a second person: team membership is the + control. -## This manager's own safe list +## This manager's safe list -The definition governs this manager (`giantswarm-platform-manager`, role `platformManager`, above). Its safe -list, the tools agents call unasked on `governed`, is: +Tools agents call unasked on `governed`: `get_info`, `list_installations`, `list_actions`, `get_action` and +`verify_capability` (read-only; the three list/get tools also refresh Action records from GitHub as the caller and +decide nothing). -| Tool | Why it is safe | -|---|---| -| `get_info` | who the caller is, the definitions and their schemas | -| `list_installations` | the installations and their capability states, read as the caller | -| `list_actions` | the Action records | -| `get_action` | one Action record | -| `verify_capability` | compares the repositories with a definition and writes nothing | - -`get_action`, `list_actions` and `list_installations` bring the Action records up to date with GitHub as the -caller as they read them: an action can move to rolling out, failed or removed, and the facts are posted to its -review thread or the team's standup channel. They follow what GitHub says and decide nothing. - -These tools stay asking: - -- `enable_capability`, `reconcile_capability` and `disable_capability` ask agents even for a dry run: muster - matches tool names, and the same tool commits with `mode: commit`. A separate plan tool would let agents - plan unasked. -- `verify_installation` records its result on the Action. -- `watch_action` moves stages and posts to the review thread. -- `deny_action` closes pull requests. -- `approve_action` and `merge_action` are floors and are never safe. +Everything else asks, because muster matches tool names: `enable_capability`, `reconcile_capability` and +`disable_capability` even for a dry run (the same tool commits with `mode: commit`), `verify_installation` +(records its result), `watch_action` (moves stages, posts to review threads), `deny_action` (closes pull +requests). `approve_action` and `merge_action` are floors, never safe. diff --git a/helm/giantswarm-platform-manager/README.md b/helm/giantswarm-platform-manager/README.md index d72c62f7..04b5e239 100644 --- a/helm/giantswarm-platform-manager/README.md +++ b/helm/giantswarm-platform-manager/README.md @@ -44,13 +44,13 @@ header; every other tool answers with the user token alone. | hub | string | `""` | Name of the hub installation this manager runs on. Its management-clusters repository holds the Dev Portal's app-config the registry also reads, and the hub side of every capability lands in its repositories. Empty leaves `list_installations` refusing with the reason; `get_info` reports `registry.configured: false`. | | actions.enabled | bool | `true` | Keep the Action records — one `Action` (`platform-manager.giantswarm.io/v1alpha1`) per enablement or reconcile a person commits: actor, installations, capability, inputs, pull requests, approval, rollout, probes, result — as custom resources in the release namespace, read and written with the pod's ServiceAccount (the CRD, a Role and its binding are rendered). Off: no ServiceAccount token is mounted, `get_action` and `list_actions` refuse with the reason and `get_info` reports `actions.configured: false`. | | actions.installCRD | bool | `true` | Render the `actions.platform-manager.giantswarm.io` CRD from the chart's templates (so upgrades follow the chart). Off when the CRD is delivered separately. | -| actions.governanceRecordPolicy | bool | `true` | Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount create, update or delete the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`, decision #99): a record written by anyone else would read as reviewed governance. Needs Kubernetes 1.30 or later. | +| actions.governanceRecordPolicy | bool | `true` | Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount write the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`). Needs Kubernetes 1.30 or later. | | approvals.gatewayURL | string | `""` | klaus-gateway's base URL as reached from the pod (for example `http://klaus-gateway.agent-platform.svc:8080`): the team-review endpoint an action's approval request goes to. Empty refuses `mode: commit` (nothing is committed that no one can approve); `get_info` reports `approvals.configured: false`. The requests carry the pod's projected ServiceAccount token in the gateway's audience; the gateway's `reviews.allowedCallers` must name this ServiceAccount. | | approvals.team | string | `""` | The team whose members decide, as the gateway names it. | | approvals.channel | string | `""` | The capability-owning team's channel the reviews land in (a Slack channel ID). | | approvals.noticeChannel | string | `""` | The channel told, without buttons, once an action's change is applied on a customer installation: who, what, why and the account engineer (the Account Engineers' channel ID); it never sees the review. Must differ from `channel`; empty sends no notice. | | approvals.standupChannel | string | `""` | The owning team's standup channel (a Slack channel ID): an action on Giant Swarm's test installations alone (the hub's customer's, not the hub) needs no review, and its merge is told here in one sentence. Empty refuses `mode: commit` on test installations; the hub and customer installations keep the review. | -| approvals.governanceTeam | string | `""` | The GitHub team whose active members approve an action that changes an installation's governance (`org/team`): approve_action checks the approver's membership as the approver and refuses when it cannot read it. Empty: no governance change can be approved. | +| approvals.governanceTeam | string | `""` | The GitHub team (`org/team`) whose active members approve an action that changes an installation's governance. Empty: none can be approved. | | approvals.audience | string | `"klaus-gateway"` | Audience of the projected ServiceAccount token the requests carry: the gateway's TokenReview audience. | | live.enabled | bool | `false` | Serve the live tools `verify_installation` and `watch_action` on `mcp.path`, beside every other tool: they read an installation through muster as the person the platform ID token muster forwards next to the bearer names (`X-Muster-Id-Token`). The chart's `MCPServer` then sets `auth.forwardIdentity: true`, which needs muster ≥ 5.31.0 and `oauth.enabled`. A call without a valid identity token is refused by the live tools, naming the header; the GitHub tools answer as before. Off: the live tools are not served, the live dimensions of every verify read not checked, and `get_info` reports `live.configured: false`. | | live.issuer | string | `""` | Issuer of the forwarded tokens: the platform identity provider's, `https://dex./dex` on an installation. Required with `live.enabled`. | diff --git a/helm/giantswarm-platform-manager/values.schema.json b/helm/giantswarm-platform-manager/values.schema.json index 1cd23e06..b2149847 100644 --- a/helm/giantswarm-platform-manager/values.schema.json +++ b/helm/giantswarm-platform-manager/values.schema.json @@ -13,7 +13,7 @@ }, "governanceRecordPolicy": { "type": "boolean", - "description": "Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount create, update or delete the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`, decision #99): a record written by anyone else would read as reviewed governance. Needs Kubernetes 1.30 or later." + "description": "Render a ValidatingAdmissionPolicy and its binding that let only this release's ServiceAccount write the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`). Needs Kubernetes 1.30 or later." }, "installCRD": { "type": "boolean", @@ -44,7 +44,7 @@ }, "governanceTeam": { "type": "string", - "description": "The GitHub team whose active members approve an action that changes an installation's governance (`org/team`): approve_action checks the approver's membership as the approver and refuses when it cannot read it. Empty: no governance change can be approved.", + "description": "The GitHub team (`org/team`) whose active members approve an action that changes an installation's governance. Empty: none can be approved.", "pattern": "^([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)?$" }, "noticeChannel": { diff --git a/helm/giantswarm-platform-manager/values.yaml b/helm/giantswarm-platform-manager/values.yaml index f4042cdc..0790d2e9 100644 --- a/helm/giantswarm-platform-manager/values.yaml +++ b/helm/giantswarm-platform-manager/values.yaml @@ -65,10 +65,9 @@ actions: # separately. installCRD: true # -- Render a ValidatingAdmissionPolicy and its binding that let only this - # release's ServiceAccount create, update or delete the reviewed-governance - # records (`governancerecords.platform-manager.giantswarm.io`, decision #99): - # a record written by anyone else would read as reviewed governance. Needs - # Kubernetes 1.30 or later. + # release's ServiceAccount write the reviewed-governance records + # (`governancerecords.platform-manager.giantswarm.io`). Needs Kubernetes 1.30 + # or later. governanceRecordPolicy: true approvals: @@ -96,10 +95,8 @@ approvals: # `mode: commit` on test installations; the hub and customer installations # keep the review. standupChannel: "" - # -- The GitHub team whose active members approve an action that changes - # an installation's governance (`org/team`): approve_action checks the - # approver's membership as the approver and refuses when it cannot read - # it. Empty: no governance change can be approved. + # -- The GitHub team (`org/team`) whose active members approve an action that + # changes an installation's governance. Empty: none can be approved. governanceTeam: "" # @schema pattern: ^([A-Za-z0-9-]+/[A-Za-z0-9_.-]+)?$ # -- Audience of the projected ServiceAccount token the requests carry: the # gateway's TokenReview audience. From d6c5eb44c66d5d7d3508eed9c4a22e8db951b7e3 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Mon, 30 Nov 2026 13:58:04 +0100 Subject: [PATCH 25/27] feat(agent-platform): wire the portal's workload identity for muster's inline approval The input portalWorkloadToken.enabled (off by default) binds muster's muster-approval-decider Role to the portal's ServiceAccount (muster.rbac.approvalDecider.subjects) and has the portal's chart project that ServiceAccount's token for audience muster and name it in muster.workloadTokenFile (backstage.musterWorkloadToken.enabled in the Component's values). The meta chart wires both only for a portal it deploys itself; a portal of the customer-portal definition is a release of its own. Refused while the meta chart, muster or portal chart release carrying it is unset (GovernanceChart, PortalWorkloadTokenChart), off the 4 line, under a hold below them, without a portal on the installation and while the portal's chart line admits no chart that projects the token. Read back from the binding's presence, so a reconcile keeps it. --- definitions/agent-platform/README.md | 3 +- definitions/agent-platform/features.yaml | 2 + definitions/agent-platform/schema.json | 16 ++ .../managergrants_readback_test.go | 1 + internal/installations/readback_test.go | 2 +- .../workloadtoken_readback_test.go | 38 +++++ internal/verify/verify_test.go | 4 +- render/agentplatform/input.go | 16 +- render/agentplatform/portal.go | 10 +- render/agentplatform/render.go | 10 +- render/agentplatform/workloadtoken.go | 92 ++++++++++++ render/agentplatform/workloadtoken_test.go | 138 ++++++++++++++++++ 12 files changed, 322 insertions(+), 10 deletions(-) create mode 100644 internal/installations/workloadtoken_readback_test.go create mode 100644 render/agentplatform/workloadtoken.go create mode 100644 render/agentplatform/workloadtoken_test.go diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index d8e7fd1a..01b3a410 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -5,7 +5,7 @@ policy decides once, and what the definition drops. The render library reads it. | File | What it is | |---|---| -| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), the platform's governance, `governance.mode` (`trusted`, the default, or `governed`) and `governance.governedServers` (default none, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | +| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), the portal's workload identity for muster, `portalWorkloadToken.enabled` (default false), the platform's governance, `governance.mode` (`trusted`, the default, or `governed`) and `governance.governedServers` (default none, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. A removal of kind `deleted-file` (`extras:`, one file, no YAML path) names a file the definition no longer renders: a reconcile deletes it, unlists it from the kustomization.yaml of its directory and lists the objects it declares for a person to delete after the merge; without one a reconcile keeps every file on record. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | @@ -57,6 +57,7 @@ policy decides once, and what the definition drops. The render library reads it. | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | | The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`; Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager/giantswarm-platform-manager`, always, and the overrides of the chart's servers by source, each `{role, safe}` or `null` to drop it; Helm merges the maps, a typed safe list replaces the chart's) | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so no `kept` entry is needed. Refused, typed or read back, under the conditions in [docs/governance.md](../../docs/governance.md) (no chart release yet, off the 4 line, version holds, invalid roles or safe lists). A commit that changes the governance against what the last reviewed action left is an Action a second, active member of the governance reviewers' team approves, on Giant Swarm's test installations too | +| The portal's own workload identity for muster's inline tool approval (giantswarm/giantswarm#38902): `muster.rbac.approvalDecider.subjects` binds `muster-approval-decider` to the portal's ServiceAccount `backstage/backstage`, and the Component's values set `backstage.musterWorkloadToken.enabled`, so the portal's chart projects the token (audience `muster`) and names it in `muster.workloadTokenFile` | `portalWorkloadToken.enabled`, default false; read back from the binding's presence. Refused while `GovernanceChart` or `PortalWorkloadTokenChart` is unset, off the 4 line, under a meta chart or muster hold below the releases, without a portal on the installation, and while the portal's chart line admits no chart that projects the token. muster must also trust the portal's dedicated client (`muster.muster.approval.trustedClients`), which this input does not write | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/definitions/agent-platform/features.yaml b/definitions/agent-platform/features.yaml index 8e8790d7..c9568612 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -137,4 +137,6 @@ features: - {id: portal-auth-provider, kind: backstage, key: agent-platform/app-config.yaml gs.authProvider / auth.providers} - {id: portal-database-client, kind: backstage, key: agent-platform/app-config.yaml backend.database.client} - {id: portal-extra-app-config, kind: backstage, key: agent-platform/values.yaml backstage.extraAppConfig (the Component's app-config file and its checksum)} + - {id: portal-workload-token, kind: backstage, key: "agent-platform/values.yaml backstage.musterWorkloadToken (the portal's projected token for muster, named in muster.workloadTokenFile)"} + - {id: portal-approval-decider, kind: configmap, key: "muster.rbac.approvalDecider (the portal's ServiceAccount bound to muster-approval-decider)"} - {id: portal-helmrelease-values-from, kind: backstage, key: agent-platform/kustomization.yaml patches (the HelmRelease valuesFrom patch)} diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index 879503a9..9e623df2 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -895,6 +895,22 @@ } } }, + "portalWorkloadToken": { + "type": "object", + "additionalProperties": false, + "description": "One choice: the portal's own workload identity for muster's inline tool approval.", + "properties": { + "enabled": { + "type": "boolean", + "default": false, + "x-source": "person", + "x-readback": {"file": "configmap", "key": "muster.rbac.approvalDecider", "kind": "present"}, + "x-feature": "portal", + "x-renders": ["configmap:muster.rbac.approvalDecider", "backstage:agent-platform/values:backstage.musterWorkloadToken"], + "description": "Let the portal decide tool approvals inline in its chat (giantswarm/giantswarm#38902): bind muster's Role muster-approval-decider to the portal's ServiceAccount backstage/backstage (muster.rbac.approvalDecider.subjects) and have the portal's chart project that ServiceAccount's token for audience muster and name it in muster.workloadTokenFile (backstage.musterWorkloadToken.enabled in the Component's values). muster takes a person's decision from the portal only with that token beside the person's; off, the default, the chat opens muster's approval page instead. Either half alone decides nothing. Needs a portal on this installation (the token is valid only in its own cluster), the 4 chart line, the meta chart and muster releases that ship the Role, and a portal chart line that admits the chart projecting the token; refused otherwise, and refused while either release is unset. muster must also trust the portal's dedicated client (muster.muster.approval.trustedClients), which this input does not write. Read back from the binding's presence in the configmap patch on record, so a reconcile keeps it." + } + } + }, "versions": { "type": "object", "additionalProperties": false, diff --git a/internal/installations/managergrants_readback_test.go b/internal/installations/managergrants_readback_test.go index c6437f6c..08c483fc 100644 --- a/internal/installations/managergrants_readback_test.go +++ b/internal/installations/managergrants_readback_test.go @@ -20,6 +20,7 @@ func managerGrantDefaults(choices map[string]any) map[string]any { "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, + inputPortalWorkloadToken: false, } maps.Copy(want, choices) return want diff --git a/internal/installations/readback_test.go b/internal/installations/readback_test.go index 2c3fa804..af808291 100644 --- a/internal/installations/readback_test.go +++ b/internal/installations/readback_test.go @@ -324,7 +324,7 @@ func TestDefaults(t *testing.T) { // The holds and their reasons, by component: none by default. holds := map[string]any{"muster": "", "valkey": "", "kagent": "", "agent-manager": "", "klaus-gateway": "", grantClusterManager: "", grantModelManager: "", grantSkillManager: ""} want := map[string]any{"modelServing": map[string]any{keyEnabled: false}, "aiChat": map[string]any{keyEnabled: false, "model": "claude-opus-5", keyProvider: "anthropic"}, - "scheduling": map[string]any{"singletonsCapacity": "any"}, "networkPolicy": map[string]any{"mcpBackends": map[string]any{}}, "llmRouting": map[string]any{"rateLimits": []any{}, "rateLimitsComment": ""}, "sessions": map[string]any{"idleTTL": ""}, keySkills: map[string]any{keyRepositories: []any{}}, + "scheduling": map[string]any{"singletonsCapacity": "any"}, "networkPolicy": map[string]any{"mcpBackends": map[string]any{}}, "llmRouting": map[string]any{"rateLimits": []any{}, "rateLimitsComment": ""}, "sessions": map[string]any{"idleTTL": ""}, keyPortalWorkloadToken: map[string]any{keyEnabled: false}, keySkills: map[string]any{keyRepositories: []any{}}, "hive": map[string]any{keyEnabled: false, "plans": map[string]any{keyRepositories: []any{}}, "magazine": map[string]any{"repository": ""}, boardRoadmap: map[string]any{"board": boardRoadmap, "teams": []any{}}}, "clusterManager": map[string]any{keyGitHub: map[string]any{grantExchangeField: map[string]any{keyEnabled: false}}}, diff --git a/internal/installations/workloadtoken_readback_test.go b/internal/installations/workloadtoken_readback_test.go new file mode 100644 index 00000000..bfe8f5e4 --- /dev/null +++ b/internal/installations/workloadtoken_readback_test.go @@ -0,0 +1,38 @@ +package installations + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + // keyPortalWorkloadToken and inputPortalWorkloadToken are the portal's + // workload identity for muster, read back as present or not. + keyPortalWorkloadToken = "portalWorkloadToken" + inputPortalWorkloadToken = keyPortalWorkloadToken + ".enabled" +) + +// The agent-platform definition reads the portal's workload identity back +// from the binding's presence in the configmap patch on record, so a +// reconcile keeps it; its absence reads back as off. +func TestPortalWorkloadTokenReadBack(t *testing.T) { + definition, found := FindCapability(AgentPlatform) + require.True(t, found) + for _, test := range []struct { + name string + patch string + want bool + }{ + {"bound", "muster:\n rbac:\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: backstage\n namespace: backstage\n", true}, + {"other bindings alone", "muster:\n rbac:\n mcpServerEditor:\n subjects: []\n", false}, + {"absent", "", false}, + } { + t.Run(test.name, func(t *testing.T) { + read := files(map[string]string{"acme/configs:" + definition.EnabledMarker("rowan"): test.patch}) + got, err := definition.ReadBack(t.Context(), read, readBackInstallation, readBackName, nil) + require.NoError(t, err) + require.Equal(t, test.want, got[inputPortalWorkloadToken]) + }) + } +} diff --git a/internal/verify/verify_test.go b/internal/verify/verify_test.go index 83e2edf9..98782987 100644 --- a/internal/verify/verify_test.go +++ b/internal/verify/verify_test.go @@ -672,11 +672,11 @@ func TestDrivenInputsAreThePersonsAndTheTyped(t *testing.T) { tenantInputs := []string{"tenants.platform.editors", "tenants.platform.users", "tenants.platformTeam"} governanceInputs := []string{"governance.governedServers", "governance.mode"} got, err := drivenInputs(def, Inputs{Values: doc("a.test", "acme", true)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"portalWorkloadToken.enabled", "scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("from the record: %v %v", got, err) } got, err = drivenInputs(def, Inputs{Values: doc("a.test", "acme", true), Typed: doc("b.test", "acme", false)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"portalWorkloadToken.enabled", "scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("with facts typed: %v %v", got, err) } } diff --git a/render/agentplatform/input.go b/render/agentplatform/input.go index ddd1ac85..7c14fe0e 100644 --- a/render/agentplatform/input.go +++ b/render/agentplatform/input.go @@ -198,6 +198,11 @@ type Input struct { // and the servers muster governs (governance.*), read back from the // configmap patch on record so a reconcile keeps it (governance.go). Governance Governance + // PortalWorkloadToken is the person's choice to wire the portal's + // workload identity for muster's inline approval + // (portalWorkloadToken.enabled, workloadtoken.go), read back from the + // configmap patch on record. + PortalWorkloadToken bool // Components are the components the policy gives the installation, by // name: its organisation's list and, where the policy names a Slack app // for the installation, the chat gateway. @@ -741,8 +746,11 @@ type document struct { } `json:"platform"` PlatformTeam *[]Subject `json:"platformTeam"` } `json:"tenants"` - Governance Governance `json:"governance"` - Versions Versions `json:"versions"` + Governance Governance `json:"governance"` + PortalWorkloadToken struct { + Enabled bool `json:"enabled"` + } `json:"portalWorkloadToken"` + Versions Versions `json:"versions"` } // MCPBackend is one in-cluster MCP backend the meta chart's network policy @@ -958,6 +966,7 @@ func Parse(raw any) (*Input, error) { in.PlatformTenant = PlatformTenant{Users: d.Tenants.Platform.Users, Editors: d.Tenants.Platform.Editors, PlatformTeam: d.Tenants.PlatformTeam, Viewers: d.MusterMcpServerViewers} in.Governance = d.Governance in.Governance.withoutPlatformServers() + in.PortalWorkloadToken = d.PortalWorkloadToken.Enabled in.selectLine(pol.targetLine(in.Installation)) if err := in.checkRecord(); err != nil { return nil, err @@ -1162,6 +1171,9 @@ func (in *Input) checkRecord() error { if err := in.checkGovernance(); err != nil { return err } + if err := in.checkPortalWorkloadToken(); err != nil { + return err + } if in.Installation.Private && in.klausGateway() && !holdAdmits(in.Versions.Components[componentMuster], "5.64.0") { return refuse(describe("versions.components.muster") + " excludes Muster 5.64.0 or later, required for the pinned gateway client document; move or lift the hold before applying the pins") } diff --git a/render/agentplatform/portal.go b/render/agentplatform/portal.go index a6d5dc49..aa0011f9 100644 --- a/render/agentplatform/portal.go +++ b/render/agentplatform/portal.go @@ -362,14 +362,20 @@ func (in *Input) portalAppConfig() render.Map { // alone changes nothing the HelmRelease sees), the OTLP export of the // backend's traces and its scraped metrics where the chart takes them, and, // for a chat on Vertex, the Google project and location the chart exports to -// the pod. No list: the portal's environment is the customer-portal +// the pod, and the portal's workload token for muster where +// portalWorkloadToken is on (workloadtoken.go). No list: the portal's environment is the customer-portal // definition's. func (in *Input) portalValues() render.Map { fragment := render.Map{e("filename", portalAppConfigFile), e("configMapRef", portalAppConfigMap)} if in.portalRollsOnFragment() { fragment = append(fragment, e("checksum", fmt.Sprintf("%x", sha256.Sum256(render.MustYAML(in.portalAppConfig()))))) } - m := render.Map{e("backstage", render.Map{e("extraAppConfig", []render.Map{fragment})})} + backstage := render.Map{e("extraAppConfig", []render.Map{fragment})} + if in.portalWorkloadToken() { + // The portal's workload token for muster (workloadtoken.go). + backstage = append(backstage, e("musterWorkloadToken", render.Map{e("enabled", true)})) + } + m := render.Map{e("backstage", backstage)} if in.portalExportsTraces() { observability := render.Map{e("otel", render.Map{ e("endpoint", portalOTLPEndpoint), e("protocol", "grpc"), e("headers", portalOTLPHeaders)})} diff --git a/render/agentplatform/render.go b/render/agentplatform/render.go index fcdaa9c8..457f9006 100644 --- a/render/agentplatform/render.go +++ b/render/agentplatform/render.go @@ -530,8 +530,14 @@ func (in *Input) musterValues() render.Map { muster = append(muster, e("extraCaFile", extraCaFile())) } out := render.Map{e("muster", append(muster, e("oauth", oauth)))} - if admins := in.connectorAdmins(); admins != nil { - out = append(out, render.Entry{Key: "rbac", Value: admins, Comment: "Giant Swarm's connector admins and workflow editors: the admin groups\nbound to muster's mcpserver-editor and workflow-editor Roles (the meta chart\nappends the platform team)."}) + rbac := in.connectorAdmins() + comment := "Giant Swarm's connector admins and workflow editors: the admin groups\nbound to muster's mcpserver-editor and workflow-editor Roles (the meta chart\nappends the platform team)." + if in.portalWorkloadToken() { + rbac = append(rbac, e("approvalDecider", in.approvalDecider())) + comment += "\nThe portal's ServiceAccount, bound to muster-approval-decider: muster takes\na person's inline approval decision only with its token beside theirs." + } + if rbac != nil { + out = append(out, render.Entry{Key: "rbac", Value: rbac, Comment: comment}) } return out } diff --git a/render/agentplatform/workloadtoken.go b/render/agentplatform/workloadtoken.go new file mode 100644 index 00000000..ca5d0ebf --- /dev/null +++ b/render/agentplatform/workloadtoken.go @@ -0,0 +1,92 @@ +package agentplatform + +import ( + "fmt" + + "github.com/Masterminds/semver/v3" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +// The portal's workload identity for muster (portalWorkloadToken.enabled). +// muster takes a person's inline approval decision, and a sign-in handoff +// ticket request, from the portal only with the portal backend's own +// projected ServiceAccount token (audience muster) beside the person's, and +// only from a ServiceAccount bound to its Role muster-approval-decider. The +// meta chart wires both only for a portal it deploys itself +// (components.backstage); a portal the customer-portal definition renders is +// a release of its own, so this definition wires it: +// +// - the configmap patch binds muster-approval-decider to the portal's +// ServiceAccount (muster.rbac.approvalDecider.subjects); +// - the Component's values have the portal's chart project the token and +// name it in muster.workloadTokenFile (backstage.musterWorkloadToken, an +// object key, so it merges with the portal's own values). +// +// Off by default. Either half alone decides nothing: a token without the +// binding fails muster's access review, a binding without a token sends +// none. The token is valid on the cluster its ServiceAccount lives in only, +// so the portal must run on this installation. + +// PortalWorkloadTokenChart is the first portal chart that takes +// backstage.musterWorkloadToken (giantswarm/backstage's tool-approval work). +// UNSET until that release exists: an earlier chart's schema refuses the key +// and the portal's HelmRelease fails, so while it is unset the input is +// refused (fail closed). Set it to the release once it is cut; tests set it +// to exercise the render. +var PortalWorkloadTokenChart = "" + +const ( + // inputPortalWorkloadToken is the input, by its schema path. + inputPortalWorkloadToken = "portalWorkloadToken.enabled" + // portalServiceAccount is the portal's ServiceAccount, the chart's name + // in the portal's namespace. + portalServiceAccount = "backstage" +) + +// portalWorkloadToken says whether the platform wires the portal's workload +// identity for muster; checkPortalWorkloadToken has refused it where it +// cannot hold. +func (in *Input) portalWorkloadToken() bool { return in.PortalWorkloadToken } + +// approvalDecider is muster.rbac.approvalDecider: the portal's ServiceAccount +// alone. +func (in *Input) approvalDecider() render.Map { + return render.Map{e("subjects", []render.Map{{e("kind", "ServiceAccount"), e("name", portalServiceAccount), e("namespace", backstageNamespace)}})} +} + +// checkPortalWorkloadToken refuses the input where it cannot hold: while no +// meta chart and muster release carry muster-approval-decider +// (GovernanceChart unset, the same tool-approval releases), off the 4 chart +// line, under a hold of either below them, without a portal running on this +// installation, and while the portal's chart line admits no chart that +// projects the token (PortalWorkloadTokenChart unset or above its line). +func (in *Input) checkPortalWorkloadToken() error { + if !in.portalWorkloadToken() { + return nil + } + if GovernanceChart == "" { + return refuse(fmt.Sprintf("%s needs the meta chart and muster releases that ship muster's approval-decider Role, and none is released yet", describe(inputPortalWorkloadToken))) + } + if in.Installation.ChartLine != lineFour { + return in.refuseOffLineFour(inputPortalWorkloadToken) + } + if !holdAdmits(in.Versions.Chart, GovernanceChart) { + return refuse(fmt.Sprintf("%s needs the meta chart %s or later, and %s holds it at %s; move or lift the hold first", describe(inputPortalWorkloadToken), GovernanceChart, describe("versions.chart"), in.Versions.Chart)) + } + if hold := in.Versions.Components[componentMuster]; hold != "" && (GovernanceMuster == "" || !floorAtLeast(hold, GovernanceMuster)) { + return refuse(fmt.Sprintf("%s needs the muster release that ships its approval-decider Role, and %s holds muster at %s, whose chart refuses the binding; move or lift the hold first", describe(inputPortalWorkloadToken), describe("versions.components.muster"), hold)) + } + p := in.hostedPortal() + if p == nil || p.Installation != in.Installation.Name { + return refuse(fmt.Sprintf("%s binds the portal's ServiceAccount in %s's own cluster, and no portal runs on %s: the token is valid only where its ServiceAccount lives", describe(inputPortalWorkloadToken), in.Installation.Name, in.Installation.Name)) + } + if PortalWorkloadTokenChart == "" || !portalChartAdmits(p.ChartLine, semver.MustParse(PortalWorkloadTokenChart)) { + floor := PortalWorkloadTokenChart + if floor == "" { + floor = "the release that projects the token (not released yet)" + } + return refuse(fmt.Sprintf("%s needs the portal chart %s or later, and the portal %s runs the chart line %q; move the portal's chart line first", describe(inputPortalWorkloadToken), floor, p.Domain, p.ChartLine)) + } + return nil +} diff --git a/render/agentplatform/workloadtoken_test.go b/render/agentplatform/workloadtoken_test.go new file mode 100644 index 00000000..cd814e47 --- /dev/null +++ b/render/agentplatform/workloadtoken_test.go @@ -0,0 +1,138 @@ +package agentplatform + +import ( + "errors" + "path/filepath" + "strings" + "testing" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +const ( + // testPortalWorkloadTokenChart is the portal chart the tests take as the + // first that projects the token. + testPortalWorkloadTokenChart = "3.53.0" + keyPortalWorkloadToken = "portalWorkloadToken" + // wantDecider is the binding the configmap patch carries. + wantDecider = "\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: backstage\n namespace: backstage\n" + // wantToken is the Component's values turning the projection on. + wantToken = "\n musterWorkloadToken:\n enabled: true\n" +) + +// withPortalWorkloadTokenReleases takes the meta chart, muster and portal +// chart releases as cut for the test. Not parallel, like +// withGovernanceReleases. +func withPortalWorkloadTokenReleases(t *testing.T) { + t.Helper() + withGovernanceReleases(t) + chart := PortalWorkloadTokenChart + PortalWorkloadTokenChart = testPortalWorkloadTokenChart + t.Cleanup(func() { PortalWorkloadTokenChart = chart }) +} + +// workloadTokenInput is the organizations-portal installation, whose portal +// runs on it, with the input on and the portal's chart line set. +func workloadTokenInput(t *testing.T, line string) (map[string]any, map[string]string) { + t.Helper() + input, secrets := loadInput(t, shapeOrganizationsPortal) + input[keyPortalWorkloadToken] = map[string]any{keyEnabled: true} + installation := input["installation"].(map[string]any) + portals := installation["portals"].([]any) + portals[0].(map[string]any)["chartLine"] = line + return input, secrets +} + +// componentValues is the Component's values file of a result. +func componentValues(t *testing.T, result *render.Result) string { + t.Helper() + for name, content := range result.Tree() { + if strings.HasSuffix(filepath.ToSlash(name), "/extras/backstage/agent-platform/values.yaml") { + return string(content) + } + } + t.Fatal("no Component values rendered") + return "" +} + +// On, with the releases cut and a portal on the installation whose chart +// line admits the projecting chart, the configmap patch binds the portal's +// ServiceAccount to muster-approval-decider and the Component's values have +// the portal's chart project the token; the binding reads back as the input +// (a reconcile keeps both). Off, neither renders. +func TestPortalWorkloadTokenRenders(t *testing.T) { + withPortalWorkloadTokenReleases(t) + input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") + result, err := Render(input, secrets, render.ModeCommit) + if err != nil { + t.Fatal(err) + } + if patch := platformPatch(t, result); !strings.Contains(patch, wantDecider) { + t.Fatalf("the patch binds no portal ServiceAccount:\n%s", patch) + } + if values := componentValues(t, result); !strings.Contains(values, wantToken) || !strings.Contains(values, "extraAppConfig") { + t.Fatalf("the Component's values project no token beside the fragment:\n%s", values) + } + + off, secrets := loadInput(t, shapeOrganizationsPortal) + result, err = Render(off, secrets, render.ModeCommit) + if err != nil { + t.Fatal(err) + } + if strings.Contains(platformPatch(t, result), "approvalDecider") || strings.Contains(componentValues(t, result), "musterWorkloadToken") { + t.Fatal("off, the patch or the Component's values carry the portal's workload identity") + } +} + +// While the releases are unset (the shipped state) the input is refused: +// fail closed, an earlier muster or portal chart refuses the keys. +func TestPortalWorkloadTokenIsRefusedUntilItsReleasesExist(t *testing.T) { + input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "portalWorkloadToken.enabled needs the meta chart and muster releases") { + t.Fatalf("got %v, want ErrInput naming the input and the missing release", err) + } + + withGovernanceReleases(t) + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "the release that projects the token (not released yet)") { + t.Fatalf("got %v, want ErrInput naming the missing portal chart release", err) + } +} + +// Where the input cannot hold, it is refused naming it: no portal on the +// installation, a portal chart line below the projecting chart, a hold of +// muster or the meta chart below the releases with the Role. +func TestPortalWorkloadTokenRefusals(t *testing.T) { + withPortalWorkloadTokenReleases(t) + for _, c := range []struct { + name string + input func() (map[string]any, map[string]string) + names string + }{ + {"a portal on another installation", func() (map[string]any, map[string]string) { + input, secrets := loadInput(t, shapePlatformTenantRetired) + input[keyPortalWorkloadToken] = map[string]any{keyEnabled: true} + return input, secrets + }, "no portal runs on garnet"}, + {"a portal chart line below the projecting chart", func() (map[string]any, map[string]string) { + return workloadTokenInput(t, ">=2.1.0 <3.0.0") + }, "needs the portal chart 3.53.0 or later"}, + {"a muster hold below the release", func() (map[string]any, map[string]string) { + input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") + input["versions"] = map[string]any{"components": map[string]any{componentMuster: ">=5.60.0 <5.61.0"}} + return input, secrets + }, "holds muster at"}, + {"a meta chart hold below the release", func() (map[string]any, map[string]string) { + input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") + input["versions"] = map[string]any{"chart": "4.180.0"} + return input, secrets + }, "needs the meta chart " + testGovernanceChart + " or later"}, + } { + t.Run(c.name, func(t *testing.T) { + input, secrets := c.input() + _, err := Render(input, secrets, render.ModeCommit) + if !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), inputPortalWorkloadToken) || !strings.Contains(err.Error(), c.names) { + t.Fatalf("got %v, want ErrInput naming the input and %q", err, c.names) + } + }) + } +} From f8aa62880fc3f345f1df46aafedfa2c1c86a8a40 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Mon, 30 Nov 2026 14:17:59 +0100 Subject: [PATCH 26/27] feat(agent-platform): make the portal's inline approval one input that trusts its client The input is now inlineApproval.enabled. Beside the decider binding and the projected token it names the portal's Dex client, backstage as the record reads it, as the portal's own (backstage.oidcClientId) and as muster's one trusted client (muster.muster.approval.trustedClients); a portal signing in through a client of its own is refused. The gates now check what the installation resolves to, not only that a release exists: InlineApprovalChart (the meta chart that sets the trusted-clients floor), InlineApprovalMuster (that floor) and PortalWorkloadTokenChart, a release candidate only where the installation or the portal's chart line follows them, the muster check with or without a hold. A portal on another installation is refused, naming the fallback to muster's approval page. The binding names the ServiceAccount the portal's values on record set (installation.portals[*].serviceAccount), else the chart's default, and the input reads back from that binding in the list, not from the key's presence. Tests cover the parsed subjects, a render and read-back round trip, the 3 line and release candidates. --- definitions/agent-platform/README.md | 4 +- definitions/agent-platform/features.yaml | 2 +- definitions/agent-platform/schema.json | 13 +- internal/installations/derive.go | 37 ++- internal/installations/derive_test.go | 20 ++ .../inlineapproval_readback_test.go | 77 +++++ .../managergrants_readback_test.go | 2 +- internal/installations/readback_test.go | 2 +- internal/installations/registry.go | 6 +- .../workloadtoken_readback_test.go | 38 --- internal/verify/verify_test.go | 4 +- render/agentplatform/inlineapproval.go | 177 +++++++++++ render/agentplatform/inlineapproval_test.go | 275 ++++++++++++++++++ render/agentplatform/input.go | 22 +- render/agentplatform/portal.go | 4 +- render/agentplatform/render.go | 10 +- render/agentplatform/workloadtoken.go | 92 ------ render/agentplatform/workloadtoken_test.go | 138 --------- render/portal.go | 4 + 19 files changed, 616 insertions(+), 311 deletions(-) create mode 100644 internal/installations/inlineapproval_readback_test.go delete mode 100644 internal/installations/workloadtoken_readback_test.go create mode 100644 render/agentplatform/inlineapproval.go create mode 100644 render/agentplatform/inlineapproval_test.go delete mode 100644 render/agentplatform/workloadtoken.go delete mode 100644 render/agentplatform/workloadtoken_test.go diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index 01b3a410..76b789c9 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -5,7 +5,7 @@ policy decides once, and what the definition drops. The render library reads it. | File | What it is | |---|---| -| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), the portal's workload identity for muster, `portalWorkloadToken.enabled` (default false), the platform's governance, `governance.mode` (`trusted`, the default, or `governed`) and `governance.governedServers` (default none, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | +| `schema.json` | JSON Schema (draft 2020-12, `additionalProperties: false`) of the inputs: the record under `installation` (read, never typed) and the ten choices, `modelServing.enabled` (default false), the singletons' placement, `scheduling.singletonsCapacity` (`any`, the default, or `on-demand`), the in-cluster MCP backends the network policy fences, `networkPolicy.mcpBackends` (default none), the LLM listener's rate limits, `llmRouting.rateLimits` (default none), with the comment above them, `llmRouting.rateLimitsComment`, how long an idle agent Session and its workspace directory live, `sessions.idleTTL` (default none, the chart's), the portal's AI chat, `aiChat.enabled` (default false) with `aiChat.model` and `aiChat.provider` (`anthropic` or `vertex`, with `aiChat.google.project` and `location`), the portal's skill repositories, `skills.repositories` (default none), the portal's Hive section, `hive.enabled` (default false) with its repositories and board, the managers' commit modes, `clusterManager.github.tokenExchange.enabled`, `modelManager.github.tokenExchange.enabled` and `agentManager.github.tokenExchange.enabled` (each default false), the skill-manager's sources, `skillManager.sources` (default none), and the GitHub App it reads them with, `skillManager.github.app.secretName` (default none), the platform-shipped default agent, `defaultAgent.enabled` (default true) and `defaultAgent.modelConfig` (default none), the bots whose posts reach the chat gateway's thread context, `klausGateway.slack.contextBotIDs` (default none), with the comment above them, `klausGateway.slack.contextBotIDsComment`, the bots admitted by their Slack profile name, `klausGateway.slack.contextBotNames` (default none), with the comment above them, `klausGateway.slack.contextBotNamesComment`, the Agent Platform organizations, `organizations.enabled` (default false) with `organizations.apiHostnames` (default none), `organizations.commit.enabled` and `organizations.portal.enabled` (each default false), the platform tenant's bindings, `tenants.platform.users`, `tenants.platform.editors` and `tenants.platformTeam`, and muster's MCP-server viewers, `musterMcpServerViewers` (each default unset, the chart's), the portal's inline tool approval, `inlineApproval.enabled` (default false), the platform's governance, `governance.mode` (`trusted`, the default, or `governed`) and `governance.governedServers` (default none, the chart's), and the version holds, `versions.chart` and `versions.components.` (each default none), with their reasons, `versions.reasons.chart` and `versions.reasons.components.` (the comment above the hold, default none). Every leaf carries `x-source`, `x-feature` and `x-renders`; a choice carries `x-readback`, the file — one, or several, the first on record holding the key answering — and key it is read back from, the kind where it is not the key's value (`present`, `host`, `installation`, `comment`, `entries`, `file`), and `unless`, keys of the file whose presence yields nothing. A choice that renders only under a switch carries `x-requires`, the switch's key: typed other than its default with the switch off, it is refused; read back, it renders nothing. `x-files` names each file's path, `` the installation and `` the installation hosting the portal the platform's portal section is written into, so a portal choice is read back where the section is rendered, whichever installation's plan reads it. | | `policy.yaml` | The fleet's decisions, keyed by the owning organisation: which components its installations run, the chat gateway's shape, the connector names a target's Dex registers for a hub (the organisation's plain name for the target's first hub of the organisation, the hub's own for every further one; `staff` names the organisations whose hubs' connectors go under `oidc.giantswarm`, each named after the hub, since dex-operator registers `-simple-oidc` there; `furtherByHand` the organisations whose further hubs' connectors the targets keep by hand, which no target renders; `exchangeThrough` the first hub's default exchange connector and per-target overrides, described in [federation-exchange.md](../../docs/federation-exchange.md); `labels` the name a target's login page shows for an organisation's hub connector, the hub's name for an organisation without one), the Teleport cluster and the poll interval of every OCIRepository the definition renders (`flux.sourceInterval`) — and, keyed by installation, where a Slack app exists, which is where the gateway runs, with the installation's own default agent, and which stage and organisations run the platform's release candidates. | | `removals.yaml` | Keys an enabled installation carries today that the definition does not render, each with the reason it is dropped: the template renders it, it becomes a referenced Secret, the platform does not read it, the customer-portal definition owns it, or it is a named migration (M12…) of a former input. A key of kind `kept` is not dropped: its replacement is not on the fleet yet (muster's trusted issuers the shared defaults do not derive, a connector pin, muster's provider token refresh threshold, the kagent controller's and the Postgres instances' on-demand pin, tuned resources, the installation's own Postgres databases with the kagent controller's mount of its fresh database, kagent's Harnesses, the toolchain-manager's switch and values with the kagent controller's tool image egress origins), so the plan carries it from the record into the render, comments included, and the comparison finds it as defined; the reason says what has to land before the key goes. A removal with `keptWhile` is kept the same way only while the render carries that path: the default ModelConfig's model pin and display name and the inlined ModelConfigs stay while the render carries `kagent.providers`, and go with M43 once it does not. The configmap patch is rendered whole, not edited: a hand-written key no input renders and no `kept` entry names, nested under a rendered block or not, is drift, and a reconcile removes it. A removal of kind `deleted-file` (`extras:`, one file, no YAML path) names a file the definition no longer renders: a reconcile deletes it, unlists it from the kustomization.yaml of its directory and lists the objects it declares for a person to delete after the merge; without one a reconcile keeps every file on record. | | `migrations.yaml` | Keys the definition renders that an installation enabled before a migration lacks (a referenced client Secret, the hub's token-exchange client in a spoke's Dex, the portal's Component, the edge's JWT provider, …), each with the migration that adds it: a leaf the record lacks under one of them is a planned change, not drift; so is a comma-separated scalar (kagent's `oidc-extra-audience`) whose only change is entries named as `[]`. | @@ -57,7 +57,7 @@ policy decides once, and what the definition drops. The render library reads it. | The skill catalog of the portal's agent creation: `agentPlatform.skills.repositories` in the Component's fragment, the GitHub repositories whose `SKILL.md` files the create flow offers — on a hand-kept portal too, since the list is the portal's own; none listed, no key, the plugin's empty catalog | the third choice, `skills.repositories` (default none), read back from the Component's fragment on record, else from the portal's own app-config (a hand-kept portal lists them there, and the list moves into the fragment at the next reconcile, the customer-portal definition keeping it in the app-config until then); refused where no portal carries a section for the installation | | The portal's Hive section (Plans, Roadmap and the product magazine at `/hive`) in the Component's fragment: the `plans` block — the plan repositories, the magazine's repository (its `data` and `main` branches, the plugin's defaults) and GitHub through the grant server on this muster — and the `roadmap` block — the board, its default teams and pro on this muster, each `muster` entry naming the server's `toolPrefix` where it differs from its name —, and on a rendered portal the shared extension list with the Hive's pages (`#extensionsAgentPlatformHive`, `AiChat` before `Hive` and `GrafanaDashboards` after it where they are on); a hand-kept portal keeps its own list. No credential: both backends forward the person's ID token from this installation's Dex and muster runs the servers' tools with the person's own grants | the choice `hive.enabled` with `hive.plans.repositories` (refused empty), `hive.magazine.repository` (default none) and `hive.roadmap.board` (`roadmap`, the default, or `customer`) with `hive.roadmap.teams` (default none), read back from the fragment on record, else from the portal's own app-config, so a portal that carries the section by hand reads back on. Refused where the portal is not hosted on this installation, or `installation.mcpServers` lists no server with `githubGrant` or none with `board` (pro, by its label `muster.giantswarm.io/type: mcp-pro`; its `spec.toolPrefix` read as `toolPrefix`) | | The platform's governance (Governing tool calls, giantswarm/giantswarm#38902): the meta chart's `governance` (`mode`, written only as `governed`; Giant Swarm's `roleFloors`, always) and `governedServers` (Giant Swarm's `giantswarm-platform-manager/giantswarm-platform-manager`, always, and the overrides of the chart's servers by source, each `{role, safe}` or `null` to drop it; Helm merges the maps, a typed safe list replaces the chart's) | `governance.mode` and `governance.governedServers`, read back from the configmap patch on record, so no `kept` entry is needed. Refused, typed or read back, under the conditions in [docs/governance.md](../../docs/governance.md) (no chart release yet, off the 4 line, version holds, invalid roles or safe lists). A commit that changes the governance against what the last reviewed action left is an Action a second, active member of the governance reviewers' team approves, on Giant Swarm's test installations too | -| The portal's own workload identity for muster's inline tool approval (giantswarm/giantswarm#38902): `muster.rbac.approvalDecider.subjects` binds `muster-approval-decider` to the portal's ServiceAccount `backstage/backstage`, and the Component's values set `backstage.musterWorkloadToken.enabled`, so the portal's chart projects the token (audience `muster`) and names it in `muster.workloadTokenFile` | `portalWorkloadToken.enabled`, default false; read back from the binding's presence. Refused while `GovernanceChart` or `PortalWorkloadTokenChart` is unset, off the 4 line, under a meta chart or muster hold below the releases, without a portal on the installation, and while the portal's chart line admits no chart that projects the token. muster must also trust the portal's dedicated client (`muster.muster.approval.trustedClients`), which this input does not write | +| The portal's inline tool approval (giantswarm/giantswarm#38902): `backstage.oidcClientId` and `muster.muster.approval.trustedClients` name the portal's Dex client `backstage`, `muster.rbac.approvalDecider.subjects` binds `muster-approval-decider` to the portal's ServiceAccount, and the Component's values set `backstage.musterWorkloadToken.enabled`, so the portal's chart projects the token (audience `muster`) and names it in `muster.workloadTokenFile` | `inlineApproval.enabled`, default false; read back from the portal's binding. Refused while `InlineApprovalChart`, `InlineApprovalMuster` or `PortalWorkloadTokenChart` is unset, off the 4 line, where the installation (or the portal's chart line) does not resolve those releases (a release candidate on a stable-only one), without a portal on the installation itself (a portal elsewhere opens muster's approval page), and where the portal signs in through a client other than `backstage` | | The platform's own MCP servers, the login connector, `forbidInlineSecrets`, the default model, muster's trusted issuers, resources | the shared-configs template — a hand-written copy is a removal, not an input | ## Agent-manager credential operations diff --git a/definitions/agent-platform/features.yaml b/definitions/agent-platform/features.yaml index c9568612..e812a9ea 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -138,5 +138,5 @@ features: - {id: portal-database-client, kind: backstage, key: agent-platform/app-config.yaml backend.database.client} - {id: portal-extra-app-config, kind: backstage, key: agent-platform/values.yaml backstage.extraAppConfig (the Component's app-config file and its checksum)} - {id: portal-workload-token, kind: backstage, key: "agent-platform/values.yaml backstage.musterWorkloadToken (the portal's projected token for muster, named in muster.workloadTokenFile)"} - - {id: portal-approval-decider, kind: configmap, key: "muster.rbac.approvalDecider (the portal's ServiceAccount bound to muster-approval-decider)"} + - {id: portal-inline-approval, kind: configmap, key: "muster.rbac.approvalDecider / muster.muster.approval / backstage.oidcClientId (the portal's ServiceAccount bound to muster-approval-decider, and its Dex client as muster's trusted client)"} - {id: portal-helmrelease-values-from, kind: backstage, key: agent-platform/kustomization.yaml patches (the HelmRelease valuesFrom patch)} diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index 9e623df2..fb367ab4 100644 --- a/definitions/agent-platform/schema.json +++ b/definitions/agent-platform/schema.json @@ -57,7 +57,8 @@ "name": {"type": "string", "minLength": 1, "description": "The installation's name: its kagent entry and the name and provider of its muster entry derive from it."}, "baseDomain": {"type": "string", "minLength": 1, "description": "The installation's base domain: its muster's URL derives from it."} }}}, - "chartLine": {"type": "string", "x-source": "registry", "description": "The chart line the portal follows: the ref its directory kustomization (management-clusters//extras/backstage/backstage/kustomization.yaml) patches onto the fleet base's backstage OCIRepository — the customer-portal definition's chart.line (>=A =A.B.C-0 following the release candidates) or a tag. Before backstage 1.1.0 the portal's agent-platform plugin composes the agent's HelmRelease itself and reads the agents' Flux identity from agentPlatform.fluxServiceAccountName, which the portal section then names (kagent-flux); from 1.1.0 agents are created through agent-manager and the key is not read. Absent when the kustomization patches no ref: a plan with kagent on an installation whose hosted portal carries none, or one of another form, is refused naming the file."} + "serviceAccount": {"type": "string", "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$", "x-source": "registry", "description": "The ServiceAccount the portal's pods run as: the chart's name where the portal's values on record (management-clusters//extras/backstage/backstage/app-config.yaml, data.values) set one. Absent, the chart's default, backstage. The inline approval binds it (inlineApproval.enabled)."}, + "chartLine": {"type": "string", "x-source": "registry", "description": "The chart line the portal follows: the ref its directory kustomization (management-clusters//extras/backstage/backstage/kustomization.yaml) patches onto the fleet base's backstage OCIRepository — the customer-portal definition's chart.line (>=A =A.B.C-0 following the release candidates) or a tag. Before backstage 1.1.0 the portal's agent-platform plugin composes the agent's HelmRelease itself and reads the agents' Flux identity from agentPlatform.fluxServiceAccountName, which the portal section then names (kagent-flux); from 1.1.0 agents are created through agent-manager and the key is not read. Absent when the kustomization patches no ref: a plan with kagent on an installation whose hosted portal carries none, or one of another form, is refused naming the file."} } } }, @@ -895,19 +896,19 @@ } } }, - "portalWorkloadToken": { + "inlineApproval": { "type": "object", "additionalProperties": false, - "description": "One choice: the portal's own workload identity for muster's inline tool approval.", + "description": "One choice: the portal's inline tool approval.", "properties": { "enabled": { "type": "boolean", "default": false, "x-source": "person", - "x-readback": {"file": "configmap", "key": "muster.rbac.approvalDecider", "kind": "present"}, + "x-readback": {"file": "configmap", "key": "muster.rbac.approvalDecider.subjects.[namespace=backstage]", "kind": "present"}, "x-feature": "portal", - "x-renders": ["configmap:muster.rbac.approvalDecider", "backstage:agent-platform/values:backstage.musterWorkloadToken"], - "description": "Let the portal decide tool approvals inline in its chat (giantswarm/giantswarm#38902): bind muster's Role muster-approval-decider to the portal's ServiceAccount backstage/backstage (muster.rbac.approvalDecider.subjects) and have the portal's chart project that ServiceAccount's token for audience muster and name it in muster.workloadTokenFile (backstage.musterWorkloadToken.enabled in the Component's values). muster takes a person's decision from the portal only with that token beside the person's; off, the default, the chat opens muster's approval page instead. Either half alone decides nothing. Needs a portal on this installation (the token is valid only in its own cluster), the 4 chart line, the meta chart and muster releases that ship the Role, and a portal chart line that admits the chart projecting the token; refused otherwise, and refused while either release is unset. muster must also trust the portal's dedicated client (muster.muster.approval.trustedClients), which this input does not write. Read back from the binding's presence in the configmap patch on record, so a reconcile keeps it." + "x-renders": ["configmap:backstage.oidcClientId", "configmap:muster.muster.approval.trustedClients", "configmap:muster.rbac.approvalDecider", "backstage:agent-platform/values:backstage.musterWorkloadToken"], + "description": "Let the portal running on this installation decide tool approvals inline in its chat (giantswarm/giantswarm#38902). muster takes a person's decision from the portal only with a token of a client it trusts with approvals, the portal backend's own ServiceAccount token beside it, and that ServiceAccount bound to its Role muster-approval-decider. On, the configmap patch names the portal's Dex client (backstage, the definition's portal client, read from the record) as the portal's own (backstage.oidcClientId) and muster's one trusted client (muster.muster.approval.trustedClients), binds muster-approval-decider to the portal's ServiceAccount (installation.portals[*].serviceAccount, else backstage) in namespace backstage, and the Component's values have the portal's chart project the token for audience muster and name it in muster.workloadTokenFile (backstage.musterWorkloadToken.enabled). Off, the default, the chat opens muster's approval page instead. Needs a portal running on this installation (the token is valid only in its own cluster; a portal on another installation opens muster's page), signing in through the definition's portal client, the 4 chart line, and a meta chart, muster and portal chart line this installation resolves to at or above InlineApprovalChart, InlineApprovalMuster and PortalWorkloadTokenChart (a release candidate only where the installation, or the portal's line, follows them); refused otherwise, and while any of the three is unset. Read back from the portal's binding in the configmap patch on record, so a reconcile keeps it." } } }, diff --git a/internal/installations/derive.go b/internal/installations/derive.go index cd4a371c..36e26837 100644 --- a/internal/installations/derive.go +++ b/internal/installations/derive.go @@ -40,11 +40,15 @@ import ( // whether its Grafana plugin is wired: its app-config carries the plugin's // proxy endpoint. type Portal struct { - Host string - Customer string - Domain string - ClientID string - ChartLine string + Host string + Customer string + Domain string + ClientID string + ChartLine string + // ServiceAccount is the ServiceAccount the portal's pods run as: the + // chart's name where the portal's values on record set one, else empty + // (the chart's default, render.PortalServiceAccount). + ServiceAccount string Broker string Installations []string Tunnelled []string @@ -99,15 +103,16 @@ type FederatedInstallation struct { // installation's plan renders it. A hand-kept portal carries its own section // for the installations it proxies, so its list is not read. type PortalRef struct { - Installation string `json:"installation"` - Customer string `json:"customer"` - Domain string `json:"domain"` - ClientID string `json:"clientId,omitempty"` - HandKept bool `json:"handKept,omitempty"` - GrafanaWired bool `json:"grafanaWired,omitempty"` - HandKeptChat bool `json:"handKeptChat,omitempty"` - ChartLine string `json:"chartLine,omitempty"` - Installations []PortalInstallation `json:"installations,omitempty"` + Installation string `json:"installation"` + Customer string `json:"customer"` + Domain string `json:"domain"` + ClientID string `json:"clientId,omitempty"` + HandKept bool `json:"handKept,omitempty"` + GrafanaWired bool `json:"grafanaWired,omitempty"` + HandKeptChat bool `json:"handKeptChat,omitempty"` + ChartLine string `json:"chartLine,omitempty"` + ServiceAccount string `json:"serviceAccount,omitempty"` + Installations []PortalInstallation `json:"installations,omitempty"` } // PortalInstallation is an installation a portal shows that runs the agent @@ -238,7 +243,7 @@ func (r *Registry) readPortal(ctx context.Context, c *gh.Client, host Installati if err != nil { return nil, fmt.Errorf("%s: %w", PortalConfigPath(host.Name), err) } - p := &Portal{Host: host.Name, Customer: host.Customer, Domain: hostOf(cfg.BaseURL), HandKept: cfg.HandKept, GrafanaWired: cfg.GrafanaWired, HandKeptChat: cfg.HandKeptChat, Entries: cfg.Installations} + p := &Portal{Host: host.Name, Customer: host.Customer, Domain: hostOf(cfg.BaseURL), HandKept: cfg.HandKept, GrafanaWired: cfg.GrafanaWired, HandKeptChat: cfg.HandKeptChat, ServiceAccount: cfg.Name, Entries: cfg.Installations} for name := range cfg.Installations { p.Installations = append(p.Installations, name) } @@ -707,7 +712,7 @@ func (r *Report) derivePortals(portals []Portal) []string { var targets []string for _, p := range portals { if slices.Contains(p.Installations, r.Name) { - r.Portals = append(r.Portals, PortalRef{Installation: p.Host, Customer: p.Customer, Domain: p.Domain, ClientID: p.ClientID, HandKept: p.HandKept, GrafanaWired: p.GrafanaWired, HandKeptChat: p.HandKeptChat, ChartLine: p.ChartLine}) + r.Portals = append(r.Portals, PortalRef{Installation: p.Host, Customer: p.Customer, Domain: p.Domain, ClientID: p.ClientID, HandKept: p.HandKept, GrafanaWired: p.GrafanaWired, HandKeptChat: p.HandKeptChat, ChartLine: p.ChartLine, ServiceAccount: p.ServiceAccount}) } if p.Broker != r.Name { continue diff --git a/internal/installations/derive_test.go b/internal/installations/derive_test.go index ae5d567a..898c318c 100644 --- a/internal/installations/derive_test.go +++ b/internal/installations/derive_test.go @@ -462,3 +462,23 @@ func TestHubConnectorFacts(t *testing.T) { t.Errorf("a hub not inspected without a configs repository on record: %v", err) } } + +// A portal's values that name the chart other than its default name the +// ServiceAccount its pods run as, which the inline approval binds; without +// the key it is empty, the chart's default. +func TestPortalConfigServiceAccount(t *testing.T) { + appConfig := "app:\n baseUrl: https://portal.aspen.fleet.test\ngs:\n installations:\n aspen: {}\n" + for _, c := range []struct{ name, values, want string }{ + {"named", "name: dev-portal\n", "dev-portal"}, + {"the chart's default", "", ""}, + } { + values := c.values + "backstage:\n appConfig: |\n" + indent(appConfig, " ") + cfg, err := parsePortalConfig("apiVersion: v1\nkind: ConfigMap\ndata:\n values: |\n" + indent(values, " ")) + if err != nil { + t.Fatal(err) + } + if cfg.Name != c.want { + t.Errorf("%s: name %q, want %q", c.name, cfg.Name, c.want) + } + } +} diff --git a/internal/installations/inlineapproval_readback_test.go b/internal/installations/inlineapproval_readback_test.go new file mode 100644 index 00000000..e3847daa --- /dev/null +++ b/internal/installations/inlineapproval_readback_test.go @@ -0,0 +1,77 @@ +package installations + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/giantswarm/giantswarm-platform-manager/render" + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" +) + +const ( + // keyInlineApproval and inputInlineApproval are the portal's inline + // approval, read back from the portal's binding. + keyInlineApproval = "inlineApproval" + inputInlineApproval = keyInlineApproval + ".enabled" +) + +// The agent-platform definition reads the portal's inline approval back +// from the portal's ServiceAccount among muster's approval deciders on +// record: an empty list, other subjects, or other keys under +// approvalDecider read back as off, so a hand edit meaning "nobody" is not +// turned on again at the next reconcile. +func TestInlineApprovalReadBack(t *testing.T) { + definition, found := FindCapability(AgentPlatform) + require.True(t, found) + for _, test := range []struct { + name string + patch string + want bool + }{ + {"the portal bound", "muster:\n rbac:\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: backstage\n namespace: backstage\n", true}, + {"an empty list", "muster:\n rbac:\n approvalDecider:\n subjects: []\n", false}, + {"the Role off", "muster:\n rbac:\n approvalDecider:\n create: false\n", false}, + {"another subject", "muster:\n rbac:\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: agent\n namespace: kagent\n", false}, + {"other bindings alone", "muster:\n rbac:\n mcpServerEditor:\n subjects: []\n", false}, + {"absent", "", false}, + } { + t.Run(test.name, func(t *testing.T) { + read := files(map[string]string{"acme/configs:" + definition.EnabledMarker("rowan"): test.patch}) + got, err := definition.ReadBack(t.Context(), read, readBackInstallation, readBackName, nil) + require.NoError(t, err) + require.Equal(t, test.want, got[inputInlineApproval]) + }) + } +} + +// What the render writes reads back as the input on, and renders the same +// patch again: a reconcile keeps the inline approval as it is. +func TestInlineApprovalSurvivesAReconcile(t *testing.T) { + c, m, p := agentplatform.InlineApprovalChart, agentplatform.InlineApprovalMuster, agentplatform.PortalWorkloadTokenChart + agentplatform.InlineApprovalChart, agentplatform.InlineApprovalMuster, agentplatform.PortalWorkloadTokenChart = "4.190.0", "5.74.0", "3.53.0" + t.Cleanup(func() { + agentplatform.InlineApprovalChart, agentplatform.InlineApprovalMuster, agentplatform.PortalWorkloadTokenChart = c, m, p + }) + definition, found := FindCapability(AgentPlatform) + require.True(t, found) + ownLine := func(doc map[string]any) { + portal := doc["installation"].(map[string]any)["portals"].([]any)[0].(map[string]any) + portal["chartLine"] = ">=3.0.0 <4.0.0" + } + + _, _, doc, marker := inputFromTheRecord(t, "organizations-portal", nil) + ownLine(doc) + doc[keyInlineApproval] = map[string]any{"enabled": true} + result, err := definition.Render(doc, nil, render.ModeCommit) + require.NoError(t, err) + rendered := string(result.Tree()["giantswarm/giantswarm-configs/"+marker]) + require.Contains(t, rendered, "approvalDecider:") + + _, read, doc, _ := inputFromTheRecord(t, "organizations-portal", func(string) string { return rendered }) + require.Equal(t, true, read[inputInlineApproval]) + ownLine(doc) + result, err = definition.Render(doc, nil, render.ModeCommit) + require.NoError(t, err) + require.Equal(t, rendered, string(result.Tree()["giantswarm/giantswarm-configs/"+marker])) +} diff --git a/internal/installations/managergrants_readback_test.go b/internal/installations/managergrants_readback_test.go index 08c483fc..e9012930 100644 --- a/internal/installations/managergrants_readback_test.go +++ b/internal/installations/managergrants_readback_test.go @@ -20,7 +20,7 @@ func managerGrantDefaults(choices map[string]any) map[string]any { "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, - inputPortalWorkloadToken: false, + inputInlineApproval: false, } maps.Copy(want, choices) return want diff --git a/internal/installations/readback_test.go b/internal/installations/readback_test.go index af808291..b9b9ebcf 100644 --- a/internal/installations/readback_test.go +++ b/internal/installations/readback_test.go @@ -324,7 +324,7 @@ func TestDefaults(t *testing.T) { // The holds and their reasons, by component: none by default. holds := map[string]any{"muster": "", "valkey": "", "kagent": "", "agent-manager": "", "klaus-gateway": "", grantClusterManager: "", grantModelManager: "", grantSkillManager: ""} want := map[string]any{"modelServing": map[string]any{keyEnabled: false}, "aiChat": map[string]any{keyEnabled: false, "model": "claude-opus-5", keyProvider: "anthropic"}, - "scheduling": map[string]any{"singletonsCapacity": "any"}, "networkPolicy": map[string]any{"mcpBackends": map[string]any{}}, "llmRouting": map[string]any{"rateLimits": []any{}, "rateLimitsComment": ""}, "sessions": map[string]any{"idleTTL": ""}, keyPortalWorkloadToken: map[string]any{keyEnabled: false}, keySkills: map[string]any{keyRepositories: []any{}}, + "scheduling": map[string]any{"singletonsCapacity": "any"}, "networkPolicy": map[string]any{"mcpBackends": map[string]any{}}, "llmRouting": map[string]any{"rateLimits": []any{}, "rateLimitsComment": ""}, "sessions": map[string]any{"idleTTL": ""}, keyInlineApproval: map[string]any{keyEnabled: false}, keySkills: map[string]any{keyRepositories: []any{}}, "hive": map[string]any{keyEnabled: false, "plans": map[string]any{keyRepositories: []any{}}, "magazine": map[string]any{"repository": ""}, boardRoadmap: map[string]any{"board": boardRoadmap, "teams": []any{}}}, "clusterManager": map[string]any{keyGitHub: map[string]any{grantExchangeField: map[string]any{keyEnabled: false}}}, diff --git a/internal/installations/registry.go b/internal/installations/registry.go index 67e870ef..07cdcfe1 100644 --- a/internal/installations/registry.go +++ b/internal/installations/registry.go @@ -353,6 +353,9 @@ type portalConfig struct { HandKept bool GrafanaWired bool HandKeptChat bool + // Name is the portal chart's name the values set, the ServiceAccount + // its pods run as; empty for the chart's default. + Name string } func parsePortalConfig(data string) (*portalConfig, error) { @@ -368,6 +371,7 @@ func parsePortalConfig(data string) (*portalConfig, error) { return nil, errors.New("the ConfigMap has no data.values") } var values struct { + Name string `yaml:"name"` Backstage struct { AppConfig string `yaml:"appConfig"` } `yaml:"backstage"` @@ -415,7 +419,7 @@ func parsePortalConfig(data string) (*portalConfig, error) { } _, grafanaWired := appConfig.Proxy.Endpoints[render.PortalGrafanaProxy] cfg := &portalConfig{Installations: appConfig.GS.Installations, BaseURL: appConfig.App.BaseURL, BrokerTokenURL: appConfig.GS.ClusterTokenBroker.TokenURL, - Tunnelled: map[string]bool{}, PlatformProxied: map[string]bool{}, HandKept: appConfig.App.Extensions.Kind == yaml.SequenceNode, GrafanaWired: grafanaWired, HandKeptChat: !appConfig.AIChat.IsZero()} + Tunnelled: map[string]bool{}, PlatformProxied: map[string]bool{}, HandKept: appConfig.App.Extensions.Kind == yaml.SequenceNode, GrafanaWired: grafanaWired, HandKeptChat: !appConfig.AIChat.IsZero(), Name: values.Name} for _, m := range appConfig.Kubernetes.ClusterLocatorMethods { for _, cluster := range m.Clusters { if hostOf(cluster.URL) == tunnelKubernetesHost(cluster.Name) { diff --git a/internal/installations/workloadtoken_readback_test.go b/internal/installations/workloadtoken_readback_test.go deleted file mode 100644 index bfe8f5e4..00000000 --- a/internal/installations/workloadtoken_readback_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package installations - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -const ( - // keyPortalWorkloadToken and inputPortalWorkloadToken are the portal's - // workload identity for muster, read back as present or not. - keyPortalWorkloadToken = "portalWorkloadToken" - inputPortalWorkloadToken = keyPortalWorkloadToken + ".enabled" -) - -// The agent-platform definition reads the portal's workload identity back -// from the binding's presence in the configmap patch on record, so a -// reconcile keeps it; its absence reads back as off. -func TestPortalWorkloadTokenReadBack(t *testing.T) { - definition, found := FindCapability(AgentPlatform) - require.True(t, found) - for _, test := range []struct { - name string - patch string - want bool - }{ - {"bound", "muster:\n rbac:\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: backstage\n namespace: backstage\n", true}, - {"other bindings alone", "muster:\n rbac:\n mcpServerEditor:\n subjects: []\n", false}, - {"absent", "", false}, - } { - t.Run(test.name, func(t *testing.T) { - read := files(map[string]string{"acme/configs:" + definition.EnabledMarker("rowan"): test.patch}) - got, err := definition.ReadBack(t.Context(), read, readBackInstallation, readBackName, nil) - require.NoError(t, err) - require.Equal(t, test.want, got[inputPortalWorkloadToken]) - }) - } -} diff --git a/internal/verify/verify_test.go b/internal/verify/verify_test.go index 98782987..6e69c37e 100644 --- a/internal/verify/verify_test.go +++ b/internal/verify/verify_test.go @@ -672,11 +672,11 @@ func TestDrivenInputsAreThePersonsAndTheTyped(t *testing.T) { tenantInputs := []string{"tenants.platform.editors", "tenants.platform.users", "tenants.platformTeam"} governanceInputs := []string{"governance.governedServers", "governance.mode"} got, err := drivenInputs(def, Inputs{Values: doc("a.test", "acme", true)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"portalWorkloadToken.enabled", "scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{"inlineApproval.enabled"}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("from the record: %v %v", got, err) } got, err = drivenInputs(def, Inputs{Values: doc("a.test", "acme", true), Typed: doc("b.test", "acme", false)}) - if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"portalWorkloadToken.enabled", "scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { + if err != nil || !reflect.DeepEqual(got, slices.Concat(agentInputs, chatInputs, []string{"clusterManager.github.tokenExchange.enabled", "defaultAgent.enabled", "defaultAgent.modelConfig"}, governanceInputs, hiveInputs, []string{"inlineApproval.enabled"}, []string{baseDomainInput, customerInput}, gatewayInputs, llmInputs, []string{"modelManager.github.tokenExchange.enabled", servingInput, "musterMcpServerViewers", "networkPolicy.mcpBackends"}, organizationsInputs, []string{"scheduling.singletonsCapacity", "sessions.idleTTL", "skillManager.github.app.secretName", "skillManager.github.tokenExchange.enabled", "skillManager.sources", skillsInput}, tenantInputs, versionInputs)) { t.Errorf("with facts typed: %v %v", got, err) } } diff --git a/render/agentplatform/inlineapproval.go b/render/agentplatform/inlineapproval.go new file mode 100644 index 00000000..9dcc594d --- /dev/null +++ b/render/agentplatform/inlineapproval.go @@ -0,0 +1,177 @@ +package agentplatform + +import ( + "fmt" + "strings" + + "github.com/Masterminds/semver/v3" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +// The portal's inline tool approval (inlineApproval.enabled). muster takes a +// person's approval decision, and a sign-in handoff ticket request, from the +// portal only when three things hold: the person's token is of a client +// muster trusts with approvals (muster.approval.trustedClients), the portal +// backend's own projected ServiceAccount token (audience muster) comes with +// it, and that ServiceAccount is bound to muster's Role +// muster-approval-decider. The meta chart wires all three only for a portal +// it deploys itself (components.backstage); a portal of the customer-portal +// definition is a release of its own, so this definition wires them: +// +// - the configmap patch names the portal's Dex client as the portal's own +// (backstage.oidcClientId) and as muster's one trusted client +// (muster.muster.approval.trustedClients), and binds +// muster-approval-decider to the portal's ServiceAccount +// (muster.rbac.approvalDecider.subjects); +// - the Component's values have the portal's chart project the token and +// name it in muster.workloadTokenFile (backstage.musterWorkloadToken, an +// object key, so it merges with the portal's own values). +// +// Off by default. No part alone decides anything. The token is valid only +// in the cluster its ServiceAccount lives in, so inline approval works only +// for a portal running on the installation itself; any other portal opens +// muster's approval page instead. + +// The releases the input needs, UNSET until they exist: an earlier chart +// refuses or ignores the keys, so while one is unset the input is refused +// (fail closed). Set each to its release once it is cut, a release candidate +// while only installations that follow release candidates should take the +// input (a stable-only installation is then refused); tests set them. +var ( + // InlineApprovalChart is the first meta chart that sets + // agent-platform.muster.trustedClientsFloor: below it, or with the floor + // unset, the meta chart fails the render of an own trustedClients list. + InlineApprovalChart = "" + // InlineApprovalMuster is that floor, the first muster that reviews the + // portal's workload token and ships muster-approval-decider; an earlier + // muster chart's schema refuses the binding. + InlineApprovalMuster = "" + // PortalWorkloadTokenChart is the first portal chart that takes + // backstage.musterWorkloadToken; an earlier chart's schema refuses it. + PortalWorkloadTokenChart = "" +) + +// inputInlineApproval is the input, by its schema path. +const inputInlineApproval = "inlineApproval.enabled" + +// inlineApproval says whether the platform wires the portal's inline +// approval; checkInlineApproval has refused it where it cannot hold. +func (in *Input) inlineApproval() bool { return in.InlineApproval } + +// ownPortal is the portal running on this installation, nil without one. +func (in *Input) ownPortal() *PortalRef { + for i := range in.Installation.Portals { + if p := &in.Installation.Portals[i]; p.Installation == in.Installation.Name { + return p + } + } + return nil +} + +// inlineApprovalClient is the Dex client muster trusts with the portal's +// approvals: the own portal's client as the record reads it from the Dex +// patch, else the definition's portal client where this Dex carries it. +// Only the definition's client is trusted: its one use is the portals' +// sign-in (one redirect URI per portal, no other id registered under it), +// which a client registered by hand is not known to be. "" otherwise. +func (in *Input) inlineApprovalClient() string { + p := in.ownPortal() + if p == nil { + return "" + } + id := p.ClientID + if id == "" && in.portalClient() { + id = render.PortalDexClientID + } + if id != render.PortalDexClientID { + return "" + } + return id +} + +// portalServiceAccount is the ServiceAccount the own portal's pods run as. +func (in *Input) portalServiceAccount() string { + if p := in.ownPortal(); p != nil && p.ServiceAccount != "" { + return p.ServiceAccount + } + return render.PortalServiceAccount +} + +// approvalDecider is muster.rbac.approvalDecider: the own portal's +// ServiceAccount alone. +func (in *Input) approvalDecider() render.Map { + return render.Map{e("subjects", []render.Map{{e("kind", "ServiceAccount"), e("name", in.portalServiceAccount()), e("namespace", backstageNamespace)}})} +} + +// musterApproval is muster.muster.approval: the portal's client as the one +// trusted client. +func (in *Input) musterApproval() render.Map { + return render.Map{e("trustedClients", []string{in.inlineApprovalClient()})} +} + +// resolvable says whether a version source the installation resolves +// through takes a release at or above release: a release candidate only +// where the installation follows release candidates (followsCandidates), +// and the hold, where there is one, admitting it. +func resolvable(release, hold string, followsCandidates bool) bool { + v := semver.MustParse(release) + if v.Prerelease() != "" && !followsCandidates { + return false + } + return holdAdmits(hold, release) +} + +// candidate names a release a stable-only source cannot resolve. +func candidate(release string) string { + if strings.Contains(release, "-") { + return ", a release candidate this installation, which follows stable releases only, does not resolve" + } + return "" +} + +// checkInlineApproval refuses the input unless the installation resolves +// what it needs: the releases set, the 4 chart line, a meta chart and a +// muster this installation resolves to at or above them (a release +// candidate only where it follows them, with or without a hold), a portal +// running on the installation whose client is the definition's portal +// client, and a portal chart line that resolves to the chart projecting the +// token (a release candidate only on a line that follows them). +func (in *Input) checkInlineApproval() error { + if !in.inlineApproval() { + return nil + } + if InlineApprovalChart == "" || InlineApprovalMuster == "" || PortalWorkloadTokenChart == "" { + return refuse(fmt.Sprintf("%s needs the meta chart, muster and portal chart releases that carry the portal's inline approval, and not all are released yet", describe(inputInlineApproval))) + } + if in.Installation.ChartLine != lineFour { + return in.refuseOffLineFour(inputInlineApproval) + } + if !resolvable(InlineApprovalChart, in.Versions.Chart, in.ReleaseCandidates) { + return refuse(fmt.Sprintf("%s needs the meta chart %s or later%s, and this installation resolves the meta chart from %s; move or lift the hold, or wait for the stable release", describe(inputInlineApproval), InlineApprovalChart, candidate(InlineApprovalChart), orRange(in.Versions.Chart, in.chartSemver()))) + } + hold := in.Versions.Components[componentMuster] + if !resolvable(InlineApprovalMuster, hold, in.ReleaseCandidates) || (hold != "" && !floorAtLeast(hold, InlineApprovalMuster)) { + return refuse(fmt.Sprintf("%s needs muster %s or later%s, below which the meta chart fails the render of the trusted client and muster's chart refuses the binding, and this installation resolves muster from %s; move or lift the hold, or wait for the stable release", describe(inputInlineApproval), InlineApprovalMuster, candidate(InlineApprovalMuster), orRange(hold, "the meta chart's range"))) + } + p := in.ownPortal() + if p == nil { + return refuse(fmt.Sprintf("%s needs a portal running on %s itself: the portal's token is valid only in its own cluster, so a portal on another installation cannot decide here and opens muster's approval page instead", describe(inputInlineApproval), in.Installation.Name)) + } + if in.inlineApprovalClient() == "" { + return refuse(fmt.Sprintf("%s trusts the portal's Dex client with approvals, and the portal %s signs in through %q, not the definition's portal client %s, whose one use is the portals' sign-in; register the portal on %s first", describe(inputInlineApproval), p.Domain, p.ClientID, render.PortalDexClientID, render.PortalDexClientID)) + } + line := p.ChartLine + if !portalChartAdmits(line, semver.MustParse(PortalWorkloadTokenChart)) || (candidate(PortalWorkloadTokenChart) != "" && !render.ReleaseCandidates(line)) { + return refuse(fmt.Sprintf("%s needs the portal chart %s or later, and the portal %s follows the chart line %q, which does not resolve it; move the portal's chart line first", describe(inputInlineApproval), PortalWorkloadTokenChart, p.Domain, line)) + } + return nil +} + +// orRange is a hold, else the range it stands in for. +func orRange(hold, fallback string) string { + if hold != "" { + return "the hold " + hold + } + return fallback +} diff --git a/render/agentplatform/inlineapproval_test.go b/render/agentplatform/inlineapproval_test.go new file mode 100644 index 00000000..fa109541 --- /dev/null +++ b/render/agentplatform/inlineapproval_test.go @@ -0,0 +1,275 @@ +package agentplatform + +import ( + "errors" + "path/filepath" + "reflect" + "strings" + "testing" + + "gopkg.in/yaml.v3" + + "github.com/giantswarm/giantswarm-platform-manager/render" +) + +// The releases the tests take as cut, stable and as release candidates. +const ( + testInlineApprovalChart = "4.190.0" + testInlineApprovalMuster = "5.74.0" + testPortalWorkloadTokenChart = "3.53.0" + keyInlineApproval = "inlineApproval" + keyPortals = "portals" + keyChartLine = "chartLine" + portalLine3 = ">=3.0.0 <4.0.0" + ownClient = "dev-portal" + keyBackstage = "backstage" +) + +// withInlineApprovalReleases takes the three releases as cut for the test. +// Not parallel, like withGovernanceReleases. +func withInlineApprovalReleases(t *testing.T, chart, muster, portal string) { + t.Helper() + c, m, p := InlineApprovalChart, InlineApprovalMuster, PortalWorkloadTokenChart + InlineApprovalChart, InlineApprovalMuster, PortalWorkloadTokenChart = chart, muster, portal + t.Cleanup(func() { InlineApprovalChart, InlineApprovalMuster, PortalWorkloadTokenChart = c, m, p }) +} + +// withStableReleases takes the three releases as cut as stable releases. +func withStableReleases(t *testing.T) { + t.Helper() + withInlineApprovalReleases(t, testInlineApprovalChart, testInlineApprovalMuster, testPortalWorkloadTokenChart) +} + +// ownPortalRecord is the record's portal of the installation itself. +func ownPortalRecord(input map[string]any) map[string]any { + return input["installation"].(map[string]any)[keyPortals].([]any)[0].(map[string]any) +} + +// inlineApprovalInput is the organizations-portal installation, whose portal +// runs on it, with the input on and the portal on the given chart line. +func inlineApprovalInput(t *testing.T, line string) (map[string]any, map[string]string) { + t.Helper() + input, secrets := loadInput(t, shapeOrganizationsPortal) + input[keyInlineApproval] = map[string]any{keyEnabled: true} + ownPortalRecord(input)[keyChartLine] = line + return input, secrets +} + +// componentValues is the Component's values of a result, decoded. +func componentValues(t *testing.T, result *render.Result) map[string]any { + t.Helper() + for name, content := range result.Tree() { + if strings.HasSuffix(filepath.ToSlash(name), "/extras/backstage/agent-platform/values.yaml") { + var cm struct { + Data struct { + Values string `yaml:"values"` + } `yaml:"data"` + } + var values map[string]any + if err := yaml.Unmarshal(content, &cm); err != nil { + t.Fatal(err) + } + if err := yaml.Unmarshal([]byte(cm.Data.Values), &values); err != nil { + t.Fatal(err) + } + return values + } + } + t.Fatal("no Component values rendered") + return nil +} + +// decodeYAML is a rendered YAML file, decoded. +func decodeYAML(t *testing.T, text string) map[string]any { + t.Helper() + var m map[string]any + if err := yaml.Unmarshal([]byte(text), &m); err != nil { + t.Fatal(err) + } + return m +} + +// at is the value at a dotted path of a decoded document, nil when absent. +func at(m map[string]any, path string) any { + var cur any = m + for _, k := range strings.Split(path, ".") { + next, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = next[k] + } + return cur +} + +// On, with the releases cut and a portal on the installation whose chart +// line resolves the projecting chart, the patch names the portal's client as +// its own and muster's one trusted client and binds the portal's +// ServiceAccount alone, and the Component's values project the token. The +// ServiceAccount follows the record. Off, none of it renders. +func TestInlineApprovalRenders(t *testing.T) { + withStableReleases(t) + for _, c := range []struct { + name, serviceAccount, want string + }{ + {"the chart's default ServiceAccount", "", render.PortalServiceAccount}, + {"the ServiceAccount the portal's values name", ownClient, ownClient}, + } { + t.Run(c.name, func(t *testing.T) { + input, secrets := inlineApprovalInput(t, portalLine3) + if c.serviceAccount != "" { + ownPortalRecord(input)["serviceAccount"] = c.serviceAccount + } + result, err := Render(input, secrets, render.ModeCommit) + if err != nil { + t.Fatal(err) + } + patch := decodeYAML(t, platformPatch(t, result)) + wantSubjects := []any{map[string]any{"kind": "ServiceAccount", fieldName: c.want, credentialNamespaceVariable: backstageNamespace}} + if got := at(patch, "muster.rbac.approvalDecider.subjects"); !reflect.DeepEqual(got, wantSubjects) { + t.Errorf("subjects %v, want %v", got, wantSubjects) + } + if got := at(patch, "muster.muster.approval.trustedClients"); !reflect.DeepEqual(got, []any{render.PortalDexClientID}) { + t.Errorf("trustedClients %v, want the portal's client alone", got) + } + if got := at(patch, "backstage.oidcClientId"); got != render.PortalDexClientID { + t.Errorf("backstage.oidcClientId %v, want the portal's client", got) + } + values := componentValues(t, result) + if got := at(values, "backstage.musterWorkloadToken"); !reflect.DeepEqual(got, map[string]any{keyEnabled: true}) { + t.Errorf("backstage.musterWorkloadToken %v, want it enabled", got) + } + if at(values, "backstage.extraAppConfig") == nil { + t.Error("the fragment's mount is gone beside the token") + } + }) + } + + off, secrets := loadInput(t, shapeOrganizationsPortal) + result, err := Render(off, secrets, render.ModeCommit) + if err != nil { + t.Fatal(err) + } + patch := decodeYAML(t, platformPatch(t, result)) + for _, key := range []string{"muster.rbac.approvalDecider", "muster.muster.approval", keyBackstage} { + if at(patch, key) != nil { + t.Errorf("off, the patch carries %s", key) + } + } + if at(componentValues(t, result), "backstage.musterWorkloadToken") != nil { + t.Error("off, the Component's values project a token") + } +} + +// While a release is unset (the shipped state) the input is refused: fail +// closed, an earlier chart refuses or ignores the keys. +func TestInlineApprovalIsRefusedUntilItsReleasesExist(t *testing.T) { + for _, set := range [][3]string{{"", "", ""}, {testInlineApprovalChart, testInlineApprovalMuster, ""}, {testInlineApprovalChart, "", testPortalWorkloadTokenChart}, {"", testInlineApprovalMuster, testPortalWorkloadTokenChart}} { + withInlineApprovalReleases(t, set[0], set[1], set[2]) + input, secrets := inlineApprovalInput(t, portalLine3) + if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "not all are released yet") { + t.Fatalf("%v: got %v, want ErrInput naming the missing release", set, err) + } + } +} + +// Where the installation does not resolve what the input needs, it is +// refused naming the input: a portal on another installation (which falls +// back to muster's page), a portal signing in through a client of its own, +// a portal chart line below the projecting chart, holds of the meta chart +// or muster below the releases, the 3 chart line, and release candidates on +// a stable-only installation or chart line. +func TestInlineApprovalRefusals(t *testing.T) { + for _, c := range []struct { + name string + releases [3]string + input func() (map[string]any, map[string]string) + names string + }{ + {"a portal on another installation", [3]string{}, func() (map[string]any, map[string]string) { + input, secrets := loadInput(t, shapePlatformTenantRetired) + input[keyInlineApproval] = map[string]any{keyEnabled: true} + return input, secrets + }, "needs a portal running on garnet itself"}, + {"a portal client of its own", [3]string{}, func() (map[string]any, map[string]string) { + input, secrets := inlineApprovalInput(t, portalLine3) + ownPortalRecord(input)["clientId"] = ownClient + return input, secrets + }, `signs in through "dev-portal"`}, + {"a portal chart line below the projecting chart", [3]string{}, func() (map[string]any, map[string]string) { + return inlineApprovalInput(t, ">=2.1.0 <3.0.0") + }, "needs the portal chart 3.53.0 or later"}, + {"a portal candidate on a stable chart line", [3]string{testInlineApprovalChart, testInlineApprovalMuster, "3.53.0-rc.1"}, func() (map[string]any, map[string]string) { + return inlineApprovalInput(t, portalLine3) + }, "needs the portal chart 3.53.0-rc.1 or later"}, + {"a muster hold below the release", [3]string{}, func() (map[string]any, map[string]string) { + input, secrets := inlineApprovalInput(t, portalLine3) + input["versions"] = map[string]any{"components": map[string]any{componentMuster: ">=5.60.0 <5.61.0"}} + return input, secrets + }, "resolves muster from the hold >=5.60.0 <5.61.0"}, + {"a meta chart hold below the release", [3]string{}, func() (map[string]any, map[string]string) { + input, secrets := inlineApprovalInput(t, portalLine3) + input["versions"] = map[string]any{"chart": "4.180.0"} + return input, secrets + }, "resolves the meta chart from the hold 4.180.0"}, + {"the 3 chart line", [3]string{}, func() (map[string]any, map[string]string) { + input, secrets := loadInput(t, shapePublicCustomer) + input[keyInlineApproval] = map[string]any{keyEnabled: true} + return input, secrets + }, "is the 4 chart line's"}, + } { + t.Run(c.name, func(t *testing.T) { + if c.releases == ([3]string{}) { + withStableReleases(t) + } else { + withInlineApprovalReleases(t, c.releases[0], c.releases[1], c.releases[2]) + } + input, secrets := c.input() + _, err := Render(input, secrets, render.ModeCommit) + if !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), inputInlineApproval) || !strings.Contains(err.Error(), c.names) { + t.Fatalf("got %v, want ErrInput naming the input and %q", err, c.names) + } + if c.name == "a portal on another installation" && !strings.Contains(err.Error(), "opens muster's approval page instead") { + t.Fatalf("got %v, want it to name the fallback", err) + } + }) + } +} + +// Release candidates as gates: an installation that follows them takes the +// input, a stable-only one is refused for the meta chart and for muster with +// or without a hold, so a manager whose gates are candidates never writes +// keys a stable-only installation's charts refuse. +func TestInlineApprovalCandidates(t *testing.T) { + withStableReleases(t) + input, _ := inlineApprovalInput(t, portalLine3) + in, err := Parse(input) + if err != nil { + t.Fatal(err) + } + withInlineApprovalReleases(t, "4.190.0-rc.2", testInlineApprovalMuster, testPortalWorkloadTokenChart) + in.ReleaseCandidates = false + if err := in.checkInlineApproval(); err == nil || !strings.Contains(err.Error(), "a release candidate this installation, which follows stable releases only, does not resolve") { + t.Fatalf("stable-only, a candidate meta chart: got %v", err) + } + in.ReleaseCandidates = true + if err := in.checkInlineApproval(); err != nil { + t.Fatalf("following candidates, a candidate meta chart: %v", err) + } + + withInlineApprovalReleases(t, testInlineApprovalChart, "5.74.0-rc.3", testPortalWorkloadTokenChart) + in.ReleaseCandidates = false + if err := in.checkInlineApproval(); err == nil || !strings.Contains(err.Error(), "needs muster 5.74.0-rc.3 or later, a release candidate") { + t.Fatalf("stable-only, a candidate muster without a hold: got %v", err) + } + in.ReleaseCandidates = true + if err := in.checkInlineApproval(); err != nil { + t.Fatalf("following candidates, a candidate muster: %v", err) + } + + withInlineApprovalReleases(t, testInlineApprovalChart, testInlineApprovalMuster, "3.53.0-rc.1") + in.Installation.Portals[0].ChartLine = ">=3.0.0-0" + if err := in.checkInlineApproval(); err != nil { + t.Fatalf("a portal line following candidates, a candidate portal chart: %v", err) + } +} diff --git a/render/agentplatform/input.go b/render/agentplatform/input.go index 7c14fe0e..05bcca26 100644 --- a/render/agentplatform/input.go +++ b/render/agentplatform/input.go @@ -198,11 +198,10 @@ type Input struct { // and the servers muster governs (governance.*), read back from the // configmap patch on record so a reconcile keeps it (governance.go). Governance Governance - // PortalWorkloadToken is the person's choice to wire the portal's - // workload identity for muster's inline approval - // (portalWorkloadToken.enabled, workloadtoken.go), read back from the - // configmap patch on record. - PortalWorkloadToken bool + // InlineApproval is the person's choice to wire the portal's inline + // tool approval (inlineApproval.enabled, inlineapproval.go), read back + // from the configmap patch on record. + InlineApproval bool // Components are the components the policy gives the installation, by // name: its organisation's list and, where the policy names a Slack app // for the installation, the chat gateway. @@ -370,6 +369,9 @@ type PortalRef struct { GrafanaWired bool `json:"grafanaWired,omitempty"` HandKeptChat bool `json:"handKeptChat,omitempty"` Installations []PortalInstallation `json:"installations,omitempty"` + // ServiceAccount is the ServiceAccount the portal's pods run as, where + // its values on record name the chart other than its default. + ServiceAccount string `json:"serviceAccount,omitempty"` } // PortalInstallation is an installation a portal shows that runs the agent @@ -746,10 +748,10 @@ type document struct { } `json:"platform"` PlatformTeam *[]Subject `json:"platformTeam"` } `json:"tenants"` - Governance Governance `json:"governance"` - PortalWorkloadToken struct { + Governance Governance `json:"governance"` + InlineApproval struct { Enabled bool `json:"enabled"` - } `json:"portalWorkloadToken"` + } `json:"inlineApproval"` Versions Versions `json:"versions"` } @@ -966,7 +968,7 @@ func Parse(raw any) (*Input, error) { in.PlatformTenant = PlatformTenant{Users: d.Tenants.Platform.Users, Editors: d.Tenants.Platform.Editors, PlatformTeam: d.Tenants.PlatformTeam, Viewers: d.MusterMcpServerViewers} in.Governance = d.Governance in.Governance.withoutPlatformServers() - in.PortalWorkloadToken = d.PortalWorkloadToken.Enabled + in.InlineApproval = d.InlineApproval.Enabled in.selectLine(pol.targetLine(in.Installation)) if err := in.checkRecord(); err != nil { return nil, err @@ -1171,7 +1173,7 @@ func (in *Input) checkRecord() error { if err := in.checkGovernance(); err != nil { return err } - if err := in.checkPortalWorkloadToken(); err != nil { + if err := in.checkInlineApproval(); err != nil { return err } if in.Installation.Private && in.klausGateway() && !holdAdmits(in.Versions.Components[componentMuster], "5.64.0") { diff --git a/render/agentplatform/portal.go b/render/agentplatform/portal.go index aa0011f9..a40205f6 100644 --- a/render/agentplatform/portal.go +++ b/render/agentplatform/portal.go @@ -363,7 +363,7 @@ func (in *Input) portalAppConfig() render.Map { // backend's traces and its scraped metrics where the chart takes them, and, // for a chat on Vertex, the Google project and location the chart exports to // the pod, and the portal's workload token for muster where -// portalWorkloadToken is on (workloadtoken.go). No list: the portal's environment is the customer-portal +// inlineApproval is on (inlineapproval.go). No list: the portal's environment is the customer-portal // definition's. func (in *Input) portalValues() render.Map { fragment := render.Map{e("filename", portalAppConfigFile), e("configMapRef", portalAppConfigMap)} @@ -371,7 +371,7 @@ func (in *Input) portalValues() render.Map { fragment = append(fragment, e("checksum", fmt.Sprintf("%x", sha256.Sum256(render.MustYAML(in.portalAppConfig()))))) } backstage := render.Map{e("extraAppConfig", []render.Map{fragment})} - if in.portalWorkloadToken() { + if in.inlineApproval() { // The portal's workload token for muster (workloadtoken.go). backstage = append(backstage, e("musterWorkloadToken", render.Map{e("enabled", true)})) } diff --git a/render/agentplatform/render.go b/render/agentplatform/render.go index 457f9006..29d72aa2 100644 --- a/render/agentplatform/render.go +++ b/render/agentplatform/render.go @@ -297,6 +297,11 @@ func (in *Input) configmapPatch() render.Map { })) } m = append(m, e("muster", in.musterValues())) + if in.inlineApproval() { + // The portal runs as a release of its own; its client is named here so + // the meta chart takes it as muster's trusted client (inlineapproval.go). + m = append(m, e("backstage", render.Map{e("oidcClientId", in.inlineApprovalClient())})) + } targets := in.Installation.Federation.Targets var mcps render.Map if len(targets) > 0 { @@ -529,10 +534,13 @@ func (in *Input) musterValues() render.Map { if in.hasPrivateTarget() { muster = append(muster, e("extraCaFile", extraCaFile())) } + if in.inlineApproval() { + muster = append(muster, e("approval", in.musterApproval())) + } out := render.Map{e("muster", append(muster, e("oauth", oauth)))} rbac := in.connectorAdmins() comment := "Giant Swarm's connector admins and workflow editors: the admin groups\nbound to muster's mcpserver-editor and workflow-editor Roles (the meta chart\nappends the platform team)." - if in.portalWorkloadToken() { + if in.inlineApproval() { rbac = append(rbac, e("approvalDecider", in.approvalDecider())) comment += "\nThe portal's ServiceAccount, bound to muster-approval-decider: muster takes\na person's inline approval decision only with its token beside theirs." } diff --git a/render/agentplatform/workloadtoken.go b/render/agentplatform/workloadtoken.go deleted file mode 100644 index ca5d0ebf..00000000 --- a/render/agentplatform/workloadtoken.go +++ /dev/null @@ -1,92 +0,0 @@ -package agentplatform - -import ( - "fmt" - - "github.com/Masterminds/semver/v3" - - "github.com/giantswarm/giantswarm-platform-manager/render" -) - -// The portal's workload identity for muster (portalWorkloadToken.enabled). -// muster takes a person's inline approval decision, and a sign-in handoff -// ticket request, from the portal only with the portal backend's own -// projected ServiceAccount token (audience muster) beside the person's, and -// only from a ServiceAccount bound to its Role muster-approval-decider. The -// meta chart wires both only for a portal it deploys itself -// (components.backstage); a portal the customer-portal definition renders is -// a release of its own, so this definition wires it: -// -// - the configmap patch binds muster-approval-decider to the portal's -// ServiceAccount (muster.rbac.approvalDecider.subjects); -// - the Component's values have the portal's chart project the token and -// name it in muster.workloadTokenFile (backstage.musterWorkloadToken, an -// object key, so it merges with the portal's own values). -// -// Off by default. Either half alone decides nothing: a token without the -// binding fails muster's access review, a binding without a token sends -// none. The token is valid on the cluster its ServiceAccount lives in only, -// so the portal must run on this installation. - -// PortalWorkloadTokenChart is the first portal chart that takes -// backstage.musterWorkloadToken (giantswarm/backstage's tool-approval work). -// UNSET until that release exists: an earlier chart's schema refuses the key -// and the portal's HelmRelease fails, so while it is unset the input is -// refused (fail closed). Set it to the release once it is cut; tests set it -// to exercise the render. -var PortalWorkloadTokenChart = "" - -const ( - // inputPortalWorkloadToken is the input, by its schema path. - inputPortalWorkloadToken = "portalWorkloadToken.enabled" - // portalServiceAccount is the portal's ServiceAccount, the chart's name - // in the portal's namespace. - portalServiceAccount = "backstage" -) - -// portalWorkloadToken says whether the platform wires the portal's workload -// identity for muster; checkPortalWorkloadToken has refused it where it -// cannot hold. -func (in *Input) portalWorkloadToken() bool { return in.PortalWorkloadToken } - -// approvalDecider is muster.rbac.approvalDecider: the portal's ServiceAccount -// alone. -func (in *Input) approvalDecider() render.Map { - return render.Map{e("subjects", []render.Map{{e("kind", "ServiceAccount"), e("name", portalServiceAccount), e("namespace", backstageNamespace)}})} -} - -// checkPortalWorkloadToken refuses the input where it cannot hold: while no -// meta chart and muster release carry muster-approval-decider -// (GovernanceChart unset, the same tool-approval releases), off the 4 chart -// line, under a hold of either below them, without a portal running on this -// installation, and while the portal's chart line admits no chart that -// projects the token (PortalWorkloadTokenChart unset or above its line). -func (in *Input) checkPortalWorkloadToken() error { - if !in.portalWorkloadToken() { - return nil - } - if GovernanceChart == "" { - return refuse(fmt.Sprintf("%s needs the meta chart and muster releases that ship muster's approval-decider Role, and none is released yet", describe(inputPortalWorkloadToken))) - } - if in.Installation.ChartLine != lineFour { - return in.refuseOffLineFour(inputPortalWorkloadToken) - } - if !holdAdmits(in.Versions.Chart, GovernanceChart) { - return refuse(fmt.Sprintf("%s needs the meta chart %s or later, and %s holds it at %s; move or lift the hold first", describe(inputPortalWorkloadToken), GovernanceChart, describe("versions.chart"), in.Versions.Chart)) - } - if hold := in.Versions.Components[componentMuster]; hold != "" && (GovernanceMuster == "" || !floorAtLeast(hold, GovernanceMuster)) { - return refuse(fmt.Sprintf("%s needs the muster release that ships its approval-decider Role, and %s holds muster at %s, whose chart refuses the binding; move or lift the hold first", describe(inputPortalWorkloadToken), describe("versions.components.muster"), hold)) - } - p := in.hostedPortal() - if p == nil || p.Installation != in.Installation.Name { - return refuse(fmt.Sprintf("%s binds the portal's ServiceAccount in %s's own cluster, and no portal runs on %s: the token is valid only where its ServiceAccount lives", describe(inputPortalWorkloadToken), in.Installation.Name, in.Installation.Name)) - } - if PortalWorkloadTokenChart == "" || !portalChartAdmits(p.ChartLine, semver.MustParse(PortalWorkloadTokenChart)) { - floor := PortalWorkloadTokenChart - if floor == "" { - floor = "the release that projects the token (not released yet)" - } - return refuse(fmt.Sprintf("%s needs the portal chart %s or later, and the portal %s runs the chart line %q; move the portal's chart line first", describe(inputPortalWorkloadToken), floor, p.Domain, p.ChartLine)) - } - return nil -} diff --git a/render/agentplatform/workloadtoken_test.go b/render/agentplatform/workloadtoken_test.go deleted file mode 100644 index cd814e47..00000000 --- a/render/agentplatform/workloadtoken_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package agentplatform - -import ( - "errors" - "path/filepath" - "strings" - "testing" - - "github.com/giantswarm/giantswarm-platform-manager/render" -) - -const ( - // testPortalWorkloadTokenChart is the portal chart the tests take as the - // first that projects the token. - testPortalWorkloadTokenChart = "3.53.0" - keyPortalWorkloadToken = "portalWorkloadToken" - // wantDecider is the binding the configmap patch carries. - wantDecider = "\n approvalDecider:\n subjects:\n - kind: ServiceAccount\n name: backstage\n namespace: backstage\n" - // wantToken is the Component's values turning the projection on. - wantToken = "\n musterWorkloadToken:\n enabled: true\n" -) - -// withPortalWorkloadTokenReleases takes the meta chart, muster and portal -// chart releases as cut for the test. Not parallel, like -// withGovernanceReleases. -func withPortalWorkloadTokenReleases(t *testing.T) { - t.Helper() - withGovernanceReleases(t) - chart := PortalWorkloadTokenChart - PortalWorkloadTokenChart = testPortalWorkloadTokenChart - t.Cleanup(func() { PortalWorkloadTokenChart = chart }) -} - -// workloadTokenInput is the organizations-portal installation, whose portal -// runs on it, with the input on and the portal's chart line set. -func workloadTokenInput(t *testing.T, line string) (map[string]any, map[string]string) { - t.Helper() - input, secrets := loadInput(t, shapeOrganizationsPortal) - input[keyPortalWorkloadToken] = map[string]any{keyEnabled: true} - installation := input["installation"].(map[string]any) - portals := installation["portals"].([]any) - portals[0].(map[string]any)["chartLine"] = line - return input, secrets -} - -// componentValues is the Component's values file of a result. -func componentValues(t *testing.T, result *render.Result) string { - t.Helper() - for name, content := range result.Tree() { - if strings.HasSuffix(filepath.ToSlash(name), "/extras/backstage/agent-platform/values.yaml") { - return string(content) - } - } - t.Fatal("no Component values rendered") - return "" -} - -// On, with the releases cut and a portal on the installation whose chart -// line admits the projecting chart, the configmap patch binds the portal's -// ServiceAccount to muster-approval-decider and the Component's values have -// the portal's chart project the token; the binding reads back as the input -// (a reconcile keeps both). Off, neither renders. -func TestPortalWorkloadTokenRenders(t *testing.T) { - withPortalWorkloadTokenReleases(t) - input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") - result, err := Render(input, secrets, render.ModeCommit) - if err != nil { - t.Fatal(err) - } - if patch := platformPatch(t, result); !strings.Contains(patch, wantDecider) { - t.Fatalf("the patch binds no portal ServiceAccount:\n%s", patch) - } - if values := componentValues(t, result); !strings.Contains(values, wantToken) || !strings.Contains(values, "extraAppConfig") { - t.Fatalf("the Component's values project no token beside the fragment:\n%s", values) - } - - off, secrets := loadInput(t, shapeOrganizationsPortal) - result, err = Render(off, secrets, render.ModeCommit) - if err != nil { - t.Fatal(err) - } - if strings.Contains(platformPatch(t, result), "approvalDecider") || strings.Contains(componentValues(t, result), "musterWorkloadToken") { - t.Fatal("off, the patch or the Component's values carry the portal's workload identity") - } -} - -// While the releases are unset (the shipped state) the input is refused: -// fail closed, an earlier muster or portal chart refuses the keys. -func TestPortalWorkloadTokenIsRefusedUntilItsReleasesExist(t *testing.T) { - input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") - if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "portalWorkloadToken.enabled needs the meta chart and muster releases") { - t.Fatalf("got %v, want ErrInput naming the input and the missing release", err) - } - - withGovernanceReleases(t) - if _, err := Render(input, secrets, render.ModeCommit); !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), "the release that projects the token (not released yet)") { - t.Fatalf("got %v, want ErrInput naming the missing portal chart release", err) - } -} - -// Where the input cannot hold, it is refused naming it: no portal on the -// installation, a portal chart line below the projecting chart, a hold of -// muster or the meta chart below the releases with the Role. -func TestPortalWorkloadTokenRefusals(t *testing.T) { - withPortalWorkloadTokenReleases(t) - for _, c := range []struct { - name string - input func() (map[string]any, map[string]string) - names string - }{ - {"a portal on another installation", func() (map[string]any, map[string]string) { - input, secrets := loadInput(t, shapePlatformTenantRetired) - input[keyPortalWorkloadToken] = map[string]any{keyEnabled: true} - return input, secrets - }, "no portal runs on garnet"}, - {"a portal chart line below the projecting chart", func() (map[string]any, map[string]string) { - return workloadTokenInput(t, ">=2.1.0 <3.0.0") - }, "needs the portal chart 3.53.0 or later"}, - {"a muster hold below the release", func() (map[string]any, map[string]string) { - input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") - input["versions"] = map[string]any{"components": map[string]any{componentMuster: ">=5.60.0 <5.61.0"}} - return input, secrets - }, "holds muster at"}, - {"a meta chart hold below the release", func() (map[string]any, map[string]string) { - input, secrets := workloadTokenInput(t, ">=3.0.0 <4.0.0") - input["versions"] = map[string]any{"chart": "4.180.0"} - return input, secrets - }, "needs the meta chart " + testGovernanceChart + " or later"}, - } { - t.Run(c.name, func(t *testing.T) { - input, secrets := c.input() - _, err := Render(input, secrets, render.ModeCommit) - if !errors.Is(err, ErrInput) || !strings.Contains(err.Error(), inputPortalWorkloadToken) || !strings.Contains(err.Error(), c.names) { - t.Fatalf("got %v, want ErrInput naming the input and %q", err, c.names) - } - }) - } -} diff --git a/render/portal.go b/render/portal.go index beb1fb80..3db723ed 100644 --- a/render/portal.go +++ b/render/portal.go @@ -19,6 +19,10 @@ const ( // definition references the Secret and renders the client only where it // is on record (installation.portalClientSecret). PortalDexClientSecretFile = "dex-client-backstage-secret.enc.yaml" // #nosec G101 -- a file name, not a value + // PortalServiceAccount is the ServiceAccount a portal's pods run as + // where its values set no other chart name: the backstage chart's + // default name, which the customer-portal definition never overrides. + PortalServiceAccount = "backstage" // PortalDexClientName is the client's display name in Dex. PortalDexClientName = "Dev Portal" // DexSecretKey is the key every Dex client Secret carries. From 081b39d531333bf13a976a4f4af9dd4052246ca2 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Mon, 30 Nov 2026 14:56:21 +0100 Subject: [PATCH 27/27] test(e2e): read back the inline approval input with the other switches --- internal/e2e/verify_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/e2e/verify_test.go b/internal/e2e/verify_test.go index 40ae23e4..3e8a6b4c 100644 --- a/internal/e2e/verify_test.go +++ b/internal/e2e/verify_test.go @@ -158,7 +158,7 @@ func TestVerifyCapabilityAsDefined(t *testing.T) { } // Commit mode of the organizations is read back as the commit // repository's presence, so a patch on record without it answers false. - if !reflect.DeepEqual(res.Inputs.ReadBack, map[string]any{"agentManager.github.tokenExchange.enabled": false, "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, "organizations.commit.enabled": false}) { + if !reflect.DeepEqual(res.Inputs.ReadBack, map[string]any{"agentManager.github.tokenExchange.enabled": false, "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, "organizations.commit.enabled": false, "inlineApproval.enabled": false}) { t.Errorf("read back %v", res.Inputs.ReadBack) } if res.Summary[verify.Drifted] != 0 || res.Summary[verify.DiffersByInput] != 0 || res.Summary[verify.AsDefined] == 0 { @@ -737,7 +737,7 @@ func TestVerifyCapabilityReadsBackTheServingChoice(t *testing.T) { birchByHand(t, st, c, false) res = verifyRowan(t, c, birch) - if res.Inputs.Source != verify.Source(true, false) || res.Refused != "" || !reflect.DeepEqual(res.Inputs.ReadBack, map[string]any{"agentManager.github.tokenExchange.enabled": false, "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, "organizations.commit.enabled": false}) || res.Summary[verify.DiffersByInput] != 0 { + if res.Inputs.Source != verify.Source(true, false) || res.Refused != "" || !reflect.DeepEqual(res.Inputs.ReadBack, map[string]any{"agentManager.github.tokenExchange.enabled": false, "clusterManager.github.tokenExchange.enabled": false, "modelManager.github.tokenExchange.enabled": false, "skillManager.github.tokenExchange.enabled": false, "organizations.commit.enabled": false, "inlineApproval.enabled": false}) || res.Summary[verify.DiffersByInput] != 0 { t.Fatalf("inputs %q refused %q read back %v summary %v", res.Inputs.Source, res.Refused, res.Inputs.ReadBack, res.Summary) } if serving, _ := res.Inputs.Values["modelServing"].(map[string]any); serving["enabled"] != false {