trust-registry 0.20.0

Trust Registry
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
use crate::domain::{key::TrustRecordKey, *};
use crate::storage::repository::*;
use anyhow::anyhow;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as base64;
use serde_json::Value;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
    time::{Duration, SystemTime},
};
use tokio_util::sync::CancellationToken;

use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use tokio::time::sleep;
use tracing::{error, info};

#[derive(Clone)]
pub struct FileStorage {
    file_path: PathBuf,
    update_interval: Duration,
    records: Arc<RwLock<HashMap<TrustRecordKey, TrustRecord>>>,
    last_modified: Arc<RwLock<Option<SystemTime>>>,
    shutdown: CancellationToken,
}

impl FileStorage {
    pub async fn try_new<P: Into<PathBuf>>(
        file_path: P,
        update_interval_sec: u64,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let file_path = file_path.into();
        let update_interval = Duration::from_secs(update_interval_sec);

        let records = Arc::new(RwLock::new(HashMap::new()));
        let last_modified = Arc::new(RwLock::new(None));

        let (initial_records, modified) = Self::load_if_modified(&file_path, None)
            .await?
            .ok_or_else(|| {
                anyhow!("unable to load trust records from {}", file_path.display())
                    .into_boxed_dyn_error()
            })?;

        {
            let mut guard = records.write().await;
            *guard = initial_records;
        }
        {
            let mut guard = last_modified.write().await;
            *guard = Some(modified);
        }

        let storage = Self {
            file_path: file_path.clone(),
            update_interval,
            records: Arc::clone(&records),
            last_modified: Arc::clone(&last_modified),
            shutdown: CancellationToken::new(),
        };

        storage.spawn_sync_task();

        Ok(storage)
    }

    fn spawn_sync_task(&self) {
        let file_path = self.file_path.clone();
        let update_interval = self.update_interval;
        let records = Arc::clone(&self.records);
        let last_modified = Arc::clone(&self.last_modified);
        let shutdown = self.shutdown.clone();

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = shutdown.cancelled() => {
                        info!(path = %file_path.display(), "CSV sync task shutting down");
                        break;
                    }
                    _ = sleep(update_interval) => {
                        info!(path = %file_path.display(), "Syncing trust records from file");

                        let previous = { *last_modified.read().await };

                        match Self::load_if_modified(&file_path, previous).await {
                            Ok(Some((new_records, modified))) => {
                                {
                                    let mut guard = records.write().await;
                                    *guard = new_records;
                                }
                                {
                                    let mut guard = last_modified.write().await;
                                    *guard = Some(modified);
                                }
                            }
                            Ok(None) => {}
                            Err(err) => {
                                error!(
                                    error = %err,
                                    path = %file_path.display(),
                                    "Failed to sync trust records from file"
                                );
                            }
                        }
                    }
                }
            }
        });
    }

    async fn load_if_modified(
        path: &Path,
        last_seen: Option<SystemTime>,
    ) -> Result<
        Option<(HashMap<TrustRecordKey, TrustRecord>, SystemTime)>,
        Box<dyn std::error::Error + Send + Sync>,
    > {
        let metadata = tokio::fs::metadata(path)
            .await
            .map_err(|e| format!("file_path: {path:?}, error: {e}"))?;
        let modified = metadata.modified()?;

        if let Some(previous) = last_seen
            && modified <= previous
        {
            info!(
                path = %path.display(),
                "No changes detected in trust records file"
            );
            return Ok(None);
        }

        info!(
            path = %path.display(),
            "Changes detected in trust records file, reloading"
        );
        let contents = tokio::fs::read_to_string(path).await?.trim().to_string();

        let records = Self::parse_csv(&contents)?;

        Ok(Some((records, modified)))
    }

    fn parse_csv(
        contents: &str,
    ) -> Result<HashMap<TrustRecordKey, TrustRecord>, Box<dyn std::error::Error + Send + Sync>>
    {
        let mut reader = csv::ReaderBuilder::new()
            .has_headers(true)
            .trim(csv::Trim::All)
            .from_reader(contents.as_bytes());

        let mut records = HashMap::new();

        for result in reader.deserialize::<TrustRecordCsvRow>() {
            let row = result?;
            let record = row.into_record()?;
            let key = TrustRecordKey::from_record(&record);
            records.insert(key, record);
        }

        Ok(records)
    }

    fn matches_query(record: &TrustRecord, query: &TrustRecordQuery) -> bool {
        record.entity_id() == &query.entity_id
            && record.authority_id() == &query.authority_id
            && record.action() == &query.action
            && record.resource() == &query.resource
    }

    async fn write_to_file(&self) -> Result<(), RepositoryError> {
        let records_clone = {
            let records = self.records.read().await;
            records.values().cloned().collect::<Vec<_>>()
        };

        let mut csv_records = Vec::new();
        for record in records_clone.iter() {
            csv_records.push(TrustRecordCsvRow::from_record(record));
        }

        let mut wtr = csv::Writer::from_writer(vec![]);
        for row in csv_records {
            wtr.serialize(&row)
                .map_err(|e| RepositoryError::SerializationFailed(e.to_string()))?;
        }

        let csv_data = wtr
            .into_inner()
            .map_err(|e| RepositoryError::SerializationFailed(e.to_string()))?;

        tokio::fs::write(&self.file_path, csv_data)
            .await
            .map_err(|e| RepositoryError::QueryFailed(format!("Failed to write CSV file: {e}")))?;

        // Update last_modified to prevent reload
        let metadata = tokio::fs::metadata(&self.file_path).await.map_err(|e| {
            RepositoryError::QueryFailed(format!("Failed to get file metadata: {e}"))
        })?;
        let modified = metadata.modified().map_err(|e| {
            RepositoryError::QueryFailed(format!("Failed to get modified time: {e}"))
        })?;

        let mut guard = self.last_modified.write().await;
        *guard = Some(modified);

        Ok(())
    }
}

#[async_trait::async_trait]
impl TrustRecordRepository for FileStorage {
    async fn find_by_query(
        &self,
        query: TrustRecordQuery,
    ) -> Result<Option<TrustRecord>, RepositoryError> {
        let records = Arc::clone(&self.records);

        let guard = records.read().await;
        let result = guard
            .values()
            .find(|&record| FileStorage::matches_query(record, &query))
            .cloned();

        Ok(result)
    }
}

#[async_trait::async_trait]
impl TrustRecordAdminRepository for FileStorage {
    async fn create(&self, record: TrustRecord) -> Result<(), RepositoryError> {
        let key = TrustRecordKey::from_record(&record);
        {
            let mut records = self.records.write().await;
            if records.contains_key(&key) {
                return Err(RepositoryError::RecordAlreadyExists(format!(
                    "Record already exists: {record}"
                )));
            }
            records.insert(key, record);
        }
        self.write_to_file().await
    }

    async fn update(&self, record: TrustRecord) -> Result<(), RepositoryError> {
        let key = TrustRecordKey::from_record(&record);
        {
            let mut records = self.records.write().await;
            if !records.contains_key(&key) {
                return Err(RepositoryError::RecordNotFound(format!(
                    "Record not found: {record}"
                )));
            }
            records.insert(key, record);
        }
        self.write_to_file().await
    }

    async fn delete(&self, query: TrustRecordQuery) -> Result<(), RepositoryError> {
        let key = TrustRecordKey::from_query(&query);
        {
            let mut records = self.records.write().await;
            if records.remove(&key).is_none() {
                return Err(RepositoryError::RecordNotFound(format!(
                    "Record not found: {key}",
                )));
            }
        }
        self.write_to_file().await
    }

    async fn list(&self) -> Result<TrustRecordList, RepositoryError> {
        let records = self.records.read().await;
        let records_vec: Vec<TrustRecord> = records.values().cloned().collect();
        Ok(TrustRecordList::new(records_vec))
    }

    async fn read(&self, query: TrustRecordQuery) -> Result<TrustRecord, RepositoryError> {
        let records = self.records.read().await;
        let result = records
            .values()
            .find(|&record| FileStorage::matches_query(record, &query))
            .cloned();

        result.ok_or_else(|| {
            RepositoryError::RecordNotFound(format!(
                "Record not found: {}|{}|{}|{}",
                query.entity_id, query.authority_id, query.action, query.resource
            ))
        })
    }
}

impl Drop for FileStorage {
    fn drop(&mut self) {
        self.shutdown.cancel();
    }
}

#[derive(Debug, Deserialize, Serialize)]
struct TrustRecordCsvRow {
    entity_id: String,
    authority_id: String,
    action: String,
    resource: String,
    recognized: bool,
    authorized: bool,
    context: Option<String>,
    record_type: String,
}

impl TrustRecordCsvRow {
    fn parse_context(ctx: Option<String>) -> Option<Value> {
        let record_context: Option<Value> = if let Some(c) = ctx {
            base64
                .decode(&c)
                .ok()
                .and_then(|db| String::from_utf8(db).ok())
                .and_then(|s| serde_json::from_str(&s).ok())
        } else {
            None
        };

        record_context
    }

    fn from_record(record: &TrustRecord) -> Self {
        let context = if record.context().as_value().is_object()
            || record.context().as_value().is_array()
        {
            let json_str = serde_json::to_string(record.context().as_value()).unwrap_or_default();
            let encoded = base64.encode(json_str.as_bytes());
            Some(encoded)
        } else {
            None
        };

        Self {
            entity_id: record.entity_id().to_string(),
            authority_id: record.authority_id().to_string(),
            action: record.action().to_string(),
            resource: record.resource().to_string(),
            recognized: record.is_recognized(),
            authorized: record.is_authorized(),
            context,
            record_type: record.record_type().to_string(),
        }
    }

    fn into_record(self) -> Result<TrustRecord, Box<dyn std::error::Error + Send + Sync>> {
        let ctx = TrustRecordCsvRow::parse_context(self.context);
        let mut builder = TrustRecordBuilder::new()
            .entity_id(EntityId::new(self.entity_id))
            .authority_id(AuthorityId::new(self.authority_id))
            .action(Action::new(self.action))
            .resource(Resource::new(self.resource))
            .recognized(self.recognized)
            .authorized(self.authorized)
            .record_type(RecordType::from_str(&self.record_type)?);

        if let Some(c) = ctx {
            builder = builder.context(Context::new(c));
        }

        builder
            .build()
            .map_err(|err| anyhow!("invalid trust record: {err}").into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;
    use tokio::time::{Duration, sleep};

    fn csv_header() -> String {
        String::from(
            "entity_id,authority_id,action,resource,recognized,authorized,context,record_type\n",
        )
    }

    fn sample_csv(records: &[(&str, &str, &str, &str, &str)]) -> String {
        let mut csv = String::new();
        for (entity, authority, action, resource, record_type) in records {
            csv.push_str(&format!(
                "{entity},{authority},{action},{resource},true,true,e30=,{record_type}\n"
            ));
        }
        csv
    }

    #[tokio::test]
    async fn fails_when_initial_load_fails() {
        let result = FileStorage::try_new("/does/not/exist.csv", 1).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn finds_records_from_initial_load() {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", csv_header()).unwrap();
        write!(
            file,
            "{}",
            sample_csv(&[("e1", "a1", "ac1", "r1", "authorization")])
        )
        .unwrap();

        let storage = FileStorage::try_new(file.path(), 1).await.unwrap();

        let query = TrustRecordQuery::new(
            EntityId::new("e1"),
            AuthorityId::new("a1"),
            Action::new("ac1"),
            Resource::new("r1"),
        );

        let result = storage.find_by_query(query).await.unwrap();
        assert!(result.is_some());
        let record = result.unwrap();
        assert_eq!(*record.record_type(), RecordType::Authorization);
    }

    #[tokio::test]
    async fn reloads_when_file_changes() {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", csv_header()).unwrap();
        write!(
            file,
            "{}",
            sample_csv(&[("e1", "a1", "ac1", "r1", "recognition")])
        )
        .unwrap();
        file.flush().unwrap();

        let storage = FileStorage::try_new(file.path(), 1).await.unwrap();

        sleep(Duration::from_secs(1)).await;
        write!(
            file.as_file_mut(),
            "{}",
            sample_csv(&[("e2", "a2", "ac2", "r2", "recognition")])
        )
        .unwrap();
        file.flush().unwrap();

        // Wait for sync task to detect and process changes
        // Using a reasonable buffer for slow CI machines
        sleep(Duration::from_secs(2)).await;

        let query = TrustRecordQuery::new(
            EntityId::new("e2"),
            AuthorityId::new("a2"),
            Action::new("ac2"),
            Resource::new("r2"),
        );

        let result = storage.find_by_query(query).await.unwrap();

        assert!(result.is_some());
        assert_eq!(result.clone().unwrap().entity_id().as_str(), "e2");
        assert_eq!(*result.unwrap().record_type(), RecordType::Recognition);
    }
}