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
//! Audit entry types and actions.
//!
//! Every security-relevant operation is recorded as an audit entry.
//! Entries are chain-linked (each contains the hash of the previous)
//! and signed by the runtime.
use astrid_capabilities::AuditEntryId;
use astrid_core::{Permission, RiskLevel, SessionId, Timestamp, TokenId};
use astrid_crypto::{ContentHash, KeyPair, PublicKey, Signature};
use serde::{Deserialize, Serialize};
use crate::error::{AuditError, AuditResult};
/// A single audit log entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
/// Unique entry identifier.
pub id: AuditEntryId,
/// When this entry was created.
pub timestamp: Timestamp,
/// Session this entry belongs to.
pub session_id: SessionId,
/// The principal (user identity) this action was performed on behalf of.
/// `None` for system actions that have no user context.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub principal: Option<astrid_core::PrincipalId>,
/// The action being audited.
pub action: AuditAction,
/// Authorization proof for this action.
pub authorization: AuthorizationProof,
/// Outcome of the action.
pub outcome: AuditOutcome,
/// Hash of the previous entry (chain linking).
pub previous_hash: ContentHash,
/// Runtime public key that signed this entry.
pub runtime_key: PublicKey,
/// Signature over entry contents.
pub signature: Signature,
}
impl AuditEntry {
/// Create a new audit entry (unsigned).
fn new_unsigned(
session_id: SessionId,
action: AuditAction,
authorization: AuthorizationProof,
outcome: AuditOutcome,
previous_hash: ContentHash,
runtime_key: PublicKey,
) -> Self {
Self {
id: AuditEntryId::new(),
timestamp: Timestamp::now(),
session_id,
principal: None,
action,
authorization,
outcome,
previous_hash,
runtime_key,
signature: Signature::from_bytes([0u8; 64]), // Placeholder
}
}
/// Create and sign a new audit entry.
#[must_use]
pub fn create(
session_id: SessionId,
action: AuditAction,
authorization: AuthorizationProof,
outcome: AuditOutcome,
previous_hash: ContentHash,
runtime_key: &KeyPair,
) -> Self {
let mut entry = Self::new_unsigned(
session_id,
action,
authorization,
outcome,
previous_hash,
runtime_key.export_public_key(),
);
let signing_data = entry.signing_data();
entry.signature = runtime_key.sign(&signing_data);
entry
}
/// Create and sign a new audit entry with a principal.
///
/// Used when audit entries need to record which principal an action
/// was performed on behalf of. Call sites will be wired when the
/// kernel audit integration is updated.
#[must_use]
pub fn create_with_principal(
session_id: SessionId,
principal: astrid_core::PrincipalId,
action: AuditAction,
authorization: AuthorizationProof,
outcome: AuditOutcome,
previous_hash: ContentHash,
runtime_key: &KeyPair,
) -> Self {
let mut entry = Self::new_unsigned(
session_id,
action,
authorization,
outcome,
previous_hash,
runtime_key.export_public_key(),
);
entry.principal = Some(principal);
let signing_data = entry.signing_data();
entry.signature = runtime_key.sign(&signing_data);
entry
}
/// Get the data used for signing.
#[must_use]
pub fn signing_data(&self) -> Vec<u8> {
let mut data = Vec::new();
data.extend_from_slice(self.id.0.as_bytes());
data.extend_from_slice(&self.timestamp.0.timestamp().to_le_bytes());
data.extend_from_slice(self.session_id.0.as_bytes());
// Include principal in signing data with length-delimited encoding
// to prevent ambiguity between None and adjacent field boundaries.
// 0xFF marker + 4-byte length + bytes for Some, 0x00 marker for None.
if let Some(ref p) = self.principal {
let bytes = p.as_str().as_bytes();
data.push(0xFF); // presence marker
// PrincipalId is max 64 bytes — safe truncation.
#[expect(clippy::cast_possible_truncation)]
let len = bytes.len() as u32;
data.extend_from_slice(&len.to_le_bytes());
data.extend_from_slice(bytes);
} else {
data.push(0x00); // absence marker
}
// Action is serialized to JSON for consistent hashing
if let Ok(action_json) = serde_json::to_vec(&self.action) {
data.extend_from_slice(&action_json);
}
if let Ok(auth_json) = serde_json::to_vec(&self.authorization) {
data.extend_from_slice(&auth_json);
}
// Outcome: include success/failure indicator
data.push(u8::from(matches!(
self.outcome,
AuditOutcome::Success { .. }
)));
data.extend_from_slice(self.previous_hash.as_bytes());
data.extend_from_slice(self.runtime_key.as_bytes());
data
}
/// Compute the content hash of this entry.
#[must_use]
pub fn content_hash(&self) -> ContentHash {
ContentHash::hash(&self.signing_data())
}
/// Verify the entry's signature.
///
/// # Errors
///
/// Returns [`AuditError::InvalidSignature`] if the signature does not match
/// the entry contents.
pub fn verify_signature(&self) -> AuditResult<()> {
let signing_data = self.signing_data();
self.runtime_key
.verify(&signing_data, &self.signature)
.map_err(|_| AuditError::InvalidSignature {
entry_id: self.id.to_string(),
})
}
/// Check if this entry follows another (chain linking).
#[must_use]
pub fn follows(&self, previous: &AuditEntry) -> bool {
self.previous_hash == previous.content_hash()
}
}
/// Actions that can be audited.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuditAction {
/// MCP tool was called.
McpToolCall {
/// Server name.
server: String,
/// Tool name.
tool: String,
/// Hash of the arguments (not the args themselves for privacy).
args_hash: ContentHash,
},
/// Capsule tool was called.
CapsuleToolCall {
/// Capsule ID.
capsule_id: String,
/// Tool name.
tool: String,
/// Hash of the arguments (not the args themselves for privacy).
args_hash: ContentHash,
},
/// MCP resource was read.
McpResourceRead {
/// Server name.
server: String,
/// Resource URI.
uri: String,
},
/// MCP prompt was retrieved.
McpPromptGet {
/// Server name.
server: String,
/// Prompt name.
name: String,
},
/// MCP elicitation (server requested user input).
McpElicitation {
/// Request ID.
request_id: String,
/// Schema type (text, select, confirm, etc.).
schema: String,
},
/// MCP URL elicitation (OAuth, payments).
McpUrlElicitation {
/// URL presented to user.
url: String,
/// Interaction type (oauth, payment, verification, custom).
interaction_type: String,
},
/// MCP sampling (server-initiated LLM call).
McpSampling {
/// Model used.
model: String,
/// Prompt token count.
prompt_tokens: usize,
},
/// File was read.
FileRead {
/// File path.
path: String,
},
/// File was written.
FileWrite {
/// File path.
path: String,
/// Hash of the written content.
content_hash: ContentHash,
},
/// File was deleted.
FileDelete {
/// File path.
path: String,
},
/// Capability token was created.
CapabilityCreated {
/// Token ID.
token_id: TokenId,
/// Resource pattern.
resource: String,
/// Permissions granted.
permissions: Vec<Permission>,
/// Token scope.
scope: ApprovalScope,
},
/// Capability token was revoked.
CapabilityRevoked {
/// Token ID.
token_id: TokenId,
/// Reason for revocation.
reason: String,
},
/// Approval was requested from the user.
ApprovalRequested {
/// Type of action being requested.
action_type: String,
/// Resource being accessed.
resource: String,
/// Risk level of the action.
risk_level: RiskLevel,
},
/// User granted approval.
ApprovalGranted {
/// What was approved.
action: String,
/// Resource being accessed.
resource: Option<String>,
/// Scope of approval.
scope: ApprovalScope,
},
/// User denied approval.
ApprovalDenied {
/// What was denied.
action: String,
/// Reason given.
reason: Option<String>,
},
/// Session started.
SessionStarted {
/// User ID (key ID bytes).
user_id: [u8; 8],
/// Platform the session started from.
platform: String,
},
/// Session ended.
SessionEnded {
/// Reason for ending.
reason: String,
/// Duration in seconds.
duration_secs: u64,
},
/// Context was summarized (messages evicted).
ContextSummarized {
/// Number of messages evicted.
evicted_count: usize,
/// Approximate tokens freed.
tokens_freed: usize,
},
/// LLM request was made.
LlmRequest {
/// Model used.
model: String,
/// Input token count.
input_tokens: usize,
/// Output token count.
output_tokens: usize,
},
/// Server was started.
ServerStarted {
/// Server name.
name: String,
/// Transport type.
transport: String,
/// Binary hash (if verified).
binary_hash: Option<ContentHash>,
},
/// Server was stopped.
ServerStopped {
/// Server name.
name: String,
/// Reason.
reason: String,
},
/// Elicitation request sent to user.
ElicitationSent {
/// Request ID.
request_id: String,
/// Server requesting.
server: String,
/// Type of elicitation.
elicitation_type: String,
},
/// Elicitation response received.
ElicitationReceived {
/// Request ID.
request_id: String,
/// Action taken (submit/cancel/dismiss).
action: String,
},
/// Security policy violation detected.
SecurityViolation {
/// Type of violation.
violation_type: String,
/// Details.
details: String,
/// Risk level.
risk_level: RiskLevel,
},
/// Sub-agent was spawned (parent→child linkage).
SubAgentSpawned {
/// Parent session ID.
parent_session_id: String,
/// Child session ID.
child_session_id: String,
/// Task description.
description: String,
},
/// Configuration was reloaded.
ConfigReloaded,
}
impl AuditAction {
/// Get a human-readable description of the action.
#[must_use]
pub fn description(&self) -> String {
match self {
Self::McpToolCall { server, tool, .. } => {
format!("Called tool {server}:{tool}")
},
Self::CapsuleToolCall {
capsule_id, tool, ..
} => {
format!("Called capsule tool {capsule_id}:{tool}")
},
Self::McpResourceRead { server, uri } => {
format!("Read resource {server}:{uri}")
},
Self::McpPromptGet { server, name } => {
format!("Got prompt {server}:{name}")
},
Self::McpElicitation { request_id, schema } => {
format!("Elicitation {request_id} ({schema})")
},
Self::McpUrlElicitation {
interaction_type, ..
} => {
format!("URL elicitation ({interaction_type})")
},
Self::McpSampling { model, .. } => {
format!("Sampling request to {model}")
},
Self::FileRead { path } => {
format!("Read file {path}")
},
Self::FileWrite { path, .. } => {
format!("Wrote file {path}")
},
Self::FileDelete { path } => {
format!("Deleted file {path}")
},
Self::CapabilityCreated { resource, .. } => {
format!("Created capability for {resource}")
},
Self::CapabilityRevoked { token_id, .. } => {
format!("Revoked capability {token_id}")
},
Self::ApprovalRequested {
action_type,
resource,
..
} => {
format!("Approval requested: {action_type} on {resource}")
},
Self::ApprovalGranted { action, .. } => {
format!("Approved: {action}")
},
Self::ApprovalDenied { action, .. } => {
format!("Denied: {action}")
},
Self::SessionStarted { platform, .. } => {
format!("Session started via {platform}")
},
Self::SessionEnded { reason, .. } => {
format!("Session ended: {reason}")
},
Self::ContextSummarized { evicted_count, .. } => {
format!("Summarized {evicted_count} messages")
},
Self::LlmRequest { model, .. } => {
format!("LLM request to {model}")
},
Self::ServerStarted { name, .. } => {
format!("Started server {name}")
},
Self::ServerStopped { name, .. } => {
format!("Stopped server {name}")
},
Self::ElicitationSent { server, .. } => {
format!("Elicitation from {server}")
},
Self::ElicitationReceived { action, .. } => {
format!("Elicitation response: {action}")
},
Self::SecurityViolation { violation_type, .. } => {
format!("Security violation: {violation_type}")
},
Self::SubAgentSpawned { description, .. } => {
format!("Spawned sub-agent: {description}")
},
Self::ConfigReloaded => "Configuration reloaded".to_string(),
}
}
}
/// How an action was authorized.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthorizationProof {
/// Authorized by a verified user message.
User {
/// User ID (key ID).
user_id: [u8; 8],
/// The message that triggered the action.
message_id: String,
},
/// Authorized by capability token.
Capability {
/// Token ID.
token_id: TokenId,
/// Token content hash.
token_hash: ContentHash,
},
/// Authorized by user approval.
UserApproval {
/// User ID (key ID).
user_id: [u8; 8],
/// Audit entry ID of the prior approval decision that authorized this
/// action. `None` when this entry IS the root approval decision
/// (i.e. the user just said "yes" — there is no earlier entry).
approval_entry_id: Option<AuditEntryId>,
},
/// No authorization required (low-risk operation).
NotRequired {
/// Reason no auth needed.
reason: String,
},
/// System-initiated action.
System {
/// Reason for system action.
reason: String,
},
/// Authorization was denied.
Denied {
/// Reason for denial.
reason: String,
},
}
/// Scope of an approval.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalScope {
/// This one time only.
Once,
/// For the current session.
Session,
/// For the current workspace (persists beyond session).
Workspace,
/// Persistent (creates capability).
Always,
}
impl std::fmt::Display for ApprovalScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Once => write!(f, "once"),
Self::Session => write!(f, "session"),
Self::Workspace => write!(f, "workspace"),
Self::Always => write!(f, "always"),
}
}
}
/// Outcome of an audited action.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum AuditOutcome {
/// Action succeeded.
Success {
/// Optional details.
details: Option<String>,
},
/// Action failed.
Failure {
/// Error message.
error: String,
},
}
impl AuditOutcome {
/// Create a success outcome.
#[must_use]
pub fn success() -> Self {
Self::Success { details: None }
}
/// Create a success outcome with details.
#[must_use]
pub fn success_with(details: impl Into<String>) -> Self {
Self::Success {
details: Some(details.into()),
}
}
/// Create a failure outcome.
#[must_use]
pub fn failure(error: impl Into<String>) -> Self {
Self::Failure {
error: error.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use astrid_crypto::KeyPair;
fn test_keypair() -> KeyPair {
KeyPair::generate()
}
#[test]
fn test_entry_creation() {
let keypair = test_keypair();
let session_id = SessionId::new();
let entry = AuditEntry::create(
session_id,
AuditAction::SessionStarted {
user_id: keypair.key_id(),
platform: "cli".to_string(),
},
AuthorizationProof::System {
reason: "session start".to_string(),
},
AuditOutcome::success(),
ContentHash::zero(),
&keypair,
);
assert!(entry.verify_signature().is_ok());
}
#[test]
fn test_chain_linking() {
let keypair = test_keypair();
let session_id = SessionId::new();
let entry1 = AuditEntry::create(
session_id.clone(),
AuditAction::SessionStarted {
user_id: keypair.key_id(),
platform: "cli".to_string(),
},
AuthorizationProof::System {
reason: "session start".to_string(),
},
AuditOutcome::success(),
ContentHash::zero(),
&keypair,
);
let entry2 = AuditEntry::create(
session_id,
AuditAction::McpToolCall {
server: "test".to_string(),
tool: "tool".to_string(),
args_hash: ContentHash::hash(b"args"),
},
AuthorizationProof::NotRequired {
reason: "test".to_string(),
},
AuditOutcome::success(),
entry1.content_hash(),
&keypair,
);
assert!(entry2.follows(&entry1));
assert!(!entry1.follows(&entry2));
}
#[test]
fn test_signature_tampering() {
let keypair = test_keypair();
let session_id = SessionId::new();
let mut entry = AuditEntry::create(
session_id,
AuditAction::SessionStarted {
user_id: keypair.key_id(),
platform: "cli".to_string(),
},
AuthorizationProof::System {
reason: "session start".to_string(),
},
AuditOutcome::success(),
ContentHash::zero(),
&keypair,
);
// Valid signature
assert!(entry.verify_signature().is_ok());
// Tamper with the entry
entry.action = AuditAction::SessionEnded {
reason: "tampered".to_string(),
duration_secs: 0,
};
// Signature should now fail
assert!(entry.verify_signature().is_err());
}
#[test]
fn test_action_description() {
let action = AuditAction::McpToolCall {
server: "filesystem".to_string(),
tool: "read_file".to_string(),
args_hash: ContentHash::zero(),
};
assert!(action.description().contains("filesystem:read_file"));
}
}