Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234//! API authentication: one admin credential, and an optional read-only one.//!//! `PREFECT_SERVER_API_AUTH_STRING` (or `PREFECT_API_AUTH_STRING`) is the//! admin "user:pass"; it authorizes everything. `PREFECT_SERVER_API_READONLY_AUTH_STRING`//! is a second "user:pass" that authorizes only requests which cannot change//! server state or reveal stored secrets: GET (except block documents and//! admin), the POST query endpoints (`/filter`, `/count`, `/paginate`,//! `/history`, `/lateness`, `/count-by/...`, `/filter/next`, everything under//! `/ui/`), and the events-out and logs-out sockets. Agents that only need//! to watch the server hold the read-only string, so a leaked or hijacked//! agent cannot create runs, set states, or read block secrets.//!//! When no admin string is configured the server is open, as before.
const std = @import("std");const mem = std.mem;const wap = @import("wap");const env = @import("../utilities/env.zig");const encoding = @import("../utilities/encoding.zig");
pub const Role = enum { admin, read_only };
pub fn configuredAuthString() ?[]const u8 { return env.getenv("PREFECT_SERVER_API_AUTH_STRING") orelse env.getenv("PREFECT_API_AUTH_STRING");}
pub fn configuredReadOnlyAuthString() ?[]const u8 { return env.getenv("PREFECT_SERVER_API_READONLY_AUTH_STRING");}
fn nonEmpty(s: ?[]const u8) ?[]const u8 { const v = s orelse return null; return if (v.len == 0) null else v;}
fn timingSafeEql(a: []const u8, b: []const u8) bool { if (a.len != b.len) return false; var diff: u8 = 0; for (a, b) |x, y| diff |= x ^ y; return diff == 0;}
/// which role a presented credential carries, given the configured strings./// both are compared even when the first matches, so timing does not reveal/// which one was hit.pub fn roleFor(creds: []const u8, admin: ?[]const u8, read_only: ?[]const u8) ?Role { const is_admin = if (nonEmpty(admin)) |a| timingSafeEql(creds, a) else false; const is_read_only = if (nonEmpty(read_only)) |r| timingSafeEql(creds, r) else false; if (is_admin) return .admin; if (is_read_only) return .read_only; return null;}
fn stripApiPrefix(path: []const u8) []const u8 { return if (mem.startsWith(u8, path, "/api/")) path[4..] else path;}
fn hasPathPrefix(path: []const u8, prefix: []const u8) bool { return mem.startsWith(u8, path, prefix) and (path.len == prefix.len or path[prefix.len] == '/' or path[prefix.len] == '?');}
const read_post_suffixes = [_][]const u8{ "/filter", "/filter/next", "/count", "/paginate", "/history", "/lateness",};
/// true when the request only reads state a read-only client may see./// paths arrive with or without the `/api` prefix; both spellings route.pub fn isReadRequest(method: std.http.Method, raw_path: []const u8) bool { const path = stripApiPrefix(raw_path); // block documents carry secret values (`include_secrets`), and the admin // endpoints expose server configuration if (hasPathPrefix(path, "/block_documents") or hasPathPrefix(path, "/admin")) return false; switch (method) { .GET, .HEAD => return true, .POST => { if (hasPathPrefix(path, "/ui")) return true; if (mem.startsWith(u8, path, "/events/count-by/")) return true; for (read_post_suffixes) |suffix| { if (mem.endsWith(u8, path, suffix)) return true; } return false; }, else => return false, }}
fn credentialsFromHeader(alloc: mem.Allocator, header: []const u8) ?[]const u8 { var parts = mem.tokenizeAny(u8, header, " \t\r\n"); const scheme = parts.next() orelse return null; const creds = parts.next() orelse return null; if (parts.next() != null) return null; if (!mem.eql(u8, scheme, "Basic")) return null; return encoding.base64Decode(alloc, creds) catch null;}
/// the pure core of request authorization; `authorizeRequest` feeds it the/// configured strings.pub fn authorizeWith( alloc: mem.Allocator, method: std.http.Method, path: []const u8, authorization: ?[]const u8, admin: ?[]const u8, read_only: ?[]const u8,) bool { if (nonEmpty(admin) == null) return true; const header = authorization orelse return false; const creds = credentialsFromHeader(alloc, header) orelse return false; defer alloc.free(creds); const role = roleFor(creds, admin, read_only) orelse return false; return switch (role) { .admin => true, .read_only => isReadRequest(method, path), };}
fn isHealthOrPreflight(req: *const wap.Request) bool { if (req.method == .OPTIONS) return true; if (req.method != .GET) return false; return mem.eql(u8, req.path, "/api/health") or mem.eql(u8, req.path, "/health") or mem.eql(u8, req.path, "/api/ready") or mem.eql(u8, req.path, "/ready") or mem.eql(u8, req.path, "/ui-settings");}
pub fn authorizeRequest(req: *const wap.Request) bool { if (isHealthOrPreflight(req)) return true; return authorizeWith( req.arena, req.method, req.path, req.header("authorization"), configuredAuthString(), configuredReadOnlyAuthString(), );}
/// websocket auth frame `{"type":"auth","token":"user:pass"}`. `allow_read_only`/// is true for sockets that only deliver data (events out, logs out); the/// ingest and worker sockets pass false.pub fn validateSocketAuthFrame(alloc: mem.Allocator, data: []const u8, allow_read_only: bool) bool { const admin = configuredAuthString(); if (nonEmpty(admin) == null) return true;
const parsed = std.json.parseFromSliceLeaky(std.json.Value, alloc, data, .{}) catch return false; if (parsed != .object) return false;
const token = parsed.object.get("token") orelse return false; if (token != .string) return false; const role = roleFor(token.string, admin, configuredReadOnlyAuthString()) orelse return false; return switch (role) { .admin => true, .read_only => allow_read_only, };}
test "roleFor distinguishes admin from read-only and rejects the rest" { try std.testing.expectEqual(Role.admin, roleFor("a:1", "a:1", "r:2").?); try std.testing.expectEqual(Role.read_only, roleFor("r:2", "a:1", "r:2").?); try std.testing.expect(roleFor("x:9", "a:1", "r:2") == null); try std.testing.expect(roleFor("r:2", "a:1", null) == null); try std.testing.expect(roleFor("", "a:1", "") == null);}
test "isReadRequest allows queries and refuses mutations" { const reads = [_]struct { m: std.http.Method, p: []const u8 }{ .{ .m = .GET, .p = "/api/flow_runs/abc" }, .{ .m = .GET, .p = "/deployments/abc" }, .{ .m = .POST, .p = "/api/flow_runs/filter" }, .{ .m = .POST, .p = "/api/flow_runs/count" }, .{ .m = .POST, .p = "/api/deployments/paginate" }, .{ .m = .POST, .p = "/api/flow_runs/history" }, .{ .m = .POST, .p = "/api/flow_runs/lateness" }, .{ .m = .POST, .p = "/api/flow_runs/abc/input/filter" }, .{ .m = .POST, .p = "/api/logs/filter" }, .{ .m = .POST, .p = "/api/events/filter" }, .{ .m = .POST, .p = "/api/events/filter/next" }, .{ .m = .POST, .p = "/api/events/count-by/event" }, .{ .m = .POST, .p = "/api/ui/flow_runs/history" }, .{ .m = .POST, .p = "/api/ui/task_runs/dashboard/counts" }, .{ .m = .POST, .p = "/api/v2/concurrency_limits/leases/filter" }, }; for (reads) |r| try std.testing.expect(isReadRequest(r.m, r.p));
const writes = [_]struct { m: std.http.Method, p: []const u8 }{ .{ .m = .POST, .p = "/api/flow_runs/" }, .{ .m = .POST, .p = "/api/flow_runs/abc/set_state" }, .{ .m = .POST, .p = "/api/flow_runs/abc/resume" }, .{ .m = .POST, .p = "/api/flow_runs/bulk_delete" }, .{ .m = .POST, .p = "/api/flow_runs/bulk_set_state" }, .{ .m = .POST, .p = "/api/deployments/abc/create_flow_run" }, .{ .m = .POST, .p = "/api/deployments/get_scheduled_flow_runs" }, .{ .m = .POST, .p = "/api/work_pools/home/get_scheduled_flow_runs" }, .{ .m = .POST, .p = "/api/work_pools/home/workers/heartbeat" }, .{ .m = .POST, .p = "/api/v2/concurrency_limits/increment" }, .{ .m = .POST, .p = "/api/logs/" }, .{ .m = .POST, .p = "/api/events" }, .{ .m = .POST, .p = "/api/variables/" }, .{ .m = .PATCH, .p = "/api/deployments/abc" }, .{ .m = .DELETE, .p = "/api/flow_runs/abc" }, .{ .m = .PUT, .p = "/api/automations/abc" }, // secrets and server configuration are not for the read-only role .{ .m = .POST, .p = "/api/block_documents/filter" }, .{ .m = .GET, .p = "/api/block_documents/abc" }, .{ .m = .GET, .p = "/api/admin/settings" }, // a filter-shaped suffix on a block path is still refused .{ .m = .POST, .p = "/block_documents/count" }, }; for (writes) |w| try std.testing.expect(!isReadRequest(w.m, w.p));}
test "authorizeWith: admin does everything, read-only only reads, open server when unset" { const alloc = std.testing.allocator; // "a:1" -> YToxCg is with newline; use exact encodings of "a:1" and "r:2" const admin_hdr = "Basic YTox"; // a:1 const ro_hdr = "Basic cjoy"; // r:2 try std.testing.expect(authorizeWith(alloc, .POST, "/api/flow_runs/", admin_hdr, "a:1", "r:2")); try std.testing.expect(authorizeWith(alloc, .POST, "/api/flow_runs/filter", ro_hdr, "a:1", "r:2")); try std.testing.expect(!authorizeWith(alloc, .POST, "/api/flow_runs/", ro_hdr, "a:1", "r:2")); try std.testing.expect(!authorizeWith(alloc, .GET, "/api/block_documents/x", ro_hdr, "a:1", "r:2")); try std.testing.expect(!authorizeWith(alloc, .GET, "/api/flows", null, "a:1", "r:2")); try std.testing.expect(!authorizeWith(alloc, .GET, "/api/flows", "Bearer YTox", "a:1", "r:2")); // read-only string configured alone does nothing: no admin string means open try std.testing.expect(authorizeWith(alloc, .POST, "/api/flow_runs/", null, null, "r:2")); try std.testing.expect(authorizeWith(alloc, .POST, "/api/flow_runs/", null, "", "r:2"));}