A platform-agnostic authentication toolkit for Rust: sessions, cookies, and credentials behind interfaces that do not assume a framework, a database, or a deployment model.
The project has working sessions today: cookie and credential handling, HMAC signing, a session store contract with an in-memory adapter, and a server that mints and validates real sessions. OIDC providers and JWT issuance come next.
| Crate | Knows about | Must not know about |
|---|---|---|
oxsession-core |
Cookie/Set-Cookie wire format, credentials, session model and SessionStore trait, errors |
Axum, tokio, SQL, environment variables |
oxsession-sign |
HMAC-SHA256 signatures, key ids, rotation | Axum, storage, environment variables |
oxsession-session |
Session lifecycle policy, the in-memory store | Axum, HTTP, environment variables |
oxsession-axum |
Request parts, HTTP status mapping | Parsing, signing, and storage rules |
oxsession-server |
Environment configuration, routes, session delivery, serving | Anything below the adapter |
oxsession-devtool |
Local inspection: cookie parsing, credential resolution, signature checks, id/policy validation | Session storage, minting, revocation, serving |
The rule that keeps this honest: core never sees a HeaderMap, a Router, a
Pool, or env::var. Every framework, database, and provider is an adapter,
so a second integration cannot drift away from the first.
Every integration — Rust or not — follows the same rules, which is what makes this a platform rather than one application's auth code.
Reading a request
- A client presents either
Authorization: Bearer <session-id>or a session cookie. Authorizationwins when present. A non-Bearerscheme is rejected, never silently downgraded to the cookie.- All
Cookieheaders are joined with"; "before parsing (RFC 6265 §5.4). - A credential cookie name appearing more than once is an error, not a last-one-wins coin flip.
- Names are case-sensitive; quoted values are unquoted; surrounding optional whitespace is trimmed; pairs that break the grammar are skipped.
- Limits: 8 KiB per header, 128 pairs per header.
Writing a cookie
- Values are not percent-encoded. A value must already consist of cookie-octets, so tokens should be base64url — the same bytes are then valid in every language that talks to the service.
__Host-names requireSecure,Path=/, and noDomain.__Secure-names requireSecure.SameSite=NonerequiresSecure.Pathmust be absolute.
Sessions are opaque and server-side: the client holds a random id, the server holds the subject. No claims travel in the cookie, so revocation is immediate and there is nothing to decrypt.
| Property | Detail |
|---|---|
| Id | 32 random bytes, unpadded base64url (43 chars), generated via the OS RNG |
| Lookup | SessionStore::get, with the manager enforcing expiry |
| Idle lifetime | 7 days by default, refreshed on every valid use |
| Absolute lifetime | 30 days by default, never extended by activity |
| Expiry handling | An expired id is deleted before 401 is returned, so it cannot be kept alive by retries |
| Logout | SessionStore::delete; the cookie is cleared in the same response |
| Rotation | SessionManager::rotate mints a new id and kills the old one (use after privilege changes) |
The storage contract is a trait, so the store is swappable:
pub trait SessionStore: Send + Sync {
type Error: std::error::Error + Send + Sync + 'static;
fn insert(&self, session: Session) -> impl Future<Output = Result<(), Self::Error>> + Send;
fn get(&self, id: &SessionId) -> impl Future<Output = Result<Option<Session>, Self::Error>> + Send;
fn touch(&self, id: &SessionId, expires_at: u64) -> impl Future<Output = Result<bool, Self::Error>> + Send;
fn delete(&self, id: &SessionId) -> impl Future<Output = Result<bool, Self::Error>> + Send;
fn delete_expired(&self, now: u64) -> impl Future<Output = Result<usize, Self::Error>> + Send;
}oxsession-session ships MemoryStore, the reference adapter: complete,
dependency-free, process-local, and explicitly not durable. When full it
evicts the session closest to expiry, so memory is bounded; a production
deployment needs a durable adapter with the same contract.
SessionId is a credential, so its Debug output is redacted — leaking a
session id into a log line is a login.
Subjects are limited to 1,024 UTF-8 bytes. The session error categories expose
invalid input, missing or expired sessions, entropy failure, and storage failure
without including backend details in public error text.
oxsession-node is an N-API package built with
napi-rs. It exposes cookie parsing, credential resolution, signing and
verification, and session create, validate, revoke, and rotate. Its Rust-owned
MemoryStore is process-local and non-durable: sessions are lost on restart and
are not shared across processes. Build the native module from its package
directory with npm run build. Persistent stores and JavaScript store
callbacks are outside the initial boundary. See docs/sessions.md
for the operation and error contract.
The session id is a bearer credential either way; delivery only decides which carrier the client should look at.
AUTH_SESSION_DELIVERY |
POST /sessions returns |
Cookie accepted on read? | Use when |
|---|---|---|---|
cookie (default) |
Set-Cookie only |
yes | Server-rendered apps, or any client that can hold a cookie. Scripts cannot read the id |
token |
{"session_id":"…"} in the body, Cache-Control: no-store, no cookie |
no | Browser apps keeping the id in localStorage, mobile apps, CLIs |
both |
both carriers | yes | Migrating one client type at a time |
token is a token-only deployment: it issues no cookie and accepts none, so
no ambient credential can ride along on a cross-site request. A cookie presented
in that mode is a 401, not a downgrade, and the cookie is never even parsed —
a duplicate or malformed one cannot change the status code or cost a signature
check. Bearer is accepted in every mode, because it is a credential the caller
chooses to send rather than one a browser attaches on its own.
Logout is the exception: it revokes whatever credential is presented, including a
cookie that token mode would refuse to authenticate, so an id can always be
killed instead of lingering until it expires. The client must still drop its own
localStorage entry; the server cannot reach it.
Responses that may carry a credential or describe a session — /me success and
error alike, /logout, and the mint response — are sent with
Cache-Control: no-store and Pragma: no-cache. A cookie-authenticated response
has no Vary: Cookie, so a shared cache storing it would hand one user's subject
to another, and HTTP/1.0 intermediaries ignore Cache-Control.
Putting the id in localStorage means JavaScript can read it, so an XSS bug is
a session theft — the exact thing an HttpOnly cookie prevents. The trade is
that nothing is sent automatically, so cross-site requests carry no ambient
credential. See examples/localstorage.js for a
working client:
const session = await (await fetch("/sessions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ subject: "user-1" }),
})).json();
localStorage.setItem("oxsession.session", session.session_id);
await fetch("/me", {
headers: { authorization: `Bearer ${localStorage.getItem("oxsession.session")}` },
});The bearer channel is also why signed cookies protect less than they appear to: a client holding the raw id bypasses the signature check entirely, because the id is the credential. Signing defends the cookie carrier against forgery and name replay, not the token.
For a React or other browser SPA, see docs/react.md. There is
no browser package: the app talks to the HTTP surface, with a same-origin
HttpOnly cookie through a dev proxy as the recommended setup. The server has
no CORS layer, so direct cross-origin calls need a proxy or a server change.
The companion React Demo Project
includes Playwright browser coverage and a Podman-based API benchmark for the
Node addon.
Signing is a policy decision, not a transport rule: preferences stay unsigned, session cookies can be signed. Pass the cookies that matter through a signer.
use oxsession_sign::{CookieSigner, KeyId, SecretKey};
let signer = CookieSigner::new(
KeyId::new("k1")?,
SecretKey::from_slice(&key_bytes)?, // exactly 32 bytes, zeroized on drop
);
let wire = signer.sign("session", "dXNlcj00Mg")?; // "os1.k1.dXNlcj00Mg.<mac>"
let payload = signer.verify("session", &wire)?; // bound to the cookie nameOn Axum, read and verify in one step:
let payload = oxsession_axum::signed_cookie(&cookies, &signer, "session")?;| Property | Detail |
|---|---|
| Format | os1.<keyid>.<payload>.<mac>, HMAC-SHA256 |
| Binding | The cookie name is signed, so a session value cannot be replayed as admin |
| Rotation | Key id travels in the value; up to 2 retired keys keep verifying |
| Failure | Unsigned, tampered, foreign-name, and unknown-key values are all rejected |
| Limits | 4096-byte signed value, payload must be cookie-octets with no . |
Signing the session id makes tampering detectable before a store lookup, which
turns most forged cookies into a cheap 401 instead of a database query. It is
not a replacement for server-side validation: a valid signature is not a valid
session.
Signing is not encryption: the payload is readable by the client. The wire
format, a test vector, and a 6-line Python reference implementation live in
docs/signing.md.
AUTH_DEV_LOGIN=1 cargo run -p oxsession-serverThe server listens on 127.0.0.1:3000 by default. To serve browser clients that
use localStorage, add AUTH_SESSION_DELIVERY=token and read session_id from
the POST /sessions body.
curl http://127.0.0.1:3000/health
# Mint a session (development only; requires AUTH_DEV_LOGIN=1)
curl -c jar.txt -H 'content-type: application/json' \
-d '{"subject":"user-1"}' http://127.0.0.1:3000/sessions
curl -b jar.txt http://127.0.0.1:3000/me
curl -b jar.txt -X POST http://127.0.0.1:3000/logout
# Bearer clients use the same session id
curl -H 'Authorization: Bearer <session-id>' http://127.0.0.1:3000/me| Endpoint | Response |
|---|---|
GET /health |
200 {"status":"ok"} |
GET /me |
200 {"subject":"...","expires_at":...,"source":"cookie"|"bearer"}, 401 for a missing, unknown, expired, or forged session |
POST /sessions |
201 + Set-Cookie (cookie delivery) or 201 {"session_id":"…"} (token delivery); 404 unless AUTH_DEV_LOGIN=1; 400 for an empty subject |
POST /logout |
204 + cookie deletion; revokes the session when it can be identified |
/sessions exists because there is no identity provider yet. It trusts any
subject and is therefore off by default.
oxsession-devtool is a local, read-only CLI for the
values on the wire. It prints JSON, redacts credentials by default, and never
touches a session store.
cargo run -p oxsession-devtool -- parse-cookie --header 'theme=dark; session=abc'
# Why did this request get a 401?
cargo run -p oxsession-devtool -- resolve-credential \
--authorization "$AUTH" --cookie "$COOKIE"
# Verify an os1 value without printing the key or the payload
cargo run -p oxsession-devtool -- check-cookie \
--name session --value "$WIRE" --key-file ~/.config/oxsession/keys.txt
# Check TTLs and the __Host- prefix rule before starting the server
cargo run -p oxsession-devtool -- policy \
--ttl 604800 --absolute 2592000 --cookie-name __Host-session --secureExit 0 means the answer is positive, 1 means negative (no credential, bad
MAC, invalid policy), 2 is a usage error, and 3 is configuration/IO. The full
command reference, redaction rules, and key handling are in
docs/devtool.md.
The library is configured programmatically. Only the optional server binary reads the environment:
| Variable | Default | Description |
|---|---|---|
AUTH_BIND_ADDR |
127.0.0.1 |
IP address to bind to |
AUTH_PORT |
3000 |
TCP port to listen on (1–65535) |
AUTH_SESSION_COOKIE |
session |
Cookie name holding the session id |
AUTH_SESSION_TTL_SECONDS |
604800 |
Idle lifetime, refreshed on use |
AUTH_SESSION_ABSOLUTE_TTL_SECONDS |
2592000 |
Lifetime cap from creation |
AUTH_SESSION_COOKIE_SECURE |
off | Send the cookie with Secure. Required outside localhost |
AUTH_DEV_LOGIN |
off | Enables POST /sessions |
AUTH_SESSION_DELIVERY |
cookie |
cookie, token, or both; see Delivering the credential |
AUTH_COOKIE_KEYS |
unset | keyid:base64url,keyid:base64url,...; first entry signs, the rest verify. Unset means the session id travels unsigned |
Generate a signing key:
python3 -c "import base64,os;print(base64.urlsafe_b64encode(os.urandom(32)).decode().rstrip('='))"No dotenv files are loaded.
cargo test --workspace156 tests (including two doctests) cover the parser's edge cases (quoted values, malformed pairs, duplicate names, size and pair limits), prefix rules, credential precedence, the published signing vector and tampering matrix, session expiry and sliding, store eviction, every delivery mode, the endpoints end-to-end through a real router, and the devtool's option parsing, redaction, and policy checks. The companion React demo adds Playwright browser/API coverage for the Node addon; its latest run passed one end-to-end test.
The sibling React demo has browser/API checks and a serial benchmark. From
React Demo Project, run npm install, install Chromium with
npx playwright install chromium, then npm run verify:container. This builds
the addon in a Rust Bookworm stage, runs the API in a Node Bookworm container,
starts Vite for Playwright, and measures 500 API requests per operation after
30 warmups. Podman publishes the API only on loopback. The demo README records
the environment and measured timings; timings are informational and have no
pass/fail thresholds.
Informational API baseline measured 2026-11-21 on Linux x86_64 (CachyOS kernel 7.3.3-1), AMD Ryzen 5 3400G (4 cores / 8 threads), host Node.js 26.13.0, Playwright 1.65.1 with Chromium 159.0.8154.6, and Podman 6.1.4. The API ran in Node 22 Bookworm; the addon was built in Rust Bookworm. Each row reports the median and 95th percentile latency in milliseconds and serial throughput in requests per second.
| Operation | p50 (ms) | p95 (ms) | Throughput (req/s) |
|---|---|---|---|
| Cookie parse | 1.666 | 3.181 | 530.1 |
| Credential resolve | 1.214 | 2.355 | 734.0 |
| Sign | 0.798 | 1.529 | 1,103.5 |
| Verify | 0.763 | 1.474 | 1,133.4 |
| Session create | 0.873 | 1.624 | 1,021.2 |
| Session validate | 0.909 | 1.771 | 952.2 |
| Session rotate | 0.886 | 1.740 | 1,011.9 |
| Session revoke | 1.405 | 2.382 | 655.2 |
Agent-oriented playbooks live in skills/. Start with
AGENTS.md for the repository rules, the dependency direction, and
task routing, then load the matching skills/<name>/SKILL.md. The index and
loading instructions are in skills/README.md.
Run python3 scripts/validate-agent-setup.py to check the agent entry points,
skill index, and agent skill mirrors. CI runs this check together with
formatting, workspace tests, the Node addon build, and the documentation build.
The repo has native rule entry points for Devin CLI, Antigravity, Cline, Roo
Code, and Continue, plus shared skill discovery for Codex and OpenHands.
Codex, Devin CLI, Antigravity, OpenHands, and Zed also consume AGENTS.md
directly. DeepSeek is supported through whichever agent host loads that
provider's model; DeepSeek does not currently document a provider-specific
repository rules format. See skills/agents.md for paths
and upstream references.
Session model and— done, with an in-memory adapter.SessionStoretrait- PostgreSQL adapter, then SQLite, behind the same trait. Adapters must pass a shared conformance suite.
- Generic OIDC with Google as a preset, including PKCE and
statehandling. - JWT issuance with a JWKS endpoint and key rotation.
- Sealed (encrypted) cookies — signed cookies already ship in
oxsession-sign. - Additional adapters (Actix, Hyper, serverless).
Current status, known gaps, and inconsistencies are tracked in
logs.md.
