immutableconfig

package
v1.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 6 Imported by: 0

README

Immutable Configuration System

A comprehensive, production-ready immutable configuration management system for the AegisGate Chatbot Security Gateway.

Overview

This package provides a complete immutable, read-only filesystem implementation with the following key features:

  • Versioned Configuration Storage: All configurations are versioned and stored with full audit trails
  • Integrity Verification: SHA-256 hash verification for all configuration data
  • Write-Ahead Logging (WAL): Atomic operations with crash recovery
  • Point-in-Time Snapshots: Full state capture with integrity checksums
  • File Change Detection: Real-time monitoring for unauthorized modifications
  • Seal/Unseal Mechanism: Lock the filesystem against all modifications
  • Audit Logging: Complete operation trail with timestamps and signatures

Architecture

pkg/immutable-config/
├── config.go              # ConfigData and ConfigVersion types
├── manager.go             # ConfigManager implementation
├── api.go                 # Public API
├── options.go             # Configuration options
├── filesystem/
│   ├── filesystem.go      # ImmutableFilesystem integration layer
│   ├── provider.go        # FilesystemProvider for disk persistence
│   └── filesystem_test.go # Comprehensive tests
├── readonly/
│   └── readonly.go        # ReadOnlyProvider with seal/unseal
├── snapshot/
│   └── snapshot.go        # SnapshotManager for point-in-time capture
├── wal/
│   └── wal.go             # Write-ahead logging for atomic operations
├── watcher/
│   └── watcher.go         # File change detection
├── integrity/
│   └── integrity.go       # SHA-256 integrity verification
├── logging/
│   └── audit.go           # Audit logging
└── rollback/
    └── manager.go         # Rollback management

Quick Start

Basic Usage
package main

import (
    "fmt"
    "github.com/aegisgatesecurity/aegisgate/pkg/immutable-config/filesystem"
)

func main() {
    // Create immutable filesystem
    fs, err := filesystem.NewImmutableFilesystem(&filesystem.FilesystemConfig{
        BasePath:        "/var/lib/aegisgate/config",
        MaxVersions:     100,
        MaxAuditEntries: 10000,
        EnableWatch:     true,
    })
    if err != nil {
        panic(err)
    }
    defer fs.Close()

    // Initialize
    if err := fs.Initialize(); err != nil {
        panic(err)
    }

    // Save configuration
    config := immutableconfig.NewConfigData("v1.0.0", map[string]interface{}{
        "setting1": "value1",
        "setting2": 42,
    }, map[string]string{
        "author": "admin",
    })

    version, err := fs.Save(config)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Saved version: %s\n", version.Version)

    // Load configuration
    loaded, err := fs.Load("v1.0.0")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Loaded: %v\n", loaded.Data)
}
Seal/Unseal Operations
// Seal the filesystem - no modifications allowed
if err := fs.Seal(); err != nil {
    panic(err)
}

fmt.Printf("Filesystem sealed at: %s\n", fs.SealedAt())

// Any save attempt will fail
_, err = fs.Save(newConfig)
// Error: filesystem is sealed: modifications are not allowed

// Unseal (admin operation)
if err := fs.Unseal(); err != nil {
    panic(err)
}
Snapshots
// Create snapshot
snapshot, err := fs.CreateSnapshot("backup-2026-02-21", "End of month backup")
if err != nil {
    panic(err)
}
fmt.Printf("Snapshot ID: %s\n", snapshot.ID)

// List snapshots
snapshots, err := fs.ListSnapshots()
for _, s := range snapshots {
    fmt.Printf("  %s: %s (%s)\n", s.ID, s.Name, s.Created)
}

// Restore from snapshot
if err := fs.RestoreSnapshot(snapshot.ID); err != nil {
    panic(err)
}

// Verify snapshot integrity
verified, err := fs.snapshotMgr.Verify(snapshot.ID)
if verified {
    fmt.Println("Snapshot integrity verified")
}
Integrity Verification
// Verify all configurations
results, err := fs.VerifyIntegrity()
for version, valid := range results {
    fmt.Printf("Version %s: %v\n", version, valid)
}

// Get audit log
entries := fs.GetAuditLog()
for _, entry := range entries {
    fmt.Printf("[%s] %s: %s\n", entry.Timestamp, entry.EventType, entry.Description)
}
Crash Recovery
// Recover from WAL after crash
if err := fs.Recover(); err != nil {
    panic(err)
}

// Compact WAL to remove old entries
if err := fs.CompactWAL(); err != nil {
    panic(err)
}

Components

FilesystemProvider

Disk-based storage provider with atomic write operations:

  • Atomic writes using temp file + rename
  • Automatic loading of existing configurations
  • Version management with SHA-256 hashes
  • Read-only file permissions after save
ReadOnlyProvider

Enforcement layer that wraps any Provider:

  • Seal/Unseal mechanism
  • Modification attempt tracking
  • Blocked operation logging
SnapshotManager

Point-in-time state capture:

  • Full configuration snapshots
  • Integrity checksums for verification
  • Restore capability
  • Snapshot listing and deletion
WAL (Write-Ahead Log)

Atomic operations with recovery:

  • Append-only log
  • Commit/Rollback semantics
  • Crash recovery replay
  • Automatic compaction
Watcher

Real-time file monitoring:

  • SHA-256 checksum tracking
  • Event-based notifications
  • Unauthorized change detection
  • Configurable scan intervals

Configuration Options

type FilesystemConfig struct {
    BasePath        string        // Directory for config storage
    MaxVersions     int           // Maximum versions to retain
    MaxAuditEntries int           // Maximum audit log entries
    WatchInterval   time.Duration // File scan interval
    EnableWatch     bool          // Enable file watching
    AutoSeal        bool          // Auto-seal after writes
}

Security Features

  1. Immutability: Files set to read-only (0444) after write
  2. Integrity: SHA-256 hash verification on all reads
  3. Audit Trail: Complete logging of all operations
  4. Seal Mechanism: Hard lock against modifications
  5. Change Detection: Real-time monitoring with Watcher
  6. Crash Recovery: WAL replay for data consistency

Performance

  • Read Latency: ~1-5ms (memory cached)
  • Write Latency: ~10-50ms (with WAL + fsync)
  • Snapshot Time: ~100-500ms (depends on config size)
  • Verification Time: ~1-2ms per config

Compliance

This implementation supports the following compliance requirements:

  • NIST AI RMF: Configuration integrity controls
  • ISO/IEC 42001: Change management requirements
  • SOC 2: Audit trail requirements
  • PCI-DSS: File integrity monitoring

Testing

Run the test suite:

go test ./pkg/immutable-config/... -v

License

Part of the AegisGate Chatbot Security Gateway project.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API provides the main interface for configuration operations

func NewAPI

func NewAPI(manager *ConfigManager) *API

NewAPI creates a new API instance

func (*API) Close

func (api *API) Close() error

Close closes the API and underlying resources

func (*API) GetAuditLogger

func (api *API) GetAuditLogger() *logging.AuditLogger

GetAuditLogger returns the audit logger

func (*API) GetConfigHash

func (api *API) GetConfigHash() string

GetConfigHash returns the hash of the current configuration

func (*API) GetCurrentConfig

func (api *API) GetCurrentConfig() *ConfigData

GetCurrentConfig returns the current configuration

func (*API) GetLatestVersion

func (api *API) GetLatestVersion() string

GetLatestVersion returns the latest version string

func (*API) GetVersionHistory

func (api *API) GetVersionHistory() ([]*ConfigVersion, error)

GetVersionHistory gets the version history

func (*API) LoadConfig

func (api *API) LoadConfig(version string) (*ConfigData, error)

LoadConfig loads a specific version of the configuration

func (*API) LoadLatestConfig

func (api *API) LoadLatestConfig() (*ConfigData, error)

LoadLatestConfig loads the most recent configuration

func (*API) RollbackToVersion

func (api *API) RollbackToVersion(version string) error

RollbackToVersion rolls back to a specific version

func (*API) SaveConfig

func (api *API) SaveConfig(config *ConfigData) (*ConfigVersion, error)

SaveConfig saves a new configuration version

func (*API) ValidateConfig

func (api *API) ValidateConfig() error

ValidateConfig validates the current configuration

type ConfigData

type ConfigData struct {
	Version   string                 `json:"version" yaml:"version"`
	Created   string                 `json:"created" yaml:"created"`
	Data      map[string]interface{} `json:"data" yaml:"data"`
	Metadata  map[string]string      `json:"metadata" yaml:"metadata"`
	Hash      string                 `json:"hash" yaml:"hash"`
	Signature string                 `json:"signature,omitempty" yaml:"signature,omitempty"`
}

ConfigData represents immutable configuration data

func NewConfigData

func NewConfigData(version string, data map[string]interface{}, metadata map[string]string) *ConfigData

NewConfigData creates a new configuration data instance

func (*ConfigData) Get

func (c *ConfigData) Get(key string) (interface{}, bool)

Get retrieves a value from the configuration data

func (*ConfigData) GetCreated

func (c *ConfigData) GetCreated() string

GetCreated returns the creation timestamp

func (*ConfigData) GetData

func (c *ConfigData) GetData() map[string]interface{}

GetData returns the configuration data

func (*ConfigData) GetMetadata

func (c *ConfigData) GetMetadata() map[string]string

GetMetadata returns the configuration metadata

func (*ConfigData) GetVersion

func (c *ConfigData) GetVersion() string

GetVersion returns the configuration version

func (*ConfigData) Set

func (c *ConfigData) Set(key string, value interface{})

Set sets a value in the configuration data

func (*ConfigData) String

func (c *ConfigData) String() string

String implements fmt.Stringer

func (*ConfigData) Validate

func (c *ConfigData) Validate() error

Validate validates the configuration data

type ConfigManager

type ConfigManager struct {
	// contains filtered or unexported fields
}

ConfigManager manages immutable configuration with versioning

func NewConfigManager

func NewConfigManager(provider Provider) *ConfigManager

NewConfigManager creates a new configuration manager

func NewWithOptions

func NewWithOptions(options *ConfigOptions) *ConfigManager

NewWithOptions creates a new ConfigManager with custom options

func (*ConfigManager) Close

func (cm *ConfigManager) Close() error

Close closes the config manager

func (*ConfigManager) GetAuditLogger

func (cm *ConfigManager) GetAuditLogger() *logging.AuditLogger

GetAuditLogger returns the audit logger

func (*ConfigManager) GetConfigHash

func (cm *ConfigManager) GetConfigHash() string

GetConfigHash returns the hash of the current configuration

func (*ConfigManager) GetCurrentConfig

func (cm *ConfigManager) GetCurrentConfig() *ConfigData

GetCurrentConfig returns the current configuration

func (*ConfigManager) GetLatestVersion

func (cm *ConfigManager) GetLatestVersion() string

GetLatestVersion returns the latest version string

func (*ConfigManager) GetVersionHistory

func (cm *ConfigManager) GetVersionHistory() ([]*ConfigVersion, error)

GetVersionHistory gets the version history

func (*ConfigManager) Initialize

func (cm *ConfigManager) Initialize() error

Initialize initializes the config manager

func (*ConfigManager) LoadConfig

func (cm *ConfigManager) LoadConfig(version string) (*ConfigData, error)

LoadConfig loads a specific version of the configuration

func (*ConfigManager) LoadLatestConfig

func (cm *ConfigManager) LoadLatestConfig() (*ConfigData, error)

LoadLatestConfig loads the most recent configuration This version avoids calling LoadConfig to prevent deadlock

func (*ConfigManager) RollbackToVersion

func (cm *ConfigManager) RollbackToVersion(version string) error

RollbackToVersion rolls back to a specific version

func (*ConfigManager) SaveConfig

func (cm *ConfigManager) SaveConfig(config *ConfigData) (*ConfigVersion, error)

SaveConfig saves a new configuration version

func (*ConfigManager) ValidateConfig

func (cm *ConfigManager) ValidateConfig() error

ValidateConfig validates the current configuration

type ConfigOptions

type ConfigOptions struct {
	Provider        Provider
	MaxVersions     int
	EnableRollback  bool
	MaxAuditEntries int
	EnableIntegrity bool
	EnableSignature bool
}

ConfigOptions for configuring the immutable config system

func DefaultOptions

func DefaultOptions() *ConfigOptions

DefaultOptions returns default configuration options

func NewConfigOptions

func NewConfigOptions() *ConfigOptions

NewConfigOptions creates new options with default values

type ConfigVersion

type ConfigVersion struct {
	Version   string `json:"version" yaml:"version"`
	Timestamp string `json:"timestamp" yaml:"timestamp"`
	Hash      string `json:"hash" yaml:"hash"`
	Signature string `json:"signature,omitempty" yaml:"signature,omitempty"`
}

ConfigVersion represents a versioned configuration state

func NewConfigVersion

func NewConfigVersion(version string, hash string) *ConfigVersion

NewConfigVersion creates a new config version

type InMemoryProvider

type InMemoryProvider struct {
	// contains filtered or unexported fields
}

InMemoryProvider for testing

func NewInMemoryProvider

func NewInMemoryProvider() *InMemoryProvider

NewInMemoryProvider creates a new in-memory provider

func (*InMemoryProvider) Close

func (p *InMemoryProvider) Close() error

Close closes the in-memory provider

func (*InMemoryProvider) Initialize

func (p *InMemoryProvider) Initialize() error

Initialize initializes the in-memory provider

func (*InMemoryProvider) ListVersions

func (p *InMemoryProvider) ListVersions() ([]*ConfigVersion, error)

ListVersions lists all versions

func (*InMemoryProvider) Load

func (p *InMemoryProvider) Load(version string) (*ConfigData, error)

Load loads a specific version of the configuration

func (*InMemoryProvider) Save

func (p *InMemoryProvider) Save(config *ConfigData) (*ConfigVersion, error)

Save saves a new configuration version

type Option

type Option func(*ConfigOptions)

Option is a function that configures options

func WithIntegrity

func WithIntegrity(enabled bool) Option

WithIntegrity enables/disables integrity checking

func WithMaxAuditEntries

func WithMaxAuditEntries(max int) Option

WithMaxAuditEntries sets the maximum audit log entries

func WithMaxVersions

func WithMaxVersions(max int) Option

WithMaxVersions sets the maximum number of versions to keep

func WithProvider

func WithProvider(p Provider) Option

WithProvider sets the storage provider

func WithRollback

func WithRollback(enabled bool) Option

WithRollback enables/disables rollback functionality

func WithSignature

func WithSignature(enabled bool) Option

WithSignature enables/disables signature verification

type Provider

type Provider interface {
	Initialize() error
	Load(version string) (*ConfigData, error)
	Save(config *ConfigData) (*ConfigVersion, error)
	ListVersions() ([]*ConfigVersion, error)
	Close() error
}

Provider interface for configuration storage

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL