feat(identity): verify provider tokens and attribute task actions to their actor
Two halves of one boundary: a credential resolves to an identity, and an action records which identity acted and whose authority it used. resource server. internal/infrastructure/oidc verifies a provider-issued bearer token against the provider's published keys, using an OSS OIDC library: archie compares no signature, validates no claim and rotates no key itself, holds no client secret and issues no session, so a compromised archie cannot mint an identity. Audience is required rather than optional -- a token minted for another service must not authenticate here -- and discovery happens at construction, so an unreachable provider is a startup failure rather than a request-time surprise. identity.Authenticate is the single place a credential becomes an identity, and it refuses in four distinguishable ways: no credential presented, a credential that did not verify (wrong key, expired, wrong issuer, wrong audience, malformed), a verified subject with no identity bound to it, and an identity that may not act. The order is deliberate: verification happens before any field of the token is used, so nothing an unverified token carries 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. The binding is the second bridge beside the legacy-name alias: identity_subjects keys (issuer, subject) so the same subject string from another issuer is a different caller, and rebinding moves a subject so two identities can never claim one provider subject. The contract Authenticate needs is SubjectResolver, narrower than Repository, so a consumer that only authenticates does not take the whole identity CRUD surface -- and staterpc.Client, which asserts Repository, does not need a new RPC to satisfy it. attribution. taskactions now records two identities per action: the acting identity and the authorising principal, both on the event row as new columns added through the existing migration table. The rule that the bug turned on is enforced by the event kind describing the actor: a person's approval is human_approved, an agent's is agent_approved, and an action with no verified actor is task_approved, a task-level event that credits nobody. An agent acting under a person's standing approval records itself as the actor and that person as the principal, so "approved by came from me" is answerable from the record rather than asserted. Scope and actor are separated: scope decides which task a caller may touch and is never promoted into an actor, because the dashboard's credential is a shared token and possession of it is not evidence that a person was at the keyboard. That last point is a deliberate fidelity trade, and the reason the transport is not wired: the dashboard action path passes no actor yet, so dashboard approvals are now recorded as task_approved rather than claimed as a human's. Recording nothing false is the requirement; naming the human verifiably needs the dashboard to authenticate a token and resolve it, which needs two new state-store RPCs (ResolveIdentitySubject, BindIdentitySubject) -- the next piece, not a rewrite: the verifier is a one-method interface, so introspection would be a second implementation of it. Verified: task check exit 0; focused runs recorded in the handoff. Opaque authelia_at_ tokens were inspected rather than assumed and cannot be verified against public keys; infra is configuring access_token_signed_response_alg RS256 on the archie client, with audience https://archie.catlow.cloud and issuer https://auth.catlow.cloud.
This commit is contained in:
19 files changed
+1146
-88
No files matched your search
@@ -23,6 +23,9 @@ CREATE TABLE IF NOT EXISTS events (
|
||||
workflow TEXT NOT NULL DEFAULT '',
|
||||
stage TEXT NOT NULL DEFAULT '',
|
||||
attempt INTEGER NOT NULL DEFAULT 0,
|
||||
actor_id TEXT NOT NULL DEFAULT '',
|
||||
actor_kind TEXT NOT NULL DEFAULT '',
|
||||
principal_id TEXT NOT NULL DEFAULT '',
|
||||
detail TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL DEFAULT '{}'
|
||||
);
|
||||
@@ -48,10 +51,11 @@ func insertEvent(ctx context.Context, execer eventExecer, e events.Event) (int64
|
||||
data = fmt.Appendf(nil, `{"marshal_error":%q}`, err.Error())
|
||||
}
|
||||
res, err := execer.ExecContext(ctx, `
|
||||
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
e.At.UTC().Format(time.RFC3339Nano), e.Kind, e.TaskID, e.Repo, e.Issue,
|
||||
e.Workflow, e.Stage, e.Attempt, clip(e.Detail, 4000), string(data))
|
||||
e.Workflow, e.Stage, e.Attempt, e.ActorID, e.ActorKind, e.PrincipalID,
|
||||
clip(e.Detail, 4000), string(data))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -66,7 +70,8 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
|
||||
var e events.Event
|
||||
var at, data string
|
||||
if err := rows.Scan(&e.ID, &at, &e.Kind, &e.TaskID, &e.Repo, &e.Issue,
|
||||
&e.Workflow, &e.Stage, &e.Attempt, &e.Detail, &data); err != nil {
|
||||
&e.Workflow, &e.Stage, &e.Attempt, &e.ActorID, &e.ActorKind,
|
||||
&e.PrincipalID, &e.Detail, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.At, _ = time.Parse(time.RFC3339Nano, at)
|
||||
@@ -76,7 +81,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data"
|
||||
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data"
|
||||
|
||||
// EventsSince returns up to limit events with id > sinceID, oldest
|
||||
// first -- SSE catch-up and the live feed.
|
||||
|
||||
@@ -23,6 +23,10 @@ CREATE TABLE IF NOT EXISTS identity_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
|
||||
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL,
|
||||
actor_id TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS identity_subjects (
|
||||
issuer TEXT NOT NULL, subject TEXT NOT NULL, identity_id TEXT NOT NULL REFERENCES identities(id),
|
||||
bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject)
|
||||
);`
|
||||
|
||||
const identityTimeLayout = time.RFC3339Nano
|
||||
@@ -130,6 +134,54 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
|
||||
return next, tx.Commit()
|
||||
}
|
||||
|
||||
// ResolveSubject returns the identity bound to a provider subject, so a
|
||||
// credential that verified against the provider's keys selects an identity
|
||||
// archie already knows rather than creating one.
|
||||
func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) {
|
||||
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at FROM identities i JOIN identity_subjects b ON b.identity_id=i.id WHERE b.issuer=? AND b.subject=?`, subject.Issuer, subject.Subject))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return identity.Identity{}, identity.ErrNotFound
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
// BindSubject binds an identity to the provider subject that asserts it. The
|
||||
// binding is audited like any other identity mutation: who authorised a caller
|
||||
// to act as this identity is the question the record has to answer later.
|
||||
// Rebinding an already-bound subject moves it, because a subject that changed
|
||||
// hands must resolve to whoever it belongs to now.
|
||||
func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
|
||||
if err := subject.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
|
||||
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
|
||||
}
|
||||
now := audit.At.UTC()
|
||||
if now.IsZero() {
|
||||
now = time.Now().UTC()
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
current, err := scanIdentity(tx.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return identity.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO identity_subjects(issuer,subject,identity_id,bound_at) VALUES(?,?,?,?) ON CONFLICT(issuer,subject) DO UPDATE SET identity_id=excluded.identity_id, bound_at=excluded.bound_at`, subject.Issuer, subject.Subject, id, now.Format(identityTimeLayout)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = insertIdentityEvent(ctx, tx, current, identity.Event{IdentityID: id, Type: "bind_subject", From: current.Lifecycle, To: current.Lifecycle, DisplayName: subject.Subject}, audit, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
|
||||
values := append([]struct {
|
||||
id identity.IdentityID
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
func bindAudit(requestID string) identity.Audit {
|
||||
return identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: requestID, At: time.Now().UTC()}
|
||||
}
|
||||
|
||||
func newTestIdentity(t *testing.T, s *Store, id identity.IdentityID, kind identity.Kind, name string) identity.Identity {
|
||||
t.Helper()
|
||||
value, err := identity.New(id, kind, name)
|
||||
if err != nil {
|
||||
t.Fatalf("identity.New() error = %v", err)
|
||||
}
|
||||
created, err := s.Create(context.Background(), value, bindAudit("create:"+string(id)))
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
return created
|
||||
}
|
||||
|
||||
// TestResolveSubjectReturnsTheBoundIdentity: a verified provider subject selects
|
||||
// the identity it is bound to, which is what lets a credential resolve to a
|
||||
// record archie already knows rather than creating one.
|
||||
func TestResolveSubjectReturnsTheBoundIdentity(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
agent := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000001"), identity.KindBot, "archie-agent")
|
||||
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
|
||||
|
||||
if err := s.BindSubject(ctx, agent.ID, subject, bindAudit("bind:1")); err != nil {
|
||||
t.Fatalf("BindSubject() error = %v", err)
|
||||
}
|
||||
|
||||
got, err := s.ResolveSubject(ctx, subject)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveSubject() error = %v", err)
|
||||
}
|
||||
if got.ID != agent.ID || got.Kind != identity.KindBot {
|
||||
t.Fatalf("ResolveSubject() = %+v, want %+v", got, agent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveSubjectIsKeyedOnIssuerAndSubject: the same subject string from a
|
||||
// different issuer is a different caller, so it must not resolve.
|
||||
func TestResolveSubjectIsKeyedOnIssuerAndSubject(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
agent := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000002"), identity.KindBot, "archie-agent")
|
||||
bound := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
|
||||
if err := s.BindSubject(ctx, agent.ID, bound, bindAudit("bind:2")); err != nil {
|
||||
t.Fatalf("BindSubject() error = %v", err)
|
||||
}
|
||||
|
||||
others := []struct {
|
||||
name string
|
||||
subject identity.Subject
|
||||
}{
|
||||
{"another issuer, same subject", identity.Subject{Issuer: "https://elsewhere.example", Subject: "archie"}},
|
||||
{"same issuer, another subject", identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "someone-else"}},
|
||||
}
|
||||
for _, tc := range others {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := s.ResolveSubject(ctx, tc.subject); !errors.Is(err, identity.ErrNotFound) {
|
||||
t.Fatalf("ResolveSubject() error = %v, want %v", err, identity.ErrNotFound)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindSubjectMovesAnAlreadyBoundSubject: when a subject changes hands it
|
||||
// resolves to whoever holds it now, so a reassignment cannot leave two identities
|
||||
// claiming one provider subject.
|
||||
func TestBindSubjectMovesAnAlreadyBoundSubject(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
first := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000003"), identity.KindBot, "first-agent")
|
||||
second := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000004"), identity.KindBot, "second-agent")
|
||||
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
|
||||
|
||||
if err := s.BindSubject(ctx, first.ID, subject, bindAudit("bind:3")); err != nil {
|
||||
t.Fatalf("BindSubject() error = %v", err)
|
||||
}
|
||||
if err := s.BindSubject(ctx, second.ID, subject, bindAudit("bind:4")); err != nil {
|
||||
t.Fatalf("rebind error = %v", err)
|
||||
}
|
||||
|
||||
got, err := s.ResolveSubject(ctx, subject)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveSubject() error = %v", err)
|
||||
}
|
||||
if got.ID != second.ID {
|
||||
t.Fatalf("ResolveSubject() = %s, want %s", got.ID, second.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindSubjectRequiresAuditAndAKnownIdentity(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
|
||||
|
||||
if err := s.BindSubject(ctx, identity.SystemID, subject, identity.Audit{}); err == nil {
|
||||
t.Fatal("BindSubject() accepted a binding with no audit")
|
||||
}
|
||||
if err := s.BindSubject(ctx, identity.IdentityID("does-not-exist"), subject, bindAudit("bind:5")); !errors.Is(err, identity.ErrNotFound) {
|
||||
t.Fatalf("BindSubject() error = %v, want %v", err, identity.ErrNotFound)
|
||||
}
|
||||
if err := s.BindSubject(ctx, identity.SystemID, identity.Subject{}, bindAudit("bind:6")); err == nil {
|
||||
t.Fatal("BindSubject() accepted an incomplete subject")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEventAttributionSurvivesTheRoundTrip: the attributions are only useful if
|
||||
// they come back out of the store, so a reader can answer who acted and whose
|
||||
// authority they used.
|
||||
func TestEventAttributionSurvivesTheRoundTrip(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
inserted, err := s.InsertEvent(ctx, events.Event{
|
||||
Kind: events.KindAgentApproved,
|
||||
TaskID: 11,
|
||||
ActorID: "30000000-0000-5000-8000-000000000001",
|
||||
ActorKind: string(identity.KindBot),
|
||||
PrincipalID: "30000000-0000-5000-8000-000000000009",
|
||||
Detail: "approved by an agent",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEvent() error = %v", err)
|
||||
}
|
||||
|
||||
got, err := s.TaskEvents(ctx, 11)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents() error = %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("TaskEvents() returned %d events, want 1", len(got))
|
||||
}
|
||||
e := got[0]
|
||||
if e.ID != inserted {
|
||||
t.Fatalf("event id = %d, want %d", e.ID, inserted)
|
||||
}
|
||||
if e.Kind != events.KindAgentApproved {
|
||||
t.Fatalf("kind = %q, want %q", e.Kind, events.KindAgentApproved)
|
||||
}
|
||||
if e.ActorID == "" || e.ActorKind != string(identity.KindBot) || e.PrincipalID == "" {
|
||||
t.Fatalf("attribution did not survive the round trip: %+v", e)
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,9 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
|
||||
{"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`},
|
||||
{"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`},
|
||||
{"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`},
|
||||
{"events", "actor_id", `ALTER TABLE events ADD COLUMN actor_id TEXT NOT NULL DEFAULT ''`},
|
||||
{"events", "actor_kind", `ALTER TABLE events ADD COLUMN actor_kind TEXT NOT NULL DEFAULT ''`},
|
||||
{"events", "principal_id", `ALTER TABLE events ADD COLUMN principal_id TEXT NOT NULL DEFAULT ''`},
|
||||
}
|
||||
for _, migration := range migrations {
|
||||
present := columns
|
||||
|
||||
Reference in new issue
Block a user