moloch-core 0.1.0

Core types and primitives for Moloch audit chain
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
//! Attestation registry for managing and verifying agent attestations.
//!
//! The registry tracks valid attestations, trusted authorities, and revocations.

use std::collections::{HashMap, HashSet};

use crate::crypto::{Hash, PublicKey};

use super::attestation::{AgentAttestation, AttestationError};

/// Registry of valid attestations.
///
/// The registry maintains:
/// - Active attestations indexed by agent ID
/// - Set of trusted attestation authorities
/// - Set of revoked attestation hashes
pub struct AttestationRegistry {
    /// Active attestations by agent ID (using byte array as key for efficiency).
    attestations: HashMap<[u8; 32], AgentAttestation>,

    /// Trusted attestation authorities.
    authorities: HashSet<[u8; 32]>,

    /// Revoked attestation hashes.
    revocations: HashSet<Hash>,

    /// Revocation reasons (for auditing).
    revocation_reasons: HashMap<Hash, String>,
}

impl AttestationRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            attestations: HashMap::new(),
            authorities: HashSet::new(),
            revocations: HashSet::new(),
            revocation_reasons: HashMap::new(),
        }
    }

    /// Add a trusted attestation authority.
    pub fn add_authority(&mut self, authority: &PublicKey) {
        self.authorities.insert(authority.as_bytes());
    }

    /// Remove an attestation authority.
    pub fn remove_authority(&mut self, authority: &PublicKey) {
        self.authorities.remove(&authority.as_bytes());
    }

    /// Check if an authority is trusted.
    pub fn is_trusted_authority(&self, authority: &PublicKey) -> bool {
        self.authorities.contains(&authority.as_bytes())
    }

    /// Get the number of trusted authorities.
    pub fn authority_count(&self) -> usize {
        self.authorities.len()
    }

    /// Register a new attestation.
    ///
    /// # Arguments
    /// * `attestation` - The attestation to register
    ///
    /// # Errors
    /// Returns error if:
    /// - Attestation signature is invalid
    /// - Authority is not trusted
    /// - Attestation is already expired
    pub fn register(&mut self, attestation: AgentAttestation) -> Result<(), AttestationError> {
        // Verify signature
        attestation
            .verify_signature()
            .map_err(|_| AttestationError::InvalidSignature)?;

        // Check authority is trusted
        if !self.is_trusted_authority(attestation.authority()) {
            return Err(AttestationError::UntrustedAuthority);
        }

        // Check not already expired
        let now = chrono::Utc::now().timestamp_millis();
        if !attestation.is_valid_at(now) {
            return Err(AttestationError::Expired);
        }

        // Store attestation
        let key = attestation.agent_id().as_bytes();
        self.attestations.insert(key, attestation);

        Ok(())
    }

    /// Verify an agent has a valid attestation at a given time.
    ///
    /// # Arguments
    /// * `agent_id` - The agent's public key
    /// * `action_time` - When the action occurred (Unix timestamp ms)
    ///
    /// # Errors
    /// Returns error if:
    /// - No attestation registered for agent
    /// - Attestation expired at action_time
    /// - Attestation has been revoked
    pub fn verify(
        &self,
        agent_id: &PublicKey,
        action_time: i64,
    ) -> Result<&AgentAttestation, AttestationError> {
        // Find attestation
        let key = agent_id.as_bytes();
        let attestation = self
            .attestations
            .get(&key)
            .ok_or(AttestationError::NotFound)?;

        // Check not revoked
        let attestation_hash = attestation.hash();
        if self.revocations.contains(&attestation_hash) {
            return Err(AttestationError::Revoked);
        }

        // Check validity at action time
        if !attestation.is_valid_at(action_time) {
            return Err(AttestationError::Expired);
        }

        Ok(attestation)
    }

    /// Revoke an attestation.
    ///
    /// Revocation is permanent and cannot be undone. The attestation hash
    /// is added to the revocations set.
    ///
    /// # Arguments
    /// * `attestation_hash` - Hash of the attestation to revoke
    /// * `reason` - Reason for revocation
    pub fn revoke(&mut self, attestation_hash: Hash, reason: String) {
        self.revocations.insert(attestation_hash);
        self.revocation_reasons.insert(attestation_hash, reason);
    }

    /// Check if an attestation has been revoked.
    pub fn is_revoked(&self, attestation_hash: &Hash) -> bool {
        self.revocations.contains(attestation_hash)
    }

    /// Get the revocation reason if available.
    pub fn revocation_reason(&self, attestation_hash: &Hash) -> Option<&String> {
        self.revocation_reasons.get(attestation_hash)
    }

    /// Get an attestation by agent ID (without validation).
    pub fn get(&self, agent_id: &PublicKey) -> Option<&AgentAttestation> {
        let key = agent_id.as_bytes();
        self.attestations.get(&key)
    }

    /// Remove an attestation (for cleanup, not revocation).
    pub fn remove(&mut self, agent_id: &PublicKey) -> Option<AgentAttestation> {
        let key = agent_id.as_bytes();
        self.attestations.remove(&key)
    }

    /// Get the number of registered attestations.
    pub fn attestation_count(&self) -> usize {
        self.attestations.len()
    }

    /// Get the number of revoked attestations.
    pub fn revocation_count(&self) -> usize {
        self.revocations.len()
    }
}

impl Default for AttestationRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::{hash, SecretKey};
    use std::time::Duration;

    use super::super::attestation::{AgentAttestation, RuntimeAttestation};

    fn create_attestation(
        agent: &SecretKey,
        authority: &SecretKey,
        attested_at: i64,
        validity_secs: u64,
    ) -> AgentAttestation {
        AgentAttestation::builder()
            .agent_id(agent.public_key())
            .code_hash(hash(b"code"))
            .config_hash(hash(b"config"))
            .prompt_hash(hash(b"prompt"))
            .runtime(RuntimeAttestation::new("test-v1", hash(b"runtime")))
            .attested_at(attested_at)
            .validity_period(Duration::from_secs(validity_secs))
            .sign(authority)
            .unwrap()
    }

    // === Registration Tests ===

    #[test]
    fn register_stores_attestation() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);

        registry.register(attestation).unwrap();

        assert!(registry.get(&agent.public_key()).is_some());
        assert_eq!(registry.attestation_count(), 1);
    }

    #[test]
    fn register_rejects_untrusted_authority() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        // Don't add authority to trusted set

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);

        let result = registry.register(attestation);
        assert!(matches!(result, Err(AttestationError::UntrustedAuthority)));
    }

    #[test]
    fn register_rejects_expired_attestation() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        // Create already-expired attestation
        let past = chrono::Utc::now().timestamp_millis() - 10000;
        let attestation = create_attestation(&agent, &authority, past, 1); // 1 second validity

        let result = registry.register(attestation);
        assert!(matches!(result, Err(AttestationError::Expired)));
    }

    // === Verification Tests ===

    #[test]
    fn verify_returns_attestation_if_valid() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);

        registry.register(attestation).unwrap();

        let result = registry.verify(&agent.public_key(), now + 1000);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().agent_id(), &agent.public_key());
    }

    #[test]
    fn verify_fails_if_not_registered() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let result = registry.verify(&agent.public_key(), now);

        assert!(matches!(result, Err(AttestationError::NotFound)));
    }

    #[test]
    fn verify_fails_if_expired_at_action_time() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 60); // 60 seconds

        registry.register(attestation).unwrap();

        // Verify at time after expiry
        let result = registry.verify(&agent.public_key(), now + 70 * 1000);
        assert!(matches!(result, Err(AttestationError::Expired)));
    }

    #[test]
    fn verify_fails_if_revoked() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);
        let attestation_hash = attestation.hash();

        registry.register(attestation).unwrap();
        registry.revoke(attestation_hash, "Security incident".to_string());

        let result = registry.verify(&agent.public_key(), now + 1000);
        assert!(matches!(result, Err(AttestationError::Revoked)));
    }

    // === Revocation Tests ===

    #[test]
    fn revoke_adds_to_revocation_list() {
        let mut registry = AttestationRegistry::new();
        let hash = hash(b"attestation-data");

        registry.revoke(hash, "Test revocation".to_string());

        assert!(registry.is_revoked(&hash));
        assert_eq!(registry.revocation_count(), 1);
    }

    #[test]
    fn revoke_makes_verify_fail() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);
        let attestation_hash = attestation.hash();

        registry.register(attestation).unwrap();

        // Verify works before revocation
        assert!(registry.verify(&agent.public_key(), now + 1000).is_ok());

        // Revoke
        registry.revoke(attestation_hash, "Compromised".to_string());

        // Verify fails after revocation
        let result = registry.verify(&agent.public_key(), now + 2000);
        assert!(matches!(result, Err(AttestationError::Revoked)));
    }

    #[test]
    fn revoke_is_permanent() {
        let mut registry = AttestationRegistry::new();
        let hash = hash(b"attestation-data");

        registry.revoke(hash, "First revocation".to_string());

        // Cannot un-revoke (revoke again has no effect)
        assert!(registry.is_revoked(&hash));

        // Hash remains in revocation list
        assert!(registry.is_revoked(&hash));
    }

    #[test]
    fn revocation_reason_recorded() {
        let mut registry = AttestationRegistry::new();
        let hash = hash(b"attestation-data");
        let reason = "Security vulnerability discovered".to_string();

        registry.revoke(hash, reason.clone());

        assert_eq!(registry.revocation_reason(&hash), Some(&reason));
    }

    // === Authority Management Tests ===

    #[test]
    fn add_and_remove_authority() {
        let authority = SecretKey::generate();
        let mut registry = AttestationRegistry::new();

        assert!(!registry.is_trusted_authority(&authority.public_key()));
        assert_eq!(registry.authority_count(), 0);

        registry.add_authority(&authority.public_key());
        assert!(registry.is_trusted_authority(&authority.public_key()));
        assert_eq!(registry.authority_count(), 1);

        registry.remove_authority(&authority.public_key());
        assert!(!registry.is_trusted_authority(&authority.public_key()));
        assert_eq!(registry.authority_count(), 0);
    }

    #[test]
    fn remove_attestation() {
        let authority = SecretKey::generate();
        let agent = SecretKey::generate();

        let mut registry = AttestationRegistry::new();
        registry.add_authority(&authority.public_key());

        let now = chrono::Utc::now().timestamp_millis();
        let attestation = create_attestation(&agent, &authority, now, 3600);

        registry.register(attestation).unwrap();
        assert_eq!(registry.attestation_count(), 1);

        let removed = registry.remove(&agent.public_key());
        assert!(removed.is_some());
        assert_eq!(registry.attestation_count(), 0);
    }
}