astrid-kernel 0.7.0

Astrid micro-kernel, the core of the Astrid OS
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
//! Unit tests for the Layer 6 admin module (issue #672).
//!
//! Two tiers:
//!
//! 1. **Pure mapping tests** — exhaustiveness of
//!    [`required_capability_for_admin_request`], scope resolution,
//!    audit-method labels, and response-topic construction.
//! 2. **Composition tests** — reassemble the same pieces the runtime
//!    uses ([`GroupConfig`] + [`PrincipalProfile`] +
//!    [`CapabilityCheck`]) and assert the post-condition invariants
//!    (cross-tenant deny for `agent`, ArcSwap hot-reload observed by the
//!    next check, cache invalidation reflects on-disk writes,
//!    revoke-precedence preserved across a subsequent grant).

use std::sync::Arc;

use astrid_capabilities::CapabilityCheck;
use astrid_core::principal::PrincipalId;
use astrid_core::{GroupConfig, PrincipalProfile};
use astrid_events::kernel_api::AdminRequestKind;

use super::{
    AuthorityScope, admin_request_method, admin_response_topic, admin_target_principal,
    required_capability_for_admin_request, resolve_admin_scope,
};

fn pid(name: &str) -> PrincipalId {
    PrincipalId::new(name).unwrap()
}

fn all_admin_variants() -> Vec<AdminRequestKind> {
    vec![
        AdminRequestKind::AgentCreate {
            name: "n".into(),
            groups: Vec::new(),
            grants: Vec::new(),
        },
        AdminRequestKind::AgentDelete {
            principal: pid("a"),
        },
        AdminRequestKind::AgentEnable {
            principal: pid("a"),
        },
        AdminRequestKind::AgentDisable {
            principal: pid("a"),
        },
        AdminRequestKind::AgentList,
        AdminRequestKind::QuotaSet {
            principal: pid("a"),
            quotas: astrid_core::profile::Quotas::default(),
        },
        AdminRequestKind::QuotaGet {
            principal: pid("a"),
        },
        AdminRequestKind::GroupCreate {
            name: "ops".into(),
            capabilities: vec!["capsule:install".into()],
            description: None,
            unsafe_admin: false,
        },
        AdminRequestKind::GroupDelete { name: "ops".into() },
        AdminRequestKind::GroupModify {
            name: "ops".into(),
            capabilities: None,
            description: None,
            unsafe_admin: None,
        },
        AdminRequestKind::GroupList,
        AdminRequestKind::CapsGrant {
            principal: pid("a"),
            capabilities: vec!["self:capsule:install".into()],
            unsafe_admin: false,
        },
        AdminRequestKind::CapsRevoke {
            principal: pid("a"),
            capabilities: vec!["self:*".into()],
        },
    ]
}

fn agent_profile() -> PrincipalProfile {
    let mut p = PrincipalProfile::default();
    p.groups = vec!["agent".to_string()];
    p
}

fn admin_profile() -> PrincipalProfile {
    let mut p = PrincipalProfile::default();
    p.groups = vec!["admin".to_string()];
    p
}

fn authorize_with(
    profile: &PrincipalProfile,
    groups: &GroupConfig,
    caller: &PrincipalId,
    cap: &str,
) -> bool {
    CapabilityCheck::new(profile, groups, caller.clone())
        .require(cap)
        .is_ok()
}

// ── Pure mapping tests ────────────────────────────────────────────────

#[test]
fn every_variant_has_non_empty_mapping_in_both_scopes() {
    for req in all_admin_variants() {
        for scope in [AuthorityScope::Self_, AuthorityScope::Global] {
            let cap = required_capability_for_admin_request(&req, scope);
            assert!(
                !cap.is_empty(),
                "required_capability_for_admin_request returned empty for \
                 {req:?} at {scope:?}"
            );
        }
    }
}

#[test]
fn quota_self_vs_global_mapping_distinguishes_principal() {
    let req = AdminRequestKind::QuotaSet {
        principal: pid("alice"),
        quotas: astrid_core::profile::Quotas::default(),
    };
    assert_eq!(
        required_capability_for_admin_request(&req, AuthorityScope::Self_),
        "self:quota:set"
    );
    assert_eq!(
        required_capability_for_admin_request(&req, AuthorityScope::Global),
        "quota:set"
    );
}

#[test]
fn agent_list_maps_self_to_self_prefix() {
    assert_eq!(
        required_capability_for_admin_request(&AdminRequestKind::AgentList, AuthorityScope::Self_),
        "self:agent:list"
    );
    assert_eq!(
        required_capability_for_admin_request(&AdminRequestKind::AgentList, AuthorityScope::Global),
        "agent:list"
    );
}

#[test]
fn every_variant_has_a_method_label() {
    for req in all_admin_variants() {
        let m = admin_request_method(&req);
        assert!(
            m.starts_with("admin."),
            "method must start with admin.: {m}"
        );
    }
}

#[test]
fn resolve_admin_scope_self_when_target_is_caller() {
    let caller = pid("alice");
    let req = AdminRequestKind::QuotaSet {
        principal: caller.clone(),
        quotas: astrid_core::profile::Quotas::default(),
    };
    assert_eq!(resolve_admin_scope(&req, &caller), AuthorityScope::Self_);
}

#[test]
fn resolve_admin_scope_global_when_target_differs() {
    let caller = pid("alice");
    let req = AdminRequestKind::QuotaSet {
        principal: pid("bob"),
        quotas: astrid_core::profile::Quotas::default(),
    };
    assert_eq!(resolve_admin_scope(&req, &caller), AuthorityScope::Global);
}

#[test]
fn admin_target_principal_some_for_cross_tenant_variants() {
    assert!(
        admin_target_principal(&AdminRequestKind::QuotaSet {
            principal: pid("a"),
            quotas: astrid_core::profile::Quotas::default(),
        })
        .is_some()
    );
    assert!(
        admin_target_principal(&AdminRequestKind::CapsGrant {
            principal: pid("a"),
            capabilities: vec!["self:capsule:install".into()],
            unsafe_admin: false,
        })
        .is_some()
    );
}

#[test]
fn admin_target_principal_none_for_self_or_collection_variants() {
    assert!(admin_target_principal(&AdminRequestKind::AgentList).is_none());
    assert!(admin_target_principal(&AdminRequestKind::GroupList).is_none());
    assert!(
        admin_target_principal(&AdminRequestKind::AgentCreate {
            name: "n".into(),
            groups: Vec::new(),
            grants: Vec::new(),
        })
        .is_none()
    );
}

#[test]
fn admin_response_topic_mirrors_request_prefix() {
    assert_eq!(
        admin_response_topic("astrid.v1.admin.agent.create"),
        "astrid.v1.admin.response.agent.create"
    );
    assert_eq!(
        admin_response_topic("astrid.v1.admin.quota.set"),
        "astrid.v1.admin.response.quota.set"
    );
    // Pass-through when there's no prefix — defensive, shouldn't
    // happen from a well-formed event but avoids panicking.
    assert_eq!(admin_response_topic("other.topic"), "other.topic");
}

// ── Enforcement composition ──────────────────────────────────────────

#[test]
fn agent_denied_cross_tenant_every_admin_topic() {
    let groups = GroupConfig::builtin_only();
    let profile = agent_profile();
    let caller = pid("agent_user");

    for req in all_admin_variants() {
        let method = admin_request_method(&req);
        let scope = resolve_admin_scope(&req, &caller);
        let cap = required_capability_for_admin_request(&req, scope);
        let self_allowed = matches!(scope, AuthorityScope::Self_);

        let allowed = authorize_with(&profile, &groups, &caller, cap);
        if self_allowed {
            assert!(
                allowed,
                "agent should be allowed self-scoped {method} ({cap})",
            );
        } else {
            assert!(
                !allowed,
                "agent should be denied cross-tenant {method} ({cap})",
            );
        }
    }
}

#[test]
fn admin_allowed_every_admin_topic() {
    let groups = GroupConfig::builtin_only();
    let profile = admin_profile();
    let caller = pid("admin_user");

    for req in all_admin_variants() {
        let method = admin_request_method(&req);
        let scope = resolve_admin_scope(&req, &caller);
        let cap = required_capability_for_admin_request(&req, scope);
        assert!(
            authorize_with(&profile, &groups, &caller, cap),
            "admin group should be allowed {method} ({cap})",
        );
    }
}

#[test]
fn agent_holds_self_admin_caps_added_in_layer_6() {
    // The Layer 6 contract bump: built-in `agent` group gains
    // self:quota:get + self:agent:list. Verify both resolve through
    // the group config, not just via `self:*`.
    let groups = GroupConfig::builtin_only();
    let profile = agent_profile();
    let caller = pid("agent_user");

    let agent_group = groups.get("agent").unwrap();
    assert!(
        agent_group
            .capabilities
            .iter()
            .any(|c| c == "self:quota:get")
    );
    assert!(
        agent_group
            .capabilities
            .iter()
            .any(|c| c == "self:agent:list")
    );
    assert!(authorize_with(&profile, &groups, &caller, "self:quota:get"));
    assert!(authorize_with(
        &profile,
        &groups,
        &caller,
        "self:agent:list"
    ));
}

// ── ArcSwap hot-reload design invariant ──────────────────────────────

#[test]
fn arcswap_groups_swap_observed_by_next_check() {
    use arc_swap::ArcSwap;
    use astrid_core::groups::Group;

    let swap: Arc<ArcSwap<GroupConfig>> =
        Arc::new(ArcSwap::from_pointee(GroupConfig::builtin_only()));

    let profile = {
        let mut p = PrincipalProfile::default();
        p.groups = vec!["ops".to_string()];
        p
    };
    let caller = pid("ops_user");

    // Pre-swap: `ops` is unknown → fail-closed deny.
    let before = swap.load_full();
    assert!(!authorize_with(
        &profile,
        before.as_ref(),
        &caller,
        "capsule:install"
    ));

    // Atomically replace with a config that includes `ops`.
    let next = GroupConfig::builtin_only()
        .insert_custom_group(
            "ops".to_string(),
            Group {
                capabilities: vec!["capsule:install".into()],
                description: None,
                unsafe_admin: false,
            },
        )
        .unwrap();
    swap.store(Arc::new(next));

    // Post-swap check sees the new config.
    let after = swap.load_full();
    assert!(authorize_with(
        &profile,
        after.as_ref(),
        &caller,
        "capsule:install"
    ));

    // And an `Arc` cloned before the swap still sees the OLD config —
    // atomic hand-off is per-load, not per-instance.
    assert!(!authorize_with(
        &profile,
        before.as_ref(),
        &caller,
        "capsule:install"
    ));
}

// ── Cache invalidation design invariant ──────────────────────────────

#[test]
fn profile_cache_invalidation_reflects_on_disk_mutation() {
    use astrid_capsule::profile_cache::PrincipalProfileCache;
    use astrid_core::dirs::AstridHome;

    let dir = tempfile::tempdir().unwrap();
    let home = AstridHome::from_path(dir.path());
    let cache = PrincipalProfileCache::with_home(home.clone());
    let principal = pid("alice");

    // First resolve: missing file → Default (enabled=true, no grants).
    let first = cache.resolve(&principal).unwrap();
    assert!(first.enabled);
    assert!(first.grants.is_empty());

    // Write a populated profile to disk behind the cache's back.
    let mut updated = PrincipalProfile::default();
    updated.grants = vec!["self:capsule:install".into()];
    let path = PrincipalProfile::path_for(&home, &principal);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    updated.save_to_path(&path).unwrap();

    // Without invalidate, cache returns stale Default.
    let stale = cache.resolve(&principal).unwrap();
    assert!(stale.grants.is_empty());

    // After invalidate, next resolve sees the new grants.
    cache.invalidate(&principal);
    let fresh = cache.resolve(&principal).unwrap();
    assert_eq!(fresh.grants, vec!["self:capsule:install".to_string()]);
}

// ── Revoke precedence across grant/revoke mutations ─────────────────

#[test]
fn caps_grant_preserves_revoke_precedence() {
    // Adversarial: pre-existing `self:*` revoke + a fresh
    // `self:capsule:install` grant → authz check still denies
    // (revoke > grant). This is the sequence
    // `handlers::mutate_caps(_, Grant)` produces when the target
    // profile already has revokes.
    let mut profile = PrincipalProfile::default();
    profile.groups = vec!["admin".to_string()];
    profile.revokes = vec!["self:*".to_string()];
    profile.grants.push("self:capsule:install".to_string());

    let groups = GroupConfig::builtin_only();
    let caller = pid("alice");
    let check = CapabilityCheck::new(&profile, &groups, caller);
    let err = check.require("self:capsule:install").unwrap_err();
    assert!(
        matches!(
            err,
            astrid_capabilities::PermissionError::RevokedCapability { .. }
        ),
        "grant must not clear matching revoke: {err:?}"
    );
}

#[test]
fn caps_revoke_of_unheld_capability_is_not_an_error_shape() {
    // Pre-emptive revoke: principal doesn't hold X yet, we revoke X,
    // the revoke vec just appends. Later grants/groups are dominated
    // by the revoke.
    let mut profile = PrincipalProfile::default();
    profile.groups = vec!["restricted".to_string()];
    profile.revokes.push("capsule:install".to_string()); // pre-emptive
    profile.grants.push("capsule:install".to_string());

    let groups = GroupConfig::builtin_only();
    let caller = pid("alice");
    let check = CapabilityCheck::new(&profile, &groups, caller);
    assert!(check.require("capsule:install").is_err(), "revoke wins");
}