ic-platform 0.7.5

Controlled Candid and IC runtime dependency boundary
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
//! Iterative wire-nesting admission before the upstream decoder sees the header.
//!
//! This walk retains no decoded application values, performs no subtyping and
//! never rewrites bytes. It bounds all type-table paths (including unused entries)
//! and every encoded value (including skipped arguments/fields). Recursive type
//! declarations remain allowed; actual recursive values consume the depth budget.
//! Future constructors and opaque references are refused rather than passed on
//! without inspection. Upstream Candid still owns semantic/type validation.

use super::DecodeLimits;
use std::{error::Error, fmt};

/// Maximum constructed wire-type path and value depth admitted by bounded decoders.
/// Scalars use depth zero; an empty container still uses one level.
pub const MAX_DEPTH: usize = 16;

/// A compact, typed refusal from admission, without disclosing input bytes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum NestingError {
    /// Original message exceeds its existing byte allowance.
    Bytes {
        /// Observed message length.
        actual: usize,
        /// Caller-selected byte allowance.
        maximum: usize,
    },
    /// Header exceeds its existing byte allowance.
    Header {
        /// Caller-selected header byte allowance.
        maximum: usize,
    },
    /// Type table exceeds its existing entry allowance.
    Types {
        /// Declared table entries.
        actual: usize,
        /// Caller-selected entry allowance.
        maximum: usize,
    },
    /// A path through the type table exceeds the caller's nesting allowance.
    TypeDepth {
        /// Caller-selected nesting allowance.
        maximum: usize,
    },
    /// An encoded value exceeds the caller's nesting allowance.
    ValueDepth {
        /// Caller-selected nesting allowance.
        maximum: usize,
    },
    /// Admission work is exhausted, including zero-byte value expansion.
    Work {
        /// Caller-selected admission work allowance.
        maximum: usize,
    },
    /// Framing is malformed or truncated at this byte offset.
    Malformed {
        /// Offset observed before refusing framing.
        offset: usize,
    },
    /// A future constructor cannot be inspected by this admission implementation.
    Unsupported {
        /// Uninspected constructor opcode.
        opcode: i64,
    },
}
impl fmt::Display for NestingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bytes { actual, maximum } => {
                write!(f, "Candid admission bytes {actual} exceed {maximum}")
            }
            Self::Header { maximum } => {
                write!(f, "Candid admission header exceeds {maximum} bytes")
            }
            Self::Types { actual, maximum } => {
                write!(f, "Candid admission type entries {actual} exceed {maximum}")
            }
            Self::TypeDepth { maximum } => write!(f, "Candid type nesting exceeds {maximum}"),
            Self::ValueDepth { maximum } => write!(f, "Candid value nesting exceeds {maximum}"),
            Self::Work { maximum } => {
                write!(f, "Candid nesting admission work quota exceeds {maximum}")
            }
            Self::Malformed { offset } => {
                write!(f, "invalid Candid admission framing at byte {offset}")
            }
            Self::Unsupported { opcode } => {
                write!(f, "unsupported Candid admission constructor {opcode}")
            }
        }
    }
}
impl Error for NestingError {}

type Result<T> = std::result::Result<T, NestingError>;

struct Cursor<'a> {
    bytes: &'a [u8],
    pos: usize,
    end: usize,
    header: bool,
    remaining: usize,
    work_limit: usize,
}
impl Cursor<'_> {
    fn malformed(&self) -> NestingError {
        NestingError::Malformed { offset: self.pos }
    }
    fn charge(&mut self, amount: usize) -> Result<()> {
        self.remaining = self
            .remaining
            .checked_sub(amount)
            .ok_or(NestingError::Work {
                maximum: self.work_limit,
            })?;
        Ok(())
    }
    fn take(&mut self, count: usize) -> Result<&[u8]> {
        let end = self
            .pos
            .checked_add(count)
            .ok_or_else(|| self.malformed())?;
        if end > self.end {
            return Err(if self.header && self.end < self.bytes.len() {
                NestingError::Header { maximum: self.end }
            } else {
                self.malformed()
            });
        }
        self.charge(count)?;
        let bytes = &self.bytes[self.pos..end];
        self.pos = end;
        Ok(bytes)
    }
    fn byte(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }
    fn leb(&mut self, signed: bool) -> Result<u64> {
        let mut value = 0u64;
        for i in 0..10 {
            let byte = self.byte()?;
            let payload = byte & 0x7f;
            if i == 9
                && (byte & 0x80 != 0
                    || if signed {
                        payload != 0 && payload != 0x7f
                    } else {
                        payload > 1
                    })
            {
                return Err(self.malformed());
            }
            value |= u64::from(payload) << (i * 7);
            if byte & 0x80 == 0 {
                let bits = (i + 1) * 7;
                if signed && bits < 64 && byte & 0x40 != 0 {
                    value |= u64::MAX << bits;
                }
                return Ok(value);
            }
        }
        Err(self.malformed())
    }
    fn count(&mut self) -> Result<usize> {
        usize::try_from(self.leb(false)?).map_err(|_| self.malformed())
    }
    fn index(&mut self) -> Result<i64> {
        let value = self.leb(true)? as i64;
        if value < -17 && value != -24 {
            return Err(self.malformed());
        }
        Ok(value)
    }
    fn text(&mut self) -> Result<()> {
        let len = self.count()?;
        self.take(len)?;
        Ok(())
    }
    fn principal(&mut self) -> Result<()> {
        if self.byte()? != 1 {
            return Err(self.malformed());
        }
        let len = self.count()?;
        if len > 29 {
            return Err(self.malformed());
        }
        self.take(len)?;
        Ok(())
    }
}

#[derive(Clone, Copy)]
enum Kind {
    Opt,
    Vec,
    Record,
    Variant,
    Func,
    Service,
}
struct Node {
    kind: Kind,
    children: Vec<i64>,
}

fn header(cursor: &mut Cursor<'_>, limits: DecodeLimits) -> Result<(Vec<Node>, Vec<i64>)> {
    if cursor.take(4)? != b"DIDL" {
        return Err(cursor.malformed());
    }
    let count = cursor.count()?;
    if count > limits.type_entries {
        return Err(NestingError::Types {
            actual: count,
            maximum: limits.type_entries,
        });
    }
    let mut types = Vec::new();
    for _ in 0..count {
        let opcode = cursor.leb(true)? as i64;
        let kind = match opcode {
            -18 => Kind::Opt,
            -19 => Kind::Vec,
            -20 => Kind::Record,
            -21 => Kind::Variant,
            -22 => Kind::Func,
            -23 => Kind::Service,
            value if value < -24 => return Err(NestingError::Unsupported { opcode: value }),
            _ => return Err(cursor.malformed()),
        };
        let mut children = Vec::new();
        match kind {
            Kind::Opt | Kind::Vec => children.push(cursor.index()?),
            Kind::Record | Kind::Variant => {
                let fields = cursor.count()?;
                let mut previous = None;
                for _ in 0..fields {
                    let id = u32::try_from(cursor.leb(false)?).map_err(|_| cursor.malformed())?;
                    if previous.is_some_and(|prev| id <= prev) {
                        return Err(cursor.malformed());
                    }
                    previous = Some(id);
                    children.push(cursor.index()?);
                }
            }
            Kind::Func => {
                for _ in 0..2 {
                    let fields = cursor.count()?;
                    for _ in 0..fields {
                        children.push(cursor.index()?);
                    }
                }
                match cursor.byte()? {
                    0 => (),
                    1 => {
                        if !(1..=3).contains(&cursor.byte()?) {
                            return Err(cursor.malformed());
                        }
                    }
                    _ => return Err(cursor.malformed()),
                }
            }
            Kind::Service => {
                let methods = cursor.count()?;
                for _ in 0..methods {
                    cursor.text()?;
                    children.push(cursor.index()?);
                }
            }
        }
        types.push(Node { kind, children });
    }
    let count = cursor.count()?;
    let mut args = Vec::new();
    for _ in 0..count {
        args.push(cursor.index()?);
    }
    for index in args
        .iter()
        .chain(types.iter().flat_map(|node| &node.children))
    {
        if *index >= 0 && usize::try_from(*index).map_or(true, |i| i >= types.len()) {
            return Err(cursor.malformed());
        }
    }
    Ok((types, args))
}

fn type_depth(cursor: &mut Cursor<'_>, types: &[Node]) -> Result<()> {
    let mut active = vec![false; types.len()];
    let mut stack = Vec::new();
    for root in 0..types.len() {
        cursor.charge(1)?;
        active[root] = true;
        stack.push((root, 0usize));
        while let Some((index, next)) = stack.last_mut() {
            let node = &types[*index];
            if *next == node.children.len() {
                active[*index] = false;
                stack.pop();
                continue;
            }
            let child = node.children[*next];
            *next += 1;
            cursor.charge(1)?;
            if child < 0 {
                continue;
            }
            let child = usize::try_from(child).map_err(|_| cursor.malformed())?;
            if active[child] {
                continue;
            }
            if stack.len() >= MAX_DEPTH {
                return Err(NestingError::TypeDepth { maximum: MAX_DEPTH });
            }
            active[child] = true;
            stack.push((child, 0));
        }
    }
    Ok(())
}

fn width(ty: i64) -> Option<usize> {
    match ty {
        -1 | -16 => Some(0),
        -5 | -9 => Some(1),
        -6 | -10 => Some(2),
        -7 | -11 | -13 => Some(4),
        -8 | -12 | -14 => Some(8),
        _ => None,
    }
}

enum Task<'a> {
    Values(&'a [i64], usize, usize),
    Value(i64, usize),
    Repeat(i64, usize, usize),
}
fn values(cursor: &mut Cursor<'_>, types: &[Node], args: &[i64]) -> Result<()> {
    let mut stack = vec![Task::Values(args, 0, 0)];
    while let Some(task) = stack.pop() {
        let (ty, depth) = match task {
            Task::Values(items, next, depth) => {
                if next == items.len() {
                    continue;
                }
                stack.push(Task::Values(items, next + 1, depth));
                (items[next], depth)
            }
            Task::Repeat(ty, count, depth) => {
                if count == 0 {
                    continue;
                }
                stack.push(Task::Repeat(ty, count - 1, depth));
                (ty, depth)
            }
            Task::Value(ty, depth) => (ty, depth),
        };
        cursor.charge(1)?;
        if ty < 0 {
            if let Some(width) = width(ty) {
                cursor.take(width)?;
            } else {
                match ty {
                    -2 => {
                        if cursor.byte()? > 1 {
                            return Err(cursor.malformed());
                        }
                    }
                    -3 | -4 => while cursor.byte()? & 0x80 != 0 {},
                    -15 => cursor.text()?,
                    -24 => cursor.principal()?,
                    _ => return Err(cursor.malformed()),
                }
            }
            continue;
        }
        if depth >= MAX_DEPTH {
            return Err(NestingError::ValueDepth { maximum: MAX_DEPTH });
        }
        let depth = depth + 1;
        let node = &types[usize::try_from(ty).map_err(|_| cursor.malformed())?];
        match node.kind {
            Kind::Opt => match cursor.byte()? {
                0 => (),
                1 => stack.push(Task::Value(node.children[0], depth)),
                _ => return Err(cursor.malformed()),
            },
            Kind::Vec => {
                let count = cursor.count()?;
                let ty = node.children[0];
                if let Some(width) = width(ty) {
                    cursor.charge(count)?;
                    let size = count.checked_mul(width).ok_or_else(|| cursor.malformed())?;
                    cursor.take(size)?;
                } else {
                    stack.push(Task::Repeat(ty, count, depth));
                }
            }
            Kind::Record => stack.push(Task::Values(&node.children, 0, depth)),
            Kind::Variant => {
                let index = cursor.count()?;
                let child = *node.children.get(index).ok_or_else(|| cursor.malformed())?;
                stack.push(Task::Value(child, depth));
            }
            Kind::Func => {
                if cursor.byte()? != 1 {
                    return Err(cursor.malformed());
                }
                cursor.principal()?;
                cursor.text()?;
            }
            Kind::Service => cursor.principal()?,
        }
    }
    if cursor.pos != cursor.bytes.len() {
        return Err(cursor.malformed());
    }
    Ok(())
}

/// Admit the complete wire envelope using bounded heap stacks, before constructing
/// upstream `IDLDeserialize`, rejecting more than 16 constructed wire levels.
/// Admission work is capped by the saturating sum of the supplied decoding and
/// skipping quotas. The decoder retains its original, unchanged quotas afterward.
///
/// This is wire-nesting admission, not a replacement decoder or a guarantee about
/// arbitrary custom Rust visitors/expected schemas. Low-level Candid APIs remain
/// caller-owned. No future/opaque wire form is silently passed without inspection.
///
/// # Errors
/// Returns typed byte/header/type/depth/work or unsupported/framing refusals.
pub fn check(bytes: &[u8], wire: DecodeLimits) -> Result<()> {
    if bytes.len() > wire.reply_bytes {
        return Err(NestingError::Bytes {
            actual: bytes.len(),
            maximum: wire.reply_bytes,
        });
    }
    let mut cursor = Cursor {
        bytes,
        pos: 0,
        end: bytes.len().min(wire.header_bytes),
        header: true,
        remaining: wire.decoding_quota.saturating_add(wire.skipping_quota),
        work_limit: wire.decoding_quota.saturating_add(wire.skipping_quota),
    };
    let (types, args) = header(&mut cursor, wire)?;
    type_depth(&mut cursor, &types)?;
    cursor.header = false;
    cursor.end = bytes.len();
    values(&mut cursor, &types, &args)
}

#[cfg(test)]
mod tests;