tests_store.rs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  1. //! `test(store)` suite: atomic Lua, tombstones, grant index, durability.
  2. //!
  3. //! Every test here spins its own single-node Redis 7.2 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", "7.2-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. /// docs/REDIS.md: the DPoP replay marker is bounded by the proof window
  1213. /// ([`crate::jose::dpop::DPOP_JTI_TTL`]); the `private_key_jwt` marker is
  1214. /// bounded by the assertion's remaining validity (at most 360 s).
  1215. #[tokio::test]
  1216. async fn store_replay_marker_ttl_within_proof_window() -> TestResult {
  1217. let (_container, url) = redis_container(Vec::new()).await?;
  1218. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1219. let dpop_ttl = crate::jose::dpop::DPOP_JTI_TTL;
  1220. let jti = unique("jti");
  1221. if !dcr::claim_dpop_jti(&mut conn, &store, &jti, dpop_ttl).await? {
  1222. return Err(TestError::Unexpected(
  1223. "first DPoP claim must win".to_owned(),
  1224. ));
  1225. }
  1226. assert_ttl_within(
  1227. pttl_ms(&mut conn, &store.dpop_jti_key(&jti)).await?,
  1228. dpop_ttl,
  1229. )?;
  1230. let assertion_ttl = Duration::from_secs(300);
  1231. let assertion = unique("assertion");
  1232. if !dcr::claim_client_assertion_jti(&mut conn, &store, &assertion, assertion_ttl).await? {
  1233. return Err(TestError::Unexpected(
  1234. "first assertion claim must win".to_owned(),
  1235. ));
  1236. }
  1237. assert_ttl_within(
  1238. pttl_ms(&mut conn, &store.client_assertion_jti_key(&assertion)).await?,
  1239. assertion_ttl,
  1240. )
  1241. }
  1242. #[test]
  1243. fn store_keys_share_hash_tag_and_keyspaces_split() -> TestResult {
  1244. let store = Store::from_parts(
  1245. "oauth:{state}:".to_owned(),
  1246. "oauth:{rl}:".to_owned(),
  1247. DurabilityMode::WaitAof,
  1248. );
  1249. store.assert_keyspace_separation()?;
  1250. for key in [
  1251. store.code_key("h"),
  1252. store.access_key("h"),
  1253. store.refresh_key("h"),
  1254. store.grant_key("g"),
  1255. store.grant_tokens_key("g"),
  1256. store.session_key("s"),
  1257. store.par_key("p"),
  1258. store.device_key("d"),
  1259. store.user_code_key("u"),
  1260. store.dcr_iat_key("i"),
  1261. store.dpop_jti_key("j"),
  1262. store.client_assertion_jti_key("j"),
  1263. store.rotation_map_key("r"),
  1264. store.login_fail_key("l"),
  1265. ] {
  1266. if !key.contains("{state}") {
  1267. return Err(TestError::Unexpected(
  1268. "token key must carry the {state} tag".to_owned(),
  1269. ));
  1270. }
  1271. }
  1272. if !store.ratelimit_key("b").contains("{rl}") {
  1273. return Err(TestError::Unexpected(
  1274. "counter key must carry the {rl} tag".to_owned(),
  1275. ));
  1276. }
  1277. // Colliding prefixes are rejected so counters can never evict tokens.
  1278. let colliding = Store::from_parts(
  1279. "oauth:{state}:".to_owned(),
  1280. "oauth:{state}:".to_owned(),
  1281. DurabilityMode::WaitAof,
  1282. );
  1283. if colliding.assert_keyspace_separation().is_ok() {
  1284. return Err(TestError::Unexpected(
  1285. "colliding keyspaces must be rejected".to_owned(),
  1286. ));
  1287. }
  1288. Ok(())
  1289. }
  1290. #[test]
  1291. fn store_durability_selected_from_topology() -> TestResult {
  1292. // Single-node topologies must barrier on WAITAOF, never WAIT.
  1293. let single = RawRedisConfig {
  1294. url: Some("redis://127.0.0.1:6379".to_owned()),
  1295. durability: Some(DurabilityMode::Wait),
  1296. ..Default::default()
  1297. };
  1298. if RedisConfig::from_raw(single).is_ok() {
  1299. return Err(TestError::Unexpected(
  1300. "single-node WAIT must be rejected".to_owned(),
  1301. ));
  1302. }
  1303. let single = RawRedisConfig {
  1304. url: Some("redis://127.0.0.1:6379".to_owned()),
  1305. durability: Some(DurabilityMode::WaitAof),
  1306. ..Default::default()
  1307. };
  1308. let config = RedisConfig::from_raw(single)?;
  1309. if Store::from_config(&config).durability() != DurabilityMode::WaitAof {
  1310. return Err(TestError::Unexpected(
  1311. "single-node store must barrier on WAITAOF".to_owned(),
  1312. ));
  1313. }
  1314. Ok(())
  1315. }
  1316. #[test]
  1317. fn store_rotation_id_deterministic_per_old_token() -> TestResult {
  1318. let pepper = b"store-test-pepper";
  1319. let first = tokens::derive_rotation_id(pepper, "old-hash")?;
  1320. let second = tokens::derive_rotation_id(pepper, "old-hash")?;
  1321. if first != second || first.is_empty() {
  1322. return Err(TestError::Unexpected(
  1323. "rotation id must be deterministic".to_owned(),
  1324. ));
  1325. }
  1326. if tokens::derive_rotation_id(pepper, "other-hash")? == first {
  1327. return Err(TestError::Unexpected(
  1328. "rotation id must differ per token".to_owned(),
  1329. ));
  1330. }
  1331. if tokens::derive_rotation_id(b"other-pepper", "old-hash")? == first {
  1332. return Err(TestError::Unexpected(
  1333. "rotation id must differ per pepper".to_owned(),
  1334. ));
  1335. }
  1336. Ok(())
  1337. }
  1338. #[test]
  1339. fn store_error_classification_and_retry_scope() -> TestResult {
  1340. let transient_io = redis::RedisError::from(std::io::Error::new(
  1341. std::io::ErrorKind::TimedOut,
  1342. "timed out",
  1343. ));
  1344. let loading = redis::RedisError::from((
  1345. redis::ErrorKind::Server(redis::ServerErrorKind::BusyLoading),
  1346. "busy",
  1347. ));
  1348. let try_again = redis::RedisError::from((
  1349. redis::ErrorKind::Server(redis::ServerErrorKind::TryAgain),
  1350. "retry",
  1351. ));
  1352. let master_down = redis::RedisError::from((
  1353. redis::ErrorKind::Server(redis::ServerErrorKind::MasterDown),
  1354. "down",
  1355. ));
  1356. let cluster_down = redis::RedisError::from((
  1357. redis::ErrorKind::Server(redis::ServerErrorKind::ClusterDown),
  1358. "down",
  1359. ));
  1360. for error in [
  1361. &transient_io,
  1362. &loading,
  1363. &try_again,
  1364. &master_down,
  1365. &cluster_down,
  1366. ] {
  1367. if classify_redis(error) != ErrorClass::Transient {
  1368. return Err(TestError::Unexpected(
  1369. "expected a transient class".to_owned(),
  1370. ));
  1371. }
  1372. if !may_retry_op(OpClass::IdempotentRead, error)
  1373. || !may_retry_op(OpClass::ConditionalWrite, error)
  1374. || may_retry_op(OpClass::NonIdempotent, error)
  1375. {
  1376. return Err(TestError::Unexpected(
  1377. "retry scope must exclude non-idempotent ops".to_owned(),
  1378. ));
  1379. }
  1380. }
  1381. let cross_slot = redis::RedisError::from((
  1382. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1383. "slot",
  1384. ));
  1385. let readonly = redis::RedisError::from((
  1386. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1387. "ro",
  1388. ));
  1389. let type_error = redis::RedisError::from((redis::ErrorKind::UnexpectedReturnType, "type"));
  1390. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1391. for error in [&cross_slot, &readonly, &type_error, &auth] {
  1392. if classify_redis(error) != ErrorClass::Permanent {
  1393. return Err(TestError::Unexpected(
  1394. "expected a permanent class".to_owned(),
  1395. ));
  1396. }
  1397. if may_retry_op(OpClass::IdempotentRead, error) {
  1398. return Err(TestError::Unexpected(
  1399. "permanent errors must never retry".to_owned(),
  1400. ));
  1401. }
  1402. }
  1403. // Server-extension codes (`OOM`, ...) classify by code: fail closed.
  1404. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1405. match oom_value {
  1406. Ok(redis::Value::ServerError(server)) => {
  1407. let error = redis::RedisError::from(server);
  1408. if classify_redis(&error) != ErrorClass::Permanent {
  1409. return Err(TestError::Unexpected("OOM must fail closed".to_owned()));
  1410. }
  1411. }
  1412. _ => {
  1413. return Err(TestError::Unexpected(
  1414. "expected an OOM server error value".to_owned(),
  1415. ));
  1416. }
  1417. }
  1418. Ok(())
  1419. }
  1420. #[test]
  1421. fn store_permanent_infra_errors_map_to_503() -> TestResult {
  1422. use crate::error::{AppError, OAuthErrorCode};
  1423. use axum::http::StatusCode;
  1424. let cross_slot = redis::RedisError::from((
  1425. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1426. "slot",
  1427. ));
  1428. let readonly = redis::RedisError::from((
  1429. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1430. "ro",
  1431. ));
  1432. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1433. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1434. let oom = match oom_value {
  1435. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1436. _ => {
  1437. return Err(TestError::Unexpected(
  1438. "expected an OOM server error value".to_owned(),
  1439. ));
  1440. }
  1441. };
  1442. for error in [cross_slot, readonly, auth, oom] {
  1443. let mapped = AppError::from(StoreError::Redis(error));
  1444. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1445. return Err(TestError::Unexpected(
  1446. "permanent Redis infra failure must map to temporarily_unavailable".to_owned(),
  1447. ));
  1448. }
  1449. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1450. return Err(TestError::Unexpected(
  1451. "permanent Redis infra failure must render 503".to_owned(),
  1452. ));
  1453. }
  1454. }
  1455. // Genuinely internal bugs stay masked as server_error (500).
  1456. for error in [StoreError::InvalidData, StoreError::Mismatch] {
  1457. let mapped = AppError::from(error);
  1458. if mapped.code() != OAuthErrorCode::ServerError {
  1459. return Err(TestError::Unexpected(
  1460. "internal store bug must stay server_error".to_owned(),
  1461. ));
  1462. }
  1463. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1464. return Err(TestError::Unexpected(
  1465. "internal store bug must render 500".to_owned(),
  1466. ));
  1467. }
  1468. }
  1469. Ok(())
  1470. }
  1471. #[test]
  1472. fn store_error_classification() -> TestResult {
  1473. use crate::error::{AppError, OAuthErrorCode};
  1474. use axum::http::StatusCode;
  1475. let parse = redis::RedisError::from((redis::ErrorKind::Parse, "parse"));
  1476. let unexpected = redis::RedisError::from((redis::ErrorKind::UnexpectedReturnType, "type"));
  1477. let client = redis::RedisError::from((redis::ErrorKind::Client, "client"));
  1478. let wrongtype_value = redis::parse_redis_value(
  1479. b"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n",
  1480. );
  1481. let wrongtype = match wrongtype_value {
  1482. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1483. _ => {
  1484. return Err(TestError::Unexpected(
  1485. "expected a WRONGTYPE server error value".to_owned(),
  1486. ));
  1487. }
  1488. };
  1489. for error in [parse, unexpected, client, wrongtype] {
  1490. let mapped = AppError::from(StoreError::Redis(error));
  1491. if mapped.code() != OAuthErrorCode::ServerError {
  1492. return Err(TestError::Unexpected(
  1493. "programming Redis error must map to server_error".to_owned(),
  1494. ));
  1495. }
  1496. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1497. return Err(TestError::Unexpected(
  1498. "programming Redis error must render 500".to_owned(),
  1499. ));
  1500. }
  1501. }
  1502. let cross_slot = redis::RedisError::from((
  1503. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1504. "slot",
  1505. ));
  1506. let readonly = redis::RedisError::from((
  1507. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1508. "ro",
  1509. ));
  1510. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1511. let transient = redis::RedisError::from(std::io::Error::new(
  1512. std::io::ErrorKind::TimedOut,
  1513. "timed out",
  1514. ));
  1515. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1516. let oom = match oom_value {
  1517. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1518. _ => {
  1519. return Err(TestError::Unexpected(
  1520. "expected an OOM server error value".to_owned(),
  1521. ));
  1522. }
  1523. };
  1524. for error in [cross_slot, readonly, auth, transient, oom] {
  1525. let mapped = AppError::from(StoreError::Redis(error));
  1526. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1527. return Err(TestError::Unexpected(
  1528. "infra Redis failure must map to temporarily_unavailable".to_owned(),
  1529. ));
  1530. }
  1531. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1532. return Err(TestError::Unexpected(
  1533. "infra Redis failure must render 503".to_owned(),
  1534. ));
  1535. }
  1536. }
  1537. Ok(())
  1538. }
  1539. #[tokio::test]
  1540. async fn store_retry_budget_bounds_idempotent_reads() -> TestResult {
  1541. use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
  1542. static ATTEMPTS: AtomicU32 = AtomicU32::new(0);
  1543. ATTEMPTS.store(0, AtomicOrdering::Relaxed);
  1544. let (_container, url) = redis_container(Vec::new()).await?;
  1545. let (mut _conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1546. let outcome: Result<(), redis::RedisError> = retry_op!(&mut _conn, store.retry_budget(), async {
  1547. ATTEMPTS.fetch_add(1, AtomicOrdering::Relaxed);
  1548. Err::<(), redis::RedisError>(redis::RedisError::from((
  1549. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1550. "slot",
  1551. )))
  1552. });
  1553. match outcome {
  1554. Err(error)
  1555. if classify_redis(&error) == ErrorClass::Permanent
  1556. && ATTEMPTS.load(AtomicOrdering::Relaxed) == 1 => {}
  1557. _ => {
  1558. return Err(TestError::Unexpected(
  1559. "permanent errors must not retry".to_owned(),
  1560. ));
  1561. }
  1562. }
  1563. Ok(())
  1564. }
  1565. /// The record write is a single atomic `HSET`+`PEXPIRE` script: a record
  1566. /// observed after [`hset_record`] always carries both its fields AND a live
  1567. /// TTL, and a rewrite re-arms the expiry (never a persistent key).
  1568. #[tokio::test]
  1569. async fn store_hset_record_writes_fields_and_ttl() -> TestResult {
  1570. let (_container, url) = redis_container(Vec::new()).await?;
  1571. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1572. let key = unique("hset-record");
  1573. let ttl = Duration::from_secs(300);
  1574. let pairs = vec![
  1575. ("client_id".to_owned(), "client-1".to_owned()),
  1576. ("scope".to_owned(), "orders:read".to_owned()),
  1577. ];
  1578. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1579. let record = hget_record(&mut conn, &key).await?;
  1580. if record
  1581. .as_ref()
  1582. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  1583. {
  1584. return Err(TestError::Unexpected(
  1585. "written record must carry its fields".to_owned(),
  1586. ));
  1587. }
  1588. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)?;
  1589. // Rewrite: a shorter lifetime must be observable, proving the write
  1590. // re-arms the TTL and does not leave the previous expiry in place.
  1591. let rewrite = Duration::from_secs(120);
  1592. let updated = vec![
  1593. ("client_id".to_owned(), "client-2".to_owned()),
  1594. ("scope".to_owned(), "orders:read".to_owned()),
  1595. ];
  1596. hset_record(&mut conn, &key, &updated, rewrite).await?;
  1597. let record = hget_record(&mut conn, &key).await?;
  1598. if record
  1599. .as_ref()
  1600. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-2"))
  1601. {
  1602. return Err(TestError::Unexpected(
  1603. "rewrite must replace the field value".to_owned(),
  1604. ));
  1605. }
  1606. assert_ttl_within(pttl_ms(&mut conn, &key).await?, rewrite)?;
  1607. // A key whose TTL was stripped must regain a live expiry when rewritten
  1608. // through the atomic write, so no record can remain persistent.
  1609. let _: () = redis::cmd("PERSIST")
  1610. .arg(&key)
  1611. .query_async(&mut conn)
  1612. .await?;
  1613. if pttl_ms(&mut conn, &key).await? != -1 {
  1614. return Err(TestError::Unexpected(
  1615. "PERSIST must strip the TTL for the simulation".to_owned(),
  1616. ));
  1617. }
  1618. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1619. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  1620. }
  1621. /// Revoke drain exhaustion must fail closed, never report silent success.
  1622. ///
  1623. /// A zero-pass budget models the exhausted drain (a mint landing after every
  1624. /// snapshot, so the set never reads empty): members still indexed must
  1625. /// surface [`StoreError::InvalidData`], never a silent `Ok` count. The full
  1626. /// production budget on the same grant then still drains to zero with no live
  1627. /// member records behind it.
  1628. #[tokio::test]
  1629. async fn store_grant_revoke_exhaustion_is_not_silent() -> TestResult {
  1630. let (_container, url) = redis_container(Vec::new()).await?;
  1631. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1632. let grant = unique("grant");
  1633. let client = unique("client");
  1634. let seed = unique("seed-refresh");
  1635. grants::create(
  1636. &mut conn,
  1637. &store,
  1638. &grants::GrantRecord {
  1639. grant_id: grant.clone(),
  1640. client_id: client.clone(),
  1641. subject: "user-1".to_owned(),
  1642. scope: "orders:read".to_owned(),
  1643. },
  1644. Duration::from_secs(3600),
  1645. )
  1646. .await?;
  1647. tokens::put_refresh(
  1648. &mut conn,
  1649. &store,
  1650. &seed,
  1651. &refresh_record(&client, &grant),
  1652. Duration::from_secs(3600),
  1653. )
  1654. .await?;
  1655. match grants::revoke_with_passes(&mut conn, &store, &grant, 0).await {
  1656. Err(StoreError::InvalidData) => {}
  1657. Ok(count) => {
  1658. return Err(TestError::Unexpected(format!(
  1659. "exhausted drain must fail closed, got Ok({count})"
  1660. )));
  1661. }
  1662. Err(error) => {
  1663. return Err(TestError::Unexpected(format!(
  1664. "exhausted drain must be InvalidData, got {error:?}"
  1665. )));
  1666. }
  1667. }
  1668. // The production budget on the same grant drains fully: no live members.
  1669. let drained = grants::revoke(&mut conn, &store, &grant).await?;
  1670. if drained == 0 {
  1671. return Err(TestError::Unexpected(
  1672. "production revoke must count the seed member".to_owned(),
  1673. ));
  1674. }
  1675. if tokens::get_refresh(&mut conn, &store, &seed)
  1676. .await?
  1677. .is_some()
  1678. {
  1679. return Err(TestError::Unexpected(
  1680. "revoke must leave no live member record".to_owned(),
  1681. ));
  1682. }
  1683. if !grants::members(&mut conn, &store, &grant).await?.is_empty() {
  1684. return Err(TestError::Unexpected(
  1685. "revoke must leave the grant set empty".to_owned(),
  1686. ));
  1687. }
  1688. Ok(())
  1689. }
  1690. /// A corrupt poll-interval marker must fail closed, never fail open.
  1691. ///
  1692. /// A non-numeric sidecar value trips the script's `-1` path, which
  1693. /// `claim_poll_slot` surfaces as `InvalidData` (500-masked, never an
  1694. /// admission).
  1695. #[tokio::test]
  1696. async fn claim_poll_slot_corrupt_marker_fails_closed() -> TestResult {
  1697. let (_container, url) = redis_container(Vec::new()).await?;
  1698. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1699. let device_hash = unique("device");
  1700. let key = device::poll_key(&store, &device_hash);
  1701. let _: () = redis::cmd("SET")
  1702. .arg(&key)
  1703. .arg("not-a-number")
  1704. .query_async(&mut conn)
  1705. .await?;
  1706. match device::claim_poll_slot(
  1707. &mut conn,
  1708. &store,
  1709. &device_hash,
  1710. 1_700_000_000,
  1711. Duration::from_secs(5),
  1712. Duration::from_secs(600),
  1713. )
  1714. .await
  1715. {
  1716. Err(StoreError::InvalidData) => Ok(()),
  1717. Ok(slot) => Err(TestError::Unexpected(format!(
  1718. "corrupt poll marker must fail closed, admitted {slot:?}"
  1719. ))),
  1720. Err(error) => Err(TestError::Unexpected(format!(
  1721. "corrupt poll marker must be InvalidData, got {error:?}"
  1722. ))),
  1723. }
  1724. }
  1725. /// Generic Lua-runtime failures (`ERR`/`EXECABORT` server errors that are not
  1726. /// `WRONGTYPE`) are programming errors: they must map to masked
  1727. /// `server_error` (500) so 500-alerts fire, while genuine infrastructure
  1728. /// (`OOM`, `READONLY`, `CROSSSLOT`, auth, transient/connection) stays 503.
  1729. #[test]
  1730. fn store_error_classification_lua_runtime_is_500() -> TestResult {
  1731. use crate::error::{AppError, OAuthErrorCode};
  1732. use axum::http::StatusCode;
  1733. let lua_err = redis::RedisError::from((
  1734. redis::ErrorKind::Server(redis::ServerErrorKind::ResponseError),
  1735. "ERR Error running script: @user_script:1: bad argument",
  1736. ));
  1737. let exec_abort = redis::RedisError::from((
  1738. redis::ErrorKind::Server(redis::ServerErrorKind::ExecAbort),
  1739. "EXECABORT Script aborted",
  1740. ));
  1741. for error in [lua_err, exec_abort] {
  1742. let mapped = AppError::from(StoreError::Redis(error));
  1743. if mapped.code() != OAuthErrorCode::ServerError {
  1744. return Err(TestError::Unexpected(
  1745. "generic Lua-runtime failure must map to server_error".to_owned(),
  1746. ));
  1747. }
  1748. if mapped.status() != StatusCode::INTERNAL_SERVER_ERROR {
  1749. return Err(TestError::Unexpected(
  1750. "generic Lua-runtime failure must render 500".to_owned(),
  1751. ));
  1752. }
  1753. }
  1754. // Genuine infrastructure stays fail-closed 503.
  1755. let oom_value = redis::parse_redis_value(b"-OOM command not allowed\r\n");
  1756. let oom = match oom_value {
  1757. Ok(redis::Value::ServerError(server)) => redis::RedisError::from(server),
  1758. _ => {
  1759. return Err(TestError::Unexpected(
  1760. "expected an OOM server error value".to_owned(),
  1761. ));
  1762. }
  1763. };
  1764. let readonly = redis::RedisError::from((
  1765. redis::ErrorKind::Server(redis::ServerErrorKind::ReadOnly),
  1766. "ro",
  1767. ));
  1768. let cross_slot = redis::RedisError::from((
  1769. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1770. "slot",
  1771. ));
  1772. let auth = redis::RedisError::from((redis::ErrorKind::AuthenticationFailed, "auth"));
  1773. let transient = redis::RedisError::from(std::io::Error::new(
  1774. std::io::ErrorKind::TimedOut,
  1775. "timed out",
  1776. ));
  1777. for error in [oom, readonly, cross_slot, auth, transient] {
  1778. let mapped = AppError::from(StoreError::Redis(error));
  1779. if mapped.code() != OAuthErrorCode::TemporarilyUnavailable {
  1780. return Err(TestError::Unexpected(
  1781. "infra failure must map to temporarily_unavailable".to_owned(),
  1782. ));
  1783. }
  1784. if mapped.status() != StatusCode::SERVICE_UNAVAILABLE {
  1785. return Err(TestError::Unexpected(
  1786. "infra failure must render 503".to_owned(),
  1787. ));
  1788. }
  1789. }
  1790. Ok(())
  1791. }
  1792. /// T3-B1: `decide` (EXISTS then HSET) racing `consume` (atomic DEL) must
  1793. /// never resurrect a zombie record. Every round puts a fresh record and runs
  1794. /// both ops concurrently; after both settle the key must be gone in every
  1795. /// case (decide won and consume reaped the verdict, or consume won and
  1796. /// decide saw the miss) — a surviving record is a verdict recreated after
  1797. /// the delete, i.e. a lost update.
  1798. #[tokio::test]
  1799. async fn store_device_decide_consume_leaves_no_zombie() -> TestResult {
  1800. let (_container, url) = redis_container(Vec::new()).await?;
  1801. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1802. let client = unique("client");
  1803. for round in 0..100u32 {
  1804. let device_hash = format!("{}-{round:03}", unique("device-race"));
  1805. let user_code = format!("{}-{round:03}", unique("user-race"));
  1806. let grant = format!("{}-{round:03}", unique("grant-race"));
  1807. device::put(
  1808. &mut conn,
  1809. &store,
  1810. &device_hash,
  1811. &user_code,
  1812. &device::DeviceRecord {
  1813. client_id: client.clone(),
  1814. scope: "orders:read".to_owned(),
  1815. status: device::DeviceStatus::Pending,
  1816. subject: String::new(),
  1817. grant_id: String::new(),
  1818. },
  1819. Duration::from_secs(600),
  1820. )
  1821. .await?;
  1822. let decide_task = tokio::spawn({
  1823. let conn = conn.clone();
  1824. let store = store.clone();
  1825. let device_hash = device_hash.clone();
  1826. let grant = grant.clone();
  1827. async move {
  1828. let mut conn = conn;
  1829. device::decide(
  1830. &mut conn,
  1831. &store,
  1832. &device_hash,
  1833. device::DeviceStatus::Approved,
  1834. "user-1",
  1835. &grant,
  1836. )
  1837. .await
  1838. }
  1839. });
  1840. let consume_task = tokio::spawn({
  1841. let conn = conn.clone();
  1842. let store = store.clone();
  1843. let device_hash = device_hash.clone();
  1844. async move {
  1845. let mut conn = conn;
  1846. device::consume(&mut conn, &store, &device_hash).await
  1847. }
  1848. });
  1849. let decided = decide_task
  1850. .await
  1851. .map_err(|_| TestError::Join)?
  1852. .map_err(|error| TestError::Unexpected(format!("round {round} decide: {error:?}")))?;
  1853. let consumed_present = consume_task
  1854. .await
  1855. .map_err(|_| TestError::Join)?
  1856. .map_err(|error| TestError::Unexpected(format!("round {round} consume: {error:?}")))?
  1857. .is_some();
  1858. let observed = device::poll(&mut conn, &store, &device_hash)
  1859. .await
  1860. .map_err(|error| TestError::Unexpected(format!("round {round} poll: {error:?}")))?;
  1861. if observed.is_some() {
  1862. return Err(TestError::Unexpected(format!(
  1863. "round {round}: zombie (decided={decided}, consumed={consumed_present})"
  1864. )));
  1865. }
  1866. }
  1867. Ok(())
  1868. }
  1869. /// T3-B4: a rotation into a revoked grant must be fenced, never minted.
  1870. ///
  1871. /// A token minted mid-cascade (live record, grant record already gone) must
  1872. /// not rotate into fresh tokens: the fence rejects with `Absent`, writes no
  1873. /// new records, indexes no new members, and leaves the presented record live
  1874. /// (fail closed, no cascade on a fenced write).
  1875. #[tokio::test]
  1876. async fn store_grant_revoke_fence_rejects_rotation_into_revoked_grant() -> TestResult {
  1877. let (_container, url) = redis_container(Vec::new()).await?;
  1878. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1879. let grant = unique("grant");
  1880. let client = unique("client");
  1881. let old = unique("old-refresh");
  1882. let pepper = b"store-test-pepper";
  1883. grants::create(
  1884. &mut conn,
  1885. &store,
  1886. &grants::GrantRecord {
  1887. grant_id: grant.clone(),
  1888. client_id: client.clone(),
  1889. subject: "user-1".to_owned(),
  1890. scope: "orders:read".to_owned(),
  1891. },
  1892. Duration::from_secs(3600),
  1893. )
  1894. .await?;
  1895. tokens::put_refresh(
  1896. &mut conn,
  1897. &store,
  1898. &old,
  1899. &refresh_record(&client, &grant),
  1900. Duration::from_secs(3600),
  1901. )
  1902. .await?;
  1903. grants::revoke(&mut conn, &store, &grant).await?;
  1904. // The mid-cascade mint: a live record re-indexed after the grant record
  1905. // died (the rotation SADD that slipped through the revoke snapshot).
  1906. let late_old = unique("late-refresh");
  1907. tokens::put_refresh(
  1908. &mut conn,
  1909. &store,
  1910. &late_old,
  1911. &refresh_record(&client, &grant),
  1912. Duration::from_secs(3600),
  1913. )
  1914. .await?;
  1915. let new_refresh = unique("fenced-refresh");
  1916. let new_access = unique("fenced-access");
  1917. let outcome = tokens::rotate(
  1918. &mut conn,
  1919. &store,
  1920. pepper,
  1921. &rotation_input(&late_old, &client, &new_refresh, &new_access, &grant, None),
  1922. )
  1923. .await?;
  1924. if !matches!(outcome, tokens::RotateOutcome::Absent) {
  1925. return Err(TestError::Unexpected(
  1926. "rotation into a revoked grant must be fenced to Absent".to_owned(),
  1927. ));
  1928. }
  1929. if tokens::get_refresh(&mut conn, &store, &new_refresh)
  1930. .await?
  1931. .is_some()
  1932. || tokens::get_access(&mut conn, &store, &new_access)
  1933. .await?
  1934. .is_some()
  1935. {
  1936. return Err(TestError::Unexpected(
  1937. "fenced rotation must leave no minted records behind".to_owned(),
  1938. ));
  1939. }
  1940. if grants::members(&mut conn, &store, &grant)
  1941. .await?
  1942. .iter()
  1943. .any(|member| member == &new_refresh || member == &new_access)
  1944. {
  1945. return Err(TestError::Unexpected(
  1946. "fenced rotation must index no new members".to_owned(),
  1947. ));
  1948. }
  1949. if tokens::get_refresh(&mut conn, &store, &late_old)
  1950. .await?
  1951. .is_none()
  1952. {
  1953. return Err(TestError::Unexpected(
  1954. "fenced rotation must not cascade on the presented record".to_owned(),
  1955. ));
  1956. }
  1957. Ok(())
  1958. }
  1959. /// T3-B4: one `revoke` call drains members indexed mid-cascade.
  1960. ///
  1961. /// A single-shot `SMEMBERS`-snapshot revoke leaves a member `SADD`ed after
  1962. /// its snapshot alive; `revoke` must loop until the grant set reads empty so
  1963. /// a mint that lands mid-cascade is deleted by a later pass.
  1964. #[tokio::test]
  1965. async fn store_grant_revoke_drains_mid_cascade_members() -> TestResult {
  1966. let (_container, url) = redis_container(Vec::new()).await?;
  1967. let (mut conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1968. let grant = unique("grant");
  1969. let client = unique("client");
  1970. grants::create(
  1971. &mut conn,
  1972. &store,
  1973. &grants::GrantRecord {
  1974. grant_id: grant.clone(),
  1975. client_id: client.clone(),
  1976. subject: "user-1".to_owned(),
  1977. scope: "orders:read".to_owned(),
  1978. },
  1979. Duration::from_secs(3600),
  1980. )
  1981. .await?;
  1982. tokens::put_refresh(
  1983. &mut conn,
  1984. &store,
  1985. &unique("seed-refresh"),
  1986. &refresh_record(&client, &grant),
  1987. Duration::from_secs(3600),
  1988. )
  1989. .await?;
  1990. tokens::put_access(
  1991. &mut conn,
  1992. &store,
  1993. &unique("seed-access"),
  1994. &access_record(&client, &grant),
  1995. Duration::from_secs(300),
  1996. )
  1997. .await?;
  1998. // First pass: the cascade snapshot. A mint lands after it (the SADD the
  1999. // single-shot script can never see).
  2000. let set_key = store.grant_tokens_key(&grant);
  2001. let grant_key = store.grant_key(&grant);
  2002. let mut first = super::SCRIPT_GRANT_REVOKE.prepare_invoke();
  2003. first.key(set_key.as_str()).key(grant_key.as_str());
  2004. first
  2005. .arg(store.refresh_key_prefix().as_str())
  2006. .arg(store.access_key_prefix().as_str());
  2007. let _: u64 = first.invoke_async(&mut conn).await?;
  2008. let late_refresh = unique("late-refresh");
  2009. let late_access = unique("late-access");
  2010. tokens::put_refresh(
  2011. &mut conn,
  2012. &store,
  2013. &late_refresh,
  2014. &refresh_record(&client, &grant),
  2015. Duration::from_secs(3600),
  2016. )
  2017. .await?;
  2018. tokens::put_access(
  2019. &mut conn,
  2020. &store,
  2021. &late_access,
  2022. &access_record(&client, &grant),
  2023. Duration::from_secs(300),
  2024. )
  2025. .await?;
  2026. // One `revoke` call must drain the stragglers: no survivor records, an
  2027. // empty index, and a count that includes the late pair.
  2028. let drained = grants::revoke(&mut conn, &store, &grant).await?;
  2029. if drained < 2 {
  2030. return Err(TestError::Unexpected(
  2031. "revoke must count the mid-cascade pair".to_owned(),
  2032. ));
  2033. }
  2034. if tokens::get_refresh(&mut conn, &store, &late_refresh)
  2035. .await?
  2036. .is_some()
  2037. || tokens::get_access(&mut conn, &store, &late_access)
  2038. .await?
  2039. .is_some()
  2040. {
  2041. return Err(TestError::Unexpected(
  2042. "revoke must delete tokens minted mid-cascade".to_owned(),
  2043. ));
  2044. }
  2045. if !grants::members(&mut conn, &store, &grant).await?.is_empty() {
  2046. return Err(TestError::Unexpected(
  2047. "revoke must leave the grant set empty".to_owned(),
  2048. ));
  2049. }
  2050. Ok(())
  2051. }
  2052. /// T3-B5: a barrier failure after the rotation write returns the originating
  2053. /// request's tokens instead of a whole-grant lockout.
  2054. ///
  2055. /// On a replica-less `WAIT` node the barrier always fails closed; the
  2056. /// originating rotation (this request id) must still resolve to its
  2057. /// already-minted pair (`RotatedUnbarriered`), while a non-originating request id on the
  2058. /// tombstoned old token still cascades (fail closed, no tokens).
  2059. #[tokio::test]
  2060. async fn store_rotation_barrier_failure_returns_replay_for_originating_id() -> TestResult {
  2061. let (_container, url) = redis_container(Vec::new()).await?;
  2062. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2063. let fragile = Store::from_parts(
  2064. "oauth:{state}:".to_owned(),
  2065. "oauth:{rl}:".to_owned(),
  2066. DurabilityMode::Wait,
  2067. );
  2068. let grant = unique("grant");
  2069. let client = unique("client");
  2070. let old = unique("old-refresh");
  2071. let new_refresh = unique("new-refresh");
  2072. let new_access = unique("new-access");
  2073. let pepper = b"store-test-pepper";
  2074. grants::create(
  2075. &mut conn,
  2076. &durable,
  2077. &grants::GrantRecord {
  2078. grant_id: grant.clone(),
  2079. client_id: client.clone(),
  2080. subject: "user-1".to_owned(),
  2081. scope: "orders:read".to_owned(),
  2082. },
  2083. Duration::from_secs(3600),
  2084. )
  2085. .await?;
  2086. tokens::put_refresh(
  2087. &mut conn,
  2088. &durable,
  2089. &old,
  2090. &refresh_record(&client, &grant),
  2091. Duration::from_secs(3600),
  2092. )
  2093. .await?;
  2094. let outcome = tokens::rotate(
  2095. &mut conn,
  2096. &fragile,
  2097. pepper,
  2098. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  2099. )
  2100. .await?;
  2101. match outcome {
  2102. tokens::RotateOutcome::RotatedUnbarriered {
  2103. new_refresh_hash,
  2104. new_access_hash,
  2105. } if new_refresh_hash == new_refresh && new_access_hash == new_access => {}
  2106. _ => {
  2107. return Err(TestError::Unexpected(
  2108. "barrier failure must return the originating pair as RotatedUnbarriered".to_owned(),
  2109. ));
  2110. }
  2111. }
  2112. if tokens::get_refresh(&mut conn, &durable, &new_refresh)
  2113. .await?
  2114. .is_none()
  2115. || tokens::get_access(&mut conn, &durable, &new_access)
  2116. .await?
  2117. .is_none()
  2118. {
  2119. return Err(TestError::Unexpected(
  2120. "originating pair must be readable after barrier failure".to_owned(),
  2121. ));
  2122. }
  2123. // A non-originating request id on the tombstoned old token gets no tokens:
  2124. // reuse, plus the cascade.
  2125. let request_id = tokens::derive_rotation_id(pepper, &old)?;
  2126. let map_key = durable.rotation_map_key(&request_id);
  2127. let _: () = redis::cmd("DEL")
  2128. .arg(&map_key)
  2129. .query_async(&mut conn)
  2130. .await?;
  2131. let foreign = tokens::rotate(
  2132. &mut conn,
  2133. &durable,
  2134. pepper,
  2135. &rotation_input(
  2136. &old,
  2137. &client,
  2138. &unique("foreign"),
  2139. &unique("foreign-a"),
  2140. &grant,
  2141. Some("req-foreign".to_owned()),
  2142. ),
  2143. )
  2144. .await?;
  2145. if !matches!(foreign, tokens::RotateOutcome::Reused { .. }) {
  2146. return Err(TestError::Unexpected(
  2147. "non-originating retry must stay fail-closed reuse".to_owned(),
  2148. ));
  2149. }
  2150. Ok(())
  2151. }
  2152. /// T3-B5: a barrier failure after a winning replay-marker claim must not burn
  2153. /// the proof.
  2154. ///
  2155. /// The marker is removed before the `Durability` error surfaces, so the
  2156. /// originating `jti` can be claimed again; a concurrent non-originating
  2157. /// claimant still loses while the marker stands.
  2158. #[tokio::test]
  2159. async fn store_replay_marker_barrier_failure_does_not_burn_proof() -> TestResult {
  2160. let (_container, url) = redis_container(Vec::new()).await?;
  2161. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2162. let fragile = Store::from_parts(
  2163. "oauth:{state}:".to_owned(),
  2164. "oauth:{rl}:".to_owned(),
  2165. DurabilityMode::Wait,
  2166. );
  2167. let jti = unique("jti");
  2168. let ttl = Duration::from_secs(300);
  2169. match dcr::claim_dpop_jti(&mut conn, &fragile, &jti, ttl).await {
  2170. Err(StoreError::Durability) => {}
  2171. _ => {
  2172. return Err(TestError::Unexpected(
  2173. "failing barrier must surface Durability".to_owned(),
  2174. ));
  2175. }
  2176. }
  2177. let marker: Option<String> = redis::cmd("GET")
  2178. .arg(durable.dpop_jti_key(&jti))
  2179. .query_async(&mut conn)
  2180. .await?;
  2181. if marker.is_some() {
  2182. return Err(TestError::Unexpected(
  2183. "failed claim must not leave the marker behind".to_owned(),
  2184. ));
  2185. }
  2186. if !dcr::claim_dpop_jti(&mut conn, &durable, &jti, ttl).await? {
  2187. return Err(TestError::Unexpected(
  2188. "originating jti must be claimable after the failure".to_owned(),
  2189. ));
  2190. }
  2191. Ok(())
  2192. }
  2193. /// A field-less `HSET` is a Redis arity error; the empty-pairs guard falls
  2194. /// back to the TTL touch alone, so an existing record keeps its fields and a
  2195. /// live expiry instead of becoming persistent (or erroring out).
  2196. #[tokio::test]
  2197. async fn store_hset_record_empty_pairs_keeps_ttl() -> TestResult {
  2198. let (_container, url) = redis_container(Vec::new()).await?;
  2199. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2200. let key = unique("hset-empty");
  2201. let ttl = Duration::from_secs(300);
  2202. let pairs = vec![("client_id".to_owned(), "client-1".to_owned())];
  2203. hset_record(&mut conn, &key, &pairs, ttl).await?;
  2204. hset_record(&mut conn, &key, &[], ttl).await?;
  2205. let record = hget_record(&mut conn, &key).await?;
  2206. if record
  2207. .as_ref()
  2208. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  2209. {
  2210. return Err(TestError::Unexpected(
  2211. "empty rewrite must preserve the fields".to_owned(),
  2212. ));
  2213. }
  2214. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  2215. }
  2216. /// Wait-mode writes without a replica always fail the barrier; the pending
  2217. /// pre-mint must skip it (`Ok`) while the barriered write fails closed.
  2218. #[tokio::test]
  2219. async fn store_put_access_pending_skips_barrier() -> TestResult {
  2220. let (_container, url) = redis_container(Vec::new()).await?;
  2221. let (mut conn, _) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2222. let fragile = Store::from_parts(
  2223. "oauth:{state}:".to_owned(),
  2224. "oauth:{rl}:".to_owned(),
  2225. DurabilityMode::Wait,
  2226. );
  2227. let grant = unique("grant");
  2228. let client = unique("client");
  2229. let pending_hash = unique("pending-access");
  2230. let barriered_hash = unique("barriered-access");
  2231. tokens::put_access_pending(
  2232. &mut conn,
  2233. &fragile,
  2234. &pending_hash,
  2235. &access_record(&client, &grant),
  2236. Duration::from_secs(300),
  2237. )
  2238. .await?;
  2239. if tokens::get_access(&mut conn, &fragile, &pending_hash)
  2240. .await?
  2241. .is_none()
  2242. {
  2243. return Err(TestError::Unexpected(
  2244. "pending write must be readable without a barrier".to_owned(),
  2245. ));
  2246. }
  2247. match tokens::put_access(
  2248. &mut conn,
  2249. &fragile,
  2250. &barriered_hash,
  2251. &access_record(&client, &grant),
  2252. Duration::from_secs(300),
  2253. )
  2254. .await
  2255. {
  2256. Err(StoreError::Durability) => Ok(()),
  2257. Ok(()) => Err(TestError::Unexpected(
  2258. "barriered write without replicas must fail closed".to_owned(),
  2259. )),
  2260. Err(error) => Err(TestError::Unexpected(format!(
  2261. "barriered write must be Durability, got {error:?}"
  2262. ))),
  2263. }
  2264. }
  2265. /// A barrier failure still mints a readable pair; revoking the grant must
  2266. /// delete that recovered pair, so no unbarriered token survives revocation.
  2267. #[tokio::test]
  2268. async fn store_recovered_pair_revocable_after_unbarriered_rotation() -> TestResult {
  2269. let (_container, url) = redis_container(Vec::new()).await?;
  2270. let (mut conn, durable) = direct_store(&url, DurabilityMode::WaitAof).await?;
  2271. let fragile = Store::from_parts(
  2272. "oauth:{state}:".to_owned(),
  2273. "oauth:{rl}:".to_owned(),
  2274. DurabilityMode::Wait,
  2275. );
  2276. let grant = unique("grant");
  2277. let client = unique("client");
  2278. let old = unique("old-refresh");
  2279. let new_refresh = unique("new-refresh");
  2280. let new_access = unique("new-access");
  2281. let pepper = b"store-test-pepper";
  2282. grants::create(
  2283. &mut conn,
  2284. &durable,
  2285. &grants::GrantRecord {
  2286. grant_id: grant.clone(),
  2287. client_id: client.clone(),
  2288. subject: "user-1".to_owned(),
  2289. scope: "orders:read".to_owned(),
  2290. },
  2291. Duration::from_secs(3600),
  2292. )
  2293. .await?;
  2294. tokens::put_refresh(
  2295. &mut conn,
  2296. &durable,
  2297. &old,
  2298. &refresh_record(&client, &grant),
  2299. Duration::from_secs(3600),
  2300. )
  2301. .await?;
  2302. match tokens::rotate(
  2303. &mut conn,
  2304. &fragile,
  2305. pepper,
  2306. &rotation_input(&old, &client, &new_refresh, &new_access, &grant, None),
  2307. )
  2308. .await?
  2309. {
  2310. tokens::RotateOutcome::RotatedUnbarriered {
  2311. new_refresh_hash,
  2312. new_access_hash,
  2313. } if new_refresh_hash == new_refresh && new_access_hash == new_access => {}
  2314. _ => {
  2315. return Err(TestError::Unexpected(
  2316. "barrier failure must force RotatedUnbarriered".to_owned(),
  2317. ));
  2318. }
  2319. }
  2320. grants::revoke(&mut conn, &durable, &grant).await?;
  2321. if tokens::get_refresh(&mut conn, &durable, &new_refresh)
  2322. .await?
  2323. .is_some()
  2324. {
  2325. return Err(TestError::Unexpected(
  2326. "revoke must delete the recovered refresh token".to_owned(),
  2327. ));
  2328. }
  2329. if tokens::get_access(&mut conn, &durable, &new_access)
  2330. .await?
  2331. .is_some()
  2332. {
  2333. return Err(TestError::Unexpected(
  2334. "revoke must delete the recovered access token".to_owned(),
  2335. ));
  2336. }
  2337. Ok(())
  2338. }