diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts index aedbeef..65ff56f 100644 --- a/apps/web/src/api/client.ts +++ b/apps/web/src/api/client.ts @@ -235,7 +235,7 @@ export const opaqueLoginComplete = (loginId: string, finalizationHex: string) => credential_finalization: finalizationHex, }); -// --- recovery shares + key management + logout (authenticated) --- +// --- recovery shares + key management (authenticated) --- export const storeShares = ( shares: { share_index: number; encrypted_share: string }[], @@ -269,9 +269,6 @@ export const spkRotate = ( token: string, ) => post<{ rotated: boolean }>("/keys/spk/rotate", body, token); -export const logoutAll = (token: string) => - post<{ revoked: boolean }>("/auth/logout_all", {}, token); - // --- encrypted history backup (Option A; authenticated, opt-in) --- // Blobs are AES-GCM ciphertext under the client's history_key - the server can't // read them. Scoped to the authenticated user. diff --git a/apps/web/src/components/KeyAlert.tsx b/apps/web/src/components/KeyAlert.tsx index 346610d..d918dca 100644 --- a/apps/web/src/components/KeyAlert.tsx +++ b/apps/web/src/components/KeyAlert.tsx @@ -38,8 +38,8 @@ export default function KeyAlert() { {!notMe ? ( <>

- If it was you — a new phone or browser, or “Log out everywhere” on another of - your devices — tap “That was me”. + If it was you — setting up a new phone or browser, or your other device updating its + keys — tap “That was me”.

); } diff --git a/apps/web/src/services/prekeys.ts b/apps/web/src/services/prekeys.ts index 51a9d1e..dea5b47 100644 --- a/apps/web/src/services/prekeys.ts +++ b/apps/web/src/services/prekeys.ts @@ -8,8 +8,7 @@ // - The server's one-time supply is topped up in batches when it runs low. // - The signed prekey rotates every 30 ± 5 days. Each retired private half is // kept for the 60-day max message TTL (+ a day), so a handshake queued against -// it still opens - however many rotations (incl. "log out everywhere") happen -// meanwhile. +// it still opens - however many rotations happen meanwhile. // Order is always: persist the new PRIVATE keys durably, then publish - the // server must never hand out a public key whose private half we don't hold. // diff --git a/apps/web/src/services/session.ts b/apps/web/src/services/session.ts index e0bbdcb..e156829 100644 --- a/apps/web/src/services/session.ts +++ b/apps/web/src/services/session.ts @@ -1,99 +1,18 @@ -// Session management (docs 4.9 / 16E). "Log out everywhere" does TWO things: +// On-device session actions (docs 4.9): lock the app, erase this device. // -// 1. Token revocation (already the working mechanism): POST /auth/logout_all sets -// a per-user cutoff so every session token issued on every device dies at once -// (auth/extract.rs rejects issued_at < cutoff). This is what actually logs -// other devices out. -// -// 2. Signed-prekey rotation (added here): rotate the SPK so a future PQXDH init -// can't target the OLD signed prekey - forward secrecy against a lost/seized -// or other device that still holds the old SPK private key. This is scoped to -// the explicit "log out everywhere" action; routine, replenish-driven SPK -// rotation stays DECOUPLED from session life (docs/KNOWN_LIMITATIONS). -// -// NOTE (deliberate): we do NOT tie token validity to an spk_version (the build -// guide's Option C). That would log every device out on routine ~monthly rotation. -// The cutoff already invalidates tokens; SPK rotation here is orthogonal forward -// secrecy layered on top. -import * as api from "../api/client"; +// There is deliberately no "log out everywhere". Each device holds the account's +// keys and signs itself in with them - there's no password - so no server action +// could remove a device that holds them without the server keeping a list of your +// devices, which Privex doesn't. A server-side token cutoff only looked like it did +// (every device signed straight back in), stored when you pressed it, and left +// connected devices untouched. See docs/private/KNOWN_LIMITATIONS.md. import { db } from "../db"; import { useAuth } from "../store/auth"; -import { cryptoCall } from "../workers/crypto-client"; import { lockNow, wipeKeystore } from "../crypto/keystore"; -import { loadBundle, finalizeIdentity } from "../onboarding/store"; -import { nextSpkRotation, retainSpks } from "./prekeys"; -import { toHex, type SignedSpk } from "../crypto/onboarding-crypto"; import { disconnectWebSocket } from "./websocket"; import { stopCoverTraffic } from "./cover-traffic"; import { resetMessaging } from "./messaging"; -export interface SessionCryptoApi { - generateSignedSpk(edPriv: Uint8Array, dilPriv: Uint8Array): Promise; -} - -export const workerSessionCrypto: SessionCryptoApi = { - generateSignedSpk: (ed, dil) => cryptoCall("generate_signed_spk", [ed, dil]), -}; - -/** Log out of ALL devices: rotate the SPK (forward secrecy) then revoke every - * token. Order matters: spk_rotate needs the still-valid token, and logout_all - * revokes it. On reload this device re-authenticates (identity key unchanged) and - * already holds the new SPK private key saved below, so it can keep answering - * inbound PQXDH sessions. */ -export async function logoutEverywhere(crypto: SessionCryptoApi = workerSessionCrypto): Promise { - const bundle = await loadBundle(); - const token = useAuth.getState().sessionToken; - if (!bundle || !token) throw new Error("not authenticated"); - - const spk = await crypto.generateSignedSpk( - bundle.identity.ed25519_priv, - bundle.identity.dilithium3_priv, - ); - - // Save the new key BEFORE publishing it, like a routine rotation (prekeys.ts): - // the server must never hold a signed prekey this device lacks - it couldn't - // answer handshakes to it, and key-watch would take it for another device. If - // the publish fails, the key stays pending and prekey upkeep publishes it - // later; nothing is revoked. The old private half is kept briefly so a - // handshake already in flight against it still opens. - const now = Math.floor(Date.now() / 1000); - bundle.prevSpks = retainSpks([{ ...bundle.spk, retiredAt: now }, ...(bundle.prevSpks ?? [])], now); - bundle.spk = { pub: spk.pub, priv: spk.priv }; - bundle.spkSig = { ed: spk.sigEd, dil: spk.sigDil }; - bundle.spkRotateAfter = nextSpkRotation(now); - bundle.spkPending = true; - await finalizeIdentity(bundle); // rewrites priv_bundle_enc; keeps opks + mnemonic + progress - resetMessaging(); // the cached identity must pick up the new signed prekey - - // spk_rotate OVERWRITES the stored SPK and appends a KT entry. - await api.spkRotate( - { spk_x25519_pub: toHex(spk.pub), spk_sig_ed: toHex(spk.sigEd), spk_sig_dil: toHex(spk.sigDil) }, - token, - ); - bundle.spkPending = false; - await finalizeIdentity(bundle); - resetMessaging(); - - // Revoke every token across all devices (incl. this one - we re-auth on reload). - await api.logoutAll(token); -} - -/** - * "Erase this device": a full LOCAL reset - delete every message, contact, - * session, AND the identity key material, then sign out to a clean onboarding. - * - * IRREVERSIBLE: without a recovery phrase / OPAQUE password / server backup, the - * account is gone. This is DESTRUCTIVE by design. - * - * SAFETY CONTRACT (do not violate): this runs ONLY from the explicit, confirmed - * Settings action. It is NEVER wired to a 401, a boot/restore failure, a slow - * load, or any transient/network condition - the correct response to those is to - * RE-AUTHENTICATE from the local identity (auth-session.ts), never to delete data. - * So a latency spike or an ambiguous auth error can never nuke local data. - * - * Does NOT contact the server (nothing to tell it - the data was only ever local). - * The caller reloads afterwards so all in-memory module caches are dropped too. - */ /** * Lock the app: drop the in-memory data key AND fully tear down the live session, * so a locked device is INERT - no WebSocket, no cover traffic, no session token, @@ -117,6 +36,22 @@ export function lockApp(): void { useAuth.getState().signOut(); // drop the session token + authenticated flag } +/** + * "Erase this device": a full LOCAL reset - delete every message, contact, + * session, AND the identity key material, then sign out to a clean onboarding. + * + * IRREVERSIBLE: without a recovery phrase / OPAQUE password / server backup, the + * account is gone. This is DESTRUCTIVE by design. + * + * SAFETY CONTRACT (do not violate): this runs ONLY from the explicit, confirmed + * Settings action. It is NEVER wired to a 401, a boot/restore failure, a slow + * load, or any transient/network condition - the correct response to those is to + * RE-AUTHENTICATE from the local identity (auth-session.ts), never to delete data. + * So a latency spike or an ambiguous auth error can never nuke local data. + * + * Does NOT contact the server (nothing to tell it - the data was only ever local). + * The caller reloads afterwards so all in-memory module caches are dropped too. + */ export async function eraseThisDevice(): Promise { // 1. Stop anything that could re-write IndexedDB mid-wipe. stopCoverTraffic(); diff --git a/apps/web/src/test/prekeys.test.ts b/apps/web/src/test/prekeys.test.ts index 7135e3d..8abe3bf 100644 --- a/apps/web/src/test/prekeys.test.ts +++ b/apps/web/src/test/prekeys.test.ts @@ -234,8 +234,8 @@ describe("signed prekey rotation", () => { // Not due yet → nothing happens. expect(await rotateSpkIfDue(me, prekeyCrypto, "tok", t0 + DAY)).toBe(false); - // Two more rotations in quick succession (as "log out everywhere" can cause): - // every retired key is still inside its window, so all are kept. + // Two more rotations in quick succession: every retired key is still inside + // its window, so all are kept. me.spkRotateAfter = undefined; await rotateSpkIfDue(me, prekeyCrypto, "tok", t0 + 10); me.spkRotateAfter = undefined; diff --git a/apps/web/src/test/session.test.ts b/apps/web/src/test/session.test.ts index 1f014fd..d7543db 100644 --- a/apps/web/src/test/session.test.ts +++ b/apps/web/src/test/session.test.ts @@ -1,7 +1,5 @@ -// Session management (16E): "log out everywhere" rotates the SPK for forward -// secrecy AND revokes every token via the cutoff. Verifies order (rotate with the -// still-valid token BEFORE revoke), that the new SPK private key is persisted -// locally (so this device keeps answering inbound PQXDH), and the mutual/no-op guards. +// On-device session actions: locking tears the live session down; erasing wipes +// everything local without contacting the server. import { readFileSync } from "node:fs"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; @@ -23,14 +21,12 @@ vi.mock("../crypto/keystore", () => ({ })); import { initCrypto, wasm } from "../crypto/wasm"; -import { genIdentityBundle, toHex, type SignedSpk } from "../crypto/onboarding-crypto"; -import { generateSignedSpk } from "../crypto/onboarding-crypto"; -import { persistGeneratedIdentity, finalizeIdentity, loadBundle } from "../onboarding/store"; +import { genIdentityBundle } from "../crypto/onboarding-crypto"; +import { persistGeneratedIdentity, finalizeIdentity } from "../onboarding/store"; import { EncryptedMessages } from "../db/encrypted-db"; import { useAuth } from "../store/auth"; import { db } from "../db"; -import * as api from "../api/client"; -import { eraseThisDevice, lockApp, logoutEverywhere, type SessionCryptoApi } from "../services/session"; +import { eraseThisDevice, lockApp } from "../services/session"; import * as ws from "../services/websocket"; import * as cover from "../services/cover-traffic"; @@ -61,100 +57,6 @@ beforeEach(async () => { const entropy = (f: number) => new Uint8Array(32).fill(f); -describe("log out everywhere (16E)", () => { - it("rotates the SPK (before revoke) and persists the new private key locally", async () => { - const me = genIdentityBundle(wasm, entropy(0x31)); - await persistGeneratedIdentity(me); - await finalizeIdentity(me); // mark done + retain mnemonic (as after onboarding) - useAuth.getState().setSession("tok-1", me.userId); - - const oldSpkPriv = toHex(me.spk.priv); - const order: string[] = []; - let savedBeforePublish = false; - const rotateSpy = vi.spyOn(api, "spkRotate").mockImplementation(async (req) => { - order.push("rotate"); - // The device already holds the key it's publishing (never the other way round). - savedBeforePublish = toHex((await loadBundle())!.spk.pub) === req.spk_x25519_pub; - return { rotated: true }; - }); - const logoutSpy = vi.spyOn(api, "logoutAll").mockImplementation(async () => { - order.push("logout"); - return { revoked: true }; - }); - - // Injected crypto = the real wasm SPK generator (plain-data helper). - const crypto: SessionCryptoApi = { - generateSignedSpk: async (ed, dil) => generateSignedSpk(wasm, ed, dil), - }; - await logoutEverywhere(crypto); - - // SPK rotated with the still-valid token BEFORE the token is revoked. - expect(order).toEqual(["rotate", "logout"]); - expect(savedBeforePublish).toBe(true); - const rotatedArg = rotateSpy.mock.calls[0]; - expect(rotatedArg[1]).toBe("tok-1"); // authed with the pre-revocation token - - // The uploaded SPK pub is a NEW key, hybrid-signed → server would accept it. - const uploaded = rotatedArg[0] as { spk_x25519_pub: string; spk_sig_ed: string; spk_sig_dil: string }; - expect(uploaded.spk_x25519_pub).not.toBe(toHex(me.spk.pub)); - - // The new SPK PRIVATE key is persisted locally (this device can still answer - // inbound PQXDH). The old priv is gone. - const reloaded = await loadBundle(); - expect(toHex(reloaded!.spk.pub)).toBe(uploaded.spk_x25519_pub); - expect(toHex(reloaded!.spk.priv)).not.toBe(oldSpkPriv); - // Signature on the stored bundle matches the uploaded one. - expect(toHex(reloaded!.spkSig.ed)).toBe(uploaded.spk_sig_ed); - // Identity + mnemonic preserved (same account; seed-view still works). - expect(reloaded!.userId).toBe(me.userId); - expect(reloaded!.mnemonic).toBe(me.mnemonic); - expect(reloaded!.spkPending).toBe(false); // published - - rotateSpy.mockRestore(); - logoutSpy.mockRestore(); - }); - - it("does NOT revoke if the SPK rotation fails (no partial logout)", async () => { - const me = genIdentityBundle(wasm, entropy(0x32)); - await persistGeneratedIdentity(me); - await finalizeIdentity(me); - useAuth.getState().setSession("tok-2", me.userId); - - const rotateSpy = vi.spyOn(api, "spkRotate").mockRejectedValue(new api.ApiError(400)); - const logoutSpy = vi.spyOn(api, "logoutAll").mockResolvedValue({ revoked: true }); - - const stub: SignedSpk = { - pub: new Uint8Array(32).fill(1), - priv: new Uint8Array(32).fill(2), - sigEd: new Uint8Array(64).fill(3), - sigDil: new Uint8Array(64).fill(4), - }; - await expect( - logoutEverywhere({ generateSignedSpk: async () => stub }), - ).rejects.toBeInstanceOf(api.ApiError); - - expect(logoutSpy).not.toHaveBeenCalled(); // token NOT revoked on rotate failure - // The new key was saved first and stays pending (prekey upkeep publishes it - // later); the old one - still the server's - is kept. - const after = (await loadBundle())!; - expect(toHex(after.spk.pub)).toBe(toHex(stub.pub)); - expect(after.spkPending).toBe(true); - expect(after.prevSpks!.map((k) => toHex(k.pub))).toContain(toHex(me.spk.pub)); - - rotateSpy.mockRestore(); - logoutSpy.mockRestore(); - }); - - it("throws (no calls) when not authenticated", async () => { - const rotateSpy = vi.spyOn(api, "spkRotate"); - await expect(logoutEverywhere({ generateSignedSpk: async () => ({} as SignedSpk) })).rejects.toThrow( - /not authenticated/, - ); - expect(rotateSpy).not.toHaveBeenCalled(); - rotateSpy.mockRestore(); - }); -}); - describe("app lock teardown", () => { it("lockApp drops the key AND the live session (WS, cover traffic, token)", () => { useAuth.getState().setSession("live-token", "px_" + "aa".repeat(16)); @@ -203,8 +105,7 @@ describe("erase this device (16E follow-up)", () => { expect(await db.messages.count()).toBe(1); // Any network call during erase would be a bug (nothing to tell the server). - const anyPost = vi.spyOn(api, "logoutAll"); - const anyRotate = vi.spyOn(api, "spkRotate"); + const anyFetch = vi.spyOn(globalThis, "fetch"); await eraseThisDevice(); @@ -217,9 +118,7 @@ describe("erase this device (16E follow-up)", () => { expect(useAuth.getState().authenticated).toBe(false); expect(useAuth.getState().sessionToken).toBe(null); // No server contact. - expect(anyPost).not.toHaveBeenCalled(); - expect(anyRotate).not.toHaveBeenCalled(); - anyPost.mockRestore(); - anyRotate.mockRestore(); + expect(anyFetch).not.toHaveBeenCalled(); + anyFetch.mockRestore(); }); }); diff --git a/apps/web/src/workers/crypto.worker.ts b/apps/web/src/workers/crypto.worker.ts index 00cf07c..f22d108 100644 --- a/apps/web/src/workers/crypto.worker.ts +++ b/apps/web/src/workers/crypto.worker.ts @@ -41,7 +41,7 @@ const handlers: Record unknown> = { a[3] as Uint8Array, a[4] as Uint8Array, ), - // Fresh signed prekey for rotation (16E "log out everywhere"). Struct → plain. + // Fresh signed prekey for rotation (services/prekeys.ts). Struct → plain. generate_signed_spk: (a) => oc.generateSignedSpk(wasm, a[0] as Uint8Array, a[1] as Uint8Array), // One-time prekey top-up (services/prekeys.ts). Structs → plain data. generate_opks: (a) => oc.generateOpks(wasm, a[0] as number, a[1] as number), diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 76af550..dc3fed8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -389,7 +389,6 @@ opaque_records: px_id → OPRF record + encrypted envelope (server canno kt_log: Merkle tree of all key operations (UNLOGGED, auto-repaired at startup on crash) recovery_shares: px_id → encrypted Shamir shares (server cannot decrypt) history_blobs: px_id → encrypted history blobs (UNLOGGED, OPT-IN ONLY) -linked_devices: px_id → device public keys (UNLOGGED) pow_challenges: challenge_id → difficulty + expiry (UNLOGGED, 30 min TTL) ``` @@ -398,7 +397,8 @@ pow_challenges: challenge_id → difficulty + expiry (UNLOGGED, 30 min T ``` Real name, email, phone number, IP address, last seen, message content, file content, sender identity, social graph, call participants or duration, -passwords or functions of passwords, private keys +passwords or functions of passwords, private keys, a list of your devices +(linked devices are known only to each other, in each device's own storage) ``` ### Critical PostgreSQL Configuration @@ -410,7 +410,6 @@ CREATE UNLOGGED TABLE message_queue (...); CREATE UNLOGGED TABLE blob_index (...); CREATE UNLOGGED TABLE kt_log (...); CREATE UNLOGGED TABLE history_blobs (...); -CREATE UNLOGGED TABLE linked_devices (...); CREATE UNLOGGED TABLE pow_challenges (...); ``` @@ -442,10 +441,9 @@ log { ### Session Token Security -Session tokens include `spk_version`. When a user rotates their Signed Pre-Key: -- `spk_version` increments in the database -- All existing tokens with old `spk_version` return 401 immediately -- This implements "log out everywhere" without storing a token revocation list +A session token is an HMAC-signed `{user_id, issued_at, expires_at, random id}`, valid for 24 hours. The app keeps it in memory only and sends it only in the `X-Privex-Auth` header. The server keeps no session list and no revocation record. + +There is no "log out everywhere". Each device holds the account's keys and signs itself in with them (there's no password), so no server action could remove a device that holds them without the server keeping a list of your devices, which Privex doesn't. To take Privex off a device, use "Erase this device" on it. A lost device is protected by App Lock; if App Lock wasn't on, move to a new account. --- diff --git a/server/src/auth/extract.rs b/server/src/auth/extract.rs index e92c132..b474be7 100644 --- a/server/src/auth/extract.rs +++ b/server/src/auth/extract.rs @@ -1,6 +1,7 @@ // Authenticated-user extractor. Reads the session token from the X-Privex-Auth // HEADER only - never from a URL/query string (those can land in proxy logs). -// Any failure is a generic 401. +// Any failure is a generic 401. Tokens are stateless (HMAC + 24 h expiry): the +// server keeps no session list and no revocation record. use axum::async_trait; use axum::extract::FromRequestParts; @@ -9,7 +10,6 @@ use axum::http::request::Parts; use crate::auth::token; use crate::error::ApiError; use crate::now_unix; -use crate::rds; use crate::state::AppState; pub struct AuthUser(pub String); @@ -24,25 +24,8 @@ impl FromRequestParts for AuthUser { .get("x-privex-auth") .and_then(|v| v.to_str().ok()) .ok_or_else(ApiError::unauthorized)?; - let (user_id, issued_at) = - token::verify_with_iat(&state.config.token_mac_key, header, now_unix()) - .ok_or_else(ApiError::unauthorized)?; - - // "Log out everywhere": reject tokens issued before the user's revocation - // cutoff. Fail CLOSED on a Redis error - revocation is the only kill switch - // for a stolen token, so "cannot confirm validity" must reject. Availability - // cost is nil in practice: nearly every endpoint already 500s when Redis is - // down (rate limits, challenges, tickets all live there). 500 (not 401) so - // clients treat it as transient, not as a bad token. - let cutoff = - rds::get_revoke_cutoff(&state.redis, &state.config.redis_ns_key, &user_id) - .await - .map_err(|_| ApiError::internal())?; - if let Some(cutoff) = cutoff { - if issued_at < cutoff { - return Err(ApiError::unauthorized()); - } - } + let user_id = token::verify(&state.config.token_mac_key, header, now_unix()) + .ok_or_else(ApiError::unauthorized)?; Ok(AuthUser(user_id)) } } diff --git a/server/src/auth/token.rs b/server/src/auth/token.rs index 38639f7..54d6d8d 100644 --- a/server/src/auth/token.rs +++ b/server/src/auth/token.rs @@ -46,12 +46,6 @@ pub fn mint(key: &[u8; 32], user_id: &str, now: i64) -> String { /// Returns the user_id if the token is authentic and unexpired, else None. pub fn verify(key: &[u8; 32], token: &str, now: i64) -> Option { - verify_with_iat(key, token, now).map(|(user_id, _)| user_id) -} - -/// Like `verify`, but also returns the token's `issued_at` so a caller can apply -/// a revocation cutoff ("log out everywhere" invalidates tokens issued earlier). -pub fn verify_with_iat(key: &[u8; 32], token: &str, now: i64) -> Option<(String, i64)> { let (p_b64, t_b64) = token.split_once('.')?; let pj = URL_SAFE_NO_PAD.decode(p_b64).ok()?; let tag = URL_SAFE_NO_PAD.decode(t_b64).ok()?; @@ -64,7 +58,7 @@ pub fn verify_with_iat(key: &[u8; 32], token: &str, now: i64) -> Option<(String, if now >= payload.expires_at { return None; } - Some((payload.user_id, payload.issued_at)) + Some(payload.user_id) } #[cfg(test)] diff --git a/server/src/config.rs b/server/src/config.rs index b4d692e..94c5e46 100644 --- a/server/src/config.rs +++ b/server/src/config.rs @@ -12,8 +12,8 @@ pub struct Config { /// HKDF-Expand("privex-session-token") - never the root directly (PVX-24). /// 32 bytes, never logged, never leaves process. pub token_mac_key: [u8; 32], - /// PRF key for Redis key namespacing (challenges, tickets, revocation, - /// rate-limit buckets). Derived via HKDF-Expand("privex-redis-namespace"); + /// PRF key for Redis key namespacing (challenges, tickets, rate-limit + /// buckets). Derived via HKDF-Expand("privex-redis-namespace"); /// per-purpose separation inside Redis comes from the scope string that /// rds::keyed() folds into each HMAC. pub redis_ns_key: [u8; 32], diff --git a/server/src/lib.rs b/server/src/lib.rs index 1d7a84d..e182d79 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -179,7 +179,6 @@ pub fn app(state: AppState) -> Router { .route("/auth/challenge", post(routes::auth::challenge)) .route("/auth/verify", post(routes::auth::verify)) .route("/auth/ws_ticket", post(routes::auth::ws_ticket)) - .route("/auth/logout_all", post(routes::auth::logout_all)) .route( "/keys/register", post(routes::register::register).layer(DefaultBodyLimit::max(64 * 1024)), diff --git a/server/src/rds.rs b/server/src/rds.rs index 280fd29..a4bdd1d 100644 --- a/server/src/rds.rs +++ b/server/src/rds.rs @@ -181,39 +181,6 @@ pub async fn take_login_state( } } -/// Token revocation cutoff: every session token issued BEFORE this unix time is -/// invalid (used by "log out everywhere"). Keyed by HMAC(user_id); TTL = token -/// TTL, after which all older tokens have already expired. -pub async fn set_revoke_cutoff( - pool: &Pool, - server_key: &[u8; 32], - user_id: &str, - cutoff: i64, - ttl_secs: i64, -) -> anyhow::Result<()> { - let key = format!("rev:{}", keyed(server_key, "rev", user_id)); - let mut conn = pool.get().await?; - let _: () = redis::cmd("SET") - .arg(&key) - .arg(cutoff) - .arg("EX") - .arg(ttl_secs) - .query_async(&mut conn) - .await?; - Ok(()) -} - -pub async fn get_revoke_cutoff( - pool: &Pool, - server_key: &[u8; 32], - user_id: &str, -) -> anyhow::Result> { - let key = format!("rev:{}", keyed(server_key, "rev", user_id)); - let mut conn = pool.get().await?; - let value: Option = redis::cmd("GET").arg(&key).query_async(&mut conn).await?; - Ok(value) -} - /// Mark a PoW ticket spent (single use, docs 8.5). True iff THIS call spent it; /// false = already spent (a replay). Keyed by the ticket's random id - never an /// identity. The TTL outlives the ticket's own expiry, so a spent ticket can't diff --git a/server/src/routes/auth.rs b/server/src/routes/auth.rs index 837251d..8ccdc66 100644 --- a/server/src/routes/auth.rs +++ b/server/src/routes/auth.rs @@ -310,35 +310,3 @@ pub async fn ws_ticket( account_spk: AccountSpk::from(&bundle), })) } - -// --- POST /auth/logout_all --- -// "Log out everywhere": set a revocation cutoff so every session token issued -// before now (incl. the one making this call) becomes invalid. NOTE: the guide -// framed this as SPK rotation invalidating tokens, but this server's tokens are -// HMAC/TTL and SPK-independent - real revocation is the correct mechanism. SPK -// rotation (a separate /keys/spk/rotate call) is orthogonal forward secrecy. - -#[derive(Serialize)] -pub struct LogoutAllResp { - revoked: bool, -} - -pub async fn logout_all( - AuthUser(user_id): AuthUser, - State(st): State, -) -> Result, ApiError> { - // Cheap Redis write, but bound it anyway (each call extends the rev: key TTL). - crate::routes::rate_limit(&st, "logoutall", &user_id, 10, 60).await?; - // cutoff = now+1 so EVERY token issued in this second or earlier (incl. the - // caller's) is revoked; a fresh login must wait until the next second. - rds::set_revoke_cutoff( - &st.redis, - &st.config.redis_ns_key, - &user_id, - now_unix() + 1, - token::TTL_SECS, - ) - .await - .map_err(|_| ApiError::internal())?; - Ok(Json(LogoutAllResp { revoked: true })) -} diff --git a/server/tests/integration.rs b/server/tests/integration.rs index 846170c..c3e2561 100644 --- a/server/tests/integration.rs +++ b/server/tests/integration.rs @@ -2211,35 +2211,6 @@ async fn server_end_to_end() { ); } - // Log out everywhere: the token works before, then 401s after revocation. - assert_eq!( - http.post(format!("{base}/auth/ws_ticket")) - .header("X-Privex-Auth", &token) - .send() - .await - .unwrap() - .status(), - 200, - "token valid before logout_all" - ); - let lo = http - .post(format!("{base}/auth/logout_all")) - .header("X-Privex-Auth", &token) - .send() - .await - .unwrap(); - assert_eq!(lo.status(), 200); - assert_eq!( - http.post(format!("{base}/auth/ws_ticket")) - .header("X-Privex-Auth", &token) - .send() - .await - .unwrap() - .status(), - 401, - "token must be revoked after logout_all" - ); - // 6c. /metrics is non-vacuous now: after real registration/auth/message // traffic with known px_ids, the label-free counters still carry NO px_ id // and NO message id (PVX-04). This scrape AFTER the flows is what makes the @@ -2852,69 +2823,6 @@ async fn rate_limit_window_resets() { assert!(check_rate_limit(&pool, &key, "rltest", &who, 2, 1).await.unwrap(), "window reset"); } -// PVX-06: the revocation cutoff check must fail CLOSED. With Redis unreachable, -// an otherwise-valid session token is rejected by the AuthUser extractor (500, -// treated as transient by clients) instead of silently skipping the check. -// Needs no Docker: lazy PG pool + a Redis pool pointing at a dead port. -#[tokio::test] -async fn revocation_check_fails_closed_when_redis_down() { - use axum::extract::FromRequestParts; - use privex_server::auth::extract::AuthUser; - use privex_server::auth::token; - use privex_server::state::AppState; - use privex_server::ws; - - let key = [7u8; 32]; - let config = Config::for_test( - "postgres://unused:unused@127.0.0.1:1/unused".into(), - "redis://127.0.0.1:1".into(), // nothing listens here - key, - 8, - ); - let state = AppState { - db: sqlx::postgres::PgPoolOptions::new() - .connect_lazy("postgres://unused:unused@127.0.0.1:1/unused") - .unwrap(), - redis: deadpool_redis::Config::from_url("redis://127.0.0.1:1") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(), - config: Arc::new(config), - store: Arc::new(MemoryStore::new()), - online: Arc::new(ws::state::Online::new()), - devlink: Arc::new(ws::devlink::DevlinkRooms::new()), - kt_cache: privex_server::kt_cache::KtCache::new(), - ready_cache: Arc::new(tokio::sync::Mutex::new(None)), - pow_verify_sem: Arc::new(tokio::sync::Semaphore::new( - privex_server::state::POW_VERIFY_MAX_CONCURRENCY, - )), - }; - - // Mint with the config-derived token MAC subkey (PVX-24), not the raw root. - let tok = token::mint( - &state.config.token_mac_key, - "px_00000000000000000000000000000001", - now_unix(), - ); - let req = axum::http::Request::builder() - .header("x-privex-auth", &tok) - .body(()) - .unwrap(); - let (mut parts, _) = req.into_parts(); - - use axum::response::IntoResponse; - let err = AuthUser::from_request_parts(&mut parts, &state) - .await - .err() - .expect("a valid token must be REJECTED when the revocation store is unreachable"); - // Specifically 500 (transient), NOT 401 - a 401 would read to the client as a - // bad token and trigger a pointless re-auth instead of a retry. - assert_eq!( - err.into_response().status(), - 500, - "Redis-unreachable must map to 500 Internal Server Error, not 401" - ); -} - // PVX-02: /health/ready must return 503 when a dependency is unreachable, so a // broken pod is drained instead of served. Docker-free: point DB + Redis at dead // ports, serve the real router on a loopback port, and probe over HTTP.