1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod autotest_generated {
5
    use alloc::string::String;
6

            
7
    use super::*;
8

            
9
    // Payloads chosen to break naive C-string / byte-length assumptions in the
10
    // FFI layer: interior NUL, C0/C1 controls, CRLF.
11
    const NASTY_BYTES: &str = "pw\0with\u{1}nul\u{7f}\r\n\t";
12
    // Combining marks, RTL overrides, replacement char and the maximum scalar.
13
    const NASTY_UNICODE: &str =
14
        "πŸ”‘πŸ— ΠΊΠ»ΡŽΡ‡ 鍡 مفΨͺΨ§Ψ­ e\u{301}\u{202e}terces\u{202c}\u{fffd}\u{10ffff}";
15

            
16
    /// Every `KeyringResult` variant, in declaration order.
17
    fn all_variants() -> [KeyringResult; 7] {
18
        [
19
            KeyringResult::Stored,
20
            KeyringResult::Retrieved(AzString::from("s3cr3t")),
21
            KeyringResult::Deleted,
22
            KeyringResult::NotFound,
23
            KeyringResult::Denied,
24
            KeyringResult::Unavailable,
25
            KeyringResult::Error,
26
        ]
27
    }
28

            
29
    /// The documented contract, restated independently of the impl:
30
    /// `(is_ok, has_secret)`. The exhaustive match is deliberate β€” adding a
31
    /// variant to `KeyringResult` breaks this and forces the truth tables
32
    /// below to be revisited rather than silently under-testing the new one.
33
    fn expected(r: &KeyringResult) -> (bool, bool) {
34
        match r {
35
            KeyringResult::Stored => (true, false),
36
            KeyringResult::Retrieved(_) => (true, true),
37
            KeyringResult::Deleted => (true, false),
38
            KeyringResult::NotFound => (false, false),
39
            KeyringResult::Denied => (false, false),
40
            KeyringResult::Unavailable => (false, false),
41
            KeyringResult::Error => (false, false),
42
        }
43
    }
44

            
45
    // ---- getter: KeyringResult::secret ------------------------------------
46

            
47
    #[test]
48
    fn secret_returns_the_exact_payload_of_retrieved() {
49
        let r = KeyringResult::Retrieved(AzString::from("hunter2"));
50
        assert_eq!(
51
            r.secret().expect("Retrieved must yield a secret").as_str(),
52
            "hunter2"
53
        );
54
    }
55

            
56
    #[test]
57
    fn secret_is_none_for_every_non_retrieved_variant() {
58
        for r in &all_variants() {
59
            let has_secret = expected(r).1;
60
            assert_eq!(
61
                r.secret().is_some(),
62
                has_secret,
63
                "secret() disagrees with the documented contract for {r:?}"
64
            );
65
        }
66
    }
67

            
68
    #[test]
69
    fn secret_of_an_empty_payload_is_some_empty_not_none() {
70
        // An empty secret is a *present* secret. Collapsing it to `None` would
71
        // make a stored-empty-string indistinguishable from `NotFound`.
72
        let r = KeyringResult::Retrieved(AzString::from(""));
73
        assert_eq!(
74
            r.secret()
75
                .expect("empty payload is still a payload")
76
                .as_str(),
77
            ""
78
        );
79
        assert!(r.is_ok());
80

            
81
        let d = KeyringResult::Retrieved(AzString::default());
82
        assert_eq!(
83
            d.secret()
84
                .expect("default payload is still a payload")
85
                .as_str(),
86
            ""
87
        );
88
        assert!(d.is_ok());
89
    }
90

            
91
    #[test]
92
    fn secret_preserves_interior_nul_and_control_bytes() {
93
        let r = KeyringResult::Retrieved(AzString::from(NASTY_BYTES));
94
        let s = r.secret().expect("Retrieved must yield a secret");
95
        assert_eq!(s.as_str(), NASTY_BYTES);
96
        // Byte-exact: nothing truncated at the NUL, nothing re-encoded.
97
        assert_eq!(s.as_str().as_bytes(), NASTY_BYTES.as_bytes());
98
        assert_eq!(s.as_str().len(), NASTY_BYTES.len());
99
    }
100

            
101
    #[test]
102
    fn secret_preserves_multibyte_and_max_scalar_boundaries() {
103
        let r = KeyringResult::Retrieved(AzString::from(NASTY_UNICODE));
104
        let s = r.secret().expect("Retrieved must yield a secret");
105
        // `AzString::as_str` is `from_utf8_unchecked`, so a byte-level mangling
106
        // here would be UB rather than a clean error β€” assert byte equality.
107
        assert_eq!(s.as_str(), NASTY_UNICODE);
108
        assert_eq!(s.as_str().as_bytes(), NASTY_UNICODE.as_bytes());
109
        assert_eq!(s.as_str().chars().count(), NASTY_UNICODE.chars().count());
110
        assert!(s.as_str().ends_with('\u{10ffff}'));
111
    }
112

            
113
    #[test]
114
    fn secret_handles_a_megabyte_payload() {
115
        let big = "k".repeat(1 << 20);
116
        let r = KeyringResult::Retrieved(AzString::from(big.clone()));
117
        let s = r.secret().expect("Retrieved must yield a secret");
118
        assert_eq!(s.as_str().len(), 1 << 20);
119
        assert_eq!(s.as_str(), big.as_str());
120
        assert!(r.is_ok());
121
    }
122

            
123
    #[test]
124
    fn secret_borrows_the_payload_in_place_and_is_repeatable() {
125
        let r = KeyringResult::Retrieved(AzString::from("borrow-me"));
126
        let inner: &AzString = match &r {
127
            KeyringResult::Retrieved(s) => s,
128
            other => unreachable!("constructed Retrieved, got {other:?}"),
129
        };
130

            
131
        let first = r.secret().expect("Retrieved must yield a secret");
132
        assert!(
133
            core::ptr::eq(first, inner),
134
            "secret() must borrow the payload, not hand back a copy"
135
        );
136

            
137
        // Repeated calls are stable: same AzString, same backing buffer.
138
        let second = r.secret().expect("secret() must be repeatable");
139
        assert!(core::ptr::eq(first, second));
140
        assert_eq!(first.as_str().as_ptr(), second.as_str().as_ptr());
141
    }
142

            
143
    // ---- predicate: KeyringResult::is_ok ----------------------------------
144

            
145
    #[test]
146
    fn is_ok_truth_table_is_exhaustive() {
147
        for r in &all_variants() {
148
            let want = expected(r).0;
149
            assert_eq!(r.is_ok(), want, "is_ok() wrong for {r:?}");
150
        }
151

            
152
        // Spelled out as well, so a mis-edited `expected()` can't hide a bug.
153
        assert!(KeyringResult::Stored.is_ok());
154
        assert!(KeyringResult::Retrieved(AzString::from("x")).is_ok());
155
        assert!(KeyringResult::Deleted.is_ok());
156
        assert!(!KeyringResult::NotFound.is_ok());
157
        assert!(!KeyringResult::Denied.is_ok());
158
        assert!(!KeyringResult::Unavailable.is_ok());
159
        assert!(!KeyringResult::Error.is_ok());
160
    }
161

            
162
    #[test]
163
    fn is_ok_is_independent_of_the_retrieved_payload() {
164
        let payloads = [
165
            String::new(),
166
            String::from(NASTY_BYTES),
167
            String::from(NASTY_UNICODE),
168
            "a".repeat(100_000),
169
        ];
170
        for p in payloads {
171
            assert!(
172
                KeyringResult::Retrieved(AzString::from(p)).is_ok(),
173
                "Retrieved is a success outcome whatever it carries"
174
            );
175
        }
176
    }
177

            
178
    #[test]
179
    fn is_ok_and_secret_never_contradict_each_other() {
180
        for r in &all_variants() {
181
            // A secret can only come from a success; a failure never carries one.
182
            if r.secret().is_some() {
183
                assert!(r.is_ok(), "{r:?} yielded a secret but reports failure");
184
            }
185
            if !r.is_ok() {
186
                assert!(r.secret().is_none(), "failure {r:?} yielded a secret");
187
            }
188
        }
189
    }
190

            
191
    #[test]
192
    fn accessors_are_pure() {
193
        for r in &all_variants() {
194
            let before = r.clone();
195
            for _ in 0..8 {
196
                assert_eq!(r.is_ok(), before.is_ok());
197
                assert_eq!(r.secret().is_some(), before.secret().is_some());
198
            }
199
            assert_eq!(*r, before, "accessors must not mutate the receiver");
200
        }
201
    }
202

            
203
    // ---- clone/drop: AzString carries an FFI destructor ------------------
204

            
205
    #[test]
206
    fn dropping_a_clone_leaves_the_original_payload_readable() {
207
        let payload = "πŸ” secret-that-must-survive";
208
        let original = KeyringResult::Retrieved(AzString::from(payload));
209

            
210
        for _ in 0..1000 {
211
            let c = original.clone();
212
            assert_eq!(
213
                c.secret().expect("clone keeps the payload").as_str(),
214
                payload
215
            );
216
            // A shallow clone would free the original's buffer right here.
217
            drop(c);
218
        }
219

            
220
        assert_eq!(
221
            original
222
                .secret()
223
                .expect("original survives 1000 clone/drop cycles")
224
                .as_str(),
225
            payload
226
        );
227
        assert!(original.is_ok());
228
    }
229

            
230
    #[test]
231
    fn dropping_the_original_leaves_the_clone_payload_readable() {
232
        let payload = NASTY_UNICODE;
233
        let original = KeyringResult::Retrieved(AzString::from(payload));
234
        let clone = original.clone();
235
        drop(original);
236
        assert_eq!(
237
            clone.secret().expect("clone owns its payload").as_str(),
238
            payload
239
        );
240
    }
241

            
242
    #[test]
243
    fn eq_is_sensitive_to_both_variant_and_payload() {
244
        assert_eq!(
245
            KeyringResult::Retrieved(AzString::from("a")),
246
            KeyringResult::Retrieved(AzString::from("a"))
247
        );
248
        assert_ne!(
249
            KeyringResult::Retrieved(AzString::from("a")),
250
            KeyringResult::Retrieved(AzString::from("b"))
251
        );
252
        // Empty payload must not compare equal to a payload-less success.
253
        assert_ne!(
254
            KeyringResult::Retrieved(AzString::from("")),
255
            KeyringResult::Stored
256
        );
257
        assert_ne!(KeyringResult::NotFound, KeyringResult::Denied);
258
        assert_ne!(KeyringResult::Unavailable, KeyringResult::Error);
259
        assert_eq!(KeyringResult::Deleted, KeyringResult::Deleted);
260
    }
261

            
262
    // ---- round-trip: OptionKeyringResult FFI wrapper ----------------------
263

            
264
    #[test]
265
    fn option_wrapper_round_trips_none_and_every_variant() {
266
        let none: OptionKeyringResult = Option::<KeyringResult>::None.into();
267
        assert!(none.is_none());
268
        assert_eq!(Option::<KeyringResult>::from(none), None);
269
        assert!(OptionKeyringResult::default().is_none());
270

            
271
        for r in all_variants() {
272
            let wrapped: OptionKeyringResult = Some(r.clone()).into();
273
            let back: Option<KeyringResult> = wrapped.into();
274
            assert_eq!(
275
                back,
276
                Some(r),
277
                "encode/decode through OptionKeyringResult lost data"
278
            );
279
        }
280
    }
281

            
282
    #[test]
283
    fn option_wrapper_accessors_agree_with_each_other() {
284
        let payload = "round-trip-me";
285
        let some = OptionKeyringResult::Some(KeyringResult::Retrieved(AzString::from(payload)));
286
        assert!(some.is_some());
287
        assert!(!some.is_none());
288
        assert_eq!(
289
            some.as_option()
290
                .and_then(KeyringResult::secret)
291
                .map(AzString::as_str),
292
            Some(payload)
293
        );
294
        assert_eq!(some.as_ref(), some.as_option());
295

            
296
        let none = OptionKeyringResult::None;
297
        assert!(none.is_none());
298
        assert!(!none.is_some());
299
        assert!(none.as_option().is_none());
300
    }
301

            
302
    #[test]
303
    fn option_wrapper_into_option_clones_and_leaves_the_wrapper_intact() {
304
        // `into_option(&self)` takes a reference and clones β€” calling it twice
305
        // must not double-free or hollow out the wrapper.
306
        let payload = NASTY_BYTES;
307
        let wrapped = OptionKeyringResult::Some(KeyringResult::Retrieved(AzString::from(payload)));
308

            
309
        let first = wrapped.into_option().expect("Some stays Some");
310
        let second = wrapped
311
            .into_option()
312
            .expect("into_option must not consume the wrapper");
313
        assert_eq!(first, second);
314
        assert_eq!(first.secret().expect("payload survives").as_str(), payload);
315
        drop(first);
316
        assert_eq!(
317
            second
318
                .secret()
319
                .expect("payload survives its sibling")
320
                .as_str(),
321
            payload
322
        );
323
        drop(second);
324
        assert_eq!(
325
            wrapped
326
                .as_option()
327
                .and_then(KeyringResult::secret)
328
                .map(AzString::as_str),
329
            Some(payload),
330
            "wrapper must still own its payload after both clones died"
331
        );
332
    }
333

            
334
    #[test]
335
    fn option_wrapper_replace_returns_the_previous_value() {
336
        let mut o = OptionKeyringResult::None;
337
        assert_eq!(o.replace(KeyringResult::Stored), OptionKeyringResult::None);
338

            
339
        let prev = o.replace(KeyringResult::Retrieved(AzString::from("new")));
340
        assert_eq!(prev, OptionKeyringResult::Some(KeyringResult::Stored));
341
        assert_eq!(
342
            o.as_option()
343
                .and_then(KeyringResult::secret)
344
                .map(AzString::as_str),
345
            Some("new")
346
        );
347
    }
348

            
349
    #[test]
350
    fn option_wrapper_as_mut_can_overwrite_a_retrieved_payload() {
351
        let mut o = OptionKeyringResult::Some(KeyringResult::Retrieved(AzString::from("old")));
352
        if let Some(slot) = o.as_mut() {
353
            *slot = KeyringResult::Deleted; // drops the old AzString in place
354
        }
355
        assert_eq!(o.as_option(), Some(&KeyringResult::Deleted));
356
        assert!(o.as_option().expect("still Some").is_ok());
357
        assert!(o.as_option().expect("still Some").secret().is_none());
358
    }
359

            
360
    // ---- KeyringRequest: payload-carrying FFI enum ------------------------
361

            
362
    #[test]
363
    fn request_equality_is_sensitive_to_key_secret_and_biometry_flag() {
364
        let store = KeyringRequest::Store {
365
            key: AzString::from("k"),
366
            secret: AzString::from("s"),
367
            require_biometry: false,
368
        };
369
        assert_eq!(store, store.clone());
370

            
371
        assert_ne!(
372
            store,
373
            KeyringRequest::Store {
374
                key: AzString::from("k"),
375
                secret: AzString::from("s"),
376
                require_biometry: true,
377
            },
378
            "require_biometry changes the stored access control β€” it must not be ignored"
379
        );
380
        assert_ne!(
381
            store,
382
            KeyringRequest::Store {
383
                key: AzString::from("k"),
384
                secret: AzString::from("other"),
385
                require_biometry: false,
386
            }
387
        );
388
        assert_ne!(
389
            KeyringRequest::Get {
390
                key: AzString::from("k")
391
            },
392
            KeyringRequest::Delete {
393
                key: AzString::from("k")
394
            },
395
            "a read and a delete of the same key are different operations"
396
        );
397
        assert_ne!(
398
            KeyringRequest::Get {
399
                key: AzString::from("a")
400
            },
401
            KeyringRequest::Get {
402
                key: AzString::from("b")
403
            }
404
        );
405
    }
406

            
407
    #[test]
408
    fn request_payloads_survive_clone_and_drop() {
409
        let key = "πŸ”‘".repeat(10_000);
410
        let req = KeyringRequest::Store {
411
            key: AzString::from(key.clone()),
412
            secret: AzString::from(NASTY_BYTES),
413
            require_biometry: true,
414
        };
415

            
416
        let clone = req.clone();
417
        drop(req);
418

            
419
        match &clone {
420
            KeyringRequest::Store {
421
                key: k,
422
                secret: s,
423
                require_biometry,
424
            } => {
425
                assert_eq!(k.as_str(), key.as_str());
426
                assert_eq!(s.as_str(), NASTY_BYTES);
427
                assert!(*require_biometry);
428
            }
429
            other => unreachable!("constructed Store, got {other:?}"),
430
        }
431
    }
432

            
433
    #[test]
434
    fn request_accepts_empty_keys_without_panicking() {
435
        // An empty key is nonsense to a backend, but the POD type must still
436
        // construct, compare and drop cleanly rather than blow up in the callback.
437
        let empty = KeyringRequest::Get {
438
            key: AzString::from(""),
439
        };
440
        assert_eq!(
441
            empty,
442
            KeyringRequest::Get {
443
                key: AzString::default()
444
            }
445
        );
446
        assert_ne!(
447
            empty,
448
            KeyringRequest::Get {
449
                key: AzString::from("k")
450
            }
451
        );
452
    }
453
}