From eb35bb6b6e1f07594c9ac9d64312aee96e9360a3 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 07:05:12 +0300 Subject: [PATCH] feat(package,daemon): list registry tokens; list daemon targets --- docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 8 ++ docs/roadmap/21-expansion-roadmap.md | 2 +- include/Void/Build/Package/RegistryClient.hpp | 13 +++ src/Daemon/Daemon.cpp | 69 +++++++++++++- src/Main.cpp | 71 +++++++++++--- src/Package/RegistryClient.cpp | 67 +++++++++++++ tests/CliContracts.cmake | 2 + tests/DaemonTests.cpp | 94 +++++++++++++++++++ tests/RegistryTests.cpp | 15 ++- 11 files changed, 326 insertions(+), 18 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index feb27e9..472a835 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -255,6 +255,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 81 (Registry Stats & Daemon `doctor`)**: added the admin `GET /api/v1/stats` endpoint (package/release/yanked/binary/user/audit counts, ETag-validated) covered in the RBAC test (admin 200 with ETag, non-admin 403). A swarm worker added the structured `doctor` daemon request (host/tool/backends JSON) with `Daemon.doctor_reports_host_tools_and_backends` (5/5 substantive tasks; build task stopped and re-run). +- **Wave 82 (Tokens Listing & Daemon `target_list`)**: added `Package::fetch_tokens` and `vbs tokens list --registry` (token id, label, user, scopes, active/revoked; the plaintext secret is never listed), covered in the CLI E2E. A swarm worker added the `target_list` daemon request (sorted name/kind/enabled with limit and member support) and its test (5/5 tasks, including its own verification). + ## Remaining future scope - **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track C (macOS/Windows ports + dual-profile cross-compilation) and dedicated external editor plugins remain planned; Track D3 signing (SBOM, Ed25519 primitives, trusted-key enforcement/distribution, binary-variant signing/distribution) and Track E3 daemon capabilities are implemented, and Track E4 now uses `Void::Net` for the registry client/server and remote cache plus `Void::Sqlite` for the StateStore when available. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 1f2e0a1..920b77a 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -85,4 +85,5 @@ Base HEAD: `fe0d1a6` | Wave 79 (Registry metadata PATCH + workspace_info) | `PATCH /api/v1/packages/` for description/private (audited); swarm added daemon `workspace_info` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 8/8, Daemon suite passes, full CTest 8/8) | `registry/service/RegistryService.cpp`, `src/Daemon/Daemon.cpp`, `tests/{RegistryTests,DaemonTests}.cpp`, docs | | Wave 80 (Watch prefix + registry OPTIONS) | daemon watch `prefix` filter retaining non-matching events; swarm added registry OPTIONS 204 + Allow | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 9/9, Daemon suite passes, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `registry/service/RegistryService.cpp`, `tests/{DaemonTests,RegistryTests}.cpp`, docs | | Wave 81 (Registry stats + daemon doctor) | admin `GET /api/v1/stats` with ETag; swarm added daemon `doctor` diagnostics | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 9/9, Daemon suite passes, full CTest 8/8) | `registry/service/RegistryService.cpp`, `src/Daemon/Daemon.cpp`, `tests/{RegistryTests,DaemonTests}.cpp`, docs | +| Wave 82 (Tokens list + target_list) | `fetch_tokens`/`vbs tokens list`; swarm added daemon `target_list` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 9/9, Daemon suite passes, full CTest 8/8) | `include/Void/Build/Package/RegistryClient.hpp`, `src/Package/RegistryClient.cpp`, `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/{RegistryTests,DaemonTests}.cpp`, `tests/CliContracts.cmake`, docs | | Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions) |"}] Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 5159bd9..186bc37 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1235,6 +1235,14 @@ dev cpp-gcc -c build/pinned/bin/vbs_v1_tests --suite Daemon --no-color `Daemon.doctor_reports_host_tools_and_backends` passes (19 ms). - Registry suite: **9 / 9 passed** (11.76 s); full CTest: **8 / 8 passed** in 256.63 s. +## Tokens Listing & Daemon `target_list` (GCC 16.2, pin `0002e74`) + +- `vbs tokens list --registry ... --token-env ...` prints the caller's token metadata (`ci_pub`, + `active`) and never the plaintext secret (live E2E). +- Swarm `swarm_mx8g40db_mi02` (one worker) added the daemon `target_list` request and its test, + completing its own verification (5/5 tasks); `target_list_reports_targets` passes (2.48 s). +- Registry suite: **9 / 9 passed** (12.02 s); full CTest: **8 / 8 passed** in 262.80 s. + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index 48eb366..6055f50 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -73,7 +73,7 @@ flowchart LR | --- | --- | --- | | **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. | | **E2 — Multi-Package Workspaces (`workspace.cpp`)** *(verified in Docker GCC 16)* | Shared root `vbs.lock` and `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, and affected-member selection (`vbs build/test --member ` / `--changed-since `). | 3-package workspace fixture (shared library + app + tests) builds/tests with one root lockfile; member selection and `--changed-since` verified in `FullV1Tests.workspace_members_shared_build_and_member_selection`. | -| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover\|describe` (**Implemented & Verified in Wave 14; bounded `describe` added in the post-v1 daemon follow-up**). `describe` returns a bounded graph summary (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout); `vbs daemon build` executes the lowered graph in-process against the warm state store with bounded `profile`/`targets`/`jobs`, including daemon-side dependency resolution/materialization and provider import via `Package::resolve_and_materialize_dependencies`; `vbs daemon ide query` publishes/selects the profile compilation database and serves the IDE workspace/target metadata JSON over the socket, `vbs daemon compdb export` returns the published compilation-database path and entry count, `vbs daemon ide generate` writes the editor presets over the socket, `vbs daemon ide poll` exposes a bounded editor-extension watch protocol (changed paths, sequence, overflow state), `vbs daemon ide wait` adds a bounded long-poll variant, `vbs daemon ide status` reports the active editor selection and compdb state, watch requests can be filtered by path prefix, registry endpoints answer OPTIONS with an Allow header and expose admin stats, the daemon serves structured `doctor` diagnostics, `vbs daemon compdb use` switches the active editor profile under the selection lock, `vbs daemon graph` exports the target dependency graph (DOT/JSON), `vbs daemon test` builds and runs declared test targets, `vbs daemon clean` removes generated outputs while preserving the shared cache, `vbs daemon target info` reports per-target sources/outputs, `vbs daemon actions` lists bounded lowered actions, `vbs daemon pack` creates a confined deterministic source archive, `vbs daemon install` stages an install prefix (and `uninstall` removes only manifest-owned files), `vbs daemon gen-tests` generates the native test registration unit, `vbs daemon init` scaffolds confined projects, `vbs daemon compdb entries` serves bounded per-file compile arguments to editor extensions, `vbs daemon workspace members` lists workspace members cheaply, `vbs daemon ide configs` reports which editor configuration files exist, `vbs daemon compdb generations` lists editor generation history with the active selection, `vbs daemon info` exposes the daemon environment, `vbs daemon deps` resolves/materializes dependencies over the socket, registry package search and audit queries support bounded pagination/filters, releases expose a version-specific detail endpoint, package ownership and mutable metadata are managed through audited APIs, and `RegistryClient::fetch_package_owners` reads owners. Daemon workspace support describes members, builds all members in order (or a selected member) with the shared root lock, and serves member-scoped IDE query/generate/compdb requests via `--member`. Dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown/describe verified in `DaemonTests.cpp` (6/6 under `dev cpp-gcc`); the live `vbs daemon describe` CLI round-trip is verified in `vbs_cli_contract`. | +| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover\|describe` (**Implemented & Verified in Wave 14; bounded `describe` added in the post-v1 daemon follow-up**). `describe` returns a bounded graph summary (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout); `vbs daemon build` executes the lowered graph in-process against the warm state store with bounded `profile`/`targets`/`jobs`, including daemon-side dependency resolution/materialization and provider import via `Package::resolve_and_materialize_dependencies`; `vbs daemon ide query` publishes/selects the profile compilation database and serves the IDE workspace/target metadata JSON over the socket, `vbs daemon compdb export` returns the published compilation-database path and entry count, `vbs daemon ide generate` writes the editor presets over the socket, `vbs daemon ide poll` exposes a bounded editor-extension watch protocol (changed paths, sequence, overflow state), `vbs daemon ide wait` adds a bounded long-poll variant, `vbs daemon ide status` reports the active editor selection and compdb state, watch requests can be filtered by path prefix, registry endpoints answer OPTIONS with an Allow header and expose admin stats, the daemon serves structured `doctor` diagnostics, `vbs daemon compdb use` switches the active editor profile under the selection lock, `vbs daemon graph` exports the target dependency graph (DOT/JSON), `vbs daemon test` builds and runs declared test targets, `vbs tokens list` inspects registry token metadata, `vbs daemon clean` removes generated outputs while preserving the shared cache, `vbs daemon target info` reports per-target sources/outputs, `vbs daemon actions` lists bounded lowered actions, `vbs daemon pack` creates a confined deterministic source archive, `vbs daemon install` stages an install prefix (and `uninstall` removes only manifest-owned files), `vbs daemon gen-tests` generates the native test registration unit, `vbs daemon init` scaffolds confined projects, `vbs daemon compdb entries` serves bounded per-file compile arguments to editor extensions, `vbs daemon workspace members` lists workspace members cheaply, `vbs daemon ide configs` reports which editor configuration files exist, `vbs daemon compdb generations` lists editor generation history with the active selection, `vbs daemon info` exposes the daemon environment, `vbs daemon deps` resolves/materializes dependencies over the socket, registry package search and audit queries support bounded pagination/filters, releases expose a version-specific detail endpoint, package ownership and mutable metadata are managed through audited APIs, and `RegistryClient::fetch_package_owners` reads owners. Daemon workspace support describes members, builds all members in order (or a selected member) with the shared root lock, and serves member-scoped IDE query/generate/compdb requests via `--member`. Dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown/describe verified in `DaemonTests.cpp` (6/6 under `dev cpp-gcc`); the live `vbs daemon describe` CLI round-trip is verified in `vbs_cli_contract`. | | **E4 — Transport & Storage Upstream Alignment** *(Sqlite and Net client adopted)* | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. `Void::Sqlite` backs the `StateStore` when SQLite3 is present, `Void::Net` backs the `RegistryClient`, remote-cache, and registry-server HTTP transports (TLS-verifying `HttpClient`/`HttpServer`) when `Net` is enabled (`-p openssl -p boost`), keeping the pure-POSIX fallbacks. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains (verified: registry 7/7 on the Net transport; default and SQLite builds 8/8). | --- diff --git a/include/Void/Build/Package/RegistryClient.hpp b/include/Void/Build/Package/RegistryClient.hpp index b43fb40..df0c848 100644 --- a/include/Void/Build/Package/RegistryClient.hpp +++ b/include/Void/Build/Package/RegistryClient.hpp @@ -36,6 +36,19 @@ struct PublishReceipt { bool already_published{false}; }; +struct TokenInfo { + std::string token_id; + std::string username; + std::string label; + std::vector scopes; + bool revoked{false}; +}; + +// Lists the caller's (or, for admins, all) API token metadata from GET /api/v1/tokens. +// The plaintext secret is never returned by the registry after creation. +[[nodiscard]] Void::Result::Result, Void::Result::Error> +fetch_tokens(std::string_view registry_url, const RegistryAuth &auth = {}); + // Queries GET /api/v1/packages/ on a VBS registry and parses all release records // into Package::ReleaseRecord entries ready for PackageIndex + PubGrub solving. [[nodiscard]] Void::Result::Result, Void::Result::Error> diff --git a/src/Daemon/Daemon.cpp b/src/Daemon/Daemon.cpp index 628b28e..2977c4a 100644 --- a/src/Daemon/Daemon.cpp +++ b/src/Daemon/Daemon.cpp @@ -1367,6 +1367,58 @@ std::string target_info_project(const DaemonOptions &options, std::string_view p return serialize_response(JsonValue{std::move(object)}); } +// Lists every lowered target's name, kind and enabled state (bounded). +std::string target_list_project(const DaemonOptions &options, std::string_view profile_name, + std::optional compiler_override, std::size_t limit, + std::string_view member) { + auto effective_result = resolve_member_options(options, member); + if (!effective_result) { + return error_response(std::format("target_list: {}", effective_result.error())); + } + auto evaluated = + evaluate_project_graph(*effective_result, profile_name, compiler_override, "target_list"); + if (!evaluated) { + return error_response(evaluated.error()); + } + auto graph = lower_graph(*effective_result, *evaluated, {}, "target_list"); + if (!graph) { + return error_response(graph.error()); + } + + std::vector ordered; + ordered.reserve(graph->targets.size()); + for (const auto &target : graph->targets) { + ordered.push_back(&target); + } + std::ranges::sort(ordered, + [](const auto *lhs, const auto *rhs) { return lhs->name < rhs->name; }); + + JsonValue::Array targets; + for (const auto *target : ordered) { + if (targets.size() >= limit) { + break; + } + std::string name = target->name; + if (name.size() > kMaxDescribeTargetNameBytes) { + name.resize(kMaxDescribeTargetNameBytes); + } + JsonValue::Object entry; + entry.emplace("name", JsonValue{std::move(name)}); + entry.emplace("kind", JsonValue{std::string{target_kind_name(target->kind)}}); + entry.emplace("enabled", JsonValue{target->enabled}); + targets.emplace_back(std::move(entry)); + } + + JsonValue::Object object; + object.emplace("ok", JsonValue{true}); + object.emplace("op", JsonValue{std::string{"target_list"}}); + object.emplace("profile", JsonValue{evaluated->context.name}); + object.emplace("total", JsonValue{static_cast(graph->targets.size())}); + object.emplace("returned", JsonValue{static_cast(targets.size())}); + object.emplace("targets", JsonValue{std::move(targets)}); + return serialize_response(JsonValue{std::move(object)}); +} + // Lists the lowered graph's actions (bounded) for editor extensions and diagnostics. std::string actions_project(const DaemonOptions &options, std::string_view profile_name, std::optional compiler_override, @@ -2465,7 +2517,7 @@ DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view if (*name == "describe" || *name == "build" || *name == "test" || *name == "ide_query" || *name == "ide_generate" || *name == "compdb_export" || *name == "graph" || *name == "deps" || *name == "target_info" || *name == "target_flags" || - *name == "actions" || *name == "install") { + *name == "target_list" || *name == "actions" || *name == "install") { std::string profile_name{"debug"}; if (const auto entry = object->find("profile"); entry != object->end()) { const auto *value = std::get_if(&entry->second.value); @@ -2611,6 +2663,21 @@ DaemonServer::Impl::DispatchResult DaemonServer::Impl::dispatch(std::string_view kind_filter, limit, member), false}; } + if (*name == "target_list") { + std::size_t limit = 200; + if (const auto entry = object->find("limit"); entry != object->end()) { + const auto *value = std::get_if(&entry->second.value); + if (value == nullptr || *value < 0 || + *value > static_cast(kMaxActionLimit)) { + return {error_response(std::format("\"limit\" must be an integer in [0, {}]", + kMaxActionLimit)), + false}; + } + limit = static_cast(*value); + } + return {target_list_project(options, profile_name, compiler_override, limit, member), + false}; + } if (*name == "target_info" || *name == "target_flags") { const auto entry = object->find("target"); if (entry == object->end()) { diff --git a/src/Main.cpp b/src/Main.cpp index 1f25444..09915c6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1154,6 +1154,36 @@ int execute_publish_binary_command(const PublishBinaryCmdOptions &opts) { return 0; } +struct TokensCmdOptions { + std::optional registry_arg; + std::string token_env{"VBS_REGISTRY_TOKEN"}; +}; + +int execute_tokens_list_command(const TokensCmdOptions &opts) { + const std::string registry_url = opts.registry_arg + ? *opts.registry_arg + : Void::Configuration::get_env_or("VBS_REGISTRY_URL", ""); + if (registry_url.empty()) { + std::cerr << "vbs tokens list: --registry is required\n"; + return 2; + } + Package::RegistryAuth auth{Void::Configuration::get_env_or(opts.token_env, "")}; + auto tokens = Package::fetch_tokens(registry_url, auth); + if (!tokens) { + std::cerr << "vbs tokens: " << tokens.error().message() << '\n'; + return 1; + } + for (const auto &token : *tokens) { + std::cout << token.token_id << ' ' << (token.label.empty() ? "-" : token.label) << ' ' + << token.username << ' '; + for (std::size_t i = 0; i < token.scopes.size(); ++i) { + std::cout << (i > 0 ? "," : "") << token.scopes[i]; + } + std::cout << ' ' << (token.revoked ? "revoked" : "active") << '\n'; + } + return 0; +} + struct ReleasesCmdOptions { std::optional registry_arg; std::optional name_arg; @@ -1659,12 +1689,12 @@ int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) { Util::json_quote(opts.profile_arg), Util::json_quote(opts.graph_format_arg)); } else if (sub == "actions") { - request_json = std::format( - R"({{"op":"actions","profile":{},"limit":{}{}}})", Util::json_quote(opts.profile_arg), - opts.limit_arg, - opts.action_kind_arg - ? std::format(",\"kind\":{}", Util::json_quote(*opts.action_kind_arg)) - : std::string{}); + request_json = + std::format(R"({{"op":"actions","profile":{},"limit":{}{}}})", + Util::json_quote(opts.profile_arg), opts.limit_arg, + opts.action_kind_arg + ? std::format(",\"kind\":{}", Util::json_quote(*opts.action_kind_arg)) + : std::string{}); } else if (sub == "target_flags") { if (!opts.target_arg || opts.target_arg->empty()) { std::cerr << "vbs daemon target flags: --name must not be empty\n"; @@ -1747,11 +1777,9 @@ int execute_daemon_command(std::string_view sub, const DaemonCmdOptions &opts) { ? std::format(",\"file\":{}", Util::json_quote(*opts.file_filter_arg)) : std::string{}); } else if (sub == "watch_poll") { - request_json = - opts.prefix_arg - ? std::format(R"({{"op":"watch_poll","prefix":{}}})", - Util::json_quote(*opts.prefix_arg)) - : std::string{R"({"op":"watch_poll"})"}; + request_json = opts.prefix_arg ? std::format(R"({{"op":"watch_poll","prefix":{}}})", + Util::json_quote(*opts.prefix_arg)) + : std::string{R"({"op":"watch_poll"})"}; } else if (sub == "watch_wait") { std::int64_t timeout_ms = 0; const auto [ptr, ec] = @@ -2389,6 +2417,7 @@ int main(int argc, char **argv) { PublishBinaryCmdOptions publish_binary_opts; BinariesCmdOptions binaries_opts; ReleasesCmdOptions releases_opts; + TokensCmdOptions tokens_opts; publish_opts.project_arg = cwd; BridgeCmdOptions bridge_opts; GcCmdOptions gc_opts; @@ -2552,6 +2581,15 @@ int main(int argc, char **argv) { publish_binary_opts.token_env, "VBS_REGISTRY_TOKEN"); add_log_flags(publish_binary_cmd, false); // `-v` is `--version` on publish-binary. + auto &tokens_cmd = root.subcommand("tokens", "Inspect API tokens in a package registry"); + auto &tokens_list_cmd = tokens_cmd.subcommand("list", "List token metadata"); + tokens_list_cmd + .option("--registry", "-r", "Registry base URL (or VBS_REGISTRY_URL)", + tokens_opts.registry_arg) + .option_default("--token-env", "", "Environment variable holding bearer token", + tokens_opts.token_env, "VBS_REGISTRY_TOKEN"); + add_log_flags(tokens_list_cmd); + auto &releases_cmd = root.subcommand("releases", "List published releases in a package registry"); auto &releases_list_cmd = releases_cmd.subcommand("list", "List a package's releases"); @@ -2838,9 +2876,9 @@ int main(int argc, char **argv) { daemon_cmd.subcommand("actions", "List lowered build actions via the daemon"); configure_daemon_common(daemon_actions_cmd); daemon_actions_cmd - .option_default("--profile", "-p", "Profile to evaluate", daemon_opts.profile_arg, - "debug") - .option("--kind", "", "Only actions of this kind (compile|link|archive|...)", daemon_opts.action_kind_arg) + .option_default("--profile", "-p", "Profile to evaluate", daemon_opts.profile_arg, "debug") + .option("--kind", "", "Only actions of this kind (compile|link|archive|...)", + daemon_opts.action_kind_arg) .option_default("--limit", "", "Maximum actions returned (0-1000)", daemon_opts.limit_arg, "100"); auto &daemon_graph_cmd = @@ -2871,7 +2909,7 @@ int main(int argc, char **argv) { "poll", "Poll pending project file changes (editor extension protocol)"); configure_daemon_common(daemon_ide_poll_cmd); daemon_ide_poll_cmd.option("--prefix", "", "Only report changed paths under this prefix", - daemon_opts.prefix_arg); + daemon_opts.prefix_arg); auto &daemon_ide_wait_cmd = daemon_ide_cmd.subcommand( "wait", "Long-poll for project file changes (bounded, editor extension protocol)"); configure_daemon_common(daemon_ide_wait_cmd); @@ -2969,6 +3007,9 @@ int main(int argc, char **argv) { } return execute_releases_list_command(releases_opts); } + if (cmd == "tokens") { + return execute_tokens_list_command(tokens_opts); + } if (cmd == "bridge") { return execute_bridge_command(bridge_opts); } diff --git a/src/Package/RegistryClient.cpp b/src/Package/RegistryClient.cpp index 0ce3d72..a349bc0 100644 --- a/src/Package/RegistryClient.cpp +++ b/src/Package/RegistryClient.cpp @@ -675,6 +675,73 @@ fetch_package_owners(std::string_view registry_url, std::string_view package_nam return owners; } +Void::Result::Result, Void::Result::Error> +fetch_tokens(std::string_view registry_url, const RegistryAuth &auth) { + auto parsed_url = parse_registry_url(registry_url); + if (!parsed_url) { + return std::unexpected{parsed_url.error()}; + } + std::map> headers; + if (!auth.bearer_token.empty()) { + headers["Authorization"] = "Bearer " + auth.bearer_token; + } + auto reply = send_http_request(*parsed_url, "GET", "/api/v1/tokens", headers, {}); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status != 200) { + return std::unexpected{make_error( + reply->status == 401 || reply->status == 403 + ? Void::System::SystemErrorCode::permission_denied + : Void::System::SystemErrorCode::io_error, + std::format("registry GET /api/v1/tokens failed with HTTP {}", reply->status))}; + } + auto json = Void::Json::Strict::parse(reply->body); + if (!json) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "invalid JSON returned by registry tokens endpoint")}; + } + const auto *root = std::get_if(&json->value); + if (!root) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "registry response root must be a JSON object")}; + } + std::vector tokens; + const auto tit = root->find("tokens"); + if (tit == root->end()) { + return tokens; + } + const auto *array = std::get_if(&tit->second.value); + if (!array) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "registry tokens field must be a JSON array")}; + } + for (const auto &entry : *array) { + const auto *object = std::get_if(&entry.value); + if (!object) { + continue; + } + TokenInfo info; + info.token_id = get_str(*object, "token_id"); + info.username = get_str(*object, "username"); + info.label = get_str(*object, "label"); + info.revoked = get_bool(*object, "revoked", false); + if (const auto sit = object->find("scopes"); sit != object->end()) { + if (const auto *scopes = std::get_if(&sit->second.value)) { + for (const auto &scope : *scopes) { + if (const auto *text = std::get_if(&scope.value)) { + info.scopes.push_back(*text); + } + } + } + } + if (!info.token_id.empty()) { + tokens.push_back(std::move(info)); + } + } + return tokens; +} + Void::Result::Result download_binary_artifact(std::string_view url, std::string_view expected_sha256, const std::filesystem::path &dest_file, const RegistryAuth &auth) { diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 2e95188..7be6cde 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -50,6 +50,8 @@ check_process(0 "Usage: vbs publish-binary " "" publish-binary --help) check_process(0 "Usage: vbs binaries .*Commands:.*list.*fetch" "" binaries --help) check_process(0 "Usage: vbs binaries list " "" binaries list --help) check_process(0 "Usage: vbs releases list " "" releases list --help) +check_process(0 "Usage: vbs tokens list " "" tokens list --help) +check_process(2 "" "vbs tokens list: --registry is required" tokens list) check_process(2 "" "--registry and --name are required" releases list) check_process(0 "Usage: vbs releases show " "" releases show --help) check_process(2 "" "--registry, --name, and --version are required" releases show) diff --git a/tests/DaemonTests.cpp b/tests/DaemonTests.cpp index d761af9..15bc464 100644 --- a/tests/DaemonTests.cpp +++ b/tests/DaemonTests.cpp @@ -2337,6 +2337,100 @@ void build(Void::Build::Project &project) { Void::Testing::expect(!bool_field(*unknown, "ok", true)); } +VOID_TEST(Daemon, target_list_reports_targets) { + auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); + Void::Testing::require(temp.has_value()); + const auto options = make_options(temp->path()); + + { + std::ofstream descriptor{options.project_root / "build.cpp"}; + descriptor << R"cpp(#include + +void build(Void::Build::Project &project) { + auto app = project.executable("app"); + app.sources({"main.cpp"}); + auto lib = project.static_library("lib"); + lib.sources({"lib.cpp"}); +} +)cpp"; + Void::Testing::require(descriptor.good()); + } + { + std::ofstream source{options.project_root / "main.cpp"}; + source << "int main() { return 0; }\n"; + Void::Testing::require(source.good()); + } + { + std::ofstream source{options.project_root / "lib.cpp"}; + source << "int lib_value() { return 0; }\n"; + Void::Testing::require(source.good()); + } + + auto server = Void::Build::Daemon::DaemonServer::create(options); + Void::Testing::require(server.has_value()); + const auto socket = server->socket_path(); + + Void::Result::Result run_result; + std::jthread worker{[&] { run_result = server->run(); }}; + Void::Testing::require(wait_for_path(socket, std::chrono::seconds{5})); + + auto listed = request_object(socket, R"({"op":"target_list"})", std::chrono::seconds{120}); + auto bounded = + request_object(socket, R"({"op":"target_list","limit":1})", std::chrono::seconds{120}); + auto invalid = request_object(socket, R"({"op":"target_list","limit":1001})"); + auto invalid_type = request_object(socket, R"({"op":"target_list","limit":"x"})"); + auto empty = request_object(socket, R"({"op":"target_list","limit":0})"); + auto unknown_member = request_object(socket, R"({"op":"target_list","member":"nope"})"); + auto shutdown = Void::Build::Daemon::request(socket, R"({"op":"shutdown"})"); + Void::Testing::expect(shutdown.has_value()); + worker.join(); + Void::Testing::expect(run_result.has_value()); + + Void::Testing::require(listed.has_value()); + Void::Testing::expect(bool_field(*listed, "ok")); + Void::Testing::expect_eq(str_field(*listed, "op"), std::string{"target_list"}); + Void::Testing::expect(int_field(*listed, "total") >= 1); + Void::Testing::expect(int_field(*listed, "returned") == int_field(*listed, "total")); + const auto *targets = field(*listed, "targets"); + Void::Testing::require(targets != nullptr); + const auto *target_array = std::get_if(&targets->value); + Void::Testing::require(target_array != nullptr && !target_array->empty()); + bool found_app = false; + bool found_lib = false; + for (const auto &item : *target_array) { + const auto *entry = std::get_if(&item.value); + Void::Testing::require(entry != nullptr); + if (str_field(*entry, "name") == "app") { + found_app = true; + Void::Testing::expect_eq(str_field(*entry, "kind"), std::string{"executable"}); + Void::Testing::expect(bool_field(*entry, "enabled")); + } + if (str_field(*entry, "name") == "lib") { + found_lib = true; + Void::Testing::expect_eq(str_field(*entry, "kind"), std::string{"static_library"}); + Void::Testing::expect(bool_field(*entry, "enabled")); + } + } + Void::Testing::expect(found_app); + Void::Testing::expect(found_lib); + + Void::Testing::require(bounded.has_value()); + Void::Testing::expect(bool_field(*bounded, "ok")); + Void::Testing::expect_eq(int_field(*bounded, "returned"), std::int64_t{1}); + Void::Testing::expect(int_field(*bounded, "total") >= 2); + + Void::Testing::require(empty.has_value()); + Void::Testing::expect(bool_field(*empty, "ok")); + Void::Testing::expect_eq(int_field(*empty, "returned"), std::int64_t{0}); + + Void::Testing::require(invalid.has_value()); + Void::Testing::expect(!bool_field(*invalid, "ok", true)); + Void::Testing::require(invalid_type.has_value()); + Void::Testing::expect(!bool_field(*invalid_type, "ok", true)); + Void::Testing::require(unknown_member.has_value()); + Void::Testing::expect(!bool_field(*unknown_member, "ok", true)); +} + VOID_TEST(Daemon, describe_empty_project_reports_zero_targets) { auto temp = Void::FileSystem::TempDir::open("vbs_daemon_"); Void::Testing::require(temp.has_value()); diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index 718a646..b713645 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -521,7 +521,7 @@ VOID_TEST(RegistryTests, registry_rbac_immutability_csrf_xss_web_and_backup_rest Void::Testing::expect(stats->headers.contains("etag")); } auto stats_non_admin = send_loopback_http(port, "GET", "/api/v1/stats", - {{"Authorization", "Bearer " + *alice_tok}}); + {{"Authorization", "Bearer " + *alice_tok}}); Void::Testing::expect(stats_non_admin.has_value() && stats_non_admin->status == 403); auto bad_limit_text = send_loopback_http(port, "GET", "/api/v1/packages?limit=abc"); @@ -1318,6 +1318,19 @@ target_include_directories(hello_pkg PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include auto trusted_binary_res = Platform::run_supervised(trusted_fetch); Void::Testing::expect(trusted_binary_res.has_value() && !trusted_binary_res->succeeded()); + Platform::ProcessRequest tokens_list; + tokens_list.executable = vbs_bin; + tokens_list.arguments = {"tokens", "list", "--registry", reg_url}; + tokens_list.environment.set_vars["VBS_REGISTRY_TOKEN"] = *tok; + auto tokens_res = Platform::run_supervised(tokens_list); + Void::Testing::expect(tokens_res.has_value() && tokens_res->succeeded()); + if (tokens_res) { + Void::Testing::expect(tokens_res->stdout_data.find("ci_pub") != std::string::npos); + Void::Testing::expect(tokens_res->stdout_data.find("active") != std::string::npos); + // The plaintext secret must never be listed. + Void::Testing::expect(tokens_res->stdout_data.find(*tok) == std::string::npos); + } + Platform::ProcessRequest releases_list; releases_list.executable = vbs_bin; releases_list.arguments = {"releases", "list", "--registry", reg_url, "--name", "hello-pkg"};