tests_store.rs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494
  1. //! `test(store)` suite: atomic Lua, tombstones, grant index, durability.
  2. //!
  3. //! Every test here spins its own single-node Redis 8 container with AOF
  4. //! enabled (mirroring `state::test_support`), so persistence, barriers, and
  5. //! concurrent compare-and-set run against a real server.
  6. use std::{
  7. sync::atomic::{AtomicU64, Ordering},
  8. time::Duration,
  9. };
  10. use testcontainers::{
  11. GenericImage, ImageExt,
  12. core::{IntoContainerPort, WaitFor},
  13. runners::AsyncRunner,
  14. };
  15. use super::{
  16. ErrorClass, OpClass, Store, StoreError, classify_redis, codes, dcr, device, durability_barrier,
  17. grants, hget_record, hset_record, may_retry_op, par, pending, ratelimit, retry_op, sessions,
  18. sha256_hex, tokens,
  19. };
  20. use crate::{
  21. config::{ConfigError, DurabilityMode, RedisConfig, TtlConfig, redis::RawRedisConfig},
  22. state::RedisConn,
  23. test_guard::ContainerGuard,
  24. };
  25. /// Test body result (no `unwrap`/`expect` under the deny lints).
  26. type TestResult = Result<(), TestError>;
  27. /// Errors raised by the store test scaffolding itself.
  28. #[derive(Debug, thiserror::Error)]
  29. enum TestError {
  30. /// A testcontainers operation failed.
  31. #[error("container error: {0}")]
  32. Containers(#[from] testcontainers::TestcontainersError),
  33. /// The Redis configuration was rejected.
  34. #[error("config error: {0}")]
  35. Config(#[from] ConfigError),
  36. /// A Redis command failed.
  37. #[error("redis error: {0}")]
  38. Redis(#[from] redis::RedisError),
  39. /// A store operation failed.
  40. #[error("store error: {0}")]
  41. Store(#[from] StoreError),
  42. /// A spawned task failed to join.
  43. #[error("task join failed")]
  44. Join,
  45. /// A test assertion observed an unexpected value.
  46. #[error("unexpected test value: {0}")]
  47. Unexpected(String),
  48. }
  49. static TEST_NONCE: AtomicU64 = AtomicU64::new(10_000);
  50. fn unique(label: &str) -> String {
  51. let n = TEST_NONCE.fetch_add(1, Ordering::Relaxed);
  52. format!("store-test-{n}-{label}")
  53. }
  54. /// Start a single-node Redis with AOF on plus extra server flags.
  55. ///
  56. /// The guard removes the container synchronously when the test drops it.
  57. async fn redis_container(extra: Vec<&str>) -> Result<(ContainerGuard, String), TestError> {
  58. let mut args = vec!["redis-server", "--appendonly", "yes"];
  59. args.extend(extra);
  60. let container = GenericImage::new("redis", "8-alpine")
  61. .with_exposed_port(6379.tcp())
  62. .with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))
  63. .with_cmd(args)
  64. .start()
  65. .await?;
  66. let guarded = ContainerGuard::new(container);
  67. let port = guarded.get_host_port_ipv4(6379).await?;
  68. Ok((guarded, format!("redis://127.0.0.1:{port}")))
  69. }
  70. /// Connect a [`RedisConn`] plus [`Store`] directly (startup assertions live in
  71. /// task 4; here the store contract is what is under test).
  72. ///
  73. /// Timeouts are generous on purpose: the blocking `WAITAOF` barrier may wait
  74. /// out a full `everysec` fsync cycle, so the client response timeout must sit
  75. /// well above the server-side barrier wait.
  76. async fn direct_store(
  77. url: &str,
  78. durability: DurabilityMode,
  79. ) -> Result<(RedisConn, Store), TestError> {
  80. let client = redis::Client::open(url)?;
  81. let manager_config = redis::aio::ConnectionManagerConfig::new()
  82. .set_response_timeout(Some(Duration::from_secs(10)))
  83. .set_connection_timeout(Some(Duration::from_secs(5)));
  84. let manager = redis::aio::ConnectionManager::new_with_config(client, manager_config).await?;
  85. let raw = RawRedisConfig {
  86. url: Some(url.to_owned()),
  87. durability: Some(durability),
  88. response_timeout_secs: 10,
  89. connect_timeout_secs: 5,
  90. ..Default::default()
  91. };
  92. let config = RedisConfig::from_raw(raw)?;
  93. Ok((RedisConn::Single(manager), Store::from_config(&config)))
  94. }
  95. fn code_record(client: &str, grant: &str) -> codes::CodeRecord {
  96. codes::CodeRecord {
  97. client_id: client.to_owned(),
  98. redirect_uri: "https://client.example.test/cb".to_owned(),
  99. scope: "orders:read".to_owned(),
  100. code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_owned(),
  101. subject: "user-1".to_owned(),
  102. grant_id: grant.to_owned(),
  103. cnf: String::new(),
  104. }
  105. }
  106. fn refresh_record(client: &str, grant: &str) -> tokens::RefreshRecord {
  107. tokens::RefreshRecord {
  108. client_id: client.to_owned(),
  109. grant_id: grant.to_owned(),
  110. scope: "orders:read".to_owned(),
  111. subject: "user-1".to_owned(),
  112. cnf: String::new(),
  113. }
  114. }
  115. fn access_record(client: &str, grant: &str) -> tokens::AccessRecord {
  116. tokens::AccessRecord {
  117. client_id: client.to_owned(),
  118. grant_id: grant.to_owned(),
  119. scope: "orders:read".to_owned(),
  120. subject: "user-1".to_owned(),
  121. cnf: String::new(),
  122. }
  123. }
  124. fn rotation_input(
  125. old: &str,
  126. client: &str,
  127. new_refresh: &str,
  128. new_access: &str,
  129. grant: &str,
  130. request_id: Option<String>,
  131. ) -> tokens::RotationInput {
  132. tokens::RotationInput {
  133. old_refresh_hash: old.to_owned(),
  134. expected_client_id: client.to_owned(),
  135. new_refresh_hash: new_refresh.to_owned(),
  136. new_access_hash: new_access.to_owned(),
  137. new_refresh: refresh_record(client, grant),
  138. new_access: access_record(client, grant),
  139. new_refresh_ttl: Duration::from_secs(3600),
  140. new_access_ttl: Duration::from_secs(300),
  141. request_id,
  142. }
  143. }
  144. /// Remaining TTL of a key in milliseconds (`-1` persistent, `-2` absent).
  145. async fn pttl_ms(conn: &mut RedisConn, key: &str) -> Result<i64, TestError> {
  146. let pttl: i64 = redis::cmd("PTTL").arg(key).query_async(conn).await?;
  147. Ok(pttl)
  148. }
  149. /// Assert a key carries a live TTL inside the design window `(0, cap]`.
  150. ///
  151. /// `cap` comes from the configured/design lifetime, never from the observed
  152. /// value. A non-positive TTL means the key is persistent or absent (a defect:
  153. /// the artifact would outlive its intended window); the upper bound can only
  154. /// drift downward while the test runs, so a slow run cannot flake it.
  155. fn assert_ttl_within(pttl: i64, cap: Duration) -> TestResult {
  156. if pttl <= 0 || pttl > cap.as_millis() as i64 {
  157. return Err(TestError::Unexpected(format!(
  158. "PTTL {pttl} ms must be within (0, {} ms]",
  159. cap.as_millis()
  160. )));
  161. }
  162. Ok(())
  163. }
  164. #[tokio::test]
  165. async fn store_code_consume_exactly_once() -> TestResult {
  166. let (_container, url) = redis_container(Vec::new()).await?;
  167. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  168. let hash = unique("code");
  169. let grant = unique("grant");
  170. let client = unique("client");
  171. codes::issue(
  172. &mut conn,
  173. &store,
  174. &hash,
  175. &code_record(&client, &grant),
  176. Duration::from_secs(60),
  177. )
  178. .await?;
  179. let first = codes::consume(&mut conn, &store, &hash).await?;
  180. let second = codes::consume(&mut conn, &store, &hash).await?;
  181. if first
  182. .as_ref()
  183. .is_none_or(|record| record.client_id != client)
  184. {
  185. return Err(TestError::Unexpected(
  186. "first consume must return the record".to_owned(),
  187. ));
  188. }
  189. if second.is_some() {
  190. return Err(TestError::Unexpected(
  191. "second consume must return None".to_owned(),
  192. ));
  193. }
  194. Ok(())
  195. }
  196. #[tokio::test]
  197. async fn store_refresh_rotate_idempotent_replay() -> TestResult {
  198. let (_container, url) = redis_container(Vec::new()).await?;
  199. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  200. let grant = unique("grant");
  201. let client = unique("client");
  202. let old = unique("old-refresh");
  203. let new_refresh = unique("new-refresh");
  204. let new_access = unique("new-access");
  205. let pepper = b"store-test-pepper";
  206. grants::create(
  207. &mut conn,
  208. &store,
  209. &grants::GrantRecord {
  210. grant_id: grant.clone(),
  211. client_id: client.clone(),
  212. subject: "user-1".to_owned(),
  213. scope: "orders:read".to_owned(),
  214. },
  215. Duration::from_secs(3600),
  216. )
  217. .await?;
  218. tokens::put_refresh(
  219. &mut conn,
  220. &store,
  221. &old,
  222. &refresh_record(&client, &grant),
  223. Duration::from_secs(3600),
  224. )
  225. .await?;
  226. // Same old token presented twice (deterministic request id): the SAME new
  227. // tokens come back, never a double rotation.
  228. let first = tokens::rotate(
  229. &mut conn,
  230. &store,
  231. pepper,
  232. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  233. )
  234. .await?;
  235. let second = tokens::rotate(
  236. &mut conn,
  237. &store,
  238. pepper,
  239. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  240. )
  241. .await?;
  242. match (first, second) {
  243. (
  244. tokens::RotateOutcome::Rotated {
  245. new_refresh_hash: first_r,
  246. new_access_hash: first_a,
  247. },
  248. tokens::RotateOutcome::Replay {
  249. new_refresh_hash: second_r,
  250. new_access_hash: second_a,
  251. },
  252. ) if first_r == new_refresh
  253. && first_a == new_access
  254. && second_r == new_refresh
  255. && second_a == new_access =>
  256. {
  257. Ok(())
  258. }
  259. _ => Err(TestError::Unexpected(
  260. "expected Rotated then Replay with identical tokens".to_owned(),
  261. )),
  262. }
  263. }
  264. #[tokio::test]
  265. async fn store_refresh_concurrent_cas_one_rotated_one_reuse() -> TestResult {
  266. let (_container, url) = redis_container(Vec::new()).await?;
  267. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  268. let grant = unique("grant");
  269. let client = unique("client");
  270. let old = unique("old-refresh");
  271. let pepper = b"store-test-pepper";
  272. grants::create(
  273. &mut conn,
  274. &store,
  275. &grants::GrantRecord {
  276. grant_id: grant.clone(),
  277. client_id: client.clone(),
  278. subject: "user-1".to_owned(),
  279. scope: "orders:read".to_owned(),
  280. },
  281. Duration::from_secs(3600),
  282. )
  283. .await?;
  284. tokens::put_refresh(
  285. &mut conn,
  286. &store,
  287. &old,
  288. &refresh_record(&client, &grant),
  289. Duration::from_secs(3600),
  290. )
  291. .await?;
  292. // Two concurrent rotations with DISTINCT request ids (two spend attempts):
  293. // exactly one rotates, the other observes reuse.
  294. let first_tag = unique("race-refresh");
  295. let second_tag = unique("race-refresh");
  296. let first = tokio::spawn({
  297. let conn = conn.clone();
  298. let store = store.clone();
  299. let grant = grant.clone();
  300. let client = client.clone();
  301. let old = old.clone();
  302. async move {
  303. let mut conn = conn;
  304. let input = rotation_input(
  305. &old,
  306. &client,
  307. &first_tag,
  308. &format!("{first_tag}-access"),
  309. &grant,
  310. Some("req-1".to_owned()),
  311. );
  312. tokens::rotate(&mut conn, &store, pepper, &input).await
  313. }
  314. });
  315. let second = tokio::spawn({
  316. let conn = conn.clone();
  317. let store = store.clone();
  318. async move {
  319. let mut conn = conn;
  320. let input = rotation_input(
  321. &old,
  322. &client,
  323. &second_tag,
  324. &format!("{second_tag}-access"),
  325. &grant,
  326. Some("req-2".to_owned()),
  327. );
  328. tokens::rotate(&mut conn, &store, pepper, &input).await
  329. }
  330. });
  331. let first = first.await.map_err(|_| TestError::Join)??;
  332. let second = second.await.map_err(|_| TestError::Join)??;
  333. let rotated = u8::from(matches!(first, tokens::RotateOutcome::Rotated { .. }))
  334. + u8::from(matches!(second, tokens::RotateOutcome::Rotated { .. }));
  335. let reused = u8::from(matches!(first, tokens::RotateOutcome::Reused { .. }))
  336. + u8::from(matches!(second, tokens::RotateOutcome::Reused { .. }));
  337. if rotated == 1 && reused == 1 {
  338. Ok(())
  339. } else {
  340. Err(TestError::Unexpected(
  341. "expected exactly one Rotated and one Reused".to_owned(),
  342. ))
  343. }
  344. }
  345. #[tokio::test]
  346. async fn store_refresh_reuse_without_mapping_cascades() -> TestResult {
  347. let (_container, url) = redis_container(Vec::new()).await?;
  348. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  349. let grant = unique("grant");
  350. let client = unique("client");
  351. let old = unique("old-refresh");
  352. let new_refresh = unique("new-refresh");
  353. let new_access = unique("new-access");
  354. let pepper = b"store-test-pepper";
  355. grants::create(
  356. &mut conn,
  357. &store,
  358. &grants::GrantRecord {
  359. grant_id: grant.clone(),
  360. client_id: client.clone(),
  361. subject: "user-1".to_owned(),
  362. scope: "orders:read".to_owned(),
  363. },
  364. Duration::from_secs(3600),
  365. )
  366. .await?;
  367. tokens::put_refresh(
  368. &mut conn,
  369. &store,
  370. &old,
  371. &refresh_record(&client, &grant),
  372. Duration::from_secs(3600),
  373. )
  374. .await?;
  375. let first = tokens::rotate(
  376. &mut conn,
  377. &store,
  378. pepper,
  379. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  380. )
  381. .await?;
  382. if !matches!(first, tokens::RotateOutcome::Rotated { .. }) {
  383. return Err(TestError::Unexpected(
  384. "first rotation must apply".to_owned(),
  385. ));
  386. }
  387. // Expire the grace mapping (grace window elapsed), then replay the old
  388. // token: reuse, and the whole family dies.
  389. let request_id = tokens::derive_rotation_id(pepper, &old)?;
  390. let map_key = store.rotation_map_key(&request_id);
  391. let _: () = redis::cmd("DEL")
  392. .arg(&map_key)
  393. .query_async(&mut conn)
  394. .await?;
  395. let replay = tokens::rotate(
  396. &mut conn,
  397. &store,
  398. pepper,
  399. &rotation_input(
  400. &old,
  401. &client,
  402. &unique("other"),
  403. &unique("other-a"),
  404. &grant,
  405. None,
  406. ),
  407. )
  408. .await?;
  409. match replay {
  410. tokens::RotateOutcome::Reused { rotated_to } if rotated_to == new_refresh => {}
  411. _ => {
  412. return Err(TestError::Unexpected(
  413. "expected Reused pointing at the rotated token".to_owned(),
  414. ));
  415. }
  416. }
  417. if tokens::get_refresh(&mut conn, &store, &new_refresh)
  418. .await?
  419. .is_some()
  420. {
  421. return Err(TestError::Unexpected(
  422. "cascade must delete the rotated refresh token".to_owned(),
  423. ));
  424. }
  425. if tokens::get_access(&mut conn, &store, &new_access)
  426. .await?
  427. .is_some()
  428. {
  429. return Err(TestError::Unexpected(
  430. "cascade must delete the rotated access token".to_owned(),
  431. ));
  432. }
  433. if grants::get(&mut conn, &store, &grant).await?.is_some() {
  434. return Err(TestError::Unexpected(
  435. "cascade must delete the grant record".to_owned(),
  436. ));
  437. }
  438. if !grants::members(&mut conn, &store, &grant).await?.is_empty() {
  439. return Err(TestError::Unexpected(
  440. "cascade must empty the grant set".to_owned(),
  441. ));
  442. }
  443. Ok(())
  444. }
  445. #[tokio::test]
  446. async fn store_grant_revoke_cascade() -> TestResult {
  447. let (_container, url) = redis_container(Vec::new()).await?;
  448. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  449. let grant = unique("grant");
  450. let client = unique("client");
  451. let refresh = unique("refresh");
  452. let access = unique("access");
  453. grants::create(
  454. &mut conn,
  455. &store,
  456. &grants::GrantRecord {
  457. grant_id: grant.clone(),
  458. client_id: client.clone(),
  459. subject: "user-1".to_owned(),
  460. scope: "orders:read".to_owned(),
  461. },
  462. Duration::from_secs(3600),
  463. )
  464. .await?;
  465. tokens::put_refresh(
  466. &mut conn,
  467. &store,
  468. &refresh,
  469. &refresh_record(&client, &grant),
  470. Duration::from_secs(3600),
  471. )
  472. .await?;
  473. tokens::put_access(
  474. &mut conn,
  475. &store,
  476. &access,
  477. &access_record(&client, &grant),
  478. Duration::from_secs(300),
  479. )
  480. .await?;
  481. if grants::members(&mut conn, &store, &grant).await?.len() != 2 {
  482. return Err(TestError::Unexpected(
  483. "grant set must index both tokens".to_owned(),
  484. ));
  485. }
  486. let deleted = grants::revoke(&mut conn, &store, &grant).await?;
  487. if deleted < 2 {
  488. return Err(TestError::Unexpected(
  489. "revoke must delete both token keys".to_owned(),
  490. ));
  491. }
  492. if tokens::get_refresh(&mut conn, &store, &refresh)
  493. .await?
  494. .is_some()
  495. || tokens::get_access(&mut conn, &store, &access)
  496. .await?
  497. .is_some()
  498. {
  499. return Err(TestError::Unexpected(
  500. "revoke must delete member records".to_owned(),
  501. ));
  502. }
  503. // Unknown grants revoke to zero (idempotent).
  504. if grants::revoke(&mut conn, &store, &unique("no-such-grant")).await? != 0 {
  505. return Err(TestError::Unexpected(
  506. "unknown grant must revoke to zero".to_owned(),
  507. ));
  508. }
  509. Ok(())
  510. }
  511. #[tokio::test]
  512. async fn store_tombstone_detectable_after_rotation() -> TestResult {
  513. let (_container, url) = redis_container(Vec::new()).await?;
  514. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  515. let grant = unique("grant");
  516. let client = unique("client");
  517. let old = unique("old-refresh");
  518. let new_refresh = unique("new-refresh");
  519. let new_access = unique("new-access");
  520. let pepper = b"store-test-pepper";
  521. grants::create(
  522. &mut conn,
  523. &store,
  524. &grants::GrantRecord {
  525. grant_id: grant.clone(),
  526. client_id: client.clone(),
  527. subject: "user-1".to_owned(),
  528. scope: "orders:read".to_owned(),
  529. },
  530. Duration::from_secs(3600),
  531. )
  532. .await?;
  533. tokens::put_refresh(
  534. &mut conn,
  535. &store,
  536. &old,
  537. &refresh_record(&client, &grant),
  538. Duration::from_secs(3600),
  539. )
  540. .await?;
  541. // Live token: no tombstone; unknown hash: no tombstone.
  542. if tokens::tombstone_of(&mut conn, &store, &old)
  543. .await?
  544. .is_some()
  545. {
  546. return Err(TestError::Unexpected(
  547. "live token must not look tombstoned".to_owned(),
  548. ));
  549. }
  550. if tokens::tombstone_of(&mut conn, &store, &unique("absent"))
  551. .await?
  552. .is_some()
  553. {
  554. return Err(TestError::Unexpected(
  555. "absent token must not look tombstoned".to_owned(),
  556. ));
  557. }
  558. let outcome = tokens::rotate(
  559. &mut conn,
  560. &store,
  561. pepper,
  562. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  563. )
  564. .await?;
  565. if !matches!(outcome, tokens::RotateOutcome::Rotated { .. }) {
  566. return Err(TestError::Unexpected("rotation must apply".to_owned()));
  567. }
  568. match tokens::tombstone_of(&mut conn, &store, &old).await? {
  569. Some(rotated_to) if rotated_to == new_refresh => Ok(()),
  570. _ => Err(TestError::Unexpected(
  571. "tombstone must point at the new token".to_owned(),
  572. )),
  573. }
  574. }
  575. #[tokio::test]
  576. async fn store_persistence_survives_restart() -> TestResult {
  577. let (container, url) = redis_container(vec!["--appendfsync", "always"]).await?;
  578. let grant = unique("grant");
  579. let client = unique("client");
  580. let code_hash = unique("code");
  581. let refresh_hash = unique("refresh");
  582. let jti = unique("jti");
  583. {
  584. let (mut conn, store) = direct_store(&url, DurabilityMode::AppendFsyncAlways).await?;
  585. codes::issue(
  586. &mut conn,
  587. &store,
  588. &code_hash,
  589. &code_record(&client, &grant),
  590. Duration::from_secs(600),
  591. )
  592. .await?;
  593. tokens::put_refresh(
  594. &mut conn,
  595. &store,
  596. &refresh_hash,
  597. &refresh_record(&client, &grant),
  598. Duration::from_secs(3600),
  599. )
  600. .await?;
  601. if !dcr::claim_dpop_jti(&mut conn, &store, &jti, Duration::from_secs(600)).await? {
  602. return Err(TestError::Unexpected("marker claim must win".to_owned()));
  603. }
  604. }
  605. container.stop_with_timeout(Some(10)).await?;
  606. container.start().await?;
  607. let port = container.get_host_port_ipv4(6379).await?;
  608. let (mut conn, store) = direct_store(
  609. &format!("redis://127.0.0.1:{port}"),
  610. DurabilityMode::AppendFsyncAlways,
  611. )
  612. .await?;
  613. let code = codes::consume(&mut conn, &store, &code_hash).await?;
  614. if code
  615. .as_ref()
  616. .is_none_or(|record| record.client_id != client)
  617. {
  618. return Err(TestError::Unexpected(
  619. "code must survive the restart".to_owned(),
  620. ));
  621. }
  622. let refresh = tokens::get_refresh(&mut conn, &store, &refresh_hash).await?;
  623. if refresh
  624. .as_ref()
  625. .is_none_or(|record| record.grant_id != grant)
  626. {
  627. return Err(TestError::Unexpected(
  628. "refresh record must survive the restart".to_owned(),
  629. ));
  630. }
  631. if dcr::claim_dpop_jti(&mut conn, &store, &jti, Duration::from_secs(600)).await? {
  632. return Err(TestError::Unexpected(
  633. "replay marker must survive the restart".to_owned(),
  634. ));
  635. }
  636. Ok(())
  637. }
  638. #[tokio::test]
  639. async fn store_durability_barrier_modes() -> TestResult {
  640. let (_container, url) = redis_container(Vec::new()).await?;
  641. // Single-node: WAITAOF barrier succeeds after a write.
  642. let (mut conn, waitaof) = direct_store(&url, DurabilityMode::WaitAof).await?;
  643. durability_barrier(&mut conn, &waitaof).await?;
  644. // `WAIT 1` on a replica-less node acknowledges zero: fail closed.
  645. let wait = Store::from_parts(
  646. "oauth:{state}:".to_owned(),
  647. "oauth:{rl}:".to_owned(),
  648. DurabilityMode::Wait,
  649. );
  650. if durability_barrier(&mut conn, &wait).await.is_ok() {
  651. return Err(TestError::Unexpected(
  652. "WAIT without replicas must fail closed".to_owned(),
  653. ));
  654. }
  655. // `appendfsync always` assertion fails on an everysec node: fail closed.
  656. let always = Store::from_parts(
  657. "oauth:{state}:".to_owned(),
  658. "oauth:{rl}:".to_owned(),
  659. DurabilityMode::AppendFsyncAlways,
  660. );
  661. if durability_barrier(&mut conn, &always).await.is_ok() {
  662. return Err(TestError::Unexpected(
  663. "everysec node must fail the always barrier".to_owned(),
  664. ));
  665. }
  666. // ...and succeeds where the server actually fsyncs always.
  667. let (_always_container, always_url) = redis_container(vec!["--appendfsync", "always"]).await?;
  668. let (mut always_conn, _) = direct_store(&always_url, DurabilityMode::AppendFsyncAlways).await?;
  669. durability_barrier(&mut always_conn, &always).await?;
  670. Ok(())
  671. }
  672. #[tokio::test]
  673. async fn store_ratelimit_fixed_window() -> TestResult {
  674. let (_container, url) = redis_container(Vec::new()).await?;
  675. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  676. let bucket = unique("bucket");
  677. let window = Duration::from_secs(60);
  678. for _ in 0..3 {
  679. let decision = ratelimit::check_and_incr(&mut conn, &store, &bucket, window, 3).await?;
  680. if !decision.allowed {
  681. return Err(TestError::Unexpected(
  682. "first three hits must be allowed".to_owned(),
  683. ));
  684. }
  685. }
  686. let limited = ratelimit::check_and_incr(&mut conn, &store, &bucket, window, 3).await?;
  687. if limited.allowed || limited.count != 4 || limited.retry_after_secs == 0 {
  688. return Err(TestError::Unexpected(
  689. "fourth hit must be limited with Retry-After".to_owned(),
  690. ));
  691. }
  692. // Buckets are hashed under the `{rl}` keyspace, never raw labels.
  693. let key = store.ratelimit_key(&ratelimit::hash_bucket(&bucket));
  694. if !key.contains("{rl}") || key.contains(&bucket) {
  695. return Err(TestError::Unexpected(
  696. "counter key must be hashed and {rl}-tagged".to_owned(),
  697. ));
  698. }
  699. if ratelimit::hash_bucket(&bucket) != ratelimit::hash_bucket(&bucket) {
  700. return Err(TestError::Unexpected(
  701. "bucket hashing must be deterministic".to_owned(),
  702. ));
  703. }
  704. Ok(())
  705. }
  706. #[tokio::test]
  707. async fn store_replay_markers_first_claim_wins() -> TestResult {
  708. let (_container, url) = redis_container(Vec::new()).await?;
  709. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  710. let jti = unique("jti");
  711. let assertion = unique("assertion");
  712. if !dcr::claim_dpop_jti(&mut conn, &store, &jti, Duration::from_secs(300)).await? {
  713. return Err(TestError::Unexpected(
  714. "first DPoP claim must win".to_owned(),
  715. ));
  716. }
  717. if dcr::claim_dpop_jti(&mut conn, &store, &jti, Duration::from_secs(300)).await? {
  718. return Err(TestError::Unexpected(
  719. "second DPoP claim must lose".to_owned(),
  720. ));
  721. }
  722. if !dcr::claim_client_assertion_jti(&mut conn, &store, &assertion, Duration::from_secs(300))
  723. .await?
  724. {
  725. return Err(TestError::Unexpected(
  726. "first assertion claim must win".to_owned(),
  727. ));
  728. }
  729. if dcr::claim_client_assertion_jti(&mut conn, &store, &assertion, Duration::from_secs(300))
  730. .await?
  731. {
  732. return Err(TestError::Unexpected(
  733. "second assertion claim must lose".to_owned(),
  734. ));
  735. }
  736. Ok(())
  737. }
  738. #[tokio::test]
  739. async fn store_sessions_and_login_counters() -> TestResult {
  740. let (_container, url) = redis_container(Vec::new()).await?;
  741. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  742. let old_session = unique("session");
  743. let new_session = unique("session");
  744. let record = sessions::SessionRecord {
  745. subject: "user-1".to_owned(),
  746. mfa_verified: true,
  747. restricted: false,
  748. };
  749. sessions::put(
  750. &mut conn,
  751. &store,
  752. &old_session,
  753. &record,
  754. Duration::from_secs(3600),
  755. )
  756. .await?;
  757. sessions::rotate(
  758. &mut conn,
  759. &store,
  760. &old_session,
  761. &new_session,
  762. &record,
  763. Duration::from_secs(3600),
  764. )
  765. .await?;
  766. if sessions::get(&mut conn, &store, &old_session)
  767. .await?
  768. .is_some()
  769. {
  770. return Err(TestError::Unexpected(
  771. "old session must be gone after rotate".to_owned(),
  772. ));
  773. }
  774. let current = sessions::get(&mut conn, &store, &new_session).await?;
  775. if current.as_ref().is_none_or(|session| !session.mfa_verified) {
  776. return Err(TestError::Unexpected(
  777. "new session must verify MFA".to_owned(),
  778. ));
  779. }
  780. sessions::destroy(&mut conn, &store, &new_session).await?;
  781. if sessions::get(&mut conn, &store, &new_session)
  782. .await?
  783. .is_some()
  784. {
  785. return Err(TestError::Unexpected(
  786. "destroyed session must be gone".to_owned(),
  787. ));
  788. }
  789. let account = unique("alice@example.test");
  790. let first =
  791. sessions::record_failed_login(&mut conn, &store, &account, Duration::from_secs(300)).await?;
  792. let second =
  793. sessions::record_failed_login(&mut conn, &store, &account, Duration::from_secs(300)).await?;
  794. if (first, second) != (1, 2) {
  795. return Err(TestError::Unexpected(
  796. "failed-login counter must increment".to_owned(),
  797. ));
  798. }
  799. if sessions::failed_login_count(&mut conn, &store, &account).await? != 2 {
  800. return Err(TestError::Unexpected(
  801. "failed-login count must read back".to_owned(),
  802. ));
  803. }
  804. sessions::clear_failed_logins(&mut conn, &store, &account).await?;
  805. if sessions::failed_login_count(&mut conn, &store, &account).await? != 0 {
  806. return Err(TestError::Unexpected(
  807. "cleared counter must read zero".to_owned(),
  808. ));
  809. }
  810. Ok(())
  811. }
  812. #[tokio::test]
  813. async fn store_device_par_and_dcr_round_trip() -> TestResult {
  814. let (_container, url) = redis_container(Vec::new()).await?;
  815. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  816. let client = unique("client");
  817. // Device flow: put, poll, approve, consume exactly once.
  818. let device_hash = unique("device");
  819. let user_code = unique("user-code");
  820. device::put(
  821. &mut conn,
  822. &store,
  823. &device_hash,
  824. &user_code,
  825. &device::DeviceRecord {
  826. client_id: client.clone(),
  827. scope: "orders:read".to_owned(),
  828. status: device::DeviceStatus::Pending,
  829. subject: String::new(),
  830. grant_id: String::new(),
  831. },
  832. Duration::from_secs(600),
  833. )
  834. .await?;
  835. if device::resolve_user_code(&mut conn, &store, &user_code)
  836. .await?
  837. .as_deref()
  838. != Some(device_hash.as_str())
  839. {
  840. return Err(TestError::Unexpected(
  841. "user code must resolve to the device".to_owned(),
  842. ));
  843. }
  844. let grant = unique("grant");
  845. if !device::decide(
  846. &mut conn,
  847. &store,
  848. &device_hash,
  849. device::DeviceStatus::Approved,
  850. "user-1",
  851. &grant,
  852. )
  853. .await?
  854. {
  855. return Err(TestError::Unexpected("approve must apply".to_owned()));
  856. }
  857. let approved = device::poll(&mut conn, &store, &device_hash).await?;
  858. if approved
  859. .as_ref()
  860. .is_none_or(|record| record.status != device::DeviceStatus::Approved)
  861. {
  862. return Err(TestError::Unexpected(
  863. "poll must observe approval".to_owned(),
  864. ));
  865. }
  866. if device::consume(&mut conn, &store, &device_hash)
  867. .await?
  868. .is_none()
  869. {
  870. return Err(TestError::Unexpected(
  871. "first device consume must return the record".to_owned(),
  872. ));
  873. }
  874. if device::consume(&mut conn, &store, &device_hash)
  875. .await?
  876. .is_some()
  877. {
  878. return Err(TestError::Unexpected(
  879. "second device consume must return None".to_owned(),
  880. ));
  881. }
  882. // PAR: put, consume exactly once.
  883. let request_id = unique("par");
  884. par::put(
  885. &mut conn,
  886. &store,
  887. &request_id,
  888. &par::ParRecord {
  889. client_id: client.clone(),
  890. request: "{\"response_type\":\"code\"}".to_owned(),
  891. },
  892. Duration::from_secs(90),
  893. )
  894. .await?;
  895. if par::consume(&mut conn, &store, &request_id)
  896. .await?
  897. .is_none()
  898. {
  899. return Err(TestError::Unexpected(
  900. "first PAR consume must return the record".to_owned(),
  901. ));
  902. }
  903. if par::consume(&mut conn, &store, &request_id)
  904. .await?
  905. .is_some()
  906. {
  907. return Err(TestError::Unexpected(
  908. "second PAR consume must return None".to_owned(),
  909. ));
  910. }
  911. // DCR initial-access token: two uses, then exhausted.
  912. let iat = unique("iat");
  913. dcr::issue(
  914. &mut conn,
  915. &store,
  916. &iat,
  917. &dcr::InitialAccessRecord {
  918. uses_remaining: 2,
  919. label: "ops-token".to_owned(),
  920. },
  921. Duration::from_secs(3600),
  922. )
  923. .await?;
  924. let first_use = dcr::consume_one_use(&mut conn, &store, &iat).await?;
  925. if first_use
  926. .as_ref()
  927. .is_none_or(|record| record.uses_remaining != 2)
  928. {
  929. return Err(TestError::Unexpected(
  930. "first use must report the pre-decrement budget".to_owned(),
  931. ));
  932. }
  933. if dcr::consume_one_use(&mut conn, &store, &iat)
  934. .await?
  935. .is_none()
  936. {
  937. return Err(TestError::Unexpected(
  938. "second (final) use must succeed".to_owned(),
  939. ));
  940. }
  941. if dcr::consume_one_use(&mut conn, &store, &iat)
  942. .await?
  943. .is_some()
  944. {
  945. return Err(TestError::Unexpected(
  946. "exhausted token must return None".to_owned(),
  947. ));
  948. }
  949. Ok(())
  950. }
  951. /// docs/REDIS.md: `oauth:{state}:code:<hash>` carries the authorization-code
  952. /// lifetime, capped at [`crate::protocol::code::CODE_TTL_CAP`] (60 s).
  953. #[tokio::test]
  954. async fn store_code_ttl_within_configured_window() -> TestResult {
  955. let (_container, url) = redis_container(Vec::new()).await?;
  956. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  957. let ttl = TtlConfig::default();
  958. let hash = unique("code");
  959. codes::issue(
  960. &mut conn,
  961. &store,
  962. &hash,
  963. &code_record(&unique("client"), &unique("grant")),
  964. ttl.code,
  965. )
  966. .await?;
  967. let cap = ttl.code.min(crate::protocol::code::CODE_TTL_CAP);
  968. assert_ttl_within(pttl_ms(&mut conn, &store.code_key(&hash)).await?, cap)
  969. }
  970. /// docs/REDIS.md: the PAR handle lives under `ttl.par` (90 s) and both the
  971. /// device-code record and its user-code mapping under `ttl.device` (600 s).
  972. #[tokio::test]
  973. async fn store_par_device_and_user_code_ttl_within_configured_windows() -> TestResult {
  974. let (_container, url) = redis_container(Vec::new()).await?;
  975. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  976. let ttl = TtlConfig::default();
  977. let client = unique("client");
  978. let request_id = unique("par");
  979. par::put(
  980. &mut conn,
  981. &store,
  982. &request_id,
  983. &par::ParRecord {
  984. client_id: client.clone(),
  985. request: "{\"response_type\":\"code\"}".to_owned(),
  986. },
  987. ttl.par,
  988. )
  989. .await?;
  990. assert_ttl_within(
  991. pttl_ms(&mut conn, &store.par_key(&request_id)).await?,
  992. ttl.par,
  993. )?;
  994. let device_hash = unique("device");
  995. let user_code = unique("user-code");
  996. device::put(
  997. &mut conn,
  998. &store,
  999. &device_hash,
  1000. &user_code,
  1001. &device::DeviceRecord {
  1002. client_id: client,
  1003. scope: "orders:read".to_owned(),
  1004. status: device::DeviceStatus::Pending,
  1005. subject: String::new(),
  1006. grant_id: String::new(),
  1007. },
  1008. ttl.device,
  1009. )
  1010. .await?;
  1011. assert_ttl_within(
  1012. pttl_ms(&mut conn, &store.device_key(&device_hash)).await?,
  1013. ttl.device,
  1014. )?;
  1015. assert_ttl_within(
  1016. pttl_ms(&mut conn, &store.user_code_key(&user_code)).await?,
  1017. ttl.device,
  1018. )
  1019. }
  1020. /// docs/REDIS.md: the DCR initial-access-token record lives under the CLI
  1021. /// `--ttl`, defaulting to the configured `ttl.dcr_initial_access` (24 h).
  1022. #[tokio::test]
  1023. async fn store_dcr_initial_access_ttl_within_configured_window() -> TestResult {
  1024. let (_container, url) = redis_container(Vec::new()).await?;
  1025. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1026. let ttl = TtlConfig::default();
  1027. let iat = unique("iat");
  1028. dcr::issue(
  1029. &mut conn,
  1030. &store,
  1031. &iat,
  1032. &dcr::InitialAccessRecord {
  1033. uses_remaining: 2,
  1034. label: "ops-token".to_owned(),
  1035. },
  1036. ttl.dcr_initial_access,
  1037. )
  1038. .await?;
  1039. assert_ttl_within(
  1040. pttl_ms(&mut conn, &store.dcr_iat_key(&iat)).await?,
  1041. ttl.dcr_initial_access,
  1042. )
  1043. }
  1044. /// docs/REDIS.md: the rotation idempotency mapping is bounded by
  1045. /// `min(900 s, refresh TTL)`, the old refresh record becomes a tombstone with
  1046. /// the refresh lifetime, and the per-grant token index lives with the grant.
  1047. #[tokio::test]
  1048. async fn store_rotation_grace_tombstone_and_grant_index_ttl() -> TestResult {
  1049. let (_container, url) = redis_container(Vec::new()).await?;
  1050. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1051. let grant = unique("grant");
  1052. let client = unique("client");
  1053. let old = unique("old-refresh");
  1054. let new_refresh = unique("new-refresh");
  1055. let new_access = unique("new-access");
  1056. let pepper = b"store-test-pepper";
  1057. let refresh_ttl = Duration::from_secs(3600);
  1058. let access_ttl = Duration::from_secs(300);
  1059. let rotation_grace = Duration::from_secs(900);
  1060. grants::create(
  1061. &mut conn,
  1062. &store,
  1063. &grants::GrantRecord {
  1064. grant_id: grant.clone(),
  1065. client_id: client.clone(),
  1066. subject: "user-1".to_owned(),
  1067. scope: "orders:read".to_owned(),
  1068. },
  1069. refresh_ttl,
  1070. )
  1071. .await?;
  1072. assert_ttl_within(
  1073. pttl_ms(&mut conn, &store.grant_key(&grant)).await?,
  1074. refresh_ttl,
  1075. )?;
  1076. // The index is born with the access member, then extended by the refresh
  1077. // member: it must outlive the short access TTL and stay within the grant's.
  1078. tokens::put_access(
  1079. &mut conn,
  1080. &store,
  1081. &unique("access-seed"),
  1082. &access_record(&client, &grant),
  1083. access_ttl,
  1084. )
  1085. .await?;
  1086. tokens::put_refresh(
  1087. &mut conn,
  1088. &store,
  1089. &old,
  1090. &refresh_record(&client, &grant),
  1091. refresh_ttl,
  1092. )
  1093. .await?;
  1094. let index_key = store.grant_tokens_key(&grant);
  1095. let index_ttl = pttl_ms(&mut conn, &index_key).await?;
  1096. if index_ttl <= access_ttl.as_millis() as i64 {
  1097. return Err(TestError::Unexpected(
  1098. "grant index must outlive the access-token TTL".to_owned(),
  1099. ));
  1100. }
  1101. assert_ttl_within(index_ttl, refresh_ttl)?;
  1102. // Simulate the index having expired: the rotation script must re-arm it
  1103. // rather than recreate it persistent.
  1104. let _: () = redis::cmd("DEL")
  1105. .arg(&index_key)
  1106. .query_async(&mut conn)
  1107. .await?;
  1108. let outcome = tokens::rotate(
  1109. &mut conn,
  1110. &store,
  1111. pepper,
  1112. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  1113. )
  1114. .await?;
  1115. if !matches!(outcome, tokens::RotateOutcome::Rotated { .. }) {
  1116. return Err(TestError::Unexpected("rotation must apply".to_owned()));
  1117. }
  1118. assert_ttl_within(pttl_ms(&mut conn, &index_key).await?, refresh_ttl)?;
  1119. let request_id = tokens::derive_rotation_id(pepper, &old)?;
  1120. assert_ttl_within(
  1121. pttl_ms(&mut conn, &store.rotation_map_key(&request_id)).await?,
  1122. rotation_grace.min(refresh_ttl),
  1123. )?;
  1124. assert_ttl_within(
  1125. pttl_ms(&mut conn, &store.refresh_key(&old)).await?,
  1126. refresh_ttl,
  1127. )
  1128. }
  1129. /// docs/REDIS.md: `oauth:{state}:session:<id>` lives under `ttl.session`
  1130. /// (12 h); a presession is the same record before login binds a subject.
  1131. #[tokio::test]
  1132. async fn store_session_and_presession_ttl_within_configured_window() -> TestResult {
  1133. let (_container, url) = redis_container(Vec::new()).await?;
  1134. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1135. let session_ttl = TtlConfig::default().session;
  1136. let session_id = unique("session");
  1137. sessions::put(
  1138. &mut conn,
  1139. &store,
  1140. &session_id,
  1141. &sessions::SessionRecord {
  1142. subject: "user-1".to_owned(),
  1143. mfa_verified: true,
  1144. restricted: false,
  1145. },
  1146. session_ttl,
  1147. )
  1148. .await?;
  1149. assert_ttl_within(
  1150. pttl_ms(&mut conn, &store.session_key(&session_id)).await?,
  1151. session_ttl,
  1152. )?;
  1153. let presession_id = unique("presession");
  1154. sessions::put(
  1155. &mut conn,
  1156. &store,
  1157. &presession_id,
  1158. &sessions::SessionRecord {
  1159. subject: String::new(),
  1160. mfa_verified: false,
  1161. restricted: false,
  1162. },
  1163. session_ttl,
  1164. )
  1165. .await?;
  1166. assert_ttl_within(
  1167. pttl_ms(&mut conn, &store.session_key(&presession_id)).await?,
  1168. session_ttl,
  1169. )
  1170. }
  1171. /// docs/REDIS.md: `oauth:{state}:pending:<id>` is short, request-scoped
  1172. /// (`routes::PENDING_TTL`, 300 s).
  1173. #[tokio::test]
  1174. async fn store_pending_auth_ttl_within_request_window() -> TestResult {
  1175. let (_container, url) = redis_container(Vec::new()).await?;
  1176. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1177. let request_id = unique("pending");
  1178. pending::put(
  1179. &mut conn,
  1180. &store,
  1181. &request_id,
  1182. &pending::PendingAuth {
  1183. client_id: unique("client"),
  1184. redirect_uri: "https://client.example.test/cb".to_owned(),
  1185. scope: "orders:read".to_owned(),
  1186. code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_owned(),
  1187. state: Some("state-xyz".to_owned()),
  1188. dpop_jkt: None,
  1189. iss: "https://as.example.test".to_owned(),
  1190. post_logout_uri: None,
  1191. },
  1192. crate::routes::PENDING_TTL,
  1193. )
  1194. .await?;
  1195. assert_ttl_within(
  1196. pttl_ms(&mut conn, &store.token_key("pending", &request_id)).await?,
  1197. crate::routes::PENDING_TTL,
  1198. )
  1199. }
  1200. /// docs/REDIS.md: the failed-login counter lives under the lockout window
  1201. /// (`ui::login::LOCKOUT_WINDOW`, 15 min) and keys a hash of the account label.
  1202. #[tokio::test]
  1203. async fn store_login_failure_counter_ttl_within_lockout_window() -> TestResult {
  1204. let (_container, url) = redis_container(Vec::new()).await?;
  1205. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1206. let window = crate::ui::login::LOCKOUT_WINDOW;
  1207. let account = unique("alice@example.test");
  1208. sessions::record_failed_login(&mut conn, &store, &account, window).await?;
  1209. let key = store.login_fail_key(&sha256_hex(account.as_bytes()));
  1210. assert_ttl_within(pttl_ms(&mut conn, &key).await?, window)
  1211. }
  1212. /// The composite helpers scope to one source: clearing one IP's bucket
  1213. /// leaves the account counter and every other IP's bucket intact.
  1214. #[tokio::test]
  1215. async fn store_ip_failure_clear_is_scoped_to_source() -> TestResult {
  1216. let (_container, url) = redis_container(Vec::new()).await?;
  1217. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1218. let window = crate::ui::login::LOCKOUT_WINDOW;
  1219. let account = unique("alice@example.test");
  1220. sessions::record_failed_login(&mut conn, &store, &account, window).await?;
  1221. sessions::record_ip_failure(&mut conn, &store, "ip-a", &account, window).await?;
  1222. sessions::record_ip_failure(&mut conn, &store, "ip-a", &account, window).await?;
  1223. sessions::record_ip_failure(&mut conn, &store, "ip-b", &account, window).await?;
  1224. sessions::clear_ip_failures(&mut conn, &store, "ip-a", &account).await?;
  1225. if sessions::ip_failure_count(&mut conn, &store, "ip-a", &account).await? != 0 {
  1226. return Err(TestError::Unexpected(
  1227. "the cleared source bucket must read zero".to_owned(),
  1228. ));
  1229. }
  1230. if sessions::ip_failure_count(&mut conn, &store, "ip-b", &account).await? != 1 {
  1231. return Err(TestError::Unexpected(
  1232. "the other source bucket must survive the clear".to_owned(),
  1233. ));
  1234. }
  1235. if sessions::failed_login_count(&mut conn, &store, &account).await? != 1 {
  1236. return Err(TestError::Unexpected(
  1237. "the account counter must survive a scoped clear".to_owned(),
  1238. ));
  1239. }
  1240. Ok(())
  1241. }
  1242. /// docs/REDIS.md: the DPoP replay marker is bounded by the proof window
  1243. /// ([`crate::jose::dpop::DPOP_JTI_TTL`]); the `private_key_jwt` marker is
  1244. /// bounded by the assertion's remaining validity (at most 360 s).
  1245. #[tokio::test]
  1246. async fn store_replay_marker_ttl_within_proof_window() -> TestResult {
  1247. let (_container, url) = redis_container(Vec::new()).await?;
  1248. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1249. let dpop_ttl = crate::jose::dpop::DPOP_JTI_TTL;
  1250. let jti = unique("jti");
  1251. if !dcr::claim_dpop_jti(&mut conn, &store, &jti, dpop_ttl).await? {
  1252. return Err(TestError::Unexpected(
  1253. "first DPoP claim must win".to_owned(),
  1254. ));
  1255. }
  1256. assert_ttl_within(
  1257. pttl_ms(&mut conn, &store.dpop_jti_key(&jti)).await?,
  1258. dpop_ttl,
  1259. )?;
  1260. let assertion_ttl = Duration::from_secs(300);
  1261. let assertion = unique("assertion");
  1262. if !dcr::claim_client_assertion_jti(&mut conn, &store, &assertion, assertion_ttl).await? {
  1263. return Err(TestError::Unexpected(
  1264. "first assertion claim must win".to_owned(),
  1265. ));
  1266. }
  1267. assert_ttl_within(
  1268. pttl_ms(&mut conn, &store.client_assertion_jti_key(&assertion)).await?,
  1269. assertion_ttl,
  1270. )
  1271. }
  1272. #[test]
  1273. fn store_keys_share_hash_tag_and_keyspaces_split() -> TestResult {
  1274. let store = Store::from_parts(
  1275. "oauth:{state}:".to_owned(),
  1276. "oauth:{rl}:".to_owned(),
  1277. DurabilityMode::WaitAof,
  1278. );
  1279. store.assert_keyspace_separation()?;
  1280. for key in [
  1281. store.code_key("h"),
  1282. store.access_key("h"),
  1283. store.refresh_key("h"),
  1284. store.grant_key("g"),
  1285. store.grant_tokens_key("g"),
  1286. store.session_key("s"),
  1287. store.par_key("p"),
  1288. store.device_key("d"),
  1289. store.user_code_key("u"),
  1290. store.dcr_iat_key("i"),
  1291. store.dpop_jti_key("j"),
  1292. store.client_assertion_jti_key("j"),
  1293. store.rotation_map_key("r"),
  1294. store.login_fail_key("l"),
  1295. store.login_fail_ip_key("i", "l"),
  1296. store.login_fail_unknown_key("i"),
  1297. ] {
  1298. if !key.contains("{state}") {
  1299. return Err(TestError::Unexpected(
  1300. "token key must carry the {state} tag".to_owned(),
  1301. ));
  1302. }
  1303. }
  1304. if !store.ratelimit_key("b").contains("{rl}") {
  1305. return Err(TestError::Unexpected(
  1306. "counter key must carry the {rl} tag".to_owned(),
  1307. ));
  1308. }
  1309. // Colliding prefixes are rejected so counters can never evict tokens.
  1310. let colliding = Store::from_parts(
  1311. "oauth:{state}:".to_owned(),
  1312. "oauth:{state}:".to_owned(),
  1313. DurabilityMode::WaitAof,
  1314. );
  1315. if colliding.assert_keyspace_separation().is_ok() {
  1316. return Err(TestError::Unexpected(
  1317. "colliding keyspaces must be rejected".to_owned(),
  1318. ));
  1319. }
  1320. Ok(())
  1321. }
  1322. #[test]
  1323. fn store_durability_selected_from_topology() -> TestResult {
  1324. // Single-node topologies must barrier on WAITAOF, never WAIT.
  1325. let single = RawRedisConfig {
  1326. url: Some("redis://127.0.0.1:6379".to_owned()),
  1327. durability: Some(DurabilityMode::Wait),
  1328. ..Default::default()
  1329. };
  1330. if RedisConfig::from_raw(single).is_ok() {
  1331. return Err(TestError::Unexpected(
  1332. "single-node WAIT must be rejected".to_owned(),
  1333. ));
  1334. }
  1335. let single = RawRedisConfig {
  1336. url: Some("redis://127.0.0.1:6379".to_owned()),
  1337. durability: Some(DurabilityMode::WaitAof),
  1338. ..Default::default()
  1339. };
  1340. let config = RedisConfig::from_raw(single)?;
  1341. if Store::from_config(&config).durability() != DurabilityMode::WaitAof {
  1342. return Err(TestError::Unexpected(
  1343. "single-node store must barrier on WAITAOF".to_owned(),
  1344. ));
  1345. }
  1346. Ok(())
  1347. }
  1348. #[test]
  1349. fn store_rotation_id_deterministic_per_old_token() -> TestResult {
  1350. let pepper = b"store-test-pepper";
  1351. let first = tokens::derive_rotation_id(pepper, "old-hash")?;
  1352. let second = tokens::derive_rotation_id(pepper, "old-hash")?;
  1353. if first != second || first.is_empty() {
  1354. return Err(TestError::Unexpected(
  1355. "rotation id must be deterministic".to_owned(),
  1356. ));
  1357. }
  1358. if tokens::derive_rotation_id(pepper, "other-hash")? == first {
  1359. return Err(TestError::Unexpected(
  1360. "rotation id must differ per token".to_owned(),
  1361. ));
  1362. }
  1363. if tokens::derive_rotation_id(b"other-pepper", "old-hash")? == first {
  1364. return Err(TestError::Unexpected(
  1365. "rotation id must differ per pepper".to_owned(),
  1366. ));
  1367. }
  1368. Ok(())
  1369. }
  1370. #[test]
  1371. fn store_error_classification_and_retry_scope() -> TestResult {
  1372. let transient_io = redis::RedisError::from(std::io::Error::new(
  1373. std::io::ErrorKind::TimedOut,
  1374. "timed out",
  1375. ));
  1376. let loading = redis::RedisError::from((
  1377. redis::ErrorKind::Server(redis::ServerErrorKind::BusyLoading),
  1378. "busy",
  1379. ));
  1380. let try_again = redis::RedisError::from((
  1381. redis::ErrorKind::Server(redis::ServerErrorKind::TryAgain),
  1382. "retry",
  1383. ));
  1384. let master_down = redis::RedisError::from((
  1385. redis::ErrorKind::Server(redis::ServerErrorKind::MasterDown),
  1386. "down",
  1387. ));
  1388. let cluster_down = redis::RedisError::from((
  1389. redis::ErrorKind::Server(redis::ServerErrorKind::ClusterDown),
  1390. "down",
  1391. ));
  1392. for error in [
  1393. &transient_io,
  1394. &loading,
  1395. &try_again,
  1396. &master_down,
  1397. &cluster_down,
  1398. ] {
  1399. if classify_redis(error) != ErrorClass::Transient {
  1400. return Err(TestError::Unexpected(
  1401. "expected a transient class".to_owned(),
  1402. ));
  1403. }
  1404. if !may_retry_op(OpClass::IdempotentRead, error)
  1405. || !may_retry_op(OpClass::ConditionalWrite, error)
  1406. || may_retry_op(OpClass::NonIdempotent, error)
  1407. {
  1408. return Err(TestError::Unexpected(
  1409. "retry scope must exclude non-idempotent ops".to_owned(),
  1410. ));
  1411. }
  1412. }
  1413. let cross_slot = redis::RedisError::from((
  1414. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1415. "slot",
  1416. ));
  1417. let readonly = redis::RedisError::from((
  1418. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1419. "ro",
  1420. ));
  1421. let type_error = redis::RedisError::from((redis::ErrorKind::UnexpectedReturnType, "type"));
  1422. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1423. for error in [&cross_slot, &readonly, &type_error, &auth] {
  1424. if classify_redis(error) != ErrorClass::Permanent {
  1425. return Err(TestError::Unexpected(
  1426. "expected a permanent class".to_owned(),
  1427. ));
  1428. }
  1429. if may_retry_op(OpClass::IdempotentRead, error) {
  1430. return Err(TestError::Unexpected(
  1431. "permanent errors must never retry".to_owned(),
  1432. ));
  1433. }
  1434. }
  1435. // Server-extension codes (`OOM`, ...) classify by code: fail closed.
  1436. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1437. match oom_value {
  1438. Ok(redis::Value::ServerError(server)) => {
  1439. let error = redis::RedisError::from(server);
  1440. if classify_redis(&error) != ErrorClass::Permanent {
  1441. return Err(TestError::Unexpected("OOM must fail closed".to_owned()));
  1442. }
  1443. }
  1444. _ => {
  1445. return Err(TestError::Unexpected(
  1446. "expected an OOM server error value".to_owned(),
  1447. ));
  1448. }
  1449. }
  1450. Ok(())
  1451. }
  1452. #[test]
  1453. fn store_permanent_infra_errors_map_to_503() -> TestResult {
  1454. use crate::error::{AppError, OAuthErrorCode};
  1455. use axum::http::StatusCode;
  1456. let cross_slot = redis::RedisError::from((
  1457. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1458. "slot",
  1459. ));
  1460. let readonly = redis::RedisError::from((
  1461. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1462. "ro",
  1463. ));
  1464. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1465. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1466. let oom = match oom_value {
  1467. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1468. _ => {
  1469. return Err(TestError::Unexpected(
  1470. "expected an OOM server error value".to_owned(),
  1471. ));
  1472. }
  1473. };
  1474. for error in [cross_slot, readonly, auth, oom] {
  1475. let mapped = AppError::from(StoreError::Redis(error));
  1476. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1477. return Err(TestError::Unexpected(
  1478. "permanent Redis infra failure must map to temporarily_unavailable".to_owned(),
  1479. ));
  1480. }
  1481. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1482. return Err(TestError::Unexpected(
  1483. "permanent Redis infra failure must render 503".to_owned(),
  1484. ));
  1485. }
  1486. }
  1487. // Genuinely internal bugs stay masked as server_error (500).
  1488. for error in [StoreError::InvalidData, StoreError::Mismatch] {
  1489. let mapped = AppError::from(error);
  1490. if mapped.code() != OAuthErrorCode::ServerError {
  1491. return Err(TestError::Unexpected(
  1492. "internal store bug must stay server_error".to_owned(),
  1493. ));
  1494. }
  1495. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1496. return Err(TestError::Unexpected(
  1497. "internal store bug must render 500".to_owned(),
  1498. ));
  1499. }
  1500. }
  1501. Ok(())
  1502. }
  1503. #[test]
  1504. fn store_error_classification() -> TestResult {
  1505. use crate::error::{AppError, OAuthErrorCode};
  1506. use axum::http::StatusCode;
  1507. let parse = redis::RedisError::from((redis::ErrorKind::Parse, "parse"));
  1508. let unexpected = redis::RedisError::from((redis::ErrorKind::UnexpectedReturnType, "type"));
  1509. let client = redis::RedisError::from((redis::ErrorKind::Client, "client"));
  1510. let wrongtype_value = redis::parse_redis_value(
  1511. b"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n",
  1512. );
  1513. let wrongtype = match wrongtype_value {
  1514. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1515. _ => {
  1516. return Err(TestError::Unexpected(
  1517. "expected a WRONGTYPE server error value".to_owned(),
  1518. ));
  1519. }
  1520. };
  1521. for error in [parse, unexpected, client, wrongtype] {
  1522. let mapped = AppError::from(StoreError::Redis(error));
  1523. if mapped.code() != OAuthErrorCode::ServerError {
  1524. return Err(TestError::Unexpected(
  1525. "programming Redis error must map to server_error".to_owned(),
  1526. ));
  1527. }
  1528. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1529. return Err(TestError::Unexpected(
  1530. "programming Redis error must render 500".to_owned(),
  1531. ));
  1532. }
  1533. }
  1534. let cross_slot = redis::RedisError::from((
  1535. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1536. "slot",
  1537. ));
  1538. let readonly = redis::RedisError::from((
  1539. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1540. "ro",
  1541. ));
  1542. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1543. let transient = redis::RedisError::from(std::io::Error::new(
  1544. std::io::ErrorKind::TimedOut,
  1545. "timed out",
  1546. ));
  1547. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1548. let oom = match oom_value {
  1549. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1550. _ => {
  1551. return Err(TestError::Unexpected(
  1552. "expected an OOM server error value".to_owned(),
  1553. ));
  1554. }
  1555. };
  1556. for error in [cross_slot, readonly, auth, transient, oom] {
  1557. let mapped = AppError::from(StoreError::Redis(error));
  1558. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1559. return Err(TestError::Unexpected(
  1560. "infra Redis failure must map to temporarily_unavailable".to_owned(),
  1561. ));
  1562. }
  1563. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1564. return Err(TestError::Unexpected(
  1565. "infra Redis failure must render 503".to_owned(),
  1566. ));
  1567. }
  1568. }
  1569. Ok(())
  1570. }
  1571. #[tokio::test]
  1572. async fn store_retry_budget_bounds_idempotent_reads() -> TestResult {
  1573. use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
  1574. static ATTEMPTS: AtomicU32 = AtomicU32::new(0);
  1575. ATTEMPTS.store(0, AtomicOrdering::Relaxed);
  1576. let (_container, url) = redis_container(Vec::new()).await?;
  1577. let (mut _conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1578. let outcome: Result<(), redis::RedisError> = retry_op!(&mut _conn, store.retry_budget(), async {
  1579. ATTEMPTS.fetch_add(1, AtomicOrdering::Relaxed);
  1580. Err::<(), redis::RedisError>(redis::RedisError::from((
  1581. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1582. "slot",
  1583. )))
  1584. });
  1585. match outcome {
  1586. Err(error)
  1587. if classify_redis(&error) == ErrorClass::Permanent
  1588. && ATTEMPTS.load(AtomicOrdering::Relaxed) == 1 => {}
  1589. _ => {
  1590. return Err(TestError::Unexpected(
  1591. "permanent errors must not retry".to_owned(),
  1592. ));
  1593. }
  1594. }
  1595. Ok(())
  1596. }
  1597. /// The record write is a single atomic `HSET`+`PEXPIRE` script: a record
  1598. /// observed after [`hset_record`] always carries both its fields AND a live
  1599. /// TTL, and a rewrite re-arms the expiry (never a persistent key).
  1600. #[tokio::test]
  1601. async fn store_hset_record_writes_fields_and_ttl() -> TestResult {
  1602. let (_container, url) = redis_container(Vec::new()).await?;
  1603. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1604. let key = unique("hset-record");
  1605. let ttl = Duration::from_secs(300);
  1606. let pairs = vec![
  1607. ("client_id".to_owned(), "client-1".to_owned()),
  1608. ("scope".to_owned(), "orders:read".to_owned()),
  1609. ];
  1610. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1611. let record = hget_record(&mut conn, &key).await?;
  1612. if record
  1613. .as_ref()
  1614. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  1615. {
  1616. return Err(TestError::Unexpected(
  1617. "written record must carry its fields".to_owned(),
  1618. ));
  1619. }
  1620. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)?;
  1621. // Rewrite: a shorter lifetime must be observable, proving the write
  1622. // re-arms the TTL and does not leave the previous expiry in place.
  1623. let rewrite = Duration::from_secs(120);
  1624. let updated = vec![
  1625. ("client_id".to_owned(), "client-2".to_owned()),
  1626. ("scope".to_owned(), "orders:read".to_owned()),
  1627. ];
  1628. hset_record(&mut conn, &key, &updated, rewrite).await?;
  1629. let record = hget_record(&mut conn, &key).await?;
  1630. if record
  1631. .as_ref()
  1632. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-2"))
  1633. {
  1634. return Err(TestError::Unexpected(
  1635. "rewrite must replace the field value".to_owned(),
  1636. ));
  1637. }
  1638. assert_ttl_within(pttl_ms(&mut conn, &key).await?, rewrite)?;
  1639. // A key whose TTL was stripped must regain a live expiry when rewritten
  1640. // through the atomic write, so no record can remain persistent.
  1641. let _: () = redis::cmd("PERSIST")
  1642. .arg(&key)
  1643. .query_async(&mut conn)
  1644. .await?;
  1645. if pttl_ms(&mut conn, &key).await? != -1 {
  1646. return Err(TestError::Unexpected(
  1647. "PERSIST must strip the TTL for the simulation".to_owned(),
  1648. ));
  1649. }
  1650. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1651. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  1652. }
  1653. /// Revoke drain exhaustion must fail closed, never report silent success.
  1654. ///
  1655. /// A zero-pass budget models the exhausted drain (a mint landing after every
  1656. /// snapshot, so the set never reads empty): members still indexed must
  1657. /// surface [`StoreError::InvalidData`], never a silent `Ok` count. The full
  1658. /// production budget on the same grant then still drains to zero with no live
  1659. /// member records behind it.
  1660. #[tokio::test]
  1661. async fn store_grant_revoke_exhaustion_is_not_silent() -> TestResult {
  1662. let (_container, url) = redis_container(Vec::new()).await?;
  1663. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1664. let grant = unique("grant");
  1665. let client = unique("client");
  1666. let seed = unique("seed-refresh");
  1667. grants::create(
  1668. &mut conn,
  1669. &store,
  1670. &grants::GrantRecord {
  1671. grant_id: grant.clone(),
  1672. client_id: client.clone(),
  1673. subject: "user-1".to_owned(),
  1674. scope: "orders:read".to_owned(),
  1675. },
  1676. Duration::from_secs(3600),
  1677. )
  1678. .await?;
  1679. tokens::put_refresh(
  1680. &mut conn,
  1681. &store,
  1682. &seed,
  1683. &refresh_record(&client, &grant),
  1684. Duration::from_secs(3600),
  1685. )
  1686. .await?;
  1687. match grants::revoke_with_passes(&mut conn, &store, &grant, 0).await {
  1688. Err(StoreError::InvalidData) => {}
  1689. Ok(count) => {
  1690. return Err(TestError::Unexpected(format!(
  1691. "exhausted drain must fail closed, got Ok({count})"
  1692. )));
  1693. }
  1694. Err(error) => {
  1695. return Err(TestError::Unexpected(format!(
  1696. "exhausted drain must be InvalidData, got {error:?}"
  1697. )));
  1698. }
  1699. }
  1700. // The production budget on the same grant drains fully: no live members.
  1701. let drained = grants::revoke(&mut conn, &store, &grant).await?;
  1702. if drained == 0 {
  1703. return Err(TestError::Unexpected(
  1704. "production revoke must count the seed member".to_owned(),
  1705. ));
  1706. }
  1707. if tokens::get_refresh(&mut conn, &store, &seed)
  1708. .await?
  1709. .is_some()
  1710. {
  1711. return Err(TestError::Unexpected(
  1712. "revoke must leave no live member record".to_owned(),
  1713. ));
  1714. }
  1715. if !grants::members(&mut conn, &store, &grant).await?.is_empty() {
  1716. return Err(TestError::Unexpected(
  1717. "revoke must leave the grant set empty".to_owned(),
  1718. ));
  1719. }
  1720. Ok(())
  1721. }
  1722. /// A corrupt poll-interval marker must fail closed, never fail open.
  1723. ///
  1724. /// A non-numeric sidecar value trips the script's `-1` path, which
  1725. /// `claim_poll_slot` surfaces as `InvalidData` (500-masked, never an
  1726. /// admission).
  1727. #[tokio::test]
  1728. async fn claim_poll_slot_corrupt_marker_fails_closed() -> TestResult {
  1729. let (_container, url) = redis_container(Vec::new()).await?;
  1730. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1731. let device_hash = unique("device");
  1732. let key = device::poll_key(&store, &device_hash);
  1733. let _: () = redis::cmd("SET")
  1734. .arg(&key)
  1735. .arg("not-a-number")
  1736. .query_async(&mut conn)
  1737. .await?;
  1738. match device::claim_poll_slot(
  1739. &mut conn,
  1740. &store,
  1741. &device_hash,
  1742. 1_700_000_000,
  1743. Duration::from_secs(5),
  1744. Duration::from_secs(600),
  1745. )
  1746. .await
  1747. {
  1748. Err(StoreError::InvalidData) => Ok(()),
  1749. Ok(slot) => Err(TestError::Unexpected(format!(
  1750. "corrupt poll marker must fail closed, admitted {slot:?}"
  1751. ))),
  1752. Err(error) => Err(TestError::Unexpected(format!(
  1753. "corrupt poll marker must be InvalidData, got {error:?}"
  1754. ))),
  1755. }
  1756. }
  1757. /// Generic Lua-runtime failures (`ERR`/`EXECABORT` server errors that are not
  1758. /// `WRONGTYPE`) are programming errors: they must map to masked
  1759. /// `server_error` (500) so 500-alerts fire, while genuine infrastructure
  1760. /// (`OOM`, `READONLY`, `CROSSSLOT`, auth, transient/connection) stays 503.
  1761. #[test]
  1762. fn store_error_classification_lua_runtime_is_500() -> TestResult {
  1763. use crate::error::{AppError, OAuthErrorCode};
  1764. use axum::http::StatusCode;
  1765. let lua_err = redis::RedisError::from((
  1766. redis::ErrorKind::Server(redis::ServerErrorKind::ResponseError),
  1767. "ERR Error running script: @user_script:1: bad argument",
  1768. ));
  1769. let exec_abort = redis::RedisError::from((
  1770. redis::ErrorKind::Server(redis::ServerErrorKind::ExecAbort),
  1771. "EXECABORT Script aborted",
  1772. ));
  1773. for error in [lua_err, exec_abort] {
  1774. let mapped = AppError::from(StoreError::Redis(error));
  1775. if mapped.code() != OAuthErrorCode::ServerError {
  1776. return Err(TestError::Unexpected(
  1777. "generic Lua-runtime failure must map to server_error".to_owned(),
  1778. ));
  1779. }
  1780. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1781. return Err(TestError::Unexpected(
  1782. "generic Lua-runtime failure must render 500".to_owned(),
  1783. ));
  1784. }
  1785. }
  1786. // Genuine infrastructure stays fail-closed 503.
  1787. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1788. let oom = match oom_value {
  1789. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1790. _ => {
  1791. return Err(TestError::Unexpected(
  1792. "expected an OOM server error value".to_owned(),
  1793. ));
  1794. }
  1795. };
  1796. let readonly = redis::RedisError::from((
  1797. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1798. "ro",
  1799. ));
  1800. let cross_slot = redis::RedisError::from((
  1801. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1802. "slot",
  1803. ));
  1804. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1805. let transient = redis::RedisError::from(std::io::Error::new(
  1806. std::io::ErrorKind::TimedOut,
  1807. "timed out",
  1808. ));
  1809. for error in [oom, readonly, cross_slot, auth, transient] {
  1810. let mapped = AppError::from(StoreError::Redis(error));
  1811. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1812. return Err(TestError::Unexpected(
  1813. "infra failure must map to temporarily_unavailable".to_owned(),
  1814. ));
  1815. }
  1816. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1817. return Err(TestError::Unexpected(
  1818. "infra failure must render 503".to_owned(),
  1819. ));
  1820. }
  1821. }
  1822. Ok(())
  1823. }
  1824. /// T3-B1: `decide` (EXISTS then HSET) racing `consume` (atomic DEL) must
  1825. /// never resurrect a zombie record. Every round puts a fresh record and runs
  1826. /// both ops concurrently; after both settle the key must be gone in every
  1827. /// case (decide won and consume reaped the verdict, or consume won and
  1828. /// decide saw the miss) — a surviving record is a verdict recreated after
  1829. /// the delete, i.e. a lost update.
  1830. #[tokio::test]
  1831. async fn store_device_decide_consume_leaves_no_zombie() -> TestResult {
  1832. let (_container, url) = redis_container(Vec::new()).await?;
  1833. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1834. let client = unique("client");
  1835. for round in 0..100u32 {
  1836. let device_hash = format!("{}-{round:03}", unique("device-race"));
  1837. let user_code = format!("{}-{round:03}", unique("user-race"));
  1838. let grant = format!("{}-{round:03}", unique("grant-race"));
  1839. device::put(
  1840. &mut conn,
  1841. &store,
  1842. &device_hash,
  1843. &user_code,
  1844. &device::DeviceRecord {
  1845. client_id: client.clone(),
  1846. scope: "orders:read".to_owned(),
  1847. status: device::DeviceStatus::Pending,
  1848. subject: String::new(),
  1849. grant_id: String::new(),
  1850. },
  1851. Duration::from_secs(600),
  1852. )
  1853. .await?;
  1854. let decide_task = tokio::spawn({
  1855. let conn = conn.clone();
  1856. let store = store.clone();
  1857. let device_hash = device_hash.clone();
  1858. let grant = grant.clone();
  1859. async move {
  1860. let mut conn = conn;
  1861. device::decide(
  1862. &mut conn,
  1863. &store,
  1864. &device_hash,
  1865. device::DeviceStatus::Approved,
  1866. "user-1",
  1867. &grant,
  1868. )
  1869. .await
  1870. }
  1871. });
  1872. let consume_task = tokio::spawn({
  1873. let conn = conn.clone();
  1874. let store = store.clone();
  1875. let device_hash = device_hash.clone();
  1876. async move {
  1877. let mut conn = conn;
  1878. device::consume(&mut conn, &store, &device_hash).await
  1879. }
  1880. });
  1881. let decided = decide_task
  1882. .await
  1883. .map_err(|_| TestError::Join)?
  1884. .map_err(|error| TestError::Unexpected(format!("round {round} decide: {error:?}")))?;
  1885. let consumed_present = consume_task
  1886. .await
  1887. .map_err(|_| TestError::Join)?
  1888. .map_err(|error| TestError::Unexpected(format!("round {round} consume: {error:?}")))?
  1889. .is_some();
  1890. let observed = device::poll(&mut conn, &store, &device_hash)
  1891. .await
  1892. .map_err(|error| TestError::Unexpected(format!("round {round} poll: {error:?}")))?;
  1893. if observed.is_some() {
  1894. return Err(TestError::Unexpected(format!(
  1895. "round {round}: zombie (decided={decided}, consumed={consumed_present})"
  1896. )));
  1897. }
  1898. }
  1899. Ok(())
  1900. }
  1901. /// T3-B4: a rotation into a revoked grant must be fenced, never minted.
  1902. ///
  1903. /// A token minted mid-cascade (live record, grant record already gone) must
  1904. /// not rotate into fresh tokens: the fence rejects with `Absent`, writes no
  1905. /// new records, indexes no new members, and leaves the presented record live
  1906. /// (fail closed, no cascade on a fenced write).
  1907. #[tokio::test]
  1908. async fn store_grant_revoke_fence_rejects_rotation_into_revoked_grant() -> TestResult {
  1909. let (_container, url) = redis_container(Vec::new()).await?;
  1910. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1911. let grant = unique("grant");
  1912. let client = unique("client");
  1913. let old = unique("old-refresh");
  1914. let pepper = b"store-test-pepper";
  1915. grants::create(
  1916. &mut conn,
  1917. &store,
  1918. &grants::GrantRecord {
  1919. grant_id: grant.clone(),
  1920. client_id: client.clone(),
  1921. subject: "user-1".to_owned(),
  1922. scope: "orders:read".to_owned(),
  1923. },
  1924. Duration::from_secs(3600),
  1925. )
  1926. .await?;
  1927. tokens::put_refresh(
  1928. &mut conn,
  1929. &store,
  1930. &old,
  1931. &refresh_record(&client, &grant),
  1932. Duration::from_secs(3600),
  1933. )
  1934. .await?;
  1935. grants::revoke(&mut conn, &store, &grant).await?;
  1936. // The mid-cascade mint: a live record re-indexed after the grant record
  1937. // died (the rotation SADD that slipped through the revoke snapshot).
  1938. let late_old = unique("late-refresh");
  1939. tokens::put_refresh(
  1940. &mut conn,
  1941. &store,
  1942. &late_old,
  1943. &refresh_record(&client, &grant),
  1944. Duration::from_secs(3600),
  1945. )
  1946. .await?;
  1947. let new_refresh = unique("fenced-refresh");
  1948. let new_access = unique("fenced-access");
  1949. let outcome = tokens::rotate(
  1950. &mut conn,
  1951. &store,
  1952. pepper,
  1953. &rotation_input(&late_old, &client, &new_refresh, &new_access, &grant, None),
  1954. )
  1955. .await?;
  1956. if !matches!(outcome, tokens::RotateOutcome::Absent) {
  1957. return Err(TestError::Unexpected(
  1958. "rotation into a revoked grant must be fenced to Absent".to_owned(),
  1959. ));
  1960. }
  1961. if tokens::get_refresh(&mut conn, &store, &new_refresh)
  1962. .await?
  1963. .is_some()
  1964. || tokens::get_access(&mut conn, &store, &new_access)
  1965. .await?
  1966. .is_some()
  1967. {
  1968. return Err(TestError::Unexpected(
  1969. "fenced rotation must leave no minted records behind".to_owned(),
  1970. ));
  1971. }
  1972. if grants::members(&mut conn, &store, &grant)
  1973. .await?
  1974. .iter()
  1975. .any(|member| member == &new_refresh || member == &new_access)
  1976. {
  1977. return Err(TestError::Unexpected(
  1978. "fenced rotation must index no new members".to_owned(),
  1979. ));
  1980. }
  1981. if tokens::get_refresh(&mut conn, &store, &late_old)
  1982. .await?
  1983. .is_none()
  1984. {
  1985. return Err(TestError::Unexpected(
  1986. "fenced rotation must not cascade on the presented record".to_owned(),
  1987. ));
  1988. }
  1989. Ok(())
  1990. }
  1991. /// T3-B4: one `revoke` call drains members indexed mid-cascade.
  1992. ///
  1993. /// A single-shot `SMEMBERS`-snapshot revoke leaves a member `SADD`ed after
  1994. /// its snapshot alive; `revoke` must loop until the grant set reads empty so
  1995. /// a mint that lands mid-cascade is deleted by a later pass.
  1996. #[tokio::test]
  1997. async fn store_grant_revoke_drains_mid_cascade_members() -> TestResult {
  1998. let (_container, url) = redis_container(Vec::new()).await?;
  1999. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2000. let grant = unique("grant");
  2001. let client = unique("client");
  2002. grants::create(
  2003. &mut conn,
  2004. &store,
  2005. &grants::GrantRecord {
  2006. grant_id: grant.clone(),
  2007. client_id: client.clone(),
  2008. subject: "user-1".to_owned(),
  2009. scope: "orders:read".to_owned(),
  2010. },
  2011. Duration::from_secs(3600),
  2012. )
  2013. .await?;
  2014. tokens::put_refresh(
  2015. &mut conn,
  2016. &store,
  2017. &unique("seed-refresh"),
  2018. &refresh_record(&client, &grant),
  2019. Duration::from_secs(3600),
  2020. )
  2021. .await?;
  2022. tokens::put_access(
  2023. &mut conn,
  2024. &store,
  2025. &unique("seed-access"),
  2026. &access_record(&client, &grant),
  2027. Duration::from_secs(300),
  2028. )
  2029. .await?;
  2030. // First pass: the cascade snapshot. A mint lands after it (the SADD the
  2031. // single-shot script can never see).
  2032. let set_key = store.grant_tokens_key(&grant);
  2033. let grant_key = store.grant_key(&grant);
  2034. let mut first = super::SCRIPT_GRANT_REVOKE.prepare_invoke();
  2035. first.key(set_key.as_str()).key(grant_key.as_str());
  2036. first
  2037. .arg(store.refresh_key_prefix().as_str())
  2038. .arg(store.access_key_prefix().as_str());
  2039. let _: u64 = first.invoke_async(&mut conn).await?;
  2040. let late_refresh = unique("late-refresh");
  2041. let late_access = unique("late-access");
  2042. tokens::put_refresh(
  2043. &mut conn,
  2044. &store,
  2045. &late_refresh,
  2046. &refresh_record(&client, &grant),
  2047. Duration::from_secs(3600),
  2048. )
  2049. .await?;
  2050. tokens::put_access(
  2051. &mut conn,
  2052. &store,
  2053. &late_access,
  2054. &access_record(&client, &grant),
  2055. Duration::from_secs(300),
  2056. )
  2057. .await?;
  2058. // One `revoke` call must drain the stragglers: no survivor records, an
  2059. // empty index, and a count that includes the late pair.
  2060. let drained = grants::revoke(&mut conn, &store, &grant).await?;
  2061. if drained < 2 {
  2062. return Err(TestError::Unexpected(
  2063. "revoke must count the mid-cascade pair".to_owned(),
  2064. ));
  2065. }
  2066. if tokens::get_refresh(&mut conn, &store, &late_refresh)
  2067. .await?
  2068. .is_some()
  2069. || tokens::get_access(&mut conn, &store, &late_access)
  2070. .await?
  2071. .is_some()
  2072. {
  2073. return Err(TestError::Unexpected(
  2074. "revoke must delete tokens minted mid-cascade".to_owned(),
  2075. ));
  2076. }
  2077. if !grants::members(&mut conn, &store, &grant).await?.is_empty() {
  2078. return Err(TestError::Unexpected(
  2079. "revoke must leave the grant set empty".to_owned(),
  2080. ));
  2081. }
  2082. Ok(())
  2083. }
  2084. /// T3-B5: a barrier failure after the rotation write returns the originating
  2085. /// request's tokens instead of a whole-grant lockout.
  2086. ///
  2087. /// On a replica-less `WAIT` node the barrier always fails closed; the
  2088. /// originating rotation (this request id) must still resolve to its
  2089. /// already-minted pair (`RotatedUnbarriered`), while a non-originating request id on the
  2090. /// tombstoned old token still cascades (fail closed, no tokens).
  2091. #[tokio::test]
  2092. async fn store_rotation_barrier_failure_returns_replay_for_originating_id() -> TestResult {
  2093. let (_container, url) = redis_container(Vec::new()).await?;
  2094. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2095. let fragile = Store::from_parts(
  2096. "oauth:{state}:".to_owned(),
  2097. "oauth:{rl}:".to_owned(),
  2098. DurabilityMode::Wait,
  2099. );
  2100. let grant = unique("grant");
  2101. let client = unique("client");
  2102. let old = unique("old-refresh");
  2103. let new_refresh = unique("new-refresh");
  2104. let new_access = unique("new-access");
  2105. let pepper = b"store-test-pepper";
  2106. grants::create(
  2107. &mut conn,
  2108. &durable,
  2109. &grants::GrantRecord {
  2110. grant_id: grant.clone(),
  2111. client_id: client.clone(),
  2112. subject: "user-1".to_owned(),
  2113. scope: "orders:read".to_owned(),
  2114. },
  2115. Duration::from_secs(3600),
  2116. )
  2117. .await?;
  2118. tokens::put_refresh(
  2119. &mut conn,
  2120. &durable,
  2121. &old,
  2122. &refresh_record(&client, &grant),
  2123. Duration::from_secs(3600),
  2124. )
  2125. .await?;
  2126. let outcome = tokens::rotate(
  2127. &mut conn,
  2128. &fragile,
  2129. pepper,
  2130. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  2131. )
  2132. .await?;
  2133. match outcome {
  2134. tokens::RotateOutcome::RotatedUnbarriered {
  2135. new_refresh_hash,
  2136. new_access_hash,
  2137. } if new_refresh_hash == new_refresh && new_access_hash == new_access => {}
  2138. _ => {
  2139. return Err(TestError::Unexpected(
  2140. "barrier failure must return the originating pair as RotatedUnbarriered".to_owned(),
  2141. ));
  2142. }
  2143. }
  2144. if tokens::get_refresh(&mut conn, &durable, &new_refresh)
  2145. .await?
  2146. .is_none()
  2147. || tokens::get_access(&mut conn, &durable, &new_access)
  2148. .await?
  2149. .is_none()
  2150. {
  2151. return Err(TestError::Unexpected(
  2152. "originating pair must be readable after barrier failure".to_owned(),
  2153. ));
  2154. }
  2155. // A non-originating request id on the tombstoned old token gets no tokens:
  2156. // reuse, plus the cascade.
  2157. let request_id = tokens::derive_rotation_id(pepper, &old)?;
  2158. let map_key = durable.rotation_map_key(&request_id);
  2159. let _: () = redis::cmd("DEL")
  2160. .arg(&map_key)
  2161. .query_async(&mut conn)
  2162. .await?;
  2163. let foreign = tokens::rotate(
  2164. &mut conn,
  2165. &durable,
  2166. pepper,
  2167. &rotation_input(
  2168. &old,
  2169. &client,
  2170. &unique("foreign"),
  2171. &unique("foreign-a"),
  2172. &grant,
  2173. Some("req-foreign".to_owned()),
  2174. ),
  2175. )
  2176. .await?;
  2177. if !matches!(foreign, tokens::RotateOutcome::Reused { .. }) {
  2178. return Err(TestError::Unexpected(
  2179. "non-originating retry must stay fail-closed reuse".to_owned(),
  2180. ));
  2181. }
  2182. Ok(())
  2183. }
  2184. /// T3-B5: a barrier failure after a winning replay-marker claim must not burn
  2185. /// the proof.
  2186. ///
  2187. /// The marker is removed before the `Durability` error surfaces, so the
  2188. /// originating `jti` can be claimed again; a concurrent non-originating
  2189. /// claimant still loses while the marker stands.
  2190. #[tokio::test]
  2191. async fn store_replay_marker_barrier_failure_does_not_burn_proof() -> TestResult {
  2192. let (_container, url) = redis_container(Vec::new()).await?;
  2193. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2194. let fragile = Store::from_parts(
  2195. "oauth:{state}:".to_owned(),
  2196. "oauth:{rl}:".to_owned(),
  2197. DurabilityMode::Wait,
  2198. );
  2199. let jti = unique("jti");
  2200. let ttl = Duration::from_secs(300);
  2201. match dcr::claim_dpop_jti(&mut conn, &fragile, &jti, ttl).await {
  2202. Err(StoreError::Durability) => {}
  2203. _ => {
  2204. return Err(TestError::Unexpected(
  2205. "failing barrier must surface Durability".to_owned(),
  2206. ));
  2207. }
  2208. }
  2209. let marker: Option<String> = redis::cmd("GET")
  2210. .arg(durable.dpop_jti_key(&jti))
  2211. .query_async(&mut conn)
  2212. .await?;
  2213. if marker.is_some() {
  2214. return Err(TestError::Unexpected(
  2215. "failed claim must not leave the marker behind".to_owned(),
  2216. ));
  2217. }
  2218. if !dcr::claim_dpop_jti(&mut conn, &durable, &jti, ttl).await? {
  2219. return Err(TestError::Unexpected(
  2220. "originating jti must be claimable after the failure".to_owned(),
  2221. ));
  2222. }
  2223. Ok(())
  2224. }
  2225. /// A field-less `HSET` is a Redis arity error; the empty-pairs guard falls
  2226. /// back to the TTL touch alone, so an existing record keeps its fields and a
  2227. /// live expiry instead of becoming persistent (or erroring out).
  2228. #[tokio::test]
  2229. async fn store_hset_record_empty_pairs_keeps_ttl() -> TestResult {
  2230. let (_container, url) = redis_container(Vec::new()).await?;
  2231. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2232. let key = unique("hset-empty");
  2233. let ttl = Duration::from_secs(300);
  2234. let pairs = vec![("client_id".to_owned(), "client-1".to_owned())];
  2235. hset_record(&mut conn, &key, &pairs, ttl).await?;
  2236. hset_record(&mut conn, &key, &[], ttl).await?;
  2237. let record = hget_record(&mut conn, &key).await?;
  2238. if record
  2239. .as_ref()
  2240. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  2241. {
  2242. return Err(TestError::Unexpected(
  2243. "empty rewrite must preserve the fields".to_owned(),
  2244. ));
  2245. }
  2246. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  2247. }
  2248. /// Wait-mode writes without a replica always fail the barrier; the pending
  2249. /// pre-mint must skip it (`Ok`) while the barriered write fails closed.
  2250. #[tokio::test]
  2251. async fn store_put_access_pending_skips_barrier() -> TestResult {
  2252. let (_container, url) = redis_container(Vec::new()).await?;
  2253. let (mut conn, _) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2254. let fragile = Store::from_parts(
  2255. "oauth:{state}:".to_owned(),
  2256. "oauth:{rl}:".to_owned(),
  2257. DurabilityMode::Wait,
  2258. );
  2259. let grant = unique("grant");
  2260. let client = unique("client");
  2261. let pending_hash = unique("pending-access");
  2262. let barriered_hash = unique("barriered-access");
  2263. tokens::put_access_pending(
  2264. &mut conn,
  2265. &fragile,
  2266. &pending_hash,
  2267. &access_record(&client, &grant),
  2268. Duration::from_secs(300),
  2269. )
  2270. .await?;
  2271. if tokens::get_access(&mut conn, &fragile, &pending_hash)
  2272. .await?
  2273. .is_none()
  2274. {
  2275. return Err(TestError::Unexpected(
  2276. "pending write must be readable without a barrier".to_owned(),
  2277. ));
  2278. }
  2279. match tokens::put_access(
  2280. &mut conn,
  2281. &fragile,
  2282. &barriered_hash,
  2283. &access_record(&client, &grant),
  2284. Duration::from_secs(300),
  2285. )
  2286. .await
  2287. {
  2288. Err(StoreError::Durability) => Ok(()),
  2289. Ok(()) => Err(TestError::Unexpected(
  2290. "barriered write without replicas must fail closed".to_owned(),
  2291. )),
  2292. Err(error) => Err(TestError::Unexpected(format!(
  2293. "barriered write must be Durability, got {error:?}"
  2294. ))),
  2295. }
  2296. }
  2297. /// A barrier failure still mints a readable pair; revoking the grant must
  2298. /// delete that recovered pair, so no unbarriered token survives revocation.
  2299. #[tokio::test]
  2300. async fn store_recovered_pair_revocable_after_unbarriered_rotation() -> TestResult {
  2301. let (_container, url) = redis_container(Vec::new()).await?;
  2302. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2303. let fragile = Store::from_parts(
  2304. "oauth:{state}:".to_owned(),
  2305. "oauth:{rl}:".to_owned(),
  2306. DurabilityMode::Wait,
  2307. );
  2308. let grant = unique("grant");
  2309. let client = unique("client");
  2310. let old = unique("old-refresh");
  2311. let new_refresh = unique("new-refresh");
  2312. let new_access = unique("new-access");
  2313. let pepper = b"store-test-pepper";
  2314. grants::create(
  2315. &mut conn,
  2316. &durable,
  2317. &grants::GrantRecord {
  2318. grant_id: grant.clone(),
  2319. client_id: client.clone(),
  2320. subject: "user-1".to_owned(),
  2321. scope: "orders:read".to_owned(),
  2322. },
  2323. Duration::from_secs(3600),
  2324. )
  2325. .await?;
  2326. tokens::put_refresh(
  2327. &mut conn,
  2328. &durable,
  2329. &old,
  2330. &refresh_record(&client, &grant),
  2331. Duration::from_secs(3600),
  2332. )
  2333. .await?;
  2334. match tokens::rotate(
  2335. &mut conn,
  2336. &fragile,
  2337. pepper,
  2338. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  2339. )
  2340. .await?
  2341. {
  2342. tokens::RotateOutcome::RotatedUnbarriered {
  2343. new_refresh_hash,
  2344. new_access_hash,
  2345. } if new_refresh_hash == new_refresh && new_access_hash == new_access => {}
  2346. _ => {
  2347. return Err(TestError::Unexpected(
  2348. "barrier failure must force RotatedUnbarriered".to_owned(),
  2349. ));
  2350. }
  2351. }
  2352. grants::revoke(&mut conn, &durable, &grant).await?;
  2353. if tokens::get_refresh(&mut conn, &durable, &new_refresh)
  2354. .await?
  2355. .is_some()
  2356. {
  2357. return Err(TestError::Unexpected(
  2358. "revoke must delete the recovered refresh token".to_owned(),
  2359. ));
  2360. }
  2361. if tokens::get_access(&mut conn, &durable, &new_access)
  2362. .await?
  2363. .is_some()
  2364. {
  2365. return Err(TestError::Unexpected(
  2366. "revoke must delete the recovered access token".to_owned(),
  2367. ));
  2368. }
  2369. Ok(())
  2370. }