Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_steel/tests/member_invite.rs

9.9 KiB, 1 run

created by r1870400018:72163, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! `srv::member::invite` against a real Ozone store, under the target directory rather than
2//! `/tmp`.
3//!
4//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
5//! Anthropic Claude
6
7mod member {
8
9 use oxedyne_fe2o3_steel::{
10 app::{
11 constant as app_const,
12 server::VhostDb,
13 },
14 srv::{
15 context::new_db,
16 id::Uid,
17 member::{
18 Clock,
19 Token,
20 invite::{
21 InviteCfg,
22 Invites,
23 },
24 },
25 },
26 };
27
28 use oxedyne_fe2o3_core::prelude::*;
29 use oxedyne_fe2o3_iop_db::api::{
30 Database,
31 ScanOpts,
32 };
33 use oxedyne_fe2o3_jdat::prelude::*;
34
35 use std::{
36 path::{
37 Path,
38 PathBuf,
39 },
40 sync::{
41 atomic::{
42 AtomicU64,
43 Ordering,
44 },
45 Arc,
46 RwLock,
47 },
48 time::Duration,
49 };
50
51 const T0: u64 = 1_800_000_000;
52
53 struct Store {
54 db: (Arc<RwLock<VhostDb>>, Uid),
55 root: PathBuf,
56 }
57
58 impl Drop for Store {
59 fn drop(&mut self) {
60 let _ = std::fs::remove_dir_all(&self.root);
61 }
62 }
63
64 fn store(label: &str) -> Outcome<Store> {
65 let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
66 .join(fmt!("member-invite-{}-{}", label, std::process::id()));
67 let _ = std::fs::remove_dir_all(&root);
68 res!(std::fs::create_dir_all(&root), IO, File);
69 let mut db = res!(new_db(&root, &[3u8; 32], false));
70 res!(db.start("member_invite_test"));
71 res!(ok!(db.updated_api()).activate_gc(true));
72 std::thread::sleep(Duration::from_millis(200));
73 res!(db.api().ping_bots(app_const::GET_DATA_WAIT));
74 Ok(Store { db: (Arc::new(RwLock::new(db)), Uid::default()), root })
75 }
76
77 fn cfg() -> InviteCfg {
78 InviteCfg {
79 prefix: fmt!("t/"),
80 ttl_secs: 100,
81 max_open: 3,
82 }
83 }
84
85 fn clock() -> (Clock, Arc<AtomicU64>) {
86 let t = Arc::new(AtomicU64::new(T0));
87 (Clock::Manual(t.clone()), t)
88 }
89
90 fn keys(s: &Store) -> Outcome<Vec<String>> {
91 let dbr = lock_read!(s.db.0);
92 let rows = res!(dbr.scan(&ScanOpts::with_str_prefix("t/i/"), None));
93 let mut out = Vec::new();
94 for (k, _, _) in rows {
95 if let Dat::Str(name) = k {
96 // A scan lists a deleted key whose tombstone it meets; only live ones count.
97 if res!(dbr.get(&Dat::Str(name.clone()), None)).is_some() {
98 out.push(name);
99 }
100 }
101 }
102 Ok(out)
103 }
104
105 fn files_contain(dir: &Path, needle: &[u8]) -> Outcome<bool> {
106 for entry in res!(std::fs::read_dir(dir), IO, File) {
107 let p = res!(entry, IO, File).path();
108 if p.is_dir() {
109 if res!(files_contain(&p, needle)) {
110 return Ok(true);
111 }
112 } else {
113 let bytes = res!(std::fs::read(&p), IO, File);
114 if bytes.windows(needle.len()).any(|w| w == needle) {
115 return Ok(true);
116 }
117 }
118 }
119 Ok(false)
120 }
121
122 fn person(name: &str) -> Dat {
123 let mut m = DaticleMap::new();
124 m.insert(dat!("person"), dat!(name.to_string()));
125 m.insert(dat!("kind"), dat!("add-device"));
126 Dat::Map(m)
127 }
128
129 fn is_for(d: &Dat, name: &str) -> bool {
130 match d {
131 Dat::Map(m) => m.get(&dat!("person")) == Some(&dat!(name.to_string())),
132 _ => false,
133 }
134 }
135
136 #[test]
137 fn issue_and_take_once() -> Outcome<()> {
138 let s = res!(store("once"));
139 let (clk, _) = clock();
140 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
141 let tok = res!(iv.issue(&s.db, person("fred")));
142 assert_eq!(res!(iv.open_count()), 1);
143 // A peek shows it and leaves it open.
144 let seen = res!(res!(iv.peek(&tok)).ok_or_else(|| err!("A fresh invite must peek."; Test)));
145 assert_eq!(seen.payload, person("fred"));
146 assert_eq!(seen.exp, T0 + 100);
147 // The link form round-trips, and a token never formats as its bytes.
148 let link = tok.to_hex();
149 let back = res!(Token::from_hex(&link));
150 let shown = fmt!("{:?} {:?} {:?}", tok, seen, iv.list());
151 assert!(!shown.to_lowercase().contains(&link.to_lowercase()), "{}", shown);
152
153 assert_eq!(res!(iv.take(&s.db, &back)), Some(person("fred")));
154 assert_eq!(res!(iv.take(&s.db, &tok)), None, "a second take");
155 assert!(res!(iv.peek(&tok)).is_none());
156 assert_eq!(res!(iv.open_count()), 0);
157 assert!(res!(keys(&s)).is_empty());
158 // Nor does it come back after a restart.
159 let (clk, _) = clock();
160 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
161 assert_eq!(res!(iv.take(&s.db, &tok)), None);
162 let stranger = res!(Token::from_hex(&"cd".repeat(32)));
163 assert_eq!(res!(iv.take(&s.db, &stranger)), None);
164 Ok(())
165 }
166
167 #[test]
168 fn an_invite_expires() -> Outcome<()> {
169 let s = res!(store("expiry"));
170 let (clk, t) = clock();
171 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
172 let a = res!(iv.issue(&s.db, person("a")));
173 t.store(T0 + 50, Ordering::SeqCst);
174 let _b = res!(iv.issue(&s.db, person("b")));
175 t.store(T0 + 100, Ordering::SeqCst);
176 assert!(res!(iv.peek(&a)).is_none(), "expired at issued + ttl");
177 assert_eq!(res!(iv.open_count()), 1);
178 assert_eq!(res!(iv.take(&s.db, &a)), None);
179 assert_eq!(res!(keys(&s)).len(), 1, "the expired record went with the take");
180 t.store(T0 + 150, Ordering::SeqCst);
181 assert_eq!(res!(iv.sweep(&s.db)), 1);
182 assert!(res!(keys(&s)).is_empty());
183 Ok(())
184 }
185
186 #[test]
187 fn max_open_refuses_until_one_goes() -> Outcome<()> {
188 let s = res!(store("cap"));
189 let (clk, t) = clock();
190 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
191 let first = res!(iv.issue(&s.db, person("a")));
192 let _ = res!(iv.issue(&s.db, person("b")));
193 let _ = res!(iv.issue(&s.db, person("c")));
194 assert!(iv.issue(&s.db, person("d")).is_err(), "a fourth past max_open 3");
195 assert_eq!(res!(keys(&s)).len(), 3);
196 assert!(res!(iv.take(&s.db, &first)).is_some());
197 let _ = res!(iv.issue(&s.db, person("d")));
198 // Expired invites hold no place: they are swept before the count.
199 t.store(T0 + 100, Ordering::SeqCst);
200 for n in ["e", "f", "g"] {
201 let _ = res!(iv.issue(&s.db, person(n)));
202 }
203 assert_eq!(res!(keys(&s)).len(), 3);
204 assert!(InviteCfg { max_open: 0, ..cfg() }.check().is_err());
205 assert!(InviteCfg { ttl_secs: 0, ..cfg() }.check().is_err());
206 Ok(())
207 }
208
209 #[test]
210 fn purge_by_payload_and_revoke_by_id() -> Outcome<()> {
211 let s = res!(store("purge"));
212 let (clk, _) = clock();
213 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
214 let f1 = res!(iv.issue(&s.db, person("fred")));
215 let f2 = res!(iv.issue(&s.db, person("fred")));
216 let jo = res!(iv.issue(&s.db, person("jo")));
217 assert_eq!(res!(iv.purge(&s.db, |d| is_for(d, "fred"))), 2);
218 assert_eq!(res!(iv.take(&s.db, &f1)), None);
219 assert_eq!(res!(iv.take(&s.db, &f2)), None);
220 assert_eq!(res!(keys(&s)).len(), 1);
221 // The purge holds across a restart.
222 let (clk, _) = clock();
223 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
224 assert_eq!(res!(iv.open_count()), 1);
225 let id = res!(iv.list())[0].id.clone();
226 assert!(res!(iv.revoke(&s.db, &id)));
227 assert!(!res!(iv.revoke(&s.db, &id)));
228 assert!(!res!(iv.revoke(&s.db, "not-an-id")));
229 assert_eq!(res!(iv.take(&s.db, &jo)), None);
230 assert!(res!(keys(&s)).is_empty());
231 Ok(())
232 }
233
234 #[test]
235 fn two_threads_taking_one_token_one_wins() -> Outcome<()> {
236 let s = res!(store("race"));
237 let (clk, _) = clock();
238 let iv = res!(Invites::load_with_clock(&s.db, InviteCfg { max_open: 50, ..cfg() }, clk));
239 for round in 0..20 {
240 let tok = res!(iv.issue(&s.db, person("fred")));
241 let link = tok.to_hex();
242 let wins: Vec<bool> = std::thread::scope(|sc| {
243 let hs: Vec<_> = (0..2).map(|_| {
244 let link = link.clone();
245 let (iv, db) = (&iv, &s.db);
246 sc.spawn(move || -> bool {
247 match Token::from_hex(&link) {
248 Ok(t) => matches!(iv.take(db, &t), Ok(Some(_))),
249 Err(_) => false,
250 }
251 })
252 }).collect();
253 hs.into_iter().map(|h| h.join().unwrap_or(false)).collect()
254 });
255 assert_eq!(wins.iter().filter(|w| **w).count(), 1, "round {}: {:?}", round, wins);
256 }
257 assert!(res!(keys(&s)).is_empty());
258 Ok(())
259 }
260
261 #[test]
262 fn the_store_holds_the_hash_and_never_the_token() -> Outcome<()> {
263 let s = res!(store("hash"));
264 let (clk, _) = clock();
265 let iv = res!(Invites::load_with_clock(&s.db, cfg(), clk));
266 let tok = res!(iv.issue(&s.db, person("fred")));
267 let id = res!(iv.list())[0].id.clone();
268 let link = tok.to_hex();
269 assert_eq!(res!(keys(&s)), vec![fmt!("t/i/{}", id)]);
270 assert_ne!(id.to_lowercase(), link.to_lowercase());
271 let raw = res!(oxedyne_fe2o3_text::base2x::HEX.from_str(&link));
272 assert!(!res!(files_contain(&s.root, &raw)), "the raw token is in the store's files");
273 assert!(!res!(files_contain(&s.root, link.as_bytes())), "the token's text is in the store's files");
274 Ok(())
275 }
276}