ic-auth 0.57.0

Canonical authentication, proof verification and bounded receiver/issuer state with optional stable upgrade checkpoints
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
//! Stable receiver checkpoint format and upgrade lifecycle.

use super::{
    Account, AccountIndex, BTreeMap, BTreeSet, CallerRecord, Lifecycle, MemoryConfig,
    MemoryReceiver, Principal, Replay, VerificationBudget, WorkBucket, enrollment, policy,
};
use crate::stable_upgrade::{Checkpoint, DIGEST_BYTES, UpgradeError, hash_part};
use ic_storage::{DefaultMemoryImpl, Memory, RuntimeMemory};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

const MAX_PAYLOAD: usize = 128 * 1024 * 1024;
const CHUNK_ROWS: usize = 256;
const MAX_CHUNK_BYTES: usize = 2 * 1024 * 1024;
const CHECKPOINT_DOMAIN: &[u8] = b"ic-auth.checkpoint.receiver.postcard.claims.v1";

// Bound the caller key, retained login fields and session option tag, including
// worst-case principal lengths and varints. Session and replay bodies are
// accounted using their exact checkpoint encoding.
const CALLER_OVERHEAD: usize = 256;
const CHUNK_OVERHEAD: usize = 8;
const HEADER_ALLOWANCE: usize = 4096;

fn validate_checkpoint_budget(config: MemoryConfig) -> Result<(), UpgradeError> {
    let callers = config
        .login
        .max_retained_device_slots
        .saturating_add(config.unknown_logout.max_denials);
    let chunks = callers
        .div_ceil(CHUNK_ROWS)
        .saturating_add(config.capacity.max_replays.div_ceil(CHUNK_ROWS));
    let maximum = HEADER_ALLOWANCE
        .saturating_add(callers.saturating_mul(CALLER_OVERHEAD))
        .saturating_add(chunks.saturating_mul(CHUNK_OVERHEAD))
        .saturating_add(config.capacity.max_encoded_bytes);
    if maximum > MAX_PAYLOAD {
        return Err(UpgradeError::Configuration);
    }
    Ok(())
}

///
/// Fields
///
/// Defines the serialized checkpoint fields for the in-memory state.
///

#[derive(Serialize, Deserialize)]
#[serde(remote = "MemoryReceiver")]
struct Fields {
    config: MemoryConfig,
    lifecycle: Lifecycle,
    generation: u64,
    enrollment: enrollment::Enrollment,
    observed_at_ns: u64,
    #[serde(with = "crate::verification::RetainedBudget")]
    budget: VerificationBudget,
    unknown_budget: WorkBucket,
    unknown: usize,
    #[serde(skip)]
    slot_expiry: BTreeSet<(u64, Principal)>,
    #[serde(skip)]
    unknown_expiry: BTreeSet<(u64, Principal)>,
    #[serde(skip)]
    callers: BTreeMap<Principal, CallerRecord>,
    #[serde(skip)]
    replays: BTreeMap<[u8; 32], Replay>,
    #[serde(skip)]
    accounts: BTreeMap<Account, AccountIndex>,
    #[serde(skip)]
    session_expiry: BTreeSet<(u64, Principal)>,
    #[serde(skip)]
    replay_expiry: BTreeSet<(u64, [u8; 32])>,
    sessions: usize,
    encoded_bytes: usize,
}

///
/// SavedRef
///
/// Borrows the in-memory state for checkpoint encoding.
///

#[derive(Serialize)]
struct SavedRef<'a>(#[serde(with = "Fields")] &'a MemoryReceiver);

///
/// Saved
///
/// Reconstructs owned state from the checkpoint fields.
///

#[derive(Deserialize)]
struct Saved(#[serde(with = "Fields")] MemoryReceiver);

// Persist authoritative rows in bounded, ordered chunks. Derived indexes are
// restored from the same rows, and a single outer digest commits all chunks.
fn write_chunk<T: Serialize + ?Sized>(out: &mut Vec<u8>, value: &T) -> Result<(), UpgradeError> {
    let len = postcard::experimental::serialized_size(value).map_err(|_| UpgradeError::Capacity)?;
    if len > MAX_CHUNK_BYTES || out.len() + 4 + len > DIGEST_BYTES + MAX_PAYLOAD {
        return Err(UpgradeError::Capacity);
    }
    out.extend_from_slice(&(len as u32).to_le_bytes());
    let start = out.len();
    out.resize(start + len, 0);
    postcard::to_slice(value, &mut out[start..]).map_err(|_| UpgradeError::Capacity)?;
    Ok(())
}

fn read_u32(bytes: &mut &[u8]) -> Result<usize, UpgradeError> {
    let (value, rest) = bytes
        .split_first_chunk::<4>()
        .ok_or(UpgradeError::InvalidCheckpoint)?;
    *bytes = rest;
    Ok(u32::from_le_bytes(*value) as usize)
}

fn read_chunk<'a>(bytes: &mut &'a [u8]) -> Result<&'a [u8], UpgradeError> {
    let len = read_u32(bytes)?;
    if len > MAX_CHUNK_BYTES {
        return Err(UpgradeError::InvalidCheckpoint);
    }
    let (chunk, rest) = bytes
        .split_at_checked(len)
        .ok_or(UpgradeError::InvalidCheckpoint)?;
    *bytes = rest;
    Ok(chunk)
}

fn write_rows<K: Serialize, V: Serialize>(
    out: &mut Vec<u8>,
    rows: &BTreeMap<K, V>,
) -> Result<(), UpgradeError> {
    let count = u32::try_from(rows.len()).map_err(|_| UpgradeError::Capacity)?;
    if out.len() + 4 > DIGEST_BYTES + MAX_PAYLOAD {
        return Err(UpgradeError::Capacity);
    }
    out.extend_from_slice(&count.to_le_bytes());
    let mut chunk = Vec::with_capacity(CHUNK_ROWS);
    for row in rows {
        chunk.push(row);
        if chunk.len() == CHUNK_ROWS {
            write_chunk(out, chunk.as_slice())?;
            chunk.clear();
        }
    }
    if !chunk.is_empty() {
        write_chunk(out, chunk.as_slice())?;
    }
    Ok(())
}

fn read_rows<K: Ord + serde::de::DeserializeOwned, V: serde::de::DeserializeOwned>(
    bytes: &mut &[u8],
    maximum: usize,
) -> Result<BTreeMap<K, V>, UpgradeError> {
    let count = read_u32(bytes)?;
    if count > maximum {
        return Err(UpgradeError::InvalidCheckpoint);
    }
    let mut rows = BTreeMap::new();
    while rows.len() < count {
        let (len, mut body) = postcard::take_from_bytes::<usize>(read_chunk(bytes)?)
            .map_err(|_| UpgradeError::InvalidCheckpoint)?;
        if len != (count - rows.len()).min(CHUNK_ROWS) {
            return Err(UpgradeError::InvalidCheckpoint);
        }
        for _ in 0..len {
            let ((key, value), rest) = postcard::take_from_bytes::<(K, V)>(body)
                .map_err(|_| UpgradeError::InvalidCheckpoint)?;
            body = rest;
            if rows
                .last_key_value()
                .is_some_and(|(previous, _)| previous >= &key)
            {
                return Err(UpgradeError::InvalidCheckpoint);
            }
            rows.insert(key, value);
        }
        if !body.is_empty() {
            return Err(UpgradeError::InvalidCheckpoint);
        }
    }
    Ok(rows)
}

///
/// StableReceiver
///
/// Owns a single-use upgrade checkpoint and the indexed [MemoryReceiver] used
/// for ordinary operations between upgrades.
///

pub struct StableReceiver<M: Memory = DefaultMemoryImpl> {
    inner: MemoryReceiver,
    checkpoint: Checkpoint<M, MAX_PAYLOAD>,
}

impl<M: Memory> StableReceiver<M> {
    /// Initialize a genuinely fresh installation with a host-owned, empty lease.
    pub fn new_fresh(
        memory: RuntimeMemory<M>,
        config: MemoryConfig,
        now_ns: u64,
    ) -> Result<Self, UpgradeError> {
        validate_checkpoint_budget(config)?;
        let inner =
            MemoryReceiver::new_fresh(config, now_ns).map_err(|_| UpgradeError::Configuration)?;

        Ok(Self {
            inner,
            checkpoint: Checkpoint::create(memory)?,
        })
    }

    /// Consume a committed upgrade checkpoint from this module's named allocation.
    /// Supply the trusted post-upgrade canister version. Only the immediate successor
    /// of the sealing version can reopen. Abort the upgrade transaction on refusal.
    /// Obtain fresh authenticated enrollment before using retained sessions.
    pub fn reopen(
        memory: RuntimeMemory<M>,
        config: MemoryConfig,
        now_ns: u64,
        canister_version: u64,
    ) -> Result<Self, UpgradeError> {
        validate_checkpoint_budget(config)?;
        let mut checkpoint = Checkpoint::load(memory)?;
        let mut payload = checkpoint.payload(CHECKPOINT_DOMAIN, canister_version)?;
        let (Saved(mut inner), commitment): (Saved, [u8; 32]) =
            crate::stable_upgrade::decode_exact(read_chunk(&mut payload)?)?;
        let saved_config = inner.config;
        saved_config
            .login
            .validate()
            .map_err(|_| UpgradeError::InvalidCheckpoint)?;
        saved_config
            .capacity
            .validate()
            .map_err(|_| UpgradeError::InvalidCheckpoint)?;
        let mut permitted = saved_config;
        permitted.login.max_retained_device_slots = permitted
            .login
            .max_retained_device_slots
            .max(config.login.max_retained_device_slots);
        permitted.capacity.max_sessions = permitted
            .capacity
            .max_sessions
            .max(config.capacity.max_sessions);
        permitted.capacity.max_replays = permitted
            .capacity
            .max_replays
            .max(config.capacity.max_replays);
        permitted.capacity.max_encoded_bytes = permitted
            .capacity
            .max_encoded_bytes
            .max(config.capacity.max_encoded_bytes);
        if permitted != config {
            return Err(UpgradeError::Configuration);
        }
        inner.callers = read_rows(
            &mut payload,
            saved_config
                .login
                .max_retained_device_slots
                .saturating_add(config.unknown_logout.max_denials),
        )?;
        inner.replays = read_rows(&mut payload, saved_config.capacity.max_replays)?;
        if !payload.is_empty() {
            return Err(UpgradeError::InvalidCheckpoint);
        }
        if inner.lifecycle == Lifecycle::Closed {
            return Err(UpgradeError::Lifecycle);
        }
        if inner.rebuild_checkpoint_indexes()? != commitment {
            return Err(UpgradeError::InvalidCheckpoint);
        }
        inner.config = config;
        inner.observe(now_ns).map_err(|_| UpgradeError::Lifecycle)?;
        inner.lifecycle = Lifecycle::Fresh;
        inner.enrollment.discard_pending();
        checkpoint.consume();

        Ok(Self { inner, checkpoint })
    }

    /// Save in the host's pre-upgrade transaction. Success closes the running
    /// instance. Supply the trusted canister version from the pre-upgrade hook.
    /// The encoded checkpoint is limited to 128 MiB. On error the host
    /// must abort the upgrade, retaining the heap.
    pub fn seal(&mut self, canister_version: u64) -> Result<(), UpgradeError> {
        if self.inner.lifecycle == Lifecycle::Closed {
            return Err(UpgradeError::Lifecycle);
        }
        let mut image = vec![0; DIGEST_BYTES];
        write_chunk(
            &mut image,
            &(SavedRef(&self.inner), self.inner.extension_digest()),
        )?;
        write_rows(&mut image, &self.inner.callers)?;
        write_rows(&mut image, &self.inner.replays)?;
        self.checkpoint
            .save_image(CHECKPOINT_DOMAIN, canister_version, image)?;
        self.inner.close();

        Ok(())
    }

    /// Access the current Auth instance under the host transaction.
    pub fn state(&mut self) -> &mut MemoryReceiver {
        &mut self.inner
    }
}

impl<M: Memory> std::ops::Deref for StableReceiver<M> {
    type Target = MemoryReceiver;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<M: Memory> std::ops::DerefMut for StableReceiver<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<M: Memory> AsRef<MemoryReceiver> for StableReceiver<M> {
    fn as_ref(&self) -> &MemoryReceiver {
        &self.inner
    }
}

fn hash_extension(digest: &mut Sha256, facts: &super::SessionFacts<'_>) {
    if let Some(ext) = facts.ext {
        hash_part(digest, &[facts.caller.as_slice().len() as u8]);
        hash_part(digest, facts.caller.as_slice());
        hash_part(digest, &facts.fingerprint);
        hash_part(digest, &(ext.len() as u32).to_le_bytes());
        hash_part(digest, ext);
    }
}

impl MemoryReceiver {
    // Byte accounting cannot distinguish equal-length extensions exchanged by an encoder.
    fn extension_digest(&self) -> [u8; 32] {
        let mut digest = Sha256::new();
        for facts in self
            .callers
            .values()
            .filter_map(CallerRecord::session_facts)
        {
            hash_extension(&mut digest, &facts);
        }
        digest.finalize().into()
    }

    fn rebuild_checkpoint_indexes(&mut self) -> Result<[u8; 32], UpgradeError> {
        let bad = UpgradeError::InvalidCheckpoint;
        let cfg = self.config;
        if !self
            .enrollment
            .matches(cfg.enrollment, cfg.audience, self.generation)
            || self.unknown > cfg.unknown_logout.max_denials
            || self
                .callers
                .len()
                .checked_sub(self.unknown)
                .is_none_or(|known| known > cfg.login.max_retained_device_slots)
            || self.sessions > cfg.capacity.max_sessions
            || self.replays.len() > cfg.capacity.max_replays
            || self.encoded_bytes > cfg.capacity.max_encoded_bytes
            || !self.budget.matches(
                cfg.verification_costs,
                cfg.verification_capacity,
                cfg.refill_interval_ns,
                self.observed_at_ns,
            )
            || !self.unknown_budget.matches(
                cfg.unknown_logout.capacity,
                cfg.unknown_logout.refill_interval_ns,
                self.observed_at_ns,
            )
        {
            return Err(bad);
        }
        let mut digest = Sha256::new();
        let mut bytes = 0usize;
        let mut sessions = 0;
        let mut unknown = 0;
        for (caller, row) in &mut self.callers {
            policy::check_record(&row.login, cfg.audience).map_err(|_| bad)?;
            if caller != &row.login.caller {
                return Err(bad);
            }
            match row.slot() {
                Some(slot) if slot.2 < cfg.login.max_device_slots => {
                    self.slot_expiry
                        .insert((row.reclaim_at(cfg.login.max_login_ttl_ns), *caller));
                    if self
                        .accounts
                        .entry((slot.0, slot.1))
                        .or_default()
                        .set_slot(slot.2, *caller)
                        .is_some()
                    {
                        return Err(bad);
                    }
                }
                None if row.session.is_none() => {
                    self.unknown_expiry.insert((row.login.until_ns, *caller));
                    unknown += 1;
                }
                _ => return Err(bad),
            }
            if row.session.is_some() {
                if row.login.denied {
                    return Err(bad);
                }
                let facts = row.session_facts().ok_or(bad)?;
                policy::check_session_shape(&facts).map_err(|_| bad)?;
                if facts.established_at_ns > self.observed_at_ns
                    || facts.authority_generation > self.generation
                {
                    return Err(bad);
                }
                hash_extension(&mut digest, &facts);
                let session = row.session.as_mut().ok_or(bad)?;
                session.bytes = session.encoded_size().map_err(|_| bad)?;
                bytes = bytes.checked_add(session.bytes).ok_or(bad)?;
                self.session_expiry.insert((session.expires_at_ns, *caller));
                sessions += 1;
            }
        }
        for (fingerprint, replay) in &mut self.replays {
            replay.bytes = replay.encoded_size(fingerprint).map_err(|_| bad)?;
            bytes = bytes.checked_add(replay.bytes).ok_or(bad)?;
            self.replay_expiry
                .insert((replay.remove_at_ns, *fingerprint));
            let count = &mut self
                .accounts
                .entry(replay.account)
                .or_default()
                .replay_count;
            *count += 1;
            if *count > cfg.capacity.max_replays_per_account {
                return Err(bad);
            }
        }
        if bytes != self.encoded_bytes || sessions != self.sessions || unknown != self.unknown {
            return Err(bad);
        }
        Ok(digest.finalize().into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ic_auth_protocol_types::CanonicalId;

    #[test]
    fn row_chunks_require_the_exact_count_and_full_consumption() {
        // One declared row, then a Postcard sequence of (u8, u8) rows.
        for body in [&[0][..], &[2, 1, 2, 3, 4], &[1, 1], &[1, 1, 2, 3]] {
            let mut bytes = 1u32.to_le_bytes().to_vec();
            bytes.extend_from_slice(&(body.len() as u32).to_le_bytes());
            bytes.extend_from_slice(body);
            assert_eq!(
                read_rows::<u8, u8>(&mut bytes.as_slice(), 1),
                Err(UpgradeError::InvalidCheckpoint)
            );
        }
    }

    #[test]
    fn checkpoint_budget_accounts_for_dormant_slots_and_chunk_framing() {
        let mut config = MemoryConfig::starting_profile(
            ic_auth_protocol_types::AudienceId {
                canonical_network_id: CanonicalId::from_bytes([1; 32]),
                application_id: CanonicalId::from_bytes([2; 32]),
            },
            super::super::EnrollmentBinding {
                receiver: Principal::from_slice(&[10]),
                authority: Principal::from_slice(&[11]),
            },
        );
        assert_eq!(validate_checkpoint_budget(config), Ok(()));

        // 125,064 caller entries require 489 chunks. 400,000 replays need 1,563.
        let overhead = 4096 + 125_064 * 256 + (489 + 1563) * 8;
        config.capacity.max_encoded_bytes = MAX_PAYLOAD - overhead;
        assert_eq!(validate_checkpoint_budget(config), Ok(()));
        config.capacity.max_encoded_bytes += 1;
        assert_eq!(
            validate_checkpoint_budget(config),
            Err(UpgradeError::Configuration)
        );
        config.capacity.max_encoded_bytes -= 1;
        config.login.max_retained_device_slots += 1;
        assert_eq!(
            validate_checkpoint_budget(config),
            Err(UpgradeError::Configuration)
        );
        config.capacity.max_encoded_bytes = 1;
        config.login.max_retained_device_slots = usize::MAX;
        assert_eq!(
            validate_checkpoint_budget(config),
            Err(UpgradeError::Configuration)
        );
    }
}