Skip to content

feat(identity): caller identity threaded end to end (agent-identity Track A) - #430

Closed
jhrozek wants to merge 46 commits into
mainfrom
acc/caller-identity
Closed

jhrozek wants to merge 46 commits into
mainfrom
acc/caller-identity

Conversation

@jhrozek

@jhrozek jhrozek commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

No description provided.

jhrozek and others added 30 commits August 10, 2026 10:30
Track A of the agent-identity model: accept a verified principal at the
edge, thread it through every port caller, and durably record the owner of
each session and schedule. No enforcement, no signing.

Co-Authored-By: Claude Opus 5 <[email protected]>
…bels (#367)

Scenario 0 of docs/acceptance/caller-identity.md — the joint field-prep
commit for the caller-identity track (Owner) and Track C (Authority), so
the contended engine/api/*.txt regeneration and CHANGELOG note are paid
once.

- session.Principal {Issuer, Subject, GrantType, Name}: identity is the
  (Issuer, Subject) PAIR, never Subject alone. No scopes, no authority,
  no credentials, no claims map. Absent identity is a nil *Principal,
  never a fabricated anonymous one (ADR 0100 decision 1).
- session.GrantType: closed three-value enum (user / client_credentials
  / system) with a Valid predicate; the zero value is not a member.
- session.Authority: Track C's placeholder, INERT here — nothing reads
  or writes it beyond the snapshot round-trip.
- Session.Owner / Session.Authority stamped through the WRITE-ONCE
  Session.RestoreLabels: a different owner over a set one returns
  session.ErrOwnerAlreadySet; a nil owner is the ownerless no-auth path
  and does not burn the slot; the owner is stored as a copy.
- sessnap.Snapshot gains owner/authority, both omitempty, restored via
  that aggregate method. RestoreState's signature is deliberately
  UNCHANGED (a trailing parameter is Changed/breaking under
  engine/COMPATIBILITY.md; a direct-assignment field is Added/minor).
  A pre-ship snapshot restores to a nil owner + zero authority.
- The eventsource fold contract classifies both as not-event-carried:
  a folded session keeps the snapshot-restored owner, ownerless stays
  ownerless (ADR 0100 decision 5).

Co-Authored-By: Claude Opus 5 <[email protected]>
The verified caller rides the context, not a port signature: an unexported
empty-struct key plus WithPrincipal/PrincipalFromContext in engine/session
(stdlib + domain only). No port interface gains a principal parameter, so
the layering rule is untouched (ADR 0100 decision 2).

Absent identity is a nil *Principal, never a fabricated anonymous one — the
ToolHive anonymous-middleware anti-pattern the ADR rejects. WithPrincipal(ctx,
nil) returns ctx unchanged so "no identity" cannot be laundered into a
present-but-empty principal, and the stored principal is a copy so a caller
cannot mutate what the context reports.

Lands with its invariant: a new "No fabricated principal" bullet under
AGENTS.md "Things That Will Bite You", pinned by
TestInvariant_no_fabricated_principal (the absence arms were watched red with
the fabrication planted).

Co-Authored-By: Claude Opus 5 <[email protected]>
…367)

Scenario 3 of docs/acceptance/caller-identity.md; ADR 0100 decision 4.

The owner is written ONCE at create, from the verified principal on the
context — never from the request body (CreateSessionRequest gains no owner
field, so a caller can never name its own owner). An absent principal yields
an ownerless session: the no-auth path stays byte-identical and nothing is
ever fabricated.

- server.WithOwner is the create-time injection seam (a sibling of
  WithSessionID) for a caller that holds the owning principal out of band —
  task 06's schedule fire path. An explicit WithOwner beats the context
  principal; WithOwner(nil) is explicitly ownerless and does NOT fall back.
- A fork inherits the SOURCE's owner on BOTH fork paths (WithSourceSession
  carryover + the explicit ForkSession), never the forking caller's —
  otherwise fork is an ownership-laundering path.
- Never backfilled: an ownerless (pre-ship) session stays ownerless however
  many times it is loaded, run, or listed. The owner is stamped through the
  aggregate's write-once RestoreLabels, never by poking the field.
- The list row surfaces it: proto SessionSummary.owner (a new Principal
  message; absent owner = absent message), the server SessionSummary struct,
  and port.SessionMeta.Owner so the MetaLister FAST path populates the row
  identically to the Load-per-row slow path. DISPLAY ONLY — no filtering:
  a request bearing Bob's principal still lists Alice's session (scoping is
  the isolation track's, #368).

Pins AC3.1/3.2/3.4/3.5 and the service half of AC3.3; the fork-laundering and
never-backfilled arms were watched RED with the violation planted.

Co-Authored-By: Claude Opus 5 <[email protected]>
…100)

Scenario 1 of the caller-identity plan. The existing authn.go seam gains an
OIDC-shaped identity step behind its OWN predicate:

- server.PrincipalValidator: a one-method seam (Validate(ctx, bearer) ->
  *session.Principal) plus the two errors.Is-able sentinels the edge maps on,
  ErrInvalidToken (401-class) and ErrIdentityUnavailable (transient 503-class).
  Validation itself stays DELEGATED — no JWT/JWKS parsing lands in mecatl;
  wiring toolhive-core/authn behind the interface is a later one-line flip.
- SecurityConfig.identityConfigured() is true iff a validator is wired and is
  INDEPENDENT of authEnabled() ("a static shared token is configured"), which
  is a latent fail-open in both directions.
- Both surfaces: bearer -> Validate -> session.WithPrincipal on the handler
  context. A rejected token is a clean 401 with no fallback branch; an
  unreachable IdP is Unavailable/503, never mistaken for an authn failure.
  With no validator wired nothing changes: nil principal, no new failure mode,
  the TUI's default no-token path untouched.
- Rate limiting re-keys on the validated (iss, sub), so rotating a token is not
  a limit bypass; a rejected token is never keyed (the limiter runs after the
  verdict, so it creates no bucket).

Composition: --oidc-issuer / --oidc-jwks-uri / --oidc-audience, registered once
in internal/cliconfig and shared by mecated and mecak8s. The validator is built
with the SERVER-ROOT ctx (it owns background JWKS refresh), and every
construction failure is FATAL — a misconfigured verifier must not degrade to
the unauthenticated path.

Pins: TestCallerIdentity_Scenario1_{ValidTokenYieldsPrincipal,BadTokensRejected,
NoAuthByteIdentical,IdentityPredicateIndependent,JWKSDownIsTransientNotUnauthorized,
RateLimitKeyedOnPrincipal,MisconfiguredOIDCFailsToStart}.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ent (#367)

Every event in the durable log names its actor. The field is nil at every
emit site (the loop stays storage- and identity-agnostic); the server relay's
single appendEvent chokepoint stamps it from the loaded session's owner just
before the durable Append. It is log-only: no proto field carries it to the
client wire, and eventsource.Fold ignores it, so a folded session keeps the
owner its caller restored from the snapshot. An ownerless (pre-ship) session
records a nil actor — absence is never fabricated.

ADR 0100 decision 5; acceptance AC4.1 / AC4.2 / AC4.5.

Co-Authored-By: Claude Opus 5 <[email protected]>
…367)

Added (minor): a new struct field on session.Event. COMPATIBILITY.md's
reconstruction contract already classifies the identity labels as
not-event-carried, so the fold obligation table needs no change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…cipal

Internal work has no caller. Rather than crossing port boundaries with an
ABSENT principal — which the isolation track (#368) would later have to
guess about — every internal goroutine root now stamps an explicit
system principal (ADR 0100 decision 7).

internal/syscaller is the registry: one Root const + Roots entry per
internal context root, and Context(ctx, root) does the wrap. The pinning
test drives every registered root through its REAL production starter
with a port probe and asserts the principal the port actually observed,
so a root registered without its wrap goes red, and a root registered
with no driver fails the registry/table drift check.

The scheduler needs ONE wrap in Start: tick, fire, delivery and reconcile
all descend from its ctx (WithoutCancel keeps values). FireNow is
deliberately left alone — a manual fire keeps its requester's identity.

AC2.2 (docs/acceptance/caller-identity.md), pinned by
TestCallerIdentity_Scenario2_InternalGoroutinesRunAsSystem.

Co-Authored-By: Claude Opus 5 <[email protected]>
Tasks 02 and 03 each landed a package-level `alice` in
internal/adapter/server's external test package, so the accumulator does
not compile (task lint / task test both fail before reaching task 04's
work). Rename the edge-authn one to `edgeAlice`; task 03's `alice`/`bob`
owner pair keeps its names.

Integration repair only — no behaviour change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…e owner

A schedule now records the verified caller it belongs to, captured ONCE at
create time (ADR 0100 decision 6) — never derived at fire time, because
childgc sweeps the origin session on retention while the schedule lives on.
The capture rule follows the create SURFACE: the Schedule-tool path reads the
executing session's owner (the origin binder already stamped it), an
out-of-band REST/CLI create reads the context principal, and ownerless stays
empty — never fabricated. UpdateSchedule carries the owner forward verbatim
(write-once: editing a schedule cannot re-own it).

The fire runs AS the owner: makeFireFunc injects it via the explicit
server.WithOwner CreateSessionOption with GrantType client_credentials, so
the scheduler's system principal does not become the fire session's owner
while the grant type honestly says automated-not-interactive.

The fire loop is its run's only consumer, so it now appends its events to the
durable log through the ONE stamping path (Service.AppendRunEvent →
appendEvent) — a scheduled fire was the one run whose events never reached
the log, and its events therefore now carry the same actor.

Co-Authored-By: Claude Opus 5 <[email protected]>
ScheduleSpec.owner joins the proto contract as a READ-ONLY projection: the
create/update mappers deliberately ignore an inbound owner (a caller can no
more name a schedule's owner than a session's — CreateSessionRequest has no
owner field for the same reason), and scheduleSpecToProto projects the
captured value on every read.

The schedule conformance suite now pins the owner round-trip, so no transport
can silently drop it — local jsonlstore, redisstore, memschedulestore and the
ScheduleStoreService driver all run it. It also pins POINTER ISOLATION, which
caught a real aliasing bug: Owner is ScheduleSpec's first pointer field, and
both cloneSpec helpers copied only the Parts slice, so a caller mutating a
loaded schedule's owner rewrote the stored record.

Co-Authored-By: Claude Opus 5 <[email protected]>
List 1 row 39 (the OIDC validator's JWKS cache + refresh — honest that the
validator is not yet wired), List 2 rows 26-28 (session owner =
persist-in-snapshot, Event.Actor = derive-at-append, schedule owner =
persist-in-schedule-record), plus the re-audit paragraph recording why
internal/syscaller earns no row.

Co-Authored-By: Claude Opus 5 <[email protected]>
Adds the flags to the mecated server table plus a short "Caller identity"
section: it is attribution, not isolation (nothing is refused on identity
grounds yet), and the flags currently fail closed because the token validator
is not part of this build. Cross-referenced from the trust model.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ge (#367)

architecture.md gains a short "Caller identity" section tracing the four
segments of the thread: the principal enters at the authn.go edge, rides a
context key (nil when absent, explicit system principal for internal
goroutines), sessions and schedules record an owner, and Event.Actor is
stamped log-only at appendEvent. usage/mecated.md lists the three flags in
the security flag table with the attribution-not-isolation and
currently-fails-closed caveats.

Co-Authored-By: Claude Opus 5 <[email protected]>
Three panel-review Standards findings on the assembled branch:

- AGENTS.md's durable-log bullet claimed the log "adds none" to the
  events it stores. appendEvent now adds Event.Actor, so read alone the
  two bullets contradicted. Narrow the claim to CONTENT and name the one
  thing it does add.
- Add internal/syscaller to the "where things live" list — it was the
  only new top-level internal package with no entry.
- The acceptance index still listed the plan as draft.

Co-Authored-By: Claude Opus 5 <[email protected]>
The living doc described the OIDC edge as operational. usage/mecated.md
and the ADR 0027 row both state that no validator exists in this build
and --oidc-issuer is a fatal startup error today; architecture.md read
as if the deployment mode worked.

Co-Authored-By: Claude Opus 5 <[email protected]>
Both reviews found the same defect: appendEvent derived Actor from the
loaded session's OWNER, so in the multi-caller deployment these flags
enable -- and which user-docs states plainly, "any authenticated caller
can still list and act on any session" -- every event of a run driven by
Bob was stamped Alice. Repudiation in both directions, worst on
EvApproval, where the record IS a human granting a tool permission.

The implementation matched the spec, so the spec is what was wrong:
ADR 0100 decision 5 and AC4.1 both said "the loaded session's owner".
The owner answers "whose is this?"; the actor answers "who did this?".
They are different questions and routinely different values.

Amending ADR 0100 in place rather than superseding it (ADR 0002's normal
rule): 0100 has never landed on main -- it is unmerged in this same PR --
so shipping a self-contradicting record plus an immediate superseding ADR
would be theatre.

Knock-on: AC4.4 said a fire's events "carry the same actor" as its
session owner. Under acting-caller semantics a fire runs under the
scheduler's system principal, so its events name system/scheduler while
the session still names the owner. That separation is the honest reading
-- the owner is accountable, the scheduler is what acted -- so the AC now
says it. AC4.5 is reworded around "no verified caller" rather than "an
ownerless session".

The code change is task 09; this is the contract it implements.

Co-Authored-By: Claude Opus 5 <[email protected]>
jhrozek and others added 16 commits August 10, 2026 10:32
The read path handed back the stored pointer, so a caller could mutate
Subject and change what the context reports for every later reader —
corrupting ownership and audit attribution downstream. WithPrincipal's
doc-comment already promised copy semantics; now both halves of the round
trip honour it.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ug (#367)

Nine sites hand-rolled the same "copy a *Principal across a boundary, nil
stays nil" rule. The ninth — ListSessions' summary.Owner — had already
diverged and handed out a LIVE pointer into the loaded session, so any
consumer of a list row could rewrite the session's recorded owner (the same
class as the cloneSpec aliasing bug from task 06).

Clone lands beside the type; the copy sites route through it. Principal is
all-strings today so a shallow copy is a deep copy — the point is that the
day it gains a slice or map field, all sites stay correct together.

Co-Authored-By: Claude Opus 5 <[email protected]>
validateScheduleOrigin loaded the origin session, then captureScheduleOwner
loaded it a SECOND time and turned a miss into a nil owner. A childgc sweep
landing between the two reads let validation pass and the schedule be created
silently OWNERLESS — the exact deletion hazard ADR 0100 decision 6 exists for.
The validated load's owner is now threaded through instead.

The three capture rules are unchanged: origin session's owner / context
principal for an out-of-band create / nil, never fabricated.

Co-Authored-By: Claude Opus 5 <[email protected]>
identify accepted any non-nil principal the validator returned — including
one with an empty Issuer/Subject (the fabricated-anonymous caller ADR 0100
decision 2 rejects, arriving through the front door), an out-of-enum
GrantType, or the INTERNAL mecatl:internal issuer / system grant, which is
byte-identical to a syscaller-stamped harness goroutine at every downstream
consumer — including the isolation track (#368).

All four are now ErrInvalidToken (401-class, never 503), rejected before any
rate-limit bucket is created. session.GrantType.Valid finally has a
production caller.

Co-Authored-By: Claude Opus 5 <[email protected]>
… pin (#367)

The SetFire callback was a no-op that never called seen(), so only the tick
loop's Due poll was observed — fire, delivery and reconcile rested on an
inheritance argument in a comment, and a stray context.Background() in any of
them would have passed CI.

The harness now takes a path LABEL per observation and asserts every path a
root declares. The scheduler driver seeds its store so all four fire: a due
cron drives fire and (through RecordFire) delivery, a stale claimed-but-
never-started fire drives the reconcile scan. Verified red by planting
context.Background() at each of the three call sites in turn.

Co-Authored-By: Claude Opus 5 <[email protected]>
…367)

The test's comment claimed subagent-/parallel-/team- but it only loaded
subagent-p1. Parallel branches and team members mint their child session
through the same parentCaps.inheritOwner seam, so both now run under a
DIFFERENT principal than the parent's owner and assert the source owner wins.
Verified red by planting the caller-owner laundering at each seam.

Co-Authored-By: Claude Opus 5 <[email protected]>
Only UnaryInterceptor was exercised. StreamInterceptor has its own
principalStream wrapping — it overrides the stream's Context so the handler
sees the verified principal, and hands back the ORIGINAL stream when identity
is off — and no test touched it, so a regression would have shipped silently
with Converse (the main prompt surface) running unidentified.

Adds the valid-token, bad-token/IdP-outage and no-identity stream cases.
Verified red by dropping the principalStream wrap.

Co-Authored-By: Claude Opus 5 <[email protected]>
captureScheduleOwner no longer needs the manager receiver (the origin owner is
threaded in), so it becomes a free function; the AC2.2 harness takes ctx first.

Co-Authored-By: Claude Opus 5 <[email protected]>
The rebase hit the expected llms.txt conflict (upstream #428 regenerated
it, so did this branch). Resolved per the AGENTS.md convention -- take
either side, regenerate once from the merged tree -- rather than
hand-merging a generated file.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ssion owner

appendEvent resolved the attribution from the LOADED SESSION'S OWNER. This
phase ships no authorization — any authenticated caller can act on any
session — so when caller B drove a session owned by A, every durably logged
event of that run was stamped A. Repudiation in both directions, and worst on
EvApproval, where the record IS a human granting a tool permission.

Read the caller off the context instead (ADR 0100 decision 5, as amended):
all seven appendEvent call sites already pass context.WithoutCancel of their
handler ctx, which detaches cancellation but preserves values, so the true
caller was already in reach. This also drops the undocumented dependency on
the run still being registered in s.runs during the drain, which degraded to
a nil Actor with no signal.

The session OWNER semantics are untouched: it stays write-once at create and
remains the identity of record ("whose is this?"); Actor answers "who did
this?". A scheduled fire therefore keeps the schedule owner on its session
and names the scheduler's system principal on its events.

AC4.1 gains the divergent case (Alice owns, Bob drives, events name Bob);
AC4.5 is reframed around "no verified caller ⇒ nil actor" and now also
covers an OWNED session driven with no caller, which an owner-derived stamp
would fabricate an actor for; AC4.4 asserts the owner/actor split.

Refs #367

Co-Authored-By: Claude Opus 5 <[email protected]>
…ping path

emitScheduleEvent built a session.Event and called EventLog.Append DIRECTLY,
so a fire's `fired`/`failed` lifecycle event landed with Actor == nil while
the same fire's run events were stamped. appendEvent's own doc-comment says
"do not add a second stamping path" — one already existed.

Two halves to the fix. The emit moves onto the Service, where it goes through
appendEvent (nil EventLog, the WARN-not-abort failure mode and the cancel
detachment all come with it). And the callback grows a ctx: it built its own
context.WithoutCancel(context.Background()), a fresh root carrying no
principal, so merely routing it through the chokepoint would still have
stamped nil. The scheduler now passes the firing ctx — a tick fire descends
from Start's syscaller root, so a `fired` event honestly names
system/scheduler; a manual FireNow keeps its requester.

The manager's eventLog field and the now-unread ScheduleManagerConfig.EventLog
go with it, rather than sitting there looking wired.

Refs #367

Co-Authored-By: Claude Opus 5 <[email protected]>
…367)

Task 09 moved it so a schedule lifecycle event is stamped by the same
single appendEvent chokepoint as every other durable append. The
IMPLEMENTATION-NOTES delegation list still claimed the manager owned it,
and the callback description did not say why it takes a ctx -- the old
manager-side body built a fresh context.Background(), which carries no
principal, so a fired event would have recorded no actor.

Co-Authored-By: Claude Opus 5 <[email protected]>
)

Both reviews found the same class of defect in the plan itself: an AC
whose named verify: test exists and passes, but asserts something
narrower than the AC's words. ac-trace --strict blesses those, the
Definition of Done reads satisfied, and a reader concludes the property
is covered.

AC1.2 said tokens with alg=none / HS-confusion / a bad signature "are
rejected". The test feeds opaque string labels to a FAKE validator whose
allow-map holds one entry; no JWT is parsed anywhere in the tree, and
NewValidator is nil in both mains so no real build can turn OIDC on. It
now states what it does verify -- the edge honours a rejection
absolutely, on both surfaces, with no fallthrough and no keying of a
rejected token -- and names the scope limit outright.

AC2.2 said "a new goroutine that forgets the principal fails". Task 08
made the three previously-unobserved scheduler paths genuinely observed
at their real port crossings, which was the substantive half. But the
registry is manual opt-in, so the gate catches a DROPPED wrap and
registry drift, not a never-registered goroutine. Said so.

Also records two risks the reviews surfaced that the plan never named:
the full list of JWT hardening properties deferred to toolhive-core/authn
(with the RFCs), and Principal.Name as PII denormalized onto every
durable event with no retention policy.

No code change -- this is the plan telling the truth about its evidence.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant