fakecloud-logs 0.17.0

CloudWatch Logs implementation for FakeCloud
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
use std::collections::BTreeMap;
use std::sync::Arc;

use parking_lot::RwLock;

pub type SharedLogsState = Arc<RwLock<fakecloud_core::multi_account::MultiAccountState<LogsState>>>;

impl fakecloud_core::multi_account::AccountState for LogsState {
    fn new_for_account(account_id: &str, region: &str, _endpoint: &str) -> Self {
        Self::new(account_id, region)
    }
}

/// JSON object keys must be strings, so serialize
/// `HashMap<(String,String), AccountPolicy>` as a list of
/// `[policy_name, policy_type, policy]` tuples.
mod account_policy_map_serde {
    use super::AccountPolicy;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::collections::BTreeMap;

    pub fn serialize<S: Serializer>(
        map: &BTreeMap<(String, String), AccountPolicy>,
        s: S,
    ) -> Result<S::Ok, S::Error> {
        let entries: Vec<(&String, &String, &AccountPolicy)> = map
            .iter()
            .map(|((name, kind), p)| (name, kind, p))
            .collect();
        entries.serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        d: D,
    ) -> Result<BTreeMap<(String, String), AccountPolicy>, D::Error> {
        let entries: Vec<(String, String, AccountPolicy)> = Vec::deserialize(d)?;
        Ok(entries
            .into_iter()
            .map(|(name, kind, p)| ((name, kind), p))
            .collect())
    }
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogsState {
    pub account_id: String,
    pub region: String,
    pub log_groups: BTreeMap<String, LogGroup>,
    pub metric_filters: Vec<MetricFilter>,
    pub resource_policies: BTreeMap<String, ResourcePolicy>,
    pub destinations: BTreeMap<String, Destination>,
    pub queries: BTreeMap<String, QueryInfo>,
    pub export_tasks: Vec<ExportTask>,
    pub delivery_destinations: BTreeMap<String, DeliveryDestination>,
    pub delivery_sources: BTreeMap<String, DeliverySource>,
    pub deliveries: BTreeMap<String, Delivery>,
    pub query_definitions: BTreeMap<String, QueryDefinition>,
    /// Account policies keyed by (policy_name, policy_type)
    #[serde(with = "account_policy_map_serde")]
    pub account_policies: BTreeMap<(String, String), AccountPolicy>,
    /// Anomaly detectors keyed by detector ARN
    pub anomaly_detectors: BTreeMap<String, AnomalyDetector>,
    /// Import tasks keyed by import ID
    pub import_tasks: BTreeMap<String, ImportTask>,
    /// Integrations keyed by integration name
    pub integrations: BTreeMap<String, Integration>,
    /// Lookup tables keyed by ARN
    pub lookup_tables: BTreeMap<String, LookupTable>,
    /// Scheduled queries keyed by identifier (ARN)
    pub scheduled_queries: BTreeMap<String, ScheduledQuery>,
    /// S3 table integration sources keyed by integration ARN -> list of source identifiers
    pub s3_table_sources: BTreeMap<String, Vec<String>>,
    /// Bearer token authentication flag per log group
    pub bearer_token_auth: BTreeMap<String, bool>,
    /// Internal export storage: keyed by "bucket/prefix/..." path, value is exported data.
    /// Used by CreateExportTask and delivery pipeline when direct S3 access is unavailable.
    pub export_storage: BTreeMap<String, Vec<u8>>,
    /// Detected log anomalies keyed by anomaly id. Populated via the
    /// `/_fakecloud/logs/anomalies/inject` admin endpoint and surfaced
    /// through ListAnomalies / UpdateAnomaly.
    #[serde(default)]
    pub anomalies: BTreeMap<String, LogAnomaly>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogAnomaly {
    pub anomaly_id: String,
    pub anomaly_detector_arn: String,
    pub log_group_arn_list: Vec<String>,
    pub pattern_id: String,
    pub pattern_string: String,
    pub first_seen: i64,
    pub last_seen: i64,
    pub priority: String,
    pub state: String,
    pub suppressed: bool,
}

impl LogsState {
    pub fn new(account_id: &str, region: &str) -> Self {
        Self {
            account_id: account_id.to_string(),
            region: region.to_string(),
            log_groups: BTreeMap::new(),
            metric_filters: Vec::new(),
            resource_policies: BTreeMap::new(),
            destinations: BTreeMap::new(),
            queries: BTreeMap::new(),
            export_tasks: Vec::new(),
            delivery_destinations: BTreeMap::new(),
            delivery_sources: BTreeMap::new(),
            deliveries: BTreeMap::new(),
            query_definitions: BTreeMap::new(),
            account_policies: BTreeMap::new(),
            anomaly_detectors: BTreeMap::new(),
            import_tasks: BTreeMap::new(),
            integrations: BTreeMap::new(),
            lookup_tables: BTreeMap::new(),
            scheduled_queries: BTreeMap::new(),
            s3_table_sources: BTreeMap::new(),
            bearer_token_auth: BTreeMap::new(),
            export_storage: BTreeMap::new(),
            anomalies: BTreeMap::new(),
        }
    }

    pub fn reset(&mut self) {
        self.log_groups.clear();
        self.metric_filters.clear();
        self.resource_policies.clear();
        self.destinations.clear();
        self.queries.clear();
        self.export_tasks.clear();
        self.delivery_destinations.clear();
        self.delivery_sources.clear();
        self.deliveries.clear();
        self.query_definitions.clear();
        self.account_policies.clear();
        self.anomaly_detectors.clear();
        self.import_tasks.clear();
        self.integrations.clear();
        self.lookup_tables.clear();
        self.scheduled_queries.clear();
        self.s3_table_sources.clear();
        self.bearer_token_auth.clear();
        self.export_storage.clear();
        self.anomalies.clear();
    }
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogGroup {
    pub name: String,
    pub arn: String,
    pub creation_time: i64,
    pub retention_in_days: Option<i32>,
    pub kms_key_id: Option<String>,
    pub tags: BTreeMap<String, String>,
    pub log_streams: BTreeMap<String, LogStream>,
    pub stored_bytes: i64,
    pub subscription_filters: Vec<SubscriptionFilter>,
    pub data_protection_policy: Option<DataProtectionPolicy>,
    pub index_policies: Vec<IndexPolicy>,
    pub transformer: Option<Transformer>,
    pub deletion_protection: bool,
    /// `STANDARD` (default), `INFREQUENT_ACCESS`, or `DELIVERY`. Set at
    /// creation time via `CreateLogGroup`'s `logGroupClass` parameter.
    /// Tracked here so `DescribeLogGroups` round-trips it correctly.
    pub log_group_class: Option<String>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogStream {
    pub name: String,
    pub arn: String,
    pub creation_time: i64,
    pub first_event_timestamp: Option<i64>,
    pub last_event_timestamp: Option<i64>,
    pub last_ingestion_time: Option<i64>,
    pub upload_sequence_token: String,
    pub events: Vec<LogEvent>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogEvent {
    pub timestamp: i64,
    pub message: String,
    pub ingestion_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct SubscriptionFilter {
    pub filter_name: String,
    pub log_group_name: String,
    pub filter_pattern: String,
    pub destination_arn: String,
    pub role_arn: Option<String>,
    pub distribution: String,
    pub creation_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct MetricFilter {
    pub filter_name: String,
    pub filter_pattern: String,
    pub log_group_name: String,
    pub metric_transformations: Vec<MetricTransformation>,
    pub creation_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct MetricTransformation {
    pub metric_name: String,
    pub metric_namespace: String,
    pub metric_value: String,
    pub default_value: Option<f64>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct ResourcePolicy {
    pub policy_name: String,
    pub policy_document: String,
    pub last_updated_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Destination {
    pub destination_name: String,
    pub target_arn: String,
    pub role_arn: String,
    pub arn: String,
    pub access_policy: Option<String>,
    pub creation_time: i64,
    pub tags: BTreeMap<String, String>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct QueryInfo {
    pub query_id: String,
    pub log_group_name: String,
    /// Every log group / identifier referenced by this query, used by
    /// `ListLogGroupsForQuery`. Always includes `log_group_name` plus any
    /// names from `logGroupNames` / identifiers from `logGroupIdentifiers`
    /// passed at start time.
    #[serde(default)]
    pub log_group_identifiers: Vec<String>,
    pub query_string: String,
    pub start_time: i64,
    pub end_time: i64,
    pub status: String,
    pub create_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportTask {
    pub task_id: String,
    pub task_name: Option<String>,
    pub log_group_name: String,
    pub log_stream_name_prefix: Option<String>,
    pub from_time: i64,
    pub to_time: i64,
    pub destination: String,
    pub destination_prefix: String,
    pub status_code: String,
    pub status_message: String,
    #[serde(default)]
    pub creation_time: i64,
    #[serde(default)]
    pub completion_time: Option<i64>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct DeliveryDestination {
    pub name: String,
    pub arn: String,
    pub output_format: Option<String>,
    pub delivery_destination_configuration: BTreeMap<String, String>,
    pub tags: BTreeMap<String, String>,
    pub delivery_destination_policy: Option<String>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct DeliverySource {
    pub name: String,
    pub arn: String,
    pub resource_arns: Vec<String>,
    pub service: String,
    pub log_type: String,
    pub tags: BTreeMap<String, String>,
    #[serde(default)]
    pub created_at: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Delivery {
    pub id: String,
    pub delivery_source_name: String,
    pub delivery_destination_arn: String,
    pub delivery_destination_type: String,
    pub arn: String,
    pub tags: BTreeMap<String, String>,
    #[serde(default)]
    pub field_delimiter: Option<String>,
    #[serde(default)]
    pub record_fields: Vec<String>,
    #[serde(default)]
    pub s3_delivery_configuration: Option<serde_json::Value>,
    #[serde(default)]
    pub created_at: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct QueryDefinition {
    pub query_definition_id: String,
    pub name: String,
    pub query_string: String,
    pub log_group_names: Vec<String>,
    pub last_modified: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct AccountPolicy {
    pub policy_name: String,
    pub policy_type: String,
    pub policy_document: String,
    pub scope: Option<String>,
    pub selection_criteria: Option<String>,
    pub account_id: String,
    pub last_updated_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct DataProtectionPolicy {
    pub policy_document: String,
    pub last_updated_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct IndexPolicy {
    pub policy_name: String,
    pub policy_document: String,
    pub last_updated_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Transformer {
    pub transformer_config: serde_json::Value,
    pub creation_time: i64,
    pub last_modified_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct AnomalyDetector {
    pub detector_name: String,
    pub arn: String,
    pub log_group_arn_list: Vec<String>,
    pub evaluation_frequency: Option<String>,
    pub filter_pattern: Option<String>,
    pub anomaly_visibility_time: Option<i64>,
    pub creation_time: i64,
    pub last_modified_time: i64,
    pub enabled: bool,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct ImportTask {
    pub import_id: String,
    pub import_source_arn: String,
    pub import_role_arn: String,
    pub log_group_name: Option<String>,
    pub status: String,
    pub creation_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Integration {
    pub integration_name: String,
    pub integration_type: String,
    pub resource_config: serde_json::Value,
    pub status: String,
    pub creation_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LookupTable {
    pub lookup_table_name: String,
    pub arn: String,
    pub table_body: String,
    pub creation_time: i64,
    pub last_modified_time: i64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct ScheduledQuery {
    pub name: String,
    pub arn: String,
    pub query_string: String,
    pub query_language: String,
    pub schedule_expression: String,
    pub execution_role_arn: String,
    pub status: String,
    pub creation_time: i64,
    pub last_modified_time: i64,
}

/// On-disk snapshot envelope for CloudWatch Logs state. Versioned so
/// format changes fail loudly on upgrade.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct LogsSnapshot {
    pub schema_version: u32,
    #[serde(default)]
    pub accounts: Option<fakecloud_core::multi_account::MultiAccountState<LogsState>>,
    #[serde(default)]
    pub state: Option<LogsState>,
}

pub const LOGS_SNAPSHOT_SCHEMA_VERSION: u32 = 2;

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

    #[test]
    fn new_initializes_empty() {
        let state = LogsState::new("123456789012", "us-east-1");
        assert_eq!(state.account_id, "123456789012");
        assert_eq!(state.region, "us-east-1");
        assert!(state.log_groups.is_empty());
        assert!(state.queries.is_empty());
    }

    #[test]
    fn reset_clears_state() {
        let mut state = LogsState::new("123456789012", "us-east-1");
        state.bearer_token_auth.insert("g".to_string(), true);
        state.reset();
        assert!(state.bearer_token_auth.is_empty());
    }
}