Watch
0
0
Fork
You've already forked hyperhive
0

swarm-nats-auth: refuse a credential that is already over by our clock

The user JWT's exp is min(credential exp, now + 1h) with no floor at now.
When this responder's clock is ahead of the identity provider's, a token the
provider calls active can already be over here: the minted JWT then has
exp <= iat, the server refuses the client, and the log says granted=true.

Check respond::outlives(now, expires) before granting. A credential that is
over at now gets the same denial as an inactive token, and the refusal is
logged with the credential's expiry and now (granted=false on the request
line). grant() takes the now the check used, so the JWT it mints and the
check can't disagree.
This commit is contained in:
maia 2026-11-30 14:44:07 +01:00 • committed by mara
commit 72d1e181e3
3 changed files with 130 additions and 14 deletions

View file

@ -408,6 +408,10 @@ impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
}
None => (None, None, None),
};
// A credential that is over by this responder's clock gets no grant, with
// the reason logged: see `respond::outlives`.
let now = respond::now_secs();
let permissions = unless_over(now, permissions, expires, &req.user_nkey);
// The caller is an identifier, not a credential: a client id, or
// `agent:<name>` for an agent token. One line per auth request, a connect
// or a reconnect, so a `hive-<h>` line counts requests made on
@ -430,6 +434,7 @@ impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
};
let token = match &permissions {
Some(permissions) => respond::grant(
now,
&self.issuer,
&self.args.account,
&req.server_id.id,
@ -449,6 +454,28 @@ impl<S: swarm_agent_verify::CredentialSource> Responder<S> {
}
}
/// `permissions`, or `None` (logged, with the reason) when the credential
/// they were granted for is already over at `now`: see [`respond::outlives`].
fn unless_over(
now: i64,
permissions: Option<policy::Permissions>,
expires: Option<i64>,
user_nkey: &str,
) -> Option<policy::Permissions> {
permissions.filter(|_| {
let live = respond::outlives(now, expires);
if !live {
tracing::warn!(
user_nkey,
expires = ?expires,
now,
"credential already expired by this responder's clock; denying"
);
}
live
})
}
/// The request in `msg`, opened, and the server key its reply is sealed to.
/// `None`, logged, for anything else, a request with no
/// [`xkey::SERVER_XKEY_HEADER`] included.
@ -720,6 +747,27 @@ mod tests {
assert_eq!(args.agent_token_publish_subjects.len(), 6);
}
/// A credential the identity provider calls active but that this
/// responder's clock says is over gets no permissions (so the reply is the
/// denial and the line says `granted=false`); a live one, or one with no
/// expiry, keeps them.
#[test]
fn a_credential_over_by_the_responders_clock_loses_its_permissions() {
let now = 1_700_000_000;
let perms = || {
Some(policy::Permissions {
publish: vec!["a".to_owned()],
subscribe: None,
responses: None,
})
};
assert!(unless_over(now, perms(), Some(now - 1), "UCLIENT").is_none());
assert!(unless_over(now, perms(), Some(now), "UCLIENT").is_none());
assert!(unless_over(now, perms(), Some(now + 1), "UCLIENT").is_some());
assert!(unless_over(now, perms(), None, "UCLIENT").is_some());
assert!(unless_over(now, None, Some(now + 1), "UCLIENT").is_none());
}
/// A request with no `Nats-Server-Xkey` is dropped before anything reads
/// it, so it gets no reply. The same request sealed, with the header,
/// opens.

View file

@ -138,7 +138,7 @@ fn response(
}
/// Current unix seconds, as the JWT `iat`.
fn now_secs() -> i64 {
pub fn now_secs() -> i64 {
i64::try_from(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@ -213,15 +213,35 @@ impl ResponsePermission {
}
}
/// When the user JWT minted at `now` expires: at `credential_expires` (the
/// presented credential's own expiry, unix seconds) or [`MAX_USER_JWT_LIFETIME`]
/// after `now`, whichever is sooner.
fn jwt_expiry(now: i64, credential_expires: Option<i64>) -> i64 {
let latest = now.saturating_add(
i64::try_from(MAX_USER_JWT_LIFETIME.as_secs()).expect("an hour fits in an i64"),
);
credential_expires.map_or(latest, |t| t.min(latest))
}
/// Whether a user JWT minted at `now` for a credential expiring at
/// `credential_expires` would still be live, that is expire after `now`.
///
/// The credential's expiry comes from the identity provider, and `now` from
/// this responder's clock. When this clock is ahead of the provider's, a
/// token the provider calls active can already be over here, and the JWT
/// minted for it would be refused by the server the moment it arrived. Such a
/// credential is not granted.
pub fn outlives(now: i64, credential_expires: Option<i64>) -> bool {
jwt_expiry(now, credential_expires) > now
}
/// Mint the user JWT an admitted client presents.
///
/// `account` is the account **name** from the server's `accounts` block (the
/// module's `clientAccount`), not a public key — in config mode the server
/// resolves `aud` against its own config rather than against a key.
///
/// It expires at `credential_expires` (the presented credential's own
/// expiry, unix seconds) or [`MAX_USER_JWT_LIFETIME`] after `now`, whichever
/// is sooner.
/// It expires at [`jwt_expiry`].
fn user_jwt(
now: i64,
issuer: &KeyPair,
@ -230,13 +250,10 @@ fn user_jwt(
permissions: &crate::policy::Permissions,
credential_expires: Option<i64>,
) -> String {
let latest = now.saturating_add(
i64::try_from(MAX_USER_JWT_LIFETIME.as_secs()).expect("an hour fits in an i64"),
);
sign(
Claims {
iat: now,
exp: Some(credential_expires.map_or(latest, |t| t.min(latest))),
exp: Some(jwt_expiry(now, credential_expires)),
iss: issuer.public_key(),
jti: String::new(),
sub: user_nkey.to_owned(),
@ -263,14 +280,16 @@ fn user_jwt(
)
}
/// Grant: mint a user JWT placing the client in `account`, scoped to
/// `permissions` and expiring no later than `credential_expires` (see
/// [`user_jwt`]), and wrap it.
/// Grant: mint, at `now`, a user JWT placing the client in `account`, scoped
/// to `permissions` and expiring no later than `credential_expires` (see
/// [`jwt_expiry`]), and wrap it. The caller checks [`outlives`] first: a JWT
/// minted for a credential that is over would be dead on arrival.
///
/// Taking the permissions by value rather than defaulting them is the point:
/// there is no way to call this and get an unscoped grant by omission, so a
/// future caller cannot forget the argument that makes the scoping real.
pub fn grant(
now: i64,
issuer: &KeyPair,
account: &str,
server_id: &str,
@ -278,7 +297,6 @@ pub fn grant(
permissions: &crate::policy::Permissions,
credential_expires: Option<i64>,
) -> String {
let now = now_secs();
let jwt = user_jwt(
now,
issuer,
@ -444,10 +462,40 @@ mod tests {
assert_eq!(user_exp(now, Some(latest + 1)), latest);
}
/// A credential already over by the responder's clock (its clock ahead of
/// the identity provider's) must not get a user JWT: the one minted would
/// have `exp` at or before its `iat`. `now` is passed in, past the
/// credential's own `exp`.
#[test]
fn a_credential_that_is_over_at_now_does_not_outlive_it() {
let now = 1_700_000_000;
assert!(!outlives(now, Some(now - 30)), "over by 30 s");
assert!(!outlives(now, Some(now)), "over this very second");
assert!(!outlives(now, Some(i64::MIN)), "far in the past");
// The controls: a credential with any time left, one with no expiry
// of its own, and one that outlasts the cap are all live.
assert!(outlives(now, Some(now + 1)));
assert!(outlives(now, None));
assert!(outlives(now, Some(now + 10 * 60 * 60)));
}
/// The JWT the server is handed for a live credential is live: the
/// two answers agree, which is what [`outlives`] exists to keep true.
#[test]
fn a_credential_that_outlives_now_gets_a_jwt_with_exp_after_iat() {
let now = 1_700_000_000;
for expires in [Some(now + 1), Some(now + 600), None, Some(now + 100_000)] {
assert!(outlives(now, expires));
let exp = user_exp(now, expires).as_i64().expect("exp is an integer");
assert!(exp > now, "{expires:?} gave exp {exp}");
}
}
#[test]
fn a_granted_user_jwt_carries_an_exp_after_its_iat() {
let account = KeyPair::new_account();
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
@ -470,6 +518,7 @@ mod tests {
// look identical from every test that stops at the policy.
let account = KeyPair::new_account();
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
@ -497,7 +546,15 @@ mod tests {
subscribe: Some(vec!["_INBOX.agent.atlas.>".to_owned()]),
..perms()
};
let wrapper = decode_claims(&grant(&account, "APP", "NSERVER", "UCLIENT", &scoped, None));
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
"UCLIENT",
&scoped,
None,
));
let user = decode_claims(wrapper["nats"]["jwt"].as_str().expect("a user jwt"));
assert_eq!(
user["nats"]["sub"]["allow"],
@ -505,6 +562,7 @@ mod tests {
);
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
@ -524,7 +582,13 @@ mod tests {
..perms()
};
let wrapper = decode_claims(&grant(
&account, "APP", "NSERVER", "UCLIENT", &answering, None,
now_secs(),
&account,
"APP",
"NSERVER",
"UCLIENT",
&answering,
None,
));
let user = decode_claims(wrapper["nats"]["jwt"].as_str().expect("a user jwt"));
// The names and units nats-server's `jwt/v2` reads: `max` messages,
@ -535,6 +599,7 @@ mod tests {
);
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
@ -550,6 +615,7 @@ mod tests {
fn a_grant_carries_a_user_jwt_and_no_error() {
let account = KeyPair::new_account();
let claims = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",
@ -581,6 +647,7 @@ mod tests {
fn the_issued_user_jwt_names_its_account_by_aud_and_sets_no_issuer_account() {
let account = KeyPair::new_account();
let wrapper = decode_claims(&grant(
now_secs(),
&account,
"APP",
"NSERVER",

View file

@ -249,6 +249,7 @@ pub(crate) mod tests {
responses: None,
};
let token = crate::respond::grant(
crate::respond::now_secs(),
&issuer,
"APP",
&req.nats.server_id.id,