Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<ref>`), 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:<ref>`), 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.

Expand Down
2 changes: 1 addition & 1 deletion docs/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down
217 changes: 217 additions & 0 deletions internal/agent/provisioning_adopt_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
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, "[email protected]")

for attempt := 0; attempt < 2; attempt++ {
status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "[email protected]", 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, "[email protected]")

noSubject, _ := json.Marshal(map[string]string{
"external_issuer": attachTestIssuer, "external_ref": "tcusr_a", "email": "[email protected]",
})
wantStatus, want := provisionRaw(t, server, string(noSubject))
gotStatus, got := provisionRaw(t, server, adoptBody("tcusr_b", "[email protected]", "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", "[email protected]", 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, "[email protected]")
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", "[email protected]", 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": "[email protected]", "google_subject": adoptAPIGoogleSub,
})
cases := map[string]string{
"synthetic bootstrap subject": adoptBody("tcusr_x", "[email protected]", "bootstrap:tcusr_owner"),
"no external_issuer": string(withoutIssuer),
"oversize subject": adoptBody("tcusr_x", "[email protected]", strings.Repeat("1", 256)),
"control character": adoptBody("tcusr_x", "[email protected]", "1000\n0001"),
"non-numeric subject": adoptBody("tcusr_x", "[email protected]", "e2a-prober-system"),
}
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, "[email protected]")

if status, buf := provisionRaw(t, server, adoptBody("tcusr_ada", "[email protected]", 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)
}
}

// 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, "[email protected]")
store.SetTombstonePolicy(identity.TombstonePolicy{Enabled: true})

noSubject, _ := json.Marshal(map[string]string{
"external_issuer": attachTestIssuer, "external_ref": "tcusr_a", "email": "[email protected]",
})
wantStatus, want := provisionRaw(t, server, string(noSubject))
gotStatus, got := provisionRaw(t, server, adoptBody("tcusr_a", "[email protected]", "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, "[email protected]")
other, err := store.BootstrapUser(context.Background(), "[email protected]")
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", "[email protected]", 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)
}
}
Loading
Loading