Watch
0
0
Fork
You've already forked hyperhive
0

swarm-nats-auth: a callout lookup is cut off at the request's exp

This commit is contained in:
maia 2026-11-30 15:22:37 +01:00 • committed by mara
commit 17057e4258
2 changed files with 114 additions and 42 deletions

View file

@ -8,6 +8,8 @@
//! A token without the prefix is not this module's: it goes to introspection
//! unchanged.
use std::time::Duration;
use swarm_agent_verify::CredentialSource;
use swarm_agent_verify::agent_token::{AgentToken, Malformed, parse_agent_token};
@ -36,16 +38,17 @@ pub fn classify(token: &str) -> Presented<'_> {
/// The grant for an agent token, or `None` for a denial.
///
/// The store lookup is bounded by introspection's budget, under the server's
/// `authorization.timeout`. A store that does not answer holds one of the
/// The store lookup is bounded by `budget`, which the caller keeps under the
/// server's `authorization.timeout`. A store that does not answer holds one of the
/// responder's `CONCURRENT_REQUESTS` permits for at most that long, and this
/// then denies.
pub async fn authorize(
policy: &Policy,
source: &impl CredentialSource,
token: &AgentToken<'_>,
budget: Duration,
) -> Option<Permissions> {
if !swarm_agent_verify::verify(source, token, crate::introspect::INTROSPECTION_TIMEOUT).await {
if !swarm_agent_verify::verify(source, token, budget).await {
return None;
}
let permissions = policy.agent_token_permissions(token.agent);
@ -103,7 +106,13 @@ mod tests {
let Presented::Agent(token) = classify(token) else {
panic!("{token:?} must classify as an agent token");
};
authorize(&policy(), source, &token).await
authorize(
&policy(),
source,
&token,
crate::introspect::INTROSPECTION_TIMEOUT,
)
.await
}
#[tokio::test]
@ -158,7 +167,16 @@ mod tests {
let Presented::Agent(token) = classify("swarm-agent.atlas.Ab9_-zSECRET") else {
panic!("an agent token");
};
assert!(authorize(&bare, &Fake::Atlas, &token).await.is_none());
assert!(
authorize(
&bare,
&Fake::Atlas,
&token,
crate::introspect::INTROSPECTION_TIMEOUT
)
.await
.is_none()
);
}
/// Everything without the prefix reaches introspection as it arrived.

View file

@ -31,7 +31,7 @@
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::Context;
use clap::{Parser, Subcommand};
@ -288,7 +288,8 @@ async fn serve(args: Args, stop: swarm_secret_client::Shutdown) -> anyhow::Resul
let responder = Arc::clone(&responder);
let client = client.clone();
async move {
let Some((reply_to, reply)) = responder.answer(&msg).await else {
let Some((reply_to, reply)) = responder.answer(&msg, SystemTime::now()).await
else {
return;
};
if let Err(e) = client.publish(reply_to, reply.into()).await {
@ -331,19 +332,27 @@ async fn answer_each<R, F, Fut>(
in_flight.drain().await;
}
/// Whether the server has stopped waiting for the answer to a request whose
/// `exp` is `expires`. The server waits `authorization.timeout`
/// (`swarm-nats.nix`) and rounds `exp` down to the second, so it has given
/// up once the second after `exp` begins. Without `exp`, the request is
/// answered.
fn expired(expires: Option<i64>, now: SystemTime) -> bool {
/// What the responder keeps back from the time left to `exp`, for sealing and
/// sending the reply.
const REPLY_MARGIN: Duration = Duration::from_millis(100);
/// How long the answer to a request whose `exp` is `expires` may take, or
/// `None` when no time is left. The server waits `authorization.timeout`
/// (`swarm-nats.nix`) and rounds `exp` down to the second, so it may give up
/// as early as `exp`: the answer has until then, less [`REPLY_MARGIN`], and
/// never longer than introspection's own bound. Without `exp`, it has that
/// bound.
fn budget(expires: Option<i64>, now: SystemTime) -> Option<Duration> {
let Some(expires) = expires else {
return false;
return Some(introspect::INTROSPECTION_TIMEOUT);
};
now.duration_since(UNIX_EPOCH)
.ok()
.and_then(|since| i64::try_from(since.as_secs()).ok())
.is_some_and(|now| now > expires)
let exp = UNIX_EPOCH.checked_add(Duration::from_secs(u64::try_from(expires).ok()?))?;
let left = exp
.duration_since(now)
.ok()?
.checked_sub(REPLY_MARGIN)
.filter(|left| !left.is_zero())?;
Some(left.min(introspect::INTROSPECTION_TIMEOUT))
}
/// What answering a request needs, shared by every request in flight.
@ -360,19 +369,24 @@ struct Responder<S> {
impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
/// The sealed reply to `msg` and the subject it goes to, or `None` for a
/// request that gets no reply. A request the server has stopped waiting
/// for gets none, and no lookup.
async fn answer(&self, msg: &async_nats::Message) -> Option<(async_nats::Subject, Vec<u8>)> {
/// request that gets no reply. A request with no time left before the
/// server stops waiting (see [`budget`]) gets none, and no lookup; every
/// lookup is cut off at that time.
async fn answer(
&self,
msg: &async_nats::Message,
now: SystemTime,
) -> Option<(async_nats::Subject, Vec<u8>)> {
let (server_key, claims) = open_request(&self.callout_xkey, msg)?;
let req = claims.nats;
if expired(claims.exp, SystemTime::now()) {
let Some(budget) = budget(claims.exp, now) else {
tracing::warn!(
user_nkey = %req.user_nkey,
server_id = %req.server_id.id,
"auth request expired before it was answered; skipping"
"auth request has no time left before the server gives up; skipping"
);
return None;
}
};
// No token is a denial, not an error: an anonymous connect is a
// normal thing for a client to attempt and an abnormal thing to
// grant. Neither the store nor introspection is reached until
@ -389,7 +403,7 @@ impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
// the secret proved it; `granted` says which.
Some(agent_token::Presented::Agent(token)) => (
Some(format!("agent:{}", token.agent)),
agent_token::authorize(&self.policy, &self.store, &token).await,
agent_token::authorize(&self.policy, &self.store, &token, budget).await,
None,
),
Some(agent_token::Presented::Malformed(e)) => {
@ -403,6 +417,7 @@ impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
&self.args,
&self.client_secret,
token,
budget,
)
.await
}
@ -634,8 +649,9 @@ async fn introspected(
args: &Args,
client_secret: &oidc_secret::OidcSecret,
token: &str,
budget: Duration,
) -> (Option<String>, Option<policy::Permissions>, Option<i64>) {
let deadline = tokio::time::Instant::now() + introspect::INTROSPECTION_TIMEOUT;
let deadline = tokio::time::Instant::now() + budget;
let caller = client_secret
.introspect(deadline, |secret| async move {
introspect::identify_caller(
@ -903,7 +919,7 @@ mod tests {
let responder = Arc::clone(&responder);
let answered = answered.clone();
async move {
let reply = responder.answer(&msg).await;
let reply = responder.answer(&msg, SystemTime::now()).await;
answered
.send(reply.is_some())
.expect("the test is listening");
@ -937,10 +953,22 @@ mod tests {
}
}
/// A request whose `exp` has passed gets no lookup and no reply. The
/// same request with `exp` ahead is looked up and answered.
/// `exp` in the tests below, in whole Unix seconds.
const EXP: i64 = 1_760_000_000;
/// The instant `millis` after `EXP` begins; negative is before it.
fn near_exp(millis: i64) -> SystemTime {
let exp = UNIX_EPOCH + Duration::from_secs(u64::try_from(EXP).expect("positive"));
let by = Duration::from_millis(millis.unsigned_abs());
if millis < 0 { exp - by } else { exp + by }
}
/// A request with no time left before `exp` gets no lookup and no reply,
/// judged to the millisecond: one 50 ms from `exp` is inside the reply
/// margin, and one the server gave up on under a second ago is gone too.
/// The same request with time left is looked up and answered.
#[tokio::test(start_paused = true)]
async fn a_request_the_server_gave_up_on_is_skipped_without_a_lookup() {
async fn a_request_with_no_time_left_is_skipped_without_a_lookup() {
let responder = slow_responder();
let lookups = || {
responder
@ -948,24 +976,50 @@ mod tests {
.lookups
.load(std::sync::atomic::Ordering::SeqCst)
};
let stale = agent_request(&responder.callout_xkey, unix_now_plus(-1));
assert!(responder.answer(&stale).await.is_none());
let request = agent_request(&responder.callout_xkey, EXP);
for millis in [-50, 0, 999] {
let reply = responder.answer(&request, near_exp(millis)).await;
assert!(reply.is_none(), "answered at exp {millis:+} ms");
}
assert_eq!(lookups(), 0);
let live = agent_request(&responder.callout_xkey, unix_now_plus(60));
assert!(responder.answer(&live).await.is_some());
let reply = responder.answer(&request, near_exp(-60_000)).await;
assert!(reply.is_some());
assert_eq!(lookups(), 1);
}
/// `exp` is rounded down, so the server is still waiting until the
/// second after it begins.
/// The answer has until `exp`, less the reply margin, and never longer
/// than introspection's bound; the server may give up as early as `exp`,
/// which it rounds down. Without `exp` there is only the bound.
#[test]
fn a_request_expires_at_the_second_after_its_exp() {
let exp = 1_760_000_000;
let at = |millis| UNIX_EPOCH + std::time::Duration::from_millis(millis);
assert!(!expired(Some(exp), at(1_760_000_000_999)));
assert!(expired(Some(exp), at(1_760_000_001_000)));
assert!(!expired(None, at(1_760_000_001_000)));
fn the_budget_ends_before_exp_and_within_the_bound() {
let bound = introspect::INTROSPECTION_TIMEOUT;
let ms = Duration::from_millis;
assert_eq!(budget(Some(EXP), near_exp(-500)), Some(ms(400)));
assert_eq!(budget(Some(EXP), near_exp(-1_000)), Some(ms(900)));
assert_eq!(budget(Some(EXP), near_exp(-60_000)), Some(bound));
assert_eq!(budget(Some(EXP), near_exp(-100)), None);
assert_eq!(budget(Some(EXP), near_exp(0)), None);
assert_eq!(budget(Some(EXP), near_exp(999)), None);
assert_eq!(budget(Some(-1), near_exp(0)), None);
assert_eq!(budget(None, near_exp(0)), Some(bound));
}
/// A lookup that outlasts the time to `exp` is cut off there, not after
/// introspection's full bound: the server has stopped waiting by then, and
/// a reply after it is wasted. The request still gets its reply, a denial.
#[tokio::test(start_paused = true)]
async fn a_lookup_is_cut_off_at_the_requests_exp() {
let responder = slow_responder();
let request = agent_request(&responder.callout_xkey, EXP);
let started = tokio::time::Instant::now();
let reply = responder.answer(&request, near_exp(-500)).await;
assert!(reply.is_some(), "a denial is still a reply");
let took = started.elapsed();
assert!(
took <= Duration::from_millis(500),
"the lookup ran {took:?}, past exp"
);
}
/// The verb as `swarm-bao-nats-callout-xkey` runs it, with none of the