-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.zig
More file actions
350 lines (287 loc) · 10.4 KB
/
Copy pathaudit.zig
File metadata and controls
350 lines (287 loc) · 10.4 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//! Valence Shell - Audit Logging for MAA Framework
//!
//! Implements the Mutually Assured Accountability audit trail.
//! Every filesystem operation is logged with:
//! - Timestamp
//! - Operation type
//! - Path
//! - Result (success/failure with error code)
//! - Proof reference (which Coq theorem guarantees this op)
//!
//! This creates an accountable, auditable record that can be
//! used for GDPR compliance and forensic analysis.
const std = @import("std");
const Allocator = std.mem.Allocator;
const lib = @import("lib.zig");
const PosixError = lib.PosixError;
/// Operation types matching Coq definitions
pub const OperationType = enum {
mkdir,
rmdir,
create_file,
delete_file,
write_file,
read_file,
/// Get the Coq theorem that proves this operation's reversibility
pub fn proofReference(self: OperationType) []const u8 {
return switch (self) {
.mkdir => "mkdir_rmdir_reversible (filesystem_model.v:L45)",
.rmdir => "mkdir_rmdir_reversible (filesystem_model.v:L45)",
.create_file => "create_delete_file_reversible (file_operations.v:L32)",
.delete_file => "create_delete_file_reversible (file_operations.v:L32)",
.write_file => "write_file_reversible (file_content_operations.v:L67)",
.read_file => "read_only_no_mutation (file_content_operations.v:L12)",
};
}
/// Get the inverse operation (for reversibility)
pub fn inverse(self: OperationType) ?OperationType {
return switch (self) {
.mkdir => .rmdir,
.rmdir => .mkdir,
.create_file => .delete_file,
.delete_file => .create_file,
.write_file => .write_file, // self-inverse with old content
.read_file => null, // no inverse needed
};
}
};
/// Operation status
pub const OperationStatus = union(enum) {
pending,
succeeded,
failed: PosixError,
};
/// Single audit log entry
pub const AuditEntry = struct {
/// Unique operation ID
id: u64,
/// Timestamp (nanoseconds since epoch)
timestamp: i128,
/// Type of operation
operation: OperationType,
/// Path operated on
path: []const u8,
/// Result of operation
status: OperationStatus,
/// Reference to proving theorem
proof_ref: []const u8,
/// For reversible ops: the inverse operation ID (if executed)
inverse_id: ?u64,
};
/// Audit log - append-only operation record
pub const AuditLog = struct {
allocator: Allocator,
/// Log entries (append-only for integrity)
entries: std.ArrayList(AuditEntry),
/// Next operation ID
next_id: u64,
/// Optional file backing for persistence
backing_file: ?std.fs.File,
const Self = @This();
/// Create a new audit log
pub fn init(allocator: Allocator, backing_path: ?[]const u8) !Self {
var log = Self{
.allocator = allocator,
.entries = .empty,
.next_id = 1,
.backing_file = null,
};
if (backing_path) |path| {
log.backing_file = try std.fs.createFileAbsolute(path, .{
.truncate = false,
});
// Write header
const header = "# Valence Shell Audit Log\n# Format: ID|TIMESTAMP|OP|PATH|STATUS|PROOF\n";
_ = try log.backing_file.?.write(header);
}
return log;
}
/// Clean up resources
pub fn deinit(self: *Self) void {
if (self.backing_file) |*f| {
f.close();
}
self.entries.deinit(self.allocator);
}
/// Log an operation
pub fn logOperation(
self: *Self,
operation: OperationType,
path: []const u8,
status: OperationStatus,
) void {
const entry = AuditEntry{
.id = self.next_id,
.timestamp = std.time.nanoTimestamp(),
.operation = operation,
.path = path,
.status = status,
.proof_ref = operation.proofReference(),
.inverse_id = null,
};
self.entries.append(self.allocator, entry) catch return;
self.next_id += 1;
// Write to backing file if present
if (self.backing_file) |*f| {
const status_str = switch (status) {
.pending => "PENDING",
.succeeded => "OK",
.failed => |e| @tagName(e),
};
// Format log entry to buffer
var buf: [512]u8 = undefined;
const line = std.fmt.bufPrint(&buf, "{d}|{d}|{s}|{s}|{s}|{s}\n", .{
entry.id,
entry.timestamp,
@tagName(operation),
path,
status_str,
entry.proof_ref,
}) catch return;
_ = f.write(line) catch {};
}
}
/// Get the last operation ID
pub fn getLastOperationId(self: *const Self) u64 {
if (self.next_id > 1) {
return self.next_id - 1;
}
return 0;
}
/// Get entry by ID
pub fn getEntry(self: *const Self, id: u64) ?AuditEntry {
for (self.entries.items) |entry| {
if (entry.id == id) {
return entry;
}
}
return null;
}
/// Link operation to its inverse (for undo tracking)
pub fn linkInverse(self: *Self, original_id: u64, inverse_id: u64) void {
for (self.entries.items, 0..) |entry, i| {
if (entry.id == original_id) {
self.entries.items[i].inverse_id = inverse_id;
return;
}
}
}
/// Get all operations that can be undone (succeeded, has inverse, not yet undone)
pub fn getUndoableOperations(self: *const Self) []const AuditEntry {
var result: std.ArrayList(AuditEntry) = .empty;
for (self.entries.items) |entry| {
if (entry.status == .succeeded and
entry.operation.inverse() != null and
entry.inverse_id == null)
{
result.append(self.allocator, entry) catch continue;
}
}
return result.toOwnedSlice(self.allocator) catch &[_]AuditEntry{};
}
/// Generate human-readable audit report
pub fn generateReport(self: *const Self, writer: anytype) !void {
try writer.print("=== Valence Shell Audit Report ===\n\n", .{});
try writer.print("Total operations: {d}\n\n", .{self.entries.items.len});
for (self.entries.items) |entry| {
const status_str = switch (entry.status) {
.pending => "PENDING",
.succeeded => "OK",
.failed => |e| @tagName(e),
};
try writer.print(
"[{d}] {s} {s} -> {s}\n",
.{ entry.id, @tagName(entry.operation), entry.path, status_str },
);
try writer.print(" Proof: {s}\n", .{entry.proof_ref});
if (entry.inverse_id) |inv_id| {
try writer.print(" Undone by: {d}\n", .{inv_id});
}
}
}
};
/// Structured audit format for external consumption (JSON-compatible)
pub const AuditRecord = struct {
version: []const u8 = "1.0",
operation_id: u64,
timestamp_ns: i128,
operation_type: []const u8,
path: []const u8,
success: bool,
error_code: ?i32,
proof_theorem: []const u8,
proof_file: []const u8,
reversible: bool,
inverse_operation: ?[]const u8,
};
// =========================================================
// Tests
// =========================================================
test "audit_log_basic" {
const allocator = std.testing.allocator;
var log = try AuditLog.init(allocator, null);
defer log.deinit();
log.logOperation(.mkdir, "/test/path", .succeeded);
try std.testing.expect(log.entries.items.len == 1);
try std.testing.expect(log.entries.items[0].operation == .mkdir);
try std.testing.expect(log.entries.items[0].status == .succeeded);
}
test "audit_log_proof_reference" {
try std.testing.expectEqualStrings(
"mkdir_rmdir_reversible (filesystem_model.v:L45)",
OperationType.mkdir.proofReference(),
);
}
test "audit_log_inverse" {
try std.testing.expect(OperationType.mkdir.inverse() == .rmdir);
try std.testing.expect(OperationType.rmdir.inverse() == .mkdir);
try std.testing.expect(OperationType.read_file.inverse() == null);
}
test "audit_log_get_entry" {
const allocator = std.testing.allocator;
var log = try AuditLog.init(allocator, null);
defer log.deinit();
log.logOperation(.mkdir, "/test/path", .succeeded);
log.logOperation(.create_file, "/test/file.txt", .succeeded);
const entry1 = log.getEntry(1);
try std.testing.expect(entry1 != null);
try std.testing.expectEqualStrings(entry1.?.path, "/test/path");
try std.testing.expect(entry1.?.id == 1);
const entry2 = log.getEntry(2);
try std.testing.expect(entry2 != null);
try std.testing.expect(entry2.?.operation == .create_file);
}
test "audit_log_link_inverse" {
const allocator = std.testing.allocator;
var log = try AuditLog.init(allocator, null);
defer log.deinit();
log.logOperation(.mkdir, "/test/dir", .succeeded);
log.logOperation(.rmdir, "/test/dir", .succeeded);
// Link the inverse operation
log.linkInverse(1, 2);
const entry1 = log.getEntry(1);
try std.testing.expect(entry1 != null);
try std.testing.expect(entry1.?.inverse_id == 2);
}
test "audit_log_get_last_operation_id" {
const allocator = std.testing.allocator;
var log = try AuditLog.init(allocator, null);
defer log.deinit();
try std.testing.expect(log.getLastOperationId() == 0);
log.logOperation(.mkdir, "/test", .succeeded);
try std.testing.expect(log.getLastOperationId() == 1);
log.logOperation(.create_file, "/test/file", .succeeded);
try std.testing.expect(log.getLastOperationId() == 2);
}
test "audit_log_operation_failure" {
const allocator = std.testing.allocator;
var log = try AuditLog.init(allocator, null);
defer log.deinit();
log.logOperation(.mkdir, "/test", .succeeded);
log.logOperation(.mkdir, "/test", .{ .failed = .permission_denied });
try std.testing.expect(log.entries.items.len == 2);
try std.testing.expect(log.entries.items[0].status == .succeeded);
try std.testing.expect(log.entries.items[1].status == .failed);
}