Complete RedFlag codebase with two major security audit implementations.
== A-1: Ed25519 Key Rotation Support ==
Server:
- SignCommand sets SignedAt timestamp and KeyID on every signature
- signing_keys database table (migration 020) for multi-key rotation
- InitializePrimaryKey registers active key at startup
- /api/v1/public-keys endpoint for rotation-aware agents
- SigningKeyQueries for key lifecycle management
Agent:
- Key-ID-aware verification via CheckKeyRotation
- FetchAndCacheAllActiveKeys for rotation pre-caching
- Cache metadata with TTL and staleness fallback
- SecurityLogger events for key rotation and command signing
== A-2: Replay Attack Fixes (F-1 through F-7) ==
F-5 CRITICAL - RetryCommand now signs via signAndCreateCommand
F-1 HIGH - v3 format: "{agent_id}:{cmd_id}:{type}:{hash}:{ts}"
F-7 HIGH - Migration 026: expires_at column with partial index
F-6 HIGH - GetPendingCommands/GetStuckCommands filter by expires_at
F-2 HIGH - Agent-side executedIDs dedup map with cleanup
F-4 HIGH - commandMaxAge reduced from 24h to 4h
F-3 CRITICAL - Old-format commands rejected after 48h via CreatedAt
Verification fixes: migration idempotency (ETHOS #4), log format
compliance (ETHOS #1), stale comments updated.
All 24 tests passing. Docker --no-cache build verified.
See docs/ for full audit reports and deviation log (DEV-001 to DEV-019).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
172 lines
4.2 KiB
Go
172 lines
4.2 KiB
Go
package migration
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/Fimeg/RedFlag/aggregator-agent/internal/config"
|
|
)
|
|
|
|
// MigrationState is imported from config package to avoid duplication
|
|
|
|
// StateManager manages migration state persistence
|
|
type StateManager struct {
|
|
configPath string
|
|
}
|
|
|
|
// NewStateManager creates a new state manager
|
|
func NewStateManager(configPath string) *StateManager {
|
|
return &StateManager{
|
|
configPath: configPath,
|
|
}
|
|
}
|
|
|
|
// LoadState loads migration state from config file
|
|
func (sm *StateManager) LoadState() (*config.MigrationState, error) {
|
|
// Load config to get migration state
|
|
cfg, err := sm.loadConfig()
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
// Fresh install - no migration state yet
|
|
return &config.MigrationState{
|
|
LastCompleted: make(map[string]time.Time),
|
|
AgentVersion: "",
|
|
ConfigVersion: "",
|
|
Timestamp: time.Now(),
|
|
Success: false,
|
|
CompletedMigrations: []string{},
|
|
}, nil
|
|
}
|
|
return nil, fmt.Errorf("failed to load config: %w", err)
|
|
}
|
|
|
|
// Check if migration state exists in config
|
|
if cfg.MigrationState == nil {
|
|
return &config.MigrationState{
|
|
LastCompleted: make(map[string]time.Time),
|
|
AgentVersion: cfg.AgentVersion,
|
|
ConfigVersion: cfg.Version,
|
|
Timestamp: time.Now(),
|
|
Success: false,
|
|
CompletedMigrations: []string{},
|
|
}, nil
|
|
}
|
|
|
|
return cfg.MigrationState, nil
|
|
}
|
|
|
|
// SaveState saves migration state to config file
|
|
func (sm *StateManager) SaveState(state *config.MigrationState) error {
|
|
// Load current config
|
|
cfg, err := sm.loadConfig()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to load config for state save: %w", err)
|
|
}
|
|
|
|
// Update migration state
|
|
cfg.MigrationState = state
|
|
state.Timestamp = time.Now()
|
|
|
|
// Save config with updated state
|
|
return sm.saveConfig(cfg)
|
|
}
|
|
|
|
// IsMigrationCompleted checks if a specific migration was completed
|
|
func (sm *StateManager) IsMigrationCompleted(migrationType string) (bool, error) {
|
|
state, err := sm.LoadState()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
// Check completed migrations list
|
|
for _, completed := range state.CompletedMigrations {
|
|
if completed == migrationType {
|
|
return true, nil
|
|
}
|
|
}
|
|
|
|
// Also check legacy last_completed map for backward compatibility
|
|
if timestamp, exists := state.LastCompleted[migrationType]; exists {
|
|
return !timestamp.IsZero(), nil
|
|
}
|
|
|
|
return false, nil
|
|
}
|
|
|
|
// MarkMigrationCompleted marks a migration as completed
|
|
func (sm *StateManager) MarkMigrationCompleted(migrationType string, rollbackPath string, agentVersion string) error {
|
|
state, err := sm.LoadState()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Update completed migrations list
|
|
found := false
|
|
for _, completed := range state.CompletedMigrations {
|
|
if completed == migrationType {
|
|
found = true
|
|
// Update timestamp
|
|
state.LastCompleted[migrationType] = time.Now()
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
state.CompletedMigrations = append(state.CompletedMigrations, migrationType)
|
|
}
|
|
|
|
state.LastCompleted[migrationType] = time.Now()
|
|
state.AgentVersion = agentVersion
|
|
state.Success = true
|
|
if rollbackPath != "" {
|
|
state.RollbackPath = rollbackPath
|
|
}
|
|
|
|
return sm.SaveState(state)
|
|
}
|
|
|
|
// CleanupOldDirectories removes old migration directories after successful migration
|
|
func (sm *StateManager) CleanupOldDirectories() error {
|
|
oldDirs := []string{
|
|
"/etc/aggregator",
|
|
"/var/lib/aggregator",
|
|
}
|
|
|
|
for _, oldDir := range oldDirs {
|
|
if _, err := os.Stat(oldDir); err == nil {
|
|
fmt.Printf("[MIGRATION] Cleaning up old directory: %s\n", oldDir)
|
|
if err := os.RemoveAll(oldDir); err != nil {
|
|
fmt.Printf("[MIGRATION] Warning: Failed to remove old directory %s: %v\n", oldDir, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// loadConfig loads configuration from file
|
|
func (sm *StateManager) loadConfig() (*config.Config, error) {
|
|
data, err := os.ReadFile(sm.configPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var cfg config.Config
|
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &cfg, nil
|
|
}
|
|
|
|
// saveConfig saves configuration to file
|
|
func (sm *StateManager) saveConfig(cfg *config.Config) error {
|
|
data, err := json.MarshalIndent(cfg, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return os.WriteFile(sm.configPath, data, 0644)
|
|
} |