Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/dev/monitor.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Date: 2026-11-27. State: first form. The monitor shows what the programs of the

The monitor shows the audit log of the project: `audit.md` has its schema, its folder, and its commands. The dockyard window writes the records with `src/audit/audit.tcl`. The monitor reads the last 10,000 records at its start, then the new records every 250 ms (`dockyard::audit query -after SEQ`).

The rules file (`dockyard-HASH.rules`) is next to the control socket of the project (`$XDG_RUNTIME_DIR`, or `/tmp` with the user ID), with mode 0600. `dockyard::monitor rule` and `dockyard::monitor rules` (`src/sandbox/monitor.zig`) write and read it.
The rules file (`dockyard-HASH.rules`) is next to the control socket of the project (`$XDG_RUNTIME_DIR`, or the private folder of `host.controlPath`), with mode 0600. `dockyard::monitor rule` and `dockyard::monitor rules` (`src/sandbox/monitor.zig`) write and read it.

## The front ends

Expand Down
2 changes: 1 addition & 1 deletion docs/monitor.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ The log is the audit log of the project. It is outside the project folder, becau
dockyard --audit-export ~/dockyard/my-app > audit.jsonl
```

Your rules are in `dockyard-HASH.rules` next to the control socket of the project (`$XDG_RUNTIME_DIR`, or `/tmp` with your user ID in its name). The dockyard window reads the rules every 250 ms and gives the proxy its new allow list.
Your rules are in `dockyard-HASH.rules` next to the control socket of the project (`$XDG_RUNTIME_DIR`, or the private folder `~/.local/state/dockyard/run` on Linux and `~/Library/Caches/dockyard/run` on macOS). The dockyard window reads the rules every 250 ms and gives the proxy its new allow list.

## Not in the monitor yet

Expand Down
2 changes: 1 addition & 1 deletion docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ The capabilities that a project declares, and the compute limit and the memory l

## The MCP bridge

The MCP server (`dockyard --mcp`) talks to the preview child over a Unix socket. The socket is in `$XDG_RUNTIME_DIR`, or in `/tmp` with your user id in its name. The `eval` tool runs Tcl in the preview interpreter, with the capabilities of the preview only.
The MCP server (`dockyard --mcp`) talks to the preview child over a Unix socket. The socket is in `$XDG_RUNTIME_DIR` when that folder belongs to you and has mode 0700. Else it is in a folder of mode 0700 that dockyard makes and checks: `~/.local/state/dockyard/run` (or `$XDG_STATE_HOME/dockyard/run`) on Linux, and `~/Library/Caches/dockyard/run` on macOS. A client connects only to a socket file that belongs to you and is not a link. The `eval` tool runs Tcl in the preview interpreter, with the capabilities of the preview only.

`.mcp.json` has the full path of the dockyard program. The agent program asks you to approve this server before it uses it.

Expand Down
88 changes: 71 additions & 17 deletions src/app/host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const std = @import("std");
const builtin = @import("builtin");
const ztcl = @import("ztcl");
const control = @import("control.zig");
const sock = @import("../sandbox/sock.zig");

const on_win = builtin.os.tag == .windows;
const delimiter: u8 = if (on_win) ';' else ':';
Expand Down Expand Up @@ -64,21 +65,67 @@ pub const Setup = struct {
dark: bool = false,
};

/// The path of the control socket of the preview of `project`, from
/// the folder `runtime` (`XDG_RUNTIME_DIR`). With no folder, the path
/// is in `/tmp` with the user ID in its name, and on Windows in the temp
/// folder of the user.
pub fn controlPath(a: std.mem.Allocator, runtime: ?[]const u8, project: []const u8) ![:0]const u8 {
/// The path of the control socket of the preview of `project`, in the
/// folder `runtime` (`XDG_RUNTIME_DIR`) when it is a private folder of
/// the user. Else the path is in the private folder `dockyard/run`
/// (mode 0700) below `XDG_STATE_HOME` or `~/.local/state` on Linux, and
/// below `~/Library/Caches` on macOS. dockyard makes that folder and
/// checks its owner and mode (`sock.privateDir`). On Windows the path is
/// in the temp folder of the user.
/// The folders of the environment that `controlPath` reads.
pub const Dirs = struct {
runtime: ?[]const u8 = null,
state: ?[]const u8 = null,
home: ?[]const u8 = null,

/// The folders of an environment list (`NAME=value`).
pub fn fromList(env: []const [:0]const u8) Dirs {
var d: Dirs = .{};
for (env) |e| {
if (std.mem.startsWith(u8, e, "XDG_RUNTIME_DIR=")) d.runtime = e["XDG_RUNTIME_DIR=".len..];
if (std.mem.startsWith(u8, e, "XDG_STATE_HOME=")) d.state = e["XDG_STATE_HOME=".len..];
if (std.mem.startsWith(u8, e, "HOME=")) d.home = e["HOME=".len..];
}
return d;
}

/// The folders of an environment map.
pub fn fromMap(m: *const std.process.Environ.Map) Dirs {
return .{ .runtime = m.get("XDG_RUNTIME_DIR"), .state = m.get("XDG_STATE_HOME"), .home = m.get("HOME") };
}
};

pub fn controlPath(a: std.mem.Allocator, dirs: Dirs, project: []const u8) ![:0]const u8 {
const runtime = dirs.runtime;
const hash = std.hash.Wyhash.hash(0, project);
if (runtime) |r| if (r.len > 0) return std.fmt.allocPrintSentinel(a, "{s}/dockyard-{x:0>16}.sock", .{ r, hash }, 0);
if (runtime) |r| if (!on_win and r.len > 0 and r[0] == '/') {
const rz = try a.dupeSentinel(u8, r, 0);
if (sock.statNoFollow(rz)) |st| if (st.uid == sock.uid() and st.mode & 0o077 == 0)
return std.fmt.allocPrintSentinel(a, "{s}/dockyard-{x:0>16}.sock", .{ r, hash }, 0);
};
if (comptime on_win) {
var buf: [260]u8 = undefined;
const n = GetTempPathA(buf.len, &buf);
if (n == 0 or n >= buf.len) return error.NoTempFolder;
// The folder ends with `\`.
return std.fmt.allocPrintSentinel(a, "{s}dockyard-{x:0>16}.sock", .{ buf[0..n], hash }, 0);
}
return std.fmt.allocPrintSentinel(a, "/tmp/dockyard-{d}-{x:0>16}.sock", .{ std.c.getuid(), hash }, 0);
const dir = try runDir(a, dirs);
try sock.privateDir(dir);
return std.fmt.allocPrintSentinel(a, "{s}/dockyard-{x:0>16}.sock", .{ dir, hash }, 0);
}

/// The private folder of the sockets when there is no runtime folder.
fn runDir(a: std.mem.Allocator, dirs: Dirs) ![:0]const u8 {
const home = dirs.home orelse "";
if (comptime builtin.os.tag.isDarwin()) {
if (home.len == 0) return error.NoHome;
return std.fmt.allocPrintSentinel(a, "{s}/Library/Caches/dockyard/run", .{home}, 0);
}
if (dirs.state) |state| if (state.len > 0 and state[0] == '/')
return std.fmt.allocPrintSentinel(a, "{s}/dockyard/run", .{state}, 0);
if (home.len == 0) return error.NoHome;
return std.fmt.allocPrintSentinel(a, "{s}/.local/state/dockyard/run", .{home}, 0);
}

/// The `PATH` with only its full paths, in memory of `a`.
Expand Down Expand Up @@ -128,12 +175,8 @@ pub fn allow(it: *ztcl.Interp, project: []const u8, env: []const [:0]const u8) !
it.exec_host = .{ .allow = null, .timeout_ms = 0, .env = env };
try it.register("::dockyard::findProgram", cmdFindProgram);
// The preview child gets the same environment, so the same socket path.
var runtime: ?[]const u8 = null;
for (env) |e| if (std.mem.startsWith(u8, e, "XDG_RUNTIME_DIR=")) {
runtime = e["XDG_RUNTIME_DIR=".len..];
};
var fba = std.heap.FixedBufferAllocator.init(&preview_path_buf);
preview_path = try controlPath(fba.allocator(), runtime, project);
preview_path = try controlPath(fba.allocator(), Dirs.fromList(env), project);
try it.register("dockyard::preview::call", cmdPreviewCall);
}

Expand Down Expand Up @@ -265,13 +308,24 @@ test "the control path depends on the project folder" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const one = try controlPath(a, "/run/user/7", "/home/u/app");
try std.testing.expect(std.mem.startsWith(u8, one, "/run/user/7/dockyard-"));
try std.testing.expect(!std.mem.eql(u8, one, try controlPath(a, "/run/user/7", "/home/u/other")));
const plain = try controlPath(a, null, "/x");
// A runtime folder that is not a private folder of the user is not used.
// Windows has no libc here, and its control path does not use the
// home folder: the folder of the test is a name in the current folder.
const home = if (comptime on_win) "dockyard-test-home" else try std.fmt.allocPrint(a, "{s}/dockyard-test-home-{d}", .{
if (std.c.getenv("TMPDIR")) |t| std.mem.sliceTo(t, 0) else "/tmp",
std.c.getpid(),
});
defer std.Io.Dir.cwd().deleteTree(std.testing.io, home) catch {};
const one = try controlPath(a, .{ .runtime = "/tmp", .home = home }, "/home/u/app");
// The socket is not in /tmp itself. The home folder of the test is
// below /tmp, so a check of the start of the path is not enough.
try std.testing.expect(!std.mem.eql(u8, std.fs.path.dirname(one).?, "/tmp"));
if (comptime !on_win) try std.testing.expect(std.mem.startsWith(u8, one, home));
try std.testing.expect(!std.mem.eql(u8, one, try controlPath(a, .{ .runtime = "/tmp", .home = home }, "/home/u/other")));
const plain = try controlPath(a, .{ .home = home }, "/x");
if (comptime on_win) {
try std.testing.expect(isFull(plain) and std.mem.indexOf(u8, plain, "\\dockyard-") != null);
} else try std.testing.expect(std.mem.startsWith(u8, plain, "/tmp/dockyard-"));
} else try std.testing.expect(std.mem.indexOf(u8, plain, "/dockyard/run/dockyard-") != null);
}

test "the PATH of Windows keeps only full paths" {
Expand Down
7 changes: 3 additions & 4 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ pub fn main(init: std.process.Init) !void {
else
init.environ_map.get("PWD") orelse "/";
const folder = if (project) |p| try std.fs.path.resolve(arena, &.{ cwd, p }) else cwd;
const runtime = init.environ_map.get("XDG_RUNTIME_DIR");
const audit_dir = audit.dirFor(arena, init.environ_map, folder) catch "";
if (audit_export) {
// The exit code is 1 when the chain is broken.
Expand All @@ -196,7 +195,7 @@ pub fn main(init: std.process.Init) !void {
}
if (serve_mcp) {
crash.install(arena, io, init.environ_map, null);
const sock = try host.controlPath(arena, runtime, folder);
const sock = try host.controlPath(arena, host.Dirs.fromMap(init.environ_map), folder);
try mcp.main(init.gpa, io, sock);
return;
}
Expand Down Expand Up @@ -238,7 +237,7 @@ pub fn main(init: std.process.Init) !void {
try guest_release.setVars(&it, release);
it.vm_host.image_keys = guest_release.keys;
it.vm_host.image_store = guest_release.store(arena, init.environ_map);
try monitor.register(&it, try host.controlPath(arena, runtime, folder));
try monitor.register(&it, try host.controlPath(arena, host.Dirs.fromMap(init.environ_map), folder));
// Windows has no audit log yet: the writer uses POSIX files.
if (comptime @import("builtin").os.tag != .windows) if (audit_dir.len > 0) try audit.register(&it, audit_dir);
try it.setVar("::dockyard::tui", .{ .str = if (tui) "1" else "0" });
Expand Down Expand Up @@ -284,7 +283,7 @@ pub fn main(init: std.process.Init) !void {

var ctl: ?*control.Control = null;
if (run_path) |f| {
const sock = try host.controlPath(arena, runtime, std.fs.path.dirname(f) orelse "/");
const sock = try host.controlPath(arena, host.Dirs.fromMap(init.environ_map), std.fs.path.dirname(f) orelse "/");
const err_sink: ztcl.Output = .{ .ctx = err, .write = write };
ctl = control.start(arena, app, sock, err_sink, exitNow) catch |e| blk: {
// The stderr of the child is buffered: the line goes out now, so
Expand Down
89 changes: 89 additions & 0 deletions src/sandbox/sock.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
//! `recv` and `send` for the data, and `closesocket`. Winsock starts at
//! the first call. A Windows socket file has no mode: it is in the temp
//! folder of the user, which other users cannot open.
//!
//! On Linux and macOS, `connect` checks that the socket file belongs to
//! the user and is not a link, so a socket that another user made at the
//! path gets no request. `privateDir` makes and checks a folder of mode
//! 0700 for the sockets.

const std = @import("std");
const builtin = @import("builtin");
Expand Down Expand Up @@ -63,6 +68,10 @@ pub fn bindListen(fd: Fd, path: [:0]const u8) !void {

pub fn connect(fd: Fd, path: [:0]const u8) !void {
const addr = try addrOf(path);
if (comptime !on_win) {
const st = statNoFollow(path) orelse return error.ConnectionRefused;
if (st.mode & s_ifmt != s_ifsock or st.uid != uid()) return error.NotOwner;
}
const rc = if (comptime on_win) win.connect(fd, &addr, @sizeOf(Addr)) else std.c.connect(fd, @ptrCast(&addr), @sizeOf(Addr));
if (rc != 0) return error.ConnectionRefused;
}
Expand Down Expand Up @@ -183,3 +192,83 @@ test "a socket at a path answers a connection" {
const n = read(conn, &got);
try std.testing.expectEqualStrings("ping", got[0..@intCast(n)]);
}

const s_ifmt: u32 = 0o170000;
const s_ifdir: u32 = 0o040000;
const s_ifsock: u32 = 0o140000;

pub const Owner = struct { uid: u32, mode: u32 };

/// The user ID of the process (0 on Windows, which has no user IDs here).
pub fn uid() u32 {
if (comptime on_win) return 0;
return @intCast(std.c.getuid());
}

/// The owner and the mode of `path`, without following a link at its
/// end, or null when it does not exist.
pub fn statNoFollow(path: [:0]const u8) ?Owner {
if (comptime on_win) return null;
if (comptime builtin.os.tag == .linux) {
const linux = std.os.linux;
var sx: linux.Statx = undefined;
const rc = linux.statx(linux.AT.FDCWD, path.ptr, linux.AT.SYMLINK_NOFOLLOW, .{ .TYPE = true, .MODE = true, .UID = true }, &sx);
if (linux.errno(rc) != .SUCCESS) return null;
return .{ .uid = sx.uid, .mode = sx.mode };
}
var st: std.c.Stat = undefined;
if (std.c.fstatat(std.c.AT.FDCWD, path.ptr, &st, std.c.AT.SYMLINK_NOFOLLOW) != 0) return null;
return .{ .uid = @intCast(st.uid), .mode = @intCast(st.mode) };
}

/// Makes the folder `path` and each folder above it that does not exist
/// (mode 0700), then checks the last one: a folder, not a link, of the
/// user, with no rights for others. A folder of the user with more rights
/// gets mode 0700.
pub fn privateDir(path: [:0]const u8) !void {
if (comptime on_win) return;
var buf: [1024]u8 = undefined;
if (path.len >= buf.len or path.len == 0 or path[0] != '/') return error.BadPath;
var i: usize = 1;
while (i <= path.len) : (i += 1) {
if (i < path.len and path[i] != '/') continue;
@memcpy(buf[0..i], path[0..i]);
buf[i] = 0;
_ = std.c.mkdir(@ptrCast(&buf), 0o700);
}
const st = statNoFollow(path) orelse return error.NoFolder;
if (st.mode & s_ifmt != s_ifdir or st.uid != uid()) return error.NotOwner;
if (st.mode & 0o077 != 0) {
if (std.c.chmod(path.ptr, 0o700) != 0) return error.NotOwner;
}
}

test "a socket folder is private and a socket of another owner gets no connect" {
if (comptime on_win) return error.SkipZigTest;
var buf: [256]u8 = undefined;
const base = if (std.c.getenv("TMPDIR")) |t| std.mem.sliceTo(t, 0) else "/tmp";
const dir = try std.fmt.bufPrintSentinel(&buf, "{s}/dockyard-test-sockdir-{d}/run", .{ base, std.c.getpid() }, 0);
try privateDir(dir);
try std.testing.expectEqual(@as(u32, 0o700), statNoFollow(dir).?.mode & 0o777);
_ = std.c.chmod(dir.ptr, 0o755);
try privateDir(dir);
try std.testing.expectEqual(@as(u32, 0o700), statNoFollow(dir).?.mode & 0o777);
// A link in the place of the folder is refused.
var lbuf: [256]u8 = undefined;
const link = try std.fmt.bufPrintSentinel(&lbuf, "{s}/dockyard-test-sockdir-{d}/link", .{ base, std.c.getpid() }, 0);
_ = std.c.symlink(dir.ptr, link.ptr);
try std.testing.expectError(error.NotOwner, privateDir(link));
// A plain file at the path of a socket gets no connect.
var fbuf: [256]u8 = undefined;
const file = try std.fmt.bufPrintSentinel(&fbuf, "{s}/f.sock", .{dir}, 0);
const fd = std.c.open(file.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true }, @as(std.c.mode_t, 0o600));
_ = std.c.close(fd);
const s = try open();
defer close(s);
try std.testing.expectError(error.NotOwner, connect(s, file));
_ = std.c.unlink(file.ptr);
_ = std.c.unlink(link.ptr);
_ = std.c.rmdir(dir.ptr);
var pbuf: [256]u8 = undefined;
_ = std.c.rmdir((try std.fmt.bufPrintSentinel(&pbuf, "{s}/dockyard-test-sockdir-{d}", .{ base, std.c.getpid() }, 0)).ptr);
}
16 changes: 12 additions & 4 deletions src/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ const Run = struct {
try std.fmt.allocPrintSentinel(a, "TEMP={s}", .{t}, 0),
try std.fmt.allocPrintSentinel(a, "TMP={s}", .{t}, 0),
});
} else try a.dupe([:0]const u8, &.{ "PATH=" ++ test_path, "HOME=/tmp", "PS1=$ " });
} else try a.dupe([:0]const u8, &.{ "PATH=" ++ test_path, try std.fmt.allocPrintSentinel(a, "HOME={s}.home", .{folder}, 0), "PS1=$ " });
try host.allow(&r.it, folder, env);
// The folder of the ztk programs has the ztk program of the build,
// for the target of this computer: a link, or a copy on Windows,
Expand Down Expand Up @@ -173,7 +173,7 @@ const Run = struct {
fn tool(r: *Run, name: []const u8, args: []const u8) ![]const u8 {
const a = r.arena.allocator();
const folder = r.dir;
const sock = try host.controlPath(a, null, folder);
const sock = try host.controlPath(a, testDirs(a, folder), folder);
const msg = try std.fmt.allocPrint(a, "{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"{s}\",\"arguments\":{s}}}}}", .{ name, args });
var k: usize = 0;
while (true) : (k += 1) {
Expand Down Expand Up @@ -216,9 +216,15 @@ fn writeFile(a: std.mem.Allocator, folder: []const u8, name: []const u8, text: [
try Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = path, .data = text });
}

/// The folders of the environment of a test run: HOME is FOLDER.home,
/// as in the environment of `Run.start`.
fn testDirs(a: std.mem.Allocator, folder: []const u8) host.Dirs {
return .{ .home = std.fmt.allocPrint(a, "{s}.home", .{folder}) catch null };
}

/// Removes a test project with its folders, and its control socket.
fn removeFolder(a: std.mem.Allocator, folder: []const u8) void {
if (host.controlPath(a, null, folder)) |sock| {
if (host.controlPath(a, testDirs(a, folder), folder)) |sock| {
Io.Dir.cwd().deleteFile(std.testing.io, sock) catch {};
} else |_| {}
Io.Dir.cwd().deleteTree(std.testing.io, folder) catch {};
Expand Down Expand Up @@ -348,13 +354,15 @@ test "dockyard --mcp answers a client on stdin and stdout" {
var to_child: [2]c_int = undefined;
var from_child: [2]c_int = undefined;
if (std.c.pipe(&to_child) != 0 or std.c.pipe(&from_child) != 0) return error.Unexpected;
const home = try std.fmt.allocPrintSentinel(a, "HOME={s}.home", .{folder}, 0);
const pid = std.c.fork();
if (pid == 0) {
_ = std.c.dup2(to_child[0], 0);
_ = std.c.dup2(from_child[1], 1);
for ([_]c_int{ to_child[0], to_child[1], from_child[0], from_child[1] }) |fd| _ = std.c.close(fd);
const argv = [_:null]?[*:0]const u8{ exe, "--mcp", folder.ptr };
const envp = [_:null]?[*:0]const u8{"PATH=/usr/bin:/bin"};
// The same HOME as the window of the test, so the same socket.
const envp = [_:null]?[*:0]const u8{ "PATH=/usr/bin:/bin", home.ptr };
_ = execve(exe, &argv, &envp);
std.c._exit(127);
}
Expand Down
Loading