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:
sam committed 2026-09-22 14:34:16 +10:00
1 parent 06800c621a
commit a7d6f71d5a
19 files changed
+1146 -88

No files matched your search

+126 -34
View File
@@ -5,7 +5,9 @@ import (
"context"
"errors"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -29,6 +31,84 @@ type Task struct {
Attempt int
}
// Actor is the identity that performed an action, and the principal whose
// authority permitted it.
//
// The two are separate fields because an agent acting under a person's standing
// approval is not the same fact as a person acting: a record that collapsed
// them would answer "who approved this" with the wrong identity. An empty
// Principal means UNATTRIBUTED -- no authority was recorded, which is a
// different fact from the actor authorising itself.
type Actor struct {
Identity identity.IdentityID
Kind identity.Kind
Principal identity.IdentityID
}
// ActorFor builds an actor from the identity a credential resolved to. The kind
// travels with the actor so an event can record that an agent acted without a
// consumer having to resolve the identity to find out.
func ActorFor(value identity.Identity) Actor {
return Actor{Identity: value.ID, Kind: value.Kind}
}
// AuthorisedBy records where an action's authority came from.
func (a Actor) AuthorisedBy(principal identity.IdentityID) Actor {
a.Principal = principal
return a
}
// Human reports whether a person performed the action. Only a human's action is
// recorded as a human's: the event kind describes the actor.
func (a Actor) Human() bool { return a.Kind == identity.KindUser }
// Attributed reports whether the action is attributed to an identity. An action
// with no identity is still recorded -- refusing it would hide the action from
// the timeline -- but its record claims nothing about who performed it, and its
// kind says so.
func (a Actor) Attributed() bool { return strings.TrimSpace(string(a.Identity)) != "" }
// describe renders the attribution for a human reading a task timeline.
func (a Actor) describe(verb string) string {
if !a.Attributed() {
return verb + " with no recorded actor"
}
text := verb + " by " + string(a.Identity)
if a.Kind != "" {
text += " (" + string(a.Kind) + ")"
}
if a.Principal != "" {
return text + ", authorised by " + string(a.Principal)
}
return text + ", no authorising principal"
}
// approvedKind and rejectedKind name what happened and who did it. There is no
// single kind for an approval: an agent's approval recorded as a human's is the
// falsehood this trio exists to prevent, and an action with no verified actor
// is recorded as a task-level event rather than credited to anyone.
func approvedKind(actor Actor) string {
switch {
case actor.Human():
return events.KindHumanApproved
case actor.Attributed():
return events.KindAgentApproved
default:
return events.KindTaskApproved
}
}
func rejectedKind(actor Actor) string {
switch {
case actor.Human():
return events.KindHumanRejected
case actor.Attributed():
return events.KindAgentRejected
default:
return events.KindTaskRejected
}
}
type Store interface {
TaskByID(context.Context, int64) (*Task, error)
Transition(context.Context, int64, string, string, string) error
@@ -49,9 +129,13 @@ type Service struct {
Warn func(string, ...any)
}
// Apply scopes chat requests to an identity. A nil identity denotes an
// authenticated dashboard operator, who may act across identities.
func (s Service) Apply(ctx context.Context, identity *string, id int64, action taskstate.Action) error {
// Apply scopes chat requests to an identity. A nil scope denotes a caller
// authenticated across identities, which is the dashboard's own credential;
// scope limits which task a chat identity may act on, and never says who acted.
//
// The actor is not derived from scope: scope is which tasks a caller may touch,
// actor is who touched one, and the two are only equal by coincidence.
func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action) error {
task, err := s.Store.TaskByID(ctx, id)
if err != nil {
return err
@@ -59,18 +143,18 @@ func (s Service) Apply(ctx context.Context, identity *string, id int64, action t
if task == nil {
return fmt.Errorf("task %d: %w", id, ErrNotFound)
}
if identity != nil && task.Identity != *identity {
return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *identity)
if scope != nil && task.Identity != *scope {
return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *scope)
}
if err := taskstate.CheckAction(task.Status, action); err != nil {
return fmt.Errorf("%w: %w", ErrConflict, err)
}
mutation, err := s.apply(ctx, task, identity, action)
mutation, err := s.apply(ctx, task, actor, action)
if err != nil {
return err
}
if mutation.verb != "" && task.ForgeBacked {
s.closeRejectedIssue(ctx, task, identity, mutation.verb)
s.closeRejectedIssue(ctx, task, actor, mutation.verb)
}
s.emit(ctx, mutation.event)
return nil
@@ -85,37 +169,48 @@ type outcome struct {
// record alongside it. Errors from the store are returned unwrapped: the
// caller maps them to a response, and the rules-level errors (ErrConflict)
// were already checked above.
func (s Service) apply(ctx context.Context, task *Task, identity *string, action taskstate.Action) (outcome, error) {
source := "the dashboard"
if identity != nil {
source = "chat"
}
o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Attempt: task.Attempt}}
func (s Service) apply(ctx context.Context, task *Task, actor Actor, action taskstate.Action) (outcome, error) {
o := outcome{event: s.attributed(task, actor)}
switch action {
case taskstate.ActionApprove:
err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement")
o.event.Kind, o.event.Detail = events.KindHumanApproved, "approved via "+source
o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved")
return o, err
case taskstate.ActionRetry:
return s.applyRetry(ctx, task, source, o)
return s.applyRetry(ctx, task, actor, o)
case taskstate.ActionStop:
return s.applyStop(ctx, task, source, o)
return s.applyStop(ctx, task, actor, o)
case taskstate.ActionReject:
o.event.Kind, o.event.Detail, o.verb = events.KindHumanRejected, "rejected via "+source, "rejected"
o.event.Kind, o.event.Detail, o.verb = rejectedKind(actor), actor.describe("rejected"), "rejected"
if task.Status == "running" && s.CancelTask != nil {
s.CancelTask(task.ID)
}
return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", "declined from "+source)
return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", actor.describe("declined"))
case taskstate.ActionCancel, taskstate.ActionAbandon:
return s.applyCancelOrAbandon(ctx, task, action, source, o)
return s.applyCancelOrAbandon(ctx, task, action, actor, o)
case taskstate.ActionArchive:
return s.applyArchive(ctx, task, source, o)
return s.applyArchive(ctx, task, actor, o)
default:
return o, fmt.Errorf("unsupported task action %q", action)
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
// attributed builds the event skeleton every action carries: the task, the run
// and both identities. Every event this service records passes through here, so
// no action can be recorded without its attribution.
func (s Service) attributed(task *Task, actor Actor) events.Event {
return events.Event{
TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo,
Issue: task.IssueNumber,
Attempt: task.Attempt,
ActorID: string(actor.Identity),
ActorKind: string(actor.Kind),
PrincipalID: string(actor.Principal),
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
limit := 0
if s.MaxRetries != nil {
limit = s.MaxRetries(task)
@@ -131,33 +226,33 @@ func (s Service) applyRetry(ctx context.Context, task *Task, source string, o ou
return o, fmt.Errorf("%w: %s", ErrConflict, reason)
}
err := s.Store.RetryTask(ctx, task.ID, "parked", "")
o.event.Kind, o.event.Detail = events.KindTaskRetried, "retried via "+source
o.event.Kind, o.event.Detail = events.KindTaskRetried, actor.describe("retried")
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_stage": task.Stage, "previous_reason": task.ParkReason}
return o, err
}
func (s Service) applyStop(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
func (s Service) applyStop(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
if s.CancelTask == nil {
return o, ErrUnavailable
}
o.event.Kind, o.event.Detail = events.KindTaskStopped, "stopped via "+source+"; recoverable work remains parked"
o.event.Kind, o.event.Detail = events.KindTaskStopped, actor.describe("stopped")+"; recoverable work remains parked"
if !s.CancelTask(task.ID) {
o.event.Detail = "no active execution was found; recoverable work was parked via " + source
o.event.Detail = "no active execution was found; recoverable work was parked, " + actor.describe("stopped")
}
return o, s.Store.Transition(ctx, task.ID, "running", "parked", o.event.Detail)
}
func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, source string, o outcome) (outcome, error) {
func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, actor Actor, o outcome) (outcome, error) {
from, kind, verb := "queued", events.KindTaskCancelled, "cancelled"
if action == taskstate.ActionAbandon {
from, kind, verb = "parked", events.KindTaskAbandoned, "abandoned"
}
o.event.Kind, o.event.Detail, o.verb = kind, verb+" via "+source, verb
o.event.Kind, o.event.Detail, o.verb = kind, actor.describe(verb), verb
return o, s.Store.Transition(ctx, task.ID, from, "closed_wont_do", o.event.Detail)
}
func (s Service) applyArchive(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, "archive requested via "+source
func (s Service) applyArchive(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, actor.describe("archive requested")
id, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, o.event)
if err != nil {
return o, err
@@ -171,15 +266,12 @@ func (s Service) applyArchive(ctx context.Context, task *Task, source string, o
return o, nil
}
func (s Service) closeRejectedIssue(ctx context.Context, task *Task, identity *string, verb string) {
func (s Service) closeRejectedIssue(ctx context.Context, task *Task, actor Actor, verb string) {
if s.CloseIssue == nil {
s.warn("task rejected but no forge is wired; the issue stays open and will be re-polled", "task", task.ID)
return
}
comment := fmt.Sprintf("Closing: this task was %s from the archie %s. Reopen the issue to have archie pick it up again.", verb, "dashboard")
if identity != nil {
comment = fmt.Sprintf("Closing: this task was %s from archie chat. Reopen the issue to have archie pick it up again.", verb)
}
comment := fmt.Sprintf("Closing: this task was %s in archie (%s). Reopen the issue to have archie pick it up again.", verb, actor.describe("actioned"))
if err := s.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
s.warn("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "err", err)
}
+211
View File
@@ -0,0 +1,211 @@
package taskactions
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
type fakeStore struct {
task *Task
events []events.Event
}
func (f *fakeStore) TaskByID(context.Context, int64) (*Task, error) { return f.task, nil }
func (f *fakeStore) Transition(context.Context, int64, string, string, string) error {
return nil
}
func (f *fakeStore) Requeue(context.Context, int64, string, string) error { return nil }
func (f *fakeStore) RetryTask(context.Context, int64, string, string) error {
return nil
}
func (f *fakeStore) ArchiveTask(_ context.Context, _ int64, _ string, e events.Event) (int64, error) {
f.events = append(f.events, e)
return int64(len(f.events)), nil
}
func (f *fakeStore) InsertEvent(_ context.Context, e events.Event) (int64, error) {
f.events = append(f.events, e)
return int64(len(f.events)), nil
}
func (f *fakeStore) last() events.Event {
if len(f.events) == 0 {
return events.Event{}
}
return f.events[len(f.events)-1]
}
const (
humanID = identity.IdentityID("20000000-0000-5000-8000-000000000001")
agentID = identity.IdentityID("20000000-0000-5000-8000-000000000002")
)
func humanActor() Actor {
return ActorFor(identity.Identity{ID: humanID, Kind: identity.KindUser, Lifecycle: identity.LifecycleActive})
}
func agentActor() Actor {
return ActorFor(identity.Identity{ID: agentID, Kind: identity.KindBot, Lifecycle: identity.LifecycleActive})
}
// TestEventKindDescribesTheActor is the rule that the bug turned on: an agent's
// approval was written down as a human's. The kind names the actor, so an
// agent's action can never be read as a person's, and an action with no verified
// actor is recorded as a task-level event that credits nobody.
func TestEventKindDescribesTheActor(t *testing.T) {
tests := []struct {
name string
action taskstate.Action
actor Actor
wantKind string
}{
{"a person approves", taskstate.ActionApprove, humanActor(), events.KindHumanApproved},
{"an agent approves", taskstate.ActionApprove, agentActor(), events.KindAgentApproved},
{"a person rejects", taskstate.ActionReject, humanActor(), events.KindHumanRejected},
{"an agent rejects", taskstate.ActionReject, agentActor(), events.KindAgentRejected},
{"an unattributed approval", taskstate.ActionApprove, Actor{}, events.KindTaskApproved},
{"an unattributed rejection", taskstate.ActionReject, Actor{}, events.KindTaskRejected},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, tc.actor, 7, tc.action); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.Kind != tc.wantKind {
t.Fatalf("event kind = %q, want %q", got.Kind, tc.wantKind)
}
if tc.actor.Human() && got.Kind == events.KindAgentApproved {
t.Fatal("a person's action was recorded as an agent's")
}
if tc.actor.Attributed() && !tc.actor.Human() && got.Kind == events.KindHumanApproved {
t.Fatal("an agent's action was recorded as a human approval")
}
})
}
}
// TestActorAndPrincipalAreRecordedSeparately is the two-attribution requirement:
// an agent acting under a person's standing authority records both, so "approved
// by came from me" is answerable from the record.
func TestActorAndPrincipalAreRecordedSeparately(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
actor := agentActor().AuthorisedBy(humanID)
if err := service.Apply(context.Background(), nil, actor, 7, taskstate.ActionApprove); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.ActorID != string(agentID) {
t.Fatalf("actor = %q, want %q", got.ActorID, agentID)
}
if got.ActorKind != string(identity.KindBot) {
t.Fatalf("actor kind = %q, want %q", got.ActorKind, identity.KindBot)
}
if got.PrincipalID != string(humanID) {
t.Fatalf("principal = %q, want %q", got.PrincipalID, humanID)
}
if got.Kind != events.KindAgentApproved {
t.Fatalf("event kind = %q, want %q", got.Kind, events.KindAgentApproved)
}
}
// TestUnattributedActionClaimsNoApprover: with no verified actor the record must
// not credit the actor's own authority, and must not name a human.
func TestUnattributedActionClaimsNoApprover(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, Actor{}, 7, taskstate.ActionApprove); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.ActorID != "" || got.ActorKind != "" || got.PrincipalID != "" {
t.Fatalf("unattributed action recorded an actor: %+v", got)
}
if got.Kind == events.KindHumanApproved || got.Kind == events.KindAgentApproved {
t.Fatalf("unattributed action claimed an actor through its kind: %q", got.Kind)
}
}
// TestEveryActionCarriesItsAttribution: no action path may record an event that
// skipped the attribution, including the ones that also close a forge issue.
func TestEveryActionCarriesItsAttribution(t *testing.T) {
actions := []struct {
action taskstate.Action
status string
}{
{taskstate.ActionApprove, "waiting_human"},
{taskstate.ActionReject, "waiting_human"},
{taskstate.ActionRetry, "parked"},
{taskstate.ActionStop, "running"},
{taskstate.ActionCancel, "queued"},
{taskstate.ActionAbandon, "parked"},
}
for _, tc := range actions {
t.Run(string(tc.action), func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: tc.status}}
service := Service{
Store: store,
CancelTask: func(int64) bool { return true },
}
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action); err != nil {
t.Fatalf("Apply(%s) error = %v", tc.action, err)
}
got := store.last()
if got.ActorID != string(agentID) || got.ActorKind != string(identity.KindBot) {
t.Fatalf("%s recorded without its actor: %+v", tc.action, got)
}
})
}
}
// TestScopeStillLimitsATaskButIsNotTheActor: scope answers which task a caller
// may touch. It is not an actor, and passing one must not attribute the action
// to it.
func TestScopeStillLimitsATaskButIsNotTheActor(t *testing.T) {
other := "sam"
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human", Identity: "archie"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove); err == nil {
t.Fatal("Apply() allowed an identity to act on another identity's task")
}
if len(store.events) != 0 {
t.Fatalf("a refused action recorded %d events", len(store.events))
}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove); err == nil {
t.Fatal("Apply() allowed a scoped caller to act on a foreign task")
}
}
func TestActorForCarriesTheKindAndLeavesTheActionUnattributedWithoutAPrincipal(t *testing.T) {
actor := agentActor()
if actor.Principal != "" {
t.Fatalf("ActorFor() set a principal: %q", actor.Principal)
}
if !actor.Attributed() {
t.Fatal("ActorFor() produced an unattributed actor for a real identity")
}
if (Actor{}).Attributed() {
t.Fatal("the zero Actor reported itself as attributed")
}
if (Actor{}).Human() {
t.Fatal("the zero Actor reported itself as a human")
}
}