-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnif.ex
More file actions
316 lines (267 loc) · 9.81 KB
/
Copy pathnif.ex
File metadata and controls
316 lines (267 loc) · 9.81 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
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
defmodule VSH.NIF do
@moduledoc """
NIF bindings to the Zig FFI layer using Zigler.
This module provides direct access to the verified filesystem operations
implemented in Zig with precondition checking derived from Coq proofs.
## Architecture
```
Elixir (VSH.NIF) → Zigler → Zig (valence_ffi) → POSIX syscalls
```
## Verification Status
The Zig layer implements precondition checks matching:
- `mkdir_precondition` from filesystem_model.v
- `rmdir_precondition` from filesystem_model.v
- `create_file_precondition` from file_operations.v
- `delete_file_precondition` from file_operations.v
## Implementation Note
This module uses Zigler to compile Zig code directly into NIFs,
eliminating the need for C wrapper code. The Zig implementation
provides memory safety and direct POSIX access.
"""
use Zig, otp_app: :vsh
~Z"""
// SPDX-License-Identifier: MPL-2.0
// Valence Shell - Zigler NIF implementation
const std = @import("std");
const beam = @import("beam");
// Global filesystem handle
var g_fs: ?*Filesystem = null;
var g_allocator: std.mem.Allocator = undefined;
// Audit log entry
const AuditEntry = struct {
operation: []const u8,
path: []const u8,
result: PosixError,
timestamp: i64,
};
// Simple audit log (ring buffer of last 100 entries)
const AUDIT_LOG_SIZE = 100;
var g_audit_log: [AUDIT_LOG_SIZE]?AuditEntry = [_]?AuditEntry{null} ** AUDIT_LOG_SIZE;
var g_audit_index: usize = 0;
var g_audit_count: usize = 0;
fn recordAudit(operation: []const u8, path: []const u8, result: PosixError) void {
g_audit_log[g_audit_index] = AuditEntry{
.operation = operation,
.path = path,
.result = result,
.timestamp = std.time.timestamp(),
};
g_audit_index = (g_audit_index + 1) % AUDIT_LOG_SIZE;
if (g_audit_count < AUDIT_LOG_SIZE) {
g_audit_count += 1;
}
}
fn getLastAudit() ?AuditEntry {
if (g_audit_count == 0) return null;
const last_index = if (g_audit_index == 0) AUDIT_LOG_SIZE - 1 else g_audit_index - 1;
return g_audit_log[last_index];
}
// POSIX error codes matching Coq's posix_errors.v
const PosixError = enum(i32) {
success = 0,
eexist = 17,
enoent = 2,
eacces = 13,
enotdir = 20,
eisdir = 21,
enotempty = 39,
einval = 22,
pub fn fromError(err: anyerror) PosixError {
return switch (err) {
error.PathAlreadyExists => .eexist,
error.FileNotFound => .enoent,
error.AccessDenied => .eacces,
error.NotDir => .enotdir,
error.IsDir => .eisdir,
error.DirNotEmpty => .enotempty,
else => .einval,
};
}
};
// Filesystem handle with sandboxing
const Filesystem = struct {
root: []const u8,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator, root: []const u8) !*Filesystem {
const fs = try allocator.create(Filesystem);
fs.* = .{
.root = root,
.allocator = allocator,
};
return fs;
}
pub fn deinit(self: *Filesystem) void {
self.allocator.destroy(self);
}
fn resolvePath(self: *const Filesystem, path: []const u8) ?[]const u8 {
const full_path = std.fs.path.join(self.allocator, &[_][]const u8{ self.root, path }) catch return null;
if (std.mem.indexOf(u8, full_path, "..")) |_| {
self.allocator.free(full_path);
return null;
}
return full_path;
}
pub fn mkdir(self: *Filesystem, path: []const u8) PosixError {
const full_path = self.resolvePath(path) orelse return .eacces;
defer self.allocator.free(full_path);
std.fs.makeDirAbsolute(full_path) catch |err| {
return PosixError.fromError(err);
};
return .success;
}
pub fn rmdir(self: *Filesystem, path: []const u8) PosixError {
const full_path = self.resolvePath(path) orelse return .eacces;
defer self.allocator.free(full_path);
std.fs.deleteDirAbsolute(full_path) catch |err| {
return PosixError.fromError(err);
};
return .success;
}
pub fn createFile(self: *Filesystem, path: []const u8) PosixError {
const full_path = self.resolvePath(path) orelse return .eacces;
defer self.allocator.free(full_path);
const file = std.fs.createFileAbsolute(full_path, .{ .exclusive = true }) catch |err| {
return PosixError.fromError(err);
};
file.close();
return .success;
}
pub fn deleteFile(self: *Filesystem, path: []const u8) PosixError {
const full_path = self.resolvePath(path) orelse return .eacces;
defer self.allocator.free(full_path);
std.fs.deleteFileAbsolute(full_path) catch |err| {
return PosixError.fromError(err);
};
return .success;
}
};
fn ensureFs() !*Filesystem {
if (g_fs) |fs| return fs;
g_allocator = beam.allocator;
const sandbox = std.process.getEnvVarOwned(g_allocator, "VSH_SANDBOX") catch |err| {
if (err == error.EnvironmentVariableNotFound) {
return try Filesystem.init(g_allocator, "/tmp/vsh-sandbox");
}
return err;
};
defer g_allocator.free(sandbox);
g_fs = try Filesystem.init(g_allocator, sandbox);
return g_fs.?;
}
fn errorToAtom(err: PosixError) beam.term {
return switch (err) {
.success => beam.make(.{.ok}, .{}),
.eexist => beam.make(.{.eexist}, .{}),
.enoent => beam.make(.{.enoent}, .{}),
.eacces => beam.make(.{.eacces}, .{}),
.enotdir => beam.make(.{.enotdir}, .{}),
.eisdir => beam.make(.{.eisdir}, .{}),
.enotempty => beam.make(.{.enotempty}, .{}),
.einval => beam.make(.{.einval}, .{}),
};
}
// NIF: mkdir/1
pub fn mkdir(path: []const u8) beam.term {
const fs = ensureFs() catch return beam.make(.{.@"error", .init_failed}, .{});
const result = fs.mkdir(path);
recordAudit("mkdir", path, result);
if (result == .success) {
return beam.make(.{.ok}, .{});
}
return beam.make(.{.@"error", errorToAtom(result)}, .{});
}
// NIF: rmdir/1
pub fn rmdir(path: []const u8) beam.term {
const fs = ensureFs() catch return beam.make(.{.@"error", .init_failed}, .{});
const result = fs.rmdir(path);
recordAudit("rmdir", path, result);
if (result == .success) {
return beam.make(.{.ok}, .{});
}
return beam.make(.{.@"error", errorToAtom(result)}, .{});
}
// NIF: create_file/1
pub fn create_file(path: []const u8) beam.term {
const fs = ensureFs() catch return beam.make(.{.@"error", .init_failed}, .{});
const result = fs.createFile(path);
recordAudit("create_file", path, result);
if (result == .success) {
return beam.make(.{.ok}, .{});
}
return beam.make(.{.@"error", errorToAtom(result)}, .{});
}
// NIF: delete_file/1
pub fn delete_file(path: []const u8) beam.term {
const fs = ensureFs() catch return beam.make(.{.@"error", .init_failed}, .{});
const result = fs.deleteFile(path);
recordAudit("delete_file", path, result);
if (result == .success) {
return beam.make(.{.ok}, .{});
}
return beam.make(.{.@"error", errorToAtom(result)}, .{});
}
// NIF: get_last_audit/0
pub fn get_last_audit() beam.term {
const entry = getLastAudit() orelse return beam.make(.{.@"error", .no_entries}, .{});
// Return as {operation, path, result, timestamp}
return beam.make(.{
entry.operation,
entry.path,
errorToAtom(entry.result),
entry.timestamp,
}, .{});
}
"""
@doc """
Create a directory with precondition checking.
Returns:
- `:ok` on success
- `{:error, :eexist}` if path already exists
- `{:error, :enoent}` if parent doesn't exist
- `{:error, :enotdir}` if parent is not a directory
- `{:error, :eacces}` if no write permission
"""
@spec mkdir(String.t()) :: :ok | {:error, atom()}
def mkdir(_path), do: :erlang.nif_error(:not_loaded)
@doc """
Remove an empty directory with precondition checking.
Returns:
- `:ok` on success
- `{:error, :enoent}` if path doesn't exist
- `{:error, :enotdir}` if not a directory
- `{:error, :enotempty}` if directory not empty
- `{:error, :eacces}` if no write permission on parent
"""
@spec rmdir(String.t()) :: :ok | {:error, atom()}
def rmdir(_path), do: :erlang.nif_error(:not_loaded)
@doc """
Create an empty file with precondition checking.
Returns:
- `:ok` on success
- `{:error, :eexist}` if path already exists
- `{:error, :enoent}` if parent doesn't exist
- `{:error, :enotdir}` if parent is not a directory
- `{:error, :eacces}` if no write permission
"""
@spec create_file(String.t()) :: :ok | {:error, atom()}
def create_file(_path), do: :erlang.nif_error(:not_loaded)
@doc """
Delete a file with precondition checking.
Returns:
- `:ok` on success
- `{:error, :enoent}` if path doesn't exist
- `{:error, :eisdir}` if path is a directory
- `{:error, :eacces}` if no write permission on parent
"""
@spec delete_file(String.t()) :: :ok | {:error, atom()}
def delete_file(_path), do: :erlang.nif_error(:not_loaded)
@doc """
Get the last audit log entry.
Returns the most recent operation recorded by the Zig FFI layer,
including the proof reference for MAA compliance.
"""
@spec get_last_audit() :: {:ok, map()} | {:error, :no_entries}
def get_last_audit, do: :erlang.nif_error(:not_loaded)
end