ic-auth 0.41.1

Portable authentication, delegation proof verification and local session machinery
Documentation
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Persistent session admission, replay, bounded cleanup and reopen behavior.
#![cfg(all(feature = "persistent", feature = "portable-signature-verification"))]
mod support;
use ic_auth::{
    persistent::{
        StoreError,
        receiver::{BudgetPolicy, LoginLimits, ReceiverConfig, ReceiverStore},
    },
    portable::{LoginRevocationError, ValidatedGrants},
    portable_credential::PortableVerificationContext,
    portable_signature::PreparedIssuerKey,
    session::{
        RequiredScopes, SessionAdmissionContext, SessionContext, SessionError, SessionEstablished,
        SessionLimits, SessionPolicy,
    },
    session_request::{SessionRequest, SessionTtlPolicy},
};
use ic_auth_protocol_types::*;
use ic_platform::ed25519::SigningKey;
use ic_storage::{
    StableKey, StorageConfig, VectorMemory,
    testing::{MeteredMemory, fixture_runtime},
};

type Backing = MeteredMemory<VectorMemory>;
const NOW: u64 = 10_000_000_000;
fn memory(backing: Backing) -> ic_auth::persistent::receiver::ReceiverMemory<Backing> {
    let runtime = fixture_runtime(
        backing,
        "auth",
        "auth.",
        &["auth.receiver.v1", "auth.metadata.v1", "auth.callers.v1"],
        StorageConfig::default(),
    )
    .unwrap();
    let open = |key| {
        runtime
            .open_memory(&StableKey::parse(key).unwrap())
            .unwrap()
    };
    ic_auth::persistent::receiver::ReceiverMemory {
        state: ic_auth::persistent::StoreMemory {
            records: open("auth.receiver.v1"),
            metadata: open("auth.metadata.v1"),
        },
        callers: open("auth.callers.v1"),
    }
}
fn configuration(audience: AudienceId, sessions: usize, bytes: usize) -> ReceiverConfig {
    configuration_with_costs(
        audience,
        sessions,
        bytes,
        ic_auth::admission_budget::VerificationCosts {
            ed25519: 1,
            certified: 1,
        },
    )
}
fn configuration_with_costs(
    audience: AudienceId,
    sessions: usize,
    bytes: usize,
    costs: ic_auth::admission_budget::VerificationCosts,
) -> ReceiverConfig {
    ReceiverConfig::new(
        audience,
        SessionLimits::new(sessions, 64, 32, bytes).unwrap(),
        LoginLimits {
            admitted: 16,
            unknown: 4,
            maximum_ttl_ns: 90 * 86_400_000_000_000,
            devices_per_account: 8,
        },
        BudgetPolicy {
            burst: 8,
            refill_interval_ns: 1,
        },
        BudgetPolicy {
            burst: 8,
            refill_interval_ns: 1,
        },
        costs,
    )
    .unwrap()
}
fn policy(generation: u64) -> SessionPolicy {
    SessionPolicy {
        enabled: true,
        subject_admissible: true,
        generation,
    }
}
fn ttl() -> SessionTtlPolicy {
    SessionTtlPolicy::new(30, 60).unwrap()
}
fn claims(device: u8, slot: u8, generation: u64) -> PortableClaims {
    let mut claims = support::claims(
        SigningKey::from_bytes(&[device; 32])
            .verifying_key()
            .to_bytes(),
    );
    claims.device_slot = slot;
    claims.device_generation = generation;
    claims.login_started_at_ns = NOW - 1;
    claims.login_deadline_ns = NOW + 100_000_000_000;
    claims.issued_at_ns = NOW;
    claims.admission_expires_at_ns = NOW + 1_000_000_000;
    claims
}
fn credential(claims: &PortableClaims) -> PortableCredential {
    PortableCredential {
        claims: ic_auth::portable::encode_claims(claims).unwrap(),
        proof: PortableProof::Ed25519 {
            signature: support::signature(claims, &support::issuer_key()).to_vec(),
        },
    }
}
fn admit(
    store: &mut ReceiverStore<Backing>,
    claims: &PortableClaims,
    now: u64,
) -> Result<SessionEstablished, SessionError> {
    admit_credential(store, claims, &credential(claims), now)
}
fn admit_credential(
    store: &mut ReceiverStore<Backing>,
    claims: &PortableClaims,
    credential: &PortableCredential,
    now: u64,
) -> Result<SessionEstablished, SessionError> {
    let grants = ValidatedGrants::new(claims.grants.clone()).unwrap();
    let context = support::claims_context(support::authority(claims, &grants, now));
    store.admit(
        credential,
        SessionRequest::new(vec!["read".into()], None).unwrap(),
        &SessionAdmissionContext {
            verification: PortableVerificationContext::Ed25519 {
                claims: &context,
                public_key: &PreparedIssuerKey::new(
                    support::issuer_key().verifying_key().to_bytes(),
                )
                .unwrap(),
            },
            role: &"user".parse().unwrap(),
            ttl: ttl(),
        },
        policy(store.generation()),
    )
}

#[test]
fn admission_abuse_budget_survives_reopen_and_rejections_have_measured_io() {
    let first = claims(1, 0, 1);
    let backing = Backing::new(VectorMemory::default());
    let config = configuration(first.audience, 2, 65_536);
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    let mut bad = credential(&first);
    let PortableProof::Ed25519 { signature } = &mut bad.proof else {
        unreachable!()
    };
    signature[0] ^= 1;
    for attempt in 0..8 {
        backing.reset();
        assert_eq!(
            admit_credential(&mut store, &first, &bad, NOW)
                .unwrap_err()
                .admission_refusal(),
            AdmissionRefusal::InvalidCredential
        );
        eprintln!("persistent abuse invalid {attempt}: {:?}", backing.counts());
    }
    drop(store);
    let mut store = ReceiverStore::open(memory(backing.clone()), &config, NOW).unwrap();
    for device in 2..10 {
        let rotating = claims(device, 0, 1);
        backing.reset();
        let result = admit(&mut store, &rotating, NOW);
        assert_eq!(
            result.as_ref().err().map(SessionError::admission_refusal),
            Some(AdmissionRefusal::Throttled)
        );
        eprintln!(
            "persistent abuse throttled {device}: {:?}",
            backing.counts()
        );
        assert_eq!(backing.counts().writes, 0);
    }
    assert_eq!(store.occupancy(), Default::default());
    let mut malformed = credential(&first);
    malformed.claims.clear();
    for (label, now) in [("same_clock", NOW), ("advanced_clock", NOW + 1)] {
        backing.reset();
        assert!(admit_credential(&mut store, &first, &malformed, now).is_err());
        eprintln!("persistent abuse malformed {label}: {:?}", backing.counts());
        assert_eq!(backing.counts().writes > 0, now > NOW);
    }
    let admitted = admit(&mut store, &first, NOW + 1).unwrap();
    backing.reset();
    let retry = admit(&mut store, &first, NOW + 1).unwrap();
    assert!(matches!(admitted, SessionEstablished::Created(_)));
    assert!(matches!(retry, SessionEstablished::ExactRetry(_)));
    eprintln!("persistent abuse exact retry: {:?}", backing.counts());
    assert_eq!(backing.counts().writes, 0);
}

#[test]
fn weighted_failed_verification_persists_cost_and_rejects_changed_policy() {
    let first = claims(1, 0, 1);
    let backing = Backing::new(VectorMemory::default());
    let config = configuration_with_costs(
        first.audience,
        2,
        65_536,
        ic_auth::admission_budget::VerificationCosts {
            ed25519: 4,
            certified: 8,
        },
    );
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    let mut bad = credential(&first);
    let PortableProof::Ed25519 { signature } = &mut bad.proof else {
        unreachable!()
    };
    signature[0] ^= 1;
    for _ in 0..2 {
        assert_eq!(
            admit_credential(&mut store, &first, &bad, NOW)
                .unwrap_err()
                .admission_refusal(),
            AdmissionRefusal::InvalidCredential
        );
    }
    drop(store);
    assert!(matches!(
        ReceiverStore::open(
            memory(backing.clone()),
            &configuration(first.audience, 2, 65_536),
            NOW
        ),
        Err(StoreError::Corrupt)
    ));
    let mut store = ReceiverStore::open(memory(backing), &config, NOW).unwrap();
    assert_eq!(
        admit(&mut store, &first, NOW + 3)
            .unwrap_err()
            .admission_refusal(),
        AdmissionRefusal::Throttled
    );
    assert!(admit(&mut store, &first, NOW + 4).is_ok());
}

#[test]
fn wrong_browser_skips_populated_indexes_without_breaking_expired_proof_retry() {
    let backing = Backing::new(VectorMemory::default());
    let first = claims(1, 0, 1);
    let config = ReceiverConfig::new(
        first.audience,
        SessionLimits::new(1024, 2048, 8, 16 * 1024 * 1024).unwrap(),
        LoginLimits {
            admitted: 1024,
            unknown: 4,
            maximum_ttl_ns: 90 * 86_400_000_000_000,
            devices_per_account: 8,
        },
        BudgetPolicy {
            burst: 2048,
            refill_interval_ns: 1,
        },
        BudgetPolicy {
            burst: 8,
            refill_interval_ns: 1,
        },
        ic_auth::admission_budget::VerificationCosts {
            ed25519: 1,
            certified: 1,
        },
    )
    .unwrap();
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 4096).unwrap();
    let mut retained = first.clone();
    for n in 1..=1024u16 {
        let mut c = first.clone();
        let mut seed = [0; 32];
        seed[..2].copy_from_slice(&n.to_be_bytes());
        c.browser_public_key = SigningKey::from_bytes(&seed).verifying_key().to_bytes();
        c.account_subject = Principal::from_slice(&n.to_be_bytes());
        admit(&mut store, &c, NOW).unwrap();
        retained = c;
    }
    assert_eq!(store.occupancy().sessions, 1024);
    drop(store);
    let mut store = ReceiverStore::open(memory(backing.clone()), &config, NOW).unwrap();
    backing.reset();
    assert_eq!(
        admit_credential(&mut store, &first, &credential(&retained), NOW)
            .unwrap_err()
            .admission_refusal(),
        AdmissionRefusal::InvalidCredential
    );
    eprintln!("wrong browser at 1024 sessions: {:?}", backing.counts());
    assert_eq!((backing.counts().reads, backing.counts().writes), (0, 0));
    let later = retained.admission_expires_at_ns + 1;
    assert!(matches!(
        admit(&mut store, &retained, later).unwrap(),
        SessionEstablished::ExactRetry(_)
    ));
    drop(store);
    let mut store = ReceiverStore::open(memory(backing), &config, later).unwrap();
    assert!(
        admit_credential(&mut store, &first, &credential(&retained), NOW).is_err(),
        "cheap refusal never erases the clock fence"
    );
}
fn authenticate(
    store: &mut ReceiverStore<Backing>,
    claims: &PortableClaims,
    now: u64,
    generation: u64,
) -> Result<Principal, SessionError> {
    let grants = ValidatedGrants::new(claims.grants.clone()).unwrap();
    store.authenticate(
        &SessionContext {
            authority: support::authority(claims, &grants, now),
            max_ttl: ttl().maximum(),
            role: &"user".parse().unwrap(),
            required_scopes: RequiredScopes::NONE,
        },
        policy(generation),
        |session| session.subject(),
    )
}
#[test]
fn durable_devices_replacement_logout_replay_and_authority_use_the_existing_engine() {
    let first = claims(1, 0, 1);
    let peer = claims(2, 1, 2);
    let next = claims(3, 0, 3);
    let backing = Backing::new(VectorMemory::default());
    let config = configuration(first.audience, 2, 65_536);
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    assert!(matches!(
        admit(&mut store, &first, NOW).unwrap(),
        SessionEstablished::Created(_)
    ));
    assert!(matches!(
        admit(&mut store, &first, NOW).unwrap(),
        SessionEstablished::ExactRetry(_)
    ));
    admit(&mut store, &peer, NOW).unwrap();
    assert_eq!(store.occupancy().admitted_logins, 2);
    assert!(matches!(
        admit(&mut store, &next, NOW).unwrap(),
        SessionEstablished::Replaced(_)
    ));
    assert_eq!(store.occupancy().sessions, 2);
    assert_eq!(store.occupancy().replays, 3);
    assert!(authenticate(&mut store, &first, NOW, 0).is_err());
    assert_eq!(
        authenticate(&mut store, &next, NOW, 0),
        Ok(next.account_subject)
    );
    assert_eq!(
        authenticate(&mut store, &peer, NOW, 0),
        Ok(peer.account_subject)
    );
    let count = store.occupancy();
    drop(store);
    let mut store = ReceiverStore::open(memory(backing.clone()), &config, NOW).unwrap();
    assert_eq!(store.occupancy(), count);
    assert_eq!(
        authenticate(&mut store, &next, NOW, 0),
        Ok(next.account_subject)
    );
    assert!(matches!(
        store.logout(
            ic_auth::portable::browser_principal(&next.browser_public_key),
            NOW
        ),
        LogoutResult::Revoked { .. }
    ));
    assert!(matches!(
        authenticate(&mut store, &next, NOW, 0),
        Err(SessionError::Revocation(LoginRevocationError::Revoked))
    ));
    assert!(admit(&mut store, &next, NOW).is_err());
    assert_eq!(store.occupancy().replays, 3);
    assert_eq!(
        authenticate(&mut store, &peer, NOW, 0),
        Ok(peer.account_subject)
    );
    store.advance_generation().unwrap();
    assert_eq!(
        authenticate(&mut store, &peer, NOW, 1),
        Err(SessionError::StaleAuthority)
    );
    store.prune(NOW + 200_000_000_000, 32).unwrap();
    assert_eq!(
        (
            store.occupancy().sessions,
            store.occupancy().replays,
            store.occupancy().admitted_logins
        ),
        (0, 0, 2)
    );
    drop(store);
    let store = ReceiverStore::open(memory(backing), &config, NOW + 200_000_000_000).unwrap();
    assert_eq!(
        store.occupancy().admitted_logins,
        2,
        "known slot fences never expire into reusable capacity"
    );
}

#[test]
fn capacity_signature_clock_and_configuration_refusals_preserve_records() {
    let first = claims(1, 0, 1);
    let peer = claims(2, 1, 2);
    let backing = Backing::new(VectorMemory::default());
    let config = configuration(first.audience, 1, 65_536);
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    admit(&mut store, &first, NOW).unwrap();
    let count = store.occupancy();
    assert_eq!(admit(&mut store, &peer, NOW), Err(SessionError::Capacity));
    assert_eq!(store.occupancy(), count);
    assert!(authenticate(&mut store, &first, NOW - 1, 0).is_err());
    drop(store);
    // Different limits are explicit configuration mismatch, never silent reset.
    let wrong = configuration(first.audience, 2, 65_536);
    assert!(matches!(
        ReceiverStore::open(memory(backing.clone()), &wrong, NOW),
        Err(StoreError::Corrupt)
    ));
    let mut store = ReceiverStore::open(memory(backing), &config, NOW).unwrap();
    assert_eq!(store.occupancy(), count);
    assert_eq!(
        authenticate(&mut store, &first, NOW, 0),
        Ok(first.account_subject)
    );
}

#[test]
fn invalid_signature_and_byte_refusals_leave_no_session_replay_or_login() {
    let first = claims(1, 0, 1);
    let backing = Backing::new(VectorMemory::default());
    let config = configuration(first.audience, 2, 65_536);
    let mut store = ReceiverStore::create(memory(backing), config, 0, NOW - 100).unwrap();
    let mut bad = credential(&first);
    let PortableProof::Ed25519 { signature } = &mut bad.proof else {
        unreachable!()
    };
    signature[0] ^= 1;
    let grants = ValidatedGrants::new(first.grants.clone()).unwrap();
    let context = support::claims_context(support::authority(&first, &grants, NOW));
    let result = store.admit(
        &bad,
        SessionRequest::new(vec!["read".into()], None).unwrap(),
        &SessionAdmissionContext {
            verification: PortableVerificationContext::Ed25519 {
                claims: &context,
                public_key: &PreparedIssuerKey::new(
                    support::issuer_key().verifying_key().to_bytes(),
                )
                .unwrap(),
            },
            role: &"user".parse().unwrap(),
            ttl: ttl(),
        },
        policy(0),
    );
    assert!(result.is_err());
    assert_eq!(store.occupancy(), Default::default());
    admit(&mut store, &first, NOW).unwrap();
    let backing = Backing::new(VectorMemory::default());
    let config = configuration(first.audience, 2, 1);
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    assert_eq!(
        admit(&mut store, &first, NOW),
        Err(SessionError::ByteCapacity)
    );
    assert_eq!(store.occupancy(), Default::default());
    drop(store);
    assert_eq!(
        ReceiverStore::open(memory(backing), &config, NOW)
            .unwrap()
            .occupancy(),
        Default::default()
    );
}

#[test]
fn inspection_pages_preserve_expired_stale_sessions_and_skip_fences_after_reopen() {
    let backing = Backing::new(VectorMemory::default());
    let mut claims = [claims(1, 0, 1), claims(2, 1, 2), claims(3, 2, 3)];
    let caller =
        |claims: &PortableClaims| ic_auth::portable::browser_principal(&claims.browser_public_key);
    claims.sort_by_key(caller);
    let config = configuration(claims[0].audience, 4, 65_536);
    let mut store =
        ReceiverStore::create(memory(backing.clone()), config.clone(), 0, NOW - 100).unwrap();
    for claims in &claims {
        admit(&mut store, claims, NOW).unwrap();
    }
    backing.reset();
    let page = store.inspect_sessions(None, 1, 1, NOW).unwrap();
    assert_eq!(page.sessions.len(), 1);
    assert_eq!(page.sessions[0].caller(), caller(&claims[0]));
    assert_eq!(page.next_after, Some(caller(&claims[0])));
    assert_eq!(backing.counts().writes, 0);
    store.logout(caller(&claims[1]), NOW);
    store.advance_generation().unwrap();
    drop(store);
    let store = ReceiverStore::open(memory(backing.clone()), &config, NOW).unwrap();
    backing.reset();
    let expired_at = NOW + 61_000_000_000;
    let empty = store
        .inspect_sessions(page.next_after, 1, 1, expired_at)
        .unwrap();
    assert!(empty.sessions.is_empty());
    assert_eq!(empty.next_after, Some(caller(&claims[1])));
    let last = store
        .inspect_sessions(empty.next_after, 1, 1, expired_at)
        .unwrap();
    assert_eq!(last.sessions.len(), 1);
    assert_eq!(last.sessions[0].caller(), caller(&claims[2]));
    assert!(last.sessions[0].expires_at_ns() <= last.observed_at_ns);
    assert_ne!(last.sessions[0].generation(), last.generation);
    assert_eq!(last.next_after, None);
    assert_eq!(store.observed_at_ns(), NOW);
    assert_eq!((backing.counts().writes, backing.counts().grows), (0, 0));
}