icydb 0.286.1

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
//! Bounded application-supplied read-authorization contracts.
//!
//! Application identity, roles, sessions, policy storage, and audit remain
//! application concerns. This module owns only synchronous caller/surface decisions
//! before IcyDB request construction.

use ic_platform::Principal;

use crate::{Error, ErrorOrigin, diagnostic::RuntimeBoundaryCode};

/// Generated read surface presented to an application authorization guard.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReadAuthorizationSurface {
    /// The complete admitted generated SQL query lane.
    Sql,
    /// The dedicated generated accepted-schema query lane.
    Schema,
}

/// Bounded context supplied to an application read-authorization guard.
///
/// Authorization runs before SQL parsing. An allowed SQL invocation grants the
/// complete SQL surface across all entities; this context cannot enforce entity,
/// field, statement or row restrictions. Use a narrower application endpoint
/// when callers must receive only a selected entity or projection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ReadAuthorizationContext {
    /// Principal observed at the generated endpoint boundary.
    pub caller: Principal,
    /// Generated read surface being authorized.
    pub surface: ReadAuthorizationSurface,
}

/// Complete application decision for one generated read invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReadAuthorizationDecision {
    /// Continue into normal IcyDB startup admission and read execution.
    Allow,
    /// Reject this invocation without constructing an IcyDB request.
    Deny,
}

/// Exact synchronous application guard accepted by generated read endpoints.
pub type ReadAuthorizationGuard = fn(ReadAuthorizationContext) -> ReadAuthorizationDecision;

/// Maximum principal count accepted by [`allowlist`].
pub const MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS: usize = 64;

/// Decide one read invocation against a fixed bounded principal allowlist.
///
/// Anonymous callers, empty or missing matches, and lists above the fixed
/// maximum deny. Matching uses exact principal equality and performs no
/// allocation, logging, mutation, database entry, timer work, or remote call.
///
/// This helper checks the principal only: it does not restrict `context.surface`.
/// Reusing it for SQL and schema grants both surfaces to matching readers.
/// Use [`allowlist_for_surface`] to grant just one surface.
#[must_use]
pub fn allowlist(
    context: ReadAuthorizationContext,
    readers: &[Principal],
) -> ReadAuthorizationDecision {
    if context.caller == Principal::anonymous()
        || readers.len() > MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS
    {
        return ReadAuthorizationDecision::Deny;
    }

    if readers.contains(&context.caller) {
        ReadAuthorizationDecision::Allow
    } else {
        ReadAuthorizationDecision::Deny
    }
}

/// Decide one read invocation for a single surface and bounded principal list.
///
/// A mismatched surface denies before principal admission. Matching surfaces
/// use [`allowlist`], including its anonymous and capacity refusals. SQL access
/// still covers every entity and admitted statement, not a per-entity subset.
#[must_use]
pub fn allowlist_for_surface(
    context: ReadAuthorizationContext,
    surface: ReadAuthorizationSurface,
    readers: &[Principal],
) -> ReadAuthorizationDecision {
    if context.surface != surface {
        return ReadAuthorizationDecision::Deny;
    }
    allowlist(context, readers)
}

/// Apply the canonical generated SQL read-authorization boundary.
///
/// This is public only for generated-code and evidence-canister plumbing.
/// Transport principal bytes are checked and normalized through Platform before
/// constructing the application context. This boundary does not require the
/// transport and database to select the same Platform package identity.
#[doc(hidden)]
pub fn authorize_sql_read(
    caller: impl AsRef<[u8]>,
    guard: ReadAuthorizationGuard,
) -> Result<(), Error> {
    authorize_read(
        caller.as_ref(),
        ReadAuthorizationSurface::Sql,
        guard,
        RuntimeBoundaryCode::SqlSurfacePolicyDenied,
    )
}

/// Apply the canonical generated accepted-schema read-authorization boundary.
///
/// This is public only for generated-code and evidence-canister plumbing.
/// Transport principal bytes are checked and normalized through Platform before
/// constructing the application context. This boundary does not require the
/// transport and database to select the same Platform package identity.
#[doc(hidden)]
pub fn authorize_schema_read(
    caller: impl AsRef<[u8]>,
    guard: ReadAuthorizationGuard,
) -> Result<(), Error> {
    authorize_read(
        caller.as_ref(),
        ReadAuthorizationSurface::Schema,
        guard,
        RuntimeBoundaryCode::SchemaSurfacePolicyDenied,
    )
}

fn authorize_read(
    caller: &[u8],
    surface: ReadAuthorizationSurface,
    guard: ReadAuthorizationGuard,
    denied_boundary: RuntimeBoundaryCode,
) -> Result<(), Error> {
    // A principal's canonical bytes, rather than a transport crate's Rust type,
    // are the identity boundary. Refuse invalid bytes before application code.
    let caller = Principal::try_from_slice(caller).map_err(|_| policy_denied(denied_boundary))?;
    if caller == Principal::anonymous() {
        return Err(policy_denied(denied_boundary));
    }

    let context = ReadAuthorizationContext { caller, surface };
    match guard(context) {
        ReadAuthorizationDecision::Allow => Ok(()),
        ReadAuthorizationDecision::Deny => Err(policy_denied(denied_boundary)),
    }
}

const fn policy_denied(boundary: RuntimeBoundaryCode) -> Error {
    Error::from_runtime_boundary(boundary, ErrorOrigin::Interface)
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use super::*;
    use ic_platform::principal::ExternalPrincipal;

    thread_local! {
        static GUARD_CALLS: Cell<u8> = const { Cell::new(0) };
        static OBSERVED_CONTEXT: Cell<Option<ReadAuthorizationContext>> = const { Cell::new(None) };
    }

    fn principal(seed: u8) -> Principal {
        Principal::self_authenticating([seed; 32])
    }

    fn counting_allow(context: ReadAuthorizationContext) -> ReadAuthorizationDecision {
        assert_eq!(context.surface, ReadAuthorizationSurface::Sql);
        GUARD_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
        ReadAuthorizationDecision::Allow
    }

    fn counting_deny(context: ReadAuthorizationContext) -> ReadAuthorizationDecision {
        assert_eq!(context.surface, ReadAuthorizationSurface::Sql);
        GUARD_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
        ReadAuthorizationDecision::Deny
    }

    fn counting_schema_allow(context: ReadAuthorizationContext) -> ReadAuthorizationDecision {
        assert_eq!(context.surface, ReadAuthorizationSurface::Schema);
        GUARD_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
        ReadAuthorizationDecision::Allow
    }

    fn take_guard_calls() -> u8 {
        GUARD_CALLS.with(|calls| calls.replace(0))
    }

    #[test]
    fn allowlist_is_bounded_exact_and_fail_closed() {
        let reader = principal(1);
        let outsider = principal(2);
        let reader_context = ReadAuthorizationContext {
            caller: reader,
            surface: ReadAuthorizationSurface::Sql,
        };

        assert_eq!(
            allowlist(reader_context, &[]),
            ReadAuthorizationDecision::Deny
        );
        assert_eq!(
            allowlist(reader_context, &[outsider, reader, reader]),
            ReadAuthorizationDecision::Allow,
        );
        assert_eq!(
            allowlist(
                ReadAuthorizationContext {
                    caller: outsider,
                    surface: ReadAuthorizationSurface::Sql,
                },
                &[reader],
            ),
            ReadAuthorizationDecision::Deny,
        );
        assert_eq!(
            allowlist(
                ReadAuthorizationContext {
                    caller: Principal::anonymous(),
                    surface: ReadAuthorizationSurface::Sql,
                },
                &[Principal::anonymous()],
            ),
            ReadAuthorizationDecision::Deny,
        );

        let maximum = [reader; MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS];
        assert_eq!(
            allowlist(reader_context, &maximum),
            ReadAuthorizationDecision::Allow,
        );
        let over_capacity = [reader; MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS + 1];
        assert_eq!(
            allowlist(reader_context, &over_capacity),
            ReadAuthorizationDecision::Deny,
        );
    }

    #[test]
    fn surface_allowlist_preserves_bounded_admission_and_denies_other_surfaces() {
        let reader = principal(1);
        let outsider = principal(2);
        for granted in [
            ReadAuthorizationSurface::Sql,
            ReadAuthorizationSurface::Schema,
        ] {
            for observed in [
                ReadAuthorizationSurface::Sql,
                ReadAuthorizationSurface::Schema,
            ] {
                for caller in [reader, outsider, Principal::anonymous()] {
                    for readers in [
                        vec![],
                        vec![reader],
                        vec![Principal::anonymous()],
                        vec![reader; MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS],
                        vec![reader; MAX_READ_AUTHORIZATION_ALLOWLIST_PRINCIPALS + 1],
                    ] {
                        let context = ReadAuthorizationContext {
                            caller,
                            surface: observed,
                        };
                        let expected = if granted == observed {
                            allowlist(context, &readers)
                        } else {
                            ReadAuthorizationDecision::Deny
                        };
                        assert_eq!(allowlist_for_surface(context, granted, &readers), expected);
                    }
                }
            }
        }
        let schema_guard = |context| {
            allowlist_for_surface(context, ReadAuthorizationSurface::Schema, &[principal(1)])
        };
        assert_eq!(authorize_schema_read(reader, schema_guard), Ok(()));
        assert_eq!(
            authorize_sql_read(reader, schema_guard).unwrap_err().code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SQL_SURFACE_POLICY_DENIED,
        );
    }

    #[test]
    fn sql_authorization_rejects_anonymous_without_calling_application_code() {
        take_guard_calls();

        let error = authorize_sql_read(Principal::anonymous(), counting_allow)
            .expect_err("anonymous SQL read should be denied");

        assert_eq!(
            error.code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SQL_SURFACE_POLICY_DENIED,
        );
        assert_eq!(take_guard_calls(), 0);
    }

    #[test]
    fn sql_authorization_invokes_one_guard_once_and_preserves_its_decision() {
        take_guard_calls();
        let caller = principal(3);

        assert_eq!(authorize_sql_read(caller, counting_allow), Ok(()));
        assert_eq!(take_guard_calls(), 1);

        let error = authorize_sql_read(caller, counting_deny)
            .expect_err("application denial should be returned");
        assert_eq!(
            error.code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SQL_SURFACE_POLICY_DENIED,
        );
        assert_eq!(take_guard_calls(), 1);
    }

    #[test]
    fn schema_authorization_uses_schema_context_and_schema_denial() {
        take_guard_calls();
        let caller = principal(11);
        assert_eq!(authorize_schema_read(caller, counting_schema_allow), Ok(()));
        assert_eq!(take_guard_calls(), 1);

        let error = authorize_schema_read(Principal::anonymous(), counting_schema_allow)
            .expect_err("anonymous schema reads must fail before the guard");
        assert_eq!(
            error.code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SCHEMA_SURFACE_POLICY_DENIED,
        );
        assert_eq!(take_guard_calls(), 0);
    }

    #[test]
    fn external_callers_preserve_identity_and_authorization() {
        let caller = principal(7);
        let external = ExternalPrincipal::from(caller);
        let sql_guard = |context: ReadAuthorizationContext| {
            assert_eq!(context.caller, principal(7));
            assert_eq!(context.surface, ReadAuthorizationSurface::Sql);
            ReadAuthorizationDecision::Allow
        };
        let schema_guard = |context: ReadAuthorizationContext| {
            assert_eq!(context.caller, principal(7));
            assert_eq!(context.surface, ReadAuthorizationSurface::Schema);
            ReadAuthorizationDecision::Allow
        };
        assert_eq!(authorize_sql_read(external, sql_guard), Ok(()));
        assert_eq!(authorize_schema_read(external, schema_guard), Ok(()));
        assert_eq!(
            authorize_sql_read(ExternalPrincipal::anonymous(), sql_guard)
                .expect_err("anonymous transport caller must be denied before its guard")
                .code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SQL_SURFACE_POLICY_DENIED,
        );
        assert_eq!(
            authorize_schema_read(ExternalPrincipal::anonymous(), schema_guard)
                .expect_err("anonymous transport caller must be denied before its guard")
                .code(),
            crate::ErrorCode::RUNTIME_BOUNDARY_SCHEMA_SURFACE_POLICY_DENIED,
        );
    }

    #[test]
    fn caller_bytes_preserve_all_canonical_lengths_on_both_surfaces() {
        fn record(context: ReadAuthorizationContext) -> ReadAuthorizationDecision {
            OBSERVED_CONTEXT.with(|observed| observed.set(Some(context)));
            ReadAuthorizationDecision::Allow
        }

        let bytes = [2; Principal::MAX_LENGTH_IN_BYTES];
        for length in 0..=bytes.len() {
            let caller = &bytes[..length];
            let expected = Principal::from_slice(caller);
            assert_eq!(authorize_sql_read(caller, record), Ok(()));
            assert_eq!(
                OBSERVED_CONTEXT.with(Cell::take),
                Some(ReadAuthorizationContext {
                    caller: expected,
                    surface: ReadAuthorizationSurface::Sql,
                }),
            );
            assert_eq!(authorize_schema_read(caller, record), Ok(()));
            assert_eq!(
                OBSERVED_CONTEXT.with(Cell::take),
                Some(ReadAuthorizationContext {
                    caller: expected,
                    surface: ReadAuthorizationSurface::Schema,
                }),
            );
        }
    }

    #[test]
    fn invalid_caller_bytes_deny_before_guard_invocation() {
        take_guard_calls();
        let invalid = [0; Principal::MAX_LENGTH_IN_BYTES + 1];
        let anonymous = Principal::anonymous();
        for caller in [invalid.as_slice(), anonymous.as_slice()] {
            assert_eq!(
                authorize_sql_read(caller, counting_allow)
                    .expect_err("invalid or anonymous SQL caller must be denied")
                    .code(),
                crate::ErrorCode::RUNTIME_BOUNDARY_SQL_SURFACE_POLICY_DENIED,
            );
            assert_eq!(
                authorize_schema_read(caller, counting_schema_allow)
                    .expect_err("invalid or anonymous schema caller must be denied")
                    .code(),
                crate::ErrorCode::RUNTIME_BOUNDARY_SCHEMA_SURFACE_POLICY_DENIED,
            );
        }
        assert_eq!(take_guard_calls(), 0);
    }
}