feat(webui): verify a provider credential on a request path
The verifier was a library nothing called. A request now carries a credential or is refused: webui.Server.Authenticate resolves a presented bearer token to the identity that may act, and requireIdentity attaches it to the request context. With a provider configured that check replaces the shared token, so every request resolves to a named identity or is refused; with none, the shared-token gate stays for a loopback instance. Nothing about the caller is read from the request. The subject comes from the credential the provider signed and the identity is the record that subject is bound to, which is what makes attribution possible at all: a caller cannot assert who it is, it can only present what the provider gave it. A test sends an X-Archie-Identity header and an actor field in the body alongside a valid token and asserts the resolved identity is still the credential's. Refusals follow HTTP's own distinction: absent or unverifiable credentials are 401 and name the scheme, while a credential that verified for an identity that may not act is 403. Each is covered, because a refusal path with no test is a path nobody has watched refuse. The two state-store RPCs the dashboard needs to resolve a subject exist: ResolveIdentitySubject and BindIdentitySubject, with the client implementing identity.SubjectBinding (a narrower contract than Repository, so the administrative facade keeps its shape) and the server answering Unavailable rather than pretending when a process has no binding store. chat.proto carries the actor for the next step: actor_id, actor_kind and principal_id on ApplyOperatorTaskActionRequest, regenerated here. The transport can now carry an attribution and nothing fills it yet, which is why the dashboard still records task_approved rather than a human attribution. Not wired in production yet, and worth stating plainly: dep.Authenticate is a seam nothing sets, because the dashboard is served only by the UI process and that process is documented to take endpoint references only -- there is deliberately no config.Config in it. OIDC settings must therefore arrive as flags there, which is an existing design boundary I did not want to cross unilaterally. config.Oidc exists so the daemon-side wiring has somewhere to read from. Verified: task check exit 0 after this commit; focused webui run records the resolution and all four refusals.
This commit is contained in:
1 parent
faf32d44b5
commit
369ae695d4
14 files changed
+1391
-672
No files matched your search
+90
-2
@@ -1,9 +1,11 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -12,6 +14,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// tokenCookie carries the dashboard token once it has been exchanged from the
|
||||
@@ -89,8 +93,12 @@ func LoadOrCreateToken(path string) (string, error) {
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// requireToken wraps h with token authentication. A zero token disables the
|
||||
// check entirely, which is how loopback binds stay frictionless.
|
||||
// requireToken wraps h with the credential check this process is configured for.
|
||||
//
|
||||
// With an identity provider configured, the check is a provider-issued bearer
|
||||
// token that resolves to a named identity, and a request that cannot produce one
|
||||
// is refused. With no provider, the shared token is the gate, which is the
|
||||
// frictionless loopback behaviour a single-operator instance wants.
|
||||
//
|
||||
// The token may arrive as ?t=... once; it is then moved into a
|
||||
// SameSite=Strict, HttpOnly cookie and the caller redirected to the clean URL.
|
||||
@@ -98,6 +106,9 @@ func LoadOrCreateToken(path string) (string, error) {
|
||||
// The token is read per request rather than captured when the handler is
|
||||
// built, so a Server whose Token is set after Handler() is still protected.
|
||||
func (s *Server) requireToken(h http.Handler) http.Handler {
|
||||
if s.Authenticate != nil {
|
||||
return s.requireIdentity(h)
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Token == "" {
|
||||
h.ServeHTTP(w, r)
|
||||
@@ -149,6 +160,83 @@ func (s *Server) requireToken(h http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// requireIdentity authenticates a request from a provider-issued bearer token and
|
||||
// attaches the identity that token resolved to.
|
||||
//
|
||||
// Nothing about the caller is read from the request body, a header or a query
|
||||
// parameter: the subject comes from the credential the provider signed, and the
|
||||
// identity is the record that subject is bound to. That is why an agent's action
|
||||
// can be attributed at all -- a caller cannot assert who it is, it can only
|
||||
// present what the provider gave it.
|
||||
func (s *Server) requireIdentity(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
credential, ok := bearerCredential(r)
|
||||
if !ok {
|
||||
s.refuseUnidentified(w, r, identity.ErrNoCredential)
|
||||
return
|
||||
}
|
||||
value, err := s.Authenticate(r.Context(), credential)
|
||||
if err != nil {
|
||||
s.refuseUnidentified(w, r, err)
|
||||
return
|
||||
}
|
||||
h.ServeHTTP(w, r.WithContext(WithActingIdentity(r.Context(), value)))
|
||||
})
|
||||
}
|
||||
|
||||
// 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.
|
||||
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
|
||||
}
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
return token, token != ""
|
||||
}
|
||||
|
||||
// refuseUnidentified answers a request archie could not attribute to an identity.
|
||||
//
|
||||
// The status is HTTP's own distinction: absent or unverifiable credentials are
|
||||
// 401 and name the scheme, while a credential that verified for an identity that
|
||||
// may not act is 403 -- the caller proved who it is and is still not allowed.
|
||||
func (s *Server) refuseUnidentified(w http.ResponseWriter, r *http.Request, err error) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
allowed := errors.Is(err, identity.ErrIdentityInactive) || errors.Is(err, identity.ErrSubjectUnbound)
|
||||
status := http.StatusUnauthorized
|
||||
reason := "That credential was not accepted."
|
||||
switch {
|
||||
case errors.Is(err, identity.ErrIdentityInactive):
|
||||
status, reason = http.StatusForbidden, "That identity may not act."
|
||||
case errors.Is(err, identity.ErrSubjectUnbound):
|
||||
status, reason = http.StatusForbidden, "That credential is not bound to an identity here."
|
||||
default:
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="archie"`)
|
||||
}
|
||||
if !allowed && wantsDocument(r) {
|
||||
s.authPage(w, reason)
|
||||
return
|
||||
}
|
||||
http.Error(w, reason, status)
|
||||
}
|
||||
|
||||
type actingIdentityContextKey struct{}
|
||||
|
||||
// WithActingIdentity returns a context carrying the identity a request resolved
|
||||
// to, so a handler can attribute what it does without re-verifying anything.
|
||||
func WithActingIdentity(ctx context.Context, value identity.Identity) context.Context {
|
||||
return context.WithValue(ctx, actingIdentityContextKey{}, value)
|
||||
}
|
||||
|
||||
// ActingIdentity returns the identity a request resolved to, if it resolved to
|
||||
// one. A false result means the request was not authenticated, which is a
|
||||
// different fact from an authenticated request whose actor is unrecorded.
|
||||
func ActingIdentity(ctx context.Context) (identity.Identity, bool) {
|
||||
value, ok := ctx.Value(actingIdentityContextKey{}).(identity.Identity)
|
||||
return value, ok
|
||||
}
|
||||
|
||||
// wantsDocument reports whether a request is a browser navigation rather than an
|
||||
// API or stream call. A navigation sends text/html in Accept; fetch() sends */*
|
||||
// or a JSON type, and EventSource sends text/event-stream.
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
var testActingIdentity = identity.Identity{
|
||||
ID: "40000000-0000-5000-8000-000000000001",
|
||||
Kind: identity.KindUser,
|
||||
DisplayName: "sam",
|
||||
Lifecycle: identity.LifecycleActive,
|
||||
Version: 1,
|
||||
}
|
||||
|
||||
// withIdentityCheck builds the middleware over a stub provider, which is the
|
||||
// seam the dashboard sees: verification and binding are proved in
|
||||
// internal/infrastructure/oidc and internal/domain/identity, and what is proved
|
||||
// here is that a request either resolves or is refused.
|
||||
func withIdentityCheck(t *testing.T, authenticate func(context.Context, string) (identity.Identity, error)) http.Handler {
|
||||
t.Helper()
|
||||
s := &Server{Authenticate: authenticate}
|
||||
return s.requireToken(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
value, ok := ActingIdentity(r.Context())
|
||||
if !ok {
|
||||
t.Error("handler ran without a resolved identity")
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(string(value.ID)))
|
||||
}))
|
||||
}
|
||||
|
||||
func TestIdentityRequestResolvesToTheCredentialSubject(t *testing.T) {
|
||||
seen := ""
|
||||
handler := withIdentityCheck(t, func(_ context.Context, raw string) (identity.Identity, error) {
|
||||
seen = raw
|
||||
return testActingIdentity, nil
|
||||
})
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/tasks/7/action", strings.NewReader(`{"actor":"someone-else"}`))
|
||||
request.Header.Set("Authorization", "Bearer "+"a-provider-token")
|
||||
// A caller-supplied identity must not be consulted: the only source of the
|
||||
// acting identity is the credential the provider signed.
|
||||
request.Header.Set("X-Archie-Identity", "attacker-chosen")
|
||||
request.Header.Set("X-Archie-Actor", "attacker-chosen")
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)
|
||||
}
|
||||
if seen != "a-provider-token" {
|
||||
t.Fatalf("verifier saw %q, want the presented credential", seen)
|
||||
}
|
||||
if got := recorder.Body.String(); got != string(testActingIdentity.ID) {
|
||||
t.Fatalf("resolved identity = %q, want %q", got, testActingIdentity.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentityRequestRefusesEveryCallerItCannotAttribute(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
credential string
|
||||
authErr error
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "no credential presented",
|
||||
credential: "",
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "credential rejected",
|
||||
credential: "Bearer expired-or-foreign",
|
||||
authErr: identity.ErrCredentialRejected,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "subject not bound to an identity",
|
||||
credential: "Bearer valid-but-unknown",
|
||||
authErr: identity.ErrSubjectUnbound,
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
{
|
||||
name: "identity may not act",
|
||||
credential: "Bearer valid-but-suspended",
|
||||
authErr: identity.ErrIdentityInactive,
|
||||
wantStatus: http.StatusForbidden,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
handler := withIdentityCheck(t, func(_ context.Context, _ string) (identity.Identity, error) {
|
||||
if tc.authErr == nil {
|
||||
t.Fatal("the verifier was called with no credential to verify")
|
||||
}
|
||||
return identity.Identity{}, tc.authErr
|
||||
})
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/tasks", nil)
|
||||
if tc.credential != "" {
|
||||
request.Header.Set("Authorization", tc.credential)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, tc.wantStatus)
|
||||
}
|
||||
if tc.wantStatus == http.StatusUnauthorized &&
|
||||
recorder.Header().Get("WWW-Authenticate") == "" {
|
||||
t.Fatal("a 401 must name the scheme it accepts")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentityCheckReplacesTheSharedToken: with a provider configured the shared
|
||||
// token is no longer a way in, because a credential that names nobody cannot
|
||||
// attribute what it does.
|
||||
func TestIdentityCheckReplacesTheSharedToken(t *testing.T) {
|
||||
handler := withIdentityCheck(t, func(_ context.Context, raw string) (identity.Identity, error) {
|
||||
if raw == "" {
|
||||
return identity.Identity{}, identity.ErrNoCredential
|
||||
}
|
||||
return testActingIdentity, nil
|
||||
})
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.AddCookie(&http.Cookie{Name: tokenCookie, Value: "the-shared-token"})
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSharedTokenStillGatesAnInstanceWithNoProvider: with no provider configured
|
||||
// the shared token remains the gate, which is the loopback-friendly behaviour a
|
||||
// single-operator instance relies on.
|
||||
func TestSharedTokenStillGatesAnInstanceWithNoProvider(t *testing.T) {
|
||||
s := &Server{Token: ""}
|
||||
reached := false
|
||||
handler := s.requireToken(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }))
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
|
||||
if !reached {
|
||||
t.Fatal("a token-less loopback server refused a request")
|
||||
}
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,13 @@ type Server struct {
|
||||
// stay frictionless -- see IsLoopback.
|
||||
Token string
|
||||
|
||||
// Authenticate resolves a credential a request presented to the identity
|
||||
// that may act, and is the whole of the provider integration: verification
|
||||
// and binding both live behind it. Non-nil replaces the shared token, so
|
||||
// every request resolves to a named identity or is refused; nil keeps the
|
||||
// shared-token gate for an instance with no provider configured.
|
||||
Authenticate func(context.Context, string) (identity.Identity, error)
|
||||
|
||||
// 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.
|
||||
|
||||
Reference in new issue
Block a user