feat(relay): verify NIP-FI agent tokens and admit agents through owners (#8401)

The relay side of NIP-FI agent tokens. An agent token has its own type,
`nip-fi-agent+jwt`, and carries its human owner's pubkey in
`nostr_owner_pubkey`. This PR verifies that claim, makes denying or
disconnecting the owner cut off every agent that owner authorized, and
makes the verified owner decide community admission. A relay without
agent support refuses the unknown type, so nothing needs to advertise or
configure agent support. The `NIP-FI.md` text for the agent type is
included.

Builds on #8372 and #8377 (both merged).

### Owner claim and owner deny

- **Token type binds the owner claim (`buzz-auth`).** A `DedicatedNipFi`
issuer policy accepts `nip-fi+jwt` (human) and `nip-fi-agent+jwt`
(agent); `AccessTokenAtJwt` policies stay `at+jwt`-only with their
`client_id` and subject rules unchanged, and unknown types are refused.
An agent token must carry a lowercase-hex `nostr_owner_pubkey` distinct
from its `nostr_pubkey`; a human or `at+jwt` token carrying the claim
with any value, including null, is `evidence_rejected`. The verified
owner is exposed as `VerifiedAssertion::owner()`.
- **No agent switch.** There is no relay setting, NIP-11 field or
operator binding field for agent support.
- **Session owner.** Each connection records its NIP-FI issuer and the
agent's owner (`NipFiSession`) on the root WebSocket manager and the
audio registry. `disconnect_nip_fi(iss, target)` closes a connection
when either its own key or its recorded owner equals the target.
- **Owner deny check.** `nip_fi_core::assertion_denied` checks the deny
set for both `(iss, k)` and `(iss, owner)`, and every existing deny
check uses it: WebSocket before upgrade and after registration, HTTP,
audio, and the shadow observer, so shadow and enforce make the same
decisions. The shadow disconnect observer matches a session's key or
owner under its issuer with the same rule, so an owner's disconnect
records a would-close for its agents.

### Shadow owner check

In shadow mode, WebSocket AUTH, audio join and HTTP admission record a
`Stage::Owner` verdict when an admitted agent token's owner is banned
(`owner/denied`), conflicts with the agent's stored owner
(`owner/denied`), or cannot be checked because a read failed
(`owner/unavailable`). These are reads only; shadow admission is
unchanged. Shadow applies the same stored-owner rule as enforce but
never writes the link, so it can't predict a later owner-link write
failure, or which of two racing first links wins.

### Admission through the verified owner

- **Owner bans, unconditionally.** `community_ban_outcome` takes the
token owner and checks its ban in place of a NIP-OA owner. That applies
whether the agent is a member itself, the relay is open, or the agent is
admitted through its owner.
- **Owner-derived membership.** In
`api::relay_members::check_membership`, an agent that is a member itself
is still admitted first. Otherwise, when a verified assertion names an
owner, the owner's membership decides (`MembershipDecision::ViaOwner`),
and no NIP-OA is needed on the connection. The issuer has already passed
this community's NIP-FI binding check at that point. When a token owner
is present it is the only owner considered.
- **Stored-owner consistency.** `link_agent_owner` replaces the boolean
`materialize_nip_oa_owner` result with `OwnerLink::{Linked, Conflict,
Unavailable}`. An unset stored owner is recorded, so relay bans and
roster removal of the owner reach the agent through
`revoke_live_access`. Shadow and enforce judge the stored owner through
one read, `stored_owner_link`, and `link_agent_owner` writes
(atomically, first write wins) only when that read finds no owner; a
failed read fails closed. If the stored owner differs from the token
owner, the request is refused with `authorization denied` on HTTP, WS
and audio. A NIP-OA owner conflict keeps its existing link-error
refusal.
- **One decision on every surface.** Root WS AUTH, audio registration
and every NIP-98 HTTP route (bridge, `buzz/v1`, git transport and
settings, invites, media, workflows, moderation reads) pass
`NipFiAdmission::token_owner()` / `VerifiedAssertion::owner()` into the
same ban, membership and owner-link steps. The final socket check
rereads bans and writer-side membership; it doesn't reread the owner
link, which is written once from NULL. HTTP membership still goes
through the bounded replica read. With a verified agent token, every
HTTP admission refusal, including the fresh ban rereads in `buzz/v1` and
Git settings, is NIP-FI's fixed `authorization_denied` (or
`authorization_unavailable` when a dependency fails), and audio checks
bans before writing the owner link. `enforce_relay_membership` now takes
the `TenantContext`, because it writes the owner link.
- **Publishing.** A ban caught while publishing over `POST /events`
after the shared membership check is also an admission refusal. Ingest
reports it as a typed `IngestError::Ban` (banned, or ban lookup
unavailable) at the write gate, the HTTP typing indicator's cached gate,
and the moderation and relay-admin command rereads. `IngestError::Ban`
carries the legacy error. The bridge turns it into the fixed
`authorization denied` / `authorization unavailable` only when the
request carries a verified agent token. WebSocket and token-less HTTP
responses are byte-for-byte unchanged, and timeouts, scopes, permissions
and every other ingest error keep their existing responses.

### Rollout

- **Deploy the relay before kgoose.** An older relay refuses
`nip-fi-agent+jwt`, so agents are locked out until both are deployed.
Humans are unaffected.
- **There is no agent-only switch.** Setting NIP-FI to shadow or off
turns it off for humans too.
- **Rollback is safe for owner links.** Stored owner links survive a
rollback, and the older code still honors them.
- **Shadow signals:** in `buzz_nip_fi_shadow_total`, `stage="owner"`
means an owner would-deny (`owner/denied`) or an owner read that was
unavailable (`owner/unavailable`), not a success. A clean agent
admission shows as `stage="admit", outcome="admit"`.
- **The relay checks that the owner is a member, not which issuer the
owner logged in through.** In a community that trusts several issuers,
any trusted issuer can name any member as owner. That matches the spec:
the issuer is trusted to vouch for the owner, and kgoose requires the
owner's attestation.

Agent tokens are only issued to relays whose NIP-FI binding trusts the
issuer, and NIP-FI itself is off unless configured. No deployed config
or secrets change.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
This commit is contained in:
Will Pfleger
2026-10-26 12:48:35 -04:00
committed by GitHub
parent d0dee1cb50
commit 369ffa0380
36 changed files with 3629 additions and 547 deletions

View File

@@ -196,6 +196,7 @@ async fn authenticate(
)
.await?;
let pubkey = *admission.proven_pubkey();
let token_owner = admission.token_owner();
let (event_id_bytes, signed_created_at) = admission.into_extra();
bridge::enforce_http_admission(state, &tenant, &pubkey)
@@ -207,21 +208,35 @@ async fn authenticate(
let tag = relay_members::extract_auth_tag_header(headers);
relay_members::enforce_relay_membership(
state,
tenant.community(),
&tenant,
pubkey.as_bytes(),
tag,
signed_created_at,
token_owner,
)
.await
.map_err(IntoResponse::into_response)?;
#[cfg(test)]
crate::nip_fi_test_hooks::before_http_ban_recheck(tenant.community()).await;
deny_banned_git_principal(
&state.db,
tenant.community(),
&pubkey,
tag,
signed_created_at,
token_owner,
)
.await?;
.await
.map_err(|legacy| match token_owner {
// A verified agent token gets only NIP-FI's fixed denial, as smart
// Git transport does, so the response never shows which step refused.
Some(_) => crate::nip_fi_core::http_denial(if legacy.status().is_server_error() {
buzz_auth::DenialClass::AuthorizationUnavailable
} else {
buzz_auth::DenialClass::AuthorizationDenied
}),
None => legacy,
})?;
// Admission ignores kind= restrictions by design (NIP-AA). Repository
// management must not turn a message-only credential into write authority.
// This HTTP operation has no event kind: only kind-unrestricted credentials

View File

@@ -199,6 +199,7 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
.await?;
let pubkey = *admission.proven_pubkey();
let token_owner = admission.token_owner();
let (event, signed_auth_created_at) = admission.into_extra();
// Relay membership gate (NIP-43). Git cannot carry a standalone
@@ -217,6 +218,15 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
legacy
}
};
// A verified agent token gets only NIP-FI's fixed denial, so the
// response never shows which step refused it.
let denied = |legacy: Response| {
if token_owner.is_some() {
crate::nip_fi_core::http_denial(buzz_auth::DenialClass::AuthorizationDenied)
} else {
legacy
}
};
#[cfg(test)]
crate::nip_fi_test_hooks::before_git_membership(tenant.community()).await;
match crate::api::relay_members::check_relay_membership(
@@ -225,14 +235,15 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
pubkey.as_bytes(),
auth_tag,
Some(signed_auth_created_at),
token_owner,
)
.await
{
Ok(crate::api::relay_members::MembershipDecision::Denied) => {
warn!(pubkey = %pubkey.to_hex(), "git: relay membership denied");
return Err(
(StatusCode::FORBIDDEN, "restricted: not a relay member").into_response()
);
return Err(denied(
(StatusCode::FORBIDDEN, "restricted: not a relay member").into_response(),
));
}
Ok(_) => {}
Err(e) => {
@@ -253,16 +264,40 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
&pubkey,
auth_tag,
Some(signed_auth_created_at),
token_owner,
)
.await
.map_err(|denial| {
if denial.status() == StatusCode::SERVICE_UNAVAILABLE {
unavailable(denial)
} else {
denial
denied(denial)
}
})?;
// A token owner other than the agent's stored owner is refused; an
// unset stored owner is recorded.
if let Some(owner) = token_owner {
use crate::api::relay_members::{link_agent_owner, OwnerLink};
match link_agent_owner(state, &tenant, &pubkey, &owner).await {
OwnerLink::Linked => {}
OwnerLink::Conflict => {
return Err(crate::nip_fi_core::http_denial(
buzz_auth::DenialClass::AuthorizationDenied,
))
}
OwnerLink::Unavailable => {
return Err(unavailable(
(
StatusCode::SERVICE_UNAVAILABLE,
crate::handlers::auth::OWNER_LINK_ERROR,
)
.into_response(),
))
}
}
}
Ok(GitAuth { pubkey, tenant })
}
}
@@ -284,6 +319,7 @@ pub(super) async fn deny_banned_git_principal(
pubkey: &nostr::PublicKey,
auth_tag: Option<&str>,
signed_auth_created_at: Option<u64>,
token_owner: Option<nostr::PublicKey>,
) -> Result<(), Response> {
let agent = git_restriction_state(db, community, pubkey).await?;
@@ -292,11 +328,13 @@ pub(super) async fn deny_banned_git_principal(
let owner = if agent.banned {
None
} else {
crate::api::relay_members::extract_nip_oa_owner(
pubkey.as_bytes(),
auth_tag,
signed_auth_created_at,
)
token_owner.or_else(|| {
crate::api::relay_members::extract_nip_oa_owner(
pubkey.as_bytes(),
auth_tag,
signed_auth_created_at,
)
})
};
let owner_state = match owner {
Some(owner) => Some(git_restriction_state(db, community, &owner).await?),
@@ -3789,7 +3827,7 @@ mod sec005_postgres_tests {
db.ensure_user(community, &member_pk).await.expect("member");
assert!(
deny_banned_git_principal(&db, community, &member.public_key(), None, None)
deny_banned_git_principal(&db, community, &member.public_key(), None, None, None)
.await
.is_ok(),
"precondition: an unbanned member passes the git ban gate"
@@ -3800,7 +3838,7 @@ mod sec005_postgres_tests {
.expect("ban");
let (status, body) = denial_parts(
deny_banned_git_principal(&db, community, &member.public_key(), None, None).await,
deny_banned_git_principal(&db, community, &member.public_key(), None, None, None).await,
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
@@ -3829,6 +3867,7 @@ mod sec005_postgres_tests {
&agent.public_key(),
Some(&auth_tag),
Some(200),
None,
)
.await
.is_ok(),
@@ -3847,6 +3886,7 @@ mod sec005_postgres_tests {
&agent.public_key(),
Some(&auth_tag),
Some(200),
None,
)
.await,
)
@@ -3860,7 +3900,7 @@ mod sec005_postgres_tests {
// An unattested request from the same agent key is unaffected: the
// cascade must follow a verified owner, not punish every agent.
assert!(
deny_banned_git_principal(&db, community, &agent.public_key(), None, None)
deny_banned_git_principal(&db, community, &agent.public_key(), None, None, None)
.await
.is_ok(),
"without an attestation there is no owner to inherit from"
@@ -3882,8 +3922,15 @@ mod sec005_postgres_tests {
let community = buzz_core::CommunityId::from_uuid(uuid::Uuid::new_v4());
let (status, body) = denial_parts(
deny_banned_git_principal(&db, community, &Keys::generate().public_key(), None, None)
.await,
deny_banned_git_principal(
&db,
community,
&Keys::generate().public_key(),
None,
None,
None,
)
.await,
)
.await;
assert_eq!(