#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Build::Registry { namespace { using JsonVal = Void::Json::Strict::Value; Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) { return Void::System::make_system_error(code, std::move(msg)); } std::int64_t now_epoch() { return std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count(); } std::string random_hex(std::size_t num_bytes) { std::vector bytes(num_bytes); if (::getrandom(bytes.data(), bytes.size(), 0) != static_cast(bytes.size())) { const auto t = static_cast( std::chrono::high_resolution_clock::now().time_since_epoch().count()); for (std::size_t i = 0; i < num_bytes; ++i) { bytes[i] = static_cast((t >> ((i % 8) * 8)) ^ (i * 0x5du)); } } return Void::Encoding::Hex::encode(std::span{bytes.data(), bytes.size()}); } // Key-stretched salted SHA-256 password hash (20,000 rounds) — swappable to Argon2id via // Void::Security. std::string derive_password_hash(std::string_view salt_hex, std::string_view password) { std::string cur = Util::sha256_hex(std::string{salt_hex} + ":" + std::string{password}); for (int i = 0; i < 20000; ++i) { cur = Util::sha256_hex(cur + ":" + std::string{salt_hex}); } return cur; } std::string_view role_name(Role r) { switch (r) { case Role::Reader: return "reader"; case Role::Publisher: return "publisher"; case Role::Admin: return "admin"; } return "reader"; } Role parse_role(std::string_view s) { if (s == "admin") return Role::Admin; if (s == "publisher") return Role::Publisher; return Role::Reader; } bool valid_package_name(std::string_view name) { if (name.empty() || name.size() > 64) { return false; } return std::ranges::all_of(name, [](char c) { return Void::Str::is_ascii_alnum(c) || c == '_' || c == '-' || c == '.'; }); } bool is_sha256_hex(std::string_view hex) { if (hex.size() != 64) { return false; } return std::ranges::all_of( hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }); } std::vector split_path(std::string_view path) { std::vector segs; for (const auto part : Void::Str::split(path, '/')) { if (!part.empty()) { segs.emplace_back(part); } } return segs; } const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) { const auto it = obj.find(k); return it == obj.end() ? nullptr : &it->second; } std::string get_str(const JsonVal::Object &obj, const std::string &k) { const auto *v = find_key(obj, k); if (!v) return {}; const auto *s = std::get_if(&v->value); return s ? *s : std::string{}; } bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) { const auto *v = find_key(obj, k); if (!v) return def; const auto *b = std::get_if(&v->value); return b ? *b : def; } std::int64_t get_i64(const JsonVal::Object &obj, const std::string &k, std::int64_t def = 0) { const auto *v = find_key(obj, k); if (!v) return def; const auto *i = std::get_if(&v->value); return i ? *i : def; } std::string content_type_for_ext(const std::filesystem::path &p) { const auto ext = p.extension().string(); if (ext == ".html") return "text/html; charset=utf-8"; if (ext == ".css") return "text/css; charset=utf-8"; if (ext == ".js") return "application/javascript; charset=utf-8"; if (ext == ".json") return "application/json; charset=utf-8"; if (ext == ".svg") return "image/svg+xml"; return "application/octet-stream"; } } // namespace RegistryService::RegistryService(RegistryConfig config) : config_{std::move(config)}, blobs_dir_{config_.data_dir / "cas" / "blobs"}, action_blobs_dir_{config_.data_dir / "action-cache" / "blobs"}, action_records_dir_{config_.data_dir / "action-cache" / "actions"}, meta_file_{config_.data_dir / "metadata.v1.json"}, lock_file_{config_.data_dir / "registry.lock"} {} Void::Result::Result, Void::Result::Error> RegistryService::open(RegistryConfig config) { std::error_code ec; std::filesystem::create_directories(config.data_dir / "cas" / "blobs", ec); std::filesystem::create_directories(config.data_dir / "action-cache" / "blobs", ec); std::filesystem::create_directories(config.data_dir / "action-cache" / "actions", ec); if (ec) { return std::unexpected{make_error(Void::System::map_errno_to_system_code(ec.value()), "RegistryService::open: cannot create data directories")}; } auto svc = std::unique_ptr(new RegistryService(std::move(config))); std::lock_guard lk{svc->mu_}; if (std::filesystem::exists(svc->meta_file_, ec)) { if (auto r = svc->load_locked(); !r) { return std::unexpected{r.error()}; } } else { if (!svc->config_.bootstrap_admin_password.empty()) { UserRecord admin; admin.username = svc->config_.bootstrap_admin_user; admin.role = Role::Admin; admin.password_salt_hex = random_hex(16); admin.password_hash_hex = derive_password_hash(admin.password_salt_hex, svc->config_.bootstrap_admin_password); svc->users_[admin.username] = std::move(admin); } if (auto r = svc->save_locked(); !r) { return std::unexpected{r.error()}; } } return svc; } Void::Result::Result RegistryService::start_http() { HttpServerOptions sopts; sopts.bind_address = config_.bind_address; sopts.port = config_.port; sopts.max_body_bytes = static_cast(config_.max_upload_bytes); return server_.start(sopts, [this](const HttpRequest &req) { return handle_request(req); }); } void RegistryService::stop_http() noexcept { server_.stop(); } std::filesystem::path RegistryService::blob_path(std::string_view sha256) const { if (sha256.size() < 2) { return blobs_dir_ / std::string{sha256}; } return blobs_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256}; } Void::Result::Result RegistryService::load_locked() { auto text = Void::FileSystem::read_file_bounded(meta_file_, {64ULL * 1024ULL * 1024ULL}); if (!text) { return std::unexpected{text.error()}; } auto parsed = Void::Json::Strict::parse(*text); if (!parsed) { return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, "corrupt registry metadata JSON")}; } const auto *root = std::get_if(&parsed->value); if (!root) { return std::unexpected{ make_error(Void::System::SystemErrorCode::io_error, "invalid registry metadata")}; } users_.clear(); tokens_.clear(); packages_.clear(); audits_.clear(); if (const auto *uv = find_key(*root, "users")) { if (const auto *uarr = std::get_if(&uv->value)) { for (const auto &item : *uarr) { if (const auto *uo = std::get_if(&item.value)) { UserRecord u; u.username = get_str(*uo, "username"); u.role = parse_role(get_str(*uo, "role")); u.password_salt_hex = get_str(*uo, "salt"); u.password_hash_hex = get_str(*uo, "password_hash"); u.active = get_bool(*uo, "active", true); users_[u.username] = std::move(u); } } } } if (const auto *tv = find_key(*root, "tokens")) { if (const auto *tarr = std::get_if(&tv->value)) { for (const auto &item : *tarr) { if (const auto *to = std::get_if(&item.value)) { ApiTokenRecord t; t.token_id = get_str(*to, "token_id"); t.username = get_str(*to, "username"); t.label = get_str(*to, "label"); t.token_sha256 = get_str(*to, "token_sha256"); t.expires_epoch = get_i64(*to, "expires_epoch", 0); t.revoked = get_bool(*to, "revoked", false); if (const auto *sv = find_key(*to, "scopes")) { if (const auto *sarr = std::get_if(&sv->value)) { for (const auto &s : *sarr) { if (const auto *ss = std::get_if(&s.value)) { t.scopes.insert(*ss); } } } } tokens_[t.token_id] = std::move(t); } } } } if (const auto *pv = find_key(*root, "packages")) { if (const auto *parr = std::get_if(&pv->value)) { for (const auto &item : *parr) { if (const auto *po = std::get_if(&item.value)) { PackageMeta p; p.name = get_str(*po, "name"); p.description = get_str(*po, "description"); p.is_private = get_bool(*po, "is_private", false); if (const auto *ov = find_key(*po, "owners")) { if (const auto *oarr = std::get_if(&ov->value)) { for (const auto &o : *oarr) { if (const auto *os = std::get_if(&o.value)) { p.owners.insert(*os); } } } } if (const auto *rv = find_key(*po, "releases")) { if (const auto *rarr = std::get_if(&rv->value)) { for (const auto &r : *rarr) { if (const auto *ro = std::get_if(&r.value)) { ReleaseMeta rm; rm.version = get_str(*ro, "version"); rm.sha256 = get_str(*ro, "sha256"); rm.size_bytes = static_cast(get_i64(*ro, "size_bytes", 0)); rm.yanked = get_bool(*ro, "yanked", false); rm.publisher = get_str(*ro, "publisher"); rm.published_epoch = get_i64(*ro, "published_epoch", 0); rm.signature = get_str(*ro, "signature"); rm.public_key = get_str(*ro, "public_key"); if (const auto *bv = find_key(*ro, "binaries")) { if (const auto *barr = std::get_if(&bv->value)) { for (const auto &b : *barr) { if (const auto *bo = std::get_if(&b.value)) { BinaryReleaseMeta bm; bm.variant_id = get_str(*bo, "variant_id"); bm.sha256 = get_str(*bo, "sha256"); bm.size_bytes = static_cast( get_i64(*bo, "size_bytes", 0)); bm.yanked = get_bool(*bo, "yanked", false); bm.signature = get_str(*bo, "signature"); bm.public_key = get_str(*bo, "public_key"); bm.publisher = get_str(*bo, "publisher"); bm.published_epoch = get_i64(*bo, "published_epoch", 0); if (!bm.variant_id.empty()) { rm.binaries[bm.variant_id] = std::move(bm); } } } } } p.releases[rm.version] = std::move(rm); } } } } packages_[p.name] = std::move(p); } } } } if (const auto *av = find_key(*root, "audits")) { if (const auto *aarr = std::get_if(&av->value)) { for (const auto &item : *aarr) { if (const auto *ao = std::get_if(&item.value)) { audits_.push_back({get_i64(*ao, "timestamp", 0), get_str(*ao, "actor"), get_str(*ao, "action"), get_str(*ao, "target"), get_str(*ao, "outcome"), get_str(*ao, "detail")}); } } } } return {}; } Void::Result::Result RegistryService::save_locked() { using Util::json_array; using Util::json_quote; auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive); if (!lock) { return std::unexpected{lock.error()}; } std::vector ulist; for (const auto &[k, v] : users_) ulist.push_back(&v); std::vector tlist; for (const auto &[k, v] : tokens_) tlist.push_back(&v); std::vector plist; for (const auto &[k, v] : packages_) plist.push_back(&v); std::string out = "{\"schema_version\":1,\"users\":"; out += json_array(ulist, [](const UserRecord *u) { return "{\"username\":" + json_quote(u->username) + ",\"role\":" + json_quote(role_name(u->role)) + ",\"salt\":" + json_quote(u->password_salt_hex) + ",\"password_hash\":" + json_quote(u->password_hash_hex) + ",\"active\":" + std::string{u->active ? "true" : "false"} + '}'; }); out += ",\"tokens\":"; out += json_array(tlist, [](const ApiTokenRecord *t) { return "{\"token_id\":" + json_quote(t->token_id) + ",\"username\":" + json_quote(t->username) + ",\"label\":" + json_quote(t->label) + ",\"token_sha256\":" + json_quote(t->token_sha256) + ",\"scopes\":" + json_array(t->scopes, json_quote) + ",\"expires_epoch\":" + std::to_string(t->expires_epoch) + ",\"revoked\":" + std::string{t->revoked ? "true" : "false"} + '}'; }); out += ",\"packages\":"; out += json_array(plist, [](const PackageMeta *p) { std::vector rlist; for (const auto &[vk, rv] : p->releases) rlist.push_back(&rv); return "{\"name\":" + json_quote(p->name) + ",\"description\":" + json_quote(p->description) + ",\"is_private\":" + std::string{p->is_private ? "true" : "false"} + ",\"owners\":" + json_array(p->owners, json_quote) + ",\"releases\":" + json_array(rlist, [](const ReleaseMeta *r) { return "{\"version\":" + json_quote(r->version) + ",\"sha256\":" + json_quote(r->sha256) + ",\"size_bytes\":" + std::to_string(r->size_bytes) + ",\"yanked\":" + std::string{r->yanked ? "true" : "false"} + ",\"publisher\":" + json_quote(r->publisher) + ",\"published_epoch\":" + std::to_string(r->published_epoch) + (r->signature.empty() ? std::string{} : ",\"signature\":" + json_quote(r->signature)) + (r->public_key.empty() ? std::string{} : ",\"public_key\":" + json_quote(r->public_key)) + ",\"binaries\":" + json_array( r->binaries, [](const auto &entry) { const auto &b = entry.second; return "{\"variant_id\":" + json_quote(b.variant_id) + ",\"sha256\":" + json_quote(b.sha256) + ",\"size_bytes\":" + std::to_string(b.size_bytes) + ",\"yanked\":" + std::string{b.yanked ? "true" : "false"} + ",\"signature\":" + json_quote(b.signature) + ",\"public_key\":" + json_quote(b.public_key) + ",\"publisher\":" + json_quote(b.publisher) + ",\"published_epoch\":" + std::to_string(b.published_epoch) + '}'; }) + '}'; }) + '}'; }); out += ",\"audits\":"; out += json_array(audits_, [](const AuditEntry &a) { return "{\"timestamp\":" + std::to_string(a.timestamp) + ",\"actor\":" + json_quote(a.actor) + ",\"action\":" + json_quote(a.action) + ",\"target\":" + json_quote(a.target) + ",\"outcome\":" + json_quote(a.outcome) + ",\"detail\":" + json_quote(a.detail) + '}'; }); out += "}\n"; return Platform::atomic_write_file(meta_file_, out, true); } void RegistryService::append_audit_locked(std::string actor, std::string action, std::string target, std::string outcome, std::string detail) { audits_.push_back({now_epoch(), std::move(actor), std::move(action), std::move(target), std::move(outcome), Package::redact_secrets(detail)}); if (audits_.size() > 2000) { audits_.erase(audits_.begin(), audits_.begin() + 500); } } std::uint64_t RegistryService::total_storage_bytes_locked() const { std::uint64_t total = 0; std::set seen; for (const auto &[pname, p] : packages_) { for (const auto &[ver, rel] : p.releases) { if (seen.insert(rel.sha256).second) { total += rel.size_bytes; } } } return total; } std::optional RegistryService::authenticate_locked(const HttpRequest &req, std::string &auth_err) const { const auto now = now_epoch(); // 1. Bearer token authentication. if (const auto auth = req.header("authorization")) { if (auth->starts_with("Bearer ")) { const auto raw_tok = auth->substr(7); const std::string hashed = Util::sha256_hex(raw_tok); for (const auto &[tid, tok] : tokens_) { if (Util::constant_time_equal(tok.token_sha256, hashed)) { if (tok.revoked) { auth_err = "token has been revoked"; return std::nullopt; } if (tok.expires_epoch > 0 && now > tok.expires_epoch) { auth_err = "token has expired"; return std::nullopt; } const auto uit = users_.find(tok.username); if (uit == users_.end() || !uit->second.active) { auth_err = "token user is inactive"; return std::nullopt; } return Principal{uit->second.username, uit->second.role, tok.scopes, false, {}}; } } auth_err = "invalid bearer token"; return std::nullopt; } auth_err = "unsupported authorization scheme"; return std::nullopt; } // 2. HttpOnly browser session cookie authentication. if (const auto sid = req.cookie("vbs_session")) { const std::string sid_hash = Util::sha256_hex(*sid); const auto sit = sessions_.find(sid_hash); if (sit == sessions_.end() || (sit->second.expires_epoch > 0 && now > sit->second.expires_epoch)) { auth_err = "session expired or invalid"; return std::nullopt; } const auto uit = users_.find(sit->second.username); if (uit == users_.end() || !uit->second.active) { auth_err = "session user is inactive"; return std::nullopt; } std::set scopes{"read"}; if (uit->second.role == Role::Publisher || uit->second.role == Role::Admin) { scopes.insert("publish"); } if (uit->second.role == Role::Admin) { scopes.insert("admin"); } return Principal{uit->second.username, uit->second.role, std::move(scopes), true, sit->second.csrf_token}; } return std::nullopt; } bool RegistryService::check_csrf_locked(const HttpRequest &req, const Principal &p) const { if (!p.via_session_cookie) { return true; // Bearer tokens are not ambient browser credentials. } const auto hdr = req.header("x-csrf-token"); if (!hdr || !Util::constant_time_equal(*hdr, p.csrf_token)) { return false; } if (const auto origin = req.header("origin")) { if (!origin->starts_with("http://127.0.0.1") && !origin->starts_with("http://localhost") && !origin->starts_with("https://")) { return false; } } return true; } Void::Result::Result RegistryService::create_user(std::string username, std::string password, Role role) { std::lock_guard lk{mu_}; if (username.empty() || password.size() < 6) { return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, "username must be nonempty and password >= 6 chars")}; } if (users_.contains(username)) { return std::unexpected{ make_error(Void::System::SystemErrorCode::already_exists, "user already exists")}; } UserRecord u; u.username = username; u.role = role; u.password_salt_hex = random_hex(16); u.password_hash_hex = derive_password_hash(u.password_salt_hex, password); users_[username] = std::move(u); append_audit_locked("system", "user.create", username, "ok", std::string{role_name(role)}); return save_locked(); } Void::Result::Result RegistryService::create_token(std::string username, std::string label, std::set scopes, std::int64_t expires_epoch) { std::lock_guard lk{mu_}; if (!users_.contains(username)) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, "user not found")}; } const std::string plaintext = "vbs_tok_" + random_hex(24); ApiTokenRecord rec; rec.token_id = "tok_" + random_hex(8); rec.username = username; rec.label = std::move(label); rec.token_sha256 = Util::sha256_hex(plaintext); rec.scopes = std::move(scopes); rec.expires_epoch = expires_epoch; tokens_[rec.token_id] = std::move(rec); append_audit_locked(username, "token.create", rec.token_id, "ok", "scoped token created"); if (auto r = save_locked(); !r) { return std::unexpected{r.error()}; } return plaintext; } HttpResponse RegistryService::serve_static_web_asset(std::string_view req_path) const { if (config_.web_root.empty()) { return HttpResponse::error_json(404, "not_found", "web UI root not configured"); } std::string rel{req_path}; if (rel == "/" || rel.empty()) { rel = "index.html"; } else if (rel.front() == '/') { rel.erase(0, 1); } if (rel.find("..") != std::string::npos || rel.find('\\') != std::string::npos) { return HttpResponse::error_json(403, "forbidden", "invalid static asset path"); } auto confined = Platform::resolve_confined_path(config_.web_root, config_.web_root / rel); if (!confined) { return HttpResponse::error_json(403, "forbidden", "path escape rejected"); } auto bytes = Void::FileSystem::read_file(*confined); if (!bytes) { return HttpResponse::error_json(404, "not_found", "asset not found"); } HttpResponse resp; resp.status = 200; resp.headers["Content-Type"] = content_type_for_ext(*confined); resp.body = std::move(*bytes); return resp; } HttpResponse RegistryService::handle_request(const HttpRequest &req) { using Util::json_array; using Util::json_quote; if (!req.path.starts_with("/api/")) { if (req.method != "GET") { return HttpResponse::error_json(405, "method_not_allowed", "GET only for static assets"); } return serve_static_web_asset(req.path); } std::lock_guard lk{mu_}; const auto segs = split_path(req.path); // Health endpoint. if (req.method == "GET" && req.path == "/api/v1/health") { return HttpResponse::json(200, "{\"status\":\"ok\",\"schema_version\":1}\n"); } // Session login: POST /api/v1/auth/login -> sets HttpOnly SameSite=Strict cookie + returns CSRF // token. if (req.method == "POST" && req.path == "/api/v1/auth/login") { auto parsed = Void::Json::Strict::parse(req.body); const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; if (!obj) { return HttpResponse::error_json(400, "invalid_json", "login body must be JSON object"); } const auto username = get_str(*obj, "username"); const auto password = get_str(*obj, "password"); const auto uit = users_.find(username); if (uit == users_.end() || !uit->second.active) { append_audit_locked(username, "auth.login", username, "denied", "invalid credentials"); return HttpResponse::error_json(401, "unauthorized", "invalid credentials"); } const auto candidate_hash = derive_password_hash(uit->second.password_salt_hex, password); if (!Util::constant_time_equal(candidate_hash, uit->second.password_hash_hex)) { append_audit_locked(username, "auth.login", username, "denied", "invalid credentials"); return HttpResponse::error_json(401, "unauthorized", "invalid credentials"); } const std::string raw_sid = random_hex(24); const std::string csrf = random_hex(24); SessionRecord srec{Util::sha256_hex(raw_sid), username, csrf, now_epoch() + 86400}; sessions_[srec.session_id_hash] = srec; append_audit_locked(username, "auth.login", username, "ok", "session created"); (void)save_locked(); auto resp = HttpResponse::json(200, "{\"username\":" + json_quote(username) + ",\"role\":" + json_quote(role_name(uit->second.role)) + ",\"csrf_token\":" + json_quote(csrf) + "}\n"); resp.set_cookies.push_back("vbs_session=" + raw_sid + "; HttpOnly; SameSite=Strict; Path=/"); return resp; } std::string auth_err; const auto principal = authenticate_locked(req, auth_err); if (!auth_err.empty()) { return HttpResponse::error_json(401, "unauthorized", auth_err); } // Session logout. if (req.method == "POST" && req.path == "/api/v1/auth/logout") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } if (const auto sid = req.cookie("vbs_session")) { sessions_.erase(Util::sha256_hex(*sid)); } auto resp = HttpResponse::json(200, "{\"logged_out\":true}\n"); resp.set_cookies.push_back("vbs_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0"); return resp; } if (req.method == "GET" && req.path == "/api/v1/auth/me") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "not logged in"); } return HttpResponse::json(200, "{\"username\":" + json_quote(principal->username) + ",\"role\":" + json_quote(role_name(principal->role)) + ",\"csrf_token\":" + json_quote(principal->csrf_token) + "}\n"); } // Shared content-addressed action cache (Track D1). // GET/PUT /api/v1/cas/blobs/ and /api/v1/cas/actions/. if (segs.size() == 5 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "cas" && (segs[3] == "blobs" || segs[3] == "actions")) { const bool is_blob = segs[3] == "blobs"; const std::string &key = segs[4]; if (!is_sha256_hex(key)) { return HttpResponse::error_json(400, "invalid_key", "CAS key must be a SHA-256 hex digest"); } if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } const auto base_dir = is_blob ? action_blobs_dir_ : action_records_dir_; const auto resource_path = base_dir / key.substr(0, 2) / (is_blob ? key : key + ".json"); if (req.method == "GET") { auto bytes = Void::FileSystem::read_file(resource_path); if (!bytes) { return HttpResponse::error_json(404, "not_found", "CAS object not found"); } HttpResponse resp; resp.status = 200; resp.headers["Content-Type"] = is_blob ? "application/octet-stream" : "application/json; charset=utf-8"; resp.body = std::move(*bytes); return resp; } if (req.method != "PUT") { return HttpResponse::error_json(405, "method_not_allowed", "CAS supports GET and PUT"); } if (!principal->scopes.contains("publish") && principal->role != Role::Admin) { append_audit_locked(principal->username, "cas.put", key, "denied", "missing publish scope"); return HttpResponse::error_json(403, "forbidden", "publish scope required"); } if (!is_blob && !Void::Json::Strict::parse(req.body)) { return HttpResponse::error_json(400, "invalid_json", "CAS action record must be JSON"); } if (is_blob && Util::sha256_hex(req.body) != key) { append_audit_locked(principal->username, "cas.put", key, "denied", "blob digest mismatch"); return HttpResponse::error_json(400, "digest_mismatch", "body SHA-256 does not match CAS key"); } std::error_code cas_ec; if (std::filesystem::is_regular_file(resource_path, cas_ec)) { return HttpResponse::json(200, "{\"stored\":true,\"created\":false}\n"); } std::filesystem::create_directories(resource_path.parent_path(), cas_ec); auto wrote = Platform::atomic_write_file(resource_path, req.body, true, is_blob ? 0444u : 0644u); if (!wrote) { return HttpResponse::error_json(500, "storage_error", "failed storing CAS object"); } append_audit_locked(principal->username, is_blob ? "cas.blob.put" : "cas.action.put", key, "ok", "stored"); return HttpResponse::json(201, "{\"stored\":true,\"created\":true}\n"); } auto can_read_pkg = [&](const PackageMeta &p) { if (!p.is_private) return true; if (!principal) return false; if (principal->role == Role::Admin) return true; return p.owners.contains(principal->username) || principal->scopes.contains("read"); }; auto can_publish_pkg = [&](const PackageMeta *existing) { if (!principal) return false; if (!principal->scopes.contains("publish") && principal->role != Role::Admin) return false; if (principal->role == Role::Admin) return true; if (principal->role != Role::Publisher) return false; if (existing && !existing->owners.empty() && !existing->owners.contains(principal->username)) { return false; } return true; }; // GET /api/v1/packages?q=... if (req.method == "GET" && req.path == "/api/v1/packages") { const std::string q = req.query.contains("q") ? req.query.at("q") : std::string{}; std::vector visible; for (const auto &[name, p] : packages_) { if (!can_read_pkg(p)) continue; if (!q.empty() && name.find(q) == std::string::npos && p.description.find(q) == std::string::npos) { continue; } visible.push_back(&p); } return HttpResponse::json( 200, "{\"packages\":" + json_array(visible, [](const PackageMeta *p) { return "{\"name\":" + json_quote(p->name) + ",\"description\":" + json_quote(p->description) + ",\"is_private\":" + std::string{p->is_private ? "true" : "false"} + ",\"release_count\":" + std::to_string(p->releases.size()) + '}'; }) + "}\n"); } // /api/v1/packages/[/[/download|/yank]] if (segs.size() >= 4 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "packages") { const std::string &pkg_name = segs[3]; if (!valid_package_name(pkg_name)) { return HttpResponse::error_json(400, "invalid_package_name", "invalid package name"); } // Package detail: GET /api/v1/packages/ if (segs.size() == 4 && req.method == "GET") { const auto pit = packages_.find(pkg_name); if (pit == packages_.end()) { return HttpResponse::error_json(404, "not_found", "package not found"); } if (!can_read_pkg(pit->second)) { return HttpResponse::error_json(principal ? 403 : 401, "forbidden", "private package requires authorization"); } std::vector rlist; for (const auto &[vk, rv] : pit->second.releases) rlist.push_back(&rv); return HttpResponse::json( 200, "{\"name\":" + json_quote(pit->second.name) + ",\"description\":" + json_quote(pit->second.description) + ",\"is_private\":" + std::string{pit->second.is_private ? "true" : "false"} + ",\"owners\":" + json_array(pit->second.owners, json_quote) + ",\"releases\":" + json_array( rlist, [](const ReleaseMeta *r) { return "{\"version\":" + json_quote(r->version) + ",\"sha256\":" + json_quote(r->sha256) + ",\"size_bytes\":" + std::to_string(r->size_bytes) + ",\"yanked\":" + std::string{r->yanked ? "true" : "false"} + ",\"publisher\":" + json_quote(r->publisher) + (r->signature.empty() ? std::string{} : ",\"signature\":" + json_quote(r->signature)) + (r->public_key.empty() ? std::string{} : ",\"public_key\":" + json_quote(r->public_key)) + ",\"binaries\":" + json_array( r->binaries, [](const auto &entry) { const auto &b = entry.second; return "{\"variant_id\":" + json_quote(b.variant_id) + ",\"sha256\":" + json_quote(b.sha256) + ",\"size_bytes\":" + std::to_string(b.size_bytes) + ",\"yanked\":" + std::string{b.yanked ? "true" : "false"} + ",\"signature\":" + json_quote(b.signature) + ",\"public_key\":" + json_quote(b.public_key) + '}'; }) + '}'; }) + "}\n"); } // Publish immutable release: PUT /api/v1/packages// if (segs.size() == 5 && req.method == "PUT") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } const std::string &ver_str = segs[4]; if (!Void::Semver::parse_strict(ver_str)) { return HttpResponse::error_json(400, "invalid_version", "release version must be strict SemVer"); } const auto pit = packages_.find(pkg_name); const PackageMeta *existing_pkg = (pit == packages_.end()) ? nullptr : &pit->second; if (!can_publish_pkg(existing_pkg)) { append_audit_locked(principal->username, "package.publish", pkg_name + "@" + ver_str, "denied", "unauthorized publisher"); (void)save_locked(); return HttpResponse::error_json(403, "forbidden", "insufficient publish authority or ownership"); } const std::string actual_sha = Util::sha256_hex(req.body); if (const auto claimed = req.header("x-content-sha256"); claimed && *claimed != actual_sha) { return HttpResponse::error_json(400, "digest_mismatch", "X-Content-SHA256 does not match uploaded bytes"); } // Optional detached Ed25519 signature metadata. The registry stores and serves it; // trust evaluation belongs to the consumer. Both fields must be present together. std::string release_signature; std::string release_public_key; if (const auto sig = req.header("x-package-signature"); sig) { release_signature = std::string{*sig}; } if (const auto key = req.header("x-package-public-key"); key) { release_public_key = std::string{*key}; } if (release_signature.empty() != release_public_key.empty()) { return HttpResponse::error_json( 400, "invalid_signature", "X-Package-Signature and X-Package-Public-Key must be provided together"); } auto is_hex = [](std::string_view text) { return std::ranges::all_of(text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }); }; if (!release_signature.empty() && (release_signature.size() != 128 || !is_hex(release_signature))) { return HttpResponse::error_json(400, "invalid_signature", "X-Package-Signature must be 128 hex characters"); } if (!release_public_key.empty() && (release_public_key.size() != 64 || !is_hex(release_public_key))) { return HttpResponse::error_json(400, "invalid_signature", "X-Package-Public-Key must be 64 hex characters"); } // Immutability check: idempotent on exact bytes, 409 Conflict on different bytes! if (existing_pkg) { if (const auto rit = existing_pkg->releases.find(ver_str); rit != existing_pkg->releases.end()) { if (rit->second.sha256 == actual_sha) { return HttpResponse::json(200, "{\"status\":\"already_published\",\"sha256\":" + json_quote(actual_sha) + "}\n"); } append_audit_locked(principal->username, "package.publish", pkg_name + "@" + ver_str, "conflict", "immutable release overwrite rejected"); (void)save_locked(); return HttpResponse::error_json( 409, "immutable_conflict", "release already exists with different content digest"); } } // Storage quota check. if (total_storage_bytes_locked() + req.body.size() > config_.max_storage_bytes) { return HttpResponse::error_json(413, "quota_exceeded", "registry storage quota exceeded"); } // Stage & validate tar archive safety (rejects traversal/symlinks/malformed tar; // NEVER executes uploaded recipes!). Void::FileSystem::TempDir probe_tmp{"vbs_reg_probe_"}; const auto staged_tar = probe_tmp / "upload.tar"; if (auto w = Platform::atomic_write_file(staged_tar, req.body, false); !w) { return HttpResponse::error_json(500, "stage_error", w.error().message()); } auto probe_extract = Package::extract_safe_tar(staged_tar, probe_tmp / "extracted"); if (!probe_extract) { append_audit_locked(principal->username, "package.publish", pkg_name + "@" + ver_str, "rejected", probe_extract.error().message()); (void)save_locked(); return HttpResponse::error_json(422, "invalid_archive", probe_extract.error().message()); } // Publish CAS blob BEFORE committing metadata! const auto dst_blob = blob_path(actual_sha); std::error_code ec; if (!std::filesystem::exists(dst_blob, ec)) { auto copied = Platform::copy_isolated(staged_tar, dst_blob, 0444u); if (!copied) { return HttpResponse::error_json(500, "blob_publish_failed", copied.error().message()); } } PackageMeta &pkg = packages_[pkg_name]; if (pkg.name.empty()) { pkg.name = pkg_name; pkg.owners.insert(principal->username); } if (const auto desc = req.header("x-package-description")) { pkg.description = std::string{*desc}; } if (const auto priv = req.header("x-package-private")) { pkg.is_private = (*priv == "true" || *priv == "1"); } pkg.releases[ver_str] = ReleaseMeta{ ver_str, actual_sha, req.body.size(), false, principal->username, now_epoch(), release_signature, release_public_key}; append_audit_locked(principal->username, "package.publish", pkg_name + "@" + ver_str, "ok", "sha256=" + actual_sha); if (auto s = save_locked(); !s) { return HttpResponse::error_json(500, "metadata_commit_failed", s.error().message()); } return HttpResponse::json(201, "{\"name\":" + json_quote(pkg_name) + ",\"version\":" + json_quote(ver_str) + ",\"sha256\":" + json_quote(actual_sha) + "}\n"); } // Download release blob: GET /api/v1/packages///download if (segs.size() == 6 && segs[5] == "download" && req.method == "GET") { const auto pit = packages_.find(pkg_name); if (pit == packages_.end()) { return HttpResponse::error_json(404, "not_found", "package not found"); } if (!can_read_pkg(pit->second)) { return HttpResponse::error_json(principal ? 403 : 401, "forbidden", "private package requires authorization"); } const auto rit = pit->second.releases.find(segs[4]); if (rit == pit->second.releases.end()) { return HttpResponse::error_json(404, "not_found", "release not found"); } const auto bpath = blob_path(rit->second.sha256); auto bytes = Void::FileSystem::read_file_bounded(bpath, {256ULL * 1024ULL * 1024ULL}); if (!bytes || Util::sha256_hex(*bytes) != rit->second.sha256) { return HttpResponse::error_json(500, "integrity_error", "stored CAS blob missing or corrupted"); } HttpResponse resp; resp.status = 200; resp.headers["Content-Type"] = "application/x-tar"; resp.headers["X-Content-SHA256"] = rit->second.sha256; resp.body = std::move(*bytes); return resp; } // Publish a prebuilt binary variant: // PUT /api/v1/packages///binaries/ if (segs.size() == 7 && segs[5] == "binaries" && req.method == "PUT") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } const std::string &ver_str = segs[4]; const std::string &variant_id = segs[6]; const bool valid_variant = !variant_id.empty() && variant_id.size() <= 128 && std::ranges::all_of(variant_id, [](char c) { return std::isalnum(static_cast(c)) || c == '.' || c == '_' || c == '-'; }); if (!valid_variant) { return HttpResponse::error_json(400, "invalid_variant_id", "variant id must be 1-128 chars of " "[A-Za-z0-9._-]"); } const auto pit = packages_.find(pkg_name); if (pit == packages_.end()) { return HttpResponse::error_json(404, "not_found", "package not found"); } if (!can_publish_pkg(&pit->second)) { return HttpResponse::error_json(403, "forbidden", "insufficient publish authority or ownership"); } const auto rit = pit->second.releases.find(ver_str); if (rit == pit->second.releases.end()) { return HttpResponse::error_json(404, "not_found", "release not found"); } const std::string actual_sha = Util::sha256_hex(req.body); if (const auto claimed = req.header("x-content-sha256"); claimed && *claimed != actual_sha) { return HttpResponse::error_json(400, "digest_mismatch", "X-Content-SHA256 does not match uploaded bytes"); } if (req.body.size() > config_.max_upload_bytes) { return HttpResponse::error_json(413, "too_large", "binary artifact exceeds limit"); } if (total_storage_bytes_locked() + req.body.size() > config_.max_storage_bytes) { return HttpResponse::error_json(413, "quota_exceeded", "registry storage quota exceeded"); } std::string binary_signature; std::string binary_public_key; if (const auto sig = req.header("x-binary-signature"); sig) { binary_signature = std::string{*sig}; } if (const auto key = req.header("x-binary-public-key"); key) { binary_public_key = std::string{*key}; } if (binary_signature.empty() != binary_public_key.empty()) { return HttpResponse::error_json( 400, "invalid_signature", "X-Binary-Signature and X-Binary-Public-Key must be provided together"); } auto is_hex = [](std::string_view text) { return std::ranges::all_of(text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }); }; if (!binary_signature.empty() && (binary_signature.size() != 128 || !is_hex(binary_signature))) { return HttpResponse::error_json(400, "invalid_signature", "X-Binary-Signature must be 128 hex characters"); } if (!binary_public_key.empty() && (binary_public_key.size() != 64 || !is_hex(binary_public_key))) { return HttpResponse::error_json(400, "invalid_signature", "X-Binary-Public-Key must be 64 hex characters"); } if (const auto bit = rit->second.binaries.find(variant_id); bit != rit->second.binaries.end()) { if (bit->second.sha256 == actual_sha) { return HttpResponse::json(200, "{\"status\":\"already_published\",\"sha256\":" + json_quote(actual_sha) + "}\n"); } return HttpResponse::error_json( 409, "immutable_conflict", "binary variant already exists with different content digest"); } Void::FileSystem::TempDir probe_tmp{"vbs_reg_binary_"}; const auto staged = probe_tmp / "binary"; if (auto w = Platform::atomic_write_file(staged, req.body, false); !w) { return HttpResponse::error_json(500, "stage_error", w.error().message()); } const auto dst_blob = blob_path(actual_sha); std::error_code ec; if (!std::filesystem::exists(dst_blob, ec)) { auto copied = Platform::copy_isolated(staged, dst_blob, 0444u); if (!copied) { return HttpResponse::error_json(500, "blob_publish_failed", copied.error().message()); } } BinaryReleaseMeta binary_meta; binary_meta.variant_id = variant_id; binary_meta.sha256 = actual_sha; binary_meta.size_bytes = req.body.size(); binary_meta.signature = binary_signature; binary_meta.public_key = binary_public_key; binary_meta.publisher = principal->username; binary_meta.published_epoch = now_epoch(); rit->second.binaries[variant_id] = std::move(binary_meta); append_audit_locked(principal->username, "binary.publish", pkg_name + "@" + ver_str + "/" + variant_id, "ok", "sha256=" + actual_sha); if (auto s = save_locked(); !s) { return HttpResponse::error_json(500, "metadata_commit_failed", s.error().message()); } return HttpResponse::json(201, "{\"variant_id\":" + json_quote(variant_id) + ",\"sha256\":" + json_quote(actual_sha) + "}\n"); } // Download a prebuilt binary variant: // GET /api/v1/packages///binaries//download if (segs.size() == 8 && segs[5] == "binaries" && segs[7] == "download" && req.method == "GET") { const auto pit = packages_.find(pkg_name); if (pit == packages_.end()) { return HttpResponse::error_json(404, "not_found", "package not found"); } if (!can_read_pkg(pit->second)) { return HttpResponse::error_json(principal ? 403 : 401, "forbidden", "private package requires authorization"); } const auto rit = pit->second.releases.find(segs[4]); if (rit == pit->second.releases.end()) { return HttpResponse::error_json(404, "not_found", "release not found"); } const auto bit = rit->second.binaries.find(segs[6]); if (bit == rit->second.binaries.end()) { return HttpResponse::error_json(404, "not_found", "binary variant not found"); } const auto bpath = blob_path(bit->second.sha256); auto bytes = Void::FileSystem::read_file_bounded(bpath, {256ULL * 1024ULL * 1024ULL}); if (!bytes || Util::sha256_hex(*bytes) != bit->second.sha256) { return HttpResponse::error_json(500, "integrity_error", "stored binary blob missing or corrupted"); } HttpResponse resp; resp.status = 200; resp.headers["Content-Type"] = "application/octet-stream"; resp.headers["X-Content-SHA256"] = bit->second.sha256; resp.body = std::move(*bytes); return resp; } // Yank/unyank a binary variant: // POST /api/v1/packages///binaries//yank if (segs.size() == 8 && segs[5] == "binaries" && segs[7] == "yank" && req.method == "POST") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } const auto pit = packages_.find(pkg_name); if (pit == packages_.end()) { return HttpResponse::error_json(404, "not_found", "package not found"); } if (!can_publish_pkg(&pit->second)) { return HttpResponse::error_json(403, "forbidden", "insufficient yank authority"); } const auto rit = pit->second.releases.find(segs[4]); if (rit == pit->second.releases.end()) { return HttpResponse::error_json(404, "not_found", "release not found"); } const auto bit = rit->second.binaries.find(segs[6]); if (bit == rit->second.binaries.end()) { return HttpResponse::error_json(404, "not_found", "binary variant not found"); } bool yanked = true; if (!req.body.empty()) { if (auto parsed = Void::Json::Strict::parse(req.body); parsed) { if (const auto *obj = std::get_if(&parsed->value)) { yanked = get_bool(*obj, "yanked", true); } } } bit->second.yanked = yanked; append_audit_locked(principal->username, yanked ? "binary.yank" : "binary.unyank", pkg_name + "@" + segs[4] + "/" + segs[6], "ok", ""); (void)save_locked(); return HttpResponse::json( 200, "{\"variant_id\":" + json_quote(segs[6]) + ",\"yanked\":" + std::string{yanked ? "true" : "false"} + "}\n"); } // Yank/unyank release: POST /api/v1/packages///yank if (segs.size() == 6 && segs[5] == "yank" && req.method == "POST") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } const auto pit = packages_.find(pkg_name); if (pit == packages_.end() || !pit->second.releases.contains(segs[4])) { return HttpResponse::error_json(404, "not_found", "release not found"); } if (!can_publish_pkg(&pit->second)) { return HttpResponse::error_json(403, "forbidden", "insufficient yank authority"); } bool yanked = true; if (!req.body.empty()) { if (auto parsed = Void::Json::Strict::parse(req.body); parsed) { if (const auto *obj = std::get_if(&parsed->value)) { yanked = get_bool(*obj, "yanked", true); } } } pit->second.releases.at(segs[4]).yanked = yanked; append_audit_locked(principal->username, yanked ? "package.yank" : "package.unyank", pkg_name + "@" + segs[4], "ok", ""); (void)save_locked(); return HttpResponse::json(200, "{\"yanked\":" + std::string{yanked ? "true" : "false"} + "}\n"); } } // Tokens API: GET/POST /api/v1/tokens, DELETE /api/v1/tokens/ if (segs.size() >= 3 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "tokens") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (req.method == "GET" && segs.size() == 3) { std::vector mine; for (const auto &[id, t] : tokens_) { if (principal->role == Role::Admin || t.username == principal->username) { mine.push_back(&t); } } return HttpResponse::json( 200, "{\"tokens\":" + json_array(mine, [](const ApiTokenRecord *t) { return "{\"token_id\":" + json_quote(t->token_id) + ",\"username\":" + json_quote(t->username) + ",\"label\":" + json_quote(t->label) + ",\"scopes\":" + json_array(t->scopes, json_quote) + ",\"revoked\":" + std::string{t->revoked ? "true" : "false"} + '}'; }) + "}\n"); } if (req.method == "POST" && segs.size() == 3) { if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } auto parsed = Void::Json::Strict::parse(req.body); const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; if (!obj) { return HttpResponse::error_json(400, "invalid_json", "expected JSON object"); } const std::string label = get_str(*obj, "label"); std::set scopes{"read"}; if (const auto *sv = find_key(*obj, "scopes")) { if (const auto *sarr = std::get_if(&sv->value)) { scopes.clear(); for (const auto &item : *sarr) { if (const auto *s = std::get_if(&item.value)) { // Prevent privilege escalation beyond caller's own role! if (*s == "admin" && principal->role != Role::Admin) { return HttpResponse::error_json(403, "privilege_escalation", "cannot mint admin token"); } if (*s == "publish" && principal->role == Role::Reader) { return HttpResponse::error_json(403, "privilege_escalation", "reader cannot mint publish token"); } scopes.insert(*s); } } } } const std::string plaintext = "vbs_tok_" + random_hex(24); ApiTokenRecord rec; rec.token_id = "tok_" + random_hex(8); rec.username = principal->username; rec.label = label; rec.token_sha256 = Util::sha256_hex(plaintext); rec.scopes = std::move(scopes); tokens_[rec.token_id] = rec; append_audit_locked(principal->username, "token.create", rec.token_id, "ok", label); (void)save_locked(); // Plaintext secret shown ONCE at creation only! return HttpResponse::json(201, "{\"token_id\":" + json_quote(rec.token_id) + ",\"token\":" + json_quote(plaintext) + "}\n"); } if (req.method == "DELETE" && segs.size() == 4) { if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } const auto tit = tokens_.find(segs[3]); if (tit == tokens_.end()) { return HttpResponse::error_json(404, "not_found", "token not found"); } if (principal->role != Role::Admin && tit->second.username != principal->username) { return HttpResponse::error_json(403, "forbidden", "cannot revoke another user's token"); } tit->second.revoked = true; append_audit_locked(principal->username, "token.revoke", segs[3], "ok", ""); (void)save_locked(); return HttpResponse::json(200, "{\"revoked\":true}\n"); } } // Admin endpoints: users, audit, storage. if (req.path == "/api/v1/users" || req.path == "/api/v1/audit" || req.path == "/api/v1/admin/storage") { if (!principal) { return HttpResponse::error_json(401, "unauthorized", "authentication required"); } if (principal->role != Role::Admin) { return HttpResponse::error_json(403, "forbidden", "admin role required"); } if (req.path == "/api/v1/users" && req.method == "GET") { std::vector ulist; for (const auto &[k, v] : users_) ulist.push_back(&v); return HttpResponse::json( 200, "{\"users\":" + json_array(ulist, [](const UserRecord *u) { return "{\"username\":" + json_quote(u->username) + ",\"role\":" + json_quote(role_name(u->role)) + ",\"active\":" + std::string{u->active ? "true" : "false"} + '}'; }) + "}\n"); } if (req.path == "/api/v1/users" && req.method == "POST") { if (!check_csrf_locked(req, *principal)) { return HttpResponse::error_json(403, "csrf_failed", "missing or invalid CSRF token"); } auto parsed = Void::Json::Strict::parse(req.body); const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; if (!obj) { return HttpResponse::error_json(400, "invalid_json", "expected JSON object"); } const auto uname = get_str(*obj, "username"); const auto pass = get_str(*obj, "password"); const auto role = parse_role(get_str(*obj, "role")); if (uname.empty() || pass.size() < 6) { return HttpResponse::error_json(400, "invalid_user", "username required and password >= 6 chars"); } UserRecord u; u.username = uname; u.role = role; u.password_salt_hex = random_hex(16); u.password_hash_hex = derive_password_hash(u.password_salt_hex, pass); users_[uname] = std::move(u); append_audit_locked(principal->username, "user.upsert", uname, "ok", std::string{role_name(role)}); (void)save_locked(); return HttpResponse::json(201, "{\"username\":" + json_quote(uname) + ",\"role\":" + json_quote(role_name(role)) + "}\n"); } if (req.path == "/api/v1/audit" && req.method == "GET") { return HttpResponse::json(200, "{\"audits\":" + json_array(audits_, [](const AuditEntry &a) { return "{\"timestamp\":" + std::to_string(a.timestamp) + ",\"actor\":" + json_quote(a.actor) + ",\"action\":" + json_quote(a.action) + ",\"target\":" + json_quote(a.target) + ",\"outcome\":" + json_quote(a.outcome) + ",\"detail\":" + json_quote(a.detail) + '}'; }) + "}\n"); } if (req.path == "/api/v1/admin/storage" && req.method == "GET") { return HttpResponse::json( 200, "{\"used_bytes\":" + std::to_string(total_storage_bytes_locked()) + ",\"quota_bytes\":" + std::to_string(config_.max_storage_bytes) + ",\"package_count\":" + std::to_string(packages_.size()) + "}\n"); } } return HttpResponse::error_json(404, "not_found", "unknown API endpoint"); } Void::Result::Result RegistryService::backup_to(const std::filesystem::path &backup_dir) { std::lock_guard lk{mu_}; std::error_code ec; std::filesystem::create_directories(backup_dir / "cas" / "blobs", ec); if (auto s = save_locked(); !s) { return std::unexpected{s.error()}; } if (auto c = Platform::copy_isolated(meta_file_, backup_dir / "metadata.v1.json"); !c) { return std::unexpected{c.error()}; } for (const auto &[pname, p] : packages_) { for (const auto &[ver, rel] : p.releases) { const auto src = blob_path(rel.sha256); const auto dst = backup_dir / "cas" / "blobs" / rel.sha256.substr(0, 2) / rel.sha256; if (std::filesystem::is_regular_file(src, ec) && !std::filesystem::exists(dst, ec)) { auto c = Platform::copy_isolated(src, dst, 0444u); if (!c) { return std::unexpected{c.error()}; } } } } return {}; } Void::Result::Result RegistryService::restore_from(const std::filesystem::path &backup_dir) { std::lock_guard lk{mu_}; const auto backup_meta = backup_dir / "metadata.v1.json"; std::error_code ec; if (!std::filesystem::is_regular_file(backup_meta, ec)) { return std::unexpected{ make_error(Void::System::SystemErrorCode::not_found, "backup metadata missing")}; } // Restore CAS blobs first, then replace metadata atomically. const auto src_blobs = backup_dir / "cas" / "blobs"; if (std::filesystem::is_directory(src_blobs, ec)) { for (const auto &ent : std::filesystem::recursive_directory_iterator(src_blobs, ec)) { if (ent.is_regular_file(ec)) { const auto rel = ent.path().lexically_relative(src_blobs); const auto dst = blobs_dir_ / rel; if (!std::filesystem::exists(dst, ec)) { auto c = Platform::copy_isolated(ent.path(), dst, 0444u); if (!c) { return std::unexpected{c.error()}; } } } } } auto copied = Platform::copy_isolated(backup_meta, meta_file_); if (!copied) { return std::unexpected{copied.error()}; } return load_locked(); } } // namespace Void::Build::Registry