From 179c1c8e8f8964fa08aad10442abb2b4de9e3c4d Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 22 Sep 2026 14:37:58 +1000 Subject: [PATCH] fix(identity): derive the caller the way the provider issues tokens Infra decoded real tokens from both clients, and two of the three facts changed this code. A machine token carries NO sub at all: it names its caller by client_id, and the identity is that client. A person's token carries sub, the provider's stable identifier for the person. The subject is now derived explicitly -- sub when present, else client_id -- and a verified token asserting neither is refused rather than accepted as an anonymous caller, because accepting it would let any token the provider ever signed act as whoever the binding happened to hold. A machine identity is therefore per client registration, one identity per client, which is what makes per-agent identity a configuration decision rather than a code change. Scopes are read from either claim shape. The standard is a space-delimited scope string and this provider also emits an scp array; reading only one shape yields no scopes at all, which is worse than reading none deliberately. The audience-at-authorisation-endpoint trap is pinned by a test: a token minted without the requested audience arrives with aud empty, and the audience check refuses it. That refusal is correct and the fix is the request the human flow builds, not a weaker check here -- a test now fails if anyone weakens it. The PRD records both as constraints: a person's client and an agent's client are registered separately because a shared registration collapses the distinction the attribution rests on, and a person's token requests the audience at the authorisation endpoint as well as the token endpoint. Verified: task check exit 0; internal/infrastructure/oidc passes, including subject derivation for both token shapes and every refusal. --- docs/data/generated/dev-docs.json | 2 +- docs/prds/identity-decision.md | 12 +++ internal/infrastructure/oidc/oidc.go | 47 ++++++++-- internal/infrastructure/oidc/oidc_test.go | 109 +++++++++++++++++++++- 4 files changed, 158 insertions(+), 12 deletions(-) diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index 2cbb9b3d0..1d1700dbe 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -244,7 +244,7 @@ "url": "/dev/prds/identity-decision/", "title": "Identity for users, agents and external agents — decision", "section": "PRDs", - "body": "# Identity for users, agents and external agents — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `docs/architecture/organisation.md` for placement;\n`docs/architecture/migration-decisions.md` §3 for the attribution semantics this\ndocument implements; `docs/prds/agent2agent-protocol.md` for the A2A surface that\nconsumes it.\n\n## Decision\n\nOne identity record covers every actor archie has: users, agents, external agents,\nservice accounts and the system. Authentication is delegated to the estate's OIDC\nprovider, and attribution stays archie's.\n\nAuthentication and authorisation are OSS archie integrates; a design that\nhand-rolls either fails this document.\n\n## The provider\n\n**Authelia is the only identity provider**, because the estate already runs it in\nfront of the dashboard and it issues credentials for both kinds of caller: humans\nuse the authorization code flow, and machines use the `client_credentials` grant,\nwhich yields a token whose subject is the client's own identifier.\n\n**Each agent is its own provider client.** A shared client would make two agents\nindistinguishable in the audit trail and revocable only together, which is the\nproperty attribution needs and the reason per-client registration is a\nrequirement.\n\n**SPIFFE/SPIRE is not adopted.** It is adopted and maintained, and its attestation\nis strictly stronger than a secret: a workload proves what it is rather than what\nit holds. It is rejected here on operational fit, not on quality: it adds a\ncontrol plane archie does not have, and the property it buys — identity attested\nfrom the platform rather than from a presented secret — answers a threat archie\ndoes not face, because archie's agents run as containers the operator launches and\nalready receive their credentials from the daemon that owns them. It is the right\nanswer when agents run on infrastructure the operator does not control.\n\n## What archie owns\n\n- **The identity record.** `internal/domain/identity` survives as archie's own\n record of an actor and is not replaced by the provider's directory, because the\n record carries what the directory does not: the lifecycle, the bindings and the\n attribution below.\n- **The lifecycle.** Active, suspended and retired, with rename, suspend,\n reactivate and retire, remain archie's. Suspending an identity must stop it\n acting whether or not the provider still authenticates it.\n- **The subject binding.** An identity that proves itself is bound to the provider\n subject that asserts it. This is the same bridge `identity_aliases` already\n provides from a legacy name to an identity, so the second binding is the same\n mechanism rather than a new one.\n- **Attribution.** Who acted, and under whose authority.\n- **The audit trail of identity changes**, which already records an actor, a source\n and a request identifier for every mutation.\n\n## What archie never owns\n\nA credential, a password, a session, a token, a signing key, a second-factor\nenrollment, or a permission rule.\n\n## How an agent proves who it is\n\n**An agent authenticates by presenting a token the provider issued to its own\nclient**, and archie validates it against the provider's published signing keys and\ntakes its subject as the acting identity. The agent holds a client secret; archie\nholds only the public keys, so a compromised archie cannot mint an identity.\n\n**A WebMCP tool call is not a proof of agent identity and cannot be made one.** A\npage can invoke its own tools, so an agent's call and a page script's call arrive\nat archie identically. No field, header or convention distinguishes them, because\nthe difference does not exist on the wire.\n\n**A WebMCP tool call is therefore attributed to the identity the request\npresented, with its source recorded as a hint.** It may record that the request\ncame from the dashboard; it never records that an agent acted, and it never\nrecords that a human approved. A tool call that a page script can forge must not\nbe the thing an audit trail rests on.\n\n**Agent-initiated action therefore arrives on a surface that carries a credential**\n— the A2A surface, or an authenticated agent call — because that is the only place\nan agent's identity is verifiable. An approval an agent makes is recorded as an\nagent's action.\n\n## The two attributions\n\nEvery task action records two identities, and `taskactions` gains both:\n\n- **The acting identity**: the identity that performed the action, derived from\n the credential the request presented and never from a string the request\n supplied.\n- **The authorising principal**: the identity whose authority the action used.\n\n**The event kind describes the actor.** An action performed by an agent is\nrecorded as an agent's action even when a human's standing approval permitted it,\nso `KindHumanApproved` is recorded only when the acting identity is a human. An\nagent acting under a standing approval records itself as the actor and the human\nas the authorising principal.\n\n**An action with no authorising principal is recorded as unattributed rather than\nattributed to the actor's own authority.** An agent's own decision and an agent\nexecuting a human's delegation are different facts, and a record that collapsed\nthem would answer the audit question \"approved by whom\" with the wrong identity.\n\n**The review gate's approver is the authorising principal of the approval on that\ntask's action record.** A task parked for a person names that person, not the\nsurface they used.\n\n## External agents\n\n**External agents are first-class, not a special case.** A peer is an identity of\nkind `service_account`, bound to its own provider client, with the same lifecycle\nas any other identity.\n\nThe cost is a provider client per peer, a subject binding, and a client secret\nwhose rotation is the peer's responsibility — and retiring a peer is two\noperations rather than one, because its record and its provider client are retired\nseparately.\n\n**A peer's identity is attributed like any other.** The acting identity is the\npeer; the authorising principal is the identity that delegated to it, so an\nexternal agent acting for a user records both.\n\n## Authorisation is deferred\n\n**No authorisation engine is built, deployed or configured.** The credential's\nscopes are the only permission input, and they are verified by the same provider\nthat issued them, so the interim authorisation is OSS archie does not maintain.\n\n**Two things are not built now**: a policy language, and a decision point that\nanswers per-skill or per-task questions beyond a scope.\n\n**When a caller must be limited to a subset of what a scope permits** — A2A's\nper-skill model, where a peer may invoke some skills and not others — the decision\npoint is added behind a single archie interface that takes a subject, an action and\na resource. The engine behind it is an in-process library or a policy service, and\nthe choice waits for that requirement rather than being made now.\n\n## Verification\n\n- An agent obtains a token from the provider with its own client credentials and\n acts; its identity is recorded as the acting identity.\n- A call with no credential is refused, and a call with an expired or\n wrongly-signed token is refused.\n- A token issued to one agent is not accepted as another agent's identity.\n- A suspended identity cannot act, with a valid provider token.\n- A WebMCP tool call records the presented identity and its source, and never\n records an agent as the actor or a human as the approver.\n- An agent's approval records the agent as the acting identity and the human whose\n authority it used as the authorising principal, and does not record the human as\n the actor.\n- An approval with no authorising principal is recorded as unattributed.\n- No password, session, token, signing key or permission rule exists in archie's\n storage.\n" + "body": "# Identity for users, agents and external agents — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `docs/architecture/organisation.md` for placement;\n`docs/architecture/migration-decisions.md` §3 for the attribution semantics this\ndocument implements; `docs/prds/agent2agent-protocol.md` for the A2A surface that\nconsumes it.\n\n## Decision\n\nOne identity record covers every actor archie has: users, agents, external agents,\nservice accounts and the system. Authentication is delegated to the estate's OIDC\nprovider, and attribution stays archie's.\n\nAuthentication and authorisation are OSS archie integrates; a design that\nhand-rolls either fails this document.\n\n## The provider\n\n**Authelia is the only identity provider**, because the estate already runs it in\nfront of the dashboard and it issues credentials for both kinds of caller: humans\nuse the authorization code flow, and machines use the `client_credentials` grant,\nwhich yields a token whose subject is the client's own identifier.\n\n**Each agent is its own provider client.** A shared client would make two agents\nindistinguishable in the audit trail and revocable only together, which is the\nproperty attribution needs and the reason per-client registration is a\nrequirement.\n\n**A person's client and an agent's client are registered separately**, because the\ntwo token shapes differ and a shared registration would collapse the distinction\nthe attribution rests on. A person's token names them in `sub`. A machine's token\ncarries no `sub` at all and names its client instead, so a machine identity is keyed\non its client registration and exists one per client. A token asserting neither is\nrefused.\n\n**A person's token requests the audience at the authorisation endpoint**, not only\nat the token endpoint. A provider that otherwise returns the audience empty\nproduces a valid token archie must refuse, and that refusal looks like a signing\nfault rather than a missing request parameter.\n\n**SPIFFE/SPIRE is not adopted.** It is adopted and maintained, and its attestation\nis strictly stronger than a secret: a workload proves what it is rather than what\nit holds. It is rejected here on operational fit, not on quality: it adds a\ncontrol plane archie does not have, and the property it buys — identity attested\nfrom the platform rather than from a presented secret — answers a threat archie\ndoes not face, because archie's agents run as containers the operator launches and\nalready receive their credentials from the daemon that owns them. It is the right\nanswer when agents run on infrastructure the operator does not control.\n\n## What archie owns\n\n- **The identity record.** `internal/domain/identity` survives as archie's own\n record of an actor and is not replaced by the provider's directory, because the\n record carries what the directory does not: the lifecycle, the bindings and the\n attribution below.\n- **The lifecycle.** Active, suspended and retired, with rename, suspend,\n reactivate and retire, remain archie's. Suspending an identity must stop it\n acting whether or not the provider still authenticates it.\n- **The subject binding.** An identity that proves itself is bound to the provider\n subject that asserts it. This is the same bridge `identity_aliases` already\n provides from a legacy name to an identity, so the second binding is the same\n mechanism rather than a new one.\n- **Attribution.** Who acted, and under whose authority.\n- **The audit trail of identity changes**, which already records an actor, a source\n and a request identifier for every mutation.\n\n## What archie never owns\n\nA credential, a password, a session, a token, a signing key, a second-factor\nenrollment, or a permission rule.\n\n## How an agent proves who it is\n\n**An agent authenticates by presenting a token the provider issued to its own\nclient**, and archie validates it against the provider's published signing keys and\ntakes its subject as the acting identity. The agent holds a client secret; archie\nholds only the public keys, so a compromised archie cannot mint an identity.\n\n**A WebMCP tool call is not a proof of agent identity and cannot be made one.** A\npage can invoke its own tools, so an agent's call and a page script's call arrive\nat archie identically. No field, header or convention distinguishes them, because\nthe difference does not exist on the wire.\n\n**A WebMCP tool call is therefore attributed to the identity the request\npresented, with its source recorded as a hint.** It may record that the request\ncame from the dashboard; it never records that an agent acted, and it never\nrecords that a human approved. A tool call that a page script can forge must not\nbe the thing an audit trail rests on.\n\n**Agent-initiated action therefore arrives on a surface that carries a credential**\n— the A2A surface, or an authenticated agent call — because that is the only place\nan agent's identity is verifiable. An approval an agent makes is recorded as an\nagent's action.\n\n## The two attributions\n\nEvery task action records two identities, and `taskactions` gains both:\n\n- **The acting identity**: the identity that performed the action, derived from\n the credential the request presented and never from a string the request\n supplied.\n- **The authorising principal**: the identity whose authority the action used.\n\n**The event kind describes the actor.** An action performed by an agent is\nrecorded as an agent's action even when a human's standing approval permitted it,\nso `KindHumanApproved` is recorded only when the acting identity is a human. An\nagent acting under a standing approval records itself as the actor and the human\nas the authorising principal.\n\n**An action with no authorising principal is recorded as unattributed rather than\nattributed to the actor's own authority.** An agent's own decision and an agent\nexecuting a human's delegation are different facts, and a record that collapsed\nthem would answer the audit question \"approved by whom\" with the wrong identity.\n\n**The review gate's approver is the authorising principal of the approval on that\ntask's action record.** A task parked for a person names that person, not the\nsurface they used.\n\n## External agents\n\n**External agents are first-class, not a special case.** A peer is an identity of\nkind `service_account`, bound to its own provider client, with the same lifecycle\nas any other identity.\n\nThe cost is a provider client per peer, a subject binding, and a client secret\nwhose rotation is the peer's responsibility — and retiring a peer is two\noperations rather than one, because its record and its provider client are retired\nseparately.\n\n**A peer's identity is attributed like any other.** The acting identity is the\npeer; the authorising principal is the identity that delegated to it, so an\nexternal agent acting for a user records both.\n\n## Authorisation is deferred\n\n**No authorisation engine is built, deployed or configured.** The credential's\nscopes are the only permission input, and they are verified by the same provider\nthat issued them, so the interim authorisation is OSS archie does not maintain.\n\n**Two things are not built now**: a policy language, and a decision point that\nanswers per-skill or per-task questions beyond a scope.\n\n**When a caller must be limited to a subset of what a scope permits** — A2A's\nper-skill model, where a peer may invoke some skills and not others — the decision\npoint is added behind a single archie interface that takes a subject, an action and\na resource. The engine behind it is an in-process library or a policy service, and\nthe choice waits for that requirement rather than being made now.\n\n## Verification\n\n- An agent obtains a token from the provider with its own client credentials and\n acts; its identity is recorded as the acting identity.\n- A call with no credential is refused, and a call with an expired or\n wrongly-signed token is refused.\n- A token issued to one agent is not accepted as another agent's identity.\n- A suspended identity cannot act, with a valid provider token.\n- A WebMCP tool call records the presented identity and its source, and never\n records an agent as the actor or a human as the approver.\n- An agent's approval records the agent as the acting identity and the human whose\n authority it used as the authorising principal, and does not record the human as\n the actor.\n- An approval with no authorising principal is recorded as unattributed.\n- No password, session, token, signing key or permission rule exists in archie's\n storage.\n" }, { "url": "/dev/prds/image-capability-contract/", diff --git a/docs/prds/identity-decision.md b/docs/prds/identity-decision.md index fd15b4667..123d8101e 100644 --- a/docs/prds/identity-decision.md +++ b/docs/prds/identity-decision.md @@ -28,6 +28,18 @@ indistinguishable in the audit trail and revocable only together, which is the property attribution needs and the reason per-client registration is a requirement. +**A person's client and an agent's client are registered separately**, because the +two token shapes differ and a shared registration would collapse the distinction +the attribution rests on. A person's token names them in `sub`. A machine's token +carries no `sub` at all and names its client instead, so a machine identity is keyed +on its client registration and exists one per client. A token asserting neither is +refused. + +**A person's token requests the audience at the authorisation endpoint**, not only +at the token endpoint. A provider that otherwise returns the audience empty +produces a valid token archie must refuse, and that refusal looks like a signing +fault rather than a missing request parameter. + **SPIFFE/SPIRE is not adopted.** It is adopted and maintained, and its attestation is strictly stronger than a secret: a workload proves what it is rather than what it holds. It is rejected here on operational fit, not on quality: it adds a diff --git a/internal/infrastructure/oidc/oidc.go b/internal/infrastructure/oidc/oidc.go index 2a1e5467e..bb4a0f49b 100644 --- a/internal/infrastructure/oidc/oidc.go +++ b/internal/infrastructure/oidc/oidc.go @@ -57,16 +57,51 @@ func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Creden if err != nil { return identity.Credential{}, fmt.Errorf("oidc: verify: %w", err) } + // Claims are read after verification and are the only source of the + // identity: an unverified token selects nothing. var claims struct { - Scope string `json:"scope"` + Subject string `json:"sub"` + ClientID string `json:"client_id"` + Scope string `json:"scope"` + Scopes []string `json:"scp"` } - // Claims are read after verification and are advisory: the identity comes - // from the verified subject and issuer, never from a claim a caller could - // have written into an unverified token. _ = token.Claims(&claims) + subject, err := subjectFor(token.Issuer, claims.Subject, claims.ClientID) + if err != nil { + return identity.Credential{}, err + } return identity.Credential{ - Subject: identity.Subject{Issuer: token.Issuer, Subject: token.Subject}, - Scopes: strings.Fields(claims.Scope), + Subject: subject, + Scopes: scopesFor(claims.Scope, claims.Scopes), Expires: token.Expiry, }, nil } + +// subjectFor derives the caller a token asserts. +// +// A person's token carries sub, the provider's stable identifier for that person. +// A machine's token carries no sub at all and identifies its caller by client_id, +// so a machine identity is keyed on the client and one identity exists per client +// registration. A token asserting neither identifies nobody and is refused rather +// than being accepted as an anonymous caller. +func subjectFor(issuer, subject, clientID string) (identity.Subject, error) { + switch { + case strings.TrimSpace(subject) != "": + return identity.Subject{Issuer: issuer, Subject: strings.TrimSpace(subject)}, nil + case strings.TrimSpace(clientID) != "": + return identity.Subject{Issuer: issuer, Subject: strings.TrimSpace(clientID)}, nil + default: + return identity.Subject{}, fmt.Errorf("oidc: token asserts neither sub nor client_id") + } +} + +// scopesFor reads the granted scopes from either claim shape. Providers differ: +// the standard is a space-delimited scope string, and this provider also emits an +// scp array. Reading only one shape silently yields no scopes at all, which is +// worse than reading none deliberately. +func scopesFor(scope string, scopes []string) []string { + if len(scopes) > 0 { + return scopes + } + return strings.Fields(scope) +} diff --git a/internal/infrastructure/oidc/oidc_test.go b/internal/infrastructure/oidc/oidc_test.go index d6f790c89..8247ee002 100644 --- a/internal/infrastructure/oidc/oidc_test.go +++ b/internal/infrastructure/oidc/oidc_test.go @@ -7,6 +7,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "slices" "testing" "time" @@ -63,10 +64,18 @@ func newProvider(t *testing.T) *provider { return p } +// testClaims is the claim set this provider emits. A machine token carries +// client_id and no sub; a person's token carries sub. +type testClaims struct { + jwt.Claims + ClientID string `json:"client_id,omitempty"` + Scopes []string `json:"scp,omitempty"` +} + // token signs a token with the given key for the given claims. -func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*jwt.Claims)) string { +func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*testClaims)) string { t.Helper() - claims := jwt.Claims{ + claims := testClaims{ Issuer: p.server.URL, Subject: "sam", Audience: jwt.Audience{testAudience}, @@ -111,6 +120,88 @@ func TestVerifyAcceptsAProviderIssuedToken(t *testing.T) { } } +// TestVerifyDerivesTheSubjectTheWayTheProviderIssuesIt: a person is named by sub +// and a machine by client_id, because a machine token carries no sub at all. +// Getting this wrong does not fail loudly -- it binds every machine caller to one +// identity, or to none. +func TestVerifyDerivesTheSubjectTheWayTheProviderIssuesIt(t *testing.T) { + p := newProvider(t) + verifier := p.verifier(t) + + tests := []struct { + name string + mutate func(*testClaims) + wantSubject string + wantScopes []string + }{ + { + name: "a person's token carries sub", + mutate: func(c *testClaims) { + c.Subject = "a150ab4b-0000-0000-0000-000000000001" + c.Scopes = []string{"openid", "profile", "email", "groups"} + }, + wantSubject: "a150ab4b-0000-0000-0000-000000000001", + wantScopes: []string{"openid", "profile", "email", "groups"}, + }, + { + name: "a machine token carries client_id and no sub", + mutate: func(c *testClaims) { + c.Subject = "" + c.ClientID = "archie" + c.Scopes = []string{"authelia.bearer.authz"} + }, + wantSubject: "archie", + wantScopes: []string{"authelia.bearer.authz"}, + }, + { + name: "sub wins when a token carries both", + mutate: func(c *testClaims) { + c.Subject = "a150ab4b-0000-0000-0000-000000000002" + c.ClientID = "archie-web" + }, + wantSubject: "a150ab4b-0000-0000-0000-000000000002", + }, + { + name: "a space-delimited scope claim is read too", + mutate: func(c *testClaims) { + c.Subject = "a150ab4b-0000-0000-0000-000000000003" + c.ClientID = "" + c.Scopes = nil + }, + wantSubject: "a150ab4b-0000-0000-0000-000000000003", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + credential, err := verifier.Verify(context.Background(), p.token(t, p.key, tc.mutate)) + if err != nil { + t.Fatalf("Verify() error = %v", err) + } + if credential.Subject.Subject != tc.wantSubject { + t.Fatalf("subject = %q, want %q", credential.Subject.Subject, tc.wantSubject) + } + if tc.wantScopes != nil && !slices.Equal(credential.Scopes, tc.wantScopes) { + t.Fatalf("scopes = %v, want %v", credential.Scopes, tc.wantScopes) + } + }) + } +} + +// TestVerifyRefusesATokenThatNamesNobody: a verified token asserting neither sub +// nor client_id is an anonymous caller, and accepting it would let any token the +// provider ever signed act as whoever the binding happened to hold. +func TestVerifyRefusesATokenThatNamesNobody(t *testing.T) { + p := newProvider(t) + token := p.token(t, p.key, func(c *testClaims) { + c.Subject = "" + c.ClientID = "" + }) + if _, err := p.verifier(t).Verify(context.Background(), token); err == nil { + t.Fatal("Verify() accepted a token that asserts no caller") + } +} + func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) { p := newProvider(t) verifier := p.verifier(t) @@ -125,7 +216,7 @@ func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) { }, { name: "expired", - token: p.token(t, p.key, func(c *jwt.Claims) { c.Expiry = jwt.NewNumericDate(time.Now().Add(-time.Hour)) }), + token: p.token(t, p.key, func(c *testClaims) { c.Expiry = jwt.NewNumericDate(time.Now().Add(-time.Hour)) }), }, { name: "signed by a key the provider never published", @@ -133,11 +224,19 @@ func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) { }, { name: "issued for another audience", - token: p.token(t, p.key, func(c *jwt.Claims) { c.Audience = jwt.Audience{"another-service"} }), + token: p.token(t, p.key, func(c *testClaims) { c.Audience = jwt.Audience{"another-service"} }), }, { name: "issued by another provider", - token: p.token(t, p.key, func(c *jwt.Claims) { c.Issuer = "https://someone-else.example" }), + token: p.token(t, p.key, func(c *testClaims) { c.Issuer = "https://someone-else.example" }), + }, + { + // The human path's failure mode: a token minted without the requested + // audience arrives with an empty audience, and the check here refuses + // it. The fix is requesting the audience at the authorisation + // endpoint, not weakening this check. + name: "issued with no audience at all", + token: p.token(t, p.key, func(c *testClaims) { c.Audience = nil }), }, { name: "not a token at all",