chio-kernel-core 0.1.0

Portable (no_std + alloc) Chio kernel core: pure verdict evaluation, capability verification, and receipt signing
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
//! Portable scope matching for tool grants.
//!
//! This module implements portable scope matching for tool grants.
//!
//! The hosted kernel still carries the richest matcher in
//! `chio-kernel::request_matching`, but the portable core must never
//! silently drop a grant constraint. Constraints that can be evaluated
//! from request arguments are enforced here; constraints that require
//! richer kernel state (governed intent, runtime attestation, SQL result
//! inspection, regex compilation, etc.) fail closed with an explicit
//! error instead of widening scope.
//!
//! Callers that want the full constraint pipeline continue to go through
//! `chio_kernel::capability_matches_request` -- the public API in the
//! orchestration shell is unchanged. This function is the pure-compute
//! kernel the portable adapters will consume directly.
//!
//! Verified-core boundary note:
//! `formal/proof-manifest.toml` includes the portable matcher because it is
//! the fail-closed subset of scope evaluation that never reaches into stores,
//! regex engines, runtime-attestation records, or governed-transaction state.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use chio_core_types::capability::{CapabilityToken, ChioScope, Constraint, Operation, ToolGrant};

/// Borrowed match result, ordered by specificity.
///
/// Mirrors the layout of `chio_kernel::MatchingGrant` but is exposed
/// publicly so portable adapters can rank and iterate matches without
/// re-running the sort.
#[derive(Debug, Clone, Copy)]
pub struct MatchedGrant<'a> {
    /// Index of this grant inside the scope's grant vector.
    pub index: usize,
    /// The matched grant itself.
    pub grant: &'a ToolGrant,
    /// Specificity tuple: `(server-exact, tool-exact, constraint-count)`.
    pub specificity: (u8, u8, usize),
}

/// Errors that can be raised by the portable scope matcher.
///
/// The full matcher in `chio-kernel` surfaces richer error variants
/// (invalid-constraint, attestation-trust, etc.); the portable core
/// returns the two coarse-grained cases that do not require regex or
/// other IO-adjacent machinery.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScopeMatchError {
    /// No grant in the scope covers the requested `(server, tool, Invoke)`.
    OutOfScope,
    /// The portable kernel cannot safely evaluate a constraint carried by a
    /// target-matching grant.
    ConstraintError(String),
}

/// Resolve the set of grants that authorise a tool invocation on the
/// given server.
///
/// Returns the matched grants sorted by decreasing specificity
/// (exact-exact first, then exact-wildcard, then wildcard-wildcard; ties
/// broken by grant-list order).
pub fn resolve_matching_grants<'a>(
    scope: &'a ChioScope,
    tool_name: &str,
    server_id: &str,
    arguments: &serde_json::Value,
) -> Result<Vec<MatchedGrant<'a>>, ScopeMatchError> {
    let mut matches: Vec<MatchedGrant<'a>> = Vec::new();

    for (index, grant) in scope.grants.iter().enumerate() {
        let covered = match grant_covers(grant, tool_name, server_id, arguments) {
            Ok(covered) => covered,
            Err(error @ ScopeMatchError::ConstraintError(_)) => return Err(error),
            Err(error) => return Err(error),
        };
        if !covered {
            continue;
        }

        matches.push(MatchedGrant {
            index,
            grant,
            specificity: (
                u8::from(grant.server_id == server_id),
                u8::from(grant.tool_name == tool_name),
                grant.constraints.len(),
            ),
        });
    }

    matches.sort_by(|left, right| {
        right
            .specificity
            .cmp(&left.specificity)
            .then_with(|| left.index.cmp(&right.index))
    });

    Ok(matches)
}

/// Convenience wrapper that runs [`resolve_matching_grants`] against a
/// full capability token.
pub fn resolve_capability_grants<'a>(
    capability: &'a CapabilityToken,
    tool_name: &str,
    server_id: &str,
    arguments: &serde_json::Value,
) -> Result<Vec<MatchedGrant<'a>>, ScopeMatchError> {
    let matches = resolve_matching_grants(&capability.scope, tool_name, server_id, arguments)?;
    if matches.is_empty() {
        return Err(ScopeMatchError::OutOfScope);
    }
    Ok(matches)
}

fn grant_covers(
    grant: &ToolGrant,
    tool_name: &str,
    server_id: &str,
    arguments: &serde_json::Value,
) -> Result<bool, ScopeMatchError> {
    Ok(matches_pattern(&grant.server_id, server_id)
        && matches_pattern(&grant.tool_name, tool_name)
        && grant.operations.contains(&Operation::Invoke)
        && constraints_match(&grant.constraints, arguments)?)
}

fn constraints_match(
    constraints: &[Constraint],
    arguments: &serde_json::Value,
) -> Result<bool, ScopeMatchError> {
    for constraint in constraints {
        if !constraint_matches(constraint, arguments)? {
            return Ok(false);
        }
    }
    Ok(true)
}

fn constraint_matches(
    constraint: &Constraint,
    arguments: &serde_json::Value,
) -> Result<bool, ScopeMatchError> {
    let string_leaves = collect_string_leaves(arguments);

    match constraint {
        Constraint::PathPrefix(prefix) => {
            let candidates: Vec<&str> = string_leaves
                .iter()
                .filter(|leaf| {
                    leaf.key.as_deref().is_some_and(is_path_key) || looks_like_path(&leaf.value)
                })
                .map(|leaf| leaf.value.as_str())
                .collect();
            Ok(!candidates.is_empty()
                && candidates
                    .into_iter()
                    .all(|path| path_has_prefix(path, prefix)))
        }
        Constraint::DomainExact(expected) => {
            let expected = normalize_domain(expected);
            let domains = collect_domain_candidates(&string_leaves);
            Ok(!domains.is_empty() && domains.into_iter().all(|domain| domain == expected))
        }
        Constraint::DomainGlob(pattern) => {
            let pattern = pattern.to_ascii_lowercase();
            let domains = collect_domain_candidates(&string_leaves);
            Ok(!domains.is_empty()
                && domains
                    .into_iter()
                    .all(|domain| wildcard_matches(&pattern, &domain)))
        }
        Constraint::MaxLength(max) => Ok(string_leaves.iter().all(|leaf| leaf.value.len() <= *max)),
        Constraint::MaxArgsSize(max) => Ok(arguments.to_string().len() <= *max),
        Constraint::Custom(key, expected) => Ok(argument_contains_custom(arguments, key, expected)),
        Constraint::AudienceAllowlist(allowed) => {
            Ok(audience_allowlist_matches(arguments, allowed))
        }
        Constraint::MemoryStoreAllowlist(allowed) => {
            Ok(memory_store_allowlist_matches(arguments, allowed))
        }
        Constraint::RegexMatch(_)
        | Constraint::GovernedIntentRequired
        | Constraint::RequireApprovalAbove { .. }
        | Constraint::SellerExact(_)
        | Constraint::MinimumRuntimeAssurance(_)
        | Constraint::MinimumAutonomyTier(_)
        | Constraint::TableAllowlist(_)
        | Constraint::ColumnDenylist(_)
        | Constraint::MaxRowsReturned(_)
        | Constraint::OperationClass(_)
        | Constraint::ContentReviewTier(_)
        | Constraint::MaxTransactionAmountUsd(_)
        | Constraint::RequireDualApproval(_)
        | Constraint::ModelConstraint { .. }
        | Constraint::MemoryWriteDenyPatterns(_) => Err(ScopeMatchError::ConstraintError(format!(
            "portable kernel cannot safely evaluate {}",
            constraint_name(constraint)
        ))),
    }
}

fn matches_pattern(pattern: &str, candidate: &str) -> bool {
    pattern == "*" || pattern == candidate
}

fn path_has_prefix(candidate: &str, prefix: &str) -> bool {
    let Some(candidate) = normalize_path(candidate) else {
        return false;
    };
    let Some(prefix) = normalize_path(prefix) else {
        return false;
    };
    if candidate.is_absolute != prefix.is_absolute {
        return false;
    }
    if prefix.segments.len() > candidate.segments.len() {
        return false;
    }
    prefix
        .segments
        .iter()
        .zip(candidate.segments.iter())
        .all(|(expected, actual)| expected == actual)
}

#[derive(Debug, PartialEq, Eq)]
struct NormalizedPath {
    is_absolute: bool,
    segments: Vec<String>,
}

fn normalize_path(path: &str) -> Option<NormalizedPath> {
    let is_absolute = path.starts_with('/') || path.starts_with('\\');
    let mut segments = Vec::new();
    for segment in path.split(['/', '\\']) {
        if segment.is_empty() || segment == "." {
            continue;
        }
        if segment == ".." {
            segments.pop()?;
            continue;
        }
        segments.push(segment.to_string());
    }
    Some(NormalizedPath {
        is_absolute,
        segments,
    })
}

fn constraint_name(constraint: &Constraint) -> &'static str {
    match constraint {
        Constraint::PathPrefix(_) => "path_prefix",
        Constraint::DomainExact(_) => "domain_exact",
        Constraint::DomainGlob(_) => "domain_glob",
        Constraint::RegexMatch(_) => "regex_match",
        Constraint::MaxLength(_) => "max_length",
        Constraint::MaxArgsSize(_) => "max_args_size",
        Constraint::GovernedIntentRequired => "governed_intent_required",
        Constraint::RequireApprovalAbove { .. } => "require_approval_above",
        Constraint::SellerExact(_) => "seller_exact",
        Constraint::MinimumRuntimeAssurance(_) => "minimum_runtime_assurance",
        Constraint::MinimumAutonomyTier(_) => "minimum_autonomy_tier",
        Constraint::Custom(_, _) => "custom",
        Constraint::TableAllowlist(_) => "table_allowlist",
        Constraint::ColumnDenylist(_) => "column_denylist",
        Constraint::MaxRowsReturned(_) => "max_rows_returned",
        Constraint::OperationClass(_) => "operation_class",
        Constraint::AudienceAllowlist(_) => "audience_allowlist",
        Constraint::ContentReviewTier(_) => "content_review_tier",
        Constraint::MaxTransactionAmountUsd(_) => "max_transaction_amount_usd",
        Constraint::RequireDualApproval(_) => "require_dual_approval",
        Constraint::ModelConstraint { .. } => "model_constraint",
        Constraint::MemoryStoreAllowlist(_) => "memory_store_allowlist",
        Constraint::MemoryWriteDenyPatterns(_) => "memory_write_deny_patterns",
    }
}

#[derive(Clone)]
struct StringLeaf {
    key: Option<String>,
    value: String,
}

fn collect_string_leaves(arguments: &serde_json::Value) -> Vec<StringLeaf> {
    let mut leaves = Vec::new();
    collect_string_leaves_inner(arguments, None, &mut leaves);
    leaves
}

fn collect_string_leaves_inner(
    arguments: &serde_json::Value,
    current_key: Option<&str>,
    leaves: &mut Vec<StringLeaf>,
) {
    match arguments {
        serde_json::Value::String(value) => leaves.push(StringLeaf {
            key: current_key.map(str::to_string),
            value: value.clone(),
        }),
        serde_json::Value::Array(values) => {
            for value in values {
                collect_string_leaves_inner(value, current_key, leaves);
            }
        }
        serde_json::Value::Object(map) => {
            for (key, value) in map {
                collect_string_leaves_inner(value, Some(key), leaves);
            }
        }
        serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {}
    }
}

fn is_path_key(key: &str) -> bool {
    let key = key.to_ascii_lowercase();
    key.contains("path")
        || matches!(
            key.as_str(),
            "file" | "filepath" | "dir" | "directory" | "root" | "cwd"
        )
}

fn looks_like_path(value: &str) -> bool {
    !value.contains("://")
        && (value.starts_with('/')
            || value.starts_with("./")
            || value.starts_with("../")
            || value.starts_with("~/")
            || value.contains('/')
            || value.contains('\\'))
}

fn collect_domain_candidates(string_leaves: &[StringLeaf]) -> Vec<String> {
    string_leaves
        .iter()
        .filter_map(|leaf| parse_domain(&leaf.value))
        .collect()
}

fn parse_domain(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    let host_port = if let Some((_, rest)) = trimmed.split_once("://") {
        rest
    } else {
        trimmed
    };

    let authority = host_port
        .split(['/', '?', '#'])
        .next()
        .unwrap_or(host_port)
        .rsplit('@')
        .next()
        .unwrap_or(host_port);
    let host = authority
        .split(':')
        .next()
        .unwrap_or(authority)
        .trim_matches('.');
    let normalized = normalize_domain(host);

    if normalized == "localhost"
        || (!normalized.is_empty()
            && normalized.contains('.')
            && normalized.chars().all(|character| {
                character.is_ascii_alphanumeric() || character == '-' || character == '.'
            }))
    {
        Some(normalized)
    } else {
        None
    }
}

fn normalize_domain(value: &str) -> String {
    value.trim().trim_matches('.').to_ascii_lowercase()
}

fn wildcard_matches(pattern: &str, candidate: &str) -> bool {
    let pattern_chars: Vec<char> = pattern.chars().collect();
    let candidate_chars: Vec<char> = candidate.chars().collect();
    let (mut pattern_idx, mut candidate_idx) = (0usize, 0usize);
    let (mut star_idx, mut match_idx) = (None, 0usize);

    while candidate_idx < candidate_chars.len() {
        if pattern_idx < pattern_chars.len()
            && (pattern_chars[pattern_idx] == candidate_chars[candidate_idx]
                || pattern_chars[pattern_idx] == '*')
        {
            if pattern_chars[pattern_idx] == '*' {
                star_idx = Some(pattern_idx);
                match_idx = candidate_idx;
                pattern_idx += 1;
            } else {
                pattern_idx += 1;
                candidate_idx += 1;
            }
        } else if let Some(star_position) = star_idx {
            pattern_idx = star_position + 1;
            match_idx += 1;
            candidate_idx = match_idx;
        } else {
            return false;
        }
    }

    while pattern_idx < pattern_chars.len() && pattern_chars[pattern_idx] == '*' {
        pattern_idx += 1;
    }

    pattern_idx == pattern_chars.len()
}

fn argument_contains_custom(arguments: &serde_json::Value, key: &str, expected: &str) -> bool {
    match arguments {
        serde_json::Value::Object(map) => map.iter().any(|(entry_key, value)| {
            (entry_key == key && value.as_str() == Some(expected))
                || argument_contains_custom(value, key, expected)
        }),
        serde_json::Value::Array(values) => values
            .iter()
            .any(|value| argument_contains_custom(value, key, expected)),
        serde_json::Value::Null
        | serde_json::Value::Bool(_)
        | serde_json::Value::Number(_)
        | serde_json::Value::String(_) => false,
    }
}

fn audience_allowlist_matches(arguments: &serde_json::Value, allowed: &[String]) -> bool {
    let mut observed: Vec<String> = Vec::new();
    collect_audience_values(arguments, &mut observed);
    if observed.is_empty() {
        return true;
    }
    observed
        .iter()
        .all(|value| allowed.iter().any(|allowed_value| allowed_value == value))
}

fn collect_audience_values(arguments: &serde_json::Value, out: &mut Vec<String>) {
    match arguments {
        serde_json::Value::Object(map) => {
            for (key, value) in map {
                if is_audience_key(key) {
                    collect_string_values(value, out);
                } else {
                    collect_audience_values(value, out);
                }
            }
        }
        serde_json::Value::Array(values) => {
            for value in values {
                collect_audience_values(value, out);
            }
        }
        _ => {}
    }
}

fn is_audience_key(key: &str) -> bool {
    matches!(
        key.to_ascii_lowercase().as_str(),
        "recipient" | "recipients" | "audience" | "to" | "channel" | "channels"
    )
}

fn collect_string_values(value: &serde_json::Value, out: &mut Vec<String>) {
    match value {
        serde_json::Value::String(s) => out.push(s.clone()),
        serde_json::Value::Array(values) => {
            for value in values {
                collect_string_values(value, out);
            }
        }
        _ => {}
    }
}

fn memory_store_allowlist_matches(arguments: &serde_json::Value, allowed: &[String]) -> bool {
    let mut observed: Vec<String> = Vec::new();
    collect_memory_store_values(arguments, &mut observed);
    if observed.is_empty() {
        return true;
    }
    observed
        .iter()
        .all(|value| allowed.iter().any(|allowed_value| allowed_value == value))
}

fn collect_memory_store_values(arguments: &serde_json::Value, out: &mut Vec<String>) {
    match arguments {
        serde_json::Value::Object(map) => {
            for (key, value) in map {
                if is_memory_store_key(key) {
                    collect_string_values(value, out);
                } else {
                    collect_memory_store_values(value, out);
                }
            }
        }
        serde_json::Value::Array(values) => {
            for value in values {
                collect_memory_store_values(value, out);
            }
        }
        _ => {}
    }
}

fn is_memory_store_key(key: &str) -> bool {
    matches!(
        key.to_ascii_lowercase().as_str(),
        "store" | "memory_store" | "collection" | "namespace"
    )
}