This repository was archived by the owner on Mar 7, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathaudit.go
More file actions
111 lines (99 loc) · 2.5 KB
/
Copy pathaudit.go
File metadata and controls
111 lines (99 loc) · 2.5 KB
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
package agentmesh
import (
"crypto/sha256"
"encoding/hex"
"sync"
"time"
)
// AuditEntry represents a single immutable audit record.
type AuditEntry struct {
Timestamp time.Time `json:"timestamp"`
AgentID string `json:"agent_id"`
Action string `json:"action"`
Decision PolicyDecision `json:"decision"`
Hash string `json:"hash"`
PreviousHash string `json:"previous_hash"`
}
// AuditLogger maintains an append-only hash-chained audit log.
type AuditLogger struct {
mu sync.Mutex
entries []*AuditEntry
}
// NewAuditLogger creates an empty AuditLogger.
func NewAuditLogger() *AuditLogger {
return &AuditLogger{}
}
// Log appends a new entry to the audit chain.
func (al *AuditLogger) Log(agentID, action string, decision PolicyDecision) *AuditEntry {
al.mu.Lock()
defer al.mu.Unlock()
prevHash := ""
if len(al.entries) > 0 {
prevHash = al.entries[len(al.entries)-1].Hash
}
entry := &AuditEntry{
Timestamp: time.Now().UTC(),
AgentID: agentID,
Action: action,
Decision: decision,
PreviousHash: prevHash,
}
entry.Hash = computeHash(entry)
al.entries = append(al.entries, entry)
return entry
}
// Verify checks the integrity of the entire hash chain.
func (al *AuditLogger) Verify() bool {
al.mu.Lock()
defer al.mu.Unlock()
for i, entry := range al.entries {
expected := computeHash(entry)
if entry.Hash != expected {
return false
}
if i == 0 {
if entry.PreviousHash != "" {
return false
}
} else {
if entry.PreviousHash != al.entries[i-1].Hash {
return false
}
}
}
return true
}
// GetEntries returns entries matching the given filter.
func (al *AuditLogger) GetEntries(filter AuditFilter) []*AuditEntry {
al.mu.Lock()
defer al.mu.Unlock()
var result []*AuditEntry
for _, e := range al.entries {
if filter.AgentID != "" && e.AgentID != filter.AgentID {
continue
}
if filter.Action != "" && e.Action != filter.Action {
continue
}
if filter.Decision != nil && e.Decision != *filter.Decision {
continue
}
if filter.StartTime != nil && e.Timestamp.Before(*filter.StartTime) {
continue
}
if filter.EndTime != nil && e.Timestamp.After(*filter.EndTime) {
continue
}
result = append(result, e)
}
return result
}
func computeHash(e *AuditEntry) string {
data := e.Timestamp.Format(time.RFC3339Nano) + "|" +
e.AgentID + "|" +
e.Action + "|" +
string(e.Decision) + "|" +
e.PreviousHash
h := sha256.Sum256([]byte(data))
return hex.EncodeToString(h[:])
}