guardian-db 0.15.0

High-performance, local-first decentralized database built on Rust and Iroh
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
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
use crate::access_control::manifest::{CreateAccessControllerOptions, ManifestParams};
use crate::access_control::traits::AccessController;
use crate::address::Address;
use crate::guardian::error::{GuardianError, Result};
use crate::log::{access_control::LogEntry, identity_provider::IdentityProvider};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{Span, debug, info, instrument, warn};

/// Estado interno do SimpleAccessController
struct SimpleAccessControllerState {
    allowed_keys: HashMap<String, Vec<String>>,
}

/// Estrutura principal do controlador de acesso simples.
/// Mantém uma lista de chaves autorizadas em memória.
pub struct SimpleAccessController {
    state: Arc<RwLock<SimpleAccessControllerState>>,
    span: Span,
}

impl SimpleAccessController {
    /// Cria um novo SimpleAccessController com configuração inicial opcional
    #[instrument(skip(initial_keys))]
    pub fn new(initial_keys: Option<HashMap<String, Vec<String>>>) -> Self {
        let mut allowed_keys = initial_keys.unwrap_or_default();

        // Garante que pelo menos as categorias básicas existam
        allowed_keys.entry("read".to_string()).or_default();
        allowed_keys.entry("write".to_string()).or_default();
        allowed_keys.entry("admin".to_string()).or_default();

        info!(target: "simple_access_controller",
            categories = ?allowed_keys.keys().collect::<Vec<_>>(),
            total_permissions = allowed_keys.values().map(|v| v.len()).sum::<usize>(),
            "Created SimpleAccessController"
        );

        Self {
            state: Arc::new(RwLock::new(SimpleAccessControllerState { allowed_keys })),
            span: tracing::info_span!("simple_access_controller"),
        }
    }

    /// Cria um novo SimpleAccessController simples
    #[allow(dead_code)]
    pub fn new_simple() -> Self {
        Self::new(None)
    }

    /// Retorna uma referência ao span de tracing para instrumentação
    pub fn span(&self) -> &Span {
        &self.span
    }

    /// Lista todas as chaves de uma capacidade
    pub async fn list_keys(&self, capability: &str) -> Vec<String> {
        let state = self.state.read().await;
        state
            .allowed_keys
            .get(capability)
            .cloned()
            .unwrap_or_default()
    }

    /// Lista todas as capacidades disponíveis
    #[allow(dead_code)]
    pub async fn list_capabilities(&self) -> Vec<String> {
        let state = self.state.read().await;
        state.allowed_keys.keys().cloned().collect()
    }

    /// Verifica se uma chave tem uma capacidade específica
    #[allow(dead_code)]
    pub async fn has_capability(&self, capability: &str, key_id: &str) -> bool {
        let state = self.state.read().await;

        if let Some(keys) = state.allowed_keys.get(capability) {
            keys.contains(&"*".to_string()) || keys.contains(&key_id.to_string())
        } else {
            false
        }
    }

    /// Remove todas as chaves de uma capacidade
    pub async fn clear_capability(&self, capability: &str) -> Result<()> {
        if capability.is_empty() {
            return Err(GuardianError::Store(
                "Capability cannot be empty".to_string(),
            ));
        }

        let mut state = self.state.write().await;

        if let Some(keys) = state.allowed_keys.get_mut(capability) {
            let count = keys.len();
            keys.clear();

            info!(target: "simple_access_controller",
                capability = %capability,
                removed_keys = count,
                "Capability cleared"
            );
        } else {
            warn!(target: "simple_access_controller",
                capability = %capability,
                "Capability not found for clearing"
            );
        }

        Ok(())
    }

    /// Obtém estatísticas das permissões
    pub async fn get_stats(&self) -> HashMap<String, usize> {
        let state = self.state.read().await;
        state
            .allowed_keys
            .iter()
            .map(|(capability, keys)| (capability.clone(), keys.len()))
            .collect()
    }

    /// Verifica se uma capacidade está vazia
    pub async fn is_capability_empty(&self, capability: &str) -> bool {
        let state = self.state.read().await;
        state
            .allowed_keys
            .get(capability)
            .map(|keys| keys.is_empty())
            .unwrap_or(true)
    }

    /// Conta o total de permissões em todas as capacidades
    pub async fn total_permissions(&self) -> usize {
        let state = self.state.read().await;
        state.allowed_keys.values().map(|keys| keys.len()).sum()
    }

    /// Exporta todas as permissões para um HashMap
    pub async fn export_permissions(&self) -> HashMap<String, Vec<String>> {
        let state = self.state.read().await;
        state.allowed_keys.clone()
    }

    /// Importa permissões de um HashMap (substitui todas as existentes)
    pub async fn import_permissions(
        &self,
        permissions: HashMap<String, Vec<String>>,
    ) -> Result<()> {
        let mut state = self.state.write().await;

        info!(target: "simple_access_controller", "Importing permissions: capabilities_count={}, total_permissions={}",
            permissions.len(),
            permissions.values().map(|v| v.len()).sum::<usize>()
        );

        state.allowed_keys = permissions;
        Ok(())
    }

    /// Adiciona múltiplas chaves a uma capacidade de uma vez
    pub async fn grant_multiple(&self, capability: &str, key_ids: Vec<&str>) -> Result<()> {
        let _entered = self.span.enter();

        if capability.is_empty() {
            return Err(GuardianError::Store(
                "Capability cannot be empty".to_string(),
            ));
        }

        let mut state = self.state.write().await;
        let keys = state
            .allowed_keys
            .entry(capability.to_string())
            .or_insert_with(Vec::new);

        let mut added_count = 0;
        for key_id in key_ids {
            if !key_id.is_empty() && !keys.contains(&key_id.to_string()) {
                keys.push(key_id.to_string());
                added_count += 1;
            }
        }

        let total_keys = keys.len();
        let capability_name = capability.to_string();

        info!(target: "simple_access_controller", "Multiple permissions granted: capability={}, added_keys={}, total_keys={}",
            capability_name, added_count, total_keys
        );

        Ok(())
    }

    /// Remove múltiplas chaves de uma capacidade de uma vez
    pub async fn revoke_multiple(&self, capability: &str, key_ids: Vec<&str>) -> Result<()> {
        let _entered = self.span.enter();

        if capability.is_empty() {
            return Err(GuardianError::Store(
                "Capability cannot be empty".to_string(),
            ));
        }

        let mut state = self.state.write().await;

        if let Some(keys) = state.allowed_keys.get_mut(capability) {
            let initial_len = keys.len();

            for key_id in key_ids {
                keys.retain(|k| k != key_id);
            }

            let removed_count = initial_len - keys.len();
            let remaining_keys = keys.len();
            let capability_name = capability.to_string();
            let should_remove_capability = keys.is_empty();

            info!(target: "simple_access_controller", "Multiple permissions revoked: capability={}, removed_keys={}, remaining_keys={}",
                capability_name, removed_count, remaining_keys
            );

            // Remove a capacidade completamente se não há mais chaves
            if should_remove_capability {
                state.allowed_keys.remove(capability);
                debug!(target: "simple_access_controller", "Capability removed completely: capability={}",
                    capability
                );
            }
        }

        Ok(())
    }

    /// Clona as permissões de uma capacidade para outra
    pub async fn clone_capability(
        &self,
        source_capability: &str,
        target_capability: &str,
    ) -> Result<()> {
        if source_capability.is_empty() || target_capability.is_empty() {
            return Err(GuardianError::Store(
                "Source and target capabilities cannot be empty".to_string(),
            ));
        }

        let mut state = self.state.write().await;

        if let Some(source_keys) = state.allowed_keys.get(source_capability) {
            let cloned_keys = source_keys.clone();
            let keys_count = cloned_keys.len();

            state
                .allowed_keys
                .insert(target_capability.to_string(), cloned_keys);

            info!(target: "simple_access_controller", "Capability cloned: source_capability={}, target_capability={}, cloned_keys={}",
                source_capability, target_capability, keys_count
            );
        } else {
            return Err(GuardianError::Store(format!(
                "Source capability '{}' not found",
                source_capability
            )));
        }

        Ok(())
    }

    /// Este controlador não tem um endereço, pois não é persistido.
    pub fn address(&self) -> Option<Box<dyn Address>> {
        None
    }

    /// Método factory alternativo
    #[instrument(skip(params))]
    pub fn from_options(params: CreateAccessControllerOptions) -> Result<Self> {
        // As permissões são extraídas diretamente dos parâmetros de criação.
        let allowed_keys = params.get_all_access();
        Ok(Self {
            state: Arc::new(RwLock::new(SimpleAccessControllerState { allowed_keys })),
            span: tracing::info_span!("simple_access_controller", controller_type = "simple"),
        })
    }
}

#[async_trait]
impl AccessController for SimpleAccessController {
    fn get_type(&self) -> &str {
        "simple"
    }

    async fn get_authorized_by_role(&self, role: &str) -> Result<Vec<String>> {
        let _entered = self.span.enter();

        // Validação de parâmetros
        if role.is_empty() {
            return Err(GuardianError::Store("Role cannot be empty".to_string()));
        }

        let state = self.state.read().await;

        // Log da consulta
        debug!(target: "simple_access_controller", "Getting authorized keys by role: role={}",
            role
        );

        let keys = state.allowed_keys.get(role).cloned().unwrap_or_default();

        debug!(target: "simple_access_controller", "Retrieved authorized keys: role={}, key_count={}",
            role, keys.len()
        );

        Ok(keys)
    }

    async fn grant(&self, capability: &str, key_id: &str) -> Result<()> {
        let _entered = self.span.enter();

        // Validação de parâmetros
        if capability.is_empty() {
            return Err(GuardianError::Store(
                "Capability cannot be empty".to_string(),
            ));
        }
        if key_id.is_empty() {
            return Err(GuardianError::Store("Key ID cannot be empty".to_string()));
        }

        let mut state = self.state.write().await;

        // Log da operação
        info!(target: "simple_access_controller", "Granting permission: capability={}, key_id={}",
            capability, key_id
        );

        // Adiciona a chave à lista de permissões para a capacidade especificada
        let entry = state
            .allowed_keys
            .entry(capability.to_string())
            .or_insert_with(Vec::new);

        // Verifica se a chave já existe para evitar duplicatas
        if !entry.contains(&key_id.to_string()) {
            entry.push(key_id.to_string());
            let total_keys = entry.len();
            let capability_name = capability.to_string();
            let key_id_name = key_id.to_string();

            debug!(target: "simple_access_controller", "Permission granted successfully: capability={}, key_id={}, total_keys={}",
                capability_name, key_id_name, total_keys
            );
        } else {
            debug!(target: "simple_access_controller", "Permission already exists: capability={}, key_id={}",
                capability, key_id
            );
        }

        Ok(())
    }

    async fn revoke(&self, capability: &str, key_id: &str) -> Result<()> {
        let _entered = self.span.enter();

        // Validação de parâmetros
        if capability.is_empty() {
            return Err(GuardianError::Store(
                "Capability cannot be empty".to_string(),
            ));
        }
        if key_id.is_empty() {
            return Err(GuardianError::Store("Key ID cannot be empty".to_string()));
        }

        let mut state = self.state.write().await;

        // Log da operação
        info!(target: "simple_access_controller", "Revoking permission: capability={}, key_id={}",
            capability, key_id
        );

        // Remove a chave da lista de permissões para a capacidade especificada
        if let Some(keys) = state.allowed_keys.get_mut(capability) {
            let initial_len = keys.len();
            keys.retain(|k| k != key_id);

            if keys.len() < initial_len {
                let remaining_keys = keys.len();
                let capability_name = capability.to_string();
                let key_id_name = key_id.to_string();
                let should_remove_capability = keys.is_empty();

                debug!(target: "simple_access_controller", "Permission revoked successfully: capability={}, key_id={}, remaining_keys={}",
                    capability_name, key_id_name, remaining_keys
                );

                // Remove a entrada completamente se não há mais chaves
                if should_remove_capability {
                    state.allowed_keys.remove(capability);
                    debug!(target: "simple_access_controller", "Capability removed completely: capability={}",
                        capability
                    );
                }
            } else {
                debug!(target: "simple_access_controller", "Permission not found for revocation: capability={}, key_id={}",
                    capability, key_id
                );
            }
        } else {
            debug!(target: "simple_access_controller", "Capability not found for revocation: capability={}",
                capability
            );
        }

        Ok(())
    }

    async fn load(&self, address: &str) -> Result<()> {
        // Validação de parâmetros
        if address.is_empty() {
            return Err(GuardianError::Store("Address cannot be empty".to_string()));
        }

        // Log da operação
        info!(target: "simple_access_controller", "Loading access controller configuration: address={}",
            address
        );

        // Para SimpleAccessController, load é uma operação no-op já que é baseado em memória
        // Em uma implementação mais avançada, isso poderia carregar de um arquivo ou rede
        debug!(target: "simple_access_controller", "Load operation completed (no-op for simple controller): address={}",
            address
        );

        Ok(())
    }

    async fn save(&self) -> Result<Box<dyn ManifestParams>> {
        let state = self.state.read().await;

        // Log da operação
        info!(target: "simple_access_controller", "Saving access controller configuration");

        // Cria opções com as permissões atuais
        let mut options = CreateAccessControllerOptions::new_empty();
        options.set_type("simple".to_string());

        // Copia todas as permissões atuais para o manifesto
        for (capability, keys) in &state.allowed_keys {
            options.set_access(capability.clone(), keys.clone());
        }

        debug!(target: "simple_access_controller", "Save operation completed: capabilities_count={}",
            state.allowed_keys.len()
        );

        Ok(Box::new(options))
    }

    async fn close(&self) -> Result<()> {
        let state = self.state.read().await;

        // Log da operação de fechamento
        info!(target: "simple_access_controller", "Closing simple access controller");

        // Para SimpleAccessController, close é uma operação no-op já que é baseado em memória
        // Em uma implementação mais avançada, isso poderia fechar conexões ou salvar estado
        debug!(target: "simple_access_controller", "Close operation completed: capabilities_count={}",
            state.allowed_keys.len()
        );

        Ok(())
    }

    async fn can_append(
        &self,
        entry: &dyn LogEntry,
        identity_provider: &dyn IdentityProvider,
        _additional_context: &dyn crate::log::access_control::CanAppendAdditionalContext,
    ) -> Result<()> {
        let _entered = self.span.enter();
        let state = self.state.read().await;

        // Obtém o ID da identidade da entrada
        let entry_identity = entry.get_identity();
        let entry_id = entry_identity.id();

        debug!(target: "simple_access_controller", "Checking append permission: entry_id={}",
            entry_id
        );

        // Verifica primeiro as chaves com permissão de escrita
        if let Some(write_keys) = state.allowed_keys.get("write") {
            // Verifica se há um wildcard que permite qualquer identidade
            if write_keys.contains(&"*".to_string()) {
                debug!(target: "simple_access_controller", "Wildcard permission found, verifying identity: entry_id={}",
                    entry_id
                );

                // Ainda assim, verifica a identidade para garantir que é válida
                if let Err(e) = identity_provider
                    .verify_identity(entry.get_identity())
                    .await
                {
                    warn!(target: "simple_access_controller", "Invalid identity signature for wildcard access: entry_id={}, error={}",
                        entry_id, e
                    );
                    return Err(GuardianError::Store(format!(
                        "Invalid identity signature: {}",
                        e
                    )));
                }

                debug!(target: "simple_access_controller", "Append permission granted (wildcard): entry_id={}",
                    entry_id
                );
                return Ok(());
            }

            // Verifica se o ID da entrada está na lista de chaves autorizadas para escrita
            if write_keys.contains(&entry_id.to_string()) {
                // Verifica a assinatura da identidade
                if let Err(e) = identity_provider.verify_identity(entry_identity).await {
                    warn!(target: "simple_access_controller", "Invalid identity signature for authorized key: entry_id={}, error={}",
                        entry_id, e
                    );
                    return Err(GuardianError::Store(format!(
                        "Invalid identity signature for authorized key {}: {}",
                        entry_id, e
                    )));
                }

                debug!(target: "simple_access_controller", "Append permission granted (write key): entry_id={}",
                    entry_id
                );
                return Ok(());
            }
        }

        // Verifica também permissões de admin (admin pode escrever)
        if let Some(admin_keys) = state.allowed_keys.get("admin")
            && (admin_keys.contains(&"*".to_string()) || admin_keys.contains(&entry_id.to_string()))
        {
            // Verifica a assinatura da identidade
            if let Err(e) = identity_provider.verify_identity(entry_identity).await {
                warn!(target: "simple_access_controller", "Invalid identity signature for admin key: entry_id={}, error={}",
                    entry_id, e
                );
                return Err(GuardianError::Store(format!(
                    "Invalid identity signature for admin key {}: {}",
                    entry_id, e
                )));
            }

            debug!(target: "simple_access_controller", "Append permission granted (admin key): entry_id={}",
                entry_id
            );
            return Ok(());
        }

        warn!(target: "simple_access_controller", "Access denied for append operation: entry_id={}, available_write_keys={:?}, available_admin_keys={:?}",
            entry_id, state.allowed_keys.get("write"), state.allowed_keys.get("admin")
        );

        Err(GuardianError::Store(format!(
            "Access denied: identity {} not authorized for write operations",
            entry_id
        )))
    }
}