Skip to content

feat: Implement audit event types and logging infrastructure (#134)#158

Merged
inureyes merged 3 commits intomainfrom
feature/issue-134-audit-infrastructure
Jan 24, 2026
Merged

feat: Implement audit event types and logging infrastructure (#134)#158
inureyes merged 3 commits intomainfrom
feature/issue-134-audit-infrastructure

Conversation

@inureyes
Copy link
Member

Summary

Implements the audit logging infrastructure for bssh-server as specified in #134.

This PR provides:

  • AuditEvent type with comprehensive fields for tracking events
  • EventType enum covering all security and operational events
  • EventResult enum for operation outcomes
  • AuditExporter trait for pluggable export destinations
  • NullExporter for testing and disabled audit scenarios
  • AuditManager with buffering and background async processing

Changes

New Files

  • src/server/audit/mod.rs - Audit manager and configuration
  • src/server/audit/event.rs - Event type definitions
  • src/server/audit/exporter.rs - Exporter trait and NullExporter

Modified Files

  • src/server/mod.rs - Added audit module export
  • Cargo.toml - Added serde feature to chrono, serde_json to dev-dependencies

Implementation Details

AuditEvent

  • Unique event ID using UUID
  • Timestamp with chrono DateTime
  • Comprehensive fields: event_type, session_id, user, client_ip, path, dest_path, bytes, result, details, protocol
  • Builder pattern for constructing events
  • Full serde serialization support

EventType

Covers all audit scenarios:

  • Authentication: AuthSuccess, AuthFailure, AuthRateLimited
  • Sessions: SessionStart, SessionEnd
  • Commands: CommandExecuted, CommandBlocked
  • File operations: FileOpenRead, FileOpenWrite, FileRead, FileWrite, FileClose, FileUploaded, FileDownloaded, FileDeleted, FileRenamed
  • Directory operations: DirectoryCreated, DirectoryDeleted, DirectoryListed
  • Filters: TransferDenied, TransferAllowed
  • Security: IpBlocked, IpUnblocked, SuspiciousActivity

AuditManager

  • Async event processing with background worker
  • Configurable buffering (default: 1000 events, batch size: 100)
  • Periodic flush interval (default: 5 seconds)
  • Multiple exporter support
  • Graceful shutdown with event flush

Test Coverage

All 19 tests passing:

  • ✅ Event creation and builder pattern
  • ✅ Event serialization/deserialization
  • ✅ NullExporter operations (export, batch, flush, close)
  • ✅ AuditManager lifecycle (creation, enabled/disabled, batch processing)
  • ✅ Background worker buffering and flushing

Quality Checks

  • cargo test audit - All 19 tests passing
  • cargo clippy -- -D warnings - No warnings
  • cargo fmt - Code formatted
  • cargo build --lib - Compiles successfully

Related Issues

Closes #134

Part of #123 (bssh-server implementation)
Depends on #124 (shared module structure)

Future Work

This PR provides the foundation for:

Add comprehensive audit logging infrastructure for bssh-server with:

- AuditEvent type with id, timestamp, event_type, session_id, user,
  client_ip, path, bytes, result, details, and protocol fields
- EventType enum covering authentication, session, command, file
  operations, directory operations, filters, and security events
- EventResult enum (Success, Failure, Denied, Error)
- AuditExporter trait with export, export_batch, flush, and close methods
- NullExporter implementation that discards events for testing
- AuditManager managing multiple exporters with buffering and
  background worker for async processing
- Comprehensive unit tests for all components

Files created:
- src/server/audit/mod.rs - Audit manager and configuration
- src/server/audit/event.rs - Event type definitions
- src/server/audit/exporter.rs - Exporter trait and NullExporter

Files modified:
- src/server/mod.rs - Added audit module export
- Cargo.toml - Added serde feature to chrono, serde_json to dev-dependencies

All tests passing (19 tests).
@inureyes inureyes added type:enhancement New feature or request status:review Under review priority:high High priority issue labels Jan 24, 2026
@inureyes
Copy link
Member Author

Security & Performance Review - PR #158

Analysis Summary

  • PR Branch: feature/issue-134-audit-infrastructure
  • Scope: changed-files (audit logging infrastructure)
  • Languages: Rust
  • Total issues: 7
  • Critical: 1 | High: 2 | Medium: 3 | Low: 1

CRITICAL

1. Potential Sensitive Data Leakage via details Field

File: src/server/audit/event.rs (line 62)
Issue: The details: Option<String> field allows arbitrary string content without any sanitization or validation. When used for authentication failures or command execution events, callers might inadvertently include sensitive information like passwords, tokens, or session secrets.

Impact: Audit logs exported to external systems (OTEL, Logstash, File) could expose credentials if developers pass sensitive data in the details field.

Recommendation:

  • Add documentation warnings about not including sensitive data
  • Consider implementing a sanitization method or using a structured details type
  • Add a SensitiveString wrapper with redaction for serialization

HIGH

2. No AuditManager Graceful Shutdown / Drop Implementation

File: src/server/audit/mod.rs
Issue: The AuditManager struct does not implement Drop trait. When the manager is dropped, the background worker task continues running as a detached tokio task. This means:

  • Events in the buffer may be lost on shutdown
  • The sender channel is dropped, causing the receiver to eventually close, but there's no guarantee pending events are flushed
  • No explicit shutdown mechanism is provided

Impact: Audit events could be lost during server shutdown, violating audit completeness requirements.

Recommendation:

  • Add a shutdown() method that signals the worker to flush and exit
  • Consider implementing Drop to trigger graceful shutdown
  • Store the JoinHandle from tokio::spawn to await completion

3. Unbounded Memory Growth Risk in Buffer Clone

File: src/server/audit/mod.rs (line 300)
Issue: flush_buffer clones the entire buffer for each exporter:

if let Err(e) = exporter.export_batch(buffer.clone()).await {

With multiple exporters, this creates N clones of potentially large event batches (up to 100 events by default). Each AuditEvent contains multiple String and PathBuf fields, making clones expensive.

Impact: Under high audit event volume with multiple exporters, memory usage spikes during flush operations.

Recommendation:

  • Use Arc<Vec<AuditEvent>> for batch sharing across exporters
  • Or change the trait to accept &[AuditEvent] instead of Vec<AuditEvent>

MEDIUM

4. Silent Event Loss When Channel is Full

File: src/server/audit/mod.rs (line 245-247)
Issue: When the audit channel is full, events are silently dropped with only a warning log:

if let Err(e) = self.sender.send(event).await {
    tracing::warn!("Failed to send audit event: {}", e);
}

Impact: Under backpressure, audit events are lost without the caller knowing. For compliance-critical deployments, this could be unacceptable.

Recommendation:

  • Add configuration option for backpressure behavior (drop, block, error)
  • Add metrics/counters for dropped events
  • Consider try_send with explicit overflow handling

5. Missing Input Validation for Builder Methods

File: src/server/audit/mod.rs (lines 131-152)
Issue: The configuration builder methods accept any values without validation:

  • buffer_size could be 0 (causing panic on channel creation)
  • batch_size could be 0 (causing infinite loop in worker)
  • flush_interval_secs could be 0 (causing tight loop)

Impact: Invalid configuration could cause panics or resource exhaustion.

Recommendation:

  • Add validation in builder methods (minimum values)
  • Or validate in AuditManager::new() and return error

6. Default Implementation Creates Empty User/Session

File: src/server/audit/event.rs (lines 232-236)
Issue: The Default implementation creates an event with empty user and session_id:

Self::new(EventType::CommandExecuted, String::new(), String::new())

Impact: Default-constructed events in logs would lack attribution, making audit trails incomplete or misleading.

Recommendation:

  • Remove Default implementation, or
  • Use a sentinel value like "<unknown>" instead of empty string
  • Consider making user and session_id non-optional with validation

LOW

7. Unnecessary #[allow(dead_code)] on Unimplemented Exporters

File: src/server/audit/mod.rs (lines 85-103)
Issue: The File, Otel, and Logstash enum variants are marked with #[allow(dead_code)] and fall back to NullExporter. This could lead to silent misconfiguration in production.

Impact: Users configuring file or OTEL export would not receive audit logs but might not notice immediately.

Recommendation:

  • Return an error instead of silently falling back to NullExporter
  • Or use todo!() / unimplemented!() to make it explicit
  • The current warning log is good but could be promoted to error-level

Positive Observations

  1. Good async patterns: Proper use of tokio::select! for concurrent event handling and timer
  2. Thread safety: AuditExporter trait requires Send + Sync
  3. Serialization: Clean serde implementation with snake_case rename
  4. Test coverage: 19 tests covering core functionality
  5. Clippy clean: No warnings from clippy
  6. UUID for event IDs: Good choice for unique, non-sequential identifiers
  7. Builder pattern: Clean ergonomic API for event construction

Summary

This is a solid foundation for audit logging infrastructure. The critical and high-priority issues should be addressed before production use, particularly:

  1. Document and sanitize the details field to prevent credential leakage
  2. Implement proper shutdown handling to ensure audit completeness
  3. Optimize buffer cloning to prevent memory spikes

The medium and low issues can be addressed in follow-up PRs.

- Add Audit Logging Module section to ARCHITECTURE.md with complete
  description of AuditEvent, EventType, EventResult, AuditExporter
  trait, NullExporter, and AuditManager components
- Update server structure in ARCHITECTURE.md to include audit/ module
- Update docs/architecture/README.md to reference audit logging
- Update code organization to show audit/ in server directory
@inureyes
Copy link
Member Author

PR Finalization Report

Project Structure Discovered

  • Project Type: Rust (Cargo workspace)
  • Test Framework: cargo test (unit tests inline with modules, integration tests in tests/)
  • Documentation System: Plain markdown (ARCHITECTURE.md, docs/architecture/)
  • Multi-language Docs: No
  • Lint Tools: cargo fmt, cargo clippy

Checklist

Tests

  • Analyzed existing test structure
  • Verified all 23 audit module tests pass
  • All 974 project tests pass

Documentation

  • ARCHITECTURE.md updated with Audit Logging Module section
  • Server structure updated to include audit/ module
  • docs/architecture/README.md updated with audit logging reference
  • Code organization updated to show audit/ directory

Code Quality

  • cargo fmt --check passes
  • cargo clippy -- -D warnings passes with no warnings
  • All tests pass

Changes Made

  • Added comprehensive documentation for the audit logging infrastructure:
    • AuditEvent type with builder pattern
    • EventType enum covering all security and operational events
    • EventResult enum for operation outcomes
    • AuditExporter trait for pluggable export destinations
    • NullExporter for testing and disabled audit scenarios
    • AuditManager with buffering and async processing
  • Updated server module structure references

Summary

The PR is production-ready with:

  • 23 comprehensive unit tests covering events, exporters, and manager
  • Full rustdoc documentation on all public APIs
  • Security considerations documented in code comments
  • Architecture documentation updated

@inureyes inureyes merged commit 3c90a69 into main Jan 24, 2026
1 of 2 checks passed
@inureyes inureyes deleted the feature/issue-134-audit-infrastructure branch January 24, 2026 04:17
@inureyes inureyes self-assigned this Jan 24, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jan 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority issue status:done Completed type:enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Design and implement audit event types and logging infrastructure

1 participant