diff --git a/CLAUDE.md b/CLAUDE.md index 9ef8eaa..a311ae7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,7 +44,9 @@ Read the ADRs, `README.md` and `docs/spec.html` before changing behaviour. never let `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_IDENTITY_TOKEN` or `ANTHROPIC_PROFILE` stay set: they outrank federation and silently shadow it. The ids are not secrets but are still - flags. + flags. An actor on Agent Substrate uses federation only with + `--anthropic-identity-token-from-core`: its identity token is one the + core signs for it, asked at every exchange, never a file or a variable. - **The connector is the boundary.** The prompt is best effort. A cluster is reached only through a connector, whose tools are offered by exact name. By default the core's tools are allowed by name (`tools.CoreTools`) and the diff --git a/cmd/tria-spot/main.go b/cmd/tria-spot/main.go index 13ce0a4..f530553 100644 --- a/cmd/tria-spot/main.go +++ b/cmd/tria-spot/main.go @@ -18,6 +18,7 @@ import ( "os" "os/signal" "strings" + "sync/atomic" "syscall" "time" @@ -82,7 +83,16 @@ func supervise(cfg config.Config, errOut io.Writer) int { return 1 } - model, err := newModel(ctx, cfg, log) + // The link is made after the model client, and the client asks for the + // identity token only at its first exchange: the holder is filled then. + var identityFrom atomic.Pointer[triggers.Link] + model, err := newModel(ctx, cfg, log, func(ctx context.Context) (string, error) { + l := identityFrom.Load() + if l == nil { + return "", errors.New("identity token: this process has no link to the core (a task actor has none)") + } + return l.IdentityToken(ctx) + }) if err != nil { log.Error("model client", "err", err) return 1 @@ -192,6 +202,7 @@ func supervise(cfg config.Config, errOut io.Writer) int { } if l, ok := tc.(*triggers.Link); ok { link = l + identityFrom.Store(l) // The server listens at once and the link starts with the core's first // request, which the process then waits for. shutdown, err := serve(cfg.Listen, l.Handler(), log) @@ -288,7 +299,7 @@ func supervise(cfg config.Config, errOut io.Writer) int { // newModel builds the model client for the configured provider and auth mode. // It fails at once on a key file it cannot read or a mode with missing ids. -func newModel(ctx context.Context, cfg config.Config, log *slog.Logger) (llm.Client, error) { +func newModel(ctx context.Context, cfg config.Config, log *slog.Logger, identityToken func(context.Context) (string, error)) (llm.Client, error) { log.Info("model", "provider", cfg.LLMProvider, "id", cfg.Model, "effort", cfg.Effort, "maxSteps", cfg.MaxSteps, "maxToolCalls", cfg.MaxToolCalls, "maxTurnTokens", cfg.MaxTurnTokens) if cfg.LLMProvider == config.ProviderGemini { o := llm.GeminiOptions{Auth: cfg.LLMAuth, Model: cfg.Model, KeyFile: cfg.GeminiKeyFile} @@ -308,6 +319,11 @@ func newModel(ctx context.Context, cfg config.Config, log *slog.Logger) (llm.Cli RuleID: cfg.FederationRuleID, OrganizationID: cfg.AnthropicOrgID, ServiceAccountID: cfg.AnthropicServiceAcctID, WorkspaceID: cfg.AnthropicWorkspaceID, IdentityTokenFile: cfg.IdentityTokenFile, } + if cfg.IdentityTokenFromCore { + o.Federation.IdentityToken = identityToken + log.Info("model auth: Anthropic workload identity federation with an identity token the core signs", "rule", cfg.FederationRuleID, "serviceAccount", cfg.AnthropicServiceAcctID) + break + } // The kubelet projects the token; absent here only means it is not mounted yet. if _, err := os.Stat(cfg.IdentityTokenFile); err != nil { log.Warn("identity token file is not readable yet; the first exchange will fail until it is", "err", err) diff --git a/docs/spec.html b/docs/spec.html index eeb9f65..2fe7b21 100644 --- a/docs/spec.html +++ b/docs/spec.html @@ -463,9 +463,9 @@

Runtimes

ReportsKept until the supervisor is idle (no turn, no task, nothing waiting), then sent in this order: turns, stats, the wake reports last. The core may suspend the actor once it has the wake report, so nothing follows it. A frame that made no wake (the rooms had nothing new) is answered with {"wake":{"reason":"rooms","lane":"long","outcome":"idle"}}, which ends the outstanding wake and leaves the stored plan. The schedule frame follows hello only when the process holds a plan, because one without would replace the core’s. What survives/state, the actor’s durable directory: the usage ledger, the room cursors and read marks, the digest, the promises, the identity, and window.json: the tokens of the last hour (the hourly ceiling), the early wakes of the last hour (their cap), the issue state edges are told against and the plan the last wake left (the core holds it; an actor that reports a promise without having run a wake says it back). Held edges do not survive a suspension, so --edge-cooldown and --chat-batch are 0 in this runtime and the next tick reads whatever a cap left. Task actor--task-actor makes a process an actor the core made for one piece of work that Tria asked for (the core’s ADR-109). It never joins: no certificate, no hello, no schedule, no rooms to poll, no lanes. It is an A2A agent (Agent2Agent protocol 0.3, a2a-go v0.3.15) and the core is its client; it serves, on --listen, GET /readyz (the substrate’s probe), GET /.well-known/agent-card.json and the JSON-RPC endpoint at / (message/send, tasks/get, tasks/cancel; every other method is refused). The card is static and names no workspace, spot or core: url /, preferredTransport JSONRPC, protocolVersion 0.3.0, push notifications on, streaming off, an http bearer security scheme and one required extension, https://triageagent.dev/a2a/spot-task/v1. The core sends one message/send with Authorization: Bearer <task token>: one text part (the goal), contextId the task key, metadata triage.workspace, triage.task.key, triage.task.title and triage.task.replyTo, and a pushNotificationConfig (the core’s receiver, the key as its token, the task token as its bearer). The actor has no setting of its own and cannot verify the core’s signature, so before it acts it confirms the task with the core: GET /v2/messenger/spot/link/tasks/{key} with the message’s bearer, answered {key, goal, title, replyTo}. On 401, 403 or 404 the A2A task ends rejected and the actor stays free for the next message; it also ends rejected when the message has no bearer, the key is not the core’s, the message’s text differs from the core’s goal (after trimming), or triage.workspace is not the workspace the actor was made for (--tenant). A second message, while the task runs or after it ended, is answered rejected (one task per actor). The message must also carry a push notification configuration whose URL has the scheme and host:port of --core-api-url (the path may differ), otherwise it ends rejected before the core is asked, and the actor never posts to any other URL; tasks/get and tasks/cancel are for the task’s own bearer, or one the core confirms for the task (the core keeps no task token and mints a fresh one for the same task; the actor asks GET /v2/messenger/spot/link/tasks/{key} with it, once, within 5 s, and remembers it when the core answers 200 with the task’s key). The bearer is written to --core-token-file (outside the state directory) and is the task’s credential for its tools and its confirmation, for this task only: the core refuses it on hello, stats, schedule, control answers and any other workspace. One turn runs the goal (the task prompt, the usual caps, schedule_next and start_task refused, calls to the core always with the workspace of the token, the room bus only). The supervisor then writes the result as one memory item (upsert_memory_item, kind note, scope global, subject the task key, title the core’s title, tags task,spot:<name>) and posts one line in the bus (say_in_workspace, reply_to the request, memory the item’s id; the line is the result in one line of 300 bytes at most). A failed task is a result like any other (failed: …), and a note that cannot be saved is said in the line. The actor then flushes its spans and ends the A2A task completed (failed when the run failed) with one artifact holding a data part {"memory": <item id>, "line": <the bus line>}. The core learns the end from the push notification the SDK’s sender posts to the configuration in the message (Authorization: Bearer <task token>, X-A2A-Notification-Token: <key>) at every state; the actor sends no wake report. tasks/cancel with the task’s bearer stops the turn at its next step, as an operator’s stop does for a task of a deployment spot, and ends the task canceled; another bearer cannot cancel it. The process keeps waiting for the core to end the actor. Spots and task actors report to memory and the bus, never to ego. - Model--llm-auth injected: the Anthropic client sends a fixed placeholder x-api-key to https://api.anthropic.com (or --llm-base-url) and the environment is not read. The egress policy of the actor has a rule for that host whose effect replaces the header with the key of a Secret (ate-secret://…), and only a request that carries the header is changed; the spot never holds the key. Anthropic provider only. The other auth modes stay for the deployment runtime. + Model--llm-auth injected: the Anthropic client sends a fixed placeholder x-api-key to https://api.anthropic.com (or --llm-base-url) and the environment is not read. The egress policy of the actor has a rule for that host whose effect replaces the header with the key of a Secret (ate-secret://…), and only a request that carries the header is changed; the spot never holds the key. Anthropic provider only. Or --llm-auth federation with --anthropic-identity-token-from-core, which needs no key anywhere: at every exchange the spot asks the core for an identity token (GET /v2/messenger/spot/link/identity-token with its access token from hello), a short-lived JWT the core signs that says which spot of which workspace it is, and exchanges it at Anthropic for a short-lived access token it keeps in memory. The core signs one only for the audiences its policy names (spots.identity), and Anthropic checks it with the core's public keys, so one federation rule serves every spot. A task actor has no link and cannot use this mode. The key, vertex and file-token modes stay for the deployment runtime. TLSAn https rule is intercepted by the egress gateway, which mints its certificates from its own CA. The template mounts a systemInfo volume with the trust bundle (egress-mitm.ate.dev and system-roots.ate.dev) at /run/ate/egress-trust-bundle and sets SSL_CERT_FILE to it, the one environment variable of the container and no credential. In-cluster names must be fully qualified (….svc.cluster.local): the DNS relay forwards the name as asked, and no search domain completes it. - No credentialThe actor holds no model key, no token file and no enrollment key, and mounts no Secret or ConfigMap: connectors are given inline (--connectors-json), what ego checks on a request is put there by the egress policy, and the one-time enrollment key a spot needs for its first join (the core refuses a spot without one) is put on the join request by the egress too: the spot sends X-Triage-Enroll-Key with a placeholder (--enroll-key-injected) and the policy replaces it from a Secret. The one thing the actor keeps is its own key and certificate on /state. + No credentialThe actor holds no model key, no token file and no enrollment key (with federation it holds, in memory and for minutes, the identity token the core signed and the access token that bought), and mounts no Secret or ConfigMap: connectors are given inline (--connectors-json), what ego checks on a request is put there by the egress policy, and the one-time enrollment key a spot needs for its first join (the core refuses a spot without one) is put on the join request by the egress too: the spot sends X-Triage-Enroll-Key with a placeholder (--enroll-key-injected) and the policy replaces it from a Secret. The one thing the actor keeps is its own key and certificate on /state. InstallThe manifests in deploy/substrate/ (one ActorTemplate and one EgressPolicy, with <placeholders>) are applied with the substrate CLI: kubectl ate create actor-template -f, create actor <actor-name> -a <atespace> --template <atespace>/<template-name>, create egress-policy <actor-name> -a <atespace> -f. The actor name is the core’s (it returns it with the spot key). The template names the image by digest, the flags, /state as a durable directory, the wake-up probe, the volume snapshot and the limits. The policy has one rule per destination the spot uses, the one for the model API replacing x-api-key with the key of a Secret (http for in-cluster names, https for the rest, hostnames only). The Helm chart installs the deployment runtime only. @@ -625,7 +625,8 @@

Model

--llm-base-urlemptyinjected: the API’s URL when it is not https://api.anthropic.com; only with --llm-auth=injected --anthropic-key-filerequired with anthropic and keyAnthropic API key file; rejected with the others --gemini-key-filerequired with gemini and keyGemini API key file; rejected with the others - --anthropic-identity-token-filerequired with federationprojected identity token (JWT) + --anthropic-identity-token-filerequired with federation, unless the token comes from the coreprojected identity token (JWT) + --anthropic-identity-token-from-corefalsefederation with --runtime=substrate: the identity token is one the core signs for the spot at every exchange; in place of the file --anthropic-federation-rule-idrequired with federationfederation rule id (fdrl_...) --anthropic-org-idrequired with federationAnthropic organization id --anthropic-service-account-idrequired with federationAnthropic service account id (svac_...) @@ -683,7 +684,7 @@

Telemetry and logs

08

Credentials

-

--llm-auth picks the model auth mode; federation and injected are Anthropic only. With injected the spot holds no key: it sends a placeholder, and the egress in front of the API replaces it with the real one. Federation ids are not secrets, but they are flags.

+

--llm-auth picks the model auth mode; federation and injected are Anthropic only. With injected the spot holds no key: it sends a placeholder, and the egress in front of the API replaces it with the real one. A substrate actor takes injected, or federation with --anthropic-identity-token-from-core (section 8). Federation ids are not secrets, but they are flags.

diff --git a/docs/spec.md b/docs/spec.md index 2920065..84b6b11 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -104,9 +104,9 @@ The core keeps the spot’s schedule (the core’s ADR-106): the spot decides wh | Reports | Kept until the supervisor is idle (no turn, no task, nothing waiting), then sent in this order: turns, stats, the wake reports last. The core may suspend the actor once it has the wake report, so nothing follows it. A frame that made no wake (the rooms had nothing new) is answered with `{"wake":{"reason":"rooms","lane":"long","outcome":"idle"}}`, which ends the outstanding wake and leaves the stored plan. The `schedule` frame follows hello only when the process holds a plan, because one without would replace the core’s. | | What survives | `/state`, the actor’s durable directory: the usage ledger, the room cursors and read marks, the digest, the promises, the identity, and `window.json`: the tokens of the last hour (the hourly ceiling), the early wakes of the last hour (their cap), the issue state edges are told against and the plan the last wake left (the core holds it; an actor that reports a promise without having run a wake says it back). Held edges do not survive a suspension, so `--edge-cooldown` and `--chat-batch` are 0 in this runtime and the next tick reads whatever a cap left. | | Task actor | `--task-actor` makes a process an actor the core made for one piece of work that Tria asked for (the core’s ADR-109). It never joins: no certificate, no hello, no schedule, no rooms to poll, no lanes. It is an A2A agent (Agent2Agent protocol 0.3, `a2a-go` v0.3.15) and the core is its client; it serves, on `--listen`, `GET /readyz` (the substrate’s probe), `GET /.well-known/agent-card.json` and the JSON-RPC endpoint at `/` (`message/send`, `tasks/get`, `tasks/cancel`; every other method is refused). The card is static and names no workspace, spot or core: `url` `/`, `preferredTransport` `JSONRPC`, `protocolVersion` `0.3.0`, push notifications on, streaming off, an `http` `bearer` security scheme and one required extension, `https://triageagent.dev/a2a/spot-task/v1`. The core sends one `message/send` with `Authorization: Bearer `: one text part (the goal), `contextId` the task key, `metadata` `triage.workspace`, `triage.task.key`, `triage.task.title` and `triage.task.replyTo`, and a `pushNotificationConfig` (the core’s receiver, the key as its token, the task token as its bearer). The actor has no setting of its own and cannot verify the core’s signature, so before it acts it confirms the task with the core: `GET /v2/messenger/spot/link/tasks/{key}` with the message’s bearer, answered `{key, goal, title, replyTo}`. The confirmation comes first, before the SDK records a task for the message: a message with no bearer, one that names no task, one whose push notification configuration is not the core’s callback for that task (`<--core-api-url>/v2/messenger/spot/link/tasks/{key}/events`, exactly), one the core answers 401, 403 or 404 for, and a second message while the task runs or after it ended (one task per actor) are answered with a JSON-RPC error: no task is made, nothing is read, run or pushed for them, and the actor stays free for the real one. A message the core confirms whose key is not the core’s, whose text differs from the core’s goal (after trimming), or whose `triage.workspace` is not the workspace the actor was made for (`--tenant`) ends its A2A task `rejected`. The actor posts to the callback of the task it recorded and to no other URL, with a client that follows no redirect; `tasks/get` and `tasks/cancel` are for the task’s own bearer, or one the core confirms for the task (the core keeps no task token and mints a fresh one for the same task; the actor asks `GET /v2/messenger/spot/link/tasks/{key}` with it, once, within 5 s, and remembers it when the core answers 200 with the task’s key). The bearer is written to `--core-token-file` (outside the state directory) and is the task’s credential for its tools and its confirmation, for this task only: the core refuses it on hello, stats, schedule, control answers and any other workspace. At a ceiling (`--daily-token-ceiling`, `--hourly-token-ceiling`) the task does not run, no model call is made, and its line says `not run`. Otherwise one turn runs the goal (the task prompt, with the title and the goal as quoted text, the usual caps, `schedule_next` and `start_task` refused, calls to the core always with the workspace of the token, the room `bus` only). The supervisor then writes the result as one memory item (`upsert_memory_item`, kind `note`, scope `global`, subject the task key, title the core’s title, tags `task,spot:`) and posts one line in the bus (`say_in_workspace`, `reply_to` the request, `memory` the item’s id; the line is the result in one line of 300 bytes at most). A failed task is a result like any other (`failed: …`), and a note that cannot be saved is said in the line. The actor then flushes its spans and ends the A2A task `completed` (`failed` when the run failed) with one artifact holding a data part `{"memory": , "line": , "usage": {"model", "input", "cached", "output", "steps", "toolCalls"}}` (`usage` is absent when nothing ran): the actor sends no turn report, so the artifact is where the core’s books learn what the task cost. The core learns the end from the push notification the SDK’s sender posts to the configuration in the message (`Authorization: Bearer `, `X-A2A-Notification-Token: `) at every state; the actor sends no wake report. `tasks/cancel` with the task’s bearer stops the turn at its next step, as an operator’s stop does for a task of a deployment spot, and ends the task `canceled`; another bearer cannot cancel it. The process keeps waiting for the core to end the actor. Spots and task actors report to memory and the bus, never to ego. | -| Model | `--llm-auth injected`: the Anthropic client sends a fixed placeholder `x-api-key` to `https://api.anthropic.com` (or `--llm-base-url`) and the environment is not read. The egress policy of the actor has a rule for that host whose effect replaces the header with the key of a Secret (`ate-secret://…`), and only a request that carries the header is changed; the spot never holds the key. Anthropic provider only. The other auth modes stay for the deployment runtime. | +| Model | `--llm-auth injected`: the Anthropic client sends a fixed placeholder `x-api-key` to `https://api.anthropic.com` (or `--llm-base-url`) and the environment is not read. The egress policy of the actor has a rule for that host whose effect replaces the header with the key of a Secret (`ate-secret://…`), and only a request that carries the header is changed; the spot never holds the key. Anthropic provider only. Or `--llm-auth federation` with `--anthropic-identity-token-from-core`, which needs no key anywhere: at every exchange the spot asks the core for an identity token (`GET /v2/messenger/spot/link/identity-token` with its access token from hello), a short-lived JWT the core signs that says which spot of which workspace it is, and exchanges it at Anthropic for a short-lived access token it keeps in memory. The core signs one only for the audiences its policy names (`spots.identity`), and Anthropic checks it with the core's public keys, so one federation rule serves every spot. A task actor has no link and cannot use this mode. The key, vertex and file-token modes stay for the deployment runtime. | | TLS | An `https` rule is intercepted by the egress gateway, which mints its certificates from its own CA. The template mounts a `systemInfo` volume with the trust bundle (`egress-mitm.ate.dev` and `system-roots.ate.dev`) at `/run/ate/egress-trust-bundle` and sets `SSL_CERT_FILE` to it, the one environment variable of the container and no credential. In-cluster names must be fully qualified (`….svc.cluster.local`): the DNS relay forwards the name as asked, and no search domain completes it. | -| No credential | The actor holds no model key, no token file and no enrollment key, and mounts no Secret or ConfigMap: connectors are given inline (`--connectors-json`), what ego checks on a request is put there by the egress policy, and the one-time enrollment key a spot needs for its first join (the core refuses a spot without one) is put on the join request by the egress too: the spot sends `X-Triage-Enroll-Key` with a placeholder (`--enroll-key-injected`) and the policy replaces it from a Secret. The one thing the actor keeps is its own key and certificate on `/state`. | +| No credential | The actor holds no model key, no token file and no enrollment key (with federation it holds, in memory and for minutes, the identity token the core signed and the access token that bought), and mounts no Secret or ConfigMap: connectors are given inline (`--connectors-json`), what ego checks on a request is put there by the egress policy, and the one-time enrollment key a spot needs for its first join (the core refuses a spot without one) is put on the join request by the egress too: the spot sends `X-Triage-Enroll-Key` with a placeholder (`--enroll-key-injected`) and the policy replaces it from a Secret. The one thing the actor keeps is its own key and certificate on `/state`. | | Install | The manifests in `deploy/substrate/` (one ActorTemplate and one EgressPolicy, with ``) are applied with the substrate CLI: `kubectl ate create actor-template -f`, `create actor -a --template /`, `create egress-policy -a -f`. The actor name is the core’s (it returns it with the spot key). The template names the image by digest, the flags, `/state` as a durable directory, the wake-up probe, the volume snapshot and the limits. The policy has one rule per destination the spot uses, the one for the model API replacing `x-api-key` with the key of a Secret (http for in-cluster names, https for the rest, hostnames only). The Helm chart installs the deployment runtime only. | ## The model @@ -232,7 +232,8 @@ Flags only. No credential is a flag value or an environment variable. `tria-spot | `--llm-base-url` | empty | injected: the API’s URL when it is not `https://api.anthropic.com`; only with `--llm-auth=injected` | | `--anthropic-key-file` | required with anthropic and key | Anthropic API key file; rejected with the others | | `--gemini-key-file` | required with gemini and key | Gemini API key file; rejected with the others | -| `--anthropic-identity-token-file` | required with federation | projected identity token (JWT) | +| `--anthropic-identity-token-file` | required with federation, unless the token comes from the core | projected identity token (JWT) | +| `--anthropic-identity-token-from-core` | `false` | federation with `--runtime=substrate`: the identity token is one the core signs for the spot at every exchange; in place of the file | | `--anthropic-federation-rule-id` | required with federation | federation rule id (`fdrl_...`) | | `--anthropic-org-id` | required with federation | Anthropic organization id | | `--anthropic-service-account-id` | required with federation | Anthropic service account id (`svac_...`) | @@ -291,7 +292,7 @@ Flags only. No credential is a flag value or an environment variable. `tria-spot ## Credentials -`--llm-auth` picks the model auth mode; `federation` and `injected` are Anthropic only. With `injected` the spot holds no key: it sends a placeholder, and the egress in front of the API replaces it with the real one. Federation ids are not secrets, but they are flags. +`--llm-auth` picks the model auth mode; `federation` and `injected` are Anthropic only. With `injected` the spot holds no key: it sends a placeholder, and the egress in front of the API replaces it with the real one. A substrate actor takes `injected`, or `federation` with `--anthropic-identity-token-from-core` (section 8). Federation ids are not secrets, but they are flags. *Diagram: Credentials: each Secret or projected token becomes a file in the pod or an identity binding, and one client reads each; connector credentials are not in the pod at all.* diff --git a/internal/config/config.go b/internal/config/config.go index 1eb3c3b..369a678 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -76,10 +76,14 @@ type Config struct { // a projected identity token is exchanged for a short-lived access token; // Anthropic only) or "vertex" (Claude or Gemini on Google Vertex AI through // the pod's Workload Identity). The ids are not secrets. - LLMAuth string - AnthropicKeyFile string - GeminiKeyFile string - IdentityTokenFile string + LLMAuth string + AnthropicKeyFile string + GeminiKeyFile string + IdentityTokenFile string + // IdentityTokenFromCore makes the identity token of federation one the + // core signs for this spot, asked over the link at every exchange (the + // core's ADR-123); only with --runtime=substrate, in place of the file. + IdentityTokenFromCore bool FederationRuleID string AnthropicOrgID string AnthropicServiceAcctID string @@ -244,6 +248,7 @@ func Parse(args []string, out io.Writer) (Config, error) { fs.StringVar(&c.AnthropicKeyFile, "anthropic-key-file", "", "file holding the Anthropic API key (required with --llm-provider=anthropic --llm-auth=key, rejected otherwise)") fs.StringVar(&c.GeminiKeyFile, "gemini-key-file", "", "file holding the Gemini API key, re-read on every request (required with --llm-provider=gemini --llm-auth=key, rejected otherwise)") fs.StringVar(&c.IdentityTokenFile, "anthropic-identity-token-file", "", "federation: file holding the projected identity token (JWT), re-read on every exchange") + fs.BoolVar(&c.IdentityTokenFromCore, "anthropic-identity-token-from-core", false, "federation on substrate: the identity token is one the core signs for this spot at every exchange (the core's policy spots.identity); in place of --anthropic-identity-token-file") fs.StringVar(&c.FederationRuleID, "anthropic-federation-rule-id", "", "federation: the federation rule id (fdrl_...)") fs.StringVar(&c.AnthropicOrgID, "anthropic-org-id", "", "federation: the Anthropic organization id") fs.StringVar(&c.AnthropicServiceAcctID, "anthropic-service-account-id", "", "federation: the Anthropic service account id (svac_...)") @@ -362,8 +367,8 @@ func (c Config) validateRuntime() []error { return nil case RuntimeSubstrate: var errs []error - if c.LLMAuth != AuthInjected { - errs = append(errs, errors.New("--runtime=substrate needs --llm-auth=injected: an actor holds no model credential")) + if c.LLMAuth != AuthInjected && (c.LLMAuth != AuthFederation || !c.IdentityTokenFromCore) { + errs = append(errs, errors.New("--runtime=substrate needs --llm-auth=injected, or --llm-auth=federation with --anthropic-identity-token-from-core: an actor holds no model credential")) } if c.CoreCAFingerprint == "" && !c.TaskActor() { errs = append(errs, errors.New("--runtime=substrate needs --core-ca-fingerprint: an actor joins the core by certificate")) @@ -504,6 +509,9 @@ func (c *Config) Validate() error { } } } + if c.IdentityTokenFromCore && (c.LLMProvider != ProviderAnthropic || c.LLMAuth != AuthFederation) { + errs = append(errs, errors.New("--anthropic-identity-token-from-core only applies with --llm-provider=anthropic --llm-auth=federation")) + } switch c.LLMProvider { case ProviderAnthropic: if c.GeminiKeyFile != "" { @@ -519,7 +527,14 @@ func (c *Config) Validate() error { errs = append(errs, errors.New("--anthropic-key-file must not be given with --llm-auth=federation: the key would shadow federation")) } only(AuthVertex, map[string]string{"vertex-project": c.VertexProject}) - req(c.IdentityTokenFile, "anthropic-identity-token-file") + switch { + case c.IdentityTokenFromCore && c.IdentityTokenFile != "": + errs = append(errs, errors.New("--anthropic-identity-token-from-core and --anthropic-identity-token-file are two sources of one token: give one")) + case c.IdentityTokenFromCore && c.Runtime != RuntimeSubstrate: + errs = append(errs, errors.New("--anthropic-identity-token-from-core only applies with --runtime=substrate: the token is asked over the actor's link")) + case !c.IdentityTokenFromCore: + req(c.IdentityTokenFile, "anthropic-identity-token-file") + } req(c.FederationRuleID, "anthropic-federation-rule-id") req(c.AnthropicOrgID, "anthropic-org-id") req(c.AnthropicServiceAcctID, "anthropic-service-account-id") diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 028cf9f..db9a814 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -527,3 +527,25 @@ func TestAnInjectedTelemetryTokenIsForTheSubstrateRuntimeAndNeedsNoFile(t *testi t.Error("a deployment cannot have its token injected") } } + +// An actor may use federation only with the identity token the core signs, +// by the core: it has no projected token file. +func TestSubstrateRuntimeTakesFederationWithTheActorsToken(t *testing.T) { + ids := []string{"--llm-auth", "federation", "--anthropic-federation-rule-id", "fdrl_example", + "--anthropic-org-id", "00000000-0000-0000-0000-000000000000", "--anthropic-service-account-id", "svac_example"} + c, err := Parse(with(with(substrateArgs, ids...), "--anthropic-identity-token-from-core"), io.Discard) + if err != nil || !c.IdentityTokenFromCore || c.LLMAuth != AuthFederation { + t.Fatalf("%+v %v", c, err) + } + for name, args := range map[string][]string{ + "federation with no token source": with(substrateArgs, ids...), + "federation with a token file": with(with(substrateArgs, ids...), "--anthropic-identity-token-file", "/t"), + "both sources": with(with(substrateArgs, ids...), "--anthropic-identity-token-from-core", "--anthropic-identity-token-file", "/t"), + "the actor's token with a key": with(substrateArgs, "--anthropic-identity-token-from-core"), + "the actor's token outside an actor": with(with(required, ids...), "--anthropic-identity-token-from-core"), + } { + if _, err := Parse(args, io.Discard); err == nil { + t.Errorf("%s was accepted", name) + } + } +} diff --git a/internal/llm/anthropic.go b/internal/llm/anthropic.go index 3d6ada2..c940d8c 100644 --- a/internal/llm/anthropic.go +++ b/internal/llm/anthropic.go @@ -43,6 +43,10 @@ type Federation struct { ServiceAccountID string WorkspaceID string // optional when the rule spans one workspace IdentityTokenFile string + // IdentityToken, when set, gives the identity token in place of the file: + // it is called at every exchange. An actor on Agent Substrate uses it, with + // the token the core signs for the spot. + IdentityToken func(context.Context) (string, error) } // Options configure NewAnthropic. @@ -112,6 +116,23 @@ func NewAnthropic(ctx context.Context, o Options) (*Anthropic, error) { // credential or the host. opts = append(opts, option.WithoutEnvironmentDefaults(), option.WithAPIKey(key)) case AuthFederation: + if o.Federation.IdentityToken != nil { + f := o.Federation + for name, v := range map[string]string{"rule id": f.RuleID, "organization id": f.OrganizationID, "service account id": f.ServiceAccountID} { + if strings.TrimSpace(v) == "" { + return nil, fmt.Errorf("llm: federation needs the %s", name) + } + } + // Nothing from the environment: the ids and the token source are + // given here, and a stray ANTHROPIC_* variable must not replace them. + opts = append(opts, option.WithoutEnvironmentDefaults(), option.WithFederationTokenProvider(option.IdentityTokenFunc(f.IdentityToken), option.FederationOptions{ + FederationRuleID: f.RuleID, OrganizationID: f.OrganizationID, ServiceAccountID: f.ServiceAccountID, WorkspaceID: f.WorkspaceID, + })) + if o.BaseURL == "" { + opts = append(opts, option.WithBaseURL(anthropicAPIURL)) + } + break + } if err := setFederationEnv(o.Federation); err != nil { return nil, err } diff --git a/internal/llm/llm_test.go b/internal/llm/llm_test.go index 0aa124f..e16c3b8 100644 --- a/internal/llm/llm_test.go +++ b/internal/llm/llm_test.go @@ -379,3 +379,48 @@ func TestInjectedAuthPinsTheAPIHostWhenNoBaseURLIsGiven(t *testing.T) { t.Errorf("the request went to %s://%s", rec.scheme, rec.host) } } + +// On Agent Substrate the identity token is given by a function (the actor's +// token the core signs for the spot): it is exchanged, and the access token it +// buys is what the request carries. Nothing comes from the environment. +func TestFederationWithATokenSourceExchangesItsToken(t *testing.T) { + t.Setenv("ANTHROPIC_API_KEY", "sk-from-env") + t.Setenv("ANTHROPIC_BASE_URL", "http://elsewhere.invalid") + var exchange map[string]any + var auth, apiKey string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("content-type", "application/json") + if r.URL.Path == "/v1/oauth/token" { + _ = json.NewDecoder(r.Body).Decode(&exchange) + _, _ = io.WriteString(w, `{"access_token":"sk-ant-oat01-test","token_type":"Bearer","expires_in":600,"scope":"workspace:inference"}`) + return + } + auth, apiKey = r.Header.Get("Authorization"), r.Header.Get("X-Api-Key") + _, _ = io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"test-model","stop_reason":"end_turn","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}`) + })) + defer srv.Close() + asked := 0 + a, err := NewAnthropic(context.Background(), Options{Auth: AuthFederation, Model: "test-model", BaseURL: srv.URL, Federation: Federation{ + RuleID: "fdrl_x", OrganizationID: "00000000-0000-0000-0000-000000000000", ServiceAccountID: "svac_x", + IdentityToken: func(context.Context) (string, error) { asked++; return "the.actor.token", nil }, + }}) + if err != nil { + t.Fatal(err) + } + if asked != 0 { + t.Error("the token was asked for before the first request: an actor has no link to the core yet") + } + if _, err := a.Complete(context.Background(), Request{Messages: []Message{UserText("hi")}}); err != nil { + t.Fatal(err) + } + if exchange["assertion"] != "the.actor.token" || exchange["federation_rule_id"] != "fdrl_x" || exchange["service_account_id"] != "svac_x" { + t.Errorf("the exchange: %v", exchange) + } + if auth != "Bearer sk-ant-oat01-test" || apiKey != "" { + t.Errorf("the request: Authorization %q, x-api-key %q", auth, apiKey) + } + if _, err := NewAnthropic(context.Background(), Options{Auth: AuthFederation, Model: "m", Federation: Federation{ + RuleID: "fdrl_x", IdentityToken: func(context.Context) (string, error) { return "", nil }}}); err == nil { + t.Error("a token source without the ids was accepted") + } +} diff --git a/internal/triggers/link.go b/internal/triggers/link.go index 5ead331..2b3454c 100644 --- a/internal/triggers/link.go +++ b/internal/triggers/link.go @@ -283,6 +283,54 @@ func (l *Link) Idle() { var errUnauthorized = errors.New("the core does not accept the access token") +// LinkIdentityTokenPath is where the core signs the spot's identity token: a +// short-lived JWT that says which spot of which workspace this is, for a +// service outside the core that takes workload identity. +const LinkIdentityTokenPath = LinkPath + "/identity-token" + +// IdentityToken returns a new identity token from the core. It is asked for +// at every exchange: a token is good for minutes and is taken once. +func (l *Link) IdentityToken(ctx context.Context) (string, error) { + l.mu.Lock() + tok := l.bearer + l.mu.Unlock() + if tok == "" { + return "", errors.New("identity token: the spot has not said hello to the core yet") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, l.base+LinkIdentityTokenPath, nil) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+tok) + resp, err := l.hc.Do(req) + if err != nil { + return "", fmt.Errorf("identity token: %w", err) + } + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if err != nil { + return "", fmt.Errorf("identity token: %w", err) + } + var out struct { + Token string `json:"token"` + Error string `json:"error"` + } + _ = json.Unmarshal(raw, &out) + switch { + case resp.StatusCode == http.StatusUnauthorized: + select { + case l.reauth <- struct{}{}: + default: + } + return "", fmt.Errorf("identity token: %w", errUnauthorized) + case resp.StatusCode/100 != 2: + return "", fmt.Errorf("identity token: the core answered %s: %s", resp.Status, out.Error) + case out.Token == "": + return "", errors.New("identity token: the core's answer carries none") + } + return out.Token, nil +} + // report posts one report with the access token and takes what the response // carries: the budget, and a new token when this one is half spent. func (l *Link) report(ctx context.Context, body map[string]any) error { diff --git a/internal/triggers/link_test.go b/internal/triggers/link_test.go index dcdae83..e8c389e 100644 --- a/internal/triggers/link_test.go +++ b/internal/triggers/link_test.go @@ -913,3 +913,47 @@ func TestAFreshProcessDoesNotTakeASavedSignedTokenItCannotVerify(t *testing.T) { t.Errorf("the stale token opened the frame: %+v (a bare poke asks for a plain tick)", p) } } + +// The identity token is asked from the core with the access token; the core +// signs one and hands it back. +func TestLinkIdentityToken(t *testing.T) { + var bearer string + answer, status := `{"token":"the.actor.token","expires":1}`, http.StatusOK + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != LinkIdentityTokenPath { + http.NotFound(w, r) + return + } + bearer = r.Header.Get("Authorization") + w.WriteHeader(status) + _, _ = io.WriteString(w, answer) + })) + defer srv.Close() + l := &Link{base: srv.URL, hc: srv.Client(), reauth: make(chan struct{}, 1)} + if _, err := l.IdentityToken(context.Background()); err == nil { + t.Fatal("a spot that has not said hello asked the core") + } + l.bearer = "access" + tok, err := l.IdentityToken(context.Background()) + if err != nil || tok != "the.actor.token" { + t.Fatalf("%q %v", tok, err) + } + if bearer != "Bearer access" { + t.Errorf("the request: Authorization %q", bearer) + } + // the core's policy names no audience for such tokens: it refuses and says why + answer, status = `{"error":"the policy names no issuer and audiences"}`, http.StatusConflict + if _, err := l.IdentityToken(context.Background()); err == nil || !strings.Contains(err.Error(), "no issuer") { + t.Fatalf("a refusal: %v", err) + } + // the access token ended: the link says hello again + answer, status = `{"error":"say hello again"}`, http.StatusUnauthorized + if _, err := l.IdentityToken(context.Background()); !errors.Is(err, errUnauthorized) { + t.Fatalf("an ended access token: %v", err) + } + select { + case <-l.reauth: + default: + t.Error("no new hello was asked for") + } +}