neumann_server 0.4.0

gRPC server exposing Neumann database via QueryRouter
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Audit logging for server events.
//!
//! Records authentication events, queries, and blob operations for compliance and debugging.

#![allow(clippy::missing_panics_doc)]

use std::{
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

use dashmap::DashMap;
use serde::{Deserialize, Serialize};

/// Configuration for audit logging.
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct AuditConfig {
    /// Enable audit logging.
    pub enabled: bool,
    /// Log successful authentications.
    pub log_success: bool,
    /// Log failed authentications.
    pub log_failure: bool,
    /// Log query executions.
    pub log_queries: bool,
    /// Log blob operations.
    pub log_blob_ops: bool,
    /// Log vector operations.
    pub log_vector_ops: bool,
    /// Maximum entries to retain (0 = unlimited).
    pub max_entries: usize,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            log_success: true,
            log_failure: true,
            log_queries: false,
            log_blob_ops: true,
            log_vector_ops: true,
            max_entries: 100_000,
        }
    }
}

impl AuditConfig {
    /// Create a new default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable query logging.
    #[must_use]
    pub const fn with_query_logging(mut self) -> Self {
        self.log_queries = true;
        self
    }

    /// Enable vector operations logging.
    #[must_use]
    pub const fn with_vector_logging(mut self) -> Self {
        self.log_vector_ops = true;
        self
    }

    /// Disable vector operations logging.
    #[must_use]
    pub const fn without_vector_logging(mut self) -> Self {
        self.log_vector_ops = false;
        self
    }

    /// Set maximum entries to retain.
    #[must_use]
    pub const fn with_max_entries(mut self, max: usize) -> Self {
        self.max_entries = max;
        self
    }

    /// Disable audit logging.
    #[must_use]
    pub const fn disabled(mut self) -> Self {
        self.enabled = false;
        self
    }
}

/// Audit event types.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuditEvent {
    /// Successful authentication.
    AuthSuccess {
        /// The authenticated identity.
        identity: String,
    },
    /// Failed authentication attempt.
    AuthFailure {
        /// Reason for failure.
        reason: String,
    },
    /// Query execution.
    QueryExecuted {
        /// Identity that executed the query (if authenticated).
        identity: Option<String>,
        /// The query string.
        query: String,
    },
    /// Blob upload.
    BlobUpload {
        /// Identity that uploaded (if authenticated).
        identity: Option<String>,
        /// The artifact ID.
        artifact_id: String,
        /// Size in bytes.
        size: usize,
    },
    /// Blob download.
    BlobDownload {
        /// Identity that downloaded (if authenticated).
        identity: Option<String>,
        /// The artifact ID.
        artifact_id: String,
    },
    /// Blob deletion.
    BlobDelete {
        /// Identity that deleted (if authenticated).
        identity: Option<String>,
        /// The artifact ID.
        artifact_id: String,
    },
    /// Rate limit exceeded.
    RateLimited {
        /// The rate-limited identity.
        identity: String,
        /// The operation that was limited.
        operation: String,
    },
    /// Vector upsert operation.
    VectorUpsert {
        /// Identity that performed the upsert (if authenticated).
        identity: Option<String>,
        /// The collection name.
        collection: String,
        /// Number of points upserted.
        count: usize,
    },
    /// Vector query operation.
    VectorQuery {
        /// Identity that performed the query (if authenticated).
        identity: Option<String>,
        /// The collection name.
        collection: String,
        /// Number of results requested.
        limit: usize,
    },
    /// Vector delete operation.
    VectorDelete {
        /// Identity that performed the delete (if authenticated).
        identity: Option<String>,
        /// The collection name.
        collection: String,
        /// Number of points deleted.
        count: usize,
    },
    /// Collection created.
    CollectionCreated {
        /// Identity that created the collection (if authenticated).
        identity: Option<String>,
        /// The collection name.
        collection: String,
    },
    /// Collection deleted.
    CollectionDeleted {
        /// Identity that deleted the collection (if authenticated).
        identity: Option<String>,
        /// The collection name.
        collection: String,
    },
}

/// Audit entry with timestamp and metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Unique entry ID.
    pub id: u64,
    /// The audit event.
    pub event: AuditEvent,
    /// Unix timestamp in milliseconds.
    pub timestamp: i64,
    /// Remote address of the client (if available).
    pub remote_addr: Option<String>,
}

/// Audit logger for server events.
pub struct AuditLogger {
    entries: DashMap<u64, AuditEntry>,
    counter: AtomicU64,
    config: AuditConfig,
}

impl AuditLogger {
    /// Create a new audit logger with the given configuration.
    #[must_use]
    pub fn new(config: AuditConfig) -> Self {
        Self {
            entries: DashMap::new(),
            counter: AtomicU64::new(0),
            config,
        }
    }

    #[allow(clippy::cast_possible_truncation)]
    fn now_millis() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0)
    }

    const fn should_log(&self, event: &AuditEvent) -> bool {
        if !self.config.enabled {
            return false;
        }

        match event {
            AuditEvent::AuthSuccess { .. } => self.config.log_success,
            AuditEvent::AuthFailure { .. } => self.config.log_failure,
            AuditEvent::QueryExecuted { .. } => self.config.log_queries,
            AuditEvent::BlobUpload { .. }
            | AuditEvent::BlobDownload { .. }
            | AuditEvent::BlobDelete { .. } => self.config.log_blob_ops,
            AuditEvent::VectorUpsert { .. }
            | AuditEvent::VectorQuery { .. }
            | AuditEvent::VectorDelete { .. }
            | AuditEvent::CollectionCreated { .. }
            | AuditEvent::CollectionDeleted { .. } => self.config.log_vector_ops,
            AuditEvent::RateLimited { .. } => true,
        }
    }

    fn enforce_max_entries(&self) {
        if self.config.max_entries == 0 {
            return;
        }

        let current_count = self.entries.len();
        if current_count <= self.config.max_entries {
            return;
        }

        // Remove oldest entries (lowest IDs)
        let to_remove = current_count - self.config.max_entries;
        let mut ids: Vec<u64> = self.entries.iter().map(|e| *e.key()).collect();
        ids.sort_unstable();

        for id in ids.into_iter().take(to_remove) {
            self.entries.remove(&id);
        }
    }

    /// Record an audit event (best-effort, never fails).
    pub fn record(&self, event: AuditEvent, remote_addr: Option<&str>) {
        if !self.should_log(&event) {
            return;
        }

        let id = self.counter.fetch_add(1, Ordering::SeqCst);
        let entry = AuditEntry {
            id,
            event,
            timestamp: Self::now_millis(),
            remote_addr: remote_addr.map(ToString::to_string),
        };

        self.entries.insert(id, entry);
        self.enforce_max_entries();
    }

    /// Query events by identity.
    #[must_use]
    pub fn by_identity(&self, identity: &str) -> Vec<AuditEntry> {
        self.entries
            .iter()
            .filter(|e| Self::entry_has_identity(&e.event, identity))
            .map(|e| e.clone())
            .collect()
    }

    fn entry_has_identity(event: &AuditEvent, identity: &str) -> bool {
        match event {
            AuditEvent::AuthSuccess { identity: id }
            | AuditEvent::RateLimited { identity: id, .. }
            | AuditEvent::QueryExecuted {
                identity: Some(id), ..
            }
            | AuditEvent::BlobUpload {
                identity: Some(id), ..
            }
            | AuditEvent::BlobDownload {
                identity: Some(id), ..
            }
            | AuditEvent::BlobDelete {
                identity: Some(id), ..
            }
            | AuditEvent::VectorUpsert {
                identity: Some(id), ..
            }
            | AuditEvent::VectorQuery {
                identity: Some(id), ..
            }
            | AuditEvent::VectorDelete {
                identity: Some(id), ..
            }
            | AuditEvent::CollectionCreated {
                identity: Some(id), ..
            }
            | AuditEvent::CollectionDeleted {
                identity: Some(id), ..
            } => id == identity,
            _ => false,
        }
    }

    /// Query events since timestamp.
    #[must_use]
    pub fn since(&self, since_millis: i64) -> Vec<AuditEntry> {
        self.entries
            .iter()
            .filter(|e| e.timestamp >= since_millis)
            .map(|e| e.clone())
            .collect()
    }

    /// Get recent events.
    #[must_use]
    pub fn recent(&self, limit: usize) -> Vec<AuditEntry> {
        let mut entries: Vec<_> = self.entries.iter().map(|e| e.clone()).collect();
        entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
        entries.truncate(limit);
        entries
    }

    /// Get total event count.
    #[must_use]
    pub fn count(&self) -> usize {
        self.entries.len()
    }

    /// Check if audit logging is enabled.
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the configuration.
    #[must_use]
    pub const fn config(&self) -> &AuditConfig {
        &self.config
    }
}

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

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

    #[test]
    fn test_record_auth_success() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:alice".to_string(),
            },
            Some("127.0.0.1"),
        );

        assert_eq!(logger.count(), 1);

        let entries = logger.by_identity("user:alice");
        assert_eq!(entries.len(), 1);
        assert!(matches!(entries[0].event, AuditEvent::AuthSuccess { .. }));
        assert_eq!(entries[0].remote_addr, Some("127.0.0.1".to_string()));
    }

    #[test]
    fn test_record_auth_failure() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::AuthFailure {
                reason: "invalid API key".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_record_query_executed() {
        let logger = AuditLogger::new(AuditConfig::default().with_query_logging());

        logger.record(
            AuditEvent::QueryExecuted {
                identity: Some("user:alice".to_string()),
                query: "SELECT users".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 1);

        let entries = logger.by_identity("user:alice");
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_record_query_not_logged_by_default() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::QueryExecuted {
                identity: Some("user:alice".to_string()),
                query: "SELECT users".to_string(),
            },
            None,
        );

        // Queries not logged by default
        assert_eq!(logger.count(), 0);
    }

    #[test]
    fn test_record_blob_operations() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::BlobUpload {
                identity: Some("user:alice".to_string()),
                artifact_id: "abc123".to_string(),
                size: 1024,
            },
            None,
        );

        logger.record(
            AuditEvent::BlobDownload {
                identity: Some("user:alice".to_string()),
                artifact_id: "abc123".to_string(),
            },
            None,
        );

        logger.record(
            AuditEvent::BlobDelete {
                identity: Some("user:alice".to_string()),
                artifact_id: "abc123".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 3);
    }

    #[test]
    fn test_record_rate_limited() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::RateLimited {
                identity: "user:alice".to_string(),
                operation: "request".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_query_by_identity() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:alice".to_string(),
            },
            None,
        );
        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:bob".to_string(),
            },
            None,
        );
        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:alice".to_string(),
            },
            None,
        );

        let alice_entries = logger.by_identity("user:alice");
        assert_eq!(alice_entries.len(), 2);

        let bob_entries = logger.by_identity("user:bob");
        assert_eq!(bob_entries.len(), 1);
    }

    #[test]
    fn test_query_since_timestamp() {
        let logger = AuditLogger::new(AuditConfig::default());

        let before = AuditLogger::now_millis();
        std::thread::sleep(std::time::Duration::from_millis(10));

        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:alice".to_string(),
            },
            None,
        );

        let entries = logger.since(before);
        assert_eq!(entries.len(), 1);

        let entries = logger.since(AuditLogger::now_millis() + 1000);
        assert!(entries.is_empty());
    }

    #[test]
    fn test_recent_entries() {
        let logger = AuditLogger::new(AuditConfig::default());

        for i in 0..10 {
            logger.record(
                AuditEvent::AuthSuccess {
                    identity: format!("user:{i}"),
                },
                None,
            );
            std::thread::sleep(std::time::Duration::from_millis(2));
        }

        let recent = logger.recent(3);
        assert_eq!(recent.len(), 3);
        // Most recent first
        assert!(recent[0].timestamp >= recent[1].timestamp);
        assert!(recent[1].timestamp >= recent[2].timestamp);
    }

    #[test]
    fn test_max_entries_enforcement() {
        let logger = AuditLogger::new(AuditConfig::default().with_max_entries(5));

        for i in 0..10 {
            logger.record(
                AuditEvent::AuthSuccess {
                    identity: format!("user:{i}"),
                },
                None,
            );
        }

        assert!(logger.count() <= 5);
    }

    #[test]
    fn test_disabled_no_recording() {
        let logger = AuditLogger::new(AuditConfig::default().disabled());

        logger.record(
            AuditEvent::AuthSuccess {
                identity: "user:alice".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 0);
    }

    #[test]
    fn test_is_enabled() {
        let enabled = AuditLogger::new(AuditConfig::default());
        assert!(enabled.is_enabled());

        let disabled = AuditLogger::new(AuditConfig::default().disabled());
        assert!(!disabled.is_enabled());
    }

    #[test]
    fn test_config_accessor() {
        let config = AuditConfig::default().with_query_logging();
        let logger = AuditLogger::new(config);

        assert!(logger.config().log_queries);
    }

    #[test]
    fn test_audit_config_default() {
        let config = AuditConfig::default();

        assert!(config.enabled);
        assert!(config.log_success);
        assert!(config.log_failure);
        assert!(!config.log_queries);
        assert!(config.log_blob_ops);
        assert!(config.log_vector_ops);
        assert_eq!(config.max_entries, 100_000);
    }

    #[test]
    fn test_vector_upsert_event() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::VectorUpsert {
                identity: Some("user:alice".to_string()),
                collection: "embeddings".to_string(),
                count: 10,
            },
            None,
        );

        assert_eq!(logger.count(), 1);
        let entries = logger.by_identity("user:alice");
        assert_eq!(entries.len(), 1);
        assert!(matches!(entries[0].event, AuditEvent::VectorUpsert { .. }));
    }

    #[test]
    fn test_vector_query_event() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::VectorQuery {
                identity: Some("user:alice".to_string()),
                collection: "embeddings".to_string(),
                limit: 10,
            },
            None,
        );

        assert_eq!(logger.count(), 1);
        let entries = logger.by_identity("user:alice");
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_vector_delete_event() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::VectorDelete {
                identity: Some("user:alice".to_string()),
                collection: "embeddings".to_string(),
                count: 5,
            },
            None,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_collection_created_event() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::CollectionCreated {
                identity: Some("user:alice".to_string()),
                collection: "new_collection".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_collection_deleted_event() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::CollectionDeleted {
                identity: Some("user:alice".to_string()),
                collection: "old_collection".to_string(),
            },
            None,
        );

        assert_eq!(logger.count(), 1);
    }

    #[test]
    fn test_log_vector_ops_disabled() {
        let logger = AuditLogger::new(AuditConfig::default().without_vector_logging());

        logger.record(
            AuditEvent::VectorUpsert {
                identity: Some("user:alice".to_string()),
                collection: "embeddings".to_string(),
                count: 10,
            },
            None,
        );

        logger.record(
            AuditEvent::CollectionCreated {
                identity: Some("user:alice".to_string()),
                collection: "new_collection".to_string(),
            },
            None,
        );

        // Vector events should not be logged when log_vector_ops is false
        assert_eq!(logger.count(), 0);
    }

    #[test]
    fn test_auth_failure_not_matched_by_identity() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::AuthFailure {
                reason: "invalid key".to_string(),
            },
            None,
        );

        // Auth failures don't have an identity
        let entries = logger.by_identity("user:alice");
        assert!(entries.is_empty());
    }

    #[test]
    fn test_anonymous_operations() {
        let logger = AuditLogger::new(AuditConfig::default());

        logger.record(
            AuditEvent::BlobDownload {
                identity: None,
                artifact_id: "abc123".to_string(),
            },
            None,
        );

        // Anonymous operations don't match any identity
        let entries = logger.by_identity("user:alice");
        assert!(entries.is_empty());

        // But they are still recorded
        assert_eq!(logger.count(), 1);
    }
}