Skip to content

feat(relay): close sessions when the token/cert expires#1789

Merged
kixelated merged 4 commits into
mainfrom
claude/nervous-perlman-6e67ed
Jun 19, 2026
Merged

feat(relay): close sessions when the token/cert expires#1789
kixelated merged 4 commits into
mainfrom
claude/nervous-perlman-6e67ed

Conversation

@kixelated

Copy link
Copy Markdown
Collaborator

Summary

Authentication was a one-time gate. The JWT exp claim was checked only in Key::decode at connect time, the relay's AuthToken then dropped claims.expires, and the session was held open indefinitely via a bare session.closed().await?. mTLS client certificates were validated only during the TLS handshake and never re-checked. So a credential that expired mid-session kept working until the client disconnected.

This enforces the credential's expiry for the whole session: the relay now closes the connection once the JWT exp (or the mTLS certificate's notAfter) passes, forcing the client to reconnect with a fresh credential.

What changed

  • rs/moq-relay/src/auth.rs — added expires: Option<SystemTime> to AuthToken (the struct is #[non_exhaustive], so this is additive). Populated from claims.expires in finalize(), so both the JWT path and the auth-API path carry it.
  • rs/moq-relay/src/connection.rsConnection::run races session.closed() against tokio::time::sleep until token.expires (sleeps forever via pending() when there's no expiry), closing with Error::Unauthorized when the deadline passes. The mTLS branch sets token.expires from the peer certificate.
  • rs/moq-native — new peer_certificate_expiry() helper that downcasts the backend's peer_identity() to Vec<CertificateDer> and parses the leaf's notAfter with x509-parser (already in the lockfile). Exposed on QuinnRequest, NoqRequest, and the Request wrapper; other backends return None.
  • doc/bin/relay/auth.md — notes that exp (and mTLS notAfter) is enforced for the session lifetime, not just at connect.

Reviewer notes

  • Public API (additive, non-breaking): AuthToken.expires field (on a #[non_exhaustive] struct); new pub fn peer_certificate_expiry() on moq_native::Request, QuinnRequest, NoqRequest. New optional dep x509-parser, gated behind the quinn/noq features. Targets main since there are no wire or breaking changes.
  • Clock caveat: the timer computes the delay from wall-clock SystemTime but tokio::time::sleep runs on the monotonic clock, so a large wall-clock jump after connect isn't tracked. This matches how exp was originally validated (SystemTime::now()). Exactness under clock skew would need a periodic re-check instead; happy to switch if preferred.

Test plan

  • New unit tests: JWT exp survives finalize; cert notAfter parses correctly; None/wrong-type identity yields None without panicking.
  • cargo fmt --check, clippy (both crates, noq feature on), and all lib tests pass via nix.

(Written by Claude)

Auth was a one-time gate: the JWT `exp` was checked only in Key::decode at
connect time, the relay's AuthToken dropped claims.expires, and the session
was held open indefinitely. mTLS client certs were validated only at the TLS
handshake. So a credential that expired mid-session kept working until the
client disconnected.

Carry the expiry through AuthToken (JWT `exp` via finalize, mTLS `notAfter`
parsed from the peer certificate) and, in Connection::run, race
session.closed() against a sleep until that deadline, closing with
Unauthorized once it passes.

- moq-relay: add AuthToken.expires, populate it in finalize() and on the
  mTLS path; close the session on expiry in connection.rs.
- moq-native: peer_certificate_expiry() helper (x509-parser) exposed on the
  Quinn/noq requests and the Request wrapper; other backends return None.
- Tests for exp carry-through and cert notAfter parsing; doc/bin/relay/auth.md
  notes the session-lifetime enforcement.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 12e7a2a8-d355-4c2b-ab58-7d6737c1f168

📥 Commits

Reviewing files that changed from the base of the PR and between 09ca272 and 0a39bde.

📒 Files selected for processing (1)
  • rs/moq-native/src/tls.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • rs/moq-native/src/tls.rs

Walkthrough

The relay gains continuous credential-lifetime enforcement for both JWT and mTLS sessions. A new PeerIdentity type (using the optional x509-parser dependency) safely downcasts the type-erased QUIC peer identity and exposes certificate chains, with an expiry() method that parses the leaf certificate's notAfter field as SystemTime. QuinnRequest, NoqRequest, and the unified Request type replace the boolean has_peer_certificate() method with a new peer_identity() method returning Option<PeerIdentity>. AuthToken gains a pub expires: Option<SystemTime> field populated from JWT exp claims during verification and from the peer certificate expiry in the mTLS authentication path. Connection::run now uses tokio::time::timeout to close sessions with Error::Unauthorized when the credential expiry time is reached, and auth.md documents the behavior for both authentication modes.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(relay): close sessions when the token/cert expires' directly and clearly summarizes the main change—enforcing credential expiry throughout session lifetime.
Description check ✅ Passed The description is detailed and directly related to the changeset, explaining the motivation, changes made, reviewer notes, and test plan.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch claude/nervous-perlman-6e67ed

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread rs/moq-native/src/noq.rs Outdated
Comment thread rs/moq-relay/src/connection.rs Outdated
Address review: replace has_peer_certificate() -> bool and
peer_certificate_expiry() -> Option<SystemTime> with a single, more
generic peer_identity() -> Option<PeerIdentity>. PeerIdentity owns the
validated client cert chain (leaf first) and offers chain() and expiry()
so callers can inspect it without re-parsing the type-erased QUIC identity.
has_peer_certificate becomes peer_identity().is_some() at call sites.

Also simplify Connection::run: use tokio::time::timeout instead of an
async block plus tokio::select! to close on credential expiry.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
rs/moq-native/src/tls.rs (1)

369-370: Document the rustls semver coupling for PeerIdentity::chain().

PeerIdentity::chain() exposes rustls::CertificateDer in the public signature. Since rustls is already re-exported in the public API (pub use rustls in lib.rs), this crate acknowledges the coupling—but lacks documentation that a major rustls version bump is a breaking change for moq-native consumers.

Add a doc comment on PeerIdentity::chain() or the struct itself clarifying this dependency relationship, or migrate to a crate-owned wrapper type to fully decouple the semver boundary.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rs/moq-native/src/tls.rs` around lines 369 - 370, The chain() method on the
PeerIdentity struct exposes the rustls::CertificateDer type in its public
signature, but lacks documentation about the semver coupling this creates with
the rustls crate. Add a doc comment to the chain() method (or to the
PeerIdentity struct itself) that clearly documents that this function exposes
the rustls::CertificateDer type and warns that major version bumps of rustls
constitute breaking changes for moq-native consumers, since rustls is already
part of the public API through pub use rustls in lib.rs.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rs/moq-native/src/server.rs`:
- Around line 621-623: The peer_identity() method in Request is gated behind a
feature flag `#[cfg(any(feature = "quinn", feature = "noq"))]` but the
authenticate() function in connection.rs calls it unconditionally without the
same guard. To fix this, either add the matching `#[cfg(any(feature = "quinn",
feature = "noq"))]` attribute to guard the authenticate() function in moq-relay,
or add a `#[cfg]` compile_error directive in moq-native to prevent compilation
when neither the quinn nor noq features are enabled, ensuring only supported
feature combinations can build.

---

Nitpick comments:
In `@rs/moq-native/src/tls.rs`:
- Around line 369-370: The chain() method on the PeerIdentity struct exposes the
rustls::CertificateDer type in its public signature, but lacks documentation
about the semver coupling this creates with the rustls crate. Add a doc comment
to the chain() method (or to the PeerIdentity struct itself) that clearly
documents that this function exposes the rustls::CertificateDer type and warns
that major version bumps of rustls constitute breaking changes for moq-native
consumers, since rustls is already part of the public API through pub use rustls
in lib.rs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7e697304-514b-406e-9190-00ecc879773c

📥 Commits

Reviewing files that changed from the base of the PR and between 26b7a30 and 54a5b05.

📒 Files selected for processing (7)
  • rs/moq-native/src/noq.rs
  • rs/moq-native/src/quinn.rs
  • rs/moq-native/src/server.rs
  • rs/moq-native/src/tls.rs
  • rs/moq-native/tests/backend.rs
  • rs/moq-relay/src/connection.rs
  • rs/moq-relay/src/web.rs
✅ Files skipped from review due to trivial changes (1)
  • rs/moq-relay/src/web.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • rs/moq-relay/src/connection.rs

Comment thread rs/moq-native/src/server.rs Outdated
The previous refactor gated Request::peer_identity() behind the quinn/noq
features and dropped the no-backend fallback arm that has_peer_certificate
used to have. moq-relay calls peer_identity() unconditionally, so a
backend-less build (e.g. `--no-default-features --features websocket`)
failed to compile.

Restore the always-available semantics: PeerIdentity and peer_identity()
are no longer feature-gated (x509-parser becomes a normal dependency), and
the `_ => None` fallback is back. Only PeerIdentity::from_any stays gated to
quinn/noq since that is the only place it is constructed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@kixelated kixelated enabled auto-merge (squash) June 19, 2026 03:51
chain() returns rustls::pki_types::CertificateDer in its public signature.
rustls is already re-exported (pub use rustls), so document that a major
rustls bump is a breaking change for consumers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@kixelated kixelated merged commit 855faa6 into main Jun 19, 2026
1 check passed
@kixelated kixelated deleted the claude/nervous-perlman-6e67ed branch June 19, 2026 04:01
@moq-bot moq-bot Bot mentioned this pull request Jun 18, 2026
@moq-bot moq-bot Bot mentioned this pull request Jun 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant