From af7d6fa24de7301f74b8afc8c00e606e361d6218 Mon Sep 17 00:00:00 2001 From: Josh Zhang <39790535+jiashuoz@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:02:28 -0800 Subject: [PATCH 1/4] feat(identity): adopt an existing user on provision by exact Google subject ProvisionUserAdopting is ProvisionUser plus one evidence-gated exception to "never attach on an email conflict": when the caller supplies a Google subject and the requested email belongs to a live user whose google_subject is exactly that value, the provision maps the caller's (issuer, external_ref) to that user instead of failing. The user row is never changed. A missing, different or trashed match is still ErrEmailConflict, indistinguishable from a request with no subject. A new mapping gets the same read-only and tombstone checks AttachExternalPrincipal applies, a pair already mapped elsewhere is still ErrExternalPrincipalConflict, and a synthetic bootstrap: subject is never accepted as evidence. The check runs before the insert because the insert's unique violation would abort the transaction. ProvisionUser keeps its signature and behavior. Co-Authored-By: Claude Opus 5.5 --- internal/identity/provision_adopt_test.go | 213 ++++++++++++++++++++++ internal/identity/store.go | 126 +++++++++++-- 2 files changed, 320 insertions(+), 19 deletions(-) create mode 100644 internal/identity/provision_adopt_test.go diff --git a/internal/identity/provision_adopt_test.go b/internal/identity/provision_adopt_test.go new file mode 100644 index 000000000..01c4762a1 --- /dev/null +++ b/internal/identity/provision_adopt_test.go @@ -0,0 +1,213 @@ +package identity_test + +import ( + "context" + "errors" + "testing" + + "github.com/tokencanopy/e2a/internal/identity" + "github.com/tokencanopy/e2a/internal/testutil" +) + +// A direct e2a.dev signup: a user row carrying a real Google subject. +const adoptGoogleSub = "100000000000000000001" + +func newDirectSignup(t *testing.T, store *identity.Store, email string) *identity.User { + t.Helper() + u, err := store.CreateOrGetUser(context.Background(), email, "Direct Signup", adoptGoogleSub) + if err != nil { + t.Fatal(err) + } + return u +} + +func assertUnmapped(t *testing.T, store *identity.Store, ref string) { + t.Helper() + got, err := store.GetUserByExternalPrincipal(context.Background(), testIssuer, ref) + if err != nil { + t.Fatal(err) + } + if got != nil { + t.Fatalf("(issuer, %q) is mapped to %s, want no mapping", ref, got.ID) + } +} + +func TestProvisionAdoptsExistingUserOnExactGoogleSubject(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + + u, created, adopted, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "Another Name", testIssuer, adoptGoogleSub) + if err != nil { + t.Fatalf("adopting provision: %v", err) + } + if u.ID != existing.ID || created || !adopted { + t.Fatalf("got (id=%s created=%v adopted=%v), want (id=%s false true)", u.ID, created, adopted, existing.ID) + } + + mapped, err := store.GetUserByExternalPrincipal(ctx, testIssuer, "tcusr_ada") + if err != nil || mapped == nil || mapped.ID != existing.ID { + t.Fatalf("mapping = %v, %v; want the adopted user", mapped, err) + } + // Adoption never rewrites the adopted user's own identity fields. + after, err := store.GetUserByID(ctx, existing.ID) + if err != nil { + t.Fatal(err) + } + if after.GoogleSubject != adoptGoogleSub || after.Name != "Direct Signup" || after.Email != "ada@example.test" { + t.Fatalf("adopted user changed: subject=%q name=%q email=%q", after.GoogleSubject, after.Name, after.Email) + } +} + +func TestProvisionAdoptionReplaysIdempotently(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + + for i := 0; i < 2; i++ { + u, created, adopted, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if err != nil { + t.Fatalf("attempt %d: %v", i, err) + } + if u.ID != existing.ID || created || !adopted { + t.Fatalf("attempt %d: got (id=%s created=%v adopted=%v)", i, u.ID, created, adopted) + } + } +} + +func TestProvisionRefusesAdoptionOnSubjectMismatch(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, "100000000000000000999") + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("err = %v, want ErrEmailConflict", err) + } + assertUnmapped(t, store, "tcusr_ada") +} + +func TestProvisionWithoutSubjectKeepsEmailConflict(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + + _, _, err := store.ProvisionUser(ctx, "tcusr_ada", "ada@example.test", "", testIssuer) + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("err = %v, want ErrEmailConflict", err) + } + assertUnmapped(t, store, "tcusr_ada") +} + +func TestProvisionWithSubjectAndFreeEmailCreatesAsBefore(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + + u, created, adopted, err := store.ProvisionUserAdopting(ctx, + "tcusr_new", "new@example.test", "", testIssuer, adoptGoogleSub) + if err != nil { + t.Fatal(err) + } + if !created || adopted || u.GoogleSubject != "bootstrap:tcusr_new" { + t.Fatalf("got (created=%v adopted=%v subject=%q), want a fresh bootstrap user", created, adopted, u.GoogleSubject) + } +} + +func TestProvisionRefusesAdoptingTrashedUser(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + if _, err := store.TrashAccount(ctx, existing.ID, nil); err != nil { + t.Fatal(err) + } + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("err = %v, want ErrEmailConflict", err) + } + assertUnmapped(t, store, "tcusr_ada") +} + +func TestProvisionRefusesAdoptingReadOnlyUser(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + if _, err := pool.Exec(ctx, + `INSERT INTO account_sending_controls (user_id, state, reason, actor, pause_class) + VALUES ($1, 'paused', 'synthetic abuse', 'op', 'abuse')`, existing.ID); err != nil { + t.Fatal(err) + } + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrAccountReadOnly) { + t.Fatalf("err = %v, want ErrAccountReadOnly", err) + } + assertUnmapped(t, store, "tcusr_ada") +} + +func TestProvisionAdoptionConflictsWhenPairMappedElsewhere(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + other, err := store.BootstrapUser(ctx, "other@example.test") + if err != nil { + t.Fatal(err) + } + if _, err := store.AttachExternalPrincipal(ctx, testIssuer, "tcusr_ada", other.ID); err != nil { + t.Fatal(err) + } + + _, _, _, err = store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrExternalPrincipalConflict) { + t.Fatalf("err = %v, want ErrExternalPrincipalConflict", err) + } +} + +// A synthetic subject is never evidence: "bootstrap:" would otherwise +// match the Token Canopy-created user for that ref and hand it to a +// different principal. +func TestProvisionRejectsSyntheticSubjectAsEvidence(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + native, _, err := store.ProvisionUser(ctx, "tcusr_owner", "owner@example.test", "", testIssuer) + if err != nil { + t.Fatal(err) + } + + _, _, _, err = store.ProvisionUserAdopting(ctx, + "tcusr_intruder", "owner@example.test", "", testIssuer, native.GoogleSubject) + if !errors.Is(err, identity.ErrInvalidGoogleSubject) { + t.Fatalf("err = %v, want ErrInvalidGoogleSubject", err) + } + assertUnmapped(t, store, "tcusr_intruder") +} + +// Adoption creates a delegated mapping, so it is meaningless without an +// issuer; the legacy issuer-less path must never adopt. +func TestProvisionAdoptionRequiresIssuer(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", "", adoptGoogleSub) + if !errors.Is(err, identity.ErrInvalidGoogleSubject) { + t.Fatalf("err = %v, want ErrInvalidGoogleSubject", err) + } +} diff --git a/internal/identity/store.go b/internal/identity/store.go index 621bb4784..c483d3b75 100644 --- a/internal/identity/store.go +++ b/internal/identity/store.go @@ -6281,27 +6281,106 @@ var ErrEmailConflict = errors.New("identity: email already held by another user" // writes no mapping. A pair already attached to a different user aborts // with ErrExternalPrincipalConflict. func (s *Store) ProvisionUser(ctx context.Context, externalRef, email, name, externalIssuer string) (*User, bool, error) { + u, created, _, err := s.ProvisionUserAdopting(ctx, externalRef, email, name, externalIssuer, "") + return u, created, err +} + +// ErrInvalidGoogleSubject is returned by ProvisionUserAdopting when the +// supplied Google subject cannot serve as adoption evidence: it is a +// synthetic "bootstrap:" subject, or there is no external issuer for the +// adopted user to be mapped under. +var ErrInvalidGoogleSubject = errors.New("identity: google subject is not usable as adoption evidence") + +// ProvisionUserAdopting is ProvisionUser plus one evidence-gated exception to +// "never attach on an email conflict". When googleSubject is nonempty and the +// requested email belongs to a live user whose google_subject is exactly +// googleSubject, that user is ADOPTED: no row is created or changed, the +// (externalIssuer, externalRef) mapping is inserted or replayed for it, and +// adopted=true. The proof is the identity provider's own subject for the same +// person, never the email alone: a missing, different, or trashed match still +// fails with ErrEmailConflict, indistinguishable from a request that sent no +// subject. Replaying an adoption with the same subject is idempotent. +// +// Adoption refuses a read-only (abuse-paused) account with ErrAccountReadOnly +// and a tombstoned mapping subject with ErrRegistrationRefused, exactly as +// AttachExternalPrincipal does for a new mapping. googleSubject must not be a +// "bootstrap:" value and requires a nonempty externalIssuer +// (ErrInvalidGoogleSubject). With googleSubject == "" it is ProvisionUser. +func (s *Store) ProvisionUserAdopting(ctx context.Context, externalRef, email, name, externalIssuer, googleSubject string) (u *User, created, adopted bool, err error) { + if googleSubject != "" && (externalIssuer == "" || strings.HasPrefix(googleSubject, "bootstrap:")) { + return nil, false, false, ErrInvalidGoogleSubject + } tx, err := s.pool.Begin(ctx) if err != nil { - return nil, false, err + return nil, false, false, err } defer tx.Rollback(ctx) - u, created, err := s.provisionUser(ctx, tx, externalRef, email, name, externalIssuer) + u, created, adopted, err = s.provisionUser(ctx, tx, externalRef, email, name, externalIssuer, googleSubject) if err != nil { - return nil, false, err + return nil, false, false, err } if externalIssuer != "" { if err := provisionExternalPrincipalTx(ctx, tx, externalIssuer, externalRef, u.ID); err != nil { - return nil, false, err + return nil, false, false, err } } if err := tx.Commit(ctx); err != nil { - return nil, false, err + return nil, false, false, err + } + return u, created, adopted, nil +} + +// adoptableUserTx returns the live user that the adoption evidence names, or +// (nil, nil) when no user holds the email so the caller may create one. A +// user that holds the email but fails the evidence is ErrEmailConflict, the +// same answer a request without evidence gets. It must run BEFORE the insert: +// the insert's unique violation would abort the transaction. +func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSubject, externalIssuer, externalRef string) (*User, error) { + // FOR SHARE, as AttachExternalPrincipal takes: it conflicts with the + // trash/restore/purge FOR NO KEY UPDATE, so an account cannot be trashed + // between this check and the mapping insert. + holder, err := scanUser(tx.QueryRow(ctx, + `SELECT `+userColumns+` FROM users WHERE email = $1 FOR SHARE`, email)) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + if holder.DeletedAt != nil || holder.GoogleSubject != googleSubject { + return nil, ErrEmailConflict + } + var mapped bool + if err := tx.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM external_principal_mappings WHERE issuer = $1 AND subject = $2)`, + externalIssuer, externalRef).Scan(&mapped); err != nil { + return nil, err } - return u, created, nil + if !mapped { + // A NEW mapping gets AttachExternalPrincipal's checks; replaying an + // existing one does not, so an adopted user paused afterwards still + // replays (and a pair mapped elsewhere still surfaces as a conflict + // from the mapping insert). + var readOnly bool + if err := tx.QueryRow(ctx, accountReadOnlySQL, holder.ID).Scan(&readOnly); err != nil { + return nil, err + } + if readOnly { + return nil, ErrAccountReadOnly + } + if err := s.checkTombstonesTx(ctx, tx, []TombstoneIdentifier{ + {Kind: TombstoneKindLoginSubject, Value: externalPrincipalSubject(externalIssuer, externalRef)}, + }); err != nil { + return nil, err + } + } + return holder, nil } -func (s *Store) provisionUser(ctx context.Context, tx pgx.Tx, externalRef, email, name, externalIssuer string) (*User, bool, error) { +// provisionUser resolves the provision to a user and reports whether it was +// created (a new bootstrap row) or adopted (an existing user named by the +// Google-subject evidence). Both false is a replay of the ref's own row. +func (s *Store) provisionUser(ctx context.Context, tx pgx.Tx, externalRef, email, name, externalIssuer, googleSubject string) (u *User, created, adopted bool, err error) { subject := "bootstrap:" + externalRef // A replay resolves to the existing row. A TRASHED row is refused with // ErrAccountTrashed and nothing is written (no restore, no mapping): the @@ -6311,12 +6390,21 @@ func (s *Store) provisionUser(ctx context.Context, tx pgx.Tx, externalRef, email `SELECT `+userColumns+` FROM users WHERE google_subject = $1 FOR NO KEY UPDATE`, subject)) if err == nil { if existing.DeletedAt != nil { - return nil, false, ErrAccountTrashed + return nil, false, false, ErrAccountTrashed } - return existing, false, nil + return existing, false, false, nil } if !errors.Is(err, pgx.ErrNoRows) { - return nil, false, err + return nil, false, false, err + } + if googleSubject != "" { + holder, err := s.adoptableUserTx(ctx, tx, email, googleSubject, externalIssuer, externalRef) + if err != nil { + return nil, false, false, err + } + if holder != nil { + return holder, false, true, nil + } } ids := append([]TombstoneIdentifier{ {Kind: TombstoneKindLoginSubject, Value: subject}, @@ -6325,16 +6413,16 @@ func (s *Store) provisionUser(ctx context.Context, tx pgx.Tx, externalRef, email ids = append(ids, TombstoneIdentifier{Kind: TombstoneKindLoginSubject, Value: externalPrincipalSubject(externalIssuer, externalRef)}) } if err := s.checkTombstonesTx(ctx, tx, ids); err != nil { - return nil, false, err + return nil, false, false, err } - u, err := scanUser(tx.QueryRow(ctx, + u, err = scanUser(tx.QueryRow(ctx, `INSERT INTO users (id, email, name, google_subject) VALUES ($1, $2, $3, $4) ON CONFLICT (google_subject) DO NOTHING RETURNING `+userColumns, generateID(), email, name, subject)) if err == nil { - return u, true, nil + return u, true, false, nil } var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.SQLState() == "23505" { @@ -6342,22 +6430,22 @@ func (s *Store) provisionUser(ctx context.Context, tx pgx.Tx, externalRef, email // caller can collide with is email. (An id collision is astronomically // unlikely and is not caller-actionable — surface it as a plain error.) if pgErr.ConstraintName == "users_email_key" { - return nil, false, ErrEmailConflict + return nil, false, false, ErrEmailConflict } - return nil, false, err + return nil, false, false, err } if !errors.Is(err, pgx.ErrNoRows) { - return nil, false, err + return nil, false, false, err } // A concurrent provision of the same ref won the insert: re-read it. u, err = scanUser(tx.QueryRow(ctx, `SELECT `+userColumns+` FROM users WHERE google_subject = $1`, subject)) if err != nil { - return nil, false, err + return nil, false, false, err } if u.DeletedAt != nil { - return nil, false, ErrAccountTrashed + return nil, false, false, ErrAccountTrashed } - return u, false, nil + return u, false, false, nil } // GetUserByID loads a LIVE user: a trashed account reads as not found From a18b59bf7f90d22f416b5cb2a5c3fc6d0731e846 Mon Sep 17 00:00:00 2001 From: Josh Zhang <39790535+jiashuoz@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:04:44 -0800 Subject: [PATCH 2/4] feat(agent): accept google_subject on internal provision and report adoption POST /api/internal/users/provision takes an optional google_subject, honored only with external_issuer. On an email conflict the store adopts the existing user when that user's google_subject equals it exactly, and the response is 200 {"user_id", "adopted": true}. Every other response is byte-identical to before, including the email_conflict a wrong subject gets, so the field cannot be used to probe accounts. A subject that is over 255 bytes, contains control characters, starts with bootstrap:, or arrives without an issuer is 400 invalid_google_subject. Adopting an abuse-paused account is 403 account_read_only, the rule attach already applies. The provisioning metric gains the bounded outcome "adopted"; deployment.md and observability.md describe the contract and the label. Co-Authored-By: Claude Opus 5.5 --- docs/deployment.md | 2 +- docs/observability.md | 2 +- internal/agent/provisioning_adopt_api_test.go | 181 ++++++++++++++++++ internal/agent/provisioning_api.go | 61 +++++- internal/telemetry/metrics.go | 2 +- internal/telemetry/prom.go | 2 +- internal/telemetry/prom_test.go | 3 +- 7 files changed, 246 insertions(+), 7 deletions(-) create mode 100644 internal/agent/provisioning_adopt_api_test.go diff --git a/docs/deployment.md b/docs/deployment.md index 42d2b5401..a839bccdf 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -212,7 +212,7 @@ That leaves two real horizontal-scaling caveats: **Dashboard auth is Google OAuth plus an optional generic OIDC login.** [`internal/auth/auth.go`](../internal/auth/auth.go) imports `golang.org/x/oauth2/google` directly and the config exposes `google_client_id` / `google_client_secret`. [`internal/auth/oidc.go`](../internal/auth/oidc.go) additionally implements an off-by-default OpenID Connect relying party (`E2A_OIDC_ENABLED` + the `E2A_OIDC_*` vars above) for teams on Microsoft Entra, Okta, or another standards-compliant OIDC provider. Start the flow at `GET /api/auth/oidc/login`, which accepts the same optional `return_to` and `cli_callback`/`cli_state` query parameters as the Google login (same validation rules, same post-login behavior). It is an additional login path, not a Google OAuth replacement: it maps a configured ID-token claim to an existing e2a user and never provisions new ones, so accounts must already exist (e.g. via Google OAuth or `-bootstrap-email`) before OIDC login works for them. Adding `email` to `oidc.scopes` (`E2A_OIDC_SCOPES`) makes an OIDC login whose ID token asserts `email_verified` for the account's current email record owner-mailbox proof; enable it only against an IdP that sets `email_verified: true` solely after a mailbox confirmation and resets it when the address changes, because a false proof unlocks owner-mailbox sending for a restricted account and exempts sends to that address from the erase-defer check. The CLI and SDKs authenticate with API keys, which are provider-agnostic. -**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. +**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. The one exception is evidence-gated: a request that also carries `external_issuer` and `google_subject` (the identity provider's subject the control plane verified for this person) **adopts** the account holding the email when, and only when, that account's own `google_subject` is exactly equal. The account row is not changed; the `(external_issuer, external_ref)` mapping is created for it, and the response is `200 {"user_id": "...", "adopted": true}` (a replay returns the same). A missing, different, or trashed match returns the same `409 {"error":"email_conflict"}` as a request without the field. Adopting an abuse-paused account returns `403 {"error":"account_read_only"}`, and a `google_subject` that is empty-with-no-issuer, over 255 bytes, contains control characters, or starts with `bootstrap:` returns `400 {"error":"invalid_google_subject"}`. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. **Delegated access-token verification is opt-in and generic.** When `E2A_DELEGATED_ENABLED=true` (plus the `delegated:` config block), the server verifies short-lived, audience-bound OAuth 2.0 access tokens (RFC 9068, JOSE header `typ="at+jwt"`) minted by one configured OIDC issuer, so an external control plane can call the public `/v1` API on behalf of its signed-in humans without holding e2a credentials. e2a runs OIDC discovery against `issuer_url`, verifies the token's signature against the issuer's published JWKS, and pins the exact `issuer`/`audience`/`authorized_party`/singleton `scope`, the `exp − iat` lifetime, the required context claims (with optional allowed-value sets), and the absence of the forbidden claims — all deployment data, so OSS ships no operator-specific claim policy. A verified token maps its `(issuer, subject)` pair to an existing local user and acts with **account** scope, exactly like an account API key; it never provisions on token presentation, and an unmapped subject is a `401`. The feature is fully off by default and isolated: every existing credential path (API keys, OAuth `ate2a_`, agent JWTs, session cookies) keeps working unchanged, including through a total delegated-verifier outage (which fails delegated requests `503`, never the others). A compact JWT whose protected header says `typ="at+jwt"` is owned by this verifier even while it is disabled — it never falls through to the API-key path. Issuer *network* unavailability is not fatal to startup (discovery retries in the background); a malformed static `delegated:` policy is. diff --git a/docs/observability.md b/docs/observability.md index 86c436c69..7ae3c4679 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -81,7 +81,7 @@ collapses every non-`/v1` handler. |---|---|---|---| | `e2a_oidc_discovery_total` | counter | `outcome`, `status_class` | Generic browser-login provider discovery attempts. `outcome` is `success`, `issuer_unavailable` (no response, 429, or 5xx), or `discovery_invalid` (malformed/mismatched discovery or another non-retryable response). `status_class` is the provider response class, `none` when no response was received, or `other` if an unexpected value reaches the backend. | | `e2a_oidc_callback_total` | counter | `outcome`, `trust`, `status_class` | Browser callback outcomes. `outcome` is `success`, `discovery_unavailable`, `state_invalid`, `provider_rejected`, `provider_failed`, `response_invalid`, `token_exchange_failed`, `id_token_invalid`, `claim_invalid`, `unknown_user`, `user_lookup_failed`, `request_canceled`, `session_failed`, `post_login_failed`, or `account_trashed`. `account_trashed` is a verified sign-in that resolved to an account in the trash and was issued only the restricted restore-interstitial session. `provider_rejected` is the expected provider-side `access_denied` refusal path; every other provider-returned OAuth error is the bounded actionable `provider_failed` category. `unknown_user` means the verified user ID has no mapping and remains a 403; `user_lookup_failed` means the identity store could not answer and returns a generic 503. `request_canceled` is a caller-canceled lookup reported as a bounded diagnostic 503 outcome but excluded from outage alerts. `trust=public` covers requests rejected before browser transaction state is validated; `trust=trusted` means the server-authenticated state and transaction cookies matched first. `status_class` is e2a's response class. Alert on sustained actionable `trusted` failures (including `provider_failed`, token exchange, invalid claim, unknown user, user lookup, or session failure), not scanner-shaped `public` traffic, provider-side `provider_rejected` refusals, or caller-side `request_canceled` callbacks. Raw provider codes, descriptions, database errors, and user IDs are never labels or log fields. | -| `e2a_provisioning_total` | counter | `outcome`, `trust`, `status_class` | Internal `POST /api/internal/users/provision` outcomes. `outcome` is `created`, `existing`, `rejected`, `internal_error`, `not_configured`, `malformed_request`, or `unauthorized`. `trust=public` means the HMAC was absent/not yet verified; `trust=authenticated` means the request HMAC passed before the outcome. Alert on sustained `authenticated` `rejected`/`internal_error` outcomes; public malformed/auth failures are diagnostic and must not page. | +| `e2a_provisioning_total` | counter | `outcome`, `trust`, `status_class` | Internal `POST /api/internal/users/provision` outcomes. `outcome` is `created`, `existing`, `adopted` (an existing user adopted on an exact `google_subject` match), `rejected`, `internal_error`, `not_configured`, `malformed_request`, or `unauthorized`. `trust=public` means the HMAC was absent/not yet verified; `trust=authenticated` means the request HMAC passed before the outcome. Alert on sustained `authenticated` `rejected`/`internal_error` outcomes; public malformed/auth failures are diagnostic and must not page. | All three label families are enum-allowlisted and collapse unknown values to `other`. Discovery and callback logs use only the same bounded category/trust/ diff --git a/internal/agent/provisioning_adopt_api_test.go b/internal/agent/provisioning_adopt_api_test.go new file mode 100644 index 000000000..f255298f6 --- /dev/null +++ b/internal/agent/provisioning_adopt_api_test.go @@ -0,0 +1,181 @@ +package agent_test + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gorilla/mux" + "github.com/jackc/pgx/v5" + + "github.com/tokencanopy/e2a/internal/agent" + "github.com/tokencanopy/e2a/internal/auth" + "github.com/tokencanopy/e2a/internal/config" + "github.com/tokencanopy/e2a/internal/identity" + "github.com/tokencanopy/e2a/internal/outbound" + "github.com/tokencanopy/e2a/internal/testutil" + "github.com/tokencanopy/e2a/internal/usage" +) + +const adoptAPIGoogleSub = "100000000000000000001" + +// provisionRaw sends a signed provision to the attach-configured server (which +// has the delegated issuer adoption requires) and returns status and raw body. +func provisionRaw(t *testing.T, server *httptest.Server, body string) (int, []byte) { + t.Helper() + resp := provisionRequest(t, server, attachTestSecret, []byte(body)) + defer resp.Body.Close() + buf, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + return resp.StatusCode, buf +} + +func decodeObject(t *testing.T, buf []byte) map[string]any { + t.Helper() + var out map[string]any + if err := json.Unmarshal(buf, &out); err != nil { + t.Fatalf("not a JSON object: %q", buf) + } + return out +} + +func adoptBody(ref, email, subject string) string { + b, _ := json.Marshal(map[string]string{ + "external_issuer": attachTestIssuer, + "external_ref": ref, + "email": email, + "google_subject": subject, + }) + return string(b) +} + +func directSignup(t *testing.T, store *identity.Store, email string) *identity.User { + t.Helper() + u, err := store.CreateOrGetUser(context.Background(), email, "Direct Signup", adoptAPIGoogleSub) + if err != nil { + t.Fatal(err) + } + return u +} + +func TestProvisionUser_AdoptsOnMatchingGoogleSubjectReturns200(t *testing.T) { + server, store := setupAttachAPI(t, attachTestIssuer) + existing := directSignup(t, store, "ada@example.test") + + for attempt := 0; attempt < 2; attempt++ { + status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "ada@example.test", adoptAPIGoogleSub)) + if status != http.StatusOK { + t.Fatalf("attempt %d: status = %d, want 200; body=%s", attempt, status, buf) + } + got := decodeObject(t, buf) + if got["user_id"] != existing.ID || got["adopted"] != true { + t.Fatalf("attempt %d: body = %s, want user_id=%s adopted=true", attempt, buf, existing.ID) + } + } + mapped, err := store.GetUserByExternalPrincipal(context.Background(), attachTestIssuer, "tcusr_ada") + if err != nil || mapped == nil || mapped.ID != existing.ID { + t.Fatalf("mapping = %v, %v; want the adopted user", mapped, err) + } +} + +// The evidence must not be probeable: a wrong subject gets exactly the bytes +// a request without any subject gets. +func TestProvisionUser_SubjectMismatchIsIndistinguishableEmailConflict(t *testing.T) { + server, store := setupAttachAPI(t, attachTestIssuer) + directSignup(t, store, "ada@example.test") + + noSubject, _ := json.Marshal(map[string]string{ + "external_issuer": attachTestIssuer, "external_ref": "tcusr_a", "email": "ada@example.test", + }) + wantStatus, want := provisionRaw(t, server, string(noSubject)) + gotStatus, got := provisionRaw(t, server, adoptBody("tcusr_b", "ada@example.test", "100000000000000000999")) + if wantStatus != http.StatusConflict || gotStatus != wantStatus || string(got) != string(want) { + t.Fatalf("mismatch = %d %q, no-subject = %d %q; want identical 409s", gotStatus, got, wantStatus, want) + } + if mapped, _ := store.GetUserByExternalPrincipal(context.Background(), attachTestIssuer, "tcusr_b"); mapped != nil { + t.Fatalf("mismatch created a mapping to %s", mapped.ID) + } +} + +func TestProvisionUser_SubjectWithFreeEmailCreatesWithoutAdoptedField(t *testing.T) { + server, _ := setupAttachAPI(t, attachTestIssuer) + + status, buf := provisionRaw(t, server, adoptBody("tcusr_new", "new@example.test", adoptAPIGoogleSub)) + if status != http.StatusCreated { + t.Fatalf("status = %d, want 201; body=%s", status, buf) + } + got := decodeObject(t, buf) + if _, present := got["adopted"]; present || len(got) != 1 { + t.Fatalf("body = %s, want exactly {user_id}", buf) + } +} + +func TestProvisionUser_AdoptingReadOnlyAccountIs403(t *testing.T) { + server, store := setupAttachAPI(t, attachTestIssuer) + existing := directSignup(t, store, "ada@example.test") + ctx := context.Background() + if err := store.WithTx(ctx, func(tx pgx.Tx) error { + _, err := tx.Exec(ctx, + `INSERT INTO account_sending_controls (user_id, state, reason, actor, pause_class) + VALUES ($1, 'paused', 'synthetic abuse', 'op', 'abuse')`, existing.ID) + return err + }); err != nil { + t.Fatal(err) + } + + status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "ada@example.test", adoptAPIGoogleSub)) + if status != http.StatusForbidden || decodeObject(t, buf)["error"] != identity.AccountReadOnlyCode { + t.Fatalf("status = %d body = %s, want 403 %s", status, buf, identity.AccountReadOnlyCode) + } +} + +func TestProvisionUser_GoogleSubjectValidation(t *testing.T) { + server, _ := setupAttachAPI(t, attachTestIssuer) + + withoutIssuer, _ := json.Marshal(map[string]string{ + "external_ref": "tcusr_x", "email": "x@example.test", "google_subject": adoptAPIGoogleSub, + }) + cases := map[string]string{ + "synthetic bootstrap subject": adoptBody("tcusr_x", "x@example.test", "bootstrap:tcusr_owner"), + "no external_issuer": string(withoutIssuer), + "oversize subject": adoptBody("tcusr_x", "x@example.test", strings.Repeat("1", 256)), + "control character": adoptBody("tcusr_x", "x@example.test", "1000\n0001"), + } + for name, body := range cases { + status, buf := provisionRaw(t, server, body) + if status != http.StatusBadRequest || decodeObject(t, buf)["error"] != "invalid_google_subject" { + t.Errorf("%s: status = %d body = %s, want 400 invalid_google_subject", name, status, buf) + } + } +} + +func TestProvisionUser_AdoptionRecordsAdoptedMetric(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + smtpRelay := outbound.NewSMTPRelay(&config.OutboundSMTPConfig{}) + api := agent.NewAPI(store, outbound.NewSender(smtpRelay, "test.e2a.dev"), smtpRelay, + auth.NewUserAuth(&config.OAuthConfig{}, store, false), usage.NewNoopUsageTracker(), + "e2a.dev", "test.e2a.dev", "agents.e2a.dev", "", false) + api.ConfigureProvisioning(true, attachTestSecret) + api.SetDelegatedIssuer(attachTestIssuer) + metrics := &provisioningMetricsRecorder{} + api.SetMetrics(metrics) + router := mux.NewRouter() + api.RegisterRoutes(router) + server := httptest.NewServer(router) + t.Cleanup(server.Close) + directSignup(t, store, "ada@example.test") + + if status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "ada@example.test", adoptAPIGoogleSub)); status != http.StatusOK { + t.Fatalf("status = %d body = %s", status, buf) + } + if got, want := metrics.last(t), (provisioningMetricEvent{outcome: "adopted", trust: "authenticated", statusClass: "2xx"}); got != want { + t.Fatalf("metric = %+v, want %+v", got, want) + } +} diff --git a/internal/agent/provisioning_api.go b/internal/agent/provisioning_api.go index f233ed517..d3e633c90 100644 --- a/internal/agent/provisioning_api.go +++ b/internal/agent/provisioning_api.go @@ -8,6 +8,7 @@ import ( "log" "net/http" "net/mail" + "strings" "unicode/utf8" "github.com/tokencanopy/e2a/internal/identity" @@ -27,6 +28,13 @@ type provisionUserRequest struct { ExternalRef string `json:"external_ref"` Email string `json:"email"` Name string `json:"name"` // optional; '' default + // GoogleSubject, when present, is the identity provider's subject for + // the person behind external_ref (a control plane's verified Google + // identity). It is evidence, not a key: on an email conflict, the + // provision ADOPTS the existing user only if that user's google_subject + // equals it exactly, and otherwise answers the same email_conflict as a + // request without it. Requires external_issuer; never "bootstrap:". + GoogleSubject string `json:"google_subject"` } // handleProvisionUser creates an e2a user on behalf of an external control @@ -48,7 +56,9 @@ type provisionUserRequest struct { // // Unlike the text/plain limits-invalidate surface, responses here are JSON // because the caller must branch on machine-readable outcomes (created vs -// replayed vs email-conflict). +// replayed vs adopted vs email-conflict). An adoption — an email conflict +// resolved by an exactly matching google_subject — is the only response that +// carries a second field ("adopted": true). func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { if !a.provisioningEnabled || a.provisioningSecret == "" { a.recordProvisioning("not_configured", "public", http.StatusServiceUnavailable) @@ -101,6 +111,11 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { writeProvisionError(w, http.StatusBadRequest, "invalid_issuer") return } + if req.GoogleSubject != "" && (req.ExternalIssuer == "" || !validGoogleSubject(req.GoogleSubject)) { + a.recordProvisioning("rejected", "authenticated", http.StatusBadRequest) + writeProvisionError(w, http.StatusBadRequest, "invalid_google_subject") + return + } email := identity.NormalizeEmail(req.Email) parsed, err := mail.ParseAddress(email) if err != nil || parsed.Address != email { @@ -109,7 +124,7 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { return } - user, created, err := a.store.ProvisionUser(r.Context(), req.ExternalRef, email, req.Name, req.ExternalIssuer) + user, created, adopted, err := a.store.ProvisionUserAdopting(r.Context(), req.ExternalRef, email, req.Name, req.ExternalIssuer, req.GoogleSubject) if errors.Is(err, identity.ErrEmailConflict) { // A DIFFERENT account already holds this email. Never attach, never // merge — reconciliation is the operator's/user's decision. @@ -141,6 +156,20 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { writeProvisionError(w, http.StatusForbidden, "registration_refused") return } + if errors.Is(err, identity.ErrAccountReadOnly) { + // Adoption only: a read-only (abuse-paused) account takes no new + // sign-in principal, the same rule attach applies. + a.recordProvisioning("rejected", "authenticated", http.StatusForbidden) + writeProvisionError(w, http.StatusForbidden, identity.AccountReadOnlyCode) + return + } + if errors.Is(err, identity.ErrInvalidGoogleSubject) { + // Unreachable after the validation above; kept so a store-level + // refusal can never surface as a 500. + a.recordProvisioning("rejected", "authenticated", http.StatusBadRequest) + writeProvisionError(w, http.StatusBadRequest, "invalid_google_subject") + return + } if errors.Is(err, identity.ErrTombstoneKeyUnavailable) { a.recordProvisioning("internal_error", "authenticated", http.StatusServiceUnavailable) writeProvisionError(w, http.StatusServiceUnavailable, "registration_unavailable") @@ -159,12 +188,40 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { status = http.StatusCreated outcome = "created" } + if adopted { + outcome = "adopted" + } a.recordProvisioning(outcome, "authenticated", status) w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) + if adopted { + // Only an adoption carries the flag, so every other response stays + // byte-identical for callers that decode {user_id} strictly. + _ = json.NewEncoder(w).Encode(struct { + UserID string `json:"user_id"` + Adopted bool `json:"adopted"` + }{user.ID, true}) + return + } _ = json.NewEncoder(w).Encode(map[string]string{"user_id": user.ID}) } +// validGoogleSubject bounds adoption evidence: 1..255 bytes of valid UTF-8, +// no control characters (the Cc category, as validExternalRef), and never a +// synthetic "bootstrap:" subject, which would name a control-plane-created +// user rather than prove anyone's identity. +func validGoogleSubject(s string) bool { + if s == "" || len(s) > 255 || !utf8.ValidString(s) || strings.HasPrefix(s, "bootstrap:") { + return false + } + for _, r := range s { + if r < 0x20 || (r >= 0x7f && r <= 0x9f) { + return false + } + } + return true +} + func (a *API) recordProvisioning(outcome, trust string, status int) { statusClass := "none" switch status / 100 { diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index 2ae9880bc..d8fe17f54 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -269,7 +269,7 @@ type Metrics interface { OIDCCallback(outcome, trust, statusClass string) // Provisioning counts POST /api/internal/users/provision outcomes. outcome - // ∈ {created, existing, rejected, internal_error, not_configured, + // ∈ {created, existing, adopted, rejected, internal_error, not_configured, // malformed_request, unauthorized}; trust ∈ {public, authenticated}. // "authenticated" means the request HMAC was verified before the outcome. // statusClass is the e2a response class. Labels are bounded enums and diff --git a/internal/telemetry/prom.go b/internal/telemetry/prom.go index 3bad94392..e8113fa3e 100644 --- a/internal/telemetry/prom.go +++ b/internal/telemetry/prom.go @@ -140,7 +140,7 @@ var ( ) oidcCallbackTrustSet = set("public", "trusted") provisioningSet = set( - "created", "existing", "rejected", "internal_error", "not_configured", + "created", "existing", "adopted", "rejected", "internal_error", "not_configured", "malformed_request", "unauthorized", ) provisioningTrustSet = set("public", "authenticated") diff --git a/internal/telemetry/prom_test.go b/internal/telemetry/prom_test.go index 8a8f545c6..01877ede4 100644 --- a/internal/telemetry/prom_test.go +++ b/internal/telemetry/prom_test.go @@ -133,7 +133,7 @@ func TestPromEmitsAllOIDCAndProvisioningOutcomeCategories(t *testing.T) { p.OIDCCallback(outcome, "trusted", "4xx") } for _, outcome := range []string{ - "created", "existing", "rejected", "internal_error", "not_configured", + "created", "existing", "adopted", "rejected", "internal_error", "not_configured", "malformed_request", "unauthorized", } { p.Provisioning(outcome, "authenticated", "2xx") @@ -158,6 +158,7 @@ func TestPromEmitsAllOIDCAndProvisioningOutcomeCategories(t *testing.T) { `e2a_oidc_callback_total{outcome="post_login_failed",status_class="4xx",trust="trusted"} 1`, `e2a_provisioning_total{outcome="created",status_class="2xx",trust="authenticated"} 1`, `e2a_provisioning_total{outcome="existing",status_class="2xx",trust="authenticated"} 1`, + `e2a_provisioning_total{outcome="adopted",status_class="2xx",trust="authenticated"} 1`, `e2a_provisioning_total{outcome="rejected",status_class="2xx",trust="authenticated"} 1`, `e2a_provisioning_total{outcome="internal_error",status_class="2xx",trust="authenticated"} 1`, `e2a_provisioning_total{outcome="not_configured",status_class="2xx",trust="authenticated"} 1`, From ad9eb1384999969c13c5b3136a25f7543567a8e4 Mon Sep 17 00:00:00 2001 From: Josh Zhang <39790535+jiashuoz@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:35:16 -0800 Subject: [PATCH 3/4] fix(identity): make a wrong subject answer as no subject, and replay adoption by mapping Review findings on the adoption path: - A mismatched or trashed holder returned email_conflict before the evidence-less path's tombstone check, so with tombstones on it could answer 409 where a request without a subject answers 403/503. The adoption check now returns "no evidence" and the request continues on exactly that path, so the bytes are identical by construction. - An adoption replay re-derived the user by email, so a replay after the adopted user's e2a email changed fell through to a fresh create and then external_principal_conflict. A replay now resolves by the existing (issuer, ref) mapping first, and only while the subject still matches. - The subject bound moves into identity.ValidGoogleSubject so the store enforces the same rule as the handler. Adds tests for the tombstoned mapping subject, the missing tombstone key, a replay after pause, a replay with a different subject, the handler's external_principal_conflict, and two concurrency cases (an adoption waiting on a trash, and concurrent adoptions of one pair). deployment.md now states the replay rule and every adoption error. Co-Authored-By: Claude Opus 5.5 --- docs/deployment.md | 2 +- internal/agent/provisioning_adopt_api_test.go | 35 +++ internal/agent/provisioning_api.go | 22 +- internal/identity/provision_adopt_test.go | 226 ++++++++++++++++++ internal/identity/store.go | 77 ++++-- 5 files changed, 321 insertions(+), 41 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index a839bccdf..4605a96ef 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -212,7 +212,7 @@ That leaves two real horizontal-scaling caveats: **Dashboard auth is Google OAuth plus an optional generic OIDC login.** [`internal/auth/auth.go`](../internal/auth/auth.go) imports `golang.org/x/oauth2/google` directly and the config exposes `google_client_id` / `google_client_secret`. [`internal/auth/oidc.go`](../internal/auth/oidc.go) additionally implements an off-by-default OpenID Connect relying party (`E2A_OIDC_ENABLED` + the `E2A_OIDC_*` vars above) for teams on Microsoft Entra, Okta, or another standards-compliant OIDC provider. Start the flow at `GET /api/auth/oidc/login`, which accepts the same optional `return_to` and `cli_callback`/`cli_state` query parameters as the Google login (same validation rules, same post-login behavior). It is an additional login path, not a Google OAuth replacement: it maps a configured ID-token claim to an existing e2a user and never provisions new ones, so accounts must already exist (e.g. via Google OAuth or `-bootstrap-email`) before OIDC login works for them. Adding `email` to `oidc.scopes` (`E2A_OIDC_SCOPES`) makes an OIDC login whose ID token asserts `email_verified` for the account's current email record owner-mailbox proof; enable it only against an IdP that sets `email_verified: true` solely after a mailbox confirmation and resets it when the address changes, because a false proof unlocks owner-mailbox sending for a restricted account and exempts sends to that address from the erase-defer check. The CLI and SDKs authenticate with API keys, which are provider-agnostic. -**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. The one exception is evidence-gated: a request that also carries `external_issuer` and `google_subject` (the identity provider's subject the control plane verified for this person) **adopts** the account holding the email when, and only when, that account's own `google_subject` is exactly equal. The account row is not changed; the `(external_issuer, external_ref)` mapping is created for it, and the response is `200 {"user_id": "...", "adopted": true}` (a replay returns the same). A missing, different, or trashed match returns the same `409 {"error":"email_conflict"}` as a request without the field. Adopting an abuse-paused account returns `403 {"error":"account_read_only"}`, and a `google_subject` that is empty-with-no-issuer, over 255 bytes, contains control characters, or starts with `bootstrap:` returns `400 {"error":"invalid_google_subject"}`. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. +**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. The one exception is evidence-gated: a request that also carries `external_issuer` and `google_subject` (the identity provider's subject the control plane verified for this person) **adopts** the account holding the email when, and only when, that account's own `google_subject` is exactly equal. The account row is not changed; the `(external_issuer, external_ref)` mapping is created for it, and the response is `200 {"user_id": "...", "adopted": true}`. A replay resolves by that mapping, so it survives a later change of the account's email, but it must repeat the same `google_subject`: without it, the request is an ordinary one and gets `email_conflict`. A missing, different, or trashed match takes exactly the path a request without the field takes, so it gets the same bytes (`409 email_conflict`, or a tombstone refusal that precedes it). A new adoption applies attach's rules: an abuse-paused account returns `403 {"error":"account_read_only"}`, a tombstoned mapping subject `403 registration_refused`, and a pair already mapped to a different user `409 external_principal_conflict`. A non-empty `google_subject` without `external_issuer`, over 255 bytes, containing control characters, or starting with `bootstrap:` returns `400 {"error":"invalid_google_subject"}`. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. **Delegated access-token verification is opt-in and generic.** When `E2A_DELEGATED_ENABLED=true` (plus the `delegated:` config block), the server verifies short-lived, audience-bound OAuth 2.0 access tokens (RFC 9068, JOSE header `typ="at+jwt"`) minted by one configured OIDC issuer, so an external control plane can call the public `/v1` API on behalf of its signed-in humans without holding e2a credentials. e2a runs OIDC discovery against `issuer_url`, verifies the token's signature against the issuer's published JWKS, and pins the exact `issuer`/`audience`/`authorized_party`/singleton `scope`, the `exp − iat` lifetime, the required context claims (with optional allowed-value sets), and the absence of the forbidden claims — all deployment data, so OSS ships no operator-specific claim policy. A verified token maps its `(issuer, subject)` pair to an existing local user and acts with **account** scope, exactly like an account API key; it never provisions on token presentation, and an unmapped subject is a `401`. The feature is fully off by default and isolated: every existing credential path (API keys, OAuth `ate2a_`, agent JWTs, session cookies) keeps working unchanged, including through a total delegated-verifier outage (which fails delegated requests `503`, never the others). A compact JWT whose protected header says `typ="at+jwt"` is owned by this verifier even while it is disabled — it never falls through to the API-key path. Issuer *network* unavailability is not fatal to startup (discovery retries in the background); a malformed static `delegated:` policy is. diff --git a/internal/agent/provisioning_adopt_api_test.go b/internal/agent/provisioning_adopt_api_test.go index f255298f6..12e84d42c 100644 --- a/internal/agent/provisioning_adopt_api_test.go +++ b/internal/agent/provisioning_adopt_api_test.go @@ -179,3 +179,38 @@ func TestProvisionUser_AdoptionRecordsAdoptedMetric(t *testing.T) { t.Fatalf("metric = %+v, want %+v", got, want) } } + +// The no-evidence answer is decided by the evidence-less path, so a wrong +// subject matches it byte-for-byte even when that path refuses before the +// email check (here: tombstones on, no key configured). +func TestProvisionUser_SubjectMismatchMatchesNoSubjectWhenRegistrationUnavailable(t *testing.T) { + server, store := setupAttachAPI(t, attachTestIssuer) + directSignup(t, store, "ada@example.test") + store.SetTombstonePolicy(identity.TombstonePolicy{Enabled: true}) + + noSubject, _ := json.Marshal(map[string]string{ + "external_issuer": attachTestIssuer, "external_ref": "tcusr_a", "email": "ada@example.test", + }) + wantStatus, want := provisionRaw(t, server, string(noSubject)) + gotStatus, got := provisionRaw(t, server, adoptBody("tcusr_a", "ada@example.test", "100000000000000000999")) + if wantStatus != http.StatusServiceUnavailable || gotStatus != wantStatus || string(got) != string(want) { + t.Fatalf("mismatch = %d %q, no-subject = %d %q; want identical 503s", gotStatus, got, wantStatus, want) + } +} + +func TestProvisionUser_AdoptingPairMappedElsewhereIs409(t *testing.T) { + server, store := setupAttachAPI(t, attachTestIssuer) + directSignup(t, store, "ada@example.test") + other, err := store.BootstrapUser(context.Background(), "other@example.test") + if err != nil { + t.Fatal(err) + } + if _, err := store.AttachExternalPrincipal(context.Background(), attachTestIssuer, "tcusr_ada", other.ID); err != nil { + t.Fatal(err) + } + + status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "ada@example.test", adoptAPIGoogleSub)) + if status != http.StatusConflict || decodeObject(t, buf)["error"] != "external_principal_conflict" { + t.Fatalf("status = %d body = %s, want 409 external_principal_conflict", status, buf) + } +} diff --git a/internal/agent/provisioning_api.go b/internal/agent/provisioning_api.go index d3e633c90..e742a0856 100644 --- a/internal/agent/provisioning_api.go +++ b/internal/agent/provisioning_api.go @@ -8,7 +8,6 @@ import ( "log" "net/http" "net/mail" - "strings" "unicode/utf8" "github.com/tokencanopy/e2a/internal/identity" @@ -111,7 +110,7 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { writeProvisionError(w, http.StatusBadRequest, "invalid_issuer") return } - if req.GoogleSubject != "" && (req.ExternalIssuer == "" || !validGoogleSubject(req.GoogleSubject)) { + if req.GoogleSubject != "" && (req.ExternalIssuer == "" || !identity.ValidGoogleSubject(req.GoogleSubject)) { a.recordProvisioning("rejected", "authenticated", http.StatusBadRequest) writeProvisionError(w, http.StatusBadRequest, "invalid_google_subject") return @@ -127,7 +126,8 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { user, created, adopted, err := a.store.ProvisionUserAdopting(r.Context(), req.ExternalRef, email, req.Name, req.ExternalIssuer, req.GoogleSubject) if errors.Is(err, identity.ErrEmailConflict) { // A DIFFERENT account already holds this email. Never attach, never - // merge — reconciliation is the operator's/user's decision. + // merge — reconciliation is the operator's/user's decision. (An + // exactly matching google_subject was adopted and never reaches here.) a.recordProvisioning("rejected", "authenticated", http.StatusConflict) writeProvisionError(w, http.StatusConflict, "email_conflict") return @@ -206,22 +206,6 @@ func (a *API) handleProvisionUser(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(map[string]string{"user_id": user.ID}) } -// validGoogleSubject bounds adoption evidence: 1..255 bytes of valid UTF-8, -// no control characters (the Cc category, as validExternalRef), and never a -// synthetic "bootstrap:" subject, which would name a control-plane-created -// user rather than prove anyone's identity. -func validGoogleSubject(s string) bool { - if s == "" || len(s) > 255 || !utf8.ValidString(s) || strings.HasPrefix(s, "bootstrap:") { - return false - } - for _, r := range s { - if r < 0x20 || (r >= 0x7f && r <= 0x9f) { - return false - } - } - return true -} - func (a *API) recordProvisioning(outcome, trust string, status int) { statusClass := "none" switch status / 100 { diff --git a/internal/identity/provision_adopt_test.go b/internal/identity/provision_adopt_test.go index 01c4762a1..c4723b37e 100644 --- a/internal/identity/provision_adopt_test.go +++ b/internal/identity/provision_adopt_test.go @@ -3,7 +3,11 @@ package identity_test import ( "context" "errors" + "sync" "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" "github.com/tokencanopy/e2a/internal/identity" "github.com/tokencanopy/e2a/internal/testutil" @@ -211,3 +215,225 @@ func TestProvisionAdoptionRequiresIssuer(t *testing.T) { t.Fatalf("err = %v, want ErrInvalidGoogleSubject", err) } } + +// An adoption replay resolves by the existing mapping, so it survives the +// adopted user's email changing in between (an e2a.dev sign-in rewrites it). +func TestProvisionAdoptionReplaySurvivesEmailChange(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + if _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE users SET email = 'ada.new@example.test' WHERE id = $1`, existing.ID); err != nil { + t.Fatal(err) + } + + u, created, adopted, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if err != nil { + t.Fatalf("replay after email change: %v", err) + } + if u.ID != existing.ID || created || !adopted { + t.Fatalf("got (id=%s created=%v adopted=%v), want the adopted user replayed", u.ID, created, adopted) + } +} + +// The mapping replay still demands the evidence: a different subject on an +// already-adopted pair is not a replay. +func TestProvisionAdoptionReplayRequiresSameSubject(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + if _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub); err != nil { + t.Fatal(err) + } + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, "100000000000000000999") + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("err = %v, want ErrEmailConflict", err) + } +} + +// An account paused after its adoption still replays: the read-only check +// guards only a NEW mapping, exactly as attach's replay. +func TestProvisionAdoptionReplaysAfterPause(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + if _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub); err != nil { + t.Fatal(err) + } + abusePause(t, pool, existing.ID, "") + + u, _, adopted, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if err != nil || u.ID != existing.ID || !adopted { + t.Fatalf("replay after pause = (%v, adopted=%v, %v), want the adopted user", u, adopted, err) + } +} + +// purgedMappedPrincipal leaves a live login-subject tombstone for +// (testIssuer, ref): a user mapped under it is trashed and purged. +func purgedMappedPrincipal(t *testing.T, store *identity.Store, pool *pgxpool.Pool, ref string) { + t.Helper() + ctx := context.Background() + gone, _, err := store.ProvisionUser(ctx, ref, "gone@example.test", "", testIssuer) + if err != nil { + t.Fatal(err) + } + if _, err := store.TrashAccount(ctx, gone.ID, nil); err != nil { + t.Fatal(err) + } + ageTrash(t, pool, gone.ID) + if purged, err := store.PurgeDeletedUsers(ctx, nil); err != nil || len(purged) != 1 { + t.Fatalf("purge: %v %v", purged, err) + } +} + +func TestProvisionAdoptionRefusesTombstonedMappingSubject(t *testing.T) { + store, pool, _ := tombstoneStore(t) + ctx := context.Background() + purgedMappedPrincipal(t, store, pool, "tcusr_gone") + newDirectSignup(t, store, "ada@example.test") + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_gone", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrRegistrationRefused) { + t.Fatalf("err = %v, want ErrRegistrationRefused", err) + } + assertUnmapped(t, store, "tcusr_gone") +} + +// A wrong subject must answer exactly what no subject answers, including when +// the evidence-less path refuses on a tombstone before it reaches the email. +func TestProvisionMismatchAnswersAsNoSubjectUnderTombstone(t *testing.T) { + store, pool, _ := tombstoneStore(t) + ctx := context.Background() + purgedMappedPrincipal(t, store, pool, "tcusr_gone") + newDirectSignup(t, store, "ada@example.test") + + _, _, noSubject := store.ProvisionUser(ctx, "tcusr_gone", "ada@example.test", "", testIssuer) + _, _, _, mismatch := store.ProvisionUserAdopting(ctx, + "tcusr_gone", "ada@example.test", "", testIssuer, "100000000000000000999") + if !errors.Is(noSubject, identity.ErrRegistrationRefused) || !errors.Is(mismatch, identity.ErrRegistrationRefused) { + t.Fatalf("no subject = %v, mismatch = %v; want both ErrRegistrationRefused", noSubject, mismatch) + } +} + +func TestProvisionAdoptionWithoutTombstoneKeyIsUnavailable(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + store.SetTombstonePolicy(identity.TombstonePolicy{Enabled: true}) + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrTombstoneKeyUnavailable) { + t.Fatalf("err = %v, want ErrTombstoneKeyUnavailable", err) + } + assertUnmapped(t, store, "tcusr_ada") +} + +// waitForLockWaiter blocks until some backend in this database is waiting on +// a row lock, so a concurrency test can order its two transactions. +func waitForLockWaiter(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + var n int + if err := pool.QueryRow(context.Background(), + `SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&n); err != nil { + t.Fatal(err) + } + if n > 0 { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("no transaction ever waited on the lock") +} + +// A trash that commits while an adoption waits on the holder's row wins: the +// adoption re-reads the trashed row and refuses, writing no mapping. +func TestProvisionAdoptionWaitsForConcurrentTrash(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + + trash, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + defer trash.Rollback(ctx) + if _, err := trash.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR NO KEY UPDATE`, existing.ID); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + done <- err + }() + waitForLockWaiter(t, pool) + if _, err := trash.Exec(ctx, `UPDATE users SET deleted_at = now() WHERE id = $1`, existing.ID); err != nil { + t.Fatal(err) + } + if err := trash.Commit(ctx); err != nil { + t.Fatal(err) + } + + select { + case err := <-done: + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("adoption racing a trash: err = %v, want ErrEmailConflict", err) + } + case <-time.After(10 * time.Second): + t.Fatal("adoption never finished") + } + assertUnmapped(t, store, "tcusr_ada") +} + +// Two concurrent first adoptions of one pair both resolve to the same user, +// with no deadlock and no conflict. +func TestProvisionConcurrentAdoptionsOfOnePair(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ada@example.test") + + const n = 4 + var wg sync.WaitGroup + start := make(chan struct{}) + errs := make([]error, n) + ids := make([]string, n) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + u, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ada", "ada@example.test", "", testIssuer, adoptGoogleSub) + errs[i] = err + if u != nil { + ids[i] = u.ID + } + }(i) + } + close(start) + wg.Wait() + for i := 0; i < n; i++ { + if errs[i] != nil || ids[i] != existing.ID { + t.Fatalf("adoption %d = (%s, %v), want %s", i, ids[i], errs[i], existing.ID) + } + } +} diff --git a/internal/identity/store.go b/internal/identity/store.go index c483d3b75..9a70cf5aa 100644 --- a/internal/identity/store.go +++ b/internal/identity/store.go @@ -6286,11 +6286,27 @@ func (s *Store) ProvisionUser(ctx context.Context, externalRef, email, name, ext } // ErrInvalidGoogleSubject is returned by ProvisionUserAdopting when the -// supplied Google subject cannot serve as adoption evidence: it is a -// synthetic "bootstrap:" subject, or there is no external issuer for the -// adopted user to be mapped under. +// supplied Google subject cannot serve as adoption evidence (see +// ValidGoogleSubject), or there is no external issuer for the adopted user to +// be mapped under. var ErrInvalidGoogleSubject = errors.New("identity: google subject is not usable as adoption evidence") +// ValidGoogleSubject bounds adoption evidence: 1..255 bytes of valid UTF-8, +// no control characters (the Cc category), and never a synthetic +// "bootstrap:" subject, which names a control-plane-created user rather than +// proving anyone's identity. +func ValidGoogleSubject(s string) bool { + if s == "" || len(s) > 255 || !utf8.ValidString(s) || strings.HasPrefix(s, "bootstrap:") { + return false + } + for _, r := range s { + if r < 0x20 || (r >= 0x7f && r <= 0x9f) { + return false + } + } + return true +} + // ProvisionUserAdopting is ProvisionUser plus one evidence-gated exception to // "never attach on an email conflict". When googleSubject is nonempty and the // requested email belongs to a live user whose google_subject is exactly @@ -6298,8 +6314,11 @@ var ErrInvalidGoogleSubject = errors.New("identity: google subject is not usable // (externalIssuer, externalRef) mapping is inserted or replayed for it, and // adopted=true. The proof is the identity provider's own subject for the same // person, never the email alone: a missing, different, or trashed match still -// fails with ErrEmailConflict, indistinguishable from a request that sent no -// subject. Replaying an adoption with the same subject is idempotent. +// takes exactly the path a request without a subject takes, so it fails the +// same way (ErrEmailConflict, or the tombstone refusal that precedes it). +// Replaying an adoption with the same subject is idempotent and resolves by +// the existing mapping first, so it survives a later change of the adopted +// user's email. // // Adoption refuses a read-only (abuse-paused) account with ErrAccountReadOnly // and a tombstoned mapping subject with ErrRegistrationRefused, exactly as @@ -6307,7 +6326,7 @@ var ErrInvalidGoogleSubject = errors.New("identity: google subject is not usable // "bootstrap:" value and requires a nonempty externalIssuer // (ErrInvalidGoogleSubject). With googleSubject == "" it is ProvisionUser. func (s *Store) ProvisionUserAdopting(ctx context.Context, externalRef, email, name, externalIssuer, googleSubject string) (u *User, created, adopted bool, err error) { - if googleSubject != "" && (externalIssuer == "" || strings.HasPrefix(googleSubject, "bootstrap:")) { + if googleSubject != "" && (externalIssuer == "" || !ValidGoogleSubject(googleSubject)) { return nil, false, false, ErrInvalidGoogleSubject } tx, err := s.pool.Begin(ctx) @@ -6331,14 +6350,29 @@ func (s *Store) ProvisionUserAdopting(ctx context.Context, externalRef, email, n } // adoptableUserTx returns the live user that the adoption evidence names, or -// (nil, nil) when no user holds the email so the caller may create one. A -// user that holds the email but fails the evidence is ErrEmailConflict, the -// same answer a request without evidence gets. It must run BEFORE the insert: -// the insert's unique violation would abort the transaction. +// (nil, nil) when it names none, so the caller continues on exactly the path +// a request without evidence takes (create, or fail with that path's own +// error). It must run BEFORE the insert: the insert's unique violation would +// abort the transaction. +// +// Every read takes FOR SHARE, as AttachExternalPrincipal does: it conflicts +// with the trash/restore/purge FOR NO KEY UPDATE, so an account cannot be +// trashed between this check and the mapping insert. func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSubject, externalIssuer, externalRef string) (*User, error) { - // FOR SHARE, as AttachExternalPrincipal takes: it conflicts with the - // trash/restore/purge FOR NO KEY UPDATE, so an account cannot be trashed - // between this check and the mapping insert. + // Replay first, by the mapping: an earlier adoption of this pair resolves + // to the same user even if that user's email has since changed (an + // e2a.dev sign-in rewrites it), provided the evidence still names them. + // A replay gets no read-only or tombstone check, as attach's replay. + mapped, err := scanUser(tx.QueryRow(ctx, + `SELECT `+userColumns+` FROM users + WHERE id = (SELECT user_id FROM external_principal_mappings WHERE issuer = $1 AND subject = $2) + FOR SHARE`, externalIssuer, externalRef)) + if err == nil && mapped.DeletedAt == nil && mapped.GoogleSubject == googleSubject { + return mapped, nil + } + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return nil, err + } holder, err := scanUser(tx.QueryRow(ctx, `SELECT `+userColumns+` FROM users WHERE email = $1 FOR SHARE`, email)) if errors.Is(err, pgx.ErrNoRows) { @@ -6348,19 +6382,20 @@ func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSub return nil, err } if holder.DeletedAt != nil || holder.GoogleSubject != googleSubject { - return nil, ErrEmailConflict + // No evidence: fall through to the evidence-less path, whose + // tombstone check and insert decide the answer byte-for-byte. + return nil, nil } - var mapped bool + var pairMapped bool if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM external_principal_mappings WHERE issuer = $1 AND subject = $2)`, - externalIssuer, externalRef).Scan(&mapped); err != nil { + externalIssuer, externalRef).Scan(&pairMapped); err != nil { return nil, err } - if !mapped { - // A NEW mapping gets AttachExternalPrincipal's checks; replaying an - // existing one does not, so an adopted user paused afterwards still - // replays (and a pair mapped elsewhere still surfaces as a conflict - // from the mapping insert). + if !pairMapped { + // A NEW mapping gets AttachExternalPrincipal's checks. A pair that is + // already mapped (here necessarily to someone else) skips them and + // surfaces as ErrExternalPrincipalConflict from the mapping insert. var readOnly bool if err := tx.QueryRow(ctx, accountReadOnlySQL, holder.ID).Scan(&readOnly); err != nil { return nil, err From f198e4fb0132cf11dba6f6cc43eee54b9b958a64 Mon Sep 17 00:00:00 2001 From: Josh Zhang <39790535+jiashuoz@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:36:36 -0800 Subject: [PATCH 4/4] fix(identity): adopt only standard accounts, by a numeric subject, once per issuer Adversarial review found two ways to adopt an account that is not the caller's person: - Seeded accounts carry public, non-"bootstrap:" subjects (the prober's and the conformance fixtures'), so a caller that knew one could adopt a system account. google_subject must now be 1..255 ASCII digits, the shape of a Google subject, and only account_class = 'standard' is adoptable; any other class answers exactly as a mismatch. - A second external_ref presenting the same subject added a second live mapping to an account the issuer already maps, a delegated binding the control plane can never use. A new adoption now refuses with external_principal_conflict when the holder already has a mapping from that issuer. deployment.md states both rules and names the answers that reveal a matching subject (HMAC-only). Co-Authored-By: Claude Opus 5.5 --- docs/deployment.md | 2 +- internal/agent/provisioning_adopt_api_test.go | 1 + internal/identity/provision_adopt_test.go | 55 +++++++++++++++++++ internal/identity/store.go | 35 +++++++++--- 4 files changed, 83 insertions(+), 10 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 4605a96ef..64c4673fb 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -212,7 +212,7 @@ That leaves two real horizontal-scaling caveats: **Dashboard auth is Google OAuth plus an optional generic OIDC login.** [`internal/auth/auth.go`](../internal/auth/auth.go) imports `golang.org/x/oauth2/google` directly and the config exposes `google_client_id` / `google_client_secret`. [`internal/auth/oidc.go`](../internal/auth/oidc.go) additionally implements an off-by-default OpenID Connect relying party (`E2A_OIDC_ENABLED` + the `E2A_OIDC_*` vars above) for teams on Microsoft Entra, Okta, or another standards-compliant OIDC provider. Start the flow at `GET /api/auth/oidc/login`, which accepts the same optional `return_to` and `cli_callback`/`cli_state` query parameters as the Google login (same validation rules, same post-login behavior). It is an additional login path, not a Google OAuth replacement: it maps a configured ID-token claim to an existing e2a user and never provisions new ones, so accounts must already exist (e.g. via Google OAuth or `-bootstrap-email`) before OIDC login works for them. Adding `email` to `oidc.scopes` (`E2A_OIDC_SCOPES`) makes an OIDC login whose ID token asserts `email_verified` for the account's current email record owner-mailbox proof; enable it only against an IdP that sets `email_verified: true` solely after a mailbox confirmation and resets it when the address changes, because a false proof unlocks owner-mailbox sending for a restricted account and exempts sends to that address from the erase-defer check. The CLI and SDKs authenticate with API keys, which are provider-agnostic. -**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. The one exception is evidence-gated: a request that also carries `external_issuer` and `google_subject` (the identity provider's subject the control plane verified for this person) **adopts** the account holding the email when, and only when, that account's own `google_subject` is exactly equal. The account row is not changed; the `(external_issuer, external_ref)` mapping is created for it, and the response is `200 {"user_id": "...", "adopted": true}`. A replay resolves by that mapping, so it survives a later change of the account's email, but it must repeat the same `google_subject`: without it, the request is an ordinary one and gets `email_conflict`. A missing, different, or trashed match takes exactly the path a request without the field takes, so it gets the same bytes (`409 email_conflict`, or a tombstone refusal that precedes it). A new adoption applies attach's rules: an abuse-paused account returns `403 {"error":"account_read_only"}`, a tombstoned mapping subject `403 registration_refused`, and a pair already mapped to a different user `409 external_principal_conflict`. A non-empty `google_subject` without `external_issuer`, over 255 bytes, containing control characters, or starting with `bootstrap:` returns `400 {"error":"invalid_google_subject"}`. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. +**User provisioning for an external control plane is opt-in and internal-only.** When `E2A_PROVISIONING_ENABLED=true`, the server exposes `POST /api/internal/users/provision` (not part of the public `/v1` API or the OpenAPI spec) so an operator's external control plane can create e2a users ahead of their first sign-in. The caller sends `{"external_ref", "email", "name"?}` and authenticates with a hex HMAC-SHA256 of the raw request body in `X-E2A-Internal-Signature`, keyed by `E2A_PROVISIONING_SECRET` (env-only, deliberately separate from the limits internal API secret so each can be rotated independently). `external_ref` is the idempotency key — it becomes the row's `google_subject` (`bootstrap:`), so a replay returns `200` with the same `user_id`; a fresh create returns `201`; a different `external_ref` carrying an email another account already holds returns `409 {"error":"email_conflict"}` and never attaches or merges. The one exception is evidence-gated: a request that also carries `external_issuer` and `google_subject` (the identity provider's subject the control plane verified for this person) **adopts** the account holding the email when, and only when, that account's own `google_subject` is exactly equal and it is a `standard` account (internal, system and demo accounts are never adopted). The account row is not changed; the `(external_issuer, external_ref)` mapping is created for it, and the response is `200 {"user_id": "...", "adopted": true}`. A replay resolves by that mapping, so it survives a later change of the account's email, but it must repeat the same `google_subject`: without it, the request is an ordinary one and gets `email_conflict`. A missing, different, or trashed match takes exactly the path a request without the field takes, so it gets the same bytes (`409 email_conflict`, or a tombstone refusal that precedes it). A new adoption applies attach's rules: an abuse-paused account returns `403 {"error":"account_read_only"}`, a tombstoned mapping subject `403 registration_refused`, and a pair already mapped to a different user, or an account the issuer already maps under another `external_ref`, `409 external_principal_conflict`. These three answers do reveal that the subject matched; the endpoint is HMAC-authenticated, so only the operator's control plane can see them. A non-empty `google_subject` that is not 1–255 ASCII digits (the shape of a Google subject, which rules out synthetic `bootstrap:` and seeded fixture subjects), or that arrives without `external_issuer`, returns `400 {"error":"invalid_google_subject"}`. A ref that resolves to an account in the trash returns `409 {"error":"account_trashed"}` and writes nothing — restore is interactive only (the user signs in and chooses in the dashboard), so a control plane must treat it as terminal for that principal rather than retry. When identity tombstones are enabled, a subject or email held by a live tombstone (a recently deleted or abuse-closed account) returns `403 {"error":"registration_refused"}`, and `503 {"error":"registration_unavailable"}` means the tombstone key is not configured. Provisioning creates only the user row — no session, API key, or limits row. Disabled (the self-host default), the endpoint 503s. **Delegated access-token verification is opt-in and generic.** When `E2A_DELEGATED_ENABLED=true` (plus the `delegated:` config block), the server verifies short-lived, audience-bound OAuth 2.0 access tokens (RFC 9068, JOSE header `typ="at+jwt"`) minted by one configured OIDC issuer, so an external control plane can call the public `/v1` API on behalf of its signed-in humans without holding e2a credentials. e2a runs OIDC discovery against `issuer_url`, verifies the token's signature against the issuer's published JWKS, and pins the exact `issuer`/`audience`/`authorized_party`/singleton `scope`, the `exp − iat` lifetime, the required context claims (with optional allowed-value sets), and the absence of the forbidden claims — all deployment data, so OSS ships no operator-specific claim policy. A verified token maps its `(issuer, subject)` pair to an existing local user and acts with **account** scope, exactly like an account API key; it never provisions on token presentation, and an unmapped subject is a `401`. The feature is fully off by default and isolated: every existing credential path (API keys, OAuth `ate2a_`, agent JWTs, session cookies) keeps working unchanged, including through a total delegated-verifier outage (which fails delegated requests `503`, never the others). A compact JWT whose protected header says `typ="at+jwt"` is owned by this verifier even while it is disabled — it never falls through to the API-key path. Issuer *network* unavailability is not fatal to startup (discovery retries in the background); a malformed static `delegated:` policy is. diff --git a/internal/agent/provisioning_adopt_api_test.go b/internal/agent/provisioning_adopt_api_test.go index 12e84d42c..a26427540 100644 --- a/internal/agent/provisioning_adopt_api_test.go +++ b/internal/agent/provisioning_adopt_api_test.go @@ -146,6 +146,7 @@ func TestProvisionUser_GoogleSubjectValidation(t *testing.T) { "no external_issuer": string(withoutIssuer), "oversize subject": adoptBody("tcusr_x", "x@example.test", strings.Repeat("1", 256)), "control character": adoptBody("tcusr_x", "x@example.test", "1000\n0001"), + "non-numeric subject": adoptBody("tcusr_x", "x@example.test", "e2a-prober-system"), } for name, body := range cases { status, buf := provisionRaw(t, server, body) diff --git a/internal/identity/provision_adopt_test.go b/internal/identity/provision_adopt_test.go index c4723b37e..fa8c50680 100644 --- a/internal/identity/provision_adopt_test.go +++ b/internal/identity/provision_adopt_test.go @@ -437,3 +437,58 @@ func TestProvisionConcurrentAdoptionsOfOnePair(t *testing.T) { } } } + +// Only standard customer accounts are adoptable: a system account answers as +// a mismatch does, and writes no mapping. +func TestProvisionRefusesAdoptingNonStandardAccount(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + existing := newDirectSignup(t, store, "ops@example.test") + if err := store.SetAccountClass(ctx, existing.ID, "system"); err != nil { + t.Fatal(err) + } + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_ops", "ops@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrEmailConflict) { + t.Fatalf("err = %v, want ErrEmailConflict", err) + } + assertUnmapped(t, store, "tcusr_ops") +} + +// Seeded fixture subjects are public strings, not Google identities. +func TestProvisionRejectsNonGoogleSubjectShape(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + if _, err := store.CreateOrGetUser(ctx, "probe@example.test", "Probe", "e2a-prober-system"); err != nil { + t.Fatal(err) + } + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_probe", "probe@example.test", "", testIssuer, "e2a-prober-system") + if !errors.Is(err, identity.ErrInvalidGoogleSubject) { + t.Fatalf("err = %v, want ErrInvalidGoogleSubject", err) + } + assertUnmapped(t, store, "tcusr_probe") +} + +// A holder the issuer already maps under another ref is not adopted again. +func TestProvisionRefusesSecondPrincipalFromSameIssuer(t *testing.T) { + pool := testutil.TestDB(t) + store := identity.NewStore(pool) + ctx := context.Background() + newDirectSignup(t, store, "ada@example.test") + if _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_first", "ada@example.test", "", testIssuer, adoptGoogleSub); err != nil { + t.Fatal(err) + } + + _, _, _, err := store.ProvisionUserAdopting(ctx, + "tcusr_second", "ada@example.test", "", testIssuer, adoptGoogleSub) + if !errors.Is(err, identity.ErrExternalPrincipalConflict) { + t.Fatalf("err = %v, want ErrExternalPrincipalConflict", err) + } + assertUnmapped(t, store, "tcusr_second") +} diff --git a/internal/identity/store.go b/internal/identity/store.go index 9a70cf5aa..c5a09ac36 100644 --- a/internal/identity/store.go +++ b/internal/identity/store.go @@ -6291,16 +6291,17 @@ func (s *Store) ProvisionUser(ctx context.Context, externalRef, email, name, ext // be mapped under. var ErrInvalidGoogleSubject = errors.New("identity: google subject is not usable as adoption evidence") -// ValidGoogleSubject bounds adoption evidence: 1..255 bytes of valid UTF-8, -// no control characters (the Cc category), and never a synthetic -// "bootstrap:" subject, which names a control-plane-created user rather than -// proving anyone's identity. +// ValidGoogleSubject bounds adoption evidence to the shape of a Google +// account subject: 1..255 ASCII digits. Anything else is not a Google +// identity — in particular a synthetic "bootstrap:" subject (a +// control-plane-created user) or a seeded fixture subject such as the +// prober's, both of which are public strings rather than proof of a person. func ValidGoogleSubject(s string) bool { - if s == "" || len(s) > 255 || !utf8.ValidString(s) || strings.HasPrefix(s, "bootstrap:") { + if s == "" || len(s) > 255 { return false } - for _, r := range s { - if r < 0x20 || (r >= 0x7f && r <= 0x9f) { + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { return false } } @@ -6381,9 +6382,11 @@ func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSub if err != nil { return nil, err } - if holder.DeletedAt != nil || holder.GoogleSubject != googleSubject { + if holder.DeletedAt != nil || holder.GoogleSubject != googleSubject || holder.AccountClass != "standard" { // No evidence: fall through to the evidence-less path, whose - // tombstone check and insert decide the answer byte-for-byte. + // tombstone check and insert decide the answer byte-for-byte. Only a + // standard customer account is adoptable; internal, system and demo + // accounts are never handed to an external principal. return nil, nil } var pairMapped bool @@ -6396,6 +6399,20 @@ func (s *Store) adoptableUserTx(ctx context.Context, tx pgx.Tx, email, googleSub // A NEW mapping gets AttachExternalPrincipal's checks. A pair that is // already mapped (here necessarily to someone else) skips them and // surfaces as ErrExternalPrincipalConflict from the mapping insert. + // + // Adoption also binds at most one principal per issuer: a holder the + // issuer already maps under another ref belongs to that principal, and + // a second mapping would be a live delegated binding the control plane + // can never use (its own uniqueness refuses the second claim). + var issuerMapped bool + if err := tx.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM external_principal_mappings WHERE issuer = $1 AND user_id = $2)`, + externalIssuer, holder.ID).Scan(&issuerMapped); err != nil { + return nil, err + } + if issuerMapped { + return nil, ErrExternalPrincipalConflict + } var readOnly bool if err := tx.QueryRow(ctx, accountReadOnlySQL, holder.ID).Scan(&readOnly); err != nil { return nil, err