Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the agent and its clients say to each other.//!//! One request and one response per connection, each a JSON object preceded//! by its length as a four-octet little-endian integer. The operations://!//! | op | does | answers with |//! |---|---|---|//! | `ping` | nothing | |//! | `status` | | whether unlocked, and the keys found |//! | `unlock` | asks for the master password and syncs | the keys found |//! | `lock` | forgets everything | |//! | `sync` | fetches the vault again | the keys found |//! | `describe` | picks the key for the key selector `key` | its fingerprint and algorithm |//! | `sign` | signs `digest` with the key `fingerprint` | the signature material |//! | `stop` | exits | |//! | `remote_list` | | the SSH sessions remote signing goes through, by either route |//! | `remote_allow` | stops confirming a session's signatures (`pid`, or all) | the sessions |//! | `remote_revoke` | starts confirming them again | the sessions |//!//! `describe` and `sign` unlock first if they have to. A request carries the//! client's display and terminal variables in `env`, so that pinentry//! appears where the person who asked is looking.//!//! A remote machine's request, by either route, is answered only for//! `ping`, `describe` and `sign`, has its `env` ignored, and has every//! signature confirmed on the key machine unless its SSH session is allowed.//! On the forward it comes in on the extra socket. On the tailnet it must//! also carry the pairing `token` and the `ssh` session it is for; see//! `tailnet.zig`.//!//! Some field names predate the glossary and stay as they are, since a//! client and an agent of different versions have to understand each other://! `key` is a key selector, `problems` lists unreadable notes, and a//! `KeyInfo`'s `item` is the name of its Secure Note.
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const testing = std.testing;
/// Nothing legitimate comes close: the largest thing sent is a status/// listing.pub const max_frame = 1 << 20;
pub const EnvVar = struct { name: []const u8, value: []const u8,};
/// The environment variables a pinentry needs to find its way to the user,/// which a local client sends with each request.pub const pinentry_env = [_][]const u8{ "DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "GPG_TTY", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES",};
pub const Request = struct { op: []const u8, /// `describe`: the key selector, as given to `-u`. key: ?[]const u8 = null, /// `sign`: the key's fingerprint in hex, as `describe` returned it. fingerprint: ?[]const u8 = null, /// `sign`: the SHA-512 digest, base64. digest: ?[]const u8 = null, /// `sign`: the summary, what the client says is being signed -- a /// commit's subject and author -- for the confirmation of a remote /// signature. Shown to the person confirming, never trusted. summary: ?[]const u8 = null, /// `remote_allow` and `remote_revoke`: the session's process, or null /// for all of them. pid: ?i32 = null, /// Over the tailnet: the pairing token, base64. token: ?[]const u8 = null, /// Over the tailnet: the client's `SSH_CONNECTION`, naming the session /// the request is for. ssh: ?[]const u8 = null, env: []const EnvVar = &.{},};
pub const KeyInfo = struct { fingerprint: []const u8, /// The name of the Secure Note holding the key. item: []const u8, user_ids: []const []const u8,};
pub const SessionInfo = struct { pid: i32, command: []const u8, allowed: bool,};
pub const Response = struct { ok: bool, /// A short machine-readable reason, when `ok` is false: `locked`, /// `cancelled`, `no_key`, `ambiguous`, `bad_credentials`, and so on. @"error": ?[]const u8 = null, /// A sentence for a person, when there is something to say. message: ?[]const u8 = null, unlocked: ?bool = null, keys: ?[]const KeyInfo = null, /// The unreadable notes, each with why it could not be read. problems: ?[]const []const u8 = null, fingerprint: ?[]const u8 = null, algorithm: ?u8 = null, /// `sign`: the signature material, base64. material: ?[]const u8 = null, /// The `remote_` operations: the SSH sessions the agent knows of. sessions: ?[]const SessionInfo = null,};
pub const FrameError = error{ FrameTooLarge, EndOfStream, ReadFailed, OutOfMemory };
pub fn writeFrame(w: *Io.Writer, payload: []const u8) Io.Writer.Error!void { try w.writeInt(u32, @intCast(payload.len), .little); try w.writeAll(payload); try w.flush();}
/// Reads one frame, allocated from `gpa`.pub fn readFrame(gpa: Allocator, r: *Io.Reader) FrameError![]u8 { const len = r.takeInt(u32, .little) catch |err| return switch (err) { error.EndOfStream => error.EndOfStream, error.ReadFailed => error.ReadFailed, }; if (len > max_frame) return error.FrameTooLarge; const buf = try gpa.alloc(u8, len); errdefer gpa.free(buf); r.readSliceAll(buf) catch |err| return switch (err) { error.EndOfStream => error.EndOfStream, error.ReadFailed => error.ReadFailed, }; return buf;}
pub fn send(gpa: Allocator, w: *Io.Writer, value: anytype) (Allocator.Error || Io.Writer.Error)!void { const text = try std.json.Stringify.valueAlloc(gpa, value, .{ .emit_null_optional_fields = false }); defer gpa.free(text); try writeFrame(w, text);}
pub fn receive(comptime T: type, gpa: Allocator, r: *Io.Reader) !std.json.Parsed(T) { const text = try readFrame(gpa, r); defer gpa.free(text); return std.json.parseFromSlice(T, gpa, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, });}
test "a request and a response round trip" { const gpa = testing.allocator; var buf: [4096]u8 = undefined; var w: Io.Writer = .fixed(&buf); try send(gpa, &w, Request{ .op = "describe", .key = "ABCD", .env = &.{.{ .name = "DISPLAY", .value = ":0" }}, }); try send(gpa, &w, Response{ .ok = false, .@"error" = "locked" });
var r: Io.Reader = .fixed(w.buffered()); const req = try receive(Request, gpa, &r); defer req.deinit(); try testing.expectEqualStrings("describe", req.value.op); try testing.expectEqualStrings("ABCD", req.value.key.?); try testing.expectEqualStrings(":0", req.value.env[0].value);
const res = try receive(Response, gpa, &r); defer res.deinit(); try testing.expect(!res.value.ok); try testing.expectEqualStrings("locked", res.value.@"error".?); try testing.expectEqual(@as(?[]const u8, null), res.value.material);}
test "an oversized or truncated frame is refused" { const gpa = testing.allocator; var r: Io.Reader = .fixed(&.{ 0xff, 0xff, 0xff, 0x7f }); try testing.expectError(error.FrameTooLarge, readFrame(gpa, &r)); var r2: Io.Reader = .fixed(&.{ 10, 0, 0, 0, 'a' }); try testing.expectError(error.EndOfStream, readFrame(gpa, &r2));}