feat(nip-fi): scope disconnects to tokens issued through revoke_through, stored durably (#9917)

## Summary

Builds on #9860 (merged as `c0932db19c`).

A NIP-FI disconnect command can now carry `revoke_through` (C), an
integral NumericDate. With C, the relay refuses and closes only
assertions whose verified signed `iat` is at or before C, until `until`.
Tokens issued after C are admitted straight away. Without C, the deny
covers the whole key, as before.

- **Spec:** `docs/nips/NIP-FI.md` adds the `revoke_through` claim and a
Deny scope section (admission, close scope, merging, records, the
issuer's duty) with a behavioral oracle. The existing deny,
command-algorithm, oracle and security text now carry scope. The deny
set's storage text is #9860's (shared storage, restored before
admission); this PR adds no wire claim or storage schema to the spec.
- **Parsing:** a `revoke_through` that is `null`, nonnumeric, fractional
or unrepresentable is rejected as `evidence_rejected` before any state
changes.
- **Verified `iat`:** `VerifiedAssertion::issued_at()` comes from the
time-checked `iat`, not from profile evidence. `NipFiSession` records it
at registration.
- **One predicate:** `DenyScope::covers` compares the full verified
instant (fractional `iat` included) against C. It decides admission
(WebSocket and HTTP, with asserted key and owner checked separately) and
every close scan (root and audio registries, the command route,
cross-pod delivery, shadow accounting).
- **Merge:** `DenyEntry::merge` takes the later `until`. Whole-key beats
a cutoff, two cutoffs merge to the larger C, and expired entries
contribute nothing. Activity is read from a clock sampled inside the
issuer shard lock, so an entry that expires while a merge waits
contributes nothing. A past-`until` command still does its scoped close
without changing an active entry. The close scope widens to any stronger
active entry, and a poisoned shard closes the whole key.
- **Bus:** `NipFiDisconnect.revoke_through` is optional. A message
without it means whole-key.
- **Durable cutoff (Redis):** the cutoff lives in its own per-issuer
hash, `<deny prefix>-revoke-through:<sha256(iss)>`, field `pubkey_hex`,
value C. The exact-`until` hash keeps only `secs:nanos`. One accept
script merges `until` and scope by the same rule as `DenyEntry::merge`
and gives all three keys one expiry. It judges whether the command and
the stored entry are still active by Redis `TIME` as it runs, not by the
authentication clock. Before any write it checks the target's stored
cutoff by restore's rule: a disconnect over an unreadable one returns
`unreadable`, `try_claim` fails (`503`), the claim stays unused and
nothing is recorded. Restore judges expiry when it merges. Restore reads
both hashes in one script and joins them before merging, looking deny
keys up in a set (linear at capacity), so a missing cutoff field is a
whole-key deny. A cutoff that isn't an integer, or names no deny, is
`reason="unreadable"`. As in #9860, one bad record does not hide the
others: restore still applies every readable deny (a deny under a
malformed cutoff as the whole key; an orphan cutoff adds nothing) and
then fails, so admission stays closed. `LoadDenies` and
`LoadDeniesError::Unreadable { readable }` now carry `DenyEntry`, and a
restore counts a same-`until` scope widening as changed, so it closes
the sessions it newly covers.
- **Runbook:** `docs/operator-nip-fi-bindings.md` names the cutoff hash
and how to clear a bad cutoff. It warns that deleting an orphaned cutoff
leaves no deny at all, and that a disconnect over a bad stored cutoff
fails until it is cleared.

## Deploy and rollback

Deploy this to every relay pod before any issuer sends `revoke_through`.
Until then, a pod still on the old build ignores the claim and blocks
the whole key, so the agent stays locked out until its old token
expires.

Rolling a relay back to #9860 is safe. That build reads only the
exact-`until` hash, which this PR writes in the same format, so it
restores every cutoff as a whole-key deny and never fails its restore on
this data. It ignores `revoke_through` in commands and bus messages, and
every accept it makes clears the target's stored cutoff, so its
whole-key revokes are never narrowed by a cutoff this build stored. All
of this only over-blocks: agents wait for their old tokens to expire
instead of getting back in at once.

## Testing

Behavior tests cover old and fresh tokens at admission and in close
scans, redelivery leaving fresh root and audio sessions open, cross-pod
delivery, an owner whole-key deny blocking a fresh agent token,
same-deadline scope changes in both orders, an expired whole-key entry
followed by a cutoff, past-`until` commands, invalid `revoke_through`
values, legacy bus messages, fractional `iat` at C and C + 0.5 through
real verification, replay-claim waits that cross an entry's expiry, and
root/audio handler straddle cases where the signed `iat` differs from
registration time.

Each of these was checked to fail when the code it guards is broken:
- the route's published bus message keeps the cutoff on another pod
(fails if `nip_fi_disconnect_message` drops `revoke_through`);
- a cutoff command over an active whole-key entry closes a fresh session
(fails if the route skips close-scope widening);
- a poisoned shard's close scope is whole-key;
- shadow `would_close` ends only sessions issued at or before C;
- a cutoff in Redis restores as a cutoff (fails if the accept script
stops writing the cutoff hash), and #9860's reader, taken from its final
head `02627cce`, decodes the same record as a whole-key deny;
- #9860's writer, copied verbatim from `02627cce`, writing over a stored
cutoff with an equal or shorter `until`, then a fresh restore by this
build, gives a whole-key deny;
- a full revoke that expires between authentication and its Redis write
neither widens a cutoff nor, once stored and expired, overrides one
(fails with the authentication clock);
- a whole key that is live when restore reads and expired when it merges
gives way to the stored cutoff (the load is gated, not slept; fails if
restore merges at the pre-read time);
- the Redis merge matches `DenyEntry::merge` for whole-over-cutoff,
cutoff-over-whole, two cutoffs under a shorter or longer `until`, and an
expired whole key (fails if a whole-key write stops clearing the
cutoff);
- pruning clears an expired entry's cutoff, from a fixture seeded
already expired in one atomic step;
- a same-`until` scope widening is `Merged`, not `Unchanged` (fails if
the change test compares `until` only);
- a cutoff that isn't an integer, is out of range or has no deny fails
the restore as `unreadable`;
- a malformed cutoff leaves its deny restorable as the whole key, an
orphan cutoff adds nothing, and a good cutoff still scopes its key,
while the load still fails as `unreadable`;
- a disconnect over a complete active deny whose stored cutoff is
fractional or out of range fails with the claim unused and the index
(with scores), exact and cutoff hashes unchanged (fails with the accept
script's check removed); the script's bounds are pinned to chrono's
range.
- through the real Redis load and restore, a readable deny next to a bad
record keeps its cutoff: a session issued at C is closed, one issued
after C stays open, and admission stays fenced (fails if the partial
payload drops scope).

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
This commit is contained in:
Will Pfleger
2026-11-24 19:44:03 -05:00
committed by GitHub
parent 61c070d591
commit e8a8e4cb6a
22 changed files with 2909 additions and 323 deletions

View File

@@ -68,6 +68,10 @@ pub struct NipFiDisconnect {
/// the signed command JWT is preserved across pod boundaries.
#[serde(default)]
pub until_unix_nanos: u32,
/// The command's `revoke_through` cutoff in whole seconds since the Unix
/// epoch. Absent means the deny covers the whole key.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoke_through: Option<i64>,
}
/// State of this pod's NIP-FI disconnect subscription. Every confirmed
@@ -586,6 +590,7 @@ mod tests {
pubkey_bytes: vec![0xabu8; 32],
until_unix: 9_999_999_999,
until_unix_nanos: 500_000_000,
revoke_through: None,
};
let json = serde_json::to_string(&cmd).unwrap();
let decoded: NipFiDisconnect = serde_json::from_str(&json).unwrap();
@@ -623,6 +628,7 @@ mod tests {
pubkey_bytes: vec![1u8; 32],
until_unix: 1_000_000,
until_unix_nanos: 0,
revoke_through: None,
})
.unwrap();
assert!(serde_json::from_str::<NipFiDisconnect>(&good).is_ok());

View File

@@ -11,9 +11,12 @@
//! removed only once its score is below `now`, so never early.
//! * `{deny}-until:{sha256(iss)}` — hash, field `pubkey_hex`, value the exact
//! signed `until` as `secs:nanos`, merged by maximum.
//! * `{deny}-revoke-through:{sha256(iss)}` — hash, field `pubkey_hex`: never
//! written here; every accept clears its target's field so a full revoke
//! is never narrowed by a cutoff another relay version stored.
//! * `{deny}-revoke-through:{sha256(iss)}` — hash, field `pubkey_hex`, value
//! the merged `revoke_through` cutoff, present only while the entry is
//! scoped to it; a missing field is a whole-key deny. It lives outside the
//! exact-`until` hash so relays that predate cutoffs still decode that hash
//! and read the entry as a whole-key deny; those relays clear the field on
//! every write, so their full revokes are never narrowed.
//!
//! Only the issuer's hash is stored; readers map it back through configured
//! issuers.
@@ -22,8 +25,8 @@ use buzz_auth::nip_fi::{
namespaced_command_replay_key, COMMAND_REPLAY_PREFIX, SHADOW_COMMAND_REPLAY_PREFIX,
};
use buzz_auth::{
error::AuthError, ClaimOutcome, CommandClaim, CommandReplayGuard, LoadDeniesError,
DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS,
error::AuthError, ClaimOutcome, CommandClaim, CommandReplayGuard, DenyEntry, DenyScope,
LoadDeniesError, DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS,
};
use chrono::{DateTime, Utc};
use nostr::PublicKey;
@@ -37,17 +40,34 @@ pub const DENY_STORE_PREFIX: &str = "buzz:nip-fi:deny";
pub const SHADOW_DENY_STORE_PREFIX: &str = "buzz:nip-fi:shadow-deny";
/// KEYS: claim, index, exact, cutoff. ARGV: ttl, pubkey_hex, score_ms, secs, nanos,
/// capacity, now_ms, active (0/1).
/// capacity, revoke_through ('' for the whole key). Whether the command and
/// the stored entry are still active is judged by Redis `TIME` as the script
/// runs, not by the clock the command was authenticated under. A stored
/// cutoff restore would reject returns 'unreadable' before any write.
const ACCEPT_SCRIPT: &str = r"
if redis.call('EXISTS', KEYS[1]) == 1 then return 'replay' end
local active = ARGV[8] == '1'
-- A stored cutoff restore would reject is refused here, before any write.
local stored = redis.call('HGET', KEYS[4], ARGV[2])
if stored then
local c = string.match(stored, '^[+-]?%d+$') and tonumber(stored)
if not c or c < -8334601228800 or c > 8210266876799 then return 'unreadable' end
end
local t = redis.call('TIME')
local ts, tn = tonumber(t[1]), tonumber(t[2]) * 1000
local now_ms = string.format('%.0f', ts * 1000 + math.floor(tn / 1000000))
local function live(v)
local s, n = string.match(v, '^(%-?%d+):(%d+)$')
s, n = tonumber(s), tonumber(n)
return s > ts or (s == ts and n > tn)
end
local active = live(ARGV[4] .. ':' .. ARGV[5])
if active then
local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', '(' .. ARGV[7])
local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', '(' .. now_ms)
for _, member in ipairs(expired) do
redis.call('HDEL', KEYS[3], member)
redis.call('HDEL', KEYS[4], member)
end
redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', '(' .. ARGV[7])
redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', '(' .. now_ms)
if not redis.call('ZSCORE', KEYS[2], ARGV[2])
and redis.call('ZCARD', KEYS[2]) >= tonumber(ARGV[6]) then
return 'full'
@@ -65,7 +85,22 @@ if active then
keep = s > ns or (s == ns and n >= nn)
end
if not keep then redis.call('HSET', KEYS[3], ARGV[2], ARGV[4] .. ':' .. ARGV[5]) end
redis.call('HDEL', KEYS[4], ARGV[2])
-- Scope merge: an active stored entry without a cutoff is the whole key and
-- wins; two cutoffs keep the later one. An expired entry contributes none.
local cut = ARGV[7]
if cut ~= '' and cur and live(cur) then
local prior = redis.call('HGET', KEYS[4], ARGV[2])
if not prior or not tonumber(prior) then
cut = ''
elseif tonumber(prior) > tonumber(cut) then
cut = prior
end
end
if cut == '' then
redis.call('HDEL', KEYS[4], ARGV[2])
else
redis.call('HSET', KEYS[4], ARGV[2], cut)
end
local top = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
redis.call('PEXPIREAT', KEYS[2], top[2])
redis.call('PEXPIREAT', KEYS[3], top[2])
@@ -165,8 +200,12 @@ impl CommandReplayGuard for RedisCommandReplayGuard {
.arg(claim.until.timestamp())
.arg(claim.until.timestamp_subsec_nanos())
.arg(claim.capacity)
.arg(claim.now.timestamp_millis())
.arg(u8::from(claim.until > claim.now))
.arg(
claim
.scope
.revoke_through()
.map_or_else(String::new, |c| c.to_string()),
)
.invoke_async(&mut conn)
.await
.map_err(internal)?;
@@ -174,6 +213,11 @@ impl CommandReplayGuard for RedisCommandReplayGuard {
"claimed" => Ok(ClaimOutcome::Claimed),
"replay" => Ok(ClaimOutcome::Replay),
"full" => Ok(ClaimOutcome::Full),
"unreadable" => {
let record = format!("revoke_through for {}", claim.target.to_hex());
tracing::warn!(record, "nip-fi command store: unreadable deny record");
Err(internal(format!("unreadable deny record: {record}")))
}
other => Err(internal(format!("unexpected reply: {other}"))),
}
})
@@ -183,26 +227,22 @@ impl CommandReplayGuard for RedisCommandReplayGuard {
Box::pin(async move {
let (_, exact) = deny_store_keys(&self.deny_prefix, issuer);
let mut conn = self.pool.clone();
let entries: Vec<(Vec<u8>, Vec<u8>)> = redis::cmd("HGETALL")
.arg(exact)
.query_async(&mut conn)
// One script, so a cutoff is never paired with a deadline it was
// not written with.
let (entries, cutoffs): (RawHash, RawHash) = redis::Script::new(SNAPSHOT_SCRIPT)
.key(exact)
.key(revoke_through_key(&self.deny_prefix, issuer))
.invoke_async(&mut conn)
.await
.map_err(internal)?;
// An unreadable record fails the load: skipping it would reopen
// admission without that revocation. Every other record is
// still decoded, so the caller can apply them meanwhile.
let mut denies = Vec::with_capacity(entries.len());
let mut bad = None;
for (key, until) in entries {
match decode(key, until) {
Ok((key, until)) if until > now => denies.push((key, until)),
Ok(_) => {}
Err(record) => {
tracing::warn!(record, "nip-fi command store: unreadable deny record");
bad.get_or_insert(record);
}
}
}
let entries = utf8_pairs(entries, &mut bad);
let cutoffs = utf8_pairs(cutoffs, &mut bad);
let untils = decode_untils(&entries, now, &mut bad);
let denies = join_cutoffs(untils, &entries, cutoffs, &mut bad);
match bad {
None => Ok(denies),
Some(record) => Err(LoadDeniesError::Unreadable {
@@ -214,25 +254,116 @@ impl CommandReplayGuard for RedisCommandReplayGuard {
}
}
/// A hash as `HGETALL` returns it: field and value bytes.
type RawHash = Vec<(Vec<u8>, Vec<u8>)>;
/// Keeps the first unreadable record and logs every one.
fn note(bad: &mut Option<String>, record: String) {
tracing::warn!(record, "nip-fi command store: unreadable deny record");
bad.get_or_insert(record);
}
/// A hash's fields and values as text; a record that isn't UTF-8 is
/// unreadable and left out.
fn utf8_pairs(raw: RawHash, bad: &mut Option<String>) -> Vec<(String, String)> {
raw.into_iter()
.filter_map(
|(key, value)| match (String::from_utf8(key), String::from_utf8(value)) {
(Ok(key), Ok(value)) => Some((key, value)),
_ => {
note(bad, "deny record that is not UTF-8".into());
None
}
},
)
.collect()
}
/// KEYS: exact, cutoff. Both hashes as one snapshot.
const SNAPSHOT_SCRIPT: &str = r"
return {redis.call('HGETALL', KEYS[1]), redis.call('HGETALL', KEYS[2])}
";
/// The exact-`until` hash's active entries. This is the whole of the reader
/// in relays that predate cutoffs, which therefore read every entry as a
/// whole-key deny. An unreadable record is noted in `bad` and left out; the
/// others still decode.
fn decode_untils(
entries: &[(String, String)],
now: DateTime<Utc>,
bad: &mut Option<String>,
) -> Vec<(PublicKey, DateTime<Utc>)> {
let mut denies = Vec::with_capacity(entries.len());
for (key, until) in entries {
let Ok(pubkey) = PublicKey::from_hex(key) else {
note(bad, format!("deny key {key}"));
continue;
};
match parse_until(until) {
Some(until) if until > now => denies.push((pubkey, until)),
Some(_) => {}
None => note(bad, format!("deny until {until} for {key}")),
}
}
denies
}
/// Scope each active deny by its cutoff field; a missing field is the whole
/// key. A cutoff that doesn't decode, or that names no stored deny, is
/// noted in `bad`; a deny under an undecodable cutoff stays the whole key.
fn join_cutoffs(
untils: Vec<(PublicKey, DateTime<Utc>)>,
entries: &[(String, String)],
cutoffs: Vec<(String, String)>,
bad: &mut Option<String>,
) -> Vec<(PublicKey, DenyEntry)> {
let denied: std::collections::HashSet<&str> = entries.iter().map(|(k, _)| k.as_str()).collect();
let mut scopes = std::collections::HashMap::with_capacity(cutoffs.len());
for (key, cutoff) in cutoffs {
if !denied.contains(key.as_str()) {
note(bad, format!("revoke_through for {key} without a deny"));
continue;
}
match cutoff
.parse::<i64>()
.ok()
.filter(|c| DateTime::from_timestamp(*c, 0).is_some())
{
Some(c) => {
scopes.insert(key, DenyScope::IssuedThrough(c));
}
None => note(bad, format!("revoke_through {cutoff} for {key}")),
}
}
untils
.into_iter()
.map(|(key, until)| {
let scope = scopes
.get(&key.to_hex())
.copied()
.unwrap_or(DenyScope::WholeKey);
(key, DenyEntry { until, scope })
})
.collect()
}
fn parse_until(value: &str) -> Option<DateTime<Utc>> {
let (secs, nanos) = value.split_once(':')?;
DateTime::from_timestamp(secs.parse().ok()?, nanos.parse().ok()?)
}
/// One `HGETALL` field and value as a deny, or the record that won't decode.
fn decode(key: Vec<u8>, until: Vec<u8>) -> Result<(PublicKey, DateTime<Utc>), String> {
let (Ok(key), Ok(until)) = (String::from_utf8(key), String::from_utf8(until)) else {
return Err("deny record that is not UTF-8".into());
};
let key = PublicKey::from_hex(&key).map_err(|_| format!("deny key {key}"))?;
let until = parse_until(&until).ok_or_else(|| format!("deny until {until} for {key}"))?;
Ok((key, until))
}
#[cfg(test)]
mod tests {
use super::*;
/// The accept script's cutoff bounds are restore's `from_timestamp` range.
#[test]
fn accept_cutoff_bounds_match_restore() {
for bound in [DateTime::<Utc>::MIN_UTC, DateTime::<Utc>::MAX_UTC] {
assert!(ACCEPT_SCRIPT.contains(&bound.timestamp().to_string()));
}
}
#[test]
fn ceil_ms_never_rounds_down() {
let t = DateTime::from_timestamp(10, 1).unwrap();
@@ -252,6 +383,70 @@ mod tests {
);
}
/// A bad cutoff does not hide the others: a good one still scopes its
/// key, a malformed one leaves its deny the whole key, an orphan adds
/// nothing, and the first bad record is kept.
#[test]
fn cutoff_join_keeps_readable_records_past_bad_ones() {
let [good, malformed, orphan] =
std::array::from_fn(|i| PublicKey::from_hex(&format!("{:064x}", i + 1)).unwrap());
let until = DateTime::from_timestamp(100, 0).unwrap();
let entries: Vec<_> = [good, malformed]
.iter()
.map(|k| (k.to_hex(), "100:0".to_owned()))
.collect();
let cutoffs = vec![
(good.to_hex(), "10".to_owned()),
(malformed.to_hex(), "12.5".to_owned()),
(orphan.to_hex(), "10".to_owned()),
];
let mut bad = None;
let joined = join_cutoffs(
vec![(good, until), (malformed, until)],
&entries,
cutoffs,
&mut bad,
);
assert_eq!(
joined,
vec![
(
good,
DenyEntry {
until,
scope: DenyScope::IssuedThrough(10)
}
),
(
malformed,
DenyEntry {
until,
scope: DenyScope::WholeKey
}
),
]
);
assert_eq!(
bad,
Some(format!("revoke_through 12.5 for {}", malformed.to_hex()))
);
}
/// A full issuer at the default capacity joins every cutoff to its key.
#[test]
fn cutoff_join_handles_a_full_issuer() {
let entries: Vec<_> = (0..50_000)
.map(|i| (format!("{i:064x}"), "1:0".to_owned()))
.collect();
let cutoffs = entries
.iter()
.map(|(k, _)| (k.clone(), "10".to_owned()))
.collect();
let mut bad = None;
join_cutoffs(Vec::new(), &entries, cutoffs, &mut bad);
assert_eq!(bad, None);
}
#[test]
fn exact_until_round_trips() {
let t = DateTime::from_timestamp(1_795_000_000, 123_456_789).unwrap();