Skip to content

Commit c0932db

Browse files
wpfleger96Duncanwpfleger
authored
fix(relay): persist NIP-FI revocations across restarts and bridge shadow to enforce (#9860)
## Summary Stack: this PR → #9917 NIP-FI revocations (deny entries from `POST /api/nip-fi/disconnect`) now survive relay restarts and lost pub/sub subscriptions, and an enforce relay can optionally carry over revocations accepted during the `shadow` period. ## Changes - **Durable deny store (Redis).** Per mode and issuer hash, a sorted set (score = `until` in ms, rounded up) plus a hash holding the exact signed `until`, merged by maximum. One Lua script runs all checks before any write: replay → expiry/capacity → write. Outcomes: claimed, replay (403), full (503, nothing written). Every write and prune also clears the target's field in the issuer's revoke-through cutoff hash, so a full revoke is never narrowed by a cutoff a newer relay version stored. A Redis error is an unknown outcome (503); the issuer sends a fresh command. - **Shared capacity.** `deny_set_capacity` is enforced in Redis, across pods. - **Fail-closed restore.** A pod starts closed to protected admission, refusing as authorization unavailable (HTTP 503 and the matching Nostr denial on root and audio AUTH; `shadow` records it as unavailable). Active deny entries still refuse with 403. Each key's verdict (allowed, denied, unavailable) comes from one read of the deny map, so a restore that starts mid-check is never reported as a revocation. A single consumer task restores by generation: wait for a confirmed subscription, load the stores, apply buffered messages, then reopen. A reconnect, a lag, or a received deny that does not fit the local capacity starts a new generation, so admission reopens only once the active union fits. A restore merges every stored entry first, then closes sessions only for targets it added or extended (also when it fails part-way; a capacity miss or a store error for one issuer or source doesn't end the pass, so every reachable target is still merged or closed and the first failure keeps admission closed), so restoring after a Redis blip doesn't walk every connection once per entry. While a restore keeps failing, the consumer still applies disconnects that arrive, so revoked sessions close while admission stays closed; the retry runs on a fixed one-second deadline that traffic can't push back. A stored deny record that doesn't parse fails the restore rather than being skipped; the issuer's other records are still applied and their sessions closed. Restore failures are counted in `buzz_nip_fi_deny_restore_failures_total{reason}`; a stored record that doesn't decode is counted as `reason="unreadable"`, apart from `store` (Redis unavailable). - **Bridge setting.** `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` (default false, enforce only) makes an enforce pod also subscribe to the shadow channel and restore the shadow store. - **NIP-FI spec.** Restart behaviour now allows shared storage that is restored before protected connections or HTTP requests are admitted. Disconnects document the unknown-outcome reply: when a relay can't tell whether its shared-storage write applied, it returns `503` `authorization unavailable` and closes no sessions, and the caller retries with a freshly signed command (new `jti`). Added to the step 7 pseudocode, the disconnect response table and the `authorization_unavailable` rejection row. - **Runbook.** New "Revocation during a deploy" section in `docs/operator-nip-fi-bindings.md`: coverage (restarts, not lost Redis data), non-evicting Redis, disconnect responses, capacity, boot behaviour when Redis is unreachable, recovering from an unreadable deny record (`HDEL`), and the shadow → enforce rollout steps. ## Tests - Restart restores denies from the shared store; unavailable store keeps admission closed; consumer reopens only for a live, restored subscription. - Store error returns 503 and the command retries; lost reply returns 503 and needs a fresh command. - Capacity enforced across pods; over-capacity restore stays closed; a capacity miss during the restore handoff or after a successful restore keeps or closes admission. - A restoring deny map refuses as unavailable (503 / bare close), not revoked, at each admission point: WebSocket upgrade, protected HTTP, root AUTH and audio, and when the restore starts during the check. - Restore closes only added or extended targets, still closes them when it fails part-way (a capacity miss, a failing source before a healthy one, and the first-visited issuer failing before a healthy one, and an unreadable record reported as `unreadable`, not `store`), and live delivery of an unchanged entry still closes sessions. A broadcast lag after a restore restores again. During repeated restore failures, delivered disconnects still close their sessions, admission stays closed, and steady traffic doesn't delay the next attempt (run on a paused Tokio clock). - The buzz-pubsub deny-store key and rounding unit tests now run in `just test-unit` and `run-tests.sh`. - Subscribe channels and restore sources follow mode and bridge; config rejects the bridge outside enforce. - Redis-backed (ignored, run in CI's NIP-FI Redis step; each case uses its own store namespace): script checks before writing and keeps exact `until`; expired entries free their slot and a shorter command never lowers a score (`ZADD GT`); bridge restores shadow-period denies on enforce pods; a record with an unreadable key or `until` fails the load while every readable active record after it still loads, and expired entries are still filtered; restore applies a good record past a bad one for the same issuer, closing its sessions and leaving others open, fails as `unreadable` with admission unavailable, and reopens on retry once the record is removed (fixture hashes expire after 60s); an accept with an equal or shorter `until`, and a prune, clear the target's stored cutoff. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: wpfleger <wpfleger@users.noreply.github.com>
1 parent 166245b commit c0932db

25 files changed

Lines changed: 2890 additions & 299 deletions

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Justfile‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,9 +408,10 @@ test-unit:
408408
cargo nextest run -p buzz-audit --lib
409409
# Cross-pod disconnect payload tests (NIP-FI and community archive
410410
# fence), the shared Redis connection's timeout bounds (loopback
411-
# fake peers), and the full-queue retain (no Redis dialed); all
412-
# infra-free. Keep the Cargo fallback in step.
413-
cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/) + test(/^connection::tests::/) + test(=tests::queue_full_retain_does_not_wait_and_schedules_reconciliation)'
411+
# fake peers), the full-queue retain (no Redis dialed), and the NIP-FI
412+
# deny-store key and rounding tests; all infra-free. Keep the Cargo
413+
# fallback in step.
414+
cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/) + test(/^connection::tests::/) + test(=tests::queue_full_retain_does_not_wait_and_schedules_reconciliation) + test(/^nip_fi_command_replay::tests::/)'
414415
# buzz-auth NIP-FI verifier doctests. The sealed-authority
415416
# `compile_fail` doctests prove the default-feature public API alone
416417
# cannot forge the issuer→JWKS authority; nextest does not run

‎crates/buzz-auth/src/lib.rs‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -76,17 +76,17 @@ pub use scope::{parse_scopes, Scope};
7676

7777
pub use nip_fi::{
7878
command_replay_key, validate_nip_fi_config, AssertionKeySet, AssertionPolicyId, BindRefusal,
79-
CanonicalCapabilities, ClientSubjectPosture, CommandError, CommandIssuerPolicy,
80-
CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier, CommunityBinding,
81-
CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult, DenialClass, DenySetFull,
82-
FederatedAssertionVerifier, FederatedIdentity, FederatedIdentityDiscovery, FreshnessClass,
83-
HttpJwksFetcher, IssuerCapacity, IssuerJwksConfig, IssuerKeySource, IssuerPolicy,
84-
IssuerPolicyError, IssuerRegistry, JwksFetchError, JwksFetcher, JwksSourceContract,
85-
NipFiDenyMap, NipFiMode, NipFiStartupError, ProductionJwksSource, ProvisionBindingError,
86-
ProvisionBindingPolicy, RevalidationDependencies, SubjectClass, SubjectClassContract,
87-
TokenClass, TransportContractId, VerifiedAssertion, VerifierError, VerifyAssertion,
88-
CLIENT_ATTACHED_HEADER, COMMAND_JWT_TYP, MAX_COMMAND_AGE_SECONDS, NOSTR_OWNER_PUBKEY_CLAIM,
89-
NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM,
79+
CanonicalCapabilities, ClaimOutcome, ClientSubjectPosture, CommandClaim, CommandError,
80+
CommandIssuerPolicy, CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier,
81+
CommunityBinding, CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult,
82+
DenialClass, DenySetFull, DenyStatus, FederatedAssertionVerifier, FederatedIdentity,
83+
FederatedIdentityDiscovery, FreshnessClass, HttpJwksFetcher, IssuerCapacity, IssuerJwksConfig,
84+
IssuerKeySource, IssuerPolicy, IssuerPolicyError, IssuerRegistry, JwksFetchError, JwksFetcher,
85+
JwksSourceContract, LoadDenies, LoadDeniesError, NipFiDenyMap, NipFiMode, NipFiStartupError,
86+
ProductionJwksSource, ProvisionBindingError, ProvisionBindingPolicy, RevalidationDependencies,
87+
SubjectClass, SubjectClassContract, TokenClass, TransportContractId, VerifiedAssertion,
88+
VerifierError, VerifyAssertion, CLIENT_ATTACHED_HEADER, COMMAND_JWT_TYP,
89+
MAX_COMMAND_AGE_SECONDS, NOSTR_OWNER_PUBKEY_CLAIM, NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM,
9090
};
9191

9292
#[cfg(any(test, feature = "test-utils"))]

‎crates/buzz-auth/src/nip_fi/command.rs‎

Lines changed: 51 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,19 @@
1515
//! claim ([`super::command_replay`]), then commit the slot (both-or-neither).
1616
//! 7. Return [`CommandResult`].
1717
//!
18-
//! Fail-closed: any failure inserts no deny entry, closes no session and
19-
//! publishes nothing. A failure after step 6's shared claim may leave that
20-
//! claim in place until its TTL (a guard error whose `SET` reply was lost, or a
21-
//! process stopped between claim and commit); that is fail closed, since a
22-
//! retry is then denied.
18+
//! Fail-closed: a rejected command inserts no deny entry, closes no session
19+
//! and publishes nothing. A guard error is an unknown outcome: the shared
20+
//! claim and durable deny may already be written (a lost reply), so a retry
21+
//! of the same command may be refused as a replay and the issuer sends a
22+
//! fresh command. A process stopped between claim and local commit leaves
23+
//! the durable deny for the next restore.
2324
2425
use chrono::{DateTime, Utc};
2526
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
2627
use nostr::PublicKey;
2728
use serde_json::{Map, Value};
2829

29-
use super::command_replay::CommandReplayGuard;
30+
use super::command_replay::{ClaimOutcome, CommandClaim, CommandReplayGuard};
3031
use super::config::{
3132
IssuerPolicy, IssuerRegistry, MAX_JTI_BYTES, MAX_SUBJECT_BYTES, MAX_TOKEN_BYTES,
3233
};
@@ -262,17 +263,19 @@ impl<S: IssuerKeySource + Clone> CommandVerifier<S> {
262263
/// * `body_pubkey` — the `pubkey` field parsed from the JSON body.
263264
/// * `replay` — the shared command replay guard.
264265
///
265-
/// Order: authenticate, reserve a local slot, claim `(iss, jti)` in the
266-
/// shared guard, then commit the slot. A full deny set fails before the
267-
/// shared claim, so `DenySetFull` never consumes the command and it can be
268-
/// retried. A replayed or failed claim, or a cancelled future, drops the
269-
/// local slot; the commit after a successful claim cannot fail.
266+
/// Order: authenticate, reserve a local slot, then in one shared step
267+
/// check replay and the issuer's shared capacity and, only if both pass,
268+
/// claim `(iss, jti)` and record the deny entry durably; then commit the
269+
/// slot. A full deny set (local or shared) writes nothing, so
270+
/// `DenySetFull` never consumes the command and it can be retried. A
271+
/// replayed or failed claim, or a cancelled future, drops the local slot;
272+
/// the commit after a successful claim cannot fail.
270273
///
271-
/// A claim can still remain without a local deny entry when Redis applied
272-
/// it but its reply was lost (`AuthorizationUnavailable`), or when the
273-
/// process stops between claim and commit. That inserts no deny entry,
274-
/// closes no session and publishes nothing; it fails closed, since a retry
275-
/// is denied until the claim's TTL.
274+
/// When the shared step applied but its reply was lost
275+
/// (`AuthorizationUnavailable`), or the process stops between claim and
276+
/// commit, the claim and the durable deny entry remain without a local
277+
/// one. The entry reaches pods at their next restore; a retry of the
278+
/// same command is a replay, so the issuer sends a fresh command.
276279
pub async fn verify(
277280
&self,
278281
token: &str,
@@ -286,16 +289,19 @@ impl<S: IssuerKeySource + Clone> CommandVerifier<S> {
286289
let reservation = self.reserve(&cmd, now)?;
287290
// Cover the command's remaining validity plus this pod's skew, so a
288291
// pod whose clock trails still sees the claim; the guard floors this.
289-
match replay
290-
.try_claim(
291-
&cmd.issuer,
292-
&cmd.jti,
293-
claim_ttl_secs(cmd.effective_expiry, now, cmd.skew_seconds),
294-
)
295-
.await
296-
{
297-
Ok(true) => {}
298-
Ok(false) => return Err(CommandError::AuthorizationDenied),
292+
let claim = CommandClaim {
293+
issuer: &cmd.issuer,
294+
jti: &cmd.jti,
295+
ttl_secs: claim_ttl_secs(cmd.effective_expiry, now, cmd.skew_seconds),
296+
target: &cmd.target_pubkey,
297+
until: cmd.until,
298+
capacity: cmd.capacity,
299+
now,
300+
};
301+
match replay.try_claim(claim).await {
302+
Ok(ClaimOutcome::Claimed) => {}
303+
Ok(ClaimOutcome::Replay) => return Err(CommandError::AuthorizationDenied),
304+
Ok(ClaimOutcome::Full) => return Err(CommandError::DenySetFull),
299305
Err(_) => return Err(CommandError::AuthorizationUnavailable),
300306
}
301307
Ok(Self::commit(&cmd, reservation))
@@ -479,6 +485,7 @@ impl<S: IssuerKeySource + Clone> CommandVerifier<S> {
479485
effective_expiry: exp.min(iat_plus_cmd_age),
480486
until,
481487
skew_seconds: base_policy.skew_seconds(),
488+
capacity: cmd_policy.deny_set_capacity(),
482489
})
483490
}
484491

@@ -517,6 +524,7 @@ struct AuthenticatedCommand {
517524
effective_expiry: DateTime<Utc>,
518525
until: DateTime<Utc>,
519526
skew_seconds: u64,
527+
capacity: usize,
520528
}
521529

522530
// ── Internal helpers ──────────────────────────────────────────────────────────
@@ -1372,6 +1380,7 @@ mod tests {
13721380
enum Claim {
13731381
Accept,
13741382
Replay,
1383+
Full,
13751384
Fail,
13761385
Hang,
13771386
}
@@ -1398,12 +1407,12 @@ mod tests {
13981407
impl CommandReplayGuard for ScriptedGuard {
13991408
fn try_claim<'a>(
14001409
&'a self,
1401-
_issuer: &'a str,
1402-
_jti: &'a str,
1403-
_ttl_secs: u64,
1410+
_claim: CommandClaim<'a>,
14041411
) -> std::pin::Pin<
14051412
Box<
1406-
dyn std::future::Future<Output = Result<bool, crate::error::AuthError>> + Send + 'a,
1413+
dyn std::future::Future<Output = Result<ClaimOutcome, crate::error::AuthError>>
1414+
+ Send
1415+
+ 'a,
14071416
>,
14081417
> {
14091418
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
@@ -1412,13 +1421,22 @@ mod tests {
14121421
// Yield once so concurrent verifies interleave at the claim.
14131422
tokio::task::yield_now().await;
14141423
match claim {
1415-
Claim::Accept => Ok(true),
1416-
Claim::Replay => Ok(false),
1424+
Claim::Accept => Ok(ClaimOutcome::Claimed),
1425+
Claim::Replay => Ok(ClaimOutcome::Replay),
1426+
Claim::Full => Ok(ClaimOutcome::Full),
14171427
Claim::Fail => Err(crate::error::AuthError::Internal("simulated".into())),
14181428
Claim::Hang => std::future::pending().await,
14191429
}
14201430
})
14211431
}
1432+
1433+
fn load_denies<'a>(
1434+
&'a self,
1435+
_issuer: &'a str,
1436+
_now: DateTime<Utc>,
1437+
) -> crate::nip_fi::LoadDenies<'a> {
1438+
Box::pin(async { Ok(Vec::new()) })
1439+
}
14221440
}
14231441

14241442
/// A verifier whose issuer shard holds exactly one deny entry.
@@ -1494,6 +1512,7 @@ mod tests {
14941512
let cv = one_slot_verifier();
14951513
for (claim, expected) in [
14961514
(Claim::Replay, CommandError::AuthorizationDenied),
1515+
(Claim::Full, CommandError::DenySetFull),
14971516
(Claim::Fail, CommandError::AuthorizationUnavailable),
14981517
] {
14991518
let target = target_key();

‎crates/buzz-auth/src/nip_fi/command_replay.rs‎

Lines changed: 122 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,94 @@
88
//! The claim is taken after the command is fully authenticated (so a forgery
99
//! cannot burn a legitimate `jti`) and after this pod has reserved its local
1010
//! deny-entry slot (so a `503 deny set full` never consumes the command).
11+
//!
12+
//! The same atomic step also records the deny entry durably, so a restarted
13+
//! pod can restore it (see [`CommandReplayGuard::load_denies`]). Every check
14+
//! (replay, shared capacity) runs before any write: a `Replay` or `Full`
15+
//! outcome leaves the store unchanged.
1116
1217
use std::{future::Future, pin::Pin};
1318

19+
use chrono::{DateTime, Utc};
20+
use nostr::PublicKey;
21+
1422
use sha2::{Digest, Sha256};
1523

1624
use crate::error::AuthError;
1725

18-
/// Shared seen-set for NIP-FI command `(iss, jti)` pairs.
26+
/// One authenticated command, as presented to the shared store.
27+
#[derive(Debug, Clone, Copy)]
28+
pub struct CommandClaim<'a> {
29+
/// Exact `iss` of the command.
30+
pub issuer: &'a str,
31+
/// The command's `jti`.
32+
pub jti: &'a str,
33+
/// Claim TTL; implementations clamp it as the NIP-98 guard does.
34+
pub ttl_secs: u64,
35+
/// The signed target key.
36+
pub target: &'a PublicKey,
37+
/// The signed `until`, exact.
38+
pub until: DateTime<Utc>,
39+
/// This issuer's `deny_set_capacity`, enforced across every pod.
40+
pub capacity: usize,
41+
/// Verifier clock: entries with `until <= now` are expired.
42+
pub now: DateTime<Utc>,
43+
}
44+
45+
/// Outcome of [`CommandReplayGuard::try_claim`].
46+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47+
pub enum ClaimOutcome {
48+
/// The claim is new; the deny entry (if `until > now`) is recorded.
49+
Claimed,
50+
/// `(iss, jti)` was already claimed. Nothing was written.
51+
Replay,
52+
/// The issuer's shared deny set is full. Nothing was written, so the
53+
/// same command may be retried.
54+
Full,
55+
}
56+
57+
/// Shared seen-set and durable deny store for NIP-FI commands.
1958
///
20-
/// The production implementation lives in `buzz-pubsub` (Redis `SET NX EX`).
59+
/// The production implementation lives in `buzz-pubsub` (one Redis script).
2160
/// An in-memory implementation is provided behind
2261
/// `cfg(any(test, feature = "test-utils"))`.
2362
pub trait CommandReplayGuard: Send + Sync {
24-
/// Atomically claim `(issuer, jti)`.
63+
/// Atomically check replay and shared capacity, then claim `(iss, jti)`
64+
/// and record the deny entry.
2565
///
26-
/// Returns `Ok(true)` when newly claimed (proceed) and `Ok(false)` when
27-
/// already claimed (the caller MUST reject the command as replay). On
28-
/// `Err` callers MUST fail closed. Implementations MUST use an atomic
29-
/// set-if-absent and clamp `ttl_secs` to
30-
/// [`crate::DEFAULT_REPLAY_TTL_SECS`]..=[`crate::MAX_REPLAY_TTL_SECS`],
31-
/// as the NIP-98 guard does.
66+
/// On `Err` the outcome is unknown (the write may have applied and only
67+
/// its reply been lost); callers MUST fail closed.
3268
fn try_claim<'a>(
3369
&'a self,
34-
issuer: &'a str,
35-
jti: &'a str,
36-
ttl_secs: u64,
37-
) -> Pin<Box<dyn Future<Output = Result<bool, AuthError>> + Send + 'a>>;
70+
claim: CommandClaim<'a>,
71+
) -> Pin<Box<dyn Future<Output = Result<ClaimOutcome, AuthError>> + Send + 'a>>;
72+
73+
/// Every recorded deny entry for `issuer` with `until > now`, at its exact
74+
/// signed `until`.
75+
fn load_denies<'a>(&'a self, issuer: &'a str, now: DateTime<Utc>) -> LoadDenies<'a>;
76+
}
77+
78+
/// The future [`CommandReplayGuard::load_denies`] returns.
79+
pub type LoadDenies<'a> = Pin<
80+
Box<dyn Future<Output = Result<Vec<(PublicKey, DateTime<Utc>)>, LoadDeniesError>> + Send + 'a>,
81+
>;
82+
83+
/// Why [`CommandReplayGuard::load_denies`] failed.
84+
#[derive(Debug, thiserror::Error)]
85+
pub enum LoadDeniesError {
86+
/// The store could not be read.
87+
#[error(transparent)]
88+
Store(#[from] AuthError),
89+
/// A stored deny record could not be decoded. `readable` holds every
90+
/// active record that did decode, so the caller can still apply them;
91+
/// the load is still a failure.
92+
#[error("unreadable deny record: {record}")]
93+
Unreadable {
94+
/// The first record that could not be decoded.
95+
record: String,
96+
/// The active records that decoded.
97+
readable: Vec<(PublicKey, DateTime<Utc>)>,
98+
},
3899
}
39100

40101
/// Redis key for a command replay claim:
@@ -67,22 +128,62 @@ pub fn namespaced_command_replay_key(prefix: &str, issuer: &str, jti: &str) -> S
67128
format!("{prefix}:{}", hex::encode(hasher.finalize()))
68129
}
69130

70-
/// Process-local seen-set for tests. Instances shared via `Arc` model pods
131+
/// Process-local store for tests. Instances shared via `Arc` model pods
71132
/// sharing one Redis.
72133
#[cfg(any(test, feature = "test-utils"))]
73134
#[derive(Default)]
74-
pub struct InMemoryCommandReplayGuard(std::sync::Mutex<std::collections::HashSet<String>>);
135+
pub struct InMemoryCommandReplayGuard(std::sync::Mutex<InMemoryStore>);
136+
137+
#[cfg(any(test, feature = "test-utils"))]
138+
#[derive(Default)]
139+
struct InMemoryStore {
140+
claims: std::collections::HashSet<String>,
141+
denies: std::collections::HashMap<String, std::collections::HashMap<PublicKey, DateTime<Utc>>>,
142+
}
75143

76144
#[cfg(any(test, feature = "test-utils"))]
77145
impl CommandReplayGuard for InMemoryCommandReplayGuard {
78146
fn try_claim<'a>(
79147
&'a self,
80-
issuer: &'a str,
81-
jti: &'a str,
82-
_ttl_secs: u64,
83-
) -> Pin<Box<dyn Future<Output = Result<bool, AuthError>> + Send + 'a>> {
84-
let key = command_replay_key(issuer, jti);
85-
Box::pin(async move { Ok(self.0.lock().expect("replay set").insert(key)) })
148+
claim: CommandClaim<'a>,
149+
) -> Pin<Box<dyn Future<Output = Result<ClaimOutcome, AuthError>> + Send + 'a>> {
150+
let key = command_replay_key(claim.issuer, claim.jti);
151+
let mut store = self.0.lock().expect("replay store");
152+
let outcome = if store.claims.contains(&key) {
153+
ClaimOutcome::Replay
154+
} else {
155+
let active = claim.until > claim.now;
156+
let denies = store.denies.entry(claim.issuer.to_owned()).or_default();
157+
denies.retain(|_, until| *until > claim.now);
158+
if active && !denies.contains_key(claim.target) && denies.len() >= claim.capacity {
159+
ClaimOutcome::Full
160+
} else {
161+
if active {
162+
let until = denies.entry(*claim.target).or_insert(claim.until);
163+
*until = (*until).max(claim.until);
164+
}
165+
store.claims.insert(key);
166+
ClaimOutcome::Claimed
167+
}
168+
};
169+
Box::pin(async move { Ok(outcome) })
170+
}
171+
172+
fn load_denies<'a>(&'a self, issuer: &'a str, now: DateTime<Utc>) -> LoadDenies<'a> {
173+
let denies = self
174+
.0
175+
.lock()
176+
.expect("replay store")
177+
.denies
178+
.get(issuer)
179+
.map(|d| {
180+
d.iter()
181+
.filter(|(_, u)| **u > now)
182+
.map(|(k, u)| (*k, *u))
183+
.collect()
184+
})
185+
.unwrap_or_default();
186+
Box::pin(async move { Ok(denies) })
86187
}
87188
}
88189

0 commit comments

Comments
 (0)