forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

oidc.rs1285 lines, 45.6 KiBHistoryRawDownload
1//! The OIDC provider half: relying-party registration, authorization codes,
2//! refresh tokens, and the hand-rolled RS256 JWT the endpoints mint.
3//!
4//! JWT is hand-rolled on purpose: both ends of the wire are ours, the format
5//! is `base64url(header).base64url(payload).base64url(signature)` and nothing
6//! more, and a third crate in the trust path buys nothing.
7
8use base64::Engine;
9use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
10use rsa::RsaPrivateKey;
11use rsa::signature::{SignatureEncoding, Signer};
12
13use crate::accounts::{Token, digests_match, hash_token};
14use crate::model::{AuthCode, ClientId, OidcClient, RefreshToken, UserId};
15use crate::store::{self, Result, Store, StoreError, backend};
16
17/// How long an authorization code lives, in seconds.
18pub const CODE_SECONDS: i64 = 60;
19/// How long an access/id token lives, in seconds.
20pub const TOKEN_SECONDS: i64 = 15 * 60;
21/// How long a refresh token lives.
22pub const REFRESH_DAYS: i64 = 30;
23
24#[derive(Debug, thiserror::Error)]
25pub enum OidcError {
26 #[error("database: {0}")]
27 Backend(String),
28 #[error("unknown client")]
29 UnknownClient,
30 #[error("bad client secret")]
31 BadSecret,
32}
33
34impl From<StoreError> for OidcError {
35 fn from(e: StoreError) -> Self {
36 OidcError::Backend(e.to_string())
37 }
38}
39
40/// Signs `claims` into a compact RS256 JWT under `kid`.
41pub fn sign_jwt(claims: &serde_json::Value, kid: &str, key: &RsaPrivateKey) -> String {
42 let header = serde_json::json!({ "alg": "RS256", "typ": "JWT", "kid": kid });
43 let mut out = b64url.encode(header.to_string());
44 out.push('.');
45 out.push_str(&b64url.encode(claims.to_string()));
46 let signing = rsa::pkcs1v15::SigningKey::<sha2::Sha256>::new(key.clone());
47 let signature = signing.sign(out.as_bytes());
48 out.push('.');
49 out.push_str(&b64url.encode(signature.to_bytes()));
50 out
51}
52
53// ---------------------------------------------------------------------------
54// Clients
55// ---------------------------------------------------------------------------
56
57/// Registers a relying party, returning its id and the raw client secret —
58/// shown exactly once; the row holds the digest.
59pub async fn create_client(
60 store: &Store,
61 name: &str,
62 redirect_uris: Vec<String>,
63) -> Result<(ClientId, Token)> {
64 let conn = store.conn.lock().await;
65 let id = ClientId::mint();
66 let secret = Token::mint();
67 conn.execute(
68 "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
69 VALUES (?1, ?2, ?3, ?4, ?5)",
70 turso::params![
71 id.to_string(),
72 name,
73 secret.hash(),
74 serde_json::to_string(&redirect_uris)
75 .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?,
76 store::stamp(store::now())?,
77 ],
78 )
79 .await
80 .map_err(backend)?;
81 Ok((id, secret))
82}
83
84/// Looks a client up by its public id.
85pub async fn client_by_id(store: &Store, client_id: &str) -> Result<Option<OidcClient>> {
86 let conn = store.conn.lock().await;
87 let mut rows = conn
88 .query(
89 "SELECT client_id, name, secret_hash, redirect_uris, created_at \
90 FROM oidc_clients WHERE client_id = ?1",
91 turso::params![client_id],
92 )
93 .await
94 .map_err(backend)?;
95 let Some(row) = rows.next().await.map_err(backend)? else {
96 return Ok(None);
97 };
98 Ok(Some(read_client(&row)?))
99}
100
101fn read_client(row: &turso::Row) -> Result<OidcClient> {
102 let uris_raw = store::text(row, 3)?;
103 Ok(OidcClient {
104 client_id: ClientId::from(store::text(row, 0)?),
105 name: store::text(row, 1)?,
106 secret_hash: store::text(row, 2)?,
107 redirect_uris: serde_json::from_str(&uris_raw)
108 .map_err(|e| StoreError::Corrupt(format!("redirect_uris {uris_raw:?}: {e}")))?,
109 created_at: store::parse_stamp(&store::text(row, 4)?)?,
110 })
111}
112
113/// Constant-time client-secret check.
114pub fn verify_client_secret(client: &OidcClient, secret: &str) -> bool {
115 digests_match(&client.secret_hash, &hash_token(secret))
116}
117
118/// A registered client, as the panel's Clients section and the CLI list it:
119/// no secret material — the row's digest stays an internal affair.
120#[derive(Debug, Clone)]
121pub struct ClientSummary {
122 pub client_id: ClientId,
123 pub name: String,
124 pub redirect_uris: Vec<String>,
125 pub created_at: time::OffsetDateTime,
126}
127
128/// Every registered client, oldest first — the admin panel's roster.
129pub async fn list_clients(store: &Store) -> Result<Vec<ClientSummary>> {
130 let conn = store.conn.lock().await;
131 let mut rows = conn
132 .query(
133 "SELECT client_id, name, redirect_uris, created_at FROM oidc_clients \
134 ORDER BY created_at, client_id",
135 (),
136 )
137 .await
138 .map_err(backend)?;
139 let mut out = Vec::new();
140 while let Some(row) = rows.next().await.map_err(backend)? {
141 let uris_raw = store::text(&row, 2)?;
142 out.push(ClientSummary {
143 client_id: ClientId::from(store::text(&row, 0)?),
144 name: store::text(&row, 1)?,
145 redirect_uris: serde_json::from_str(&uris_raw)
146 .map_err(|e| StoreError::Corrupt(format!("redirect_uris {uris_raw:?}: {e}")))?,
147 created_at: store::parse_stamp(&store::text(&row, 3)?)?,
148 });
149 }
150 Ok(out)
151}
152
153/// Replaces a client's secret, returning the fresh one — shown exactly once;
154/// the row keeps only the new digest and every pair minted before is dead.
155/// `None` for an unknown client.
156pub async fn rotate_client_secret(store: &Store, client_id: &str) -> Result<Option<Token>> {
157 let conn = store.conn.lock().await;
158 let secret = Token::mint();
159 let updated = conn
160 .execute(
161 "UPDATE oidc_clients SET secret_hash = ?1 WHERE client_id = ?2",
162 turso::params![secret.hash(), client_id],
163 )
164 .await
165 .map_err(backend)?;
166 Ok((updated > 0).then_some(secret))
167}
168
169/// Deletes a client outright: the registry row and every refresh token and
170/// app session minted under it, one immediate transaction — no token row
171/// outlives the pair that minted it, and introspection reads them as
172/// inactive on the very next call. The person's sign-in sessions are not
173/// touched: the client's doors close, the browsers' stay open. `false` for
174/// an unknown client.
175pub async fn revoke_client(store: &Store, client_id: &str) -> Result<bool> {
176 let conn = store.conn.lock().await;
177 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
178 let outcome = async {
179 conn.execute(
180 "DELETE FROM refresh_tokens WHERE client_id = ?1",
181 turso::params![client_id],
182 )
183 .await
184 .map_err(backend)?;
185 conn.execute(
186 "DELETE FROM app_sessions WHERE client_id = ?1",
187 turso::params![client_id],
188 )
189 .await
190 .map_err(backend)?;
191 let deleted = conn
192 .execute(
193 "DELETE FROM oidc_clients WHERE client_id = ?1",
194 turso::params![client_id],
195 )
196 .await
197 .map_err(backend)?;
198 Ok(deleted > 0)
199 }
200 .await;
201 match outcome {
202 Ok(known) => {
203 conn.execute("COMMIT", ()).await.map_err(backend)?;
204 Ok(known)
205 }
206 Err(e) => {
207 let _ = conn.execute("ROLLBACK", ()).await;
208 Err(e)
209 }
210 }
211}
212
213// ---------------------------------------------------------------------------
214// Authorization codes
215// ---------------------------------------------------------------------------
216
217/// Mints an authorization code for a completed login. Raw code returned; the
218/// row holds the digest.
219pub async fn create_auth_code(
220 store: &Store,
221 client_id: &ClientId,
222 user: &UserId,
223 redirect_uri: &str,
224 nonce: Option<String>,
225 challenge: &str,
226 session_hash: &str,
227) -> Result<Token> {
228 let conn = store.conn.lock().await;
229 let code = Token::mint();
230 conn
231 .execute(
232 "INSERT INTO auth_codes \
233 (code_hash, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at) \
234 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
235 turso::params![
236 code.hash(),
237 client_id.to_string(),
238 user.to_string(),
239 redirect_uri,
240 nonce,
241 challenge,
242 session_hash,
243 store::stamp(store::now() + time::Duration::seconds(CODE_SECONDS))?,
244 ],
245 )
246 .await
247 .map_err(backend)?;
248 Ok(code)
249}
250
251/// Consumes a code: returns its row exactly once. The SELECT and the
252/// `consumed_at` stamp run inside one immediate transaction, so two parallel
253/// exchanges of the same code cannot both succeed.
254pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthCode>> {
255 let conn = store.conn.lock().await;
256 let hash = hash_token(code);
257 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
258 let outcome = async {
259 let mut rows = conn
260 .query(
261 "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \
262 expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1",
263 turso::params![hash.clone()],
264 )
265 .await
266 .map_err(backend)?;
267 let Some(row) = rows.next().await.map_err(backend)? else {
268 return Ok(None);
269 };
270 if store::opt_text(&row, 7)?.is_some() {
271 return Ok(None);
272 }
273 if store::parse_stamp(&store::text(&row, 6)?)? < store::now() {
274 return Ok(None);
275 }
276 conn.execute(
277 "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2",
278 turso::params![store::stamp(store::now())?, hash],
279 )
280 .await
281 .map_err(backend)?;
282 Ok(Some(AuthCode {
283 client_id: ClientId::from(store::text(&row, 0)?),
284 user_id: UserId::from(store::text(&row, 1)?),
285 redirect_uri: store::text(&row, 2)?,
286 nonce: store::opt_text(&row, 3)?,
287 code_challenge: store::text(&row, 4)?,
288 session_hash: store::text(&row, 5)?,
289 expires_at: store::parse_stamp(&store::text(&row, 6)?)?,
290 }))
291 }
292 .await;
293 match outcome {
294 Ok(found) => {
295 conn.execute("COMMIT", ()).await.map_err(backend)?;
296 Ok(found)
297 }
298 Err(e) => {
299 let _ = conn.execute("ROLLBACK", ()).await;
300 Err(e)
301 }
302 }
303}
304
305/// Reads a code without spending it — the `/token` handler's pre-flight, so
306/// a presentation that fails its client, redirect, or PKCE check cannot
307/// burn the code for its rightful owner. The same validity rules as
308/// [`consume_auth_code`] apply: unknown, consumed, and expired codes read
309/// as `None`. The code is still consumable afterwards; [`consume_auth_code`]
310/// remains the only spender, and its transaction decides a race.
311pub async fn peek_auth_code(store: &Store, code: &str) -> Result<Option<AuthCode>> {
312 let conn = store.conn.lock().await;
313 let mut rows = conn
314 .query(
315 "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \
316 expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1",
317 turso::params![hash_token(code)],
318 )
319 .await
320 .map_err(backend)?;
321 let Some(row) = rows.next().await.map_err(backend)? else {
322 return Ok(None);
323 };
324 if store::opt_text(&row, 7)?.is_some() {
325 return Ok(None);
326 }
327 if store::parse_stamp(&store::text(&row, 6)?)? < store::now() {
328 return Ok(None);
329 }
330 Ok(Some(AuthCode {
331 client_id: ClientId::from(store::text(&row, 0)?),
332 user_id: UserId::from(store::text(&row, 1)?),
333 redirect_uri: store::text(&row, 2)?,
334 nonce: store::opt_text(&row, 3)?,
335 code_challenge: store::text(&row, 4)?,
336 session_hash: store::text(&row, 5)?,
337 expires_at: store::parse_stamp(&store::text(&row, 6)?)?,
338 }))
339}
340
341// ---------------------------------------------------------------------------
342// Refresh tokens
343// ---------------------------------------------------------------------------
344
345/// Issues a refresh token bound to the central session that minted it, so
346/// revoking the session retires every token the apps are still holding.
347pub async fn issue_refresh(
348 store: &Store,
349 user: &UserId,
350 client_id: &ClientId,
351 session_hash: &str,
352) -> Result<Token> {
353 let conn = store.conn.lock().await;
354 let token = Token::mint();
355 conn.execute(
356 "INSERT INTO refresh_tokens \
357 (token_hash, user_id, client_id, session_hash, expires_at) \
358 VALUES (?1, ?2, ?3, ?4, ?5)",
359 turso::params![
360 token.hash(),
361 user.to_string(),
362 client_id.to_string(),
363 session_hash,
364 store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
365 ],
366 )
367 .await
368 .map_err(backend)?;
369 Ok(token)
370}
371
372/// Rotates a refresh token: the presented one is revoked, a fresh one is
373/// minted against the same session, and the new raw token plus the old row
374/// come back. `None` for unknown, expired, or revoked tokens — and for tokens
375/// whose central session is gone, which is what makes SSO logout global.
376pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, RefreshToken)>> {
377 let conn = store.conn.lock().await;
378 let hash = hash_token(token);
379 conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
380 let outcome = async {
381 let mut rows = conn
382 .query(
383 "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
384 FROM refresh_tokens WHERE token_hash = ?1",
385 turso::params![hash.clone()],
386 )
387 .await
388 .map_err(backend)?;
389 let Some(row) = rows.next().await.map_err(backend)? else {
390 return Ok(None);
391 };
392 if store::opt_text(&row, 4)?.is_some() {
393 return Ok(None);
394 }
395 if store::parse_stamp(&store::text(&row, 3)?)? < store::now() {
396 return Ok(None);
397 }
398 let record = RefreshToken {
399 user_id: UserId::from(store::text(&row, 0)?),
400 client_id: ClientId::from(store::text(&row, 1)?),
401 session_hash: store::text(&row, 2)?,
402 expires_at: store::parse_stamp(&store::text(&row, 3)?)?,
403 };
404 // The session that minted this token must still be alive.
405 let mut sessions = conn
406 .query(
407 "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
408 turso::params![record.session_hash.clone()],
409 )
410 .await
411 .map_err(backend)?;
412 let Some(session) = sessions.next().await.map_err(backend)? else {
413 return Ok(None);
414 };
415 if store::opt_text(&session, 1)?.is_some() {
416 return Ok(None);
417 }
418 if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
419 return Ok(None);
420 }
421
422 let now = store::stamp(store::now())?;
423 conn.execute(
424 "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2",
425 turso::params![now.clone(), hash.clone()],
426 )
427 .await
428 .map_err(backend)?;
429 // Inlined from `issue_refresh`: the transaction already holds the
430 // connection, and the helper locks for itself.
431 let fresh = Token::mint();
432 conn.execute(
433 "INSERT INTO refresh_tokens \
434 (token_hash, user_id, client_id, session_hash, expires_at) \
435 VALUES (?1, ?2, ?3, ?4, ?5)",
436 turso::params![
437 fresh.hash(),
438 record.user_id.to_string(),
439 record.client_id.to_string(),
440 record.session_hash.clone(),
441 store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
442 ],
443 )
444 .await
445 .map_err(backend)?;
446 Ok(Some((fresh, record)))
447 }
448 .await;
449 match outcome {
450 Ok(found) => {
451 conn.execute("COMMIT", ()).await.map_err(backend)?;
452 Ok(found)
453 }
454 Err(e) => {
455 let _ = conn.execute("ROLLBACK", ()).await;
456 Err(e)
457 }
458 }
459}
460
461/// Reads a refresh token without rotating it — the `/token` handler's
462/// pre-flight, so a token presented by the wrong client is judged before
463/// any rotation can burn its owner's chain. The same validity rules as
464/// [`rotate_refresh`] apply: unknown, revoked, and expired tokens — and
465/// tokens whose central session is gone — read as `None`.
466pub async fn peek_refresh(store: &Store, token: &str) -> Result<Option<RefreshToken>> {
467 let conn = store.conn.lock().await;
468 let mut rows = conn
469 .query(
470 "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
471 FROM refresh_tokens WHERE token_hash = ?1",
472 turso::params![hash_token(token)],
473 )
474 .await
475 .map_err(backend)?;
476 let Some(row) = rows.next().await.map_err(backend)? else {
477 return Ok(None);
478 };
479 if store::opt_text(&row, 4)?.is_some() {
480 return Ok(None);
481 }
482 if store::parse_stamp(&store::text(&row, 3)?)? < store::now() {
483 return Ok(None);
484 }
485 let record = RefreshToken {
486 user_id: UserId::from(store::text(&row, 0)?),
487 client_id: ClientId::from(store::text(&row, 1)?),
488 session_hash: store::text(&row, 2)?,
489 expires_at: store::parse_stamp(&store::text(&row, 3)?)?,
490 };
491 drop(rows);
492 // The session that minted this token must still be alive.
493 let mut sessions = conn
494 .query(
495 "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
496 turso::params![record.session_hash.clone()],
497 )
498 .await
499 .map_err(backend)?;
500 let Some(session) = sessions.next().await.map_err(backend)? else {
501 return Ok(None);
502 };
503 if store::opt_text(&session, 1)?.is_some() {
504 return Ok(None);
505 }
506 if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
507 return Ok(None);
508 }
509 Ok(Some(record))
510}
511
512// ---------------------------------------------------------------------------
513// Verification (the provider half: /userinfo and future introspection)
514// ---------------------------------------------------------------------------
515
516/// RFC 7636 S256: `base64url(sha256(verifier))` must equal the challenge the
517/// `/authorize` call stored.
518pub fn pkce_matches(challenge: &str, verifier: &str) -> bool {
519 use sha2::Digest;
520 let computed = b64url.encode(sha2::Sha256::digest(verifier.as_bytes()));
521 crate::accounts::digests_match(challenge, &computed)
522}
523
524/// Verifies a compact JWT im minted: RS256 signature against the active key
525/// named by `kid`, `aud` equal to `audience`, `exp` in the future. Returns
526/// the claims on success, `None` for every way a token can fail — unknown
527/// key, bad signature, wrong audience, expired — which all read the same to
528/// the caller: this token does not authenticate anyone.
529///
530/// `iss` is the caller's to check: the issuer string is configuration the
531/// core crate does not hold.
532pub async fn verify_jwt(
533 store: &Store,
534 token: &str,
535 audience: Option<&str>,
536) -> Result<Option<serde_json::Value>> {
537 use rsa::signature::Verifier;
538
539 let parts: Vec<&str> = token.split('.').collect();
540 if parts.len() != 3 {
541 return Ok(None);
542 }
543 let Ok(header_bytes) = b64url.decode(parts[0]) else {
544 return Ok(None);
545 };
546 let Ok(header) = serde_json::from_slice::<serde_json::Value>(&header_bytes) else {
547 return Ok(None);
548 };
549 if header["alg"] != "RS256" {
550 return Ok(None);
551 }
552 let Some(kid) = header["kid"].as_str() else {
553 return Ok(None);
554 };
555 let Some(public) = crate::keys::public_key_by_kid(store, kid).await? else {
556 return Ok(None);
557 };
558 let Ok(signature_bytes) = b64url.decode(parts[2]) else {
559 return Ok(None);
560 };
561 let Ok(signature) = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) else {
562 return Ok(None);
563 };
564 let verifying = rsa::pkcs1v15::VerifyingKey::<sha2::Sha256>::new(public);
565 if verifying
566 .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
567 .is_err()
568 {
569 return Ok(None);
570 }
571 let Ok(claims_bytes) = b64url.decode(parts[1]) else {
572 return Ok(None);
573 };
574 let Ok(claims) = serde_json::from_slice::<serde_json::Value>(&claims_bytes) else {
575 return Ok(None);
576 };
577 if let Some(audience) = audience && claims["aud"].as_str() != Some(audience) {
578 return Ok(None);
579 }
580 let Some(exp) = claims["exp"].as_i64() else {
581 return Ok(None);
582 };
583 if exp <= store::now().unix_timestamp() {
584 return Ok(None);
585 }
586 Ok(Some(claims))
587}
588
589// ---------------------------------------------------------------------------
590// App sessions: the opaque, introspected session an app actually holds
591// ---------------------------------------------------------------------------
592
593/// How long an app session may live when nothing revokes it first.
594pub const APP_SESSION_DAYS: i64 = 30;
595
596/// Mints an opaque app session bound to the central session that authorized
597/// it. The app stores only this token; every request it serves introspects
598/// the token against im, so revocation is immediate rather than
599/// token-TTL-bounded.
600pub async fn issue_app_session(
601 store: &Store,
602 user: &UserId,
603 client_id: &ClientId,
604 session_hash: &str,
605) -> Result<Token> {
606 let conn = store.conn.lock().await;
607 let token = Token::mint();
608 let now = store::now();
609 conn.execute(
610 "INSERT INTO app_sessions \
611 (token_hash, user_id, client_id, session_hash, created_at, expires_at) \
612 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
613 turso::params![
614 token.hash(),
615 user.to_string(),
616 client_id.to_string(),
617 session_hash,
618 store::stamp(now)?,
619 store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?,
620 ],
621 )
622 .await
623 .map_err(backend)?;
624 Ok(token)
625}
626
627/// RFC 7662's answer shape: who this token is, or inactive. The active answer
628/// carries im's admin flag so registered apps can derive their own admin
629/// authorization from it. Inactive covers unknown, expired, revoked, a
630/// revoked central session, a disabled user, or a token presented by a client
631/// it was never issued to.
632pub async fn introspect_app_session(
633 store: &Store,
634 token: &str,
635 client_id: &str,
636) -> Result<Option<serde_json::Value>> {
637 // Both rows are read under one short-held guard; the user lookup locks
638 // for itself after it drops.
639 let (user_id, expires) = {
640 let conn = store.conn.lock().await;
641 let mut rows = conn
642 .query(
643 "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
644 FROM app_sessions WHERE token_hash = ?1",
645 turso::params![hash_token(token)],
646 )
647 .await
648 .map_err(backend)?;
649 let Some(row) = rows.next().await.map_err(backend)? else {
650 return Ok(None);
651 };
652 if store::opt_text(&row, 4)?.is_some() {
653 return Ok(None);
654 }
655 let expires = store::parse_stamp(&store::text(&row, 3)?)?;
656 if expires < store::now() {
657 return Ok(None);
658 }
659 if store::text(&row, 1)? != client_id {
660 return Ok(None);
661 }
662 // The central session must still be alive — this is what makes admin
663 // revocation immediate.
664 let session_hash = store::text(&row, 2)?;
665 let mut sessions = conn
666 .query(
667 "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
668 turso::params![session_hash],
669 )
670 .await
671 .map_err(backend)?;
672 let Some(session) = sessions.next().await.map_err(backend)? else {
673 return Ok(None);
674 };
675 if store::opt_text(&session, 1)?.is_some() {
676 return Ok(None);
677 }
678 if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
679 return Ok(None);
680 }
681 (UserId::from(store::text(&row, 0)?), expires)
682 };
683 let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else {
684 return Ok(None);
685 };
686 if user.disabled {
687 return Ok(None);
688 }
689 Ok(Some(serde_json::json!({
690 "active": true,
691 "sub": user.id.as_str(),
692 "email": user.email,
693 "name": user.name,
694 "admin": user.admin,
695 "photo_version": user.photo_version,
696 "timezone": user.timezone,
697 "exp": expires.unix_timestamp(),
698 })))
699}
700
701/// One app a person is signed into, as the connected-apps list shows it:
702/// the client, its display name, how many of its app sessions are live,
703/// and when the person first and last connected to it.
704#[derive(Debug, Clone)]
705pub struct ConnectedApp {
706 pub client_id: String,
707 pub name: String,
708 pub count: i64,
709 pub first_at: time::OffsetDateTime,
710 pub last_at: time::OffsetDateTime,
711}
712
713/// The OIDC clients holding at least one live app session for `user`,
714/// most recently connected first. Revocation and expiry filter in SQL
715/// beside the introspection answer and `stats`' counts; the display name
716/// falls back to the raw `client_id` when no registered client row stands
717/// behind it.
718pub async fn list_connected_apps(store: &Store, user: &UserId) -> Result<Vec<ConnectedApp>> {
719 let conn = store.conn.lock().await;
720 let mut rows = conn
721 .query(
722 "SELECT a.client_id, COALESCE(c.name, a.client_id), COUNT(*), \
723 MIN(a.created_at), MAX(a.created_at) \
724 FROM app_sessions a \
725 LEFT JOIN oidc_clients c ON c.client_id = a.client_id \
726 WHERE a.user_id = ?1 AND a.revoked_at IS NULL AND a.expires_at > ?2 \
727 GROUP BY a.client_id \
728 ORDER BY MAX(a.created_at) DESC, a.client_id",
729 turso::params![user.to_string(), store::stamp(store::now())?],
730 )
731 .await
732 .map_err(backend)?;
733 let mut out = Vec::new();
734 while let Some(row) = rows.next().await.map_err(backend)? {
735 out.push(ConnectedApp {
736 client_id: store::text(&row, 0)?,
737 name: store::text(&row, 1)?,
738 count: store::int(&row, 2)?,
739 first_at: store::parse_stamp(&store::text(&row, 3)?)?,
740 last_at: store::parse_stamp(&store::text(&row, 4)?)?,
741 });
742 }
743 Ok(out)
744}
745
746#[cfg(test)]
747mod tests {
748 use super::*;
749 use crate::accounts::{create_invite, create_user_from_invite};
750 use crate::sessions::{SessionMeta, create_session};
751 use rsa::signature::Verifier;
752 use std::path::Path;
753
754 #[tokio::test]
755 async fn app_session_introspection_and_instant_revoke() {
756 let (store, client_id, user_id) = fixture().await;
757 let session = create_session(&store, &user_id, &SessionMeta::default())
758 .await
759 .unwrap();
760 let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash())
761 .await
762 .unwrap();
763
764 let active = introspect_app_session(&store, app_token.expose(), client_id.as_str())
765 .await
766 .unwrap()
767 .unwrap();
768 assert_eq!(active["active"], true);
769 assert_eq!(active["sub"], user_id.as_str());
770
771 // Another client cannot spend the token.
772 assert!(
773 introspect_app_session(&store, app_token.expose(), "someone-else")
774 .await
775 .unwrap()
776 .is_none()
777 );
778
779 // Admin revokes the person: the very next introspection is inactive.
780 crate::sessions::revoke_user_sessions(&store, &user_id)
781 .await
782 .unwrap();
783 assert!(
784 introspect_app_session(&store, app_token.expose(), client_id.as_str())
785 .await
786 .unwrap()
787 .is_none(),
788 "no ghost after admin revocation"
789 );
790 }
791
792 #[tokio::test]
793 async fn app_session_introspection_carries_admin_flag() {
794 let (store, client_id, user_id) = fixture().await;
795 let invite = create_invite(&store, "ada@example.com", None, true)
796 .await
797 .unwrap();
798 let admin = create_user_from_invite(&store, invite.expose(), "Ada", "tDLr9!mZQ2xv")
799 .await
800 .unwrap();
801 for (id, want) in [(user_id, false), (admin.id, true)] {
802 let session = create_session(&store, &id, &SessionMeta::default())
803 .await
804 .unwrap();
805 let app_token = issue_app_session(&store, &id, &client_id, &session.hash())
806 .await
807 .unwrap();
808 let active =
809 introspect_app_session(&store, app_token.expose(), client_id.as_str())
810 .await
811 .unwrap()
812 .unwrap();
813 assert_eq!(active["active"], true);
814 assert_eq!(active["sub"], id.as_str());
815 assert_eq!(active["admin"], want);
816 assert_eq!(
817 active["timezone"],
818 crate::model::DEFAULT_TIMEZONE,
819 "introspection carries the display timezone"
820 );
821 }
822 }
823
824 async fn fixture() -> (Store, ClientId, UserId) {
825 let store = Store::open(Path::new(":memory:")).await.unwrap();
826 let (client_id, _secret) =
827 create_client(&store, "demo", vec!["http://app/callback".into()])
828 .await
829 .unwrap();
830 let invite = create_invite(&store, "ann@example.com", None, false)
831 .await
832 .unwrap();
833 let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
834 .await
835 .unwrap();
836 (store, client_id, user.id)
837 }
838
839 #[tokio::test]
840 async fn jwt_structure_and_signature() {
841 let store = Store::open(Path::new(":memory:")).await.unwrap();
842 let (kid, key) = crate::keys::active_signing_key(&store).await.unwrap();
843 let token = sign_jwt(
844 &serde_json::json!({ "iss": "im", "sub": "u1", "exp": 1i64 }),
845 &kid,
846 &key,
847 );
848 let parts: Vec<&str> = token.split('.').collect();
849 assert_eq!(parts.len(), 3);
850 let header: serde_json::Value =
851 serde_json::from_slice(&b64url.decode(parts[0]).unwrap()).unwrap();
852 assert_eq!(header["alg"], "RS256");
853 assert_eq!(header["kid"].as_str().unwrap(), kid);
854 let claims: serde_json::Value =
855 serde_json::from_slice(&b64url.decode(parts[1]).unwrap()).unwrap();
856 assert_eq!(claims["sub"], "u1");
857
858 let verifying =
859 rsa::pkcs1v15::VerifyingKey::<sha2::Sha256>::new(key.to_public_key());
860 let signature =
861 rsa::pkcs1v15::Signature::try_from(b64url.decode(parts[2]).unwrap().as_slice())
862 .unwrap();
863 verifying
864 .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
865 .unwrap();
866 // A tampered payload must not verify.
867 let forged = format!("{}.{}", parts[0], b64url.encode(r#"{"sub":"mallory"}"#));
868 assert!(verifying.verify(forged.as_bytes(), &signature).is_err());
869 }
870
871 #[tokio::test]
872 async fn peek_judges_without_spending() {
873 let (store, client_id, user_id) = fixture().await;
874 let session = create_session(&store, &user_id, &SessionMeta::default())
875 .await
876 .unwrap();
877
878 // A peeked code survives its peek: the rightful exchange still wins.
879 let code = create_auth_code(
880 &store,
881 &client_id,
882 &user_id,
883 "http://app/callback",
884 None,
885 "challenge",
886 &session.hash(),
887 )
888 .await
889 .unwrap();
890 let seen = peek_auth_code(&store, code.expose()).await.unwrap().unwrap();
891 assert_eq!(seen.client_id, client_id);
892 assert!(
893 consume_auth_code(&store, code.expose())
894 .await
895 .unwrap()
896 .is_some()
897 );
898
899 // A peeked refresh token survives its peek: the chain still rotates.
900 let token = issue_refresh(&store, &user_id, &client_id, &session.hash())
901 .await
902 .unwrap();
903 let record = peek_refresh(&store, token.expose()).await.unwrap().unwrap();
904 assert_eq!(record.client_id, client_id);
905 assert!(
906 rotate_refresh(&store, token.expose())
907 .await
908 .unwrap()
909 .is_some()
910 );
911 }
912
913 #[tokio::test]
914 async fn peek_reads_the_same_validity_as_spend() {
915 let (store, client_id, user_id) = fixture().await;
916 let session = create_session(&store, &user_id, &SessionMeta::default())
917 .await
918 .unwrap();
919 let code = create_auth_code(
920 &store,
921 &client_id,
922 &user_id,
923 "http://app/callback",
924 None,
925 "challenge",
926 &session.hash(),
927 )
928 .await
929 .unwrap();
930 let token = issue_refresh(&store, &user_id, &client_id, &session.hash())
931 .await
932 .unwrap();
933
934 // A spent code reads as None to the peek, exactly as to the spend.
935 consume_auth_code(&store, code.expose()).await.unwrap();
936 assert!(peek_auth_code(&store, code.expose()).await.unwrap().is_none());
937
938 // A revoked central session reads as None to the peek, exactly as
939 // to the rotation.
940 crate::sessions::revoke_session(&store, session.expose())
941 .await
942 .unwrap();
943 assert!(peek_refresh(&store, token.expose()).await.unwrap().is_none());
944 }
945
946 #[tokio::test]
947 async fn auth_code_is_single_use() {
948 let (store, client_id, user_id) = fixture().await;
949 let code = create_auth_code(
950 &store,
951 &client_id,
952 &user_id,
953 "http://app/callback",
954 None,
955 "challenge",
956 "session-hash",
957 )
958 .await
959 .unwrap();
960 let first = consume_auth_code(&store, code.expose()).await.unwrap();
961 assert!(first.is_some());
962 assert_eq!(first.unwrap().code_challenge, "challenge");
963 assert!(
964 consume_auth_code(&store, code.expose())
965 .await
966 .unwrap()
967 .is_none()
968 );
969 }
970
971 #[tokio::test]
972 async fn refresh_rotates_and_dies_with_session() {
973 let (store, client_id, user_id) = fixture().await;
974 let session = create_session(&store, &user_id, &SessionMeta::default())
975 .await
976 .unwrap();
977 let token = issue_refresh(&store, &user_id, &client_id, &session.hash())
978 .await
979 .unwrap();
980
981 let (fresh, old) = rotate_refresh(&store, token.expose())
982 .await
983 .unwrap()
984 .unwrap();
985 assert_eq!(old.user_id, user_id);
986 // The old token is spent.
987 assert!(
988 rotate_refresh(&store, token.expose())
989 .await
990 .unwrap()
991 .is_none()
992 );
993 // The fresh one works.
994 assert!(
995 rotate_refresh(&store, fresh.expose())
996 .await
997 .unwrap()
998 .is_some()
999 );
1000
1001 // Revoking the central session retires the refresh chain.
1002 let session2 = create_session(&store, &user_id, &SessionMeta::default())
1003 .await
1004 .unwrap();
1005 let token2 = issue_refresh(&store, &user_id, &client_id, &session2.hash())
1006 .await
1007 .unwrap();
1008 crate::sessions::revoke_session(&store, session2.expose())
1009 .await
1010 .unwrap();
1011 assert!(
1012 rotate_refresh(&store, token2.expose())
1013 .await
1014 .unwrap()
1015 .is_none()
1016 );
1017 }
1018
1019 #[tokio::test]
1020 async fn client_secret_verifies_constant_time() {
1021 let (store, client_id, _) = fixture().await;
1022 let client = client_by_id(&store, &client_id.to_string())
1023 .await
1024 .unwrap()
1025 .unwrap();
1026 assert!(!verify_client_secret(&client, "wrong"));
1027 assert!(
1028 client
1029 .redirect_uris
1030 .contains(&"http://app/callback".to_string())
1031 );
1032 }
1033
1034 #[tokio::test]
1035 async fn connected_apps_list_live_grants_newest_first() {
1036 let (store, client_id, user_id) = fixture().await;
1037 let (other_id, _secret) =
1038 create_client(&store, "other", vec!["http://other/callback".into()])
1039 .await
1040 .unwrap();
1041 let session = create_session(&store, &user_id, &SessionMeta::default())
1042 .await
1043 .unwrap();
1044
1045 // Two grants on the first client, one on the second; the second
1046 // client connected last and leads.
1047 issue_app_session(&store, &user_id, &client_id, &session.hash())
1048 .await
1049 .unwrap();
1050 issue_app_session(&store, &user_id, &client_id, &session.hash())
1051 .await
1052 .unwrap();
1053 issue_app_session(&store, &user_id, &other_id, &session.hash())
1054 .await
1055 .unwrap();
1056 let apps = list_connected_apps(&store, &user_id).await.unwrap();
1057 assert_eq!(apps.len(), 2);
1058 assert_eq!(apps[0].client_id, other_id.as_str());
1059 assert_eq!(apps[0].name, "other");
1060 assert_eq!(apps[0].count, 1);
1061 // The first client aggregates its two grants under its registered
1062 // display name.
1063 assert_eq!(apps[1].client_id, client_id.as_str());
1064 assert_eq!(apps[1].name, "demo");
1065 assert_eq!(apps[1].count, 2);
1066 assert!(apps[1].first_at <= apps[1].last_at);
1067
1068 // Backdate the second client's grant an hour: it connected last no
1069 // more, and the order follows the stamps, not the inserts.
1070 let conn = store.conn.lock().await;
1071 conn.execute(
1072 "UPDATE app_sessions SET created_at = ?1 WHERE client_id = ?2",
1073 turso::params![
1074 store::stamp(store::now() - time::Duration::hours(1)).unwrap(),
1075 other_id.as_str(),
1076 ],
1077 )
1078 .await
1079 .unwrap();
1080 drop(conn);
1081 let apps = list_connected_apps(&store, &user_id).await.unwrap();
1082 assert_eq!(apps[0].client_id, client_id.as_str());
1083 assert_eq!(apps[1].client_id, other_id.as_str());
1084 assert_eq!(apps[1].first_at, apps[1].last_at);
1085
1086 // Another person's grants never show up in someone else's list.
1087 let invite = create_invite(&store, "bob@example.com", None, false)
1088 .await
1089 .unwrap();
1090 let bob = create_user_from_invite(&store, invite.expose(), "Bob", "tDLr9!mZQ2xvQ")
1091 .await
1092 .unwrap();
1093 let bobs_session = create_session(&store, &bob.id, &SessionMeta::default())
1094 .await
1095 .unwrap();
1096 issue_app_session(&store, &bob.id, &other_id, &bobs_session.hash())
1097 .await
1098 .unwrap();
1099 let bobs_apps = list_connected_apps(&store, &bob.id).await.unwrap();
1100 assert_eq!(bobs_apps.len(), 1);
1101 assert_eq!(bobs_apps[0].client_id, other_id.as_str());
1102 assert_eq!(bobs_apps[0].count, 1);
1103 }
1104
1105 #[tokio::test]
1106 async fn connected_apps_skip_revoked_grants_and_fall_back_to_raw_ids() {
1107 let (store, client_id, user_id) = fixture().await;
1108 let session = create_session(&store, &user_id, &SessionMeta::default())
1109 .await
1110 .unwrap();
1111
1112 // Two grants on the client; then one of them is revoked.
1113 let revocable = issue_app_session(&store, &user_id, &client_id, &session.hash())
1114 .await
1115 .unwrap();
1116 issue_app_session(&store, &user_id, &client_id, &session.hash())
1117 .await
1118 .unwrap();
1119 let conn = store.conn.lock().await;
1120 conn.execute(
1121 "UPDATE app_sessions SET revoked_at = ?1 WHERE token_hash = ?2",
1122 turso::params![
1123 store::stamp(store::now()).unwrap(),
1124 hash_token(revocable.expose()),
1125 ],
1126 )
1127 .await
1128 .unwrap();
1129 drop(conn);
1130 let apps = list_connected_apps(&store, &user_id).await.unwrap();
1131 assert_eq!(apps.len(), 1);
1132 assert_eq!(apps[0].client_id, client_id.as_str());
1133 assert_eq!(apps[0].count, 1);
1134
1135 // A grant whose client row never existed shows the raw client_id
1136 // as its name.
1137 let conn = store.conn.lock().await;
1138 conn.execute(
1139 "INSERT INTO app_sessions \
1140 (token_hash, user_id, client_id, session_hash, created_at, expires_at) \
1141 VALUES ('ghost-hash', ?1, 'ghost-app', ?2, ?3, ?4)",
1142 turso::params![
1143 user_id.to_string(),
1144 session.hash(),
1145 store::stamp(store::now()).unwrap(),
1146 store::stamp(store::now() + time::Duration::days(30)).unwrap(),
1147 ],
1148 )
1149 .await
1150 .unwrap();
1151 drop(conn);
1152 let apps = list_connected_apps(&store, &user_id).await.unwrap();
1153 assert_eq!(apps.len(), 2);
1154 let ghost = apps
1155 .iter()
1156 .find(|app| app.client_id == "ghost-app")
1157 .unwrap();
1158 assert_eq!(ghost.name, "ghost-app");
1159 assert_eq!(ghost.count, 1);
1160
1161 // And an expired grant is not a connected app either.
1162 let conn = store.conn.lock().await;
1163 conn.execute(
1164 "UPDATE app_sessions SET expires_at = ?1 WHERE client_id = 'ghost-app'",
1165 turso::params![store::stamp(store::now() - time::Duration::days(1)).unwrap()],
1166 )
1167 .await
1168 .unwrap();
1169 drop(conn);
1170 let apps = list_connected_apps(&store, &user_id).await.unwrap();
1171 assert_eq!(apps.len(), 1);
1172 assert_eq!(apps[0].client_id, client_id.as_str());
1173 }
1174
1175 #[tokio::test]
1176 async fn rotate_client_secret_kills_the_old_pair() {
1177 let store = Store::open(Path::new(":memory:")).await.unwrap();
1178 let (client_id, original_secret) =
1179 create_client(&store, "drive", vec!["http://app/cb".into()])
1180 .await
1181 .unwrap();
1182
1183 // Rotation replaces the digest: the new secret verifies, the old
1184 // one stops, and the unknown id stays a None.
1185 let rotated = rotate_client_secret(&store, client_id.as_str())
1186 .await
1187 .unwrap()
1188 .expect("a known client rotates");
1189 let row = client_by_id(&store, client_id.as_str())
1190 .await
1191 .unwrap()
1192 .unwrap();
1193 assert!(verify_client_secret(&row, rotated.expose()));
1194 assert!(!verify_client_secret(&row, original_secret.expose()));
1195 assert!(
1196 rotate_client_secret(&store, "no-such-client")
1197 .await
1198 .unwrap()
1199 .is_none()
1200 );
1201 }
1202
1203 #[tokio::test]
1204 async fn revoke_client_deletes_its_tokens_in_one_sweep() {
1205 let (store, client_id, user_id) = fixture().await;
1206 let session = create_session(&store, &user_id, &SessionMeta::default())
1207 .await
1208 .unwrap();
1209 let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash())
1210 .await
1211 .unwrap();
1212 let refresh = issue_refresh(&store, &user_id, &client_id, &session.hash())
1213 .await
1214 .unwrap();
1215
1216 // Alive until revoked: introspection answers.
1217 assert!(
1218 introspect_app_session(&store, app_token.expose(), client_id.as_str())
1219 .await
1220 .unwrap()
1221 .is_some()
1222 );
1223
1224 assert!(revoke_client(&store, client_id.as_str()).await.unwrap());
1225
1226 // The pair is gone, and with it every token minted under it: the
1227 // app session no longer introspects, the refresh no longer turns.
1228 // The person's central session is untouched.
1229 assert!(
1230 introspect_app_session(&store, app_token.expose(), client_id.as_str())
1231 .await
1232 .unwrap()
1233 .is_none(),
1234 "no ghost app session after client revocation"
1235 );
1236 assert!(
1237 rotate_refresh(&store, refresh.expose())
1238 .await
1239 .unwrap()
1240 .is_none()
1241 );
1242 assert!(
1243 client_by_id(&store, client_id.as_str())
1244 .await
1245 .unwrap()
1246 .is_none(),
1247 "the registry row itself is gone"
1248 );
1249 assert_eq!(
1250 crate::sessions::list_sessions(&store, &user_id)
1251 .await
1252 .unwrap()
1253 .len(),
1254 1,
1255 "the person's own sign-in session stays"
1256 );
1257
1258 // Revoking again is a quiet false, not an error.
1259 assert!(!revoke_client(&store, client_id.as_str()).await.unwrap());
1260 }
1261
1262 #[tokio::test]
1263 async fn list_clients_returns_the_registry_rows() {
1264 let store = Store::open(Path::new(":memory:")).await.unwrap();
1265 let (first, _) = create_client(
1266 &store,
1267 "drive",
1268 vec!["http://a/cb".into(), "http://127.0.0.1:9000/cb".into()],
1269 )
1270 .await
1271 .unwrap();
1272 let (second, _) = create_client(&store, "in", vec!["https://in.dizey.sh/cb".into()])
1273 .await
1274 .unwrap();
1275 let rows = list_clients(&store).await.unwrap();
1276 assert_eq!(rows.len(), 2);
1277 assert_eq!(rows[0].client_id, first);
1278 assert_eq!(rows[0].name, "drive");
1279 assert_eq!(
1280 rows[0].redirect_uris,
1281 vec!["http://a/cb", "http://127.0.0.1:9000/cb"]
1282 );
1283 assert_eq!(rows[1].client_id, second);
1284 }
1285}