diff --git a/README.md b/README.md index 683ce6bcf..f7cb5c046 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, 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 @@ -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. Once a member approves or denies, the gateway shortens the message in the channel to one line — the outcome, the decider and the diff --git a/definitions/agent-platform/README.md b/definitions/agent-platform/README.md index f69b04702..a49723e95 100644 --- a/definitions/agent-platform/README.md +++ b/definitions/agent-platform/README.md @@ -5,10 +5,11 @@ 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 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, muster's organization principals and the tool server URLs their tokens may go to, 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 `[]`. | +| `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 @@ -55,6 +56,8 @@ 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`; 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 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 22c45b7c5..e812a9eae 100644 --- a/definitions/agent-platform/features.yaml +++ b/definitions/agent-platform/features.yaml @@ -93,6 +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, 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 / 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} @@ -135,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-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/governance.yaml b/definitions/agent-platform/governance.yaml new file mode 100644 index 000000000..9e88e22f2 --- /dev/null +++ b/definitions/agent-platform/governance.yaml @@ -0,0 +1,82 @@ +# 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 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, 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] + 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), 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] + # 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: + 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 + 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 +# 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] diff --git a/definitions/agent-platform/schema.json b/definitions/agent-platform/schema.json index 7010e17a4..fb367ab43 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."} } } }, @@ -849,7 +850,65 @@ "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." + } + } + }, + "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.mode"}, + "x-feature": "tool-access", + "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": { + "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: 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."} + } + } + ] + }, + "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: 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." + } + } + }, + "inlineApproval": { + "type": "object", + "additionalProperties": false, + "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.subjects.[namespace=backstage]", "kind": "present"}, + "x-feature": "portal", + "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/definitions/governance.go b/definitions/governance.go new file mode 100644 index 000000000..2aceebed1 --- /dev/null +++ b/definitions/governance.go @@ -0,0 +1,110 @@ +package definitions + +import ( + "fmt" + "maps" + "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"` +} + +// 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 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"` + WorkflowEditors []Subject `yaml:"workflowEditors"` + } `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 { + 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.Roles() { + if slices.Contains(g.Floors(role), tool) { + return role + } + } + return "" +} diff --git a/definitions/governance_test.go b/definitions/governance_test.go new file mode 100644 index 000000000..948943511 --- /dev/null +++ b/definitions/governance_test.go @@ -0,0 +1,197 @@ +package definitions_test + +import ( + "go/ast" + "go/parser" + "go/token" + "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 +// 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)) // #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) + } + 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" || name.Name == "builtinRoleFloors" { + 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 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) + } + 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{}} + } + } + 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 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.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 != "" { + 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) + } + } + 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) + } + } + 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") + } +} + +// 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/docs/governance.md b/docs/governance.md new file mode 100644 index 000000000..c76ae9c5f --- /dev/null +++ b/docs/governance.md @@ -0,0 +1,213 @@ +# 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. 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 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 | Effect | +|---|---|---| +| 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 + +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 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: + 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. + +## 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 `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 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"]}}' +``` + +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`), 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 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. + +- 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, loosening lines first: + +```text +*Governance:* this changes the platform's governance; a second person approves it, on test installations too. +*It loosens governance:* rowan: mode governed → trusted +• rowan: mode governed → trusted +``` + +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, 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`, + `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 + +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` | 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 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 + +- 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 safe list + +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). + +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 c1c1859f7..e3055b749 100644 --- a/helm/giantswarm-platform-manager/README.md +++ b/helm/giantswarm-platform-manager/README.md @@ -44,11 +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 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. The gateway must be klaus-gateway v4.19.0 or newer: older ones refuse the review's `summary` field, so no review could be posted. | | 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 (`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/templates/admission-governancerecords.yaml b/helm/giantswarm-platform-manager/templates/admission-governancerecords.yaml new file mode 100644 index 000000000..ce9aa3761 --- /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 740d4d297..73d591e94 100644 --- a/helm/giantswarm-platform-manager/templates/crd-actions.yaml +++ b/helm/giantswarm-platform-manager/templates/crd-actions.yaml @@ -143,9 +143,41 @@ 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} + 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 + additionalProperties: {type: string} 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/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml new file mode 100644 index 000000000..02a1300b8 --- /dev/null +++ b/helm/giantswarm-platform-manager/templates/crd-governancerecords.yaml @@ -0,0 +1,68 @@ +{{- 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] + x-kubernetes-validations: + - rule: self.spec.installation == self.metadata.name + message: spec.installation names the record's object + 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 + 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/templates/deployment.yaml b/helm/giantswarm-platform-manager/templates/deployment.yaml index eb71a8dc3..9ea567b8f 100644 --- a/helm/giantswarm-platform-manager/templates/deployment.yaml +++ b/helm/giantswarm-platform-manager/templates/deployment.yaml @@ -122,6 +122,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/templates/rbac.yaml b/helm/giantswarm-platform-manager/templates/rbac.yaml index e6a1e268d..a254031e7 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/helm/giantswarm-platform-manager/values.schema.json b/helm/giantswarm-platform-manager/values.schema.json index 60d0ff923..7524850eb 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 write the reviewed-governance records (`governancerecords.platform-manager.giantswarm.io`). 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." @@ -38,6 +42,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. The gateway must be klaus-gateway v4.19.0 or newer: older ones refuse the review's `summary` field, so no review could be posted." }, + "governanceTeam": { + "type": "string", + "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": { "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 4f020d204..3ea60fa9b 100644 --- a/helm/giantswarm-platform-manager/values.yaml +++ b/helm/giantswarm-platform-manager/values.yaml @@ -64,6 +64,11 @@ 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 write the reviewed-governance records + # (`governancerecords.platform-manager.giantswarm.io`). Needs Kubernetes 1.30 + # or later. + governanceRecordPolicy: true approvals: # -- klaus-gateway's base URL as reached from the pod (for example @@ -92,6 +97,9 @@ approvals: # `mode: commit` on test installations; the hub and customer installations # keep the review. standupChannel: "" + # -- 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. audience: klaus-gateway diff --git a/internal/actions/actions.go b/internal/actions/actions.go index 7dc26df87..1700e7426 100644 --- a/internal/actions/actions.go +++ b/internal/actions/actions.go @@ -119,6 +119,22 @@ 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"` + // GovernanceAfter is, per installation, the governance the commit leaves + // on record (plan.GovernanceSnapshot as JSON; a disable's is the + // 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"` + // 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. @@ -172,6 +188,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. @@ -680,3 +701,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/actions/records.go b/internal/actions/records.go new file mode 100644 index 000000000..77bbddee2 --- /dev/null +++ b/internal/actions/records.go @@ -0,0 +1,129 @@ +package actions + +import ( + "context" + "errors" + "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"` + // 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, 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. +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, expected string) 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) + current, err := c.GetRecord(ctx, r.Installation) + switch { + 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: + 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 { + return fmt.Errorf("actions: write governance record %s/%s: %w", c.ns, r.Installation, err) + } + return nil +} diff --git a/internal/approvals/approvals.go b/internal/approvals/approvals.go index ceec94500..3d1bb94cf 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/chart/chart_test.go b/internal/chart/chart_test.go index a78ab0740..f04244bd1 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/fakes_test.go b/internal/e2e/fakes_test.go index caabf6a22..f7105fe01 100644 --- a/internal/e2e/fakes_test.go +++ b/internal/e2e/fakes_test.go @@ -43,7 +43,16 @@ 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 + // 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, @@ -101,6 +110,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 +131,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{}, 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) { @@ -126,7 +141,44 @@ 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"}) + 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 { + 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 +987,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 new file mode 100644 index 000000000..49f4bc923 --- /dev/null +++ b/internal/e2e/governance_test.go @@ -0,0 +1,821 @@ +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" + "slices" + "strings" + "testing" + "time" + + "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/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" +) + +// The governance input's keys. +const ( + keyGovernanceInput = "governance" + keyMode = "mode" + keyIdleTTL = "idleTTL" + keySessions = "sessions" + keyGovernedServers = "governedServers" +) + +// 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)) +} + +// 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) + sopsFixtures(t, st.ghs) + 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, keyGovernedServers: 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()) +} + +// 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" + +// 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}, actions.RecordNone); err != nil { + t.Fatal(err) + } +} + +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) + + 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) + } + 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) != 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"`) { + 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"]) + 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") + + // 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) + // 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) + } + 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) + } + 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, `"mode":"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) + } + + 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, "\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, "\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 + // 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 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) +} + +// 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.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)}) + if isErr || out.Action == nil { + t.Fatalf("commit: %v %s", isErr, text) + } + 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 == "" { + 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) { + 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 { + 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:\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}}) + 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" { + 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) + } + 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) + } +} + +// 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) +} + +// 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 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) +} + +// 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{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 the team reviewed in action "+merged.Name) { + 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 the team reviewed in action "+merged.Name) { + 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) + seedRecord(t, st, 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) + } +} + +// 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, 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) + } + 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) + } +} + +// 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/e2e/identity_chain_test.go b/internal/e2e/identity_chain_test.go index 2e126e3af..9d5555add 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. @@ -124,9 +131,11 @@ 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. + 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/e2e/verify_test.go b/internal/e2e/verify_test.go index 40ae23e4e..3e8a6b4ca 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 { diff --git a/internal/installations/derive.go b/internal/installations/derive.go index cd4a371cb..36e26837e 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 ae5d567ae..898c318ce 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/governance_readback_test.go b/internal/installations/governance_readback_test.go new file mode 100644 index 000000000..b86b926e7 --- /dev/null +++ b/internal/installations/governance_readback_test.go @@ -0,0 +1,57 @@ +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:\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 +// 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{"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:\n mode: governed\n roleFloors:\n 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) + 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/inlineapproval_readback_test.go b/internal/installations/inlineapproval_readback_test.go new file mode 100644 index 000000000..e3847daaa --- /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 c6437f6c5..e90129304 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, + inputInlineApproval: false, } maps.Copy(want, choices) return want diff --git a/internal/installations/readback_test.go b/internal/installations/readback_test.go index d73ca7c36..b9b9ebcfd 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": ""}, 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}}}, @@ -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/installations/registry.go b/internal/installations/registry.go index 67e870efd..07cdcfe17 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/plan/governance.go b/internal/plan/governance.go new file mode 100644 index 000000000..8cde0be8a --- /dev/null +++ b/internal/plan/governance.go @@ -0,0 +1,565 @@ +package plan + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + "unicode" + + "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): 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, 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, 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 that carry the governance, and the snapshot's keys. +const ( + keyGovernance = "governance" + 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" +) + +// 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" + +// 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") +} + +// 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 + } + if v, ok := d[keyGovernedServers]; ok { + out[keyGovernedServers] = v + } + if v := dig(d, "muster", "muster", "governance"); v != nil { + out[keyMusterGovernance] = v + } + 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 +} + +// 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 + } + if out == nil { + out = GovernanceSnapshot{} + } + 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)) + 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. +// +// 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 && f.Change != ChangeUnchanged) { + continue + } + 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 != ChangeCreate && onRecord == "") + 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 { + 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) + } +} + +// 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.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) + } + 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)) + } + 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)) +} + +// 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 +// removing them loosens (review F2). +func roleFloorsOf(v any) map[string][]string { + m, _ := v.(map[string]any) + floors, _ := m["roleFloors"].(map[string]any) + 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 + 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{} + // 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) + if v != nil && overrides == nil { + out[""] = &server{odd: fmt.Sprint(v)} + } + for source, o := range overrides { + if o == nil { + out[source] = nil + continue + } + 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 + } + 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().Servers() + for _, source := range sortedKeys(old, next) { + o, n := old[source], next[source] + at := keyGovernedServers + "." + clean(source) + switch { + 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), " "))) + } + } + } +} + +// 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) + } + 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) + } + } + 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", "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(splitCamel(tool)), func(r rune) bool { return r == '_' || r == '-' || r == '.' }) { + if slices.Contains(writeVerbs, word) { + return " (named like a write)" + } + } + 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 +// 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) + } + } + return b.String() +} + +func canonical(v any) string { + if v == nil { + return "" + } + b, _ := json.Marshal(v) + return string(b) +} + +// 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 +} + +func orEmpty(v any) any { + if v == nil { + return "" + } + return v +} + +func quoteOr(s, none string) string { + if s == "" { + return none + } + return clean(s) +} diff --git a/internal/plan/governance_test.go b/internal/plan/governance_test.go new file mode 100644 index 000000000..b91a3927e --- /dev/null +++ b/internal/plan/governance_test.go @@ -0,0 +1,260 @@ +package plan + +import ( + "slices" + "strings" + "testing" + + "github.com/giantswarm/giantswarm-platform-manager/render/agentplatform" +) + +const ( + 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 +// 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: govInstallation, Files: []File{{Path: govPatch, Change: change, Current: current, Content: next}}} +} + +// 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.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 + current, next string + 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{modeGovernedToTrusted}, []string{modeGovernedToTrusted}}, + {"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}}, + {"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 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)) + 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) + } + }) + } + // 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, "")} { + 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("", 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: "b: 2\n", Content: govGoverned}}}, + } { + 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 → 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, modeGovernedToTrusted) || 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) + } +} + +// Decision #92: the meta chart's governance is a map with the mode and +// 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 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(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) + } +} + +// 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) + } +} + +// 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/plan/plan.go b/internal/plan/plan.go index 1e8bd1a16..574988c1d 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -364,8 +364,17 @@ 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"` + // 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/plan/summary.go b/internal/plan/summary.go index c5dedfb7b..371883408 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 { @@ -80,6 +82,12 @@ func Summary(p Installation) []string { if w := p.SwitchOff.Warning(); w != "" { out = append(out, w) } + 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 { c := comps[name] items := joinAdds(uniq(c.items)) @@ -178,6 +186,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 { @@ -606,3 +618,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 +} diff --git a/internal/tools/approval.go b/internal/tools/approval.go index a3ce25895..ca5a803da 100644 --- a/internal/tools/approval.go +++ b/internal/tools/approval.go @@ -139,10 +139,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(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()) + 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) } @@ -173,6 +185,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, "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 } @@ -304,6 +317,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) @@ -360,11 +378,19 @@ 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.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) 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 @@ -377,18 +403,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(actions.GovernanceOf(a)) == 0 } return false } @@ -517,8 +564,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 { @@ -528,7 +576,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(actions.GovernanceOf(a)) > 0 { return t.askApproval(ctx, a, tool) } status := a.Status @@ -732,6 +782,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/capability.go b/internal/tools/capability.go index 520c792eb..5fea3c891 100644 --- a/internal/tools/capability.go +++ b/internal/tools/capability.go @@ -361,6 +361,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, _, e.GovernanceRecord = 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 64d82c86a..e9cec2dda 100644 --- a/internal/tools/commit.go +++ b/internal/tools/commit.go @@ -152,6 +152,24 @@ 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)) } + // 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 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. + 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) @@ -180,6 +198,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 team reviewed (" + strings.Join(g.Lines, "; ") + "): a reviewed change that types the governance confirms or reverts it" + } return res, nil } @@ -187,6 +208,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) @@ -201,6 +225,18 @@ 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)) + // 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) 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/disable.go b/internal/tools/disable.go index 3d3520997..a112bc0bb 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, record, 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,26 @@ 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 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]...) + 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 +450,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 new file mode 100644 index 000000000..ca6b43e53 --- /dev/null +++ b/internal/tools/governance.go @@ -0,0 +1,496 @@ +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/plan" +) + +// Governing tool calls (giantswarm/giantswarm#38902): one person never +// changes an installation's governance alone. A commit whose plan changes +// 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 and anyone who is not +// an active member of the governance reviewers' team (approvals.governanceTeam), +// 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). + +// 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 { + if !errors.Is(err, actions.ErrNotFound) { + t.d.Log.Warn("governance_record_unread", identity.LogAttr(ctx), "audit", true, "installation", installation, "error", err.Error()) + } + return nil, nil, false + } + 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 snap, r, true +} + +// 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" +} + +// 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 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, 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, 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 + 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 + } + case current.InPlay() || next.InPlay(): + t.d.Log.Warn("governance_unrecorded", identity.LogAttr(ctx), "audit", true, "installation", 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...) + } + if !found { + r = nil + } + return g, base, actions.RecordIdentity(r) +} + +// governanceChange is the governance a commit of p changes, against the +// 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, "", "" + } + if unreadable { + g := plan.GovernanceUnreadable() + _, r, found := t.reviewedGovernance(ctx, p.Name) + if !found { + r = nil + } + return &g, "", actions.RecordIdentity(r) + } + g, _, record := t.against(ctx, p.Name, current, next) + if len(g.Lines) == 0 { + return nil, next.JSON(), record + } + return &g, next.JSON(), record +} + +// 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 +// (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 + } + 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, "", actions.RecordNone, nil + } + 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...) + g.Loosens = append(slices.Clone(lead.Loosens), g.Loosens...) + changes = true + } + if !changes { + return nil, base.JSON(), record, 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 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, 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 "" + } + 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, 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) + } + 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 +// 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, "" +} + +// 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 +// 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 := actions.GovernanceOf(a)[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(actions.GovernanceOf(a)) == 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.") + b.WriteString(governanceLoosens(a)) + cut := 0 + for _, n := range governedInstallations(a) { + line := "\n• " + n + ": " + strings.Join(actions.GovernanceOf(a)[n].Lines, "; ") + if utf8.RuneCountInString(b.String())+utf8.RuneCountInString(line) > governanceReviewMax { + cut++ + continue + } + b.WriteString(line) + } + 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 { + var out []string + for _, n := range a.Spec.Installations { + if _, ok := actions.GovernanceOf(a)[n]; ok { + out = append(out, n) + } + } + for _, n := range slices.Sorted(maps.Keys(actions.GovernanceOf(a))) { + 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, 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 := 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...)...) + } +} + +// 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 := actions.GovernanceOf(a)[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 new file mode 100644 index 000000000..bff3f76bf --- /dev/null +++ b/internal/tools/governance_test.go @@ -0,0 +1,265 @@ +package tools + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "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 { + 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, 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()) + 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) + } +} + +// 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()) + } +} + +// 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: rowanValues, 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) + } +} + +// 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) + } +} + +// 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) { + if f.have == nil { + return nil, actions.ErrNotFound + } + return f.have, nil +} + +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 +} + +// 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 + noAfter bool + base string + }{ + {"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{} + 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"}}`} + 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 { + 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") + } +} + +// 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/resync.go b/internal/tools/resync.go index 0c47bd345..94a662978 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(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 // told is the stage an action that needs no review started outside // merge_action: the standup channel hears of it as of a merge. @@ -228,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 72bfac6e1..42d714877 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 c3683f8c3..3f5bd00e7 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. @@ -156,6 +161,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) @@ -285,6 +293,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) { @@ -302,7 +311,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 243389127..f2130146f 100644 --- a/internal/tools/wave.go +++ b/internal/tools/wave.go @@ -110,10 +110,35 @@ func (t *Tools) capabilityWave(ctx context.Context, tool string, args map[string spec.CapabilityByInstallation[n] = d.Name } } - for _, p := range targets { + governs := false + 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) + g, after := p.Governance, governanceAfter(*p) + if after != "" { + if spec.GovernanceAfter == nil { + spec.GovernanceAfter = map[string]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{} + } + 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 @@ -131,6 +156,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 } @@ -142,6 +170,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) @@ -180,6 +211,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 { + // 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 { + if a, err = t.recordMoved(ctx, a, p.Name, 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) 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/verify/verify_test.go b/internal/verify/verify_test.go index 3f1880da4..6e69c37e3 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, []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"}, 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{"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/main.go b/main.go index e1b7c3214..36b9fd662 100644 --- a/main.go +++ b/main.go @@ -38,7 +38,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 @@ -61,6 +61,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)") @@ -103,7 +104,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.go b/render/agentplatform/governance.go new file mode 100644 index 000000000..b3e353a5e --- /dev/null +++ b/render/agentplatform/governance.go @@ -0,0 +1,294 @@ +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" +) + +// 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" +) + +// 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().Servers() + 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 +// governed mode or a governedServers override. +func (g Governance) governs() bool { + return g.Mode == GovernanceGoverned || len(g.GovernedServers) > 0 +} + +// 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 { + 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) + } + } + 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 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 + } + 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 + } + 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 +// 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, 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() { + 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, 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) + } + g := definitions.Governance() + 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 "" + } + 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 "" + } + 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 !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 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 new file mode 100644 index 000000000..2e1518f4e --- /dev/null +++ b/render/agentplatform/governance_test.go @@ -0,0 +1,300 @@ +package agentplatform + +import ( + "errors" + "fmt" + "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" + keyMode = "mode" + keyGovernedServers = "governedServers" + keyRole = "role" + toolListActions = "list_actions" + keySafe = "safe" + sourcePlatformManager = "giantswarm-platform-manager" + // 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. +// 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{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{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) + _, 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{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) + } +} + +// 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{ + 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:\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/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) { + t.Fatalf("the patch carries no %q:\n%s", want, patch) + } + } + mode, servers := governanceOf(t, patch) + 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}) + 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[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") || + !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) + } +} + +// 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) + } + 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{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) + } +} + +// 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) + } +} + +// 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{keyGovernedServers: 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{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(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, "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(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) { + 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{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{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}, + } { + 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 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(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(componentSkillManager, map[string]any{keySafe: manyTools(64)}), 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) + } + }) + } +} + +// 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 +} + +// 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) + } +} diff --git a/render/agentplatform/inlineapproval.go b/render/agentplatform/inlineapproval.go new file mode 100644 index 000000000..9dcc594d1 --- /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 000000000..fa1095418 --- /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 8f9fa4884..05bcca261 100644 --- a/render/agentplatform/input.go +++ b/render/agentplatform/input.go @@ -194,6 +194,14 @@ 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 + // 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. @@ -361,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 @@ -737,6 +748,10 @@ type document struct { } `json:"platform"` PlatformTeam *[]Subject `json:"platformTeam"` } `json:"tenants"` + Governance Governance `json:"governance"` + InlineApproval struct { + Enabled bool `json:"enabled"` + } `json:"inlineApproval"` Versions Versions `json:"versions"` } @@ -897,7 +912,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 +966,9 @@ 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.Governance.withoutPlatformServers() + in.InlineApproval = d.InlineApproval.Enabled in.selectLine(pol.targetLine(in.Installation)) if err := in.checkRecord(); err != nil { return nil, err @@ -1152,6 +1170,12 @@ func (in *Input) checkRecord() error { if err := in.checkPlatformTenant(); err != nil { return err } + if err := in.checkGovernance(); err != nil { + return err + } + if err := in.checkInlineApproval(); 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 a6d5dc495..a40205f6f 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 +// 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)} 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.inlineApproval() { + // 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 2c6b70349..d41641d75 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 { @@ -340,6 +345,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())})) } @@ -521,7 +527,20 @@ 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)))} + 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.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." + } + if rbac != nil { + out = append(out, render.Entry{Key: "rbac", Value: rbac, Comment: comment}) + } + 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 59f6136ee..0f7cec65d 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,26 @@ muster: - staging-gateway trustedPublicRegistrationRedirectURIs: - https://agents.runtime.example/identities/oauth2/callback/00000000-0000-4000-8000-00000000000a + # 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: + - 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 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 3eb817e41..f0a20f8b9 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,26 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # 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: + - 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 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 889dadd49..e2391d90d 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 88091a100..098b2ca4e 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 81dd693ea..5e6a83a77 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 419a40b31..df7347215 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 1d2ffdab9..dc8ed6a6c 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,26 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: marmot-token-exchange-credentials + # 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: + - 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 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 e728f66f0..587757af7 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 9b903ad6e..95f1f2826 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 0d37ad734..bfe90624d 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 a67a0d129..9e9ec0a70 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 34fb48d4e..a1496a334 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,26 @@ muster: - dex-k8s-authenticator - kagent - backstage + # 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: + - 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 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 0e73fc318..799f40f46 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,26 @@ 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 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: + - 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 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 14fba5bf8..7cf945a2a 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,26 @@ muster: scopes: openid profile email groups audience:server:client_id:dex-k8s-authenticator clientCredentialsSecretRef: name: vole-token-exchange-credentials + # 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: + - 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 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 772a1901c..98fe047a4 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,26 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # 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: + - 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 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 5027776fe..b2cd94c8f 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,26 @@ muster: trustedAudiences: - dex-k8s-authenticator - kagent + # 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: + - 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 cluster-manager: installation: name: wren diff --git a/render/portal.go b/render/portal.go index beb1fb802..3db723ed3 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.