upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/grasp-audit/src/audit.rs
blob: 0ca8737da37317679af7c1708b857a004b087401 (plain)
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
//! Audit configuration and event tagging

use nostr_sdk::prelude::*;
use std::time::Duration;

/// Audit configuration
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// Unique ID for this audit run
    pub run_id: String,
    
    /// Mode: CI (isolated) or Production (live)
    pub mode: AuditMode,
    
    /// Cleanup timestamp (events can be cleaned after this)
    pub cleanup_after: Timestamp,
    
    /// Whether to actually create events or just query
    pub read_only: bool,
}

/// Audit mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuditMode {
    /// Isolated CI/CD tests - only see own events
    CI,
    
    /// Production audit - see all events, minimal writes
    Production,
}

impl AuditConfig {
    /// Create config for CI/CD testing
    pub fn ci() -> Self {
        let run_id = format!("ci-{}", uuid::Uuid::new_v4());
        Self {
            run_id,
            mode: AuditMode::CI,
            cleanup_after: Timestamp::now() + 3600, // 1 hour from now
            read_only: false,
        }
    }
    
    /// Create config for production audit
    pub fn production() -> Self {
        let run_id = format!("prod-audit-{}", Timestamp::now().as_u64());
        Self {
            run_id,
            mode: AuditMode::Production,
            cleanup_after: Timestamp::now() + 300, // 5 minutes from now
            read_only: true, // Default to read-only for production
        }
    }
    
    /// Create config with custom run ID
    pub fn with_run_id(run_id: String, mode: AuditMode) -> Self {
        Self {
            run_id,
            mode,
            cleanup_after: Timestamp::now() + 3600,
            read_only: mode == AuditMode::Production,
        }
    }
    
    /// Get audit tags for an event
    pub fn audit_tags(&self) -> Vec<Tag> {
        vec![
            Tag::custom(
                TagKind::Custom(std::borrow::Cow::Borrowed("grasp-audit")),
                vec!["true"]
            ),
            Tag::custom(
                TagKind::Custom(std::borrow::Cow::Borrowed("audit-run-id")),
                vec![self.run_id.clone()]
            ),
            Tag::custom(
                TagKind::Custom(std::borrow::Cow::Borrowed("audit-cleanup")),
                vec![self.cleanup_after.to_string()]
            ),
        ]
    }
}

/// Builder for audit events
pub struct AuditEventBuilder {
    kind: Kind,
    content: String,
    tags: Vec<Tag>,
    config: AuditConfig,
}

impl AuditEventBuilder {
    /// Create a new audit event builder
    pub fn new(kind: Kind, content: impl Into<String>, config: AuditConfig) -> Self {
        Self {
            kind,
            content: content.into(),
            tags: Vec::new(),
            config,
        }
    }
    
    /// Add a tag
    pub fn tag(mut self, tag: Tag) -> Self {
        self.tags.push(tag);
        self
    }
    
    /// Add multiple tags
    pub fn tags(mut self, tags: Vec<Tag>) -> Self {
        self.tags.extend(tags);
        self
    }
    
    /// Build the event with audit tags
    pub async fn build(self, keys: &Keys) -> anyhow::Result<Event> {
        let mut all_tags = self.tags;
        all_tags.extend(self.config.audit_tags());
        
        let event = EventBuilder::new(self.kind, self.content, all_tags)
            .to_event(keys)
            .await?;
        
        Ok(event)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_ci_config() {
        let config = AuditConfig::ci();
        assert_eq!(config.mode, AuditMode::CI);
        assert!(!config.read_only);
        assert!(config.run_id.starts_with("ci-"));
    }
    
    #[test]
    fn test_production_config() {
        let config = AuditConfig::production();
        assert_eq!(config.mode, AuditMode::Production);
        assert!(config.read_only);
        assert!(config.run_id.starts_with("prod-audit-"));
    }
    
    #[test]
    fn test_audit_tags() {
        let config = AuditConfig::ci();
        let tags = config.audit_tags();
        
        assert_eq!(tags.len(), 3);
        
        // Check grasp-audit tag
        assert!(tags.iter().any(|t| {
            matches!(t.kind(), TagKind::Custom(k) if k == "grasp-audit")
        }));
        
        // Check audit-run-id tag
        assert!(tags.iter().any(|t| {
            matches!(t.kind(), TagKind::Custom(k) if k == "audit-run-id")
        }));
        
        // Check audit-cleanup tag
        assert!(tags.iter().any(|t| {
            matches!(t.kind(), TagKind::Custom(k) if k == "audit-cleanup")
        }));
    }
    
    #[tokio::test]
    async fn test_audit_event_builder() {
        let config = AuditConfig::ci();
        let keys = Keys::generate();
        
        let event = AuditEventBuilder::new(Kind::TextNote, "test", config.clone())
            .tag(Tag::custom(TagKind::Custom("test".into()), vec!["value"]))
            .build(&keys)
            .await
            .unwrap();
        
        // Should have our custom tag + 3 audit tags
        assert!(event.tags.len() >= 4);
        
        // Verify event is valid
        assert!(event.verify().is_ok());
    }
}