Skip to content

feat(ahp): sign in to each hook backend with managed OAuth - #355

Open
danielkov wants to merge 30 commits into
mainfrom
feat/ahp-oauth
Open

danielkov wants to merge 30 commits into
mainfrom
feat/ahp-oauth

Conversation

@danielkov

Copy link
Copy Markdown
Contributor

Summary

Kit can now sign in to OAuth-protected Agent Hooks Protocol backends. Each backend in hooks.json has its own sign-in state, built on agenthooksprotocol 0.13.1 managed OAuth. A sign-in link is shown to the user at turn start, without blocking the turn, and there are CLI commands to check, sign in and sign out per backend.

Motivation

Hook backends behind OAuth could not be used from Kit. Kit passed no auth provider to the AHP SDK, so it could only use whatever the SDK's default resolved. AHP backends often sit behind the same authorization servers as MCP servers and need a user sign-in.

Impact

  • Sign-in at turn start. When a backend reports that it needs a login, Kit prepares one in the background at the next turn and shows the link only to the user:
    • TUI: a status-line slot, with the full link shown once, wrapped and clickable.
    • Other ACP clients: an Info notice.
    • Headless: one stderr line.
    • The link never appears in a transcript the model reads, including a subagent's output.
    • Repeated turns reuse the same link until it expires. Completing the sign-in clears the link, and backends that already have a usable grant are never asked again.
  • CLI:
    • kit auth status hooks [backend]
    • kit auth login hooks [backend]; with no argument it covers only the backends that need a login.
    • kit auth logout hooks <backend> [--all-workspaces]
    • The ACP terminal-auth method hooks runs the login.
  • Configuration. Kit accepts the spec's registration OAuth preset and an optional oauth object on each backend. The object's fields are shared with the AHP harness adapters: issuer, clientId, clientSecretRef, clientMetadataDocument, registration, redirectPort, loginLifetimeMinutes, allowPrivateNetwork and trustAdvertisedIssuer.
  • Client registration. Kit can use a pre-registered client, a Client ID Metadata Document, or Dynamic Client Registration for an explicitly configured issuer.
  • Sign-in during a session. Backends that need a sign-in stay registered and follow their own failure policy, so a fail-closed backend denies until the user signs in. A backend whose hooks/configuration needed a sign-in is configured right after the sign-in, in the same session.
  • SDK upgrade. agenthooksprotocol goes from 0.10.1 to 0.13.1, which brings these SDK fixes:
    • challenged requests are replayed once;
    • a refresh token is kept until the server rejects it;
    • blank token scopes are treated as omitted;
    • skipped configuration backends get a diagnostic and are retried.

Technical details

Credential storage

SDK records are stored in Kit's credential storage, with compare-and-set on each record's version. CredentialStorage::lock_entry adds a lock per key: an in-process mutex plus an OS file lease that the kernel releases when the process exits, so there is no stale-lock handling. A per-backend index lets logout remove exactly that backend's state. Expired pending logins are pruned when a new link is recorded.

Network policy

OAuth requests go only to HTTPS and never follow redirects. Responses are capped at 1 MiB. Each address is resolved, checked and pinned per request. Non-global addresses are refused, including IPv4 embedded in IPv6, unless allowPrivateNetwork is set.

Redirect and callback

Each backend gets a fixed loopback port, derived from 30000–32767 or set with redirectPort; duplicate ports are refused. One listener per port completes any stored pending login whose state matches, so a sign-in started in one Kit process can be completed by another. The CLI shows the link only after the listener is up.

One sign-in per backend

The grant partition is the backend id, so a backend's event and upload endpoints share one sign-in. An advertised issuer is trusted only with trustAdvertisedIssuer: true, and only for public PKCE clients. Confidential clients always need a configured issuer.

Each entry gets its own cross-process lease, so holders may nest locks
on different entries, which the single refresh lock cannot allow.
Hook authentication moves to agenthooksprotocol 0.13.0 managed OAuth.
Each backend has its own grant (partitioned by backend id, so its event
and upload endpoints share one consent), pending login and fixed
loopback redirect. Records live in Kit's credential storage under
per-entry locks.

Delivery never signs in: a backend that needs a login stays registered
and fails under its failure policy. The next turn start prepares the
login in the background and offers its link; repeated turns reuse the
stored pending login until it expires.

Backends are configured by their authentication preset and the shared
hooks.json oauth object (issuer, flow, scopes, clientId,
clientSecretRef, clientMetadataDocument, registration, redirectPort,
loginLifetimeMinutes, allowPrivateNetwork).
The TUI shows a pending link in its status line, fed by the Kit
notification kit/hooks/auth. Other ACP clients get one notice per link
and one when sign-in finishes; sessions without a client print one
stderr line per link. ACP clients with terminal authentication are
offered a single hooks method.
kit auth status hooks lists each backend, kit auth login hooks
[backend] signs in to one backend or each that needs it, and
kit auth logout hooks <backend> removes only that backend's state.
A process cached which records it had indexed, so after another
process logged out, its later sign-in wrote records the index no longer
listed and the next logout missed them.
Sign-in notices carry _meta kit/hooks/auth, and a parent Kit drops such
updates from a child before capture, inspection or forwarding, so the
link never enters the subagent tool output.
The status line now says which backend needs sign-in, and the transcript
shows the full link once, wrapped and hyperlinked, so a 300-character
authorize URL is never cut off.
One loopback listener per port now serves every pending login on it and
completes only the login whose state the callback carries. Ports are
derived from 30000-32767, outside the ephemeral ranges and other
adapters' range; a duplicate explicit redirectPort is refused, and a
port held by a program other than Kit is reported. Sign-in state, grants
and logout are keyed by the backend id within its hooks file, so two
workspaces with the same backend id never share them.
Without oauth.issuer (or a preset issuer), Kit refuses the authorization
server a backend advertises unless oauth.trustAdvertisedIssuer is true,
matching the other AHP adapters. Client credentials always need issuer.
The network starts each request's client from an injected builder,
reqwest's default in production; tests supply one trusting their CA
through a test-support constructor.
The fake authorization server now checks each code's PKCE verifier, so
a callback it rejects is shown not to complete a sign-in. Store tests
cover compare-and-swap expectations across instances and per-record
ownership; the fail-closed test uses a reachable resource that rejects
anonymous requests and asserts none was sent.
IP literals and resolved addresses are judged alike: IPv4-mapped and
IPv4-compatible addresses by their IPv4 address, NAT64, 6to4 and other
special-purpose blocks refused, and only global unicast allowed. Token
requests are marked written once their connection is established.
- Completing one target's login keeps the scope's other logins and
  shows the next link.
- A shared callback port completes another Kit process's login from the
  shared store, and each exchange runs on its own task, so probes are
  answered meanwhile; the probe is also retried before warning.
- kit auth logout hooks <backend> --all-workspaces removes the backend's
  state under every workspace scope, including moved projects.
- The CLI listens before it shows the link, logout counts only stored
  records it removed, and in-process entry locks are keyed per storage.
- A test fails if the token request is not marked written on connect.
- A listener stops only after checking, under the lock offers take, that
  no login for its port arrived meanwhile.
- Expired pending-login records and their index entries are pruned each
  time a new link is recorded.
- Tests wait for both targets' logins, and cover listening before the
  link is shown, per-storage entry locks, and logins offered while a
  listener waits.
A concurrent prune could otherwise find the indexed login without its
record and drop it. Tests cover the ordering, and a listener that must
keep serving a login offered just as it stops.
Kit moves to agenthooksprotocol 0.13.1. Its provider forwards
preparations to the backend's managed OAuth, so a completed sign-in
lets the SDK retry a backend's hooks/configuration in the same session,
and configuration skips that need a login feed the turn-start hint.

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exact-head CI passed. Static review found defects in OAuth issuer and scope handling, logout indexing, workspace diagnostic routing, and sign-in callback and UI lifecycle. It also found that named status checks can touch unrelated backends and that the TUI documentation points users to the wrong place for the link.

Took 21 min

Comment thread src/ahp/auth/config.rs Resolved
Comment thread src/ahp/auth/secrets.rs Resolved
Comment thread src/ahp/auth/store.rs Resolved
Comment thread src/ahp/auth/login.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/tui/app.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread docs/user/agent-hooks-protocol.md Resolved
Kit opens ~/.kit/ahp-secrets.json once, checks that handle's owner and
permissions, refuses the file if they cannot be checked, and reads from
the same handle.
Logout deleted a record and released it before removing its index
entry, so a writer could recreate it in between and survive unindexed.
The record lock is now held until its index entry is gone.
- An oauth.issuer that is not an https URL refuses OAuth for the
  backend instead of acting as if no issuer were pinned.
- oauth.scopes add to the preset's scopes, which the SDK requires on
  every operation, so they no longer fail its ceiling check.
- A configuration skip needs a login only in the workspace that
  declared the backend; delivery needs come from the provider, which
  knows the exact target.
- A link is shown only once this process or another Kit process
  listens for it. A port another program holds is reported, with what
  to change, by the turn-start hint and by kit auth login hooks.
- kit auth login hooks takes the port over if the Kit process it was
  waiting on stops listening.
- A sign-in that cannot be prepared tells the user why, once.
- kit auth status hooks <backend> checks only that backend.
- The docs say where the TUI shows the link.
Links and reminders are kept per session: another session's late
updates never change the current view, a session's links return with
it, including ones that arrived while it attached, and a sign-in that
cannot be prepared is shown once as a notice.
A configuration skip never asks a backend authenticated by its
Authorization header to sign in, and a session's expired sign-in links
are not shown again when it returns. The providers doc comment is back
on providers, and the per-backend status test now checks the named
backend was contacted and a typo does no work.

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The title, lint, test, test-headless, test-rust, macos-rust, and macos-desktop checks passed at this head. Static review found that an OAuth manager can reuse the wrong scope ceiling across targets, and background sign-in can lose its callback listener or leave the initiating session waiting after approval. Other findings cover hint ordering and restoration, scope-denial guidance, preset documentation, and nonblocking secrets-file loading.

Took 20 min

Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread src/ahp/auth/login.rs Resolved
Comment thread src/tui/app.rs Resolved
Comment thread src/tui/app.rs Resolved
Comment thread src/ahp/auth/mod.rs Resolved
Comment thread docs/user/agent-hooks-protocol.md Resolved
Comment thread src/ahp/auth/secrets.rs Resolved
Managers were cached per backend, flow and client, so an upload binding
with different scopes reused the event binding's ceiling and was denied.
The key now includes the target's sorted scopes; the grant is still
shared.
When another Kit process holds a backend's callback port, the session
that showed the link now watches it until it ends or expires: it clears
the hint as soon as the shared store holds the grant, and takes the port
over with the same link if the peer stops listening first.
A backend's hint carries its pending link and, separately, a problem
preparing another of its targets, so the problem no longer replaces a
link that still works.
A new subscriber's replayed hints and live deliveries are serialized,
so a completion published during the replay can no longer reach the
client before the link it clears.
A completed, expired or replaced sign-in link stays in the conversation
view without its link, and a session's unresolved sign-in problems
return with it when the view is rebuilt.
A backend that requires scopes outside the ones Kit allows it is still
denied and never prompts a sign-in, but the user is now told which
scopes it asked for and to review oauth.scopes.
Each turn offered the same pending login again and started another
watcher. One watcher now follows each login, and when its link expires
behind a peer it is withdrawn, so the hint clears instead of offering a
dead link.
@danielkov

Copy link
Copy Markdown
Contributor Author

@kit-code-agent review

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found seven issues affecting OAuth manager reuse, credential cleanup, callback listener handoff, pending-login expiry, live hint ordering, TUI reattachment, and scope-denial notices.

Took 19 min

Comment thread src/ahp/auth/mod.rs
pkce,
preset_client.clone(),
scopes.clone(),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Key cached OAuth managers by effective client secret reference

The manager cache lookup runs before Kit resolves the effective secret reference. Without a backend-wide override, confidential event and upload targets with the same client ID, flow, and scopes can name different references, but the first cached manager supplies its secret to both. The later target can fail token acquisition with the wrong secret or bypass the missing-reference error it would get on a cold lookup. Resolve the effective client ID and applicable secret reference before cache lookup, and include the reference, not the secret material, in the key.

For agents:
Validate the following issue, address if needed:

<comment>Include the effective confidential-client secret reference in the key so a cache hit cannot reuse another target's secret or bypass reference validation.</comment>
<file_context>
+        let key = (
+            backend.scope.clone(),
+            pkce,
+            preset_client.clone(),
+            scopes.clone(),
+        );
</file_context>

Comment thread src/ahp/auth/secrets.rs
) -> LocalFuture<'_, Result<(), HookError>> {
Box::pin(async move {
self.0.remember(SECRETS, &reference, budget).await?;
let _lock = self.0.lock(SECRETS, &reference, budget).await?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Index a dynamic client secret while holding its record lock

Secrets::store calls remember before taking the record lock. Logout can take that lock in between, remove both the record and its index entry, and release it before the writer saves the secret. The saved secret is then absent from the index, so a subsequent logout cannot find it. The resolved delete-side fix holds the record lock correctly; the writer must also acquire that lock before remember and hold it through the save, preserving record-before-index order.

For agents:
Validate the following issue, address if needed:

<comment>Take the secret's record lock before indexing it so a concurrent logout cannot leave the subsequent save unindexed.</comment>
<file_context>
+        Box::pin(async move {
+            self.0.remember(SECRETS, &reference, budget).await?;
+            let _lock = self.0.lock(SECRETS, &reference, budget).await?;
+            let entry = self.0.storage().entry(SECRETS, &reference);
</file_context>

Comment thread src/ahp/auth/login.rs
registry().completed(&login);
return;
}
if !registry().claim(port) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Distinguish a reserved callback port from a confirmed listener

claim marks the port before the bind succeeds, but watch_peer treats a failed claim as proof that a local listener took over. With two pending logins, one watcher can exit while the other's bind attempt fails because the peer still owns the port. If the remaining watcher completes its own login and the peer stops listening, the first login has no watcher to take over or retire its link. The same reservation ambiguity lets a second backend sharing a port skip prepare's bind check and show its link before the first backend's bind result is known; a foreign-port result withdraws only the first backend's entry. Track in-flight binds separately from confirmed receiver state. Keep watchers active until a local listener owns their pending work, and publish links only after a local listener or Kit peer is confirmed.

For agents:
Validate the following issue, address if needed:

<comment>A port reservation is not a confirmed listener; keep watchers and link publication waiting for the bind outcome.</comment>
<file_context>
+        if !registry().claim(port) {
+            // A listener of this process serves the port now.
+            return;
+        }
+        match TcpListener::bind(("127.0.0.1", port)).await {
+            Ok(listener) => return listen_on(listener, port).await,
+            Err(_) => registry().stopped(port),
+        }
</file_context>

Comment thread src/ahp/auth/login.rs
let expired: Vec<_> = state
.pending
.iter()
.filter(|(_, pending)| pending.port == port && pending.expires_at <= now)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Expire pending OAuth logins individually

Completion and peer expiry promote a remaining login and assign its deadline to the whole scope entry. If that promoted login expires before another sibling, logins removes the whole entry, clears the hint, and can close the listener while the sibling is still valid. Conversely, offer can pair the displayed URL with a later sibling's deadline. Prune expired logins individually, display a surviving URL with its own expiry, and calculate the listener deadline from all surviving logins.

For agents:
Validate the following issue, address if needed:

<comment>Prune expired logins individually so the displayed link's deadline cannot discard live siblings or stop their listener.</comment>
<file_context>
+            let expired: Vec<_> = state
+                .pending
+                .iter()
+                .filter(|(_, pending)| pending.port == port && pending.expires_at <= now)
+                .map(|(scope, pending)| {
</file_context>

Comment thread src/ahp/auth/login.rs
let sink: Arc<Sink> = Arc::new({
let (inner, gate) = (Arc::clone(&inner), Arc::clone(&gate));
move |hint: &AuthHint| {
let _turn = gate.lock().unwrap_or_else(|poison| poison.into_inner());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Deliver concurrent live hints in registry order

The subscriber gate correctly puts replay before live updates, but it does not preserve order between live publishers. publish commits a hint under the registry lock, then calls the sink after unlocking. If an earlier link-plus-problem update is delayed there, a later expiry clear can reach the TUI first. The earlier update can then make the expired link clickable again, even though the registry has removed it and may send no further clear. Enqueue updates in registry commit order and drain outside the lock, or stamp updates at commit time and reject older revisions.

For agents:
Validate the following issue, address if needed:

<comment>The gate serializes sink calls, not registry commit order; preserve live update ordering so an earlier link cannot undo a later clear.</comment>
<file_context>
+            move |hint: &AuthHint| {
+                let _turn = gate.lock().unwrap_or_else(|poison| poison.into_inner());
+                inner(hint);
+            }
</file_context>

Comment thread src/tui/app.rs
}
// And its unresolved sign-in problems.
let problems: Vec<_> = self
.hook_problems

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Reconcile cached hook sign-in state on reattachment

Closing an ACP attachment drops its hint subscription, but the TUI retains that session's cached links and problems. If sign-in completes while the session is detached, the old attachment misses the clear and the new subscription replays only hints still in the registry. start_session_with_presentation can therefore redraw a consumed URL until its cached expiry or restore a resolved problem indefinitely. Invalidate the old attachment's cache before processing the new attachment's replay, or make replay an authoritative snapshot that also removes absent entries.

For agents:
Validate the following issue, address if needed:

<comment>Rebuild hook sign-in state from the new attachment's replay rather than restoring cached entries that may have cleared while detached.</comment>
<file_context>
+        // And its unresolved sign-in problems.
+        let problems: Vec<_> = self
+            .hook_problems
+            .iter()
+            .filter(|((owner, _), _)| self.session_id.as_deref() == Some(owner.as_str()))
+            .map(|((_, backend), problem)| hook_problem_text(backend, problem))
+            .collect();
</file_context>

Comment thread src/ahp/auth/mod.rs
return;
}
if let Some(backend) = self.0.backends.get(&context.backend_id) {
login::registry().problem(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Keep scope-ceiling denials out of the pending sign-in lifecycle

explain_ceiling correctly records no login need, but it publishes through Registry::problem, which stores a replayable sign-in hint. Without a recorded need or pending login, usable returns early and completion or expiry cannot clear the hint. Later sessions can still be told that Kit could not start sign-in even when the backend has a usable grant and the denial affected only one operation. Publish a deduplicated diagnostic that identifies a scope denial, not a failed sign-in, and give it a separate lifecycle without widening the ceiling or changing the denial.

For agents:
Validate the following issue, address if needed:

<comment>Report this as a scope denial without storing an unresolved sign-in hint that has no normal clearing path.</comment>
<file_context>
+            login::registry().problem(
+                &backend.scope,
+                &backend.id,
+                format!(
+                    "access_denied. The backend requires scopes ({}) outside the ones Kit allows for it. Review oauth.scopes in hooks.json.",
</file_context>

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