diff --git a/docs/dev-environment.md b/docs/dev-environment.md index 2311dab5..8894884a 100644 --- a/docs/dev-environment.md +++ b/docs/dev-environment.md @@ -95,6 +95,24 @@ runs reuse it. It cannot be `backstage.port` (7007), which kind publishes for the in-cluster Backstage. Removing the key and running `agentlab reload` unregisters it. +**Approving tool calls from `portal dev`.** Lab only. + +- *Return from muster's approval page:* muster returns only to origins on + `oauth.mcpClient.postLoginRedirectAllowlist`. While `backstage.localDevPort` + is set the lab adds `http://localhost:3000/sessions` to muster's list. It is + part of the platform values: run `agentlab platform` once after the first + `portal dev` (or after removing the key). Without it muster logs `Ignoring a + return not in oauth.mcpClient.postLoginRedirectAllowlist` and shows its own + page. +- *Inline decisions:* muster takes them only with the portal backend's workload + token beside the person's (audience `muster`, reviewed for verb `decide` on + `toolapprovals`). Every `portal dev` mints one for the lab portal's + ServiceAccount (`agent-platform/backstage`, 12 hours) with the lab's admin + kubeconfig, writes it to `state/backstage-dev/muster-workload-token` (0600) + and points `muster.workloadTokenFile` at it. Without that ServiceAccount (no + portal in the lab) approvals open muster's own pages. Restart `portal dev` + after 12 hours. + **Limits.** - The database is in memory, so every backend restart starts it empty: the diff --git a/docs/identity.md b/docs/identity.md index 289ba7a6..c5c79e91 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -315,7 +315,13 @@ the portal callback on the shared platform client. The Backstage redirect path carries the **provider name** from the app-config, not the literal word `oidc` — Backstage serves each provider at `/api/auth//handler/frame`, and the chart names it -`oidc-agent-platform`. More clients means editing the Dex template +`oidc-agent-platform`. + +`agentlab portal dev` passes the `backstage` client's secret (key +`portal-dex-client-secret` of `agent-platform/agent-platform-secrets`) as +`AGENT_PLATFORM_PORTAL_OIDC_CLIENT_SECRET`. + +More clients means editing the Dex template (`internal/lab/templates/dex.yaml.tmpl`), rebuilding and `agentlab reload`. ### `trustedPeers` points the other way round diff --git a/docs/platform.md b/docs/platform.md index eef6ee3a..872999ef 100644 --- a/docs/platform.md +++ b/docs/platform.md @@ -347,6 +347,38 @@ not a dev image is configured; `agentlab status` names it on its `registry` line, and it goes with `agentlab down`. Removing the overlay and re-running `agentlab platform` puts the released chart back. +## Running a lab in governed mode + +The chart's `governance.mode` (`trusted`, the default, or `governed`) decides +whether muster asks a person before an agent runs a write on the platform's own +servers (see the chart's README). Set it with a `platform.valuesFiles` overlay: + +```yaml +# governed.yaml +governance: + mode: governed +``` + +```yaml +platform: + valuesFiles: + - /path/to/governed.yaml +``` + +Then `agentlab platform`; it rolls muster, which reads the mode once at start. +`agentlab status` names the overlay and mode. Removing the entry and re-running +returns the lab to trusted. + +- A released chart with tool approval needs only the overlay. Until then the chart + refuses `governed` at render (release floors unset): use a dev chart whose + floors name dev builds ([Installing an unreleased + chart](#installing-an-unreleased-chart)), push the dev muster and + agent-manager charts into the lab registry and name them with + `components..versionRange` in the overlay ([An unreleased component + chart](#an-unreleased-component-chart)). +- A portal on another port than 443 needs `backstage.publicPort` (8443 on the + default edge). + ## Dev images To run a component from a build of your own, build the image, and name it diff --git a/internal/config/backstage_test.go b/internal/config/backstage_test.go index a61ce622..a91015fd 100644 --- a/internal/config/backstage_test.go +++ b/internal/config/backstage_test.go @@ -35,3 +35,17 @@ func TestBackstageLocalDevPort(t *testing.T) { } } } + +// TestBackstageLocalDevFrontendURL: the frontend origin of a hot-reload run +// (muster's return allowlist) follows localDevPort being set, and names the +// frontend's port, not the backend's. +func TestBackstageLocalDevFrontendURL(t *testing.T) { + c := Default() + if got := c.BackstageLocalDevFrontendURL(); got != "" { + t.Errorf("default BackstageLocalDevFrontendURL = %q, want none", got) + } + c.Backstage.LocalDevPort = 7099 + if got, want := c.BackstageLocalDevFrontendURL(), "http://localhost:3000"; got != want { + t.Errorf("BackstageLocalDevFrontendURL = %q, want %q", got, want) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 26f32316..ece7da02 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3402,6 +3402,18 @@ func (c *Config) BackstageLocalDevURL() string { return fmt.Sprintf("http://localhost:%d", c.Backstage.LocalDevPort) } +// BackstageLocalDevFrontendURL is where the hot-reload run's frontend serves +// (the page a person's browser is on), "" when no hot-reload run is +// configured (backstage.localDevPort unset). muster's approval page may only +// return the browser to a page on its post-login return allowlist, so the +// lab lists this origin's /sessions there. +func (c *Config) BackstageLocalDevFrontendURL() string { + if c.Backstage.LocalDevPort == 0 { + return "" + } + return fmt.Sprintf("http://localhost:%d", BackstageFrontendPort) +} + func (c *Config) KagentUIBaseURL() string { return fmt.Sprintf("http://localhost:%d", c.Platform.AgentsPort) } diff --git a/internal/lab/backstagedev.go b/internal/lab/backstagedev.go index f4cf912a..0a726f07 100644 --- a/internal/lab/backstagedev.go +++ b/internal/lab/backstagedev.go @@ -16,7 +16,10 @@ import ( "time" "gopkg.in/yaml.v3" + authenticationv1 "k8s.io/api/authentication/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" "github.com/giantswarm/agentlab/internal/config" ) @@ -46,8 +49,19 @@ const ( // urlKey and dbClientKey are app-config keys of the generated overlay. urlKey = "url" dbClientKey = "client" + // portalServiceAccount is the in-cluster portal's ServiceAccount (the + // backstage chart's name), which the platform binds to muster's + // muster-approval-decider; musterWorkloadTokenFile is where the local + // run keeps a token of it for audience muster. + portalServiceAccount = "backstage" + musterWorkloadTokenFile = "muster-workload-token" + musterWorkloadAudience = musterValues ) +// musterWorkloadTokenTTL is how long the local portal's workload token for +// muster lasts: a working day; every `agentlab portal dev` mints a new one. +const musterWorkloadTokenTTL = 12 * time.Hour + // backstageFrontendURL is where `yarn start` serves the frontend, on the port // backstage.localDevPort validation holds free (config.BackstageFrontendPort). var backstageFrontendURL = fmt.Sprintf("http://localhost:%d", config.BackstageFrontendPort) @@ -99,6 +113,7 @@ func BackstageDev(cfg *config.Config, checkout string, port int) error { if err := cfg.Save(); err != nil { return err } + note("muster's approval page returns to this portal only after `agentlab platform` re-renders the platform values (the return allowlist carries %s/sessions)", backstageFrontendURL) } // Always: a recorded localDevPort does not prove Dex was rendered with it // (a hand-edited agentlab.yaml never was). The apply is checksummed, so a @@ -269,7 +284,27 @@ func backstageDevInputs(ctx context.Context, cfg *config.Config) ([]devFile, []s if len(caData) == 0 { return nil, nil, fmt.Errorf("%s carries no cluster CA: the generated app-config cannot pin the apiserver", labKubeconfig()) } - overlay, err := backstageDevOverlay(cfg, k.cfg.Host, caData, users) + // muster takes the portal's inline approval decisions and sign-in + // handoff requests only with the portal backend's own workload token + // beside the person's (muster-approval-decider). The local run stands in + // for the lab's in-cluster portal, so it gets a token of that portal's + // ServiceAccount, minted here (lab only: the lab's admin kubeconfig). + workloadToken := "" + token, err := mintPortalWorkloadToken(ctx, k.clientset) + switch { + case err != nil: + return nil, nil, err + case token == nil: + note("the lab has no ServiceAccount %s/%s: the local portal sends muster no workload token, so approvals open muster's own pages", platformNamespace, portalServiceAccount) + default: + path, err := filepath.Abs(filepath.Join(StateDir, backstageDevDir, musterWorkloadTokenFile)) + if err != nil { + return nil, nil, err + } + files = append(files, devFile{name: musterWorkloadTokenFile, data: token}) + workloadToken = path + } + overlay, err := backstageDevOverlay(cfg, k.cfg.Host, caData, users, workloadToken) if err != nil { return nil, nil, err } @@ -286,14 +321,39 @@ func backstageDevInputs(ctx context.Context, cfg *config.Config) ([]devFile, []s } env = append(env, name+"="+string(value)) } + // The portal's own client's secret, which the chart's app-config names + // while backstage.oidcClientId is set (a chart without it never reads it). + if value := secrets.Data[backstageOIDCKey]; len(value) > 0 { + env = append(env, "AGENT_PLATFORM_PORTAL_OIDC_CLIENT_SECRET="+string(value)) + } return files, env, nil } +// mintPortalWorkloadToken asks the lab for a token of the in-cluster portal's +// ServiceAccount for audience muster (TokenRequest), nil when the lab has no +// such ServiceAccount. +func mintPortalWorkloadToken(ctx context.Context, cs kubernetes.Interface) ([]byte, error) { + ttl := int64(musterWorkloadTokenTTL.Seconds()) + got, err := cs.CoreV1().ServiceAccounts(platformNamespace).CreateToken(ctx, portalServiceAccount, &authenticationv1.TokenRequest{ + Spec: authenticationv1.TokenRequestSpec{Audiences: []string{musterWorkloadAudience}, ExpirationSeconds: &ttl}, + }, metav1.CreateOptions{}) + switch { + case apierrors.IsNotFound(err): + return nil, nil + case err != nil: + return nil, fmt.Errorf("minting the portal's workload token for muster (%s/%s): %w", platformNamespace, portalServiceAccount, err) + case got.Status.Token == "": + return nil, fmt.Errorf("minting the portal's workload token for muster (%s/%s): the API server answered no token", platformNamespace, portalServiceAccount) + } + return []byte(got.Status.Token), nil +} + // backstageDevOverlay is the app-config the local run layers last: the local -// URLs, and every in-cluster address of the chart's app-config swapped for -// the one this machine reaches — the apiserver on its published port, muster -// and the kagent API through the edge. -func backstageDevOverlay(cfg *config.Config, apiserver string, caData []byte, usersFile string) ([]byte, error) { +// URLs, every in-cluster address of the chart's app-config swapped for the +// one this machine reaches — the apiserver on its published port, muster and +// the kagent API through the edge — and, when one was minted, the file of +// the portal's workload token for muster (muster.workloadTokenFile). +func backstageDevOverlay(cfg *config.Config, apiserver string, caData []byte, usersFile, workloadTokenFile string) ([]byte, error) { backend := cfg.BackstageLocalDevURL() overlay := map[string]any{ "app": map[string]any{"baseUrl": backstageFrontendURL}, @@ -329,13 +389,7 @@ func backstageDevOverlay(cfg *config.Config, apiserver string, caData []byte, us }}, }}, }, - musterValues: map[string]any{ - "installations": []any{map[string]any{ - nameKey: platformNamespace, - urlKey: cfg.MusterBaseURL() + "/mcp", - "authProvider": "oidc-agent-platform", - }}, - }, + musterValues: musterOverlay(cfg, workloadTokenFile), "agentPlatform": map[string]any{ "kagent": map[string]any{ "installations": map[string]any{ @@ -351,6 +405,22 @@ func backstageDevOverlay(cfg *config.Config, apiserver string, caData []byte, us return append([]byte("# Generated by `agentlab portal dev` on every start.\n"), raw...), nil } +// musterOverlay is the local portal's muster block: the lab's muster through +// the edge, and the workload token file when there is one. +func musterOverlay(cfg *config.Config, workloadTokenFile string) map[string]any { + muster := map[string]any{ + "installations": []any{map[string]any{ + nameKey: platformNamespace, + urlKey: cfg.MusterBaseURL() + "/mcp", + "authProvider": "oidc-agent-platform", + }}, + } + if workloadTokenFile != "" { + muster["workloadTokenFile"] = workloadTokenFile + } + return muster +} + // BackstageBuild builds the checkout's image as its CI does, records it as // platform.devImages.backstage and, unless noApply, rolls it into the lab. // Every build gets its own tag: kind's containerd keeps running the old bits diff --git a/internal/lab/backstagedev_test.go b/internal/lab/backstagedev_test.go index 194e561e..6139c865 100644 --- a/internal/lab/backstagedev_test.go +++ b/internal/lab/backstagedev_test.go @@ -1,12 +1,19 @@ package lab import ( + "context" "slices" "strings" "testing" "time" "gopkg.in/yaml.v3" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + kubefake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" "github.com/giantswarm/agentlab/internal/config" ) @@ -18,7 +25,7 @@ func TestBackstageDevOverlay(t *testing.T) { cfg := config.Default() cfg.Platform.GatewayPort = 8443 cfg.Backstage.LocalDevPort = 7017 - raw, err := backstageDevOverlay(cfg, "https://127.0.0.1:6443", []byte("ca"), "/lab/state/backstage-dev/users.yaml") + raw, err := backstageDevOverlay(cfg, "https://127.0.0.1:6443", []byte("ca"), "/lab/state/backstage-dev/users.yaml", "/lab/state/backstage-dev/muster-workload-token") if err != nil { t.Fatal(err) } @@ -43,7 +50,8 @@ func TestBackstageDevOverlay(t *testing.T) { } `yaml:"clusterLocatorMethods"` } Muster struct { - Installations []struct{ URL string } + Installations []struct{ URL string } + WorkloadTokenFile string `yaml:"workloadTokenFile"` } AgentPlatform struct { Kagent struct { @@ -64,6 +72,7 @@ func TestBackstageDevOverlay(t *testing.T) { "apiserver": {got.Kubernetes.ClusterLocatorMethods[0].Clusters[0].URL, "https://127.0.0.1:6443"}, "apiserver caData": {got.Kubernetes.ClusterLocatorMethods[0].Clusters[0].CAData, "Y2E="}, "muster url": {got.Muster.Installations[0].URL, "https://muster.127.0.0.1.nip.io:8443/mcp"}, + "muster workload": {got.Muster.WorkloadTokenFile, "/lab/state/backstage-dev/muster-workload-token"}, "kagent api": {got.AgentPlatform.Kagent.Installations[platformNamespace].APIBaseURL, "https://agentgateway.127.0.0.1.nip.io:8443"}, } for name, c := range checks { @@ -171,3 +180,35 @@ func TestBackstageImageBuild(t *testing.T) { t.Errorf("podman build = %s, want it unlabelled", got) } } + +// TestMintPortalWorkloadToken pins the local portal's workload token for +// muster: a TokenRequest for the in-cluster portal's ServiceAccount, audience +// muster, a working day; none (and no error) where the lab has no portal. +func TestMintPortalWorkloadToken(t *testing.T) { + cs := kubefake.NewClientset(&corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: platformNamespace, Name: portalServiceAccount}}) + var asked *authenticationv1.TokenRequest + cs.PrependReactor("create", "serviceaccounts", func(action k8stesting.Action) (bool, runtime.Object, error) { + if action.GetSubresource() != "token" { + return false, nil, nil + } + asked = action.(k8stesting.CreateAction).GetObject().(*authenticationv1.TokenRequest) + answer := asked.DeepCopy() + answer.Status.Token = "lab-portal-token" + return true, answer, nil + }) + token, err := mintPortalWorkloadToken(context.Background(), cs) + if err != nil { + t.Fatal(err) + } + if string(token) != "lab-portal-token" { + t.Errorf("token = %q", token) + } + if asked == nil || !slices.Equal(asked.Spec.Audiences, []string{musterWorkloadAudience}) || asked.Spec.ExpirationSeconds == nil || *asked.Spec.ExpirationSeconds != 12*3600 { + t.Errorf("asked %+v, want audience muster for 12h", asked) + } + + none, err := mintPortalWorkloadToken(context.Background(), kubefake.NewClientset()) + if err != nil || none != nil { + t.Errorf("without the portal's ServiceAccount: token %q, err %v; want none and no error", none, err) + } +} diff --git a/internal/lab/templates/agent-platform-values.yaml.tmpl b/internal/lab/templates/agent-platform-values.yaml.tmpl index 08834045..7b4ecc33 100644 --- a/internal/lab/templates/agent-platform-values.yaml.tmpl +++ b/internal/lab/templates/agent-platform-values.yaml.tmpl @@ -595,6 +595,17 @@ muster: mcpClient: enabled: true publicUrl: "{{ .MusterBaseURL }}" +{{- with .BackstageLocalDevFrontendURL }} + # Lab only: a Backstage run with hot reload (`agentlab portal dev`, + # backstage.localDevPort) serves the frontend on http://localhost, not + # on the edge, so muster's approval page would refuse to return the + # browser to it ("Ignoring a return not in ...postLoginRedirectAllowlist") + # and the chat would not continue. The meta chart keeps an own list's + # entries and adds the portal's edge /sessions (backstage.publicPort) + # to it. + postLoginRedirectAllowlist: + - {{ . }}/sessions +{{- end }} server: enabled: true # The public URL through the edge: what Claude Code dials, and what