From 98052f785fe17ce042e4e5d5e18c5be352630b4b Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 22 Sep 2026 14:59:03 +1000 Subject: [PATCH] feat(webui): let a person sign in and act as themselves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last gap in the identity boundary: enabling a provider used to lock browsers out, because nothing could turn a sign-in into the credential the dashboard already verifies. Now a browser completes the authorization code flow with PKCE and the identity reaching the request context is the person who signed in. The audience is requested AT THE AUTHORIZATION ENDPOINT, not only at the token endpoint. Infra measured that a provider asked otherwise returns the audience empty, and this dashboard then refuses a perfectly valid token -- a failure that reads as a signing fault and is actually a missing query parameter. A test asserts the parameter is present, so it cannot quietly go missing. The flow is the libraries': discovery, the code exchange, PKCE generation and the challenge transformation are go-oidc and x/oauth2, so archie writes no protocol. The token returned by the exchange is verified through the SAME Verifier a presented token goes through, and the identity is then resolved through the same rule -- one Resolve now shared by Authenticate and the callback, so a browser sign-in cannot be accepted on terms a presented token would be refused on. Archie still issues no session. The callback stores the PROVIDER's token in an HttpOnly cookie and every later request re-verifies it, so what archie holds cannot outlive the provider's own decision. The callback checks the state it issued, and expires the state and PKCE verifier cookies on use. The sign-in routes mount on the bypass mux because they are how a caller becomes authenticated; gating them behind the credential they obtain would make signing in impossible. The client secret is never a flag: -oidc-client-secret-env names the environment variable holding it, so it cannot reach a process listing or a log line. No client id means no sign-in route and token verification is unaffected, which is what an agent-only deployment wants. Evidence, produced by driv·ng the flow rather than the seam: internal/webui/api_tasks_actor_test.go's TestBrowserSignInRecordsTheSignedInPerson walks sign-in -> callback -> cookie -> action and asserts the recorded actor is the signed-in person with human_approved. TestCallbackRefusesAMismatchedState asserts a replayed state is refused before any credential is verified. internal/infrastructure/oidc/flow_test.go runs the real flow against a test provider's own authorize and token endpoints, asserting the audience parameter, the PKCE challenge, a successful exchange, and a refused wrong verifier. Verified: task check exit 0 on this tree. --- cmd/archie-ui/main.go | 3 + go.mod | 2 +- internal/app/archieui/auth.go | 20 +++ internal/app/archieui/compose.go | 4 + internal/app/archieui/options.go | 10 ++ internal/app/archieui/run.go | 5 + internal/domain/identity/credential.go | 61 ++++++- internal/infrastructure/oidc/flow.go | 96 +++++++++++ internal/infrastructure/oidc/flow_test.go | 197 ++++++++++++++++++++++ internal/infrastructure/oidc/oidc_test.go | 16 ++ internal/webui/api_tasks_actor_test.go | 118 +++++++++++++ internal/webui/auth.go | 119 ++++++++++++- internal/webui/server.go | 14 ++ 13 files changed, 651 insertions(+), 14 deletions(-) create mode 100644 internal/infrastructure/oidc/flow.go create mode 100644 internal/infrastructure/oidc/flow_test.go diff --git a/cmd/archie-ui/main.go b/cmd/archie-ui/main.go index 6c7e59d2a..55cca4cf1 100644 --- a/cmd/archie-ui/main.go +++ b/cmd/archie-ui/main.go @@ -33,6 +33,9 @@ func run() int { flag.StringVar(&options.TokenFile, "token-file", "", "file holding the dashboard token, minted on first use") flag.StringVar(&options.OidcIssuer, "oidc-issuer", "", "identity provider issuer URL; requests must then carry a token it signed") flag.StringVar(&options.OidcAudience, "oidc-audience", "", "audience (resource identifier) this dashboard accepts tokens for; required with -oidc-issuer") + flag.StringVar(&options.OidcClientID, "oidc-client-id", "", "provider client id for browser sign-in; omitted means no sign-in flow") + flag.StringVar(&options.OidcClientSecretEnv, "oidc-client-secret-env", "", "name of the environment variable holding the sign-in client secret") + flag.StringVar(&options.OidcRedirectURL, "oidc-redirect-url", "", "callback URL registered at the provider (path must be /oauth2/callback)") flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target)") flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway") flag.StringVar(&options.State.Target, "state-target", "", "archie-state-store gRPC address (defaults to [services.state].target)") diff --git a/go.mod b/go.mod index aacbc568e..f57496476 100644 --- a/go.mod +++ b/go.mod @@ -51,7 +51,6 @@ require ( go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.57.0 // indirect golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect - golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.23.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect @@ -82,6 +81,7 @@ require ( github.com/samcharles93/ai-sdk v0.1.39 github.com/traefik/yaegi v0.16.1 golang.org/x/net v0.59.0 + golang.org/x/oauth2 v0.36.0 golang.org/x/term v0.46.0 google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e google.golang.org/protobuf v1.36.12 diff --git a/internal/app/archieui/auth.go b/internal/app/archieui/auth.go index 51b5b136a..a09f9f53a 100644 --- a/internal/app/archieui/auth.go +++ b/internal/app/archieui/auth.go @@ -3,6 +3,7 @@ package archieui import ( "context" "log/slog" + "os" "strings" "github.com/samcharles93/archie-core/internal/domain/identity" @@ -39,3 +40,22 @@ func dashboardAuthenticator(ctx context.Context, opts Options, subjects identity return value, err }, nil } + +// dashboardLoginFlow builds the browser sign-in flow from endpoint references and +// the operator's registration, or returns nil when none is configured. +// +// The secret is read from the environment variable the operator named and never +// logged, printed or stored. A client id is optional: an instance that only +// accepts agent tokens configures none, and then there is simply no sign-in +// route -- token verification is unaffected. +func dashboardLoginFlow(ctx context.Context, opts Options) (identity.LoginFlow, error) { + if strings.TrimSpace(opts.OidcIssuer) == "" || strings.TrimSpace(opts.OidcClientID) == "" { + return nil, nil + } + secret := "" + if name := strings.TrimSpace(opts.OidcClientSecretEnv); name != "" { + secret = os.Getenv(name) + } + return oidc.NewFlow(ctx, oidc.Config{Issuer: opts.OidcIssuer, Audience: opts.OidcAudience}, + opts.OidcClientID, secret, opts.OidcRedirectURL) +} diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go index 50a3b36ef..01c49b871 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -30,6 +30,9 @@ type deps struct { // Authenticate resolves a presented credential to the identity that may // act. Nil when no provider is configured, which keeps the shared token. Authenticate func(context.Context, string) (identity.Identity, error) + // Login drives the browser sign-in flow, or nil when no provider is + // configured for it. + Login identity.LoginFlow } // compose builds the dashboard server for the UI process. It sets exactly the @@ -71,6 +74,7 @@ func compose(d deps) *webui.Server { Log: d.Log, Token: d.Options.Token, Authenticate: d.Authenticate, + Login: d.Login, TrustForwardedHeaders: d.Options.trustForwardedHeaders(), Health: d.Health, ControlPlane: d.ControlPlane, diff --git a/internal/app/archieui/options.go b/internal/app/archieui/options.go index c94b38a2b..5384ec73b 100644 --- a/internal/app/archieui/options.go +++ b/internal/app/archieui/options.go @@ -66,6 +66,16 @@ type Options struct { // an issuer with no audience is refused rather than accepted without the check. OidcIssuer string OidcAudience string + // OidcClientID and OidcClientSecretEnv are the provider registration for the + // browser sign-in. The secret itself is never a flag: the flag names the + // environment variable holding it, so it cannot reach a process listing or a + // log line. No client id means no sign-in flow, which is what an instance + // that only accepts agent tokens wants. + OidcClientID string + OidcClientSecretEnv string + // OidcRedirectURL is the callback the provider returns the browser to. Its + // path must be /oauth2/callback, which is the route this process serves. + OidcRedirectURL string // TrustForwardedHeaders is tri-state so an explicit false on the command // line can override a configuration file that enables it. Nil means the // operator did not say, and the file (else false) decides. diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index a50fba15c..10bc4461c 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -48,6 +48,10 @@ func Run(ctx context.Context, options Options) error { if err != nil { return err } + login, err := dashboardLoginFlow(ctx, opts) + if err != nil { + return err + } srv := compose(deps{ Options: opts, @@ -58,6 +62,7 @@ func Run(ctx context.Context, options Options) error { ControlPlane: tasks.ControlPlane(), Identities: tasks, Authenticate: authenticate, + Login: login, }) // Live activity has no in-process bus in this process: the pump reads diff --git a/internal/domain/identity/credential.go b/internal/domain/identity/credential.go index fcd50a8e7..7030f1b78 100644 --- a/internal/domain/identity/credential.go +++ b/internal/domain/identity/credential.go @@ -48,6 +48,20 @@ type SubjectBinding interface { BindSubject(context.Context, IdentityID, Subject, Audit) error } +// LoginFlow is the browser authorization flow an identity provider requires, as +// a dashboard driving it needs it: the URL to send a browser to, then the +// completion of the flow when the browser returns. It is a contract here rather +// than in the transport because what it yields is an identity. +type LoginFlow interface { + // AuthCodeURL returns the provider URL for a sign-in and the PKCE verifier the + // callback must present with the code. + AuthCodeURL(state string) (string, string) + // Exchange completes the flow and returns what the provider proved. It + // verifies through the same path a presented token takes, so a token obtained + // by browser cannot be accepted on terms a presented token would be refused on. + Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) +} + // SubjectResolver resolves a verified provider subject to the identity bound to // it. It is deliberately narrower than Repository: authenticating a request // needs to resolve a subject, not to administer identities, so a consumer that @@ -61,6 +75,23 @@ type SubjectResolver interface { ResolveSubject(context.Context, Subject) (Identity, error) } +// ProviderSession is what a completed authorization flow yields: the credential +// the provider proved, and the provider's own token to present on later requests. +// Archie holds no session of its own -- the token belongs to the provider and is +// re-verified on every later request, so nothing archie stores can outlive it. +type ProviderSession struct { + Credential Credential + Token string + Expires time.Time +} + +// Expired reports whether a session's token is past the point of being worth +// presenting, so a caller can send the browser through the flow again instead of +// letting every request fail verification. +func (s ProviderSession) Expired(now time.Time) bool { + return !s.Expires.IsZero() && !now.Before(s.Expires) +} + var ( // ErrNoCredential means the request presented nothing to authenticate with. ErrNoCredential = errors.New("no credential presented") @@ -81,9 +112,7 @@ var ( // // The order is deliberate: the credential is verified by the provider's own // keys before anything it contains is used, so no field of an unverified token -// can select an identity. A suspended identity is refused even though its -// credential verified, because suspension is archie's decision and must not -// depend on the provider withdrawing a token. +// can select an identity. func Authenticate(ctx context.Context, subjects SubjectResolver, verifier Verifier, rawToken string) (Identity, Credential, error) { if strings.TrimSpace(rawToken) == "" { return Identity{}, Credential{}, ErrNoCredential @@ -95,20 +124,36 @@ func Authenticate(ctx context.Context, subjects SubjectResolver, verifier Verifi if err != nil { return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) } + value, err := Resolve(ctx, subjects, credential) + if err != nil { + return Identity{}, Credential{}, err + } + return value, credential, nil +} + +// Resolve turns an already-verified credential into the identity that may act. +// +// It is the single place the binding and lifecycle rules are applied, so a path +// that verified a credential itself -- the login callback exchanging an +// authorization code -- cannot reach a different verdict from the path that +// verified a presented token. A suspended identity is refused here even though +// its credential verified, because suspension is archie's decision and must not +// depend on the provider withdrawing a token. +func Resolve(ctx context.Context, subjects SubjectResolver, credential Credential) (Identity, error) { if err := credential.Subject.Validate(); err != nil { - return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) + return Identity{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err) } value, err := subjects.ResolveSubject(ctx, credential.Subject) if err != nil { if errors.Is(err, ErrNotFound) { - return Identity{}, Credential{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject) + return Identity{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject) } - return Identity{}, Credential{}, err + return Identity{}, err } if !value.CanAct() { - return Identity{}, Credential{}, fmt.Errorf("%w: %s is %s", ErrIdentityInactive, value.ID, value.Lifecycle) + return Identity{}, fmt.Errorf("%w: %s is %s", ErrIdentityInactive, value.ID, value.Lifecycle) } - return value, credential, nil + return value, nil } // CanAct reports whether an identity may perform actions. Only an active diff --git a/internal/infrastructure/oidc/flow.go b/internal/infrastructure/oidc/flow.go new file mode 100644 index 000000000..ad57100ab --- /dev/null +++ b/internal/infrastructure/oidc/flow.go @@ -0,0 +1,96 @@ +package oidc + +import ( + "context" + "fmt" + "strings" + + gooidc "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" + + "github.com/samcharles93/archie-core/internal/domain/identity" +) + +// Flow runs the authorization code flow with PKCE, so a person signs in at the +// provider and the dashboard learns who they are without archie ever seeing a +// password, holding a session, or writing any of the protocol itself: discovery, +// the code exchange, PKCE and token verification are the libraries'. +type Flow struct { + verifier *Verifier + oauth oauth2.Config + audience string +} + +// NewFlow discovers the provider and builds the browser flow. ClientID and the +// secret are the provider's registration for this dashboard; the secret is read +// from wherever the operator keeps it and is never logged or stored. +func NewFlow(ctx context.Context, cfg Config, clientID, clientSecret, redirectURL string) (*Flow, error) { + issuer := strings.TrimSpace(cfg.Issuer) + audience := strings.TrimSpace(cfg.Audience) + if issuer == "" { + return nil, fmt.Errorf("oidc: issuer is required") + } + if audience == "" { + return nil, fmt.Errorf("oidc: audience is required") + } + if strings.TrimSpace(clientID) == "" { + return nil, fmt.Errorf("oidc: client id is required for the browser flow") + } + if strings.TrimSpace(redirectURL) == "" { + return nil, fmt.Errorf("oidc: redirect URL is required for the browser flow") + } + provider, err := gooidc.NewProvider(ctx, issuer) + if err != nil { + return nil, fmt.Errorf("oidc: discover %q: %w", issuer, err) + } + return &Flow{ + verifier: &Verifier{verifier: provider.Verifier(&gooidc.Config{ClientID: audience})}, + oauth: oauth2.Config{ + ClientID: clientID, + ClientSecret: clientSecret, + Endpoint: provider.Endpoint(), + RedirectURL: redirectURL, + // openid is what makes the provider return a subject at all; profile + // and email are what make a name available for a display. + Scopes: []string{gooidc.ScopeOpenID, "profile", "email"}, + }, + audience: audience, + }, nil +} + +// AuthCodeURL returns the provider URL to send a browser to, and the PKCE +// verifier the callback must present with the code. +// +// The audience is requested HERE, at the authorization endpoint, and not only at +// the token endpoint: a provider that returns the audience empty otherwise mints +// a token this dashboard must refuse, and the refusal looks like a signing fault +// rather than a missing request parameter. The verifier is generated by the +// library, not by archie. +func (f *Flow) AuthCodeURL(state string) (string, string) { + codeVerifier := oauth2.GenerateVerifier() + url := f.oauth.AuthCodeURL(state, + oauth2.S256ChallengeOption(codeVerifier), + oauth2.SetAuthURLParam("audience", f.audience), + ) + return url, codeVerifier +} + +// Exchange completes the flow: it trades the code for the provider's tokens and +// verifies the access token through the same Verifier a presented token goes +// through. There is no second verification path here, so a token obtained by the +// browser cannot be accepted on terms a presented token would be refused on. +func (f *Flow) Exchange(ctx context.Context, code, codeVerifier string) (identity.ProviderSession, error) { + token, err := f.oauth.Exchange(ctx, strings.TrimSpace(code), oauth2.VerifierOption(codeVerifier)) + if err != nil { + return identity.ProviderSession{}, fmt.Errorf("oidc: exchange code: %w", err) + } + credential, err := f.verifier.Verify(ctx, token.AccessToken) + if err != nil { + return identity.ProviderSession{}, err + } + expires := token.Expiry + if credential.Expires.Before(expires) || expires.IsZero() { + expires = credential.Expires + } + return identity.ProviderSession{Credential: credential, Token: token.AccessToken, Expires: expires}, nil +} diff --git a/internal/infrastructure/oidc/flow_test.go b/internal/infrastructure/oidc/flow_test.go new file mode 100644 index 000000000..db992df40 --- /dev/null +++ b/internal/infrastructure/oidc/flow_test.go @@ -0,0 +1,197 @@ +package oidc + +import ( + "context" + "encoding/json" + "net/http" + "net/url" + "testing" + + "golang.org/x/oauth2" +) + +// TestAuthCodeURLRequestsTheAudienceAtTheAuthorizationEndpoint pins the trap infra +// measured: a provider that is asked for the audience only at the token endpoint +// returns a token with an empty audience, and the audience check then refuses a +// perfectly valid token. The fix is this query parameter, so a test fails if it +// ever goes missing. +func TestAuthCodeURLRequestsTheAudienceAtTheAuthorizationEndpoint(t *testing.T) { + p := newProvider(t) + flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience}, + "archie-web", "secret", p.server.URL+"/oauth2/callback") + if err != nil { + t.Fatalf("NewFlow() error = %v", err) + } + + raw, verifier := flow.AuthCodeURL("state-1") + parsed, err := url.Parse(raw) + if err != nil { + t.Fatalf("AuthCodeURL() returned an unparseable URL: %v", err) + } + query := parsed.Query() + if got := query.Get("audience"); got != testAudience { + t.Fatalf("audience = %q, want %q", got, testAudience) + } + if query.Get("code_challenge") == "" || query.Get("code_challenge_method") != "S256" { + t.Fatalf("PKCE is not on the authorization request: %v", query) + } + if verifier == "" { + t.Fatal("AuthCodeURL() returned no PKCE verifier for the callback") + } +} + +func TestNewFlowRefusesAnIncompleteConfiguration(t *testing.T) { + p := newProvider(t) + complete := Config{Issuer: p.server.URL, Audience: testAudience} + tests := []struct { + name string + cfg Config + clientID string + redirectURL string + }{ + {"no client id", complete, "", p.server.URL + "/oauth2/callback"}, + {"no redirect URL", complete, "archie-web", ""}, + {"no audience", Config{Issuer: p.server.URL}, "archie-web", p.server.URL + "/oauth2/callback"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if _, err := NewFlow(context.Background(), tc.cfg, tc.clientID, "secret", tc.redirectURL); err == nil { + t.Fatal("NewFlow() accepted a configuration it must refuse") + } + }) + } +} + +// TestExchangeCompletesARealAuthorizationCodeFlow drives the flow against the test +// provider's own authorize and token endpoints, so the code exchange and PKCE are +// exercised rather than stubbed. +func TestExchangeCompletesARealAuthorizationCodeFlow(t *testing.T) { + p := newProvider(t) + redirect := "http://dashboard.example/oauth2/callback" + flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience}, + "archie-web", "secret", redirect) + if err != nil { + t.Fatalf("NewFlow() error = %v", err) + } + + authURL, verifier := flow.AuthCodeURL("state-2") + code := p.authorize(t, authURL, "state-2") + + session, err := flow.Exchange(context.Background(), code, verifier) + if err != nil { + t.Fatalf("Exchange() error = %v", err) + } + if session.Credential.Subject.Subject != "a150ab4b-0000-0000-0000-000000000001" { + t.Fatalf("subject = %q, want the person's provider subject", session.Credential.Subject.Subject) + } + if session.Credential.Subject.Issuer != p.server.URL { + t.Fatalf("issuer = %q, want %q", session.Credential.Subject.Issuer, p.server.URL) + } + if session.Token == "" { + t.Fatal("Exchange() returned no token to present on later requests") + } +} + +// TestExchangeRefusesAWrongPKCEVerifier: the provider rejects the exchange, and +// archie must surface that as a refusal rather than a session. +func TestExchangeRefusesAWrongPKCEVerifier(t *testing.T) { + p := newProvider(t) + flow, err := NewFlow(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience}, + "archie-web", "secret", "http://dashboard.example/oauth2/callback") + if err != nil { + t.Fatalf("NewFlow() error = %v", err) + } + authURL, _ := flow.AuthCodeURL("state-3") + code := p.authorize(t, authURL, "state-3") + + if _, err := flow.Exchange(context.Background(), code, "not-the-verifier"); err == nil { + t.Fatal("Exchange() accepted a wrong PKCE verifier") + } +} + +// authorize walks a browser's side of the flow: it asks the provider's +// authorization endpoint and returns the code the provider sends back. +func (p *provider) authorize(t *testing.T, authURL, wantState string) string { + t.Helper() + request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authURL, nil) + if err != nil { + t.Fatalf("build authorize request: %v", err) + } + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, err := client.Do(request) + if err != nil { + t.Fatalf("authorize: %v", err) + } + defer func() { _ = response.Body.Close() }() + location := response.Header.Get("Location") + if location == "" { + t.Fatalf("authorize returned %d with no redirect", response.StatusCode) + } + parsed, err := url.Parse(location) + if err != nil { + t.Fatalf("authorize redirect is unparseable: %v", err) + } + if got := parsed.Query().Get("state"); got != wantState { + t.Fatalf("state = %q, want %q", got, wantState) + } + return parsed.Query().Get("code") +} + +// authorizeEndpoint is a faithful authorization endpoint: it requires the +// audience and the PKCE challenge, and it only issues a code for a verifier it +// later receives. +func (p *provider) authorizeEndpoint(t *testing.T) http.HandlerFunc { + t.Helper() + return func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + if query.Get("audience") == "" { + http.Error(w, "audience is required at the authorization endpoint", http.StatusBadRequest) + return + } + challenge := query.Get("code_challenge") + if challenge == "" || query.Get("code_challenge_method") != "S256" { + http.Error(w, "PKCE is required", http.StatusBadRequest) + return + } + code := "code-" + query.Get("state") + p.pending.Store(code, challenge) + location := query.Get("redirect_uri") + "?code=" + url.QueryEscape(code) + "&state=" + url.QueryEscape(query.Get("state")) + http.Redirect(w, r, location, http.StatusSeeOther) + } +} + +// tokenEndpoint trades a code for a signed access token, checking the PKCE +// verifier against the challenge the authorization endpoint recorded. +func (p *provider) tokenEndpoint(t *testing.T) http.HandlerFunc { + t.Helper() + return func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + code := r.PostForm.Get("code") + challenge, ok := p.pending.LoadAndDelete(code) + if !ok { + http.Error(w, "unknown code", http.StatusBadRequest) + return + } + want, ok := challenge.(string) + if !ok || pkceChallenge(r.PostForm.Get("code_verifier")) != want { + http.Error(w, "PKCE verification failed", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": p.personToken(t), + "token_type": "Bearer", + "expires_in": 3600, + "scope": "openid profile email", + }) + } +} + +// pkceChallenge computes the challenge the way the client library does, so the +// provider's check is the library's own transformation rather than archie's. +func pkceChallenge(verifier string) string { + return oauth2.S256ChallengeFromVerifier(verifier) +} diff --git a/internal/infrastructure/oidc/oidc_test.go b/internal/infrastructure/oidc/oidc_test.go index 8247ee002..11bf41b68 100644 --- a/internal/infrastructure/oidc/oidc_test.go +++ b/internal/infrastructure/oidc/oidc_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "slices" + "sync" "testing" "time" @@ -27,6 +28,8 @@ type provider struct { // other is a second, unrelated key used to sign a token the provider // never published, which is what a forged or foreign token looks like. other *rsa.PrivateKey + // pending holds the PKCE challenge each issued code must be redeemed with. + pending sync.Map } func newProvider(t *testing.T) *provider { @@ -53,6 +56,8 @@ func newProvider(t *testing.T) *provider { "id_token_signing_alg_values_supported": []string{"RS256"}, }) }) + mux.HandleFunc("/authorize", p.authorizeEndpoint(t)) + mux.HandleFunc("/token", p.tokenEndpoint(t)) mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{ @@ -97,6 +102,17 @@ func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*test return raw } +// personToken is what the token endpoint issues for a signed-in person: a +// subject, and the audience this dashboard checks. +func (p *provider) personToken(t *testing.T) string { + t.Helper() + return p.token(t, p.key, func(c *testClaims) { + c.Subject = "a150ab4b-0000-0000-0000-000000000001" + c.ClientID = "" + c.Scopes = []string{"openid", "profile", "email"} + }) +} + func (p *provider) verifier(t *testing.T) *Verifier { t.Helper() v, err := New(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience}) diff --git a/internal/webui/api_tasks_actor_test.go b/internal/webui/api_tasks_actor_test.go index 4a2d229e1..19b88551b 100644 --- a/internal/webui/api_tasks_actor_test.go +++ b/internal/webui/api_tasks_actor_test.go @@ -156,3 +156,121 @@ func TestActionRequestCannotChooseItsActor(t *testing.T) { t.Fatalf("status = %d, want 400 or 200 with the verified actor", w.Code) } } + +// stubFlow stands in for the provider's authorization-code flow. The flow itself +// is exercised against a real provider in internal/infrastructure/oidc; what is +// proved here is that the dashboard's browser path reaches the recorded actor. +type stubFlow struct { + authURL string + verifier string + session identity.ProviderSession +} + +func (f stubFlow) AuthCodeURL(state string) (string, string) { + return f.authURL + "?state=" + state, f.verifier +} + +func (f stubFlow) Exchange(context.Context, string, string) (identity.ProviderSession, error) { + return f.session, nil +} + +func cookieNamed(t *testing.T, response *http.Response, name string) *http.Cookie { + t.Helper() + for _, c := range response.Cookies() { + if c.Name == name && c.Value != "" { + return c + } + } + t.Fatalf("no %q cookie in the response", name) + return nil +} + +// TestBrowserSignInRecordsTheSignedInPerson drives the whole browser path: sign in +// through the provider, come back with a code, and then act on a task holding only +// the credential the flow stored -- the actor recorded must be that person. +func TestBrowserSignInRecordsTheSignedInPerson(t *testing.T) { + srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision") + person := identity.Identity{ + ID: "60000000-0000-5000-8000-000000000001", Kind: identity.KindUser, + DisplayName: "sam", Lifecycle: identity.LifecycleActive, + } + const token = "provider-access-token" + srv.Login = stubFlow{ + authURL: "http://provider.example/authorize", + verifier: "pkce-verifier", + session: identity.ProviderSession{ + Credential: identity.Credential{Subject: identity.Subject{Issuer: "https://idp.example", Subject: "sam"}}, + Token: token, + }, + } + srv.Authenticate = func(_ context.Context, raw string) (identity.Identity, error) { + if raw != token { + return identity.Identity{}, identity.ErrCredentialRejected + } + return person, nil + } + + // 1. A browser asks to sign in and is sent to the provider. + loginRequest := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/oauth2/login", nil) + loginResponse := httptest.NewRecorder() + srv.Handler().ServeHTTP(loginResponse, loginRequest) + if loginResponse.Code != http.StatusSeeOther { + t.Fatalf("login status = %d, want %d", loginResponse.Code, http.StatusSeeOther) + } + state := cookieNamed(t, loginResponse.Result(), loginStateCookie) + verifier := cookieNamed(t, loginResponse.Result(), loginVerifierCookie) + + // 2. The provider sends the browser back with a code. + callbackRequest := httptest.NewRequestWithContext(t.Context(), http.MethodGet, + "/oauth2/callback?code=a-code&state="+state.Value, nil) + callbackRequest.AddCookie(state) + callbackRequest.AddCookie(verifier) + callbackResponse := httptest.NewRecorder() + srv.Handler().ServeHTTP(callbackResponse, callbackRequest) + if callbackResponse.Code != http.StatusSeeOther { + t.Fatalf("callback status = %d, want %d (body %q)", callbackResponse.Code, http.StatusSeeOther, callbackResponse.Body.String()) + } + + // 3. The signed-in browser acts, presenting only what the flow stored. + stored := cookieNamed(t, callbackResponse.Result(), providerTokenCookie) + actionRequest := httptest.NewRequestWithContext(t.Context(), http.MethodPost, + "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`)) + actionRequest.Header.Set("Content-Type", "application/json") + actionRequest.Header.Set("X-Archie-CSRF", "1") + actionRequest.AddCookie(stored) + actionResponse := httptest.NewRecorder() + srv.Handler().ServeHTTP(actionResponse, actionRequest) + if actionResponse.Code != http.StatusOK { + t.Fatalf("action status = %d, want %d (body %q)", actionResponse.Code, http.StatusOK, actionResponse.Body.String()) + } + + recorded := approvalEvent(t, srv, task.ID) + if recorded.ActorID != string(person.ID) { + t.Fatalf("actor = %q, want the signed-in person %q", recorded.ActorID, person.ID) + } + if recorded.Kind != events.KindHumanApproved { + t.Fatalf("event kind = %q, want %q", recorded.Kind, events.KindHumanApproved) + } +} + +// TestCallbackRefusesAMismatchedState: the callback must check the state it issued, +// or a sign-in response could be replayed against another browser's flow. +func TestCallbackRefusesAMismatchedState(t *testing.T) { + srv, _, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision") + srv.Login = stubFlow{authURL: "http://provider.example/authorize", verifier: "pkce-verifier"} + srv.Authenticate = func(context.Context, string) (identity.Identity, error) { + t.Fatal("the callback verified a credential before checking its state") + return identity.Identity{}, nil + } + + request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, + "/oauth2/callback?code=a-code&state=not-the-state-i-issued", nil) + request.AddCookie(&http.Cookie{Name: loginStateCookie, Value: "the-state-i-issued"}) + request.AddCookie(&http.Cookie{Name: loginVerifierCookie, Value: "pkce-verifier"}) + response := httptest.NewRecorder() + srv.Handler().ServeHTTP(response, request) + + if response.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want %d", response.Code, http.StatusUnauthorized) + } +} diff --git a/internal/webui/auth.go b/internal/webui/auth.go index c6a467135..69cf23e87 100644 --- a/internal/webui/auth.go +++ b/internal/webui/auth.go @@ -20,7 +20,23 @@ import ( // tokenCookie carries the dashboard token once it has been exchanged from the // URL, so the token is not left sitting in browser history or referrers. -const tokenCookie = "archie_ui" +const ( + tokenCookie = "archie_ui" + // providerTokenCookie holds the provider's own access token after a browser + // sign-in. It is not a session archie issued: the token belongs to the + // provider and is verified on every request exactly as a presented header is, + // so nothing archie stores can outlive the provider's decision. + providerTokenCookie = "archie_provider_token" + // The sign-in flow's state and PKCE verifier live in short-lived cookies for + // the duration of the redirect, scoped to the callback path. + loginStateCookie = "archie_login_state" + loginVerifierCookie = "archie_login_verifier" + loginCookieMaxAge = 600 + // loginRoute and loginCallbackRoute must match the redirect URI registered at + // the provider: the provider returns the browser to the path it was given. + loginRoute = "GET /oauth2/login" + loginCallbackRoute = "GET /oauth2/callback" +) // IsLoopback reports whether a listen address is reachable only from this // machine. @@ -186,14 +202,107 @@ func (s *Server) requireIdentity(h http.Handler) http.Handler { // bearerCredential reads the credential a request presented. An empty token is // reported as absent rather than as a rejected one: there is nothing to verify. +// +// A browser cannot set a header on a navigation, so after the sign-in flow the +// provider's token is read from its cookie. That cookie holds the provider's +// credential, not an archie session: it is verified here on every request. func bearerCredential(r *http.Request) (string, bool) { const prefix = "Bearer " header := r.Header.Get("Authorization") - if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) { - return "", false + if len(header) > len(prefix) && strings.EqualFold(header[:len(prefix)], prefix) { + if token := strings.TrimSpace(header[len(prefix):]); token != "" { + return token, true + } } - token := strings.TrimSpace(header[len(prefix):]) - return token, token != "" + if c, err := r.Cookie(providerTokenCookie); err == nil && strings.TrimSpace(c.Value) != "" { + return c.Value, true + } + return "", false +} + +// handleLogin sends a browser to the provider with the audience requested at the +// authorization endpoint, and keeps the state and PKCE verifier the callback needs +// in cookies scoped to the callback path. +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + if s.Login == nil { + http.NotFound(w, r) + return + } + state, err := randomToken() + if err != nil { + http.Error(w, "could not start sign-in", http.StatusInternalServerError) + return + } + url, verifier := s.Login.AuthCodeURL(state) + setFlowCookie(w, r, loginStateCookie, state) + setFlowCookie(w, r, loginVerifierCookie, verifier) + http.Redirect(w, r, url, http.StatusSeeOther) +} + +// handleCallback completes the flow. It checks the state it issued, exchanges the +// code with the PKCE verifier it issued, and then resolves the resulting token +// through the same check every other request goes through -- so a browser sign-in +// cannot be accepted on terms a presented token would be refused on. +func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { + if s.Login == nil || s.Authenticate == nil { + http.NotFound(w, r) + return + } + query := r.URL.Query() + if providerErr := query.Get("error"); providerErr != "" { + s.refuseUnidentified(w, r, fmt.Errorf("%w: provider returned %s", identity.ErrCredentialRejected, providerErr)) + return + } + state, stateErr := r.Cookie(loginStateCookie) + if stateErr != nil || !tokenEqual(state.Value, query.Get("state")) { + s.refuseUnidentified(w, r, fmt.Errorf("%w: sign-in state did not match", identity.ErrCredentialRejected)) + return + } + verifier, verifierErr := r.Cookie(loginVerifierCookie) + if verifierErr != nil || strings.TrimSpace(verifier.Value) == "" { + s.refuseUnidentified(w, r, fmt.Errorf("%w: sign-in verifier is missing", identity.ErrCredentialRejected)) + return + } + session, err := s.Login.Exchange(r.Context(), query.Get("code"), verifier.Value) + if err != nil { + s.refuseUnidentified(w, r, err) + return + } + if _, err := s.Authenticate(r.Context(), session.Token); err != nil { + s.refuseUnidentified(w, r, err) + return + } + clearFlowCookie(w, r, loginStateCookie) + clearFlowCookie(w, r, loginVerifierCookie) + http.SetCookie(w, &http.Cookie{ + Name: providerTokenCookie, Value: session.Token, Path: "/", + HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, + }) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func setFlowCookie(w http.ResponseWriter, r *http.Request, name, value string) { + http.SetCookie(w, &http.Cookie{ + Name: name, Value: value, Path: "/oauth2", + HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil, + MaxAge: loginCookieMaxAge, + }) +} + +func clearFlowCookie(w http.ResponseWriter, r *http.Request, name string) { + http.SetCookie(w, &http.Cookie{ + Name: name, Value: "", Path: "/oauth2", + HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: r.TLS != nil, MaxAge: -1, + }) +} + +// randomToken returns a fresh URL-safe nonce for a sign-in's state. +func randomToken() (string, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(raw), nil } // refuseUnidentified answers a request archie could not attribute to an identity. diff --git a/internal/webui/server.go b/internal/webui/server.go index 2fe058297..d8e275e76 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -107,6 +107,13 @@ type Server struct { // shared-token gate for an instance with no provider configured. Authenticate func(context.Context, string) (identity.Identity, error) + // Login drives the provider's browser flow, so a person can sign in and the + // dashboard learns who they are. Nil removes the sign-in routes, which is what + // an instance with no provider configured gets. It is separate from + // Authenticate because a caller may present a token without ever signing in + // through a browser -- an agent does exactly that. + Login identity.LoginFlow + // Events publishes operator actions so they reach the task timeline and // the live activity stream. Optional: nil means the action is recorded // in the store but invisible to anyone watching. @@ -309,6 +316,13 @@ func (s *Server) Handler() http.Handler { top := http.NewServeMux() top.HandleFunc("GET /healthz", s.handleHealthz) top.HandleFunc("GET /health", s.handleHealth) + // The sign-in routes sit on the bypass mux because they are how a caller + // becomes authenticated: gating them behind the credential they obtain would + // make signing in impossible. + if s.Login != nil { + top.HandleFunc(loginRoute, s.handleLogin) + top.HandleFunc(loginCallbackRoute, s.handleCallback) + } if s.CaptureIntake != nil { top.Handle(captureIntakeRoute, s.CaptureIntake) }