tests_store.rs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. #[tokio::test]
  1421. async fn store_retry_budget_bounds_idempotent_reads() -> TestResult {
  1422. use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
  1423. static ATTEMPTS: AtomicU32 = AtomicU32::new(0);
  1424. ATTEMPTS.store(0, AtomicOrdering::Relaxed);
  1425. let (_container, url) = redis_container(Vec::new()).await?;
  1426. let (mut _conn, store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1427. let outcome: Result<(), redis::RedisError> = retry_op!(&mut _conn, store.retry_budget(), async {
  1428. ATTEMPTS.fetch_add(1, AtomicOrdering::Relaxed);
  1429. Err::<(), redis::RedisError>(redis::RedisError::from((
  1430. redis::ErrorKind::Server(redis::ServerErrorKind::CrossSlot),
  1431. "slot",
  1432. )))
  1433. });
  1434. match outcome {
  1435. Err(error)
  1436. if classify_redis(&error) == ErrorClass::Permanent
  1437. && ATTEMPTS.load(AtomicOrdering::Relaxed) == 1 => {}
  1438. _ => {
  1439. return Err(TestError::Unexpected(
  1440. "permanent errors must not retry".to_owned(),
  1441. ));
  1442. }
  1443. }
  1444. Ok(())
  1445. }
  1446. /// The record write is a single atomic `HSET`+`PEXPIRE` script: a record
  1447. /// observed after [`hset_record`] always carries both its fields AND a live
  1448. /// TTL, and a rewrite re-arms the expiry (never a persistent key).
  1449. #[tokio::test]
  1450. async fn store_hset_record_writes_fields_and_ttl() -> TestResult {
  1451. let (_container, url) = redis_container(Vec::new()).await?;
  1452. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1453. let key = unique("hset-record");
  1454. let ttl = Duration::from_secs(300);
  1455. let pairs = vec![
  1456. ("client_id".to_owned(), "client-1".to_owned()),
  1457. ("scope".to_owned(), "orders:read".to_owned()),
  1458. ];
  1459. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1460. let record = hget_record(&mut conn, &key).await?;
  1461. if record
  1462. .as_ref()
  1463. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  1464. {
  1465. return Err(TestError::Unexpected(
  1466. "written record must carry its fields".to_owned(),
  1467. ));
  1468. }
  1469. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)?;
  1470. // Rewrite: a shorter lifetime must be observable, proving the write
  1471. // re-arms the TTL and does not leave the previous expiry in place.
  1472. let rewrite = Duration::from_secs(120);
  1473. let updated = vec![
  1474. ("client_id".to_owned(), "client-2".to_owned()),
  1475. ("scope".to_owned(), "orders:read".to_owned()),
  1476. ];
  1477. hset_record(&mut conn, &key, &updated, rewrite).await?;
  1478. let record = hget_record(&mut conn, &key).await?;
  1479. if record
  1480. .as_ref()
  1481. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-2"))
  1482. {
  1483. return Err(TestError::Unexpected(
  1484. "rewrite must replace the field value".to_owned(),
  1485. ));
  1486. }
  1487. assert_ttl_within(pttl_ms(&mut conn, &key).await?, rewrite)?;
  1488. // A key whose TTL was stripped must regain a live expiry when rewritten
  1489. // through the atomic write, so no record can remain persistent.
  1490. let _: () = redis::cmd("PERSIST")
  1491. .arg(&key)
  1492. .query_async(&mut conn)
  1493. .await?;
  1494. if pttl_ms(&mut conn, &key).await? != -1 {
  1495. return Err(TestError::Unexpected(
  1496. "PERSIST must strip the TTL for the simulation".to_owned(),
  1497. ));
  1498. }
  1499. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1500. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  1501. }
  1502. /// A field-less `HSET` is a Redis arity error; the empty-pairs guard falls
  1503. /// back to the TTL touch alone, so an existing record keeps its fields and a
  1504. /// live expiry instead of becoming persistent (or erroring out).
  1505. #[tokio::test]
  1506. async fn store_hset_record_empty_pairs_keeps_ttl() -> TestResult {
  1507. let (_container, url) = redis_container(Vec::new()).await?;
  1508. let (mut conn, _store) = direct_store(&url, DurabilityMode::WaitAof).await?;
  1509. let key = unique("hset-empty");
  1510. let ttl = Duration::from_secs(300);
  1511. let pairs = vec![("client_id".to_owned(), "client-1".to_owned())];
  1512. hset_record(&mut conn, &key, &pairs, ttl).await?;
  1513. hset_record(&mut conn, &key, &[], ttl).await?;
  1514. let record = hget_record(&mut conn, &key).await?;
  1515. if record
  1516. .as_ref()
  1517. .is_none_or(|fields| fields.get("client_id").map(String::as_str) != Some("client-1"))
  1518. {
  1519. return Err(TestError::Unexpected(
  1520. "empty rewrite must preserve the fields".to_owned(),
  1521. ));
  1522. }
  1523. assert_ttl_within(pttl_ms(&mut conn, &key).await?, ttl)
  1524. }