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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/// Admin management API dispatcher (issue #672, Layer 6).
pub mod admin;

use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Instant;

use astrid_audit::{AuditAction, AuditOutcome, AuthorizationProof};
use astrid_capabilities::{CapabilityCheck, PermissionError};
use astrid_core::principal::PrincipalId;
use astrid_events::ipc::{IpcMessage, IpcPayload};
use astrid_events::kernel_api::{KernelRequest, KernelResponse};
use serde::Serialize;
use tracing::{debug, info, warn};

/// Spawns background tasks for the kernel management API and connection tracking.
///
/// Two listeners:
/// 1. `astrid.v1.request.*` - handles management commands (list capsules, reload, etc.)
/// 2. `client.v1.disconnect` - decrements the active connection counter on graceful disconnect.
///
/// Connection *increment* happens when the WASM proxy capsule accepts a socket
/// connection (it publishes a `client.v1.connected` event). For ungraceful disconnects,
/// the idle monitor uses `EventBus::subscriber_count()` as a secondary signal.
#[must_use]
pub(crate) fn spawn_kernel_router(kernel: Arc<crate::Kernel>) -> tokio::task::JoinHandle<()> {
    // Spawn the connection tracker as a sibling task.
    drop(spawn_connection_tracker(Arc::clone(&kernel)));
    // Spawn the Layer 6 admin dispatcher as a sibling task (issue #672).
    drop(admin::spawn_admin_router(Arc::clone(&kernel)));

    let mut receiver = kernel.event_bus.subscribe_topic("astrid.v1.request.*");

    tokio::spawn(async move {
        let mut rate_limiter = ManagementRateLimiter::new();

        while let Some(event) = receiver.recv().await {
            let astrid_events::AstridEvent::Ipc { message, .. } = &*event else {
                continue;
            };

            // Only process standard IPC messages that contain JSON payloads.
            let IpcPayload::RawJson(val) = &message.payload else {
                continue;
            };

            match serde_json::from_value::<KernelRequest>(val.clone()) {
                Ok(req) => {
                    let (method, limit) = rate_limit_for_request(&req);
                    if let Some(max) = limit
                        && !rate_limiter.check(method, max)
                    {
                        warn!(
                            security_event = true,
                            method = method,
                            "Rate limited kernel management request"
                        );
                        let response_topic =
                            message.topic.replace("kernel.request.", "kernel.response.");
                        publish_response(
                            &kernel,
                            response_topic,
                            KernelResponse::Error(format!(
                                "Rate limited: max {max} {method} requests per minute"
                            )),
                        );
                        continue;
                    }
                    let caller = resolve_caller(message);
                    handle_request(&kernel, message.topic.clone(), caller, req).await;
                },
                Err(e) => {
                    warn!(error = %e, topic = %message.topic, "Failed to parse KernelRequest from IPC");
                },
            }
        }
    })
}

/// Tracks client connection lifecycle events.
///
/// Listens on `client.v1.*` topics:
/// - `client.v1.connected` - a new socket connection was accepted.
/// - `client.v1.disconnect` - a client sent a graceful disconnect.
fn spawn_connection_tracker(kernel: Arc<crate::Kernel>) -> tokio::task::JoinHandle<()> {
    let mut receiver = kernel.event_bus.subscribe_topic("client.v1.*");

    tokio::spawn(async move {
        while let Some(event) = receiver.recv().await {
            let astrid_events::AstridEvent::Ipc { message, .. } = &*event else {
                continue;
            };
            // Derive the connecting principal from the IPC message. Today's
            // CLI socket always sets this to the default principal
            // (bootstrapped in `bootstrap_cli_root_user`), but as per-agent
            // socket auth lands (#658) the same plumbing will carry the
            // real invoking principal.
            let principal = message
                .principal
                .as_deref()
                .and_then(|p| astrid_core::principal::PrincipalId::new(p).ok())
                .unwrap_or_default();
            match &message.payload {
                IpcPayload::Disconnect { reason } => {
                    kernel.connection_closed(&principal);
                    debug!(%principal, reason = ?reason, "Client disconnected");
                },
                IpcPayload::Connect => {
                    kernel.connection_opened(&principal);
                    debug!(%principal, "New client connection accepted");
                },
                _ => {},
            }
        }
    })
}

#[expect(clippy::too_many_lines)]
async fn handle_request(
    kernel: &Arc<crate::Kernel>,
    topic: String,
    caller: PrincipalId,
    req: KernelRequest,
) {
    let response_topic = if let Some(suffix) = topic.strip_prefix("astrid.v1.request.") {
        format!("astrid.v1.response.{suffix}")
    } else {
        topic.clone()
    };

    // Capability enforcement preamble (issue #670). Resolve the caller's
    // profile, compute the required capability for this request, and
    // reject with an audited `Denied` entry on failure. No match arm
    // below is reached without `authorize_request` returning Ok.
    let method = kernel_request_method(&req);
    let scope = resolve_scope(&req, &caller);
    let required_cap = required_capability(&req, scope);
    match authorize_request(kernel, &caller, required_cap) {
        Ok(()) => {
            record_admin_audit(
                kernel,
                AdminAuditEntry {
                    caller: &caller,
                    method,
                    required_cap,
                    target_principal: None,
                    params: None,
                    authorization: AuthorizationProof::System {
                        reason: format!("policy allow: {caller} holds {required_cap}"),
                    },
                    outcome: AuditOutcome::success(),
                },
            );
        },
        Err(e) => {
            warn!(
                security_event = true,
                method = method,
                principal = %caller,
                required = required_cap,
                "Permission check denied admin request"
            );
            record_admin_audit(
                kernel,
                AdminAuditEntry {
                    caller: &caller,
                    method,
                    required_cap,
                    target_principal: None,
                    params: None,
                    authorization: AuthorizationProof::Denied {
                        reason: e.to_string(),
                    },
                    outcome: AuditOutcome::failure(e.to_string()),
                },
            );
            publish_response(kernel, response_topic, KernelResponse::Error(e.to_string()));
            return;
        },
    }

    let res = match req {
        KernelRequest::InstallCapsule { source, workspace } => {
            info!(source = %source, workspace, "Kernel received install request");
            // Here the kernel would verify identity, parse the capsule, and potentially
            // return ApprovalRequired if it needs dangerous capabilities!
            KernelResponse::Error(
                "Installation logic not yet implemented in kernel router".to_string(),
            )
        },
        KernelRequest::ApproveCapability {
            request_id,
            signature: _,
        } => {
            info!(request_id = %request_id, "Kernel received capability approval");
            KernelResponse::Error("Approval logic not yet implemented in kernel router".to_string())
        },
        KernelRequest::ListCapsules => {
            let reg = kernel.capsules.read().await;
            let mut list = Vec::new();
            for c in reg.list() {
                list.push(c.to_string());
            }
            KernelResponse::Success(serde_json::json!(list))
        },
        KernelRequest::GetCommands => {
            let reg = kernel.capsules.read().await;
            let mut commands = Vec::new();
            for c in reg.values() {
                for cmd in &c.manifest().commands {
                    commands.push(astrid_events::kernel_api::CommandInfo {
                        name: cmd.name.clone(),
                        description: cmd
                            .description
                            .clone()
                            .unwrap_or_else(|| "No description".to_string()),
                        provider_capsule: c.id().to_string(),
                    });
                }
            }
            info!(
                count = commands.len(),
                capsules = reg.len(),
                "GetCommands: returning {} commands from {} capsules",
                commands.len(),
                reg.len()
            );
            KernelResponse::Commands(commands)
        },
        KernelRequest::ReloadCapsules => {
            // Unregister capsules in a Failed state so they can be re-loaded
            // with fresh configuration (e.g. after onboarding writes .env.json).
            {
                let reg = kernel.capsules.read().await;
                let failed_ids: Vec<_> = reg
                    .list()
                    .into_iter()
                    .filter(|id| {
                        reg.get(id).is_some_and(|c| {
                            matches!(c.state(), astrid_capsule::capsule::CapsuleState::Failed(_))
                        })
                    })
                    .cloned()
                    .collect();
                drop(reg);

                let mut reg = kernel.capsules.write().await;
                for id in failed_ids {
                    let _ = reg.unregister(&id);
                }
            }

            kernel.load_all_capsules().await;
            KernelResponse::Success(serde_json::json!({"status": "reloaded"}))
        },
        KernelRequest::Shutdown { reason } => {
            info!(
                reason = reason.as_deref().unwrap_or("none"),
                "Kernel received shutdown request via management API"
            );
            // Publish response before signaling shutdown so the client gets confirmation.
            publish_response(
                kernel,
                response_topic.clone(),
                KernelResponse::Success(serde_json::json!({"status": "shutting_down"})),
            );
            // Signal the daemon's main loop to exit gracefully.
            let _ = kernel.shutdown_tx.send(true);
            // Return early — the daemon will call kernel.shutdown() from its main loop.
            return;
        },
        KernelRequest::GetStatus => {
            let uptime = kernel.boot_time.elapsed().as_secs();
            let reg = kernel.capsules.read().await;
            let loaded: Vec<String> = reg.list().iter().map(ToString::to_string).collect();
            let by_principal = kernel
                .connections_by_principal()
                .into_iter()
                .map(
                    |(p, c)| astrid_events::kernel_api::PrincipalConnectionCount {
                        principal: p.to_string(),
                        count: u32::try_from(c).unwrap_or(u32::MAX),
                    },
                )
                .collect();
            let status = astrid_events::kernel_api::DaemonStatus {
                pid: std::process::id(),
                uptime_secs: uptime,
                version: env!("CARGO_PKG_VERSION").to_string(),
                ephemeral: false, // The kernel doesn't know; daemon sets this via response override if needed
                connected_clients: u32::try_from(kernel.total_connection_count())
                    .unwrap_or(u32::MAX),
                connections_by_principal: by_principal,
                loaded_capsules: loaded,
            };
            KernelResponse::Status(status)
        },
        KernelRequest::GetCapsuleMetadata => {
            let reg = kernel.capsules.read().await;
            let mut entries = Vec::new();
            for capsule in reg.values() {
                let manifest = capsule.manifest();
                entries.push(astrid_events::kernel_api::CapsuleMetadataEntry {
                    name: manifest.package.name.clone(),
                    interceptor_events: manifest
                        .interceptors
                        .iter()
                        .map(|i| i.event.clone())
                        .collect(),
                });
            }
            KernelResponse::CapsuleMetadata(entries)
        },
    };

    publish_response(kernel, response_topic, res);
}

fn publish_response<R: Serialize>(kernel: &Arc<crate::Kernel>, response_topic: String, res: R) {
    if let Ok(val) = serde_json::to_value(res) {
        let msg = IpcMessage::new(
            response_topic,
            IpcPayload::RawJson(val),
            kernel.session_id.0,
        );
        let _ = kernel.event_bus.publish(astrid_events::AstridEvent::Ipc {
            metadata: astrid_events::EventMetadata::new("kernel_router"),
            message: msg,
        });
    }
}

// ---------------------------------------------------------------------------
// Management API rate limiting
// ---------------------------------------------------------------------------

/// Sliding window rate limiter for management API requests.
/// Tracks per-request timestamps and evicts entries older than 60 seconds,
/// preventing the 2x burst possible with fixed-window designs.
/// Single-consumer (owned by the router task), no concurrency concerns.
struct ManagementRateLimiter {
    buckets: HashMap<&'static str, VecDeque<Instant>>,
}

impl ManagementRateLimiter {
    fn new() -> Self {
        Self {
            buckets: HashMap::new(),
        }
    }

    /// Check if a request of the given type is within the rate limit.
    /// Returns `true` if allowed, `false` if rate-limited.
    fn check(&mut self, method: &'static str, max_per_minute: u32) -> bool {
        let now = Instant::now();
        let window = std::time::Duration::from_secs(60);
        let timestamps = self.buckets.entry(method).or_default();

        // Evict timestamps older than the 60-second sliding window.
        while let Some(&oldest) = timestamps.front() {
            if now.saturating_duration_since(oldest) >= window {
                timestamps.pop_front();
            } else {
                break;
            }
        }

        if timestamps.len() >= max_per_minute as usize {
            return false;
        }
        timestamps.push_back(now);
        true
    }
}

/// Return the rate limit label and max-per-minute for a request type.
/// Returns `None` for the limit if the request type is not rate-limited.
fn rate_limit_for_request(req: &KernelRequest) -> (&'static str, Option<u32>) {
    (kernel_request_method(req), rate_limit_max(req))
}

/// Return the max-per-minute rate limit for a request type, if any.
fn rate_limit_max(req: &KernelRequest) -> Option<u32> {
    match req {
        KernelRequest::ReloadCapsules => Some(5),
        KernelRequest::InstallCapsule { .. } | KernelRequest::ApproveCapability { .. } => Some(10),
        KernelRequest::Shutdown { .. } => Some(1),
        KernelRequest::ListCapsules
        | KernelRequest::GetCommands
        | KernelRequest::GetCapsuleMetadata
        | KernelRequest::GetStatus => None,
    }
}

// ---------------------------------------------------------------------------
// Management API capability enforcement (issue #670)
// ---------------------------------------------------------------------------

/// The authority surface a given [`KernelRequest`] operates over.
///
/// Today's `KernelRequest` variants carry no target-principal field, so
/// [`resolve_scope`] always returns [`AuthorityScope::Self_`] — the
/// request operates on the caller's own home.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthorityScope {
    /// Request operates on the caller's own principal.
    Self_,
    /// Request operates on global/system-wide state (e.g. shutdown).
    Global,
}

/// Return the authority scope the caller is exercising for `req`.
///
/// Currently always returns [`AuthorityScope::Self_`] because no
/// `KernelRequest` variant carries a `target_principal` field yet.
#[must_use]
pub fn resolve_scope(_req: &KernelRequest, _caller: &PrincipalId) -> AuthorityScope {
    AuthorityScope::Self_
}

/// Return the static capability string required to satisfy `req` under
/// `scope`.
///
/// Pure function so the capability mapping can be unit-tested in
/// isolation. Every `KernelRequest` variant is covered; there is no
/// default-allow branch.
#[must_use]
pub fn required_capability(req: &KernelRequest, scope: AuthorityScope) -> &'static str {
    match (req, scope) {
        (KernelRequest::Shutdown { .. }, _) => "system:shutdown",
        (KernelRequest::GetStatus, _) => "system:status",
        (KernelRequest::ReloadCapsules, AuthorityScope::Self_) => "self:capsule:reload",
        (KernelRequest::ReloadCapsules, _) => "capsule:reload",
        (KernelRequest::InstallCapsule { .. }, AuthorityScope::Self_) => "self:capsule:install",
        (KernelRequest::InstallCapsule { .. }, _) => "capsule:install",
        (
            KernelRequest::ListCapsules
            | KernelRequest::GetCommands
            | KernelRequest::GetCapsuleMetadata,
            AuthorityScope::Self_,
        ) => "self:capsule:list",
        (
            KernelRequest::ListCapsules
            | KernelRequest::GetCommands
            | KernelRequest::GetCapsuleMetadata,
            _,
        ) => "capsule:list",
        (KernelRequest::ApproveCapability { .. }, _) => "self:approval:respond",
    }
}

/// Short identifier for a [`KernelRequest`] variant, used for rate-limit
/// labels and audit method names.
#[must_use]
pub fn kernel_request_method(req: &KernelRequest) -> &'static str {
    match req {
        KernelRequest::ReloadCapsules => "ReloadCapsules",
        KernelRequest::InstallCapsule { .. } => "InstallCapsule",
        KernelRequest::ApproveCapability { .. } => "ApproveCapability",
        KernelRequest::ListCapsules => "ListCapsules",
        KernelRequest::GetCommands => "GetCommands",
        KernelRequest::GetCapsuleMetadata => "GetCapsuleMetadata",
        KernelRequest::Shutdown { .. } => "Shutdown",
        KernelRequest::GetStatus => "GetStatus",
    }
}

/// Resolve the caller [`PrincipalId`] from an incoming [`IpcMessage`].
///
/// Pre-#658 single-token socket traffic arrives without a principal
/// field set; we fall back to [`PrincipalId::default`] — the default
/// principal is bootstrapped with the built-in `admin` group, matching
/// today's single-tenant behaviour.
fn resolve_caller(message: &IpcMessage) -> PrincipalId {
    message
        .principal
        .as_deref()
        .and_then(|p| PrincipalId::new(p).ok())
        .unwrap_or_default()
}

/// Evaluate the capability check for `caller` against the kernel's
/// resolved group config and the caller's profile.
///
/// Returns `Ok(())` on success, or the policy reason on denial. Profile
/// resolution failures (malformed TOML, IO error) are themselves treated
/// as deny — fail-closed — with a synthesized `MissingCapability` so the
/// deny path has a single shape in the audit log.
fn authorize_request(
    kernel: &crate::Kernel,
    caller: &PrincipalId,
    required_cap: &str,
) -> Result<(), PermissionError> {
    let profile = match kernel.profile_cache.resolve(caller) {
        Ok(p) => p,
        Err(e) => {
            warn!(
                security_event = true,
                principal = %caller,
                error = %e,
                "Profile resolution failed — fail-closed deny"
            );
            return Err(PermissionError::MissingCapability {
                principal: caller.clone(),
                required: required_cap.to_string(),
            });
        },
    };
    // Enabled gate runs BEFORE the capability check so a disabled
    // principal cannot exercise any management API surface — even one
    // they would otherwise be authorized for. The `default` principal
    // is bootstrap-managed and `caps.revoke`/`agent.disable` against
    // it are rejected up front, so this check cannot lock the
    // single-tenant path.
    if !profile.enabled {
        warn!(
            security_event = true,
            principal = %caller,
            required = required_cap,
            "Disabled principal denied — fail-closed enforcement"
        );
        return Err(PermissionError::PrincipalDisabled {
            principal: caller.clone(),
        });
    }
    let groups = kernel.groups.load_full();
    let check = CapabilityCheck::new(profile.as_ref(), groups.as_ref(), caller.clone());
    check.require(required_cap)
}

/// Bundled inputs for [`record_admin_audit`] — keeps the call site
/// readable and the function under clippy's `too_many_arguments` cap.
pub(crate) struct AdminAuditEntry<'a> {
    /// Caller principal making the request.
    pub caller: &'a PrincipalId,
    /// Wire-name identifier for the request variant.
    pub method: &'a str,
    /// Capability string evaluated for this request.
    pub required_cap: &'a str,
    /// `None` when the request operates on the caller's own principal
    /// (Layer 5) and `Some` when the request mutates another principal
    /// (Layer 6 admin topics like `admin.quota.set`).
    pub target_principal: Option<PrincipalId>,
    /// Request payload for forensic replay (issue #672) — `None` for
    /// [`KernelRequest`] entries that have no params struct, `Some` with
    /// the wire payload for [`AdminKernelRequest`].
    pub params: Option<serde_json::Value>,
    /// Authorization proof (allow / deny).
    pub authorization: AuthorizationProof,
    /// Success or failure outcome.
    pub outcome: AuditOutcome,
}

/// Append an `AdminRequest` audit entry for the given outcome. Failures
/// to persist are logged but do not abort the request — the audit log
/// degrades to "continue + alert" by design.
fn record_admin_audit(kernel: &crate::Kernel, entry: AdminAuditEntry<'_>) {
    let AdminAuditEntry {
        caller,
        method,
        required_cap,
        target_principal,
        params,
        authorization,
        outcome,
    } = entry;
    let action = AuditAction::AdminRequest {
        method: method.to_string(),
        required_capability: required_cap.to_string(),
        target_principal,
        params,
    };
    if let Err(e) = kernel.audit_log.append_with_principal(
        kernel.session_id.clone(),
        caller.clone(),
        action,
        authorization,
        outcome,
    ) {
        warn!(
            security_event = true,
            principal = %caller,
            method = method,
            error = %e,
            "Failed to persist admin-request audit entry — continuing"
        );
    }
}

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

    #[test]
    fn rate_limiter_allows_within_limit() {
        let mut limiter = ManagementRateLimiter::new();
        for _ in 0..5 {
            assert!(limiter.check("ReloadCapsules", 5));
        }
        // 6th should be rejected
        assert!(!limiter.check("ReloadCapsules", 5));
    }

    #[test]
    fn rate_limiter_independent_buckets() {
        let mut limiter = ManagementRateLimiter::new();
        // Fill ReloadCapsules
        for _ in 0..5 {
            assert!(limiter.check("ReloadCapsules", 5));
        }
        assert!(!limiter.check("ReloadCapsules", 5));

        // InstallCapsule should still be allowed
        assert!(limiter.check("InstallCapsule", 10));
    }

    #[test]
    fn rate_limiter_sliding_window_eviction() {
        let mut limiter = ManagementRateLimiter::new();
        // Fill the bucket
        for _ in 0..5 {
            assert!(limiter.check("ReloadCapsules", 5));
        }
        assert!(!limiter.check("ReloadCapsules", 5));

        // Manually set all timestamps to 61 seconds ago to simulate expiry.
        if let Some(timestamps) = limiter.buckets.get_mut("ReloadCapsules") {
            let past = Instant::now() - std::time::Duration::from_secs(61);
            for ts in timestamps.iter_mut() {
                *ts = past;
            }
        }

        // Should be allowed again after old entries are evicted
        assert!(limiter.check("ReloadCapsules", 5));
    }

    #[test]
    fn rate_limiter_sliding_window_prevents_boundary_burst() {
        let mut limiter = ManagementRateLimiter::new();
        // Fill 5 requests
        for _ in 0..5 {
            assert!(limiter.check("ReloadCapsules", 5));
        }

        // Move only 3 of the 5 timestamps to the past (beyond 60s window).
        // This simulates partial window expiry - only 3 slots should free up.
        if let Some(timestamps) = limiter.buckets.get_mut("ReloadCapsules") {
            let past = Instant::now() - std::time::Duration::from_secs(61);
            for ts in timestamps.iter_mut().take(3) {
                *ts = past;
            }
        }

        // Should allow exactly 3 more (the evicted slots), not 5
        for _ in 0..3 {
            assert!(limiter.check("ReloadCapsules", 5));
        }
        assert!(!limiter.check("ReloadCapsules", 5));
    }

    #[test]
    fn rate_limit_for_request_returns_correct_limits() {
        let (name, limit) = rate_limit_for_request(&KernelRequest::ReloadCapsules);
        assert_eq!(name, "ReloadCapsules");
        assert_eq!(limit, Some(5));

        let (name, limit) = rate_limit_for_request(&KernelRequest::ListCapsules);
        assert_eq!(name, "ListCapsules");
        assert_eq!(limit, None);
    }

    // ── Capability mapping (issue #670) ──────────────────────────────

    fn all_request_variants() -> Vec<KernelRequest> {
        vec![
            KernelRequest::Shutdown { reason: None },
            KernelRequest::GetStatus,
            KernelRequest::ReloadCapsules,
            KernelRequest::InstallCapsule {
                source: "x".to_string(),
                workspace: false,
            },
            KernelRequest::ListCapsules,
            KernelRequest::GetCommands,
            KernelRequest::GetCapsuleMetadata,
            KernelRequest::ApproveCapability {
                request_id: "r".to_string(),
                signature: "s".to_string(),
            },
        ]
    }

    #[test]
    fn required_capability_every_variant_has_non_empty_mapping() {
        for req in all_request_variants() {
            let cap = required_capability(&req, AuthorityScope::Self_);
            assert!(
                !cap.is_empty(),
                "required_capability returned empty for {req:?}"
            );
        }
    }

    #[test]
    fn required_capability_mapping_per_variant_self_scope() {
        assert_eq!(
            required_capability(
                &KernelRequest::Shutdown { reason: None },
                AuthorityScope::Self_
            ),
            "system:shutdown"
        );
        assert_eq!(
            required_capability(&KernelRequest::GetStatus, AuthorityScope::Self_),
            "system:status"
        );
        assert_eq!(
            required_capability(&KernelRequest::ReloadCapsules, AuthorityScope::Self_),
            "self:capsule:reload"
        );
        assert_eq!(
            required_capability(
                &KernelRequest::InstallCapsule {
                    source: String::new(),
                    workspace: false
                },
                AuthorityScope::Self_
            ),
            "self:capsule:install"
        );
        assert_eq!(
            required_capability(&KernelRequest::ListCapsules, AuthorityScope::Self_),
            "self:capsule:list"
        );
        assert_eq!(
            required_capability(&KernelRequest::GetCommands, AuthorityScope::Self_),
            "self:capsule:list"
        );
        assert_eq!(
            required_capability(&KernelRequest::GetCapsuleMetadata, AuthorityScope::Self_),
            "self:capsule:list"
        );
        assert_eq!(
            required_capability(
                &KernelRequest::ApproveCapability {
                    request_id: String::new(),
                    signature: String::new(),
                },
                AuthorityScope::Self_
            ),
            "self:approval:respond"
        );
    }

    #[test]
    fn required_capability_mapping_global_scope() {
        // Global scope strips the `self:` prefix from capsule operations
        // (Layer 6 will start using this when cross-agent variants land).
        assert_eq!(
            required_capability(&KernelRequest::ReloadCapsules, AuthorityScope::Global),
            "capsule:reload"
        );
        assert_eq!(
            required_capability(
                &KernelRequest::InstallCapsule {
                    source: String::new(),
                    workspace: false
                },
                AuthorityScope::Global
            ),
            "capsule:install"
        );
        assert_eq!(
            required_capability(&KernelRequest::ListCapsules, AuthorityScope::Global),
            "capsule:list"
        );
        // system:* variants are scope-invariant.
        assert_eq!(
            required_capability(
                &KernelRequest::Shutdown { reason: None },
                AuthorityScope::Global
            ),
            "system:shutdown"
        );
    }

    #[test]
    fn resolve_scope_defaults_to_self() {
        let caller = PrincipalId::new("alice").unwrap();
        for req in all_request_variants() {
            assert_eq!(
                resolve_scope(&req, &caller),
                AuthorityScope::Self_,
                "scope should default to Self_ for today's variants"
            );
        }
    }

    // ── Caller resolution ────────────────────────────────────────────

    #[test]
    fn resolve_caller_uses_ipc_principal_when_present() {
        let mut msg = IpcMessage::new(
            "astrid.v1.request.system",
            IpcPayload::RawJson(serde_json::json!({})),
            uuid::Uuid::nil(),
        );
        msg.principal = Some("alice".to_string());
        let caller = resolve_caller(&msg);
        assert_eq!(caller.as_str(), "alice");
    }

    #[test]
    fn resolve_caller_falls_back_to_default_when_missing() {
        let msg = IpcMessage::new(
            "astrid.v1.request.system",
            IpcPayload::RawJson(serde_json::json!({})),
            uuid::Uuid::nil(),
        );
        let caller = resolve_caller(&msg);
        assert_eq!(caller, PrincipalId::default());
    }

    #[test]
    fn resolve_caller_falls_back_to_default_on_invalid_principal() {
        let mut msg = IpcMessage::new(
            "astrid.v1.request.system",
            IpcPayload::RawJson(serde_json::json!({})),
            uuid::Uuid::nil(),
        );
        // Invalid principal chars → PrincipalId::new fails → fall back.
        msg.principal = Some("alice@evil.example".to_string());
        let caller = resolve_caller(&msg);
        assert_eq!(caller, PrincipalId::default());
    }
}