axess-core 0.11.0

Core implementation for the axess library. Session state machine, multi-factor authentication engine, Cedar Policy evaluation, and pluggable storage backends. Use the `axess` facade crate unless you need direct access to internals.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! `tests`: extracted from `pii.rs` per the
//! 200-LoC inline-test rule in AGENTS.md.

use super::*;

fn user(s: &str) -> UserId {
    axess_identity::testing::user(s)
}

fn tenant(s: &str) -> TenantId {
    axess_identity::testing::tenant(s)
}

/// Token wire format is `"pii:<uuid-hyphenated>"` and
/// round-trips through `parse`. This is the documented canonical
/// shape compatible with `gov-core::pii::PiiToken`; changing it is
/// a wire-break.
#[test]
fn token_wire_format_is_pii_colon_uuid() {
    let uuid = Uuid::nil();
    let token = PiiToken::from_uuid(uuid);
    assert_eq!(token.as_str(), "pii:00000000-0000-0000-0000-000000000000");

    let parsed = PiiToken::parse(token.as_str()).expect("round-trip parse");
    assert_eq!(parsed, token);
}

/// `is_well_formed` rejects shapes that wouldn't round-trip
/// through `new`. Stable rejection set so callers can use it as a
/// pre-store validation gate.
#[test]
fn is_well_formed_rejects_malformed() {
    // Missing prefix.
    assert!(!PiiToken::is_well_formed(
        "00000000-0000-0000-0000-000000000000"
    ));
    // Wrong prefix.
    assert!(!PiiToken::is_well_formed(
        "pii_00000000-0000-0000-0000-000000000000"
    ));
    // Non-UUID body.
    assert!(!PiiToken::is_well_formed("pii:not-a-uuid"));
    // Empty.
    assert!(!PiiToken::is_well_formed(""));
    assert!(!PiiToken::is_well_formed("pii:"));
    // Right shape.
    assert!(PiiToken::is_well_formed(
        "pii:00000000-0000-0000-0000-000000000000"
    ));
}

/// `record` → `resolve` round-trips the value plaintext;
/// the returned token is the same token now stored. Pins the
/// Memory backend's basic contract.
#[tokio::test]
async fn record_then_resolve_round_trips_value() {
    let store = MemoryDevicePiiStore::new();
    let now = Utc::now();
    let token = store
        .record(
            &user("u1"),
            &tenant("t1"),
            DevicePiiCategory::DisplayName,
            "Alice's iPhone".to_string(),
            now,
        )
        .await
        .unwrap();
    assert!(PiiToken::is_well_formed(token.as_str()));
    let value = store.resolve(&token, &tenant("t1")).await.unwrap();
    assert_eq!(value.as_deref(), Some("Alice's iPhone"));
}

/// Structural tenant rail. A mapping recorded under tenant
/// A is invisible to a resolve issued from tenant B, even when
/// the caller has the right token. Same shape as missing.
/// Without this rail, a multi-tenant deployment can leak PII via
/// token-guessing across tenants.
#[tokio::test]
async fn resolve_refuses_cross_tenant_lookup() {
    let store = MemoryDevicePiiStore::new();
    let token = store
        .record(
            &user("u1"),
            &tenant("alpha"),
            DevicePiiCategory::IpAddress,
            "203.0.113.42".to_string(),
            Utc::now(),
        )
        .await
        .unwrap();

    // Same-tenant resolve hits.
    let same = store.resolve(&token, &tenant("alpha")).await.unwrap();
    assert_eq!(same.as_deref(), Some("203.0.113.42"));

    // Cross-tenant resolve returns None; same as a missing token.
    let cross = store.resolve(&token, &tenant("beta")).await.unwrap();
    assert!(
        cross.is_none(),
        "cross-tenant lookup must be invisible, not leak the value"
    );
}

/// `erase_subject` deletes every mapping for the
/// `(subject, tenant)` pair, leaves other subjects' mappings
/// alone, and returns the count erased. Subsequent `resolve` of
/// an erased token returns `None` (forms the basis of the
/// `RedactedResolver` post-erasure contract).
#[tokio::test]
async fn erase_subject_removes_only_target_subject_mappings() {
    let store = MemoryDevicePiiStore::new();
    let now = Utc::now();
    let t = tenant("t1");

    // Two mappings for the target user across two categories.
    let alice_dn = store
        .record(
            &user("alice"),
            &t,
            DevicePiiCategory::DisplayName,
            "Alice".into(),
            now,
        )
        .await
        .unwrap();
    let alice_ip = store
        .record(
            &user("alice"),
            &t,
            DevicePiiCategory::IpAddress,
            "203.0.113.1".into(),
            now,
        )
        .await
        .unwrap();
    // One mapping for a different user that must NOT be touched.
    let bob_dn = store
        .record(
            &user("bob"),
            &t,
            DevicePiiCategory::DisplayName,
            "Bob".into(),
            now,
        )
        .await
        .unwrap();

    let erased = store.erase_subject(&user("alice"), &t).await.unwrap();
    assert_eq!(erased, 2, "must erase exactly Alice's 2 rows");

    // Alice's tokens no longer resolve.
    assert!(store.resolve(&alice_dn, &t).await.unwrap().is_none());
    assert!(store.resolve(&alice_ip, &t).await.unwrap().is_none());

    // Bob's mapping survives; erasure is per-subject, not per-tenant.
    assert_eq!(
        store.resolve(&bob_dn, &t).await.unwrap().as_deref(),
        Some("Bob"),
    );
}

/// `erase_subject` is also tenant-scoped. Erasing a
/// `(subject, tenantA)` pair must NOT touch a same-named subject
/// in `tenantB`: different tenants are different data subjects
/// from the controller's perspective.
#[tokio::test]
async fn erase_subject_is_tenant_scoped() {
    let store = MemoryDevicePiiStore::new();
    let alice_alpha = store
        .record(
            &user("alice"),
            &tenant("alpha"),
            DevicePiiCategory::DisplayName,
            "Alice@alpha".into(),
            Utc::now(),
        )
        .await
        .unwrap();
    let alice_beta = store
        .record(
            &user("alice"),
            &tenant("beta"),
            DevicePiiCategory::DisplayName,
            "Alice@beta".into(),
            Utc::now(),
        )
        .await
        .unwrap();

    let erased = store
        .erase_subject(&user("alice"), &tenant("alpha"))
        .await
        .unwrap();
    assert_eq!(erased, 1);

    assert!(
        store
            .resolve(&alice_alpha, &tenant("alpha"))
            .await
            .unwrap()
            .is_none()
    );
    assert_eq!(
        store
            .resolve(&alice_beta, &tenant("beta"))
            .await
            .unwrap()
            .as_deref(),
        Some("Alice@beta"),
        "erasure in tenant alpha must not touch tenant beta"
    );
}

/// `list_for_subject` drives the Art 20 portability export.
/// Returns every mapping for the `(subject, tenant)` pair, no
/// others. Tenant-scoped (mirrors erase_subject's scoping).
#[tokio::test]
async fn list_for_subject_returns_all_mappings_in_tenant() {
    let store = MemoryDevicePiiStore::new();
    let t = tenant("t1");
    let now = Utc::now();
    store
        .record(
            &user("alice"),
            &t,
            DevicePiiCategory::DisplayName,
            "Alice".into(),
            now,
        )
        .await
        .unwrap();
    store
        .record(
            &user("alice"),
            &t,
            DevicePiiCategory::UserAgentString,
            "Mozilla/5.0".into(),
            now,
        )
        .await
        .unwrap();
    store
        .record(
            &user("bob"),
            &t,
            DevicePiiCategory::DisplayName,
            "Bob".into(),
            now,
        )
        .await
        .unwrap();

    let alice_rows = store.list_for_subject(&user("alice"), &t).await.unwrap();
    assert_eq!(
        alice_rows.len(),
        2,
        "portability export must include all of Alice's mappings"
    );
    assert!(
        alice_rows.iter().all(|m| m.subject_id == user("alice")),
        "list_for_subject must not leak other subjects' rows"
    );
}

/// The auto-impl of `DevicePiiResolver` for
/// `DevicePiiStore` collapses missing mappings to the canonical
/// `[redacted]` placeholder. Same shape regardless of whether the
/// row was erased, never existed, or is cross-tenant.
#[tokio::test]
async fn resolver_returns_redacted_for_missing_token() {
    let store = MemoryDevicePiiStore::new();
    let bogus = PiiToken::new();
    let resolved = store
        .resolve_or_redacted(&bogus, &tenant("t1"))
        .await
        .unwrap();
    assert_eq!(resolved, REDACTED_PLACEHOLDER);
}

/// The auto-impl of `DevicePiiResolver` returns the real
/// value when present. Pins that the redacted-on-missing
/// behaviour is conditional, not unconditional.
#[tokio::test]
async fn resolver_returns_real_value_when_present() {
    let store = MemoryDevicePiiStore::new();
    let token = store
        .record(
            &user("u1"),
            &tenant("t1"),
            DevicePiiCategory::DisplayName,
            "Alice".into(),
            Utc::now(),
        )
        .await
        .unwrap();
    let resolved = store
        .resolve_or_redacted(&token, &tenant("t1"))
        .await
        .unwrap();
    assert_eq!(resolved, "Alice");
}

/// `RedactedResolver` always returns the placeholder,
/// regardless of whether the token would resolve in some other
/// store. Pins the post-erasure / fail-safe contract.
#[tokio::test]
async fn redacted_resolver_unconditionally_returns_placeholder() {
    let resolver = RedactedResolver;
    let token = PiiToken::new();
    let resolved = resolver
        .resolve_or_redacted(&token, &tenant("t1"))
        .await
        .unwrap();
    assert_eq!(resolved, REDACTED_PLACEHOLDER);
}

/// `DevicePiiCategory::as_str` wire strings are stable.
/// Pinned for the same reason `AuthEventType` strings are pinned:
/// SQL backends and SOC dashboards key off these exact strings.
#[test]
fn category_wire_strings_are_stable() {
    for (variant, expected) in [
        (DevicePiiCategory::DisplayName, "display_name"),
        (DevicePiiCategory::UserAgentString, "user_agent_string"),
        (DevicePiiCategory::AcceptLanguage, "accept_language"),
        (DevicePiiCategory::IpAddress, "ip_address"),
        (DevicePiiCategory::ScreenMetrics, "screen_metrics"),
        (DevicePiiCategory::Other, "other"),
    ] {
        assert_eq!(variant.as_str(), expected);
    }
}

#[test]
fn pii_token_display_matches_as_str() {
    let token = PiiToken::new();
    assert_eq!(format!("{token}"), token.as_str());
}

#[tokio::test]
async fn memory_store_len_and_is_empty_track_inserts() {
    let store = MemoryDevicePiiStore::new();
    assert_eq!(store.len(), 0);
    assert!(store.is_empty());

    let token = PiiToken::new();
    let mapping = DevicePiiMapping {
        token: token.clone(),
        subject_id: axess_identity::testing::user("u-pii"),
        tenant_id: axess_identity::testing::tenant("t-pii"),
        category: DevicePiiCategory::IpAddress,
        value: "1.2.3.4".to_string(),
        created_at: chrono::Utc::now(),
    };
    store.mappings.insert(token, mapping);
    assert_eq!(store.len(), 1);
    assert!(!store.is_empty());
}

/// Braced, URN, hyphenless and uppercase spellings of a valid UUID are the
/// same UUID but a different string, so they would key a second mapping.
#[test]
fn parse_refuses_non_canonical_uuid_spellings() {
    let u = "6f9619ff-8b86-d011-b42d-00c04fc964ff";
    assert!(PiiToken::parse(&format!("pii:{u}")).is_some());
    for bad in [
        format!("pii:{}", u.to_uppercase()),
        format!("pii:{}", u.replace('-', "")),
        format!("pii:{{{u}}}"),
        format!("pii:urn:uuid:{u}"),
    ] {
        assert!(PiiToken::parse(&bad).is_none(), "{bad} must be refused");
        assert!(!PiiToken::is_well_formed(&bad));
    }
}

/// Tokens come from the injected RNG: the same seed mints the same token
/// sequence, and the token is the v4 UUID built from the RNG's first 16
/// bytes.
#[tokio::test]
async fn tokens_follow_the_injected_rng() {
    use axess_rng::SecureRng;
    use axess_rng::testing::MockRng;
    let mint = |seed| MemoryDevicePiiStore::new().with_rng(std::sync::Arc::new(MockRng::new(seed)));
    let record = |store: MemoryDevicePiiStore| async move {
        store
            .record(
                &user("u"),
                &tenant("t"),
                DevicePiiCategory::DisplayName,
                "v".into(),
                Utc::now(),
            )
            .await
            .unwrap()
    };
    let (a, b, c) = (
        record(mint(5)).await,
        record(mint(5)).await,
        record(mint(6)).await,
    );
    assert_eq!(a, b);
    assert_ne!(a, c);

    let mut bytes = [0u8; 16];
    MockRng::new(5).fill_bytes(&mut bytes);
    let expected = uuid::Builder::from_random_bytes(bytes).into_uuid();
    assert_eq!(a, PiiToken::from_uuid(expected));
    assert!(PiiToken::is_well_formed(a.as_str()));
}

/// The portability export lists mappings oldest first, whatever order the
/// map iterates in.
#[tokio::test]
async fn list_for_subject_is_ordered_by_creation_time() {
    use chrono::{Duration, TimeZone};
    let store = MemoryDevicePiiStore::new();
    let base = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
    // Recorded newest first so insertion order is the reverse of age.
    for i in (0..40i64).rev() {
        store
            .record(
                &user("u"),
                &tenant("t"),
                DevicePiiCategory::DisplayName,
                format!("v{i}"),
                base + Duration::minutes(i),
            )
            .await
            .unwrap();
    }
    let rows = store
        .list_for_subject(&user("u"), &tenant("t"))
        .await
        .unwrap();
    let values: Vec<String> = rows.into_iter().map(|m| m.value).collect();
    let expected: Vec<String> = (0..40).map(|i| format!("v{i}")).collect();
    assert_eq!(values, expected);
}