// Audit logging module package audit import ( "encoding/json" "fmt" "os" "path/filepath" "sync" "time" "security-connector/common/types" ) // Logger handles audit logging type Logger struct { mu sync.Mutex // Log file handle file *os.File filePath string // In-memory buffer for batch writing buffer []*types.AuditEvent // Flush interval flushInterval time.Duration // Channel for async logging logChan chan *types.AuditEvent // Stop channel stopChan chan struct{} } // NewLogger creates a new audit logger func NewLogger(logDir string) (*Logger, error) { if err := os.MkdirAll(logDir, 0755); err != nil { return nil, fmt.Errorf("failed to create log directory: %w", err) } // Generate log file name with date logFileName := fmt.Sprintf("audit_%s.jsonl", time.Now().Format("2006-01-02")) logFilePath := filepath.Join(logDir, logFileName) file, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return nil, fmt.Errorf("failed to open log file: %w", err) } logger := &Logger{ file: file, filePath: logFilePath, buffer: make([]*types.AuditEvent, 0, 100), flushInterval: 5 * time.Second, logChan: make(chan *types.AuditEvent, 1000), stopChan: make(chan struct{}), } // Start background flusher go logger.backgroundFlusher() return logger, nil } // Log logs an audit event func (l *Logger) Log(event *types.AuditEvent) { // Generate ID and timestamp if not set if event.ID == "" { event.ID = generateEventID() } if event.Timestamp.IsZero() { event.Timestamp = time.Now() } // Send to channel for async processing select { case l.logChan <- event: default: // Buffer full, log directly l.writeEvent(event) } } // writeEvent writes an event to the log file func (l *Logger) writeEvent(event *types.AuditEvent) { l.mu.Lock() defer l.mu.Unlock() data, err := json.Marshal(event) if err != nil { fmt.Fprintf(os.Stderr, "failed to marshal audit event: %v\n", err) return } // Write as JSON line if _, err := l.file.Write(append(data, '\n')); err != nil { fmt.Fprintf(os.Stderr, "failed to write audit event: %v\n", err) return } } // backgroundFlusher periodically flushes the buffer func (l *Logger) backgroundFlusher() { ticker := time.NewTicker(l.flushInterval) defer ticker.Stop() for { select { case event := <-l.logChan: l.writeEvent(event) case <-ticker.C: l.flush() case <-l.stopChan: l.flush() return } } } // flush flushes the buffer to disk func (l *Logger) flush() { l.mu.Lock() defer l.mu.Unlock() // Flush file if l.file != nil { if err := l.file.Sync(); err != nil { fmt.Fprintf(os.Stderr, "failed to sync audit log: %v\n", err) } } } // Close closes the logger func (l *Logger) Close() error { close(l.stopChan) l.mu.Lock() defer l.mu.Unlock() if l.file != nil { return l.file.Close() } return nil } // generateEventID generates a unique event ID func generateEventID() string { return fmt.Sprintf("%s_%d", time.Now().Format("20060102150405"), time.Now().UnixNano()%1000000) } // LogDeviceRegister logs a device registration event func (l *Logger) LogDeviceRegister(deviceID, result, errorCode, ipAddress string) { l.Log(&types.AuditEvent{ EventType: types.AuditDeviceRegister, DeviceID: deviceID, Result: result, ErrorCode: errorCode, IPAddress: ipAddress, }) } // LogDeviceAuth logs a device authentication event func (l *Logger) LogDeviceAuth(deviceID, result, errorCode, ipAddress string) { l.Log(&types.AuditEvent{ EventType: types.AuditDeviceAuth, DeviceID: deviceID, Result: result, ErrorCode: errorCode, IPAddress: ipAddress, }) } // LogKeyUpdate logs a key update event func (l *Logger) LogKeyUpdate(deviceID, keyID string, version int, result, errorCode string) { details, _ := json.Marshal(map[string]interface{}{ "key_id": keyID, "version": version, }) l.Log(&types.AuditEvent{ EventType: types.AuditKeyUpdate, DeviceID: deviceID, Result: result, ErrorCode: errorCode, Details: details, }) } // LogEasytierJoin logs an EasyTier join event func (l *Logger) LogEasytierJoin(deviceID, nodeID, networkID, result, errorCode string) { details, _ := json.Marshal(map[string]interface{}{ "node_id": nodeID, "network_id": networkID, }) l.Log(&types.AuditEvent{ EventType: types.AuditEasytierJoin, DeviceID: deviceID, Result: result, ErrorCode: errorCode, Details: details, }) } // LogK3sJoin logs a k3s join event func (l *Logger) LogK3sJoin(deviceID, nodeName, clusterID, result, errorCode string) { details, _ := json.Marshal(map[string]interface{}{ "node_name": nodeName, "cluster_id": clusterID, }) l.Log(&types.AuditEvent{ EventType: types.AuditK3sJoin, DeviceID: deviceID, Result: result, ErrorCode: errorCode, Details: details, }) } // LogPolicyDeny logs a policy denial event func (l *Logger) LogPolicyDeny(deviceID, subject, action, resource string) { details, _ := json.Marshal(map[string]interface{}{ "subject": subject, "action": action, "resource": resource, }) l.Log(&types.AuditEvent{ EventType: types.AuditPolicyDeny, DeviceID: deviceID, Result: "deny", Details: details, }) }