From ba749b9e475fe7d45d9d142086a0d9534f6c859c Mon Sep 17 00:00:00 2001 From: Clusterflux release Date: Sat, 25 Jul 2026 17:53:21 +0200 Subject: [PATCH] Public release source-69fccd306838 Source commit: 69fccd306838141ba9b1730f4ac4afb1a617bb4e Public tree identity: sha256:8c03637496d3f7ee1b625aa1c823cd69bfcf0247a061d8cb571e05d537329691 --- .gitignore | 4 - CLUSTERFLUX_PUBLIC_TREE.json | 22 - Cargo.toml | 3 +- README.md | 56 +- SECURITY.md | 2 +- crates/clusterflux-cli/src/admin.rs | 24 +- crates/clusterflux-cli/src/auth.rs | 12 +- crates/clusterflux-cli/src/auth_scope.rs | 2 +- crates/clusterflux-cli/src/config.rs | 3 +- crates/clusterflux-cli/src/debug.rs | 6 +- crates/clusterflux-cli/src/errors.rs | 5 +- crates/clusterflux-cli/src/node.rs | 4 +- crates/clusterflux-cli/src/output.rs | 8 +- crates/clusterflux-cli/src/process_events.rs | 4 +- crates/clusterflux-cli/src/project.rs | 12 +- crates/clusterflux-cli/src/quota.rs | 4 +- crates/clusterflux-cli/src/run.rs | 4 +- crates/clusterflux-cli/src/tests.rs | 75 +- crates/clusterflux-coordinator/src/lib.rs | 2 +- .../src/service/protocol/responses.rs | 2 +- .../src/service/routing.rs | 4 +- .../src/service/tests.rs | 12 +- crates/clusterflux-dap/src/tests.rs | 58 +- crates/clusterflux-dap/src/virtual_model.rs | 2 +- crates/clusterflux-node/src/daemon.rs | 9 +- crates/clusterflux-node/src/lib.rs | 2 +- docs/contributing/releases.md | 60 - docs/getting-started.md | 2 +- docs/nodes.md | 2 +- scripts/acceptance-private.sh | 27 - scripts/acceptance-public.sh | 54 - scripts/agent-signing.js | 99 - scripts/artifact-download-smoke.js | 401 - scripts/artifact-export-smoke.js | 275 - scripts/check-code-size.sh | 27 - scripts/check-docs.js | 113 - scripts/check-old-name.sh | 39 - scripts/cli-browser-login-flow-smoke.js | 222 - scripts/cli-error-exit-smoke.js | 365 - scripts/cli-happy-path-live-smoke.js | 7128 ----------------- scripts/cli-install-smoke.js | 61 - scripts/cli-local-run-smoke.js | 269 - scripts/cli-login-smoke.js | 72 - scripts/cli-output-mode-smoke.js | 191 - scripts/coordinator-wire.js | 43 - scripts/dap-client.js | 135 - scripts/dap-smoke.js | 510 -- scripts/deploy-release-candidate.sh | 83 - scripts/flagship-demo-smoke.js | 80 - scripts/hostile-input-contract-smoke.js | 235 - scripts/migrate-clusterflux-state.sh | 22 - scripts/node-attach-smoke.js | 307 - scripts/node-lifecycle-contract-smoke.js | 151 - scripts/node-signing.js | 181 - scripts/operator-panel-smoke.js | 385 - scripts/podman-backend-smoke.js | 86 - scripts/podman-test-env.js | 41 - scripts/prepare-public-release.js | 1283 --- scripts/private-repository-gate.sh | 14 - scripts/public-local-demo-matrix-smoke.js | 69 - scripts/public-release-preflight.js | 451 -- scripts/public-repository-gate.sh | 7 - scripts/publish-public-release.js | 354 - scripts/quic-smoke.js | 154 - scripts/real-flagship-harness.js | 285 - scripts/recovery-build-smoke.js | 139 - scripts/release-quality-gates.js | 322 - scripts/release-source-scan.sh | 73 - scripts/resource-metering-contract-smoke.js | 230 - scripts/scheduler-placement-smoke.js | 400 - scripts/sdk-spawn-runtime-smoke.js | 48 - scripts/self-hosted-coordinator-smoke.js | 666 -- scripts/source-preparation-smoke.js | 221 - scripts/tenant-isolation-contract-smoke.js | 197 - scripts/user-session-token-boundary-smoke.js | 120 - scripts/verify-public-split.sh | 72 - scripts/vscode-extension-smoke.js | 233 - scripts/vscode-f5-smoke.js | 321 - scripts/wasmtime-assignment-smoke.js | 44 - scripts/wasmtime-node-smoke.js | 172 - scripts/windows-best-effort-smoke.js | 301 - scripts/windows-runner-smoke.js | 479 -- tests/fixtures/runtime-conformance/Cargo.toml | 16 - tests/fixtures/runtime-conformance/README.md | 5 - .../envs/linux/Containerfile | 3 - .../envs/windows/Dockerfile | 2 - .../fixture/hello-clusterflux.c | 6 - tests/fixtures/runtime-conformance/src/lib.rs | 501 -- 88 files changed, 204 insertions(+), 18991 deletions(-) delete mode 100644 CLUSTERFLUX_PUBLIC_TREE.json delete mode 100644 docs/contributing/releases.md delete mode 100755 scripts/acceptance-private.sh delete mode 100755 scripts/acceptance-public.sh delete mode 100644 scripts/agent-signing.js delete mode 100755 scripts/artifact-download-smoke.js delete mode 100644 scripts/artifact-export-smoke.js delete mode 100755 scripts/check-code-size.sh delete mode 100644 scripts/check-docs.js delete mode 100755 scripts/check-old-name.sh delete mode 100644 scripts/cli-browser-login-flow-smoke.js delete mode 100755 scripts/cli-error-exit-smoke.js delete mode 100644 scripts/cli-happy-path-live-smoke.js delete mode 100755 scripts/cli-install-smoke.js delete mode 100755 scripts/cli-local-run-smoke.js delete mode 100644 scripts/cli-login-smoke.js delete mode 100644 scripts/cli-output-mode-smoke.js delete mode 100644 scripts/coordinator-wire.js delete mode 100644 scripts/dap-client.js delete mode 100644 scripts/dap-smoke.js delete mode 100755 scripts/deploy-release-candidate.sh delete mode 100644 scripts/flagship-demo-smoke.js delete mode 100644 scripts/hostile-input-contract-smoke.js delete mode 100755 scripts/migrate-clusterflux-state.sh delete mode 100755 scripts/node-attach-smoke.js delete mode 100755 scripts/node-lifecycle-contract-smoke.js delete mode 100644 scripts/node-signing.js delete mode 100755 scripts/operator-panel-smoke.js delete mode 100755 scripts/podman-backend-smoke.js delete mode 100644 scripts/podman-test-env.js delete mode 100755 scripts/prepare-public-release.js delete mode 100755 scripts/private-repository-gate.sh delete mode 100755 scripts/public-local-demo-matrix-smoke.js delete mode 100755 scripts/public-release-preflight.js delete mode 100755 scripts/public-repository-gate.sh delete mode 100755 scripts/publish-public-release.js delete mode 100755 scripts/quic-smoke.js delete mode 100644 scripts/real-flagship-harness.js delete mode 100755 scripts/recovery-build-smoke.js delete mode 100755 scripts/release-quality-gates.js delete mode 100755 scripts/release-source-scan.sh delete mode 100644 scripts/resource-metering-contract-smoke.js delete mode 100755 scripts/scheduler-placement-smoke.js delete mode 100755 scripts/sdk-spawn-runtime-smoke.js delete mode 100644 scripts/self-hosted-coordinator-smoke.js delete mode 100755 scripts/source-preparation-smoke.js delete mode 100644 scripts/tenant-isolation-contract-smoke.js delete mode 100755 scripts/user-session-token-boundary-smoke.js delete mode 100755 scripts/verify-public-split.sh delete mode 100755 scripts/vscode-extension-smoke.js delete mode 100755 scripts/vscode-f5-smoke.js delete mode 100755 scripts/wasmtime-assignment-smoke.js delete mode 100644 scripts/wasmtime-node-smoke.js delete mode 100755 scripts/windows-best-effort-smoke.js delete mode 100755 scripts/windows-runner-smoke.js delete mode 100644 tests/fixtures/runtime-conformance/Cargo.toml delete mode 100644 tests/fixtures/runtime-conformance/README.md delete mode 100644 tests/fixtures/runtime-conformance/envs/linux/Containerfile delete mode 100644 tests/fixtures/runtime-conformance/envs/windows/Dockerfile delete mode 100644 tests/fixtures/runtime-conformance/fixture/hello-clusterflux.c delete mode 100644 tests/fixtures/runtime-conformance/src/lib.rs diff --git a/.gitignore b/.gitignore index 4bdddd1..94c8535 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,3 @@ /.clusterflux/ **/.clusterflux/ /vscode-extension/node_modules/ -/private/*/Cargo.lock -!/private/hosted-policy/Cargo.lock -/private/*/target/ -/scripts/containers-home/ diff --git a/CLUSTERFLUX_PUBLIC_TREE.json b/CLUSTERFLUX_PUBLIC_TREE.json deleted file mode 100644 index ccdaf0e..0000000 --- a/CLUSTERFLUX_PUBLIC_TREE.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "kind": "clusterflux-filtered-public-tree", - "source_commit": "7fcdc75d8eaf4dc03b09086568dbb184f903f6a4", - "release_name": "release-7fcdc75d8eaf", - "filtered_out": [ - "private/**", - "internal/**", - "experiments/**", - ".git", - "target", - "git-ignored source paths", - "root/*.md except README.md", - "**/.clusterflux/**", - ".forgejo/**" - ], - "public_export": { - "host_neutral": true, - "include_forgejo_workflows": false - }, - "forgejo_host": "git.michelpaulissen.com", - "default_hosted_coordinator_endpoint": "https://clusterflux.michelpaulissen.com" -} diff --git a/Cargo.toml b/Cargo.toml index 3c10aa0..0b813bb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,13 +12,12 @@ members = [ "crates/clusterflux-wasm-runtime", "examples/hello-build", "examples/recovery-build", - "tests/fixtures/runtime-conformance", ] [workspace.package] edition = "2021" license = "Apache-2.0 OR MIT" -repository = "https://git.michelpaulissen.com/michel/clusterflux-public" +repository = "https://clusterflux.lesstuff.com" [workspace.dependencies] anyhow = "1.0" diff --git a/README.md b/README.md index de9d56c..7e2ae67 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,57 @@ # Clusterflux -Clusterflux runs a Rust-defined workflow as one distributed virtual process. A -coordinator hosts the async main, while attached nodes execute Wasm tasks, -rootless containers, and native commands. Tasks exchange canonical values and -portable typed handles instead of sharing host memory. +Clusterflux runs a Rust-defined workflow as one distributed virtual process. The +async main runs serverless, provisioning nodes to run tasks through rootless +containers. Tasks on nodes exchange data simply and efficiently. + +The user experience is built to be as much as possible like building a regular +program. The processes are debuggable as normal through a debugger adapter. + +The primary use case is to consolidate build processes into a single streamlined +developer experience. An example program can be seen below: + +~~~rust +use clusterflux::prelude::*; + +#[clusterflux::task(capabilities = "command")] +pub async fn compile(source: SourceSnapshot) -> Result { + let executable = fs::output("hello-clusterflux")?; + Command::new("cc") + .args([ + "-Os", + "-static", + "-s", + "fixture/hello-clusterflux.c", + "-o", + executable.as_str(), + ]) + .cwd(source.mount()?) + .env("SOURCE_DATE_EPOCH", "0") + .network_disabled() + .run() + .await?; + fs::publish(&executable).await +} + +#[clusterflux::main] +pub async fn build() -> Result { + let source = source::current_project().snapshot().await?; + let compile = clusterflux::spawn!(compile(source)) + .on(clusterflux::env!("linux")) + .await?; + compile.join().await +} +~~~ + +After setup, this build pipeline could be deployed as easily as launching it +through your IDE. This repository includes a VS Code extension to make +development as straightforward as possible. A full collection of CLI tools is +included for advanced usage. + +Clusterflux is explicitly local-first. It is trivial to provision existing +hardware as resources. Bulk data will typically not leave the local network, +allowing maximum throughput. The same capability, however, also makes it +possible to leverage cloud resources easily. Start with [Getting started](docs/getting-started.md). It takes you through authentication, project setup, node enrollment, a run, debugging, task restart, diff --git a/SECURITY.md b/SECURITY.md index a050c6d..2c1cd10 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ published Clusterflux release. Older preview releases are not maintained. ## Report a vulnerability -Email security@michelpaulissen.com with a concise description, affected version +Email security@clusterflux.lesstuff.com with a concise description, affected version or source revision, reproduction steps, and impact. Do not open a public issue for an unpatched vulnerability or include credentials, session tokens, private keys, provider tokens, customer data, or operator secrets in a public report. diff --git a/crates/clusterflux-cli/src/admin.rs b/crates/clusterflux-cli/src/admin.rs index 83f19a6..ce17d88 100644 --- a/crates/clusterflux-cli/src/admin.rs +++ b/crates/clusterflux-cli/src/admin.rs @@ -48,7 +48,7 @@ pub(crate) fn admin_status_report(args: AdminStatusArgs) -> Result { .unwrap_or(json!(false)), "response": response, "safe_default": "read_only", - "private_website_required": false, + "external_website_required": false, "coordinator_session_requests": session.requests(), })); } @@ -56,7 +56,7 @@ pub(crate) fn admin_status_report(args: AdminStatusArgs) -> Result { "command": "admin status", "mode": "self_hosted_local", "safe_default": "read_only", - "private_website_required": false, + "external_website_required": false, })) } @@ -86,7 +86,7 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> "project": project.clone(), "user": user, "coordinator": scope.coordinator, - "private_website_required": false, + "external_website_required": false, "self_hosted_cli_only": true, "project_config_written": project_init .get("project_config_written") @@ -107,13 +107,13 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> { "step": "start_self_hosted_coordinator", "command": "clusterflux-coordinator --listen 127.0.0.1:0", - "private_website_required": false, + "external_website_required": false, }, { "step": "create_or_link_project", "command": "clusterflux project init --yes", "completed": true, - "private_website_required": false, + "external_website_required": false, }, { "step": "create_node_enrollment_grant", @@ -121,7 +121,7 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> "clusterflux node enroll --coordinator {coordinator} --tenant {} --project-id {}", tenant, project ), - "private_website_required": false, + "external_website_required": false, }, { "step": "attach_worker_node", @@ -129,7 +129,7 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> "clusterflux node attach --coordinator {coordinator} --tenant {} --project-id {} --worker", tenant, project ), - "private_website_required": false, + "external_website_required": false, }, { "step": "run_process", @@ -137,7 +137,7 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> "clusterflux run --coordinator {coordinator} --tenant {} --project-id {}", tenant, project ), - "private_website_required": false, + "external_website_required": false, }, { "step": "inspect_status_logs_artifacts", @@ -148,12 +148,12 @@ pub(crate) fn admin_bootstrap_report(args: AdminBootstrapArgs, cwd: PathBuf) -> "clusterflux artifact list", "clusterflux quota status", ], - "private_website_required": false, + "external_website_required": false, }, { "step": "revoke_access", "command": "clusterflux admin revoke-node --node --yes", - "private_website_required": false, + "external_website_required": false, } ], })) @@ -209,7 +209,7 @@ pub(crate) fn admin_suspend_tenant_report(args: AdminSuspendTenantArgs) -> Resul "actor_tenant": actor_tenant, "actor_user": actor_user, "suspended": response.get("type").and_then(Value::as_str) == Some("tenant_suspended"), - "private_website_required": false, + "external_website_required": false, "response": response, "coordinator_session_requests": session.requests(), })); @@ -219,7 +219,7 @@ pub(crate) fn admin_suspend_tenant_report(args: AdminSuspendTenantArgs) -> Resul "status": "requires_coordinator", "requires_confirmation": !args.yes, "tenant": tenant, - "private_website_required": false, + "external_website_required": false, })) } diff --git a/crates/clusterflux-cli/src/auth.rs b/crates/clusterflux-cli/src/auth.rs index 608c9ee..d820cbc 100644 --- a/crates/clusterflux-cli/src/auth.rs +++ b/crates/clusterflux-cli/src/auth.rs @@ -227,7 +227,7 @@ pub(crate) fn auth_status_report(args: AuthStatusArgs, cwd: PathBuf) -> Result Value { "account_status": "unknown", "suspension_known": false, "account_state_known": false, - "private_moderation_details_exposed": false, + "sensitive_moderation_details_exposed": false, "signup_failure_details_exposed": false, "next_actions": ["clusterflux login --browser"], }) diff --git a/crates/clusterflux-cli/src/config.rs b/crates/clusterflux-cli/src/config.rs index db22a3f..ab744ca 100644 --- a/crates/clusterflux-cli/src/config.rs +++ b/crates/clusterflux-cli/src/config.rs @@ -5,8 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::CliScopeArgs; -pub(crate) const DEFAULT_HOSTED_COORDINATOR_ENDPOINT: &str = - "https://clusterflux.michelpaulissen.com"; +pub(crate) const DEFAULT_HOSTED_COORDINATOR_ENDPOINT: &str = "https://clusterflux.lesstuff.com"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct ProjectConfig { diff --git a/crates/clusterflux-cli/src/debug.rs b/crates/clusterflux-cli/src/debug.rs index d39c780..356ce8b 100644 --- a/crates/clusterflux-cli/src/debug.rs +++ b/crates/clusterflux-cli/src/debug.rs @@ -15,7 +15,7 @@ pub(crate) fn dap_plan(args: DapArgs) -> Result { "command": "dap", "adapter": dap_binary_path()?.display().to_string(), "args": args.args, - "private_website_required": false, + "external_website_required": false, })) } @@ -102,7 +102,7 @@ pub(crate) fn debug_attach_report_with_dap_and_session( .cloned() .unwrap_or_else(|| json!(0)), "debug_reads_quota_limited": true, - "private_website_required": false, + "external_website_required": false, "coordinator_session_requests": session.requests(), })); } @@ -115,6 +115,6 @@ pub(crate) fn debug_attach_report_with_dap_and_session( "dap": dap, "authorized": "unknown_without_coordinator", "debug_reads_quota_limited": "unknown_without_coordinator", - "private_website_required": false, + "external_website_required": false, })) } diff --git a/crates/clusterflux-cli/src/errors.rs b/crates/clusterflux-cli/src/errors.rs index 0dce2be..282a91d 100644 --- a/crates/clusterflux-cli/src/errors.rs +++ b/crates/clusterflux-cli/src/errors.rs @@ -38,7 +38,10 @@ pub(crate) fn cli_error_summary_for_category(category: &'static str, message: &s ); object.insert("community_tier_language".to_owned(), json!(true)); object.insert("community_tier_label".to_owned(), json!("community tier")); - object.insert("private_abuse_heuristics_exposed".to_owned(), json!(false)); + object.insert( + "sensitive_abuse_heuristics_exposed".to_owned(), + json!(false), + ); } } summary diff --git a/crates/clusterflux-cli/src/node.rs b/crates/clusterflux-cli/src/node.rs index 902fa14..3f04516 100644 --- a/crates/clusterflux-cli/src/node.rs +++ b/crates/clusterflux-cli/src/node.rs @@ -152,7 +152,7 @@ pub(crate) fn node_enroll_report(args: NodeEnrollArgs, cwd: PathBuf) -> Result Result String { } push_nested_string_field(&mut lines, account, "sanitized_reason", "account reason"); if let Some(exposed) = account - .get("private_moderation_details_exposed") + .get("sensitive_moderation_details_exposed") .and_then(Value::as_bool) { - lines.push(format!("private moderation details exposed: {exposed}")); + lines.push(format!("sensitive moderation details exposed: {exposed}")); } } if let Some(coordinator_selection) = value.get("coordinator") { @@ -277,10 +277,10 @@ pub(crate) fn human_report(value: &Value) -> String { )); } if let Some(flag) = value - .get("private_website_required") + .get("external_website_required") .and_then(Value::as_bool) { - lines.push(format!("private website required: {flag}")); + lines.push(format!("external website required: {flag}")); } if let Some(next_actions) = value.get("next_actions").and_then(Value::as_array) { let actions = next_actions diff --git a/crates/clusterflux-cli/src/process_events.rs b/crates/clusterflux-cli/src/process_events.rs index fa577c7..50adc60 100644 --- a/crates/clusterflux-cli/src/process_events.rs +++ b/crates/clusterflux-cli/src/process_events.rs @@ -557,7 +557,7 @@ pub(crate) fn artifact_download_grant_disclosures(response: &Value) -> Value { "cross_tenant_reuse_allowed": false, "unauthorized_project_reuse_allowed": false, "default_durable_store_assumed": false, - "private_website_required": false, + "external_website_required": false, }]) } @@ -613,7 +613,7 @@ pub(crate) fn project_quota_posture(attached_nodes: &Value, task_events: Option< "current_usage": current_usage, "limits": quota_limits_value(), "next_blocked_action": next_blocked_action, - "private_abuse_heuristics_exposed": false, + "sensitive_abuse_heuristics_exposed": false, }) } diff --git a/crates/clusterflux-cli/src/project.rs b/crates/clusterflux-cli/src/project.rs index 47140db..1573880 100644 --- a/crates/clusterflux-cli/src/project.rs +++ b/crates/clusterflux-cli/src/project.rs @@ -92,7 +92,7 @@ pub(crate) fn project_init_report(args: ProjectInitArgs, cwd: PathBuf) -> Result Ok(json!({ "command": "project init", "source": if coordinator.is_some() { "public_coordinator_api" } else { "local_project_config" }, - "private_website_required": false, + "external_website_required": false, "project_config_written": true, "project_config_write_after_coordinator_acceptance": coordinator.is_some(), "coordinator_create_before_local_write": coordinator.is_some(), @@ -104,7 +104,7 @@ pub(crate) fn project_init_report(args: ProjectInitArgs, cwd: PathBuf) -> Result "config_format": "clusterflux_project_config_v1", "links_current_directory": true, "writes_current_directory_only": true, - "private_website_required": false, + "external_website_required": false, }, "safe_defaults": { "tenant": config.tenant.clone(), @@ -115,7 +115,7 @@ pub(crate) fn project_init_report(args: ProjectInitArgs, cwd: PathBuf) -> Result "default_project_id_used": args.new_project == "project", "default_project_name_used": args.name == "Clusterflux Project", "browser_interaction_required": false, - "private_website_required": false, + "external_website_required": false, }, "project_config": config, "config_file": project_config_file(&cwd), @@ -283,7 +283,7 @@ pub(crate) fn project_list_report(args: ProjectListArgs, cwd: PathBuf) -> Result "user": user, "projects": projects, "project_count": project_count, - "private_website_required": false, + "external_website_required": false, "response": response, "coordinator_session_requests": session.requests(), })); @@ -295,7 +295,7 @@ pub(crate) fn project_list_report(args: ProjectListArgs, cwd: PathBuf) -> Result "source": "local_project_config", "projects": projects, "project_count": project_count, - "private_website_required": false, + "external_website_required": false, })) } @@ -361,7 +361,7 @@ pub(crate) fn project_select_report(args: ProjectSelectArgs, cwd: PathBuf) -> Re "source": if coordinator.is_some() { "public_coordinator_api" } else { "local_project_config" }, "selected_project": selected_project, "project_config_written": true, - "private_website_required": false, + "external_website_required": false, "project_config": config, "coordinator_response": coordinator_response, })) diff --git a/crates/clusterflux-cli/src/quota.rs b/crates/clusterflux-cli/src/quota.rs index a37977f..9c30880 100644 --- a/crates/clusterflux-cli/src/quota.rs +++ b/crates/clusterflux-cli/src/quota.rs @@ -96,7 +96,7 @@ pub(crate) fn quota_status_report(args: QuotaStatusArgs, cwd: PathBuf) -> Result "user": effective_scope.user, "coordinator": coordinator, "project_config": config, - "policy_surface": "generic public quota categories; hosted tuning remains private policy", + "policy_surface": "generic public quota categories; hosted tuning is coordinator-defined", "limits": limits, "window_seconds": window_seconds, "current_usage": current_usage, @@ -105,7 +105,7 @@ pub(crate) fn quota_status_report(args: QuotaStatusArgs, cwd: PathBuf) -> Result "next_blocked_action": quota_next_blocked_action(¤t_usage), "quota_configuration_source": if quota_status.is_some() { "coordinator" } else { "unavailable_offline" }, "quota_tier": quota_tier, - "private_abuse_heuristics_exposed": false, + "sensitive_abuse_heuristics_exposed": false, "quota_response": quota_status, })) } diff --git a/crates/clusterflux-cli/src/run.rs b/crates/clusterflux-cli/src/run.rs index b12d5a5..7dfc187 100644 --- a/crates/clusterflux-cli/src/run.rs +++ b/crates/clusterflux-cli/src/run.rs @@ -142,7 +142,7 @@ fn non_interactive_run_requires_auth_report(args: RunArgs, cwd: PathBuf) -> Valu "safe_failure": true, "message": message, "next_actions": next_actions, - "private_website_required": false, + "external_website_required": false, "machine_error": machine_error, }) } @@ -329,7 +329,7 @@ fn coordinator_run_report(plan: RunPlan) -> Result { "task_launch": launch_task_response, "coordinator_response": response, "coordinator_session_requests": session.requests(), - "private_website_required": false, + "external_website_required": false, })) } diff --git a/crates/clusterflux-cli/src/tests.rs b/crates/clusterflux-cli/src/tests.rs index c122a86..7afd3be 100644 --- a/crates/clusterflux-cli/src/tests.rs +++ b/crates/clusterflux-cli/src/tests.rs @@ -124,7 +124,7 @@ fn cli_error_classifier_distinguishes_mvp_failure_categories() { assert_eq!(summary["resource_category"], "api_calls"); assert_eq!(summary["community_tier_language"], true); assert_eq!(summary["community_tier_label"], "community tier"); - assert_eq!(summary["private_abuse_heuristics_exposed"], false); + assert_eq!(summary["sensitive_abuse_heuristics_exposed"], false); let rendered = human_report(&json!({ "command": "run", "machine_error": summary, @@ -207,7 +207,7 @@ fn non_interactive_run_without_session_requires_explicit_auth_or_local() { assert_eq!(report["status"], "authentication_required"); assert_eq!(report["non_interactive"], true); assert_eq!(report["browser_opened"], false); - assert_eq!(report["private_website_required"], false); + assert_eq!(report["external_website_required"], false); assert_eq!(report["machine_error"]["category"], "authentication"); assert_eq!(report["machine_error"]["stable_exit_code"], 20); assert_eq!(report["machine_error"]["browser_opened"], false); @@ -827,7 +827,7 @@ fn run_rejection_reports_machine_readable_error_category() { assert_eq!(rejected["machine_error"]["resource_category"], "api_calls"); assert_eq!(rejected["machine_error"]["community_tier_language"], true); assert_eq!( - rejected["machine_error"]["private_abuse_heuristics_exposed"], + rejected["machine_error"]["sensitive_abuse_heuristics_exposed"], false ); assert!(rejected["machine_error"]["next_actions"] @@ -1665,12 +1665,11 @@ fn node_attach_refuses_a_symlink_credential_target() { fn hosted_coordinator_remains_a_real_https_control_endpoint() { assert_eq!( control_endpoint_identity(DEFAULT_HOSTED_COORDINATOR_ENDPOINT).unwrap(), - "https://clusterflux.michelpaulissen.com/api/v1/control" + "https://clusterflux.lesstuff.com/api/v1/control" ); assert_eq!( - control_endpoint_identity("https://clusterflux.michelpaulissen.com/api/v1/control") - .unwrap(), - "https://clusterflux.michelpaulissen.com/api/v1/control" + control_endpoint_identity("https://clusterflux.lesstuff.com/api/v1/control").unwrap(), + "https://clusterflux.lesstuff.com/api/v1/control" ); assert!(control_endpoint_identity("http://operator.example.test").is_err()); assert_eq!( @@ -1788,7 +1787,7 @@ fn auth_status_reads_stored_cli_session_without_provider_tokens() { assert!(!line.contains(r#""actor_user":"user-session""#)); stream .write_all( - br#"{"type":"auth_status","tenant":"tenant-session","project":"project-session","actor":"user-session","authenticated":true,"account_status":"active","suspended":false,"disabled":false,"sanitized_reason":null,"next_actions":[],"private_moderation_details_exposed":false,"signup_failure_details_exposed":false}"#, + br#"{"type":"auth_status","tenant":"tenant-session","project":"project-session","actor":"user-session","authenticated":true,"account_status":"active","suspended":false,"disabled":false,"sanitized_reason":null,"next_actions":[],"sensitive_moderation_details_exposed":false,"signup_failure_details_exposed":false}"#, ) .unwrap(); stream.write_all(b"\n").unwrap(); @@ -1851,7 +1850,7 @@ fn auth_status_reads_stored_cli_session_without_provider_tokens() { "active" ); assert_eq!( - report["coordinator_account_status"]["private_moderation_details_exposed"], + report["coordinator_account_status"]["sensitive_moderation_details_exposed"], false ); } @@ -1933,7 +1932,7 @@ fn auth_status_reports_expired_or_revoked_cli_session_as_login_required() { } #[test] -fn auth_status_queries_coordinator_account_state_without_private_moderation_details() { +fn auth_status_queries_coordinator_account_state_without_sensitive_moderation_details() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap().to_string(); let server = std::thread::spawn(move || { @@ -1947,7 +1946,7 @@ fn auth_status_queries_coordinator_account_state_without_private_moderation_deta assert!(line.contains(r#""actor_user":"user-live""#)); stream .write_all( - br#"{"type":"auth_status","tenant":"tenant-live","project":"project-live","actor":"user-live","authenticated":true,"account_status":"suspended","suspended":true,"disabled":false,"sanitized_reason":"account or tenant is suspended by hosted policy","next_actions":["contact the hosted operator"],"private_moderation_details_exposed":false,"signup_failure_details_exposed":false,"abuse_score":99,"moderation_notes":"private moderation note"}"#, + br#"{"type":"auth_status","tenant":"tenant-live","project":"project-live","actor":"user-live","authenticated":true,"account_status":"suspended","suspended":true,"disabled":false,"sanitized_reason":"account or tenant is suspended by hosted policy","next_actions":["contact the hosted operator"],"sensitive_moderation_details_exposed":false,"signup_failure_details_exposed":false,"abuse_score":99,"moderation_notes":"sensitive moderation note"}"#, ) .unwrap(); stream.write_all(b"\n").unwrap(); @@ -1987,7 +1986,7 @@ fn auth_status_queries_coordinator_account_state_without_private_moderation_deta "account or tenant is suspended by hosted policy" ); assert_eq!( - report["coordinator_account_status"]["private_moderation_details_exposed"], + report["coordinator_account_status"]["sensitive_moderation_details_exposed"], false ); assert_eq!( @@ -2005,13 +2004,13 @@ fn auth_status_queries_coordinator_account_state_without_private_moderation_deta let serialized = serde_json::to_string(&report).unwrap(); assert!(!serialized.contains("abuse_score")); assert!(!serialized.contains("moderation_notes")); - assert!(!serialized.contains("private moderation note")); + assert!(!serialized.contains("sensitive moderation note")); let rendered = human_report(&report); assert!(rendered.contains("account status: suspended")); assert!(rendered.contains("account suspended: true")); - assert!(rendered.contains("private moderation details exposed: false")); - assert!(!rendered.contains("private moderation note")); + assert!(rendered.contains("sensitive moderation details exposed: false")); + assert!(!rendered.contains("sensitive moderation note")); } #[test] @@ -2062,11 +2061,11 @@ fn auth_status_reports_disabled_deleted_and_manual_review_safely() { "manual_review": manual_review, "sanitized_reason": reason, "next_actions": ["contact the hosted operator"], - "private_moderation_details_exposed": false, + "sensitive_moderation_details_exposed": false, "signup_failure_details_exposed": false, "abuse_score": 99, - "moderation_notes": "private moderation note", - "signup_policy_trace": "private signup trace", + "moderation_notes": "sensitive moderation note", + "signup_policy_trace": "sensitive signup trace", }) ) .unwrap(); @@ -2105,7 +2104,7 @@ fn auth_status_reports_disabled_deleted_and_manual_review_safely() { true ); assert_eq!( - report["coordinator_account_status"]["private_moderation_details_exposed"], + report["coordinator_account_status"]["sensitive_moderation_details_exposed"], false ); assert_eq!( @@ -2116,11 +2115,11 @@ fn auth_status_reports_disabled_deleted_and_manual_review_safely() { assert!(!serialized.contains("abuse_score")); assert!(!serialized.contains("moderation_notes")); assert!(!serialized.contains("signup_policy_trace")); - assert!(!serialized.contains("private moderation note")); + assert!(!serialized.contains("sensitive moderation note")); let rendered = human_report(&report); assert!(rendered.contains(&format!("account status: {status}"))); assert!(rendered.contains(rendered_marker)); - assert!(!rendered.contains("private moderation note")); + assert!(!rendered.contains("sensitive moderation note")); } server.join().unwrap(); } @@ -2235,11 +2234,11 @@ fn admin_bootstrap_reports_self_hosted_cli_only_path() { assert_eq!(report["command"], "admin bootstrap"); assert_eq!(report["mode"], "self_hosted_local"); - assert_eq!(report["private_website_required"], false); + assert_eq!(report["external_website_required"], false); assert_eq!(report["self_hosted_cli_only"], true); assert_eq!(report["project_config_written"], true); assert_eq!(report["project_init"]["command"], "project init"); - assert_eq!(report["project_init"]["private_website_required"], false); + assert_eq!(report["project_init"]["external_website_required"], false); assert_eq!( report["project_init"]["project_config"]["project"], "self-hosted" @@ -2265,7 +2264,7 @@ fn admin_bootstrap_reports_self_hosted_cli_only_path() { } assert!(steps.iter().all(|step| { !step - .get("private_website_required") + .get("external_website_required") .and_then(Value::as_bool) .unwrap_or(false) })); @@ -2893,13 +2892,13 @@ fn admin_status_and_suspend_use_public_coordinator_api() { assert_eq!(status["command"], "admin status"); assert_eq!(status["safe_default"], "read_only"); - assert_eq!(status["private_website_required"], false); + assert_eq!(status["external_website_required"], false); assert_eq!(status["suspended"], false); assert_eq!(suspended["command"], "admin suspend-tenant"); assert_eq!(suspended["tenant"], "tenant"); assert_eq!(suspended["actor_tenant"], "admin-tenant"); assert_eq!(suspended["suspended"], true); - assert_eq!(suspended["private_website_required"], false); + assert_eq!(suspended["external_website_required"], false); } #[test] @@ -2968,7 +2967,7 @@ fn debug_attach_reports_public_authorization() { assert_eq!(report["charged_debug_read_bytes"], 1024); assert_eq!(report["used_debug_read_bytes"], 1024); assert_eq!(report["debug_reads_quota_limited"], true); - assert_eq!(report["private_website_required"], false); + assert_eq!(report["external_website_required"], false); } #[test] @@ -3311,7 +3310,7 @@ fn project_init_uses_public_create_before_writing_local_config() { created["safe_defaults"]["browser_interaction_required"], false ); - assert_eq!(created["private_website_required"], false); + assert_eq!(created["external_website_required"], false); assert_eq!( read_project_config(temp_success.path()) .unwrap() @@ -3411,7 +3410,7 @@ fn project_list_and_select_use_public_api_without_website() { assert_eq!(list["source"], "public_coordinator_api"); assert_eq!(list["project_count"], 1); assert_eq!(list["projects"][0]["id"], "project-a"); - assert_eq!(list["private_website_required"], false); + assert_eq!(list["external_website_required"], false); assert_eq!(list["coordinator_session_requests"], 1); let selected = project_select_report( @@ -3426,7 +3425,7 @@ fn project_list_and_select_use_public_api_without_website() { assert_eq!(selected["source"], "public_coordinator_api"); assert_eq!(selected["selected_project"]["id"], "project-a"); assert_eq!(selected["project_config_written"], true); - assert_eq!(selected["private_website_required"], false); + assert_eq!(selected["external_website_required"], false); assert_eq!( read_project_config(temp.path()).unwrap().unwrap().project, "project-a" @@ -4455,7 +4454,7 @@ fn build_command_reuses_bundle_inspection_without_full_repo_upload() { let temp = tempfile::tempdir().unwrap(); let project = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../..") - .join("tests/fixtures/runtime-conformance"); + .join("examples/hello-build"); let output = temp.path().join("bundle"); let report = build_report( @@ -4473,8 +4472,8 @@ fn build_command_reuses_bundle_inspection_without_full_repo_upload() { assert_eq!(report["command"], "build"); assert_eq!(report["content_addressed"], true); assert_eq!(report["contains_full_repository_upload"], false); - assert_eq!(report["bundle_artifact"]["task_descriptor_count"], 12); - assert_eq!(report["bundle_artifact"]["entrypoint_count"], 6); + assert_eq!(report["bundle_artifact"]["task_descriptor_count"], 2); + assert_eq!(report["bundle_artifact"]["entrypoint_count"], 1); assert!(output.join("module.wasm").is_file()); assert!(output.join("manifest.json").is_file()); assert!(output.join("task-descriptors.json").is_file()); @@ -4485,9 +4484,9 @@ fn build_command_reuses_bundle_inspection_without_full_repo_upload() { .unwrap() .iter() .any(|descriptor| { - descriptor["name"] == "task_add_one" - && descriptor["argument_schema"] == "input : i32" - && descriptor["result_schema"] == "i32" + descriptor["name"] == "compile" + && descriptor["argument_schema"] == "source : SourceSnapshot" + && descriptor["result_schema"] == "Result < Artifact >" && descriptor["restart_compatibility_hash"] .as_str() .unwrap() @@ -4648,7 +4647,7 @@ fn node_enroll_reports_short_lived_public_api_grant() { assert_eq!(report["command"], "node enroll"); assert_eq!(report["status"], "created"); - assert_eq!(report["private_website_required"], false); + assert_eq!(report["external_website_required"], false); assert_eq!(report["tenant"], "tenant"); assert_eq!(report["project"], "project"); assert_eq!(report["user"], "user"); @@ -4791,7 +4790,7 @@ fn node_enroll_and_process_commands_have_safe_plan_without_coordinator() { ) .unwrap(); assert_eq!(enroll["status"], "requires_coordinator"); - assert_eq!(enroll["private_website_required"], false); + assert_eq!(enroll["external_website_required"], false); assert_eq!(enroll["enrollment_grant"], serde_json::Value::Null); assert_eq!(enroll["requested_ttl_seconds"], 60); diff --git a/crates/clusterflux-coordinator/src/lib.rs b/crates/clusterflux-coordinator/src/lib.rs index 7776307..403e8d2 100644 --- a/crates/clusterflux-coordinator/src/lib.rs +++ b/crates/clusterflux-coordinator/src/lib.rs @@ -1046,7 +1046,7 @@ mod tests { } #[test] - fn account_policy_state_summarizes_private_admin_records_safely() { + fn account_policy_state_summarizes_sensitive_admin_records_safely() { let tenant = TenantId::from("tenant"); let mut coordinator = Coordinator::boot(&InMemoryDurableStore::default(), 1); diff --git a/crates/clusterflux-coordinator/src/service/protocol/responses.rs b/crates/clusterflux-coordinator/src/service/protocol/responses.rs index dbb3874..b99bc21 100644 --- a/crates/clusterflux-coordinator/src/service/protocol/responses.rs +++ b/crates/clusterflux-coordinator/src/service/protocol/responses.rs @@ -213,7 +213,7 @@ pub enum CoordinatorResponse { manual_review: bool, sanitized_reason: Option, next_actions: Vec, - private_moderation_details_exposed: bool, + sensitive_moderation_details_exposed: bool, signup_failure_details_exposed: bool, }, AdminStatus { diff --git a/crates/clusterflux-coordinator/src/service/routing.rs b/crates/clusterflux-coordinator/src/service/routing.rs index d57af3f..aecaeef 100644 --- a/crates/clusterflux-coordinator/src/service/routing.rs +++ b/crates/clusterflux-coordinator/src/service/routing.rs @@ -45,7 +45,7 @@ impl CoordinatorService { manual_review: account_state.manual_review, sanitized_reason: account_state.sanitized_reason, next_actions: account_state.next_actions, - private_moderation_details_exposed: false, + sensitive_moderation_details_exposed: false, signup_failure_details_exposed: false, }) } @@ -609,7 +609,7 @@ impl CoordinatorService { manual_review: account_state.manual_review, sanitized_reason: account_state.sanitized_reason, next_actions: account_state.next_actions, - private_moderation_details_exposed: false, + sensitive_moderation_details_exposed: false, signup_failure_details_exposed: false, }) } diff --git a/crates/clusterflux-coordinator/src/service/tests.rs b/crates/clusterflux-coordinator/src/service/tests.rs index fba8638..c20f42b 100644 --- a/crates/clusterflux-coordinator/src/service/tests.rs +++ b/crates/clusterflux-coordinator/src/service/tests.rs @@ -1499,7 +1499,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { suspended, disabled, sanitized_reason, - private_moderation_details_exposed, + sensitive_moderation_details_exposed, signup_failure_details_exposed, .. } = service @@ -1520,7 +1520,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { assert!(!suspended); assert!(!disabled); assert!(sanitized_reason.is_none()); - assert!(!private_moderation_details_exposed); + assert!(!sensitive_moderation_details_exposed); assert!(!signup_failure_details_exposed); for (tenant, policy_name, expected_status, expected_reason) in [ @@ -1556,7 +1556,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { manual_review, sanitized_reason, next_actions, - private_moderation_details_exposed, + sensitive_moderation_details_exposed, signup_failure_details_exposed, .. } = service @@ -1578,7 +1578,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { assert!(next_actions .iter() .any(|action| action.contains("hosted operator"))); - assert!(!private_moderation_details_exposed); + assert!(!sensitive_moderation_details_exposed); assert!(!signup_failure_details_exposed); } @@ -1717,7 +1717,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { disabled, sanitized_reason, next_actions, - private_moderation_details_exposed, + sensitive_moderation_details_exposed, signup_failure_details_exposed, .. } = service @@ -1740,7 +1740,7 @@ fn service_reports_and_enforces_public_admin_tenant_suspension() { assert!(next_actions .iter() .any(|action| action.contains("hosted operator"))); - assert!(!private_moderation_details_exposed); + assert!(!sensitive_moderation_details_exposed); assert!(!signup_failure_details_exposed); let create = service diff --git a/crates/clusterflux-dap/src/tests.rs b/crates/clusterflux-dap/src/tests.rs index b9d7a36..ed1c82f 100644 --- a/crates/clusterflux-dap/src/tests.rs +++ b/crates/clusterflux-dap/src/tests.rs @@ -704,11 +704,40 @@ fn terminal_record_without_snapshots_clears_active_threads() { #[test] fn source_locals_infer_clusterflux_api_values_from_runtime_state() { - let mut state = AdapterState::default(); - let project = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../tests/fixtures/runtime-conformance") - .canonicalize() + let project = std::env::temp_dir().join(format!( + "clusterflux-dap-source-locals-{}", + std::process::id() + )); + let src = project.join("src"); + fs::create_dir_all(&src).unwrap(); + fs::write( + src.join("lib.rs"), + r#"async fn run_build_workflow() { + let source = prepare_source_snapshot(); + let linux = clusterflux::spawn::async_task_with_arg(source.clone(), compile_linux) + .name("compile linux") + .env(linux_env()) + .start() + .await .unwrap(); + let linux_thread = linux.virtual_thread_id(); + let linux_artifact = linux.join().await.unwrap(); + let package = clusterflux::spawn::async_task_with_arg( + vec![linux_artifact.clone()], + package_release, + ) + .name("package artifacts") + .env(linux_env()) + .start() + .await + .unwrap(); + let package_artifact = package.join().await.unwrap(); +} +"#, + ) + .unwrap(); + + let mut state = AdapterState::default(); state.project = project.to_string_lossy().into_owned(); state.source_path = "src/lib.rs".to_owned(); let source = fs::read_to_string(project.join(&state.source_path)).unwrap(); @@ -744,6 +773,8 @@ fn source_locals_infer_clusterflux_api_values_from_runtime_state() { variable["name"] == "unavailable-local-diagnostic" && variable["type"] == "unavailable-local" })); + + let _ = fs::remove_dir_all(project); } #[test] @@ -863,11 +894,20 @@ fn package_release(inputs: Vec) -> Artifact { #[test] fn wasm_frame_locals_expose_only_values_from_the_node_snapshot() { + let project = std::env::temp_dir().join(format!( + "clusterflux-dap-wasm-locals-{}", + std::process::id() + )); + let src = project.join("src"); + fs::create_dir_all(&src).unwrap(); + fs::write( + src.join("lib.rs"), + "pub extern \"C\" fn task_add_one(input: i32) -> i32 {\n input + 1\n}\n", + ) + .unwrap(); + let mut state = AdapterState::default(); - state.project = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../tests/fixtures/runtime-conformance") - .to_string_lossy() - .into_owned(); + state.project = project.to_string_lossy().into_owned(); state.source_path = "src/lib.rs".to_owned(); let source = fs::read_to_string(Path::new(&state.project).join(&state.source_path)).unwrap(); state.threads.get_mut(&MAIN_THREAD).unwrap().line = source @@ -895,6 +935,8 @@ fn wasm_frame_locals_expose_only_values_from_the_node_snapshot() { assert!(!locals .iter() .any(|variable| variable["name"] == "wasm-local-diagnostic")); + + let _ = fs::remove_dir_all(project); } #[test] diff --git a/crates/clusterflux-dap/src/virtual_model.rs b/crates/clusterflux-dap/src/virtual_model.rs index 5dcba43..9ef76eb 100644 --- a/crates/clusterflux-dap/src/virtual_model.rs +++ b/crates/clusterflux-dap/src/virtual_model.rs @@ -114,7 +114,7 @@ impl Default for AdapterState { project, source_path: "src/lib.rs".to_owned(), runtime_backend: RuntimeBackend::Simulated, - coordinator_endpoint: "https://clusterflux.michelpaulissen.com".to_owned(), + coordinator_endpoint: "https://clusterflux.lesstuff.com".to_owned(), tenant: TenantId::from("tenant"), project_id: ProjectId::from("project"), actor_user: UserId::from("dap"), diff --git a/crates/clusterflux-node/src/daemon.rs b/crates/clusterflux-node/src/daemon.rs index 513fc83..7a5a858 100644 --- a/crates/clusterflux-node/src/daemon.rs +++ b/crates/clusterflux-node/src/daemon.rs @@ -634,13 +634,12 @@ mod tests { #[test] fn hosted_url_remains_an_https_control_endpoint() { assert_eq!( - control_endpoint_identity("https://clusterflux.michelpaulissen.com").unwrap(), - "https://clusterflux.michelpaulissen.com/api/v1/control" + control_endpoint_identity("https://clusterflux.lesstuff.com").unwrap(), + "https://clusterflux.lesstuff.com/api/v1/control" ); assert_eq!( - control_endpoint_identity("https://clusterflux.michelpaulissen.com/api/v1/control") - .unwrap(), - "https://clusterflux.michelpaulissen.com/api/v1/control" + control_endpoint_identity("https://clusterflux.lesstuff.com/api/v1/control").unwrap(), + "https://clusterflux.lesstuff.com/api/v1/control" ); assert_eq!( control_endpoint_identity("127.0.0.1:7999").unwrap(), diff --git a/crates/clusterflux-node/src/lib.rs b/crates/clusterflux-node/src/lib.rs index f35c3d6..8b100c3 100644 --- a/crates/clusterflux-node/src/lib.rs +++ b/crates/clusterflux-node/src/lib.rs @@ -1029,7 +1029,7 @@ mod tests { } #[test] - fn public_node_crate_does_not_require_hosted_private_types() { + fn public_node_crate_does_not_require_hosted_service_types() { let _tenant = TenantId::from("tenant"); let _project = ProjectId::from("project"); let _backend = LinuxRootlessPodmanBackend; diff --git a/docs/contributing/releases.md b/docs/contributing/releases.md deleted file mode 100644 index 6dc422e..0000000 --- a/docs/contributing/releases.md +++ /dev/null @@ -1,60 +0,0 @@ -# Release candidates - -This is a contributor and release-engineering procedure, not an end-user setup -path. Publication is a three-stage transaction: - -1. `candidate` builds immutable archives and a manifest with paths relative to - the manifest directory. -2. `live-test` downloads that exact candidate in a clean job, deploys it, and - records the full named production-shaped acceptance result plus deployment, - runtime configuration, and proxy configuration identities. -3. `final` downloads the candidate and evidence in another clean job, verifies - every binding, and publishes without rebuilding any binary. - -Set `CLUSTERFLUX_RELEASE_STAGE=candidate` while creating the candidate and -`CLUSTERFLUX_RELEASE_STAGE=final` while finalizing it. The final stage requires -`CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST` and complete live evidence. There is no -incomplete-evidence publication override. - -The `clusterflux-release` runner must provide `CLUSTERFLUX_DEPLOY_COMMAND` as a -protected secret. The command runs locally with -`CLUSTERFLUX_CANDIDATE_ARCHIVE`, `CLUSTERFLUX_CANDIDATE_COORDINATOR`, and their -SHA-256 identities exported. It must deploy that executable and restart the -configured service. `scripts/deploy-release-candidate.sh` then independently -compares the running `/proc//exe` digest with the candidate and records -the service and proxy unit identities; a mismatch stops the release. - -Clusterflux release binaries are built once. The public client/node archive and -the private-source hosted-service archive are both digest-bound to the same -candidate. The hosted archive is deployed, the strict production-shaped batch -uses the public archive against it, and finalization copies both archives -without rebuilding. - -Create the candidate in a dedicated directory: - -~~~bash -CLUSTERFLUX_PUBLIC_RELEASE_DIR=target/release-candidate \ -CLUSTERFLUX_RELEASE_STAGE=candidate \ -./scripts/prepare-public-release.js -~~~ - -Deploy `target/release-candidate/assets/clusterflux-public-binaries-*.tar.gz`. -Set `CLUSTERFLUX_PUBLIC_RELEASE_MANIFEST` to the candidate manifest while -running the strict batch. Set `CLUSTERFLUX_QUALITY_GATE_EVIDENCE_PATH` to the -JSON record from the private and public acceptance commands. The result records -the source commit, source-tree and -public-tree identities, candidate binary digests, deployment generation, and -configuration identity. - -Finalize into a different directory after the strict result passes: - -~~~bash -CLUSTERFLUX_PUBLIC_RELEASE_DIR=target/public-release \ -CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST=target/release-candidate/public-release-manifest.json \ -CLUSTERFLUX_FINAL_RESULT_PATH=target/acceptance/cli-happy-path-live.json \ -./scripts/prepare-public-release.js -~~~ - -Finalization rejects a changed commit, source tree, public tree, candidate -archive, binary digest set, deployment binding, or strict result. It never runs -the release binary build when a candidate manifest is supplied. diff --git a/docs/getting-started.md b/docs/getting-started.md index 0b4f593..11e10a1 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -52,7 +52,7 @@ same stored identity: ~~~bash clusterflux-node \ - --coordinator https://clusterflux.michelpaulissen.com \ + --coordinator https://clusterflux.lesstuff.com \ --tenant "$TENANT" \ --project-id \ --node workstation \ diff --git a/docs/nodes.md b/docs/nodes.md index f6ffd19..3913859 100644 --- a/docs/nodes.md +++ b/docs/nodes.md @@ -23,7 +23,7 @@ key pair. ~~~bash clusterflux-node \ - --coordinator https://clusterflux.michelpaulissen.com \ + --coordinator https://clusterflux.lesstuff.com \ --tenant "$TENANT" \ --project-id \ --node workstation \ diff --git a/scripts/acceptance-private.sh b/scripts/acceptance-private.sh deleted file mode 100755 index 5a54a15..0000000 --- a/scripts/acceptance-private.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$repo" - -if [[ ! -d private/hosted-policy ]]; then - exit 0 -fi - -scripts/check-old-name.sh -node scripts/check-docs.js -scripts/check-code-size.sh -cargo fmt --all --manifest-path private/hosted-policy/Cargo.toml --check -cargo clippy --manifest-path private/hosted-policy/Cargo.toml --all-targets -- -D warnings -cargo test --locked --manifest-path private/hosted-policy/Cargo.toml --all-targets -node private/hosted-policy/scripts/prepare-hosted-deployment.js -if command -v podman >/dev/null 2>&1; then - node private/hosted-policy/scripts/postgres-durable-smoke.js -elif command -v nix >/dev/null 2>&1; then - nix shell nixpkgs#podman --command node private/hosted-policy/scripts/postgres-durable-smoke.js -else - node private/hosted-policy/scripts/postgres-durable-smoke.js -fi -if [[ -n "${CLUSTERFLUX_PUBLIC_RELEASE_SERVICE_ADDR:-}" ]]; then - node private/hosted-policy/scripts/hosted-service-live-check.js -fi diff --git a/scripts/acceptance-public.sh b/scripts/acceptance-public.sh deleted file mode 100755 index 96a1363..0000000 --- a/scripts/acceptance-public.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$repo" - -scripts/check-old-name.sh -node scripts/check-docs.js -scripts/check-code-size.sh -scripts/release-source-scan.sh -cargo fmt --all --check -cargo clippy --workspace --all-targets -- -D warnings -cargo test --workspace --all-targets -cargo build --workspace --all-targets -cargo build -p runtime-conformance --target wasm32-unknown-unknown -cargo build -p hello-build --target wasm32-unknown-unknown -cargo build -p recovery-build --target wasm32-unknown-unknown -node scripts/resource-metering-contract-smoke.js -node scripts/hostile-input-contract-smoke.js -node scripts/tenant-isolation-contract-smoke.js -node scripts/self-hosted-coordinator-smoke.js -node scripts/public-local-demo-matrix-smoke.js -node scripts/cli-output-mode-smoke.js -node scripts/cli-login-smoke.js -node scripts/cli-error-exit-smoke.js -node scripts/cli-browser-login-flow-smoke.js -node scripts/cli-install-smoke.js -node scripts/user-session-token-boundary-smoke.js -node scripts/sdk-spawn-runtime-smoke.js -node scripts/node-lifecycle-contract-smoke.js -node scripts/wasmtime-node-smoke.js -node scripts/wasmtime-assignment-smoke.js -if command -v podman >/dev/null 2>&1; then - node scripts/podman-backend-smoke.js -elif command -v nix >/dev/null 2>&1; then - nix shell nixpkgs#podman --command node scripts/podman-backend-smoke.js -else - node scripts/podman-backend-smoke.js -fi -node scripts/vscode-extension-smoke.js -node scripts/vscode-f5-smoke.js -node scripts/node-attach-smoke.js -node scripts/cli-local-run-smoke.js -node scripts/artifact-download-smoke.js -node scripts/artifact-export-smoke.js -node scripts/operator-panel-smoke.js -node scripts/source-preparation-smoke.js -node scripts/scheduler-placement-smoke.js -node scripts/windows-best-effort-smoke.js -node scripts/quic-smoke.js -node scripts/dap-smoke.js -node scripts/recovery-build-smoke.js -node scripts/flagship-demo-smoke.js -scripts/verify-public-split.sh diff --git a/scripts/agent-signing.js b/scripts/agent-signing.js deleted file mode 100644 index bfdc461..0000000 --- a/scripts/agent-signing.js +++ /dev/null @@ -1,99 +0,0 @@ -const crypto = require("crypto"); - -const { nodeIdentity, signedRequestPayloadDigest } = require("./node-signing"); - -function agentIdentity(seedPrefix, agent) { - const identity = nodeIdentity(seedPrefix, agent); - return { - ...identity, - publicKeyFingerprint: `sha256:${crypto - .createHash("sha256") - .update(identity.publicKey) - .digest("hex")}`, - }; -} - -function agentWorkflowSignatureMessage({ - tenant, - project, - agent, - requestKind, - process: processId, - task = "", - payloadDigest, - nonce, - issuedAtEpochSeconds, -}) { - const parts = [ - "clusterflux-agent-workflow-signature:v2", - tenant, - project, - agent, - requestKind, - processId, - task, - payloadDigest, - nonce, - String(issuedAtEpochSeconds), - ]; - return Buffer.concat( - parts.flatMap((part) => [ - Buffer.from(`${Buffer.byteLength(part)}:`), - Buffer.from(part), - Buffer.from("\n"), - ]) - ); -} - -function signedAgentWorkflowProof(identity, request, options = {}) { - const nonce = - options.nonce ?? - `${request.type}-${process.pid}-${Date.now()}-${crypto - .randomBytes(8) - .toString("hex")}`; - const issuedAtEpochSeconds = - options.issuedAtEpochSeconds ?? Math.floor(Date.now() / 1000); - const processId = - request.type === "launch_task" ? request.task_spec?.process : request.process; - const task = - request.type === "launch_task" ? request.task_spec?.task_instance : request.task || ""; - const signature = crypto.sign( - null, - agentWorkflowSignatureMessage({ - tenant: request.tenant, - project: request.project, - agent: request.actor_agent, - requestKind: request.type, - process: processId, - task, - payloadDigest: signedRequestPayloadDigest(request), - nonce, - issuedAtEpochSeconds, - }), - identity.privateKeyObject - ); - return { - nonce, - issued_at_epoch_seconds: issuedAtEpochSeconds, - signature: `ed25519:${signature.toString("base64")}`, - }; -} - -function signedAgentWorkflowRequest(identity, request, options = {}) { - const unsignedRequest = { - ...request, - agent_public_key_fingerprint: - options.publicKeyFingerprint || identity.publicKeyFingerprint, - }; - return { - ...unsignedRequest, - agent_signature: signedAgentWorkflowProof(identity, unsignedRequest, options), - }; -} - -module.exports = { - agentIdentity, - agentWorkflowSignatureMessage, - signedAgentWorkflowProof, - signedAgentWorkflowRequest, -}; diff --git a/scripts/artifact-download-smoke.js b/scripts/artifact-download-smoke.js deleted file mode 100755 index f9e3c55..0000000 --- a/scripts/artifact-download-smoke.js +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); -const { - ensureRootlessPodman, - flagshipNodeCapabilities, - launchFlagship, - repo, - runFlagshipWorker, - send, - waitForJsonLine, -} = require("./real-flagship-harness"); - -const downloadNode = "node-download"; -const downloadNodeIdentity = nodeIdentity("artifact-download-smoke", downloadNode); - -const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); - -async function downloadRetainedBytes(addr, link, artifact, expectedSize) { - const chunks = []; - let offset = 0; - for (let attempt = 0; attempt < 500; attempt += 1) { - const response = await send(addr, { - type: "open_artifact_download_stream", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - token_digest: link.link.scoped_token_digest, - chunk_bytes: 256 * 1024, - }); - assert.strictEqual(response.type, "artifact_download_stream"); - if (!response.content_bytes_available) { - assert.strictEqual(response.content_source, "retaining_node_reverse_stream_pending"); - await delay(10); - continue; - } - assert.strictEqual(response.content_source, "retaining_node_reverse_stream"); - assert.strictEqual(response.content_offset, offset); - const bytes = Buffer.from(response.content_base64, "base64"); - assert.strictEqual(response.streamed_bytes, bytes.length); - chunks.push(bytes); - offset += bytes.length; - if (response.content_eof) { - const content = Buffer.concat(chunks); - assert.strictEqual(content.length, expectedSize); - return { content, response }; - } - } - throw new Error("timed out waiting for retained artifact reverse stream"); -} - -function downloadNodeCapabilities() { - return flagshipNodeCapabilities(); -} - -(async () => { - ensureRootlessPodman(); - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback", - ], - { cwd: repo } - ); - - let worker; - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - worker = await runFlagshipWorker(addr, downloadNode, downloadNodeIdentity); - const workerReady = await worker.ready; - assert.strictEqual(workerReady.node_status, "ready"); - assert.strictEqual(workerReady.mode, "worker"); - const { compileEvent, packageEvent, process: virtualProcess } = await launchFlagship(addr); - assert.strictEqual(compileEvent.status_code, 0); - assert.strictEqual(packageEvent.status_code, 0); - assert.deepStrictEqual(compileEvent.result, { - Artifact: { - id: compileEvent.artifact_path.slice("/vfs/artifacts/".length), - digest: compileEvent.artifact_digest, - size_bytes: compileEvent.artifact_size_bytes, - }, - }); - assert.deepStrictEqual(packageEvent.result, { - Artifact: { - id: packageEvent.artifact_path.slice("/vfs/artifacts/".length), - digest: packageEvent.artifact_digest, - size_bytes: packageEvent.artifact_size_bytes, - }, - }); - assert.ok(compileEvent.artifact_size_bytes > 0); - assert.strictEqual(packageEvent.artifact_size_bytes, compileEvent.artifact_size_bytes); - assert.match(compileEvent.artifact_digest, /^sha256:[0-9a-f]{64}$/); - assert.match(packageEvent.artifact_digest, /^sha256:[0-9a-f]{64}$/); - const artifactPath = packageEvent.artifact_path; - assert.match( - artifactPath, - /^\/vfs\/artifacts\/hello-clusterflux-[0-9a-f]{64}$/ - ); - const artifact = artifactPath.slice("/vfs/artifacts/".length); - - const disconnectedReport = await send(addr, signedNodeRequest(downloadNode, downloadNodeIdentity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: downloadNode, - capabilities: downloadNodeCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [artifact], - direct_connectivity: false, - online: true, - })); - assert.strictEqual(disconnectedReport.type, "node_capabilities_recorded"); - - const disconnectedLink = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - ttl_seconds: 60, - }); - assert.strictEqual(disconnectedLink.type, "artifact_download_link"); - - const connectedReport = await send(addr, signedNodeRequest(downloadNode, downloadNodeIdentity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: downloadNode, - capabilities: downloadNodeCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [artifact], - direct_connectivity: true, - online: true, - })); - assert.strictEqual(connectedReport.type, "node_capabilities_recorded"); - - const link = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - ttl_seconds: 60, - }); - assert.strictEqual(link.type, "artifact_download_link"); - assert.strictEqual(link.link.tenant, "tenant"); - assert.strictEqual(link.link.project, "project"); - assert.strictEqual(link.link.process, virtualProcess); - assert.deepStrictEqual(link.link.actor, { User: "user" }); - assert.match(link.link.policy_context_digest, /^sha256:[0-9a-f]{64}$/); - assert.ok(link.link.expires_at_epoch_seconds > Math.floor(Date.now() / 1000)); - assert.ok(link.link.expires_at_epoch_seconds <= Math.floor(Date.now() / 1000) + 60); - assert.ok( - link.link.url_path.endsWith( - `/artifacts/tenant/project/${virtualProcess}/${artifact}` - ) - ); - assert.deepStrictEqual(link.link.source, { RetainedNode: "node-download" }); - - const crossTenant = await send(addr, { - type: "create_artifact_download_link", - tenant: "other", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - ttl_seconds: 60, - }); - assert.strictEqual(crossTenant.type, "error"); - assert.match(crossTenant.message, /artifact does not exist/); - - const crossProject = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "other-project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - ttl_seconds: 60, - }); - assert.strictEqual(crossProject.type, "error"); - assert.match(crossProject.message, /artifact does not exist/); - - const crossTenantOpen = await send(addr, { - type: "open_artifact_download_stream", - tenant: "other", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - token_digest: link.link.scoped_token_digest, - chunk_bytes: 1, - }); - assert.strictEqual(crossTenantOpen.type, "error"); - assert.match(crossTenantOpen.message, /artifact does not exist/); - - const crossProjectOpen = await send(addr, { - type: "open_artifact_download_stream", - tenant: "tenant", - project: "other-project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - token_digest: link.link.scoped_token_digest, - chunk_bytes: 1, - }); - assert.strictEqual(crossProjectOpen.type, "error"); - assert.match(crossProjectOpen.message, /artifact does not exist/); - - const guessed = await send(addr, { - type: "open_artifact_download_stream", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - token_digest: "sha256:guessed", - chunk_bytes: 1, - }); - assert.strictEqual(guessed.type, "error"); - assert.match(guessed.message, /token is invalid/); - - const crossActorOpen = await send(addr, { - type: "open_artifact_download_stream", - tenant: "tenant", - project: "project", - actor_user: "other-user", - artifact, - max_bytes: 1024 * 1024, - token_digest: link.link.scoped_token_digest, - chunk_bytes: 1, - }); - assert.strictEqual(crossActorOpen.type, "error"); - assert.match(crossActorOpen.message, /token is invalid/); - - const downloaded = await downloadRetainedBytes( - addr, - link, - artifact, - packageEvent.artifact_size_bytes, - ); - const downloadedDigest = `sha256:${crypto - .createHash("sha256") - .update(downloaded.content) - .digest("hex")}`; - assert.strictEqual(downloadedDigest, packageEvent.artifact_digest); - const inspect = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-release-")); - try { - const executable = path.join(inspect, "hello-clusterflux"); - fs.writeFileSync(executable, downloaded.content); - fs.chmodSync(executable, 0o755); - assert.strictEqual( - cp.execFileSync(executable, { encoding: "utf8" }), - "hello from a real Clusterflux build\n" - ); - } finally { - fs.rmSync(inspect, { recursive: true, force: true }); - } - const cliDownloadDirectory = fs.mkdtempSync( - path.join(os.tmpdir(), "clusterflux-cli-download-") - ); - try { - const cliDownloadPath = path.join(cliDownloadDirectory, "hello-clusterflux"); - const cliDownload = JSON.parse( - cp.execFileSync( - "cargo", - [ - "run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", - "artifact", "download", artifact, - "--to", cliDownloadPath, - "--max-bytes", "1048576", - "--coordinator", `clusterflux+tcp://${addr.host}:${addr.port}`, - "--tenant", "tenant", - "--project-id", "project", - "--user", "user", - "--json", - ], - { cwd: repo, env: process.env, encoding: "utf8" } - ) - ); - assert.strictEqual(cliDownload.command, "artifact download"); - assert.strictEqual(cliDownload.local_download.status, "local_bytes_written"); - assert.strictEqual( - cliDownload.local_download.verified_digest, - packageEvent.artifact_digest - ); - assert.strictEqual( - `sha256:${crypto - .createHash("sha256") - .update(fs.readFileSync(cliDownloadPath)) - .digest("hex")}`, - packageEvent.artifact_digest - ); - } finally { - fs.rmSync(cliDownloadDirectory, { recursive: true, force: true }); - } - assert.strictEqual(downloaded.response.content_eof, true); - assert.strictEqual( - downloaded.response.charged_download_bytes, - packageEvent.artifact_size_bytes - ); - assert.strictEqual(downloaded.response.link.artifact, artifact); - - const crossActorRevoke = await send(addr, { - type: "revoke_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "other-user", - artifact, - token_digest: link.link.scoped_token_digest, - }); - assert.strictEqual(crossActorRevoke.type, "error"); - assert.match(crossActorRevoke.message, /token is invalid/); - - const revoked = await send(addr, { - type: "revoke_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - token_digest: link.link.scoped_token_digest, - }); - assert.strictEqual(revoked.type, "artifact_download_link_revoked"); - assert.strictEqual(revoked.link.scoped_token_digest, link.link.scoped_token_digest); - - const revokedOpen = await send(addr, { - type: "open_artifact_download_stream", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - token_digest: link.link.scoped_token_digest, - chunk_bytes: 1, - }); - assert.strictEqual(revokedOpen.type, "error"); - assert.match(revokedOpen.message, /revoked/); - - const gcReport = await send(addr, signedNodeRequest(downloadNode, downloadNodeIdentity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: downloadNode, - capabilities: downloadNodeCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: false, - online: true, - })); - assert.strictEqual(gcReport.type, "node_capabilities_recorded"); - - const collectedLink = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - max_bytes: 1024 * 1024, - ttl_seconds: 60, - }); - assert.strictEqual(collectedLink.type, "error"); - assert.match(collectedLink.message, /unavailable from current retention/); - } finally { - worker?.child.kill("SIGTERM"); - coordinator.kill("SIGTERM"); - } - - console.log("Artifact download smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/artifact-export-smoke.js b/scripts/artifact-export-smoke.js deleted file mode 100644 index f33b0ba..0000000 --- a/scripts/artifact-export-smoke.js +++ /dev/null @@ -1,275 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); -const { - ensureRootlessPodman, - flagshipNodeCapabilities, - launchFlagship, - repo, - runFlagshipWorker, - send, - waitForJsonLine, - waitForNodeStatus, -} = require("./real-flagship-harness"); - -const sourceNode = "node-export-source"; -const sourceIdentity = nodeIdentity("artifact-export-smoke", sourceNode); - -function nodeCapabilities() { - return flagshipNodeCapabilities(); -} - -function runJson(command, args, options = {}) { - return new Promise((resolve, reject) => { - const child = cp.spawn(command, args, { cwd: repo, ...options }); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.once("error", reject); - child.once("exit", (code) => { - if (code !== 0) { - reject( - new Error( - `${command} ${args.join(" ")} failed with code ${code}\n${stderr}\n${stdout}` - ) - ); - return; - } - try { - resolve(JSON.parse(stdout)); - } catch (error) { - reject(new Error(`${command} did not return JSON\n${stdout}\n${error.message}`)); - } - }); - }); -} - -async function reportNode( - addr, - node, - identity, - { directConnectivity = true, online = true, artifacts = [] } = {} -) { - const response = await send(addr, signedNodeRequest(node, identity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node, - capabilities: nodeCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: artifacts, - direct_connectivity: directConnectivity, - online, - })); - assert.strictEqual(response.type, "node_capabilities_recorded"); - assert.strictEqual(response.node, node); -} - -(async () => { - ensureRootlessPodman(); - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback", - ], - { - cwd: repo, - env: { ...process.env, CLUSTERFLUX_NODE_STALE_AFTER_SECONDS: "1" }, - } - ); - - let worker; - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - worker = await runFlagshipWorker(addr, sourceNode, sourceIdentity); - const workerReady = await worker.ready; - assert.strictEqual(workerReady.node_status, "ready"); - assert.strictEqual(workerReady.mode, "worker"); - const firstNodeTaskCompletion = waitForNodeStatus(worker.child, "completed"); - const { compileEvent, process: virtualProcess } = await launchFlagship(addr); - const workerCompletion = await firstNodeTaskCompletion; - assert.strictEqual(workerCompletion.node_status, "completed"); - assert.strictEqual( - workerCompletion.task_assignment_response.task_spec.task_definition, - "snapshot_current_project" - ); - assert.strictEqual( - workerCompletion.virtual_thread, - workerCompletion.task_assignment_response.task_spec.task_instance - ); - assert.strictEqual(compileEvent.status_code, 0); - assert.match( - compileEvent.artifact_path, - /^\/vfs\/artifacts\/hello-clusterflux-[0-9a-f]{64}$/ - ); - const artifact = compileEvent.artifact_path.slice("/vfs/artifacts/".length); - - await reportNode(addr, sourceNode, sourceIdentity, { - artifacts: [artifact], - }); - - const receiverIdentity = nodeIdentity("artifact-export-smoke", "node-export-receiver"); - const attachedReceiver = await send(addr, { - type: "attach_node", - tenant: "tenant", - project: "project", - node: "node-export-receiver", - public_key: receiverIdentity.publicKey, - }); - assert.strictEqual(attachedReceiver.type, "node_attached"); - await reportNode(addr, "node-export-receiver", receiverIdentity); - - const exportPlan = await send(addr, { - type: "export_artifact_to_node", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - receiver_node: "node-export-receiver", - direct_connectivity: true, - failure_reason: "", - }); - assert.strictEqual(exportPlan.type, "artifact_export_plan"); - assert.strictEqual(exportPlan.source_node, "node-export-source"); - assert.strictEqual(exportPlan.receiver_node, "node-export-receiver"); - assert.strictEqual(exportPlan.plan.transport, "NativeQuic"); - assert.strictEqual(exportPlan.plan.scope.tenant, "tenant"); - assert.strictEqual(exportPlan.plan.scope.project, "project"); - assert.strictEqual(exportPlan.plan.scope.process, virtualProcess); - assert.deepStrictEqual(exportPlan.plan.scope.object, { Artifact: artifact }); - assert.strictEqual(exportPlan.plan.source.node, "node-export-source"); - assert.strictEqual(exportPlan.plan.destination.node, "node-export-receiver"); - assert.strictEqual(exportPlan.plan.coordinator_assisted_rendezvous, true); - assert.strictEqual(exportPlan.plan.coordinator_bulk_relay_allowed, false); - assert.match(exportPlan.plan.authorization_digest, /^sha256:[0-9a-f]{64}$/); - assert.strictEqual(exportPlan.artifact_size_bytes, compileEvent.artifact_size_bytes); - - const temp = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-artifact-export-")); - const exportPath = path.join(temp, "hello-clusterflux"); - cp.execFileSync( - "cargo", - ["build", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux"], - { cwd: repo, stdio: "inherit" } - ); - const cliBinary = path.join( - path.resolve(repo, process.env.CARGO_TARGET_DIR || "target"), - "debug", - process.platform === "win32" ? "clusterflux.exe" : "clusterflux" - ); - await reportNode(addr, sourceNode, sourceIdentity, { - artifacts: [artifact], - }); - const cliExport = await runJson(cliBinary, [ - "artifact", - "export", - "--coordinator", - `${addr.host}:${addr.port}`, - "--tenant", - "tenant", - "--project-id", - "project", - "--user", - "user", - "--json", - artifact, - "--receiver-node", - "node-export-receiver", - "--to", - exportPath, - ]); - assert.strictEqual(cliExport.command, "artifact export"); - assert.strictEqual(cliExport.export_plan.local_bytes_written_by_cli, true); - assert.strictEqual(cliExport.export_plan.local_export_status, "local_bytes_written"); - assert.strictEqual( - cliExport.export_plan.bytes_written, - compileEvent.artifact_size_bytes - ); - assert.strictEqual(cliExport.local_export.stream.content_material_returned_in_report, false); - assert.strictEqual( - cliExport.local_export.verified_digest, - compileEvent.artifact_digest - ); - fs.chmodSync(exportPath, 0o755); - assert.strictEqual( - cp.execFileSync(exportPath, { encoding: "utf8" }), - "hello from a real Clusterflux build\n" - ); - - const crossTenant = await send(addr, { - type: "export_artifact_to_node", - tenant: "other", - project: "project", - actor_user: "user", - artifact, - receiver_node: "node-export-receiver", - direct_connectivity: true, - failure_reason: "", - }); - assert.strictEqual(crossTenant.type, "error"); - assert.match(crossTenant.message, /artifact does not exist/); - - await reportNode(addr, sourceNode, sourceIdentity, { artifacts: [artifact] }); - const failedDirect = await send(addr, { - type: "export_artifact_to_node", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - receiver_node: "node-export-receiver", - direct_connectivity: false, - failure_reason: "nat traversal failed", - }); - assert.strictEqual(failedDirect.type, "error"); - assert.match(failedDirect.message, /nat traversal failed/); - assert.match(failedDirect.message, /coordinator bulk relay is disabled/); - - await reportNode(addr, "node-export-receiver", receiverIdentity, { online: false }); - await new Promise((resolve) => setTimeout(resolve, 2100)); - await reportNode(addr, sourceNode, sourceIdentity, { artifacts: [artifact] }); - const offlineReceiver = await send(addr, { - type: "export_artifact_to_node", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact, - receiver_node: "node-export-receiver", - direct_connectivity: true, - failure_reason: "", - }); - assert.strictEqual(offlineReceiver.type, "error"); - assert.match(offlineReceiver.message, /offline/); - } finally { - worker?.child.kill("SIGTERM"); - coordinator.kill("SIGTERM"); - } - - console.log("Artifact export smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/check-code-size.sh b/scripts/check-code-size.sh deleted file mode 100755 index 96e54d3..0000000 --- a/scripts/check-code-size.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$repo_root" - -maximum_lines=3000 -failed=0 -source_roots=(crates) -if [[ -d private/hosted-policy/src ]]; then - source_roots+=(private/hosted-policy/src) -fi -while IFS= read -r -d '' file; do - case "$file" in - */tests.rs|*/tests/*) continue ;; - esac - lines="$(wc -l < "$file")" - if ((lines > maximum_lines)); then - printf '%s has %s lines; production file limit is %s\n' "$file" "$lines" "$maximum_lines" >&2 - failed=1 - fi -done < <(find "${source_roots[@]}" -type f -name '*.rs' -print0) - -if ((failed)); then - exit 1 -fi -printf 'production source file size guard passed (%s lines maximum)\n' "$maximum_lines" diff --git a/scripts/check-docs.js b/scripts/check-docs.js deleted file mode 100644 index dce6c9e..0000000 --- a/scripts/check-docs.js +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env node -const fs = require("node:fs"); -const path = require("node:path"); - -const root = path.resolve(__dirname, ".."); -const publicDocs = [ - "README.md", - "SECURITY.md", - "docs/getting-started.md", - "docs/architecture.md", - "docs/nodes.md", - "docs/environments.md", - "docs/artifacts.md", - "docs/debugging.md", - "docs/task-abi.md", - "docs/self-hosting.md", - "docs/security.md", -]; -const contributorDocs = ["docs/contributing/releases.md"]; -const privateDocs = [ - "private/docs/hosted-deployment.md", - "private/docs/authentik.md", - "private/docs/community-policy.md", - "private/docs/bandwidth-and-cost-controls.md", - "private/docs/publishing.md", -]; -const internalDocs = ["internal/finish_mvp_2.md"]; -const filteredPublicTree = - process.env.CLUSTERFLUX_FILTERED_PUBLIC_TREE === "1" || - fs.existsSync(path.join(root, "CLUSTERFLUX_PUBLIC_TREE.json")); - -const failures = []; -const expectExactMarkdownSet = (directory, expected) => { - const actual = fs - .readdirSync(path.join(root, directory), { withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) - .map((entry) => path.posix.join(directory, entry.name)) - .sort(); - const wanted = [...expected].sort(); - if (JSON.stringify(actual) !== JSON.stringify(wanted)) { - failures.push(`${directory} markdown set is ${actual.join(", ")}; expected ${wanted.join(", ")}`); - } -}; - -const requiredDocs = filteredPublicTree - ? [...publicDocs, ...contributorDocs] - : [...publicDocs, ...contributorDocs, ...privateDocs, ...internalDocs]; -for (const file of requiredDocs) { - if (!fs.existsSync(path.join(root, file))) failures.push(`missing canonical document: ${file}`); -} -expectExactMarkdownSet("docs", publicDocs.filter((file) => file.startsWith("docs/"))); -expectExactMarkdownSet("docs/contributing", contributorDocs); -if (filteredPublicTree) { - for (const directory of ["private", "internal"]) { - if (fs.existsSync(path.join(root, directory))) { - failures.push(`${directory}/ must not exist in the filtered public tree`); - } - } -} - -const forbidden = [ - [/\bmvp\b/i, "internal milestone term"], - [/acceptance criteria/i, "internal gate language"], - [/release verification/i, "internal release language"], - [/public\/private source split/i, "source split narrative"], - [/founder|business decisions/i, "business planning narrative"], - [/hacker news|\bHN\b/, "launch-channel narrative"], - [/\busers can\b/i, "indirect reader wording"], - [/node\s+scripts\//i, "developer script instruction"], - [/scripts\/[^\s)]*smoke/i, "smoke script instruction"], - [/internal\/[^\s)]*/i, "internal tooling reference"], - [/private\/[^\s)]*/i, "private source reference"], -]; -const topLevelCommands = new Set([ - "doctor", "login", "logout", "auth", "agent", "key", "project", "inspect", - "build", "bundle", "run", "node", "process", "task", "logs", "artifact", - "dap", "debug", "quota", "admin", -]); - -for (const file of publicDocs) { - const absolute = path.join(root, file); - const content = fs.readFileSync(absolute, "utf8"); - for (const [pattern, description] of forbidden) { - if (pattern.test(content)) failures.push(`${file}: contains ${description}`); - } - for (const match of content.matchAll(/\]\(([^)#]+)(?:#[^)]+)?\)/g)) { - const target = match[1]; - if (/^(?:https?:|mailto:)/.test(target)) continue; - const resolved = path.resolve(path.dirname(absolute), target); - if (!fs.existsSync(resolved)) failures.push(`${file}: broken link ${target}`); - } - for (const line of content.split(/\r?\n/)) { - const command = line.trim().match(/^clusterflux\s+([a-z][a-z-]*)\b/); - if (command && !topLevelCommands.has(command[1])) { - failures.push(`${file}: unknown top-level CLI command ${command[1]}`); - } - } -} - -const rootMarkdown = fs - .readdirSync(root, { withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) - .map((entry) => entry.name) - .sort(); -if (JSON.stringify(rootMarkdown) !== JSON.stringify(["README.md", "SECURITY.md"])) { - failures.push(`top-level markdown set is ${rootMarkdown.join(", ")}; expected README.md, SECURITY.md`); -} - -if (failures.length) { - for (const failure of failures) console.error(failure); - process.exit(1); -} -console.log("documentation checks passed"); diff --git a/scripts/check-old-name.sh b/scripts/check-old-name.sh deleted file mode 100755 index 9a871de..0000000 --- a/scripts/check-old-name.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$repo_root" - -legacy_lower="$(printf '%s%s' 'disa' 'smer')" -legacy_title="$(printf '%s%s' 'Disa' 'smer')" -legacy_upper="$(printf '%s%s' 'DISA' 'SMER')" -pattern="${legacy_lower}|${legacy_title}|${legacy_upper}" - -allowed_content='^\./scripts/migrate-clusterflux-state\.sh:' -matches="$( - rg -n --hidden \ - --glob '!**/.git/**' \ - --glob '!**/target/**' \ - --glob '!**/node_modules/**' \ - --glob '!**/vendor/**' \ - --glob '!**/.direnv/**' \ - --glob '!**/.cache/**' \ - --glob '!**/dist/**' \ - --glob '!**/out/**' \ - "$pattern" . 2>/dev/null | rg -v "$allowed_content" || true -)" - -paths="$( - find . \ - \( -type d \( -name .git -o -name target -o -name node_modules -o -name vendor -o -name .direnv -o -name .cache -o -name dist -o -name out \) -prune \) -o \ - -iname "*${legacy_lower}*" -print | sort || true -)" - -if [[ -n "$matches" || -n "$paths" ]]; then - [[ -z "$matches" ]] || printf '%s\n' "$matches" >&2 - [[ -z "$paths" ]] || printf '%s\n' "$paths" >&2 - printf 'unexpected legacy product name remains\n' >&2 - exit 1 -fi - -printf 'old-name guard passed\n' diff --git a/scripts/cli-browser-login-flow-smoke.js b/scripts/cli-browser-login-flow-smoke.js deleted file mode 100644 index 0c6341b..0000000 --- a/scripts/cli-browser-login-flow-smoke.js +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const net = require("net"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const tmp = path.join(repo, "target", "acceptance", "tmp", "cli-browser-login-flow"); -const project = path.join(tmp, "project"); -fs.rmSync(tmp, { recursive: true, force: true }); -fs.mkdirSync(project, { recursive: true }); - -function writeOpener() { - const opener = path.join(tmp, "browser-opener.js"); - const trace = path.join(tmp, "browser-opener.log"); - fs.writeFileSync( - opener, - `#!/usr/bin/env node -const fs = require("fs"); -const trace = ${JSON.stringify(trace)}; -const loginUrl = new URL(process.argv[2]); -const state = loginUrl.searchParams.get("state"); -const nonce = loginUrl.searchParams.get("nonce"); -const challenge = loginUrl.searchParams.get("code_challenge"); -if (loginUrl.protocol !== "https:" || !state || !nonce || !challenge) { - fs.appendFileSync(trace, "missing server-owned OIDC parameters\\n"); - process.exit(1); -} -fs.appendFileSync(trace, "server-owned browser transaction\\n"); -// Model a real browser/opener that remains alive after the CLI transaction. -// Its descriptors must not keep the invoking CLI process open. -setTimeout(() => process.exit(0), 5000); -` - ); - fs.chmodSync(opener, 0o755); - return opener; -} - -function startCoordinator() { - return new Promise((resolve, reject) => { - const requests = []; - const server = net.createServer((socket) => { - let buffered = ""; - socket.on("data", (chunk) => { - buffered += chunk.toString("utf8"); - while (buffered.includes("\n")) { - const newline = buffered.indexOf("\n"); - const line = buffered.slice(0, newline); - buffered = buffered.slice(newline + 1); - const envelope = JSON.parse(line); - requests.push(envelope); - assert.strictEqual(envelope.type, "coordinator_request"); - assert.strictEqual(envelope.protocol_version, 1); - assert.strictEqual(envelope.authentication.kind, "none"); - const request = envelope.payload; - - if (requests.length === 1) { - assert.strictEqual(envelope.request_id, "cli-1"); - assert.strictEqual(envelope.operation, "begin_oidc_browser_login"); - assert.deepStrictEqual(request, { - type: "begin_oidc_browser_login", - }); - socket.write( - `${JSON.stringify({ - type: "oidc_browser_login_started", - transaction_id: "login-transaction", - polling_secret: "opaque-polling-secret", - authorization_url: - "https://auth.michelpaulissen.com/application/o/authorize/?state=server-state&nonce=server-nonce&code_challenge=server-pkce&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fclusterflux.michelpaulissen.com%2Fauth%2Fcallback", - expires_at_epoch_seconds: 1800000000, - })}\n` - ); - continue; - } - - assert.strictEqual(envelope.request_id, "cli-2"); - assert.strictEqual(envelope.operation, "poll_oidc_browser_login"); - assert.deepStrictEqual(request, { - type: "poll_oidc_browser_login", - transaction_id: "login-transaction", - polling_secret: "opaque-polling-secret", - }); - socket.end( - `${JSON.stringify({ - type: "oidc_browser_session", - session: { - tenant: "tenant-smoke", - project: "project-smoke", - user: "user-smoke", - cli_session_credential_kind: "CliDeviceSession", - cli_session_secret: "scoped-cli-session-secret", - expires_at_epoch_seconds: 1800000000, - provider_tokens_sent_to_nodes: false, - }, - })}\n` - ); - server.close(); - } - }); - }); - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - resolve({ - url: `${address.address}:${address.port}`, - requests, - close: () => - new Promise((closeResolve) => { - if (!server.listening) closeResolve(); - else server.close(() => closeResolve()); - }), - }); - }); - }); -} - -function runClusterflux(args, env) { - return new Promise((resolve, reject) => { - const child = cp.spawn( - "cargo", - [ - "run", - "-q", - "--manifest-path", - path.join(repo, "Cargo.toml"), - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - ...args, - ], - { cwd: project, env, stdio: ["ignore", "pipe", "pipe"] } - ); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => (stdout += chunk.toString("utf8"))); - child.stderr.on("data", (chunk) => (stderr += chunk.toString("utf8"))); - child.once("error", reject); - child.once("close", (code) => { - if (code === 0) resolve(stdout); - else reject(new Error(`clusterflux exited ${code}\n${stderr}\n${stdout}`)); - }); - }); -} - -(async () => { - const opener = writeOpener(); - const coordinator = await startCoordinator(); - try { - const loginStarted = Date.now(); - const report = JSON.parse( - await runClusterflux( - [ - "login", - "--browser", - "--json", - "--coordinator", - coordinator.url, - "--project-id", - "project-smoke", - ], - { - ...process.env, - CLUSTERFLUX_BROWSER_OPEN_COMMAND: opener, - CLUSTERFLUX_BROWSER_LOGIN_TIMEOUT_SECONDS: "5", - } - ) - ); - assert( - Date.now() - loginStarted < 3000, - "a long-lived browser opener must not keep CLI output pipes or login completion open" - ); - assert.strictEqual(report.plan.coordinator, coordinator.url); - assert.strictEqual(report.boundary.cli_contacted_coordinator, true); - assert.strictEqual(report.boundary.scoped_cli_session_received, true); - assert.strictEqual(report.boundary.local_cli_session_file_written, true); - assert.strictEqual(report.boundary.provider_tokens_persisted_locally, false); - assert.strictEqual(report.boundary.provider_tokens_exposed_to_cli, false); - assert.strictEqual(report.boundary.provider_tokens_sent_to_nodes, false); - assert.strictEqual(report.boundary.coordinator_session_requests, 2); - assert.strictEqual(coordinator.requests.length, 2); - - const sessionFile = path.join(project, ".clusterflux", "session.json"); - const sessionText = fs.readFileSync(sessionFile, "utf8"); - const session = JSON.parse(sessionText); - assert.strictEqual(session.kind, "human"); - assert.strictEqual(session.coordinator, coordinator.url); - assert.strictEqual(session.tenant, "tenant-smoke"); - assert.strictEqual(session.project, "project-smoke"); - assert.strictEqual(session.user, "user-smoke"); - assert.strictEqual(session.cli_session_credential_kind, "CliDeviceSession"); - assert.strictEqual(session.token_expiry_posture, "expires_at"); - assert.strictEqual(session.expires_at, "1800000000"); - assert.strictEqual(session.provider_tokens_exposed_to_cli, false); - assert.strictEqual(session.provider_tokens_sent_to_nodes, false); - assert.doesNotMatch( - sessionText, - /access_token|refresh_token|id_token|provider-secret|authorization_code|Bearer/ - ); - - const authStatus = JSON.parse( - await runClusterflux(["auth", "status", "--json"], process.env) - ); - assert.strictEqual(authStatus.active_coordinator, coordinator.url); - assert.strictEqual(authStatus.principal, "user-smoke"); - assert.strictEqual(authStatus.tenant, "tenant-smoke"); - assert.strictEqual(authStatus.project, "project-smoke"); - assert.strictEqual(authStatus.session.kind, "human"); - assert.strictEqual(authStatus.session.source, "session_file"); - assert.strictEqual(authStatus.session.provider_tokens_exposed_to_cli, false); - assert.strictEqual(authStatus.session.provider_tokens_exposed_to_nodes, false); - } finally { - await coordinator.close(); - } - console.log("CLI browser login flow smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/cli-error-exit-smoke.js b/scripts/cli-error-exit-smoke.js deleted file mode 100755 index 68ad258..0000000 --- a/scripts/cli-error-exit-smoke.js +++ /dev/null @@ -1,365 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const http = require("http"); -const os = require("os"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const project = path.join(repo, "tests/fixtures/runtime-conformance"); -const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-cli-error-")); - -function runClusterflux(args) { - return new Promise((resolve) => { - const child = cp.spawn( - "cargo", - ["run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", ...args], - { - cwd: repo, - stdio: ["ignore", "pipe", "pipe"], - } - ); - let stdout = ""; - let stderr = ""; - child.stdout.setEncoding("utf8"); - child.stderr.setEncoding("utf8"); - child.stdout.on("data", (chunk) => { - stdout += chunk; - }); - child.stderr.on("data", (chunk) => { - stderr += chunk; - }); - child.on("close", (code, signal) => { - resolve({ code, signal, stdout, stderr }); - }); - }); -} - -async function runWithOneCoordinatorResponse(buildArgs, response) { - let request = ""; - const server = http.createServer((incoming, outgoing) => { - incoming.setEncoding("utf8"); - incoming.on("data", (chunk) => { - request += chunk; - }); - incoming.on("end", () => { - outgoing.writeHead(200, { "content-type": "application/json" }); - outgoing.end(JSON.stringify(response)); - server.close(); - }); - }); - - const address = await new Promise((resolve) => { - server.listen(0, "127.0.0.1", () => resolve(server.address())); - }); - const coordinator = `http://${address.address}:${address.port}`; - const result = await runClusterflux(buildArgs(coordinator)); - return { request, result }; -} - -async function main() { - const environmentProject = path.join(tempRoot, "missing-env-project"); - fs.mkdirSync(path.join(environmentProject, "src"), { recursive: true }); - fs.writeFileSync( - path.join(environmentProject, "Cargo.toml"), - "[package]\nname = \"missing-env-project\"\nversion = \"0.1.0\"\nedition = \"2021\"\n" - ); - fs.writeFileSync( - path.join(environmentProject, "src", "main.rs"), - "fn main() { let _target = env!(\"linux\"); }\n" - ); - const environmentFailure = await runClusterflux([ - "build", - "--project", - environmentProject, - "--json", - ]); - assert.strictEqual(environmentFailure.signal, null, environmentFailure.stderr); - assert.strictEqual(environmentFailure.code, 26, environmentFailure.stderr); - const environmentReport = JSON.parse(environmentFailure.stdout); - assert.strictEqual(environmentReport.status, "blocked_before_schedule"); - assert.strictEqual(environmentReport.scheduled_work, false); - assert.strictEqual(environmentReport.machine_error.category, "environment"); - assert.strictEqual( - environmentReport.machine_error.process_exit_code_applied, - true - ); - assert( - environmentReport.machine_error.next_actions.includes("clusterflux inspect") - ); - assert.strictEqual(environmentReport.diagnostics[0].code, "missing_environment"); - - const nonInteractive = await runClusterflux([ - "run", - "build", - "--project", - project, - "--non-interactive", - "--json", - ]); - assert.strictEqual(nonInteractive.signal, null, nonInteractive.stderr); - assert.strictEqual(nonInteractive.code, 20, nonInteractive.stderr); - assert.doesNotMatch(nonInteractive.stderr, /Opening Clusterflux browser login/); - const nonInteractiveReport = JSON.parse(nonInteractive.stdout); - assert.strictEqual(nonInteractiveReport.status, "authentication_required"); - assert.strictEqual(nonInteractiveReport.non_interactive, true); - assert.strictEqual(nonInteractiveReport.browser_opened, false); - assert.strictEqual(nonInteractiveReport.machine_error.category, "authentication"); - assert.strictEqual(nonInteractiveReport.machine_error.stable_exit_code, 20); - assert.strictEqual( - nonInteractiveReport.machine_error.process_exit_code_applied, - true - ); - assert( - nonInteractiveReport.machine_error.next_actions.includes( - "pass --local to run against local services" - ) - ); - - let request = ""; - const server = http.createServer((incoming, outgoing) => { - incoming.setEncoding("utf8"); - incoming.on("data", (chunk) => { - request += chunk; - }); - incoming.on("end", () => { - outgoing.writeHead(200, { "content-type": "application/json" }); - outgoing.end( - JSON.stringify({ - type: "error", - message: "quota unavailable: resource limit exceeded for api_calls", - }) - ); - server.close(); - }); - }); - - const address = await new Promise((resolve) => { - server.listen(0, "127.0.0.1", () => resolve(server.address())); - }); - const coordinator = `http://${address.address}:${address.port}`; - - const result = await runClusterflux([ - "run", - "build", - "--project", - project, - "--coordinator", - coordinator, - "--json", - ]); - - assert.strictEqual(result.signal, null, result.stderr); - assert.strictEqual(result.code, 22, result.stderr); - assert.match(request, /"type":"start_process"/); - const report = JSON.parse(result.stdout); - assert.strictEqual(report.status, "coordinator_rejected"); - assert.strictEqual(report.run_start.machine_error.category, "quota"); - assert.strictEqual(report.run_start.machine_error.resource_category, "api_calls"); - assert.strictEqual(report.run_start.machine_error.community_tier_language, true); - assert.strictEqual( - report.run_start.machine_error.community_tier_label, - "community tier" - ); - assert.doesNotMatch(result.stdout, new RegExp(["free", "tier"].join(" "), "i")); - assert.strictEqual( - report.run_start.machine_error.private_abuse_heuristics_exposed, - false - ); - assert.strictEqual(report.run_start.machine_error.stable_exit_code, 22); - assert.strictEqual( - report.run_start.machine_error.process_exit_code_applied, - true - ); - assert( - report.run_start.machine_error.next_actions.includes("clusterflux quota status") - ); - - const capabilityFailure = await runWithOneCoordinatorResponse( - (coordinator) => [ - "run", - "build", - "--project", - project, - "--coordinator", - coordinator, - "--json", - ], - { - type: "error", - message: - "scheduler placement failed: no capable node for placement: missing capability Command", - } - ); - assert.strictEqual(capabilityFailure.result.signal, null, capabilityFailure.result.stderr); - assert.strictEqual(capabilityFailure.result.code, 24, capabilityFailure.result.stderr); - assert.match(capabilityFailure.request, /"type":"start_process"/); - const capabilityReport = JSON.parse(capabilityFailure.result.stdout); - assert.strictEqual( - capabilityReport.run_start.machine_error.category, - "capability" - ); - assert.strictEqual( - capabilityReport.run_start.machine_error.process_exit_code_applied, - true - ); - assert( - capabilityReport.run_start.machine_error.next_actions.includes( - "attach a node with the required capabilities" - ) - ); - - const nodePolicyFailure = await runWithOneCoordinatorResponse( - (coordinator) => [ - "run", - "build", - "--project", - project, - "--coordinator", - coordinator, - "--json", - ], - { - type: "error", - message: "node policy denied native command execution", - } - ); - assert.strictEqual(nodePolicyFailure.result.signal, null, nodePolicyFailure.result.stderr); - assert.strictEqual(nodePolicyFailure.result.code, 23, nodePolicyFailure.result.stderr); - assert.match(nodePolicyFailure.request, /"type":"start_process"/); - const nodePolicyReport = JSON.parse(nodePolicyFailure.result.stdout); - assert.strictEqual( - nodePolicyReport.run_start.machine_error.category, - "policy" - ); - assert.strictEqual( - nodePolicyReport.run_start.machine_error.process_exit_code_applied, - true - ); - assert( - nodePolicyReport.run_start.machine_error.next_actions.includes( - "check coordinator policy for this action" - ) - ); - - const programFailure = await runWithOneCoordinatorResponse( - (coordinator) => [ - "task", - "list", - "--coordinator", - coordinator, - "--json", - ], - { - type: "task_events", - events: [ - { - process: "vp-current", - task: "compile", - terminal_state: "failed", - environment: "linux", - node: "node-linux", - status_code: 1, - stderr_tail: "task exited with status 1", - }, - ], - } - ); - assert.strictEqual(programFailure.result.signal, null, programFailure.result.stderr); - assert.strictEqual(programFailure.result.code, 0, programFailure.result.stderr); - assert.match(programFailure.request, /"type":"list_task_events"/); - const programReport = JSON.parse(programFailure.result.stdout); - assert.strictEqual(programReport.tasks[0].machine_error.category, "program"); - assert.strictEqual(programReport.tasks[0].machine_error.stable_exit_code, 27); - assert( - programReport.tasks[0].machine_error.next_actions.includes("clusterflux logs") - ); - - const artifactDownload = await runWithOneCoordinatorResponse( - (coordinator) => [ - "artifact", - "download", - "app.txt", - "--coordinator", - coordinator, - "--json", - ], - { - type: "artifact_download_denied", - message: "artifact download unauthorized for project", - } - ); - assert.strictEqual(artifactDownload.result.signal, null, artifactDownload.result.stderr); - assert.strictEqual(artifactDownload.result.code, 21, artifactDownload.result.stderr); - assert.match(artifactDownload.request, /"type":"create_artifact_download_link"/); - const artifactDownloadReport = JSON.parse(artifactDownload.result.stdout); - assert.strictEqual( - artifactDownloadReport.download_session.machine_error.category, - "authorization" - ); - assert.strictEqual( - artifactDownloadReport.download_session.machine_error.process_exit_code_applied, - true - ); - - const artifactExport = await runWithOneCoordinatorResponse( - (coordinator) => [ - "artifact", - "export", - "app.txt", - "--to", - path.join(project, "target", "blocked-artifact.txt"), - "--coordinator", - coordinator, - "--json", - ], - { - type: "artifact_export_unavailable", - message: "direct connectivity unavailable for artifact export", - } - ); - assert.strictEqual(artifactExport.result.signal, null, artifactExport.result.stderr); - assert.strictEqual(artifactExport.result.code, 25, artifactExport.result.stderr); - assert.match(artifactExport.request, /"type":"export_artifact_to_node"/); - const artifactExportReport = JSON.parse(artifactExport.result.stdout); - assert.strictEqual( - artifactExportReport.export_plan.machine_error.category, - "connectivity" - ); - assert.strictEqual( - artifactExportReport.export_plan.machine_error.process_exit_code_applied, - true - ); - - const confirmation = await runClusterflux([ - "process", - "cancel", - "--coordinator", - "127.0.0.1:9", - "--json", - ]); - assert.strictEqual(confirmation.signal, null, confirmation.stderr); - assert.strictEqual(confirmation.code, 23, confirmation.stderr); - const confirmationReport = JSON.parse(confirmation.stdout); - assert.strictEqual(confirmationReport.status, "confirmation_required"); - assert.strictEqual(confirmationReport.coordinator_request_sent, false); - assert.strictEqual(confirmationReport.machine_error.category, "policy"); - assert.strictEqual( - confirmationReport.machine_error.process_exit_code_applied, - true - ); - assert( - confirmationReport.next_actions.some((action) => action.includes("--yes")) - ); -} - -main() - .then(() => { - console.log("CLI error exit smoke passed"); - }) - .catch((error) => { - console.error(error); - process.exit(1); - }); diff --git a/scripts/cli-happy-path-live-smoke.js b/scripts/cli-happy-path-live-smoke.js deleted file mode 100644 index 9439f75..0000000 --- a/scripts/cli-happy-path-live-smoke.js +++ /dev/null @@ -1,7128 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const https = require("https"); -const os = require("os"); -const path = require("path"); -const { DapClient } = require("./dap-client"); -const { agentIdentity, signedAgentWorkflowRequest } = require("./agent-signing"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { - nodeIdentity, - nodeIdentityFromPrivateKey, - signedNodeHeartbeat, - signedNodeRequest, -} = require("./node-signing"); -const { configurePodmanTestEnvironment } = require("./podman-test-env"); - -const repo = path.resolve(__dirname, ".."); -configurePodmanTestEnvironment(repo); -if ( - !process.env.CLUSTERFLUX_PODMAN_NIX_SHELL && - cp.spawnSync("podman", ["--version"], { stdio: "ignore" }).status !== 0 && - cp.spawnSync("nix", ["--version"], { stdio: "ignore" }).status === 0 -) { - cp.execFileSync( - "nix", - ["shell", "nixpkgs#podman", "--command", "node", __filename], - { - cwd: repo, - env: { ...process.env, CLUSTERFLUX_PODMAN_NIX_SHELL: "1" }, - stdio: "inherit", - } - ); - process.exit(0); -} - -const releaseRoot = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_DIR || - path.join(repo, "target/public-release") -); -const acceptanceRoot = path.join(repo, "target/acceptance"); -const manifestPath = path.join(releaseRoot, "public-release-manifest.json"); -const reportPath = path.join(acceptanceRoot, "cli-happy-path-live.json"); -const serviceEndpoint = "https://clusterflux.michelpaulissen.com"; -const serviceAddr = - process.env.CLUSTERFLUX_PUBLIC_RELEASE_SERVICE_ADDR || - "clusterflux.michelpaulissen.com:443"; -const browserOpenCommand = - process.env.CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND; -const reuseSessionFile = - process.env.CLUSTERFLUX_CLI_HAPPY_PATH_REUSE_SESSION_FILE; -const qualityGateEvidencePath = - process.env.CLUSTERFLUX_QUALITY_GATE_EVIDENCE_PATH; -const enabled = process.env.CLUSTERFLUX_CLI_HAPPY_PATH_LIVE === "1"; -const strictFullRelease = process.env.CLUSTERFLUX_STRICT_FULL_RELEASE === "1"; -const strictVpsRestart = process.env.CLUSTERFLUX_STRICT_VPS_RESTART === "1"; -const strictVpsHost = process.env.CLUSTERFLUX_STRICT_VPS_HOST; -const strictVpsIdentity = process.env.CLUSTERFLUX_STRICT_VPS_IDENTITY; -const strictServiceUnit = - process.env.CLUSTERFLUX_STRICT_SERVICE_UNIT || - "clusterflux-hosted.service"; -const strictSoakSeconds = Number( - process.env.CLUSTERFLUX_STRICT_SOAK_SECONDS || "300" -); -const commands = []; - -function requireEnabled() { - if (!enabled) { - throw new Error( - "CLUSTERFLUX_CLI_HAPPY_PATH_LIVE=1 is required because this runs the live CLI happy path" - ); - } - if (!browserOpenCommand && !reuseSessionFile) { - throw new Error( - "CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND or CLUSTERFLUX_CLI_HAPPY_PATH_REUSE_SESSION_FILE is required" - ); - } - const hasSecondTenantSession = Boolean( - process.env.CLUSTERFLUX_SECOND_TENANT_SESSION_FILE - ); - if ( - strictFullRelease && - !hasSecondTenantSession - ) { - throw new Error( - "CLUSTERFLUX_STRICT_FULL_RELEASE=1 requires CLUSTERFLUX_SECOND_TENANT_SESSION_FILE so the compiled two-tenant Node and artifact collision can run" - ); - } - if (strictFullRelease && !process.env.CLUSTERFLUX_EXPIRED_USER_SESSION_FILE) { - throw new Error( - "CLUSTERFLUX_STRICT_FULL_RELEASE=1 requires CLUSTERFLUX_EXPIRED_USER_SESSION_FILE" - ); - } - if (strictFullRelease && !qualityGateEvidencePath) { - throw new Error( - "CLUSTERFLUX_STRICT_FULL_RELEASE=1 requires CLUSTERFLUX_QUALITY_GATE_EVIDENCE_PATH" - ); - } - if (strictFullRelease && !strictVpsRestart) { - throw new Error( - "CLUSTERFLUX_STRICT_FULL_RELEASE=1 requires CLUSTERFLUX_STRICT_VPS_RESTART=1" - ); - } - if (strictVpsRestart && (!strictVpsHost || !strictVpsIdentity)) { - throw new Error( - "strict VPS restart requires CLUSTERFLUX_STRICT_VPS_HOST and CLUSTERFLUX_STRICT_VPS_IDENTITY" - ); - } - if ( - !Number.isInteger(strictSoakSeconds) || - strictSoakSeconds < 120 || - strictSoakSeconds > 1800 - ) { - throw new Error("CLUSTERFLUX_STRICT_SOAK_SECONDS must be an integer from 120 to 1800"); - } -} - -function readJson(file) { - return JSON.parse(fs.readFileSync(file, "utf8")); -} - -function strictQualityGateEvidence(manifest) { - if (!strictFullRelease) return null; - const evidence = readJson(path.resolve(qualityGateEvidencePath)); - assert.strictEqual(evidence.source_commit, manifest.source_commit); - assert.strictEqual(evidence.source_tree_digest, manifest.source_tree_digest); - for (const gate of [evidence.private, evidence.public]) { - assert.strictEqual(gate.status, "passed"); - assert(Number.isFinite(gate.duration_ms) && gate.duration_ms > 0); - } - assert.strictEqual(evidence.public.independent_filtered_tree, true); - for (const id of [ - "formatting", - "clippy_warnings_denied", - "public_workspace_tests", - "private_hosted_policy_locked_tests", - "process_lifecycle_regressions", - "wasm_example_builds", - "filtered_public_tree_build_and_tests", - "vscode_extension_candidate", - ]) { - const check = evidence.checks?.[id]; - assert(check, `quality evidence omitted ${id}`); - assert.strictEqual(check.status, "passed"); - assert(Number.isFinite(check.duration_ms) && check.duration_ms > 0); - } - assert.strictEqual( - evidence.checks.vscode_extension_candidate.candidate_vsix.sha256, - manifest.release_candidate.extension_sha256 - ); - return evidence; -} - -function ensureDir(dir) { - fs.mkdirSync(dir, { recursive: true }); -} - -function sha256(bytes) { - return `sha256:${crypto.createHash("sha256").update(bytes).digest("hex")}`; -} - -function nonInteractiveGitEnv(extra = {}) { - return { - ...process.env, - GIT_TERMINAL_PROMPT: "0", - GIT_ASKPASS: process.env.GIT_ASKPASS || "/bin/false", - SSH_ASKPASS: process.env.SSH_ASKPASS || "/bin/false", - GIT_SSH_COMMAND: - process.env.GIT_SSH_COMMAND || - "ssh -o BatchMode=yes -o NumberOfPasswordPrompts=0", - ...extra, - }; -} - -function commandEnv(command, env) { - if (command !== "git") return env; - return nonInteractiveGitEnv(env); -} - -function recordCommand(command, args) { - const redacted = []; - let hideNext = false; - for (const argument of args) { - if (hideNext) { - redacted.push(""); - hideNext = false; - } else { - redacted.push(argument); - hideNext = ["--enrollment-grant", "--admin-token"].includes(argument); - } - } - commands.push([command, ...redacted].join(" ")); -} - -function run(command, args, options = {}) { - recordCommand(command, args); - return cp.execFileSync(command, args, { - cwd: repo, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - timeout: 15 * 60 * 1000, - ...options, - env: commandEnv(command, options.env), - }); -} - -function parseJsonOutput(output) { - const trimmed = output.trim(); - if (!trimmed) throw new Error("expected JSON output, got empty stdout"); - try { - return JSON.parse(trimmed); - } catch (_) { - // Commands may print progress before their final JSON report. - } - const lines = trimmed.split(/\r?\n/).filter(Boolean); - for (let index = lines.length - 1; index >= 0; index -= 1) { - try { - return JSON.parse(lines.slice(index).join("\n")); - } catch (_) { - // Keep scanning for the trailing JSON value. - } - } - throw new Error(`could not parse JSON output:\n${trimmed}`); -} - -function runJson(command, args, options = {}) { - return parseJsonOutput(run(command, args, options)); -} - -function authenticatedRequest(sessionSecret, request) { - return { - type: "authenticated", - session_secret: sessionSecret, - request, - }; -} - -function sendHostedControl(payload) { - return sendHostedControlEnvelope( - coordinatorWireRequest(payload, "strict-live") - ); -} - -function sendHostedControlEnvelope(envelope) { - const body = Buffer.from( - JSON.stringify(envelope) - ); - const url = new URL("/api/v1/control", serviceEndpoint); - return new Promise((resolve, reject) => { - const request = https.request( - url, - { - method: "POST", - headers: { - "content-type": "application/json", - "content-length": body.length, - }, - timeout: 30_000, - }, - (response) => { - const chunks = []; - response.on("data", (chunk) => chunks.push(chunk)); - response.on("end", () => { - const responseBody = Buffer.concat(chunks).toString("utf8"); - if (response.statusCode < 200 || response.statusCode >= 300) { - reject( - new Error( - `hosted control HTTP ${response.statusCode}: ${responseBody}` - ) - ); - return; - } - try { - resolve(JSON.parse(responseBody)); - } catch (error) { - reject( - new Error(`hosted control returned invalid JSON: ${error.message}`) - ); - } - }); - } - ); - request.on("timeout", () => - request.destroy(new Error("hosted control request timed out")) - ); - request.on("error", reject); - request.end(body); - }); -} - -async function runMalformedIdentifierSuite({ - clusterflux, - projectDir, - scope, - sessionSecret, - tenant, - project, - user, - suffix, - securityNode, - bundle, - releaseArtifact, -}) { - const scenarioStartedAt = Date.now(); - const forms = [ - { name: "empty", value: "" }, - { name: "whitespace", value: " \t" }, - { name: "control", value: "hostile\u0000id" }, - { name: "invalid_format", value: "hostile id!" }, - { name: "oversized", value: "x".repeat(256) }, - ]; - const tokenForms = forms - .filter((form) => form.name !== "invalid_format") - .map((form) => - form.name === "oversized" - ? { ...form, value: "x".repeat(257) } - : form - ); - assert( - Buffer.byteLength( - tokenForms.find((form) => form.name === "oversized").value - ) > 256, - "hostile token suite must exceed the signed-nonce and hosted-login byte limit" - ); - const agent = `hostile-id-agent-${suffix}`; - const agentIdentityRecord = agentIdentity("strict-hostile-id-agent", agent); - const processId = `vp-hostile-identifiers-${suffix}`; - const launchAttempt = `hostile-launch-attempt-${suffix}`; - const mainTask = `ti:${processId}:main`; - const taskSpec = { - tenant, - project, - process: processId, - task_definition: bundle.entryStableId, - task_instance: mainTask, - dispatch: { - kind: "coordinator_node_wasm", - export: bundle.entryExport, - abi: "entrypoint_v1", - }, - environment_id: null, - environment: null, - environment_digest: null, - required_capabilities: [], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [], - vfs_epoch: 1, - failure_policy: "fail_fast", - bundle_digest: bundle.digest, - }; - const rejected = []; - const elapsedMs = (started) => - Number(process.hrtime.bigint() - started) / 1_000_000; - const rejectMalformed = async ({ - principal, - requestVariant, - fieldPath, - form, - send, - token = false, - }) => { - const started = process.hrtime.bigint(); - const response = await send(form.value); - assert.strictEqual( - response.type, - "error", - `${principal} ${fieldPath} ${form.name} reached the real ${requestVariant} variant but was not rejected: ${JSON.stringify(response)}` - ); - assert.match( - response.message, - token - ? /malformed external token|token.*invalid|control characters|byte limit|empty|whitespace/i - : /malformed external identifier|(?:Agent|Artifact|Node|Process|Project|TaskDefinition|TaskInstance|Tenant|User|LaunchAttempt)Id is invalid/i, - `${principal} ${fieldPath} ${form.name} was not rejected for identifier validation: ${JSON.stringify(response)}` - ); - assert.doesNotMatch( - response.message, - /unknown variant|unknown field|missing field/i, - `${principal} ${fieldPath} ${form.name} only proved generic deserialization failure` - ); - const health = await sendHostedControl({ type: "ping" }); - assert.strictEqual( - health.type, - "pong", - `valid traffic failed after hostile ${principal} ${fieldPath} ${form.name}` - ); - rejected.push({ - principal, - request_variant: requestVariant, - field_path: fieldPath, - fault: form.name, - expected: token - ? "structured malformed external token error" - : "structured malformed external identifier error", - observed: response.message, - health_after: health.type, - duration_ms: elapsedMs(started), - }); - }; - - let agentRegistered = false; - let processStarted = false; - try { - const added = runJson( - clusterflux, - [ - "key", - "add", - ...scope, - "--agent", - agent, - "--public-key", - agentIdentityRecord.publicKey, - ], - { cwd: projectDir } - ); - assert.strictEqual(added.command, "key add"); - agentRegistered = true; - - const agentStartCases = [ - ["tenant", "tenant"], - ["project", "project"], - ["agent", "actor_agent"], - ["process", "process"], - ["launch_attempt", "launch_attempt"], - ]; - for (const [principal, field] of agentStartCases) { - for (const form of forms) { - await rejectMalformed({ - principal: `agent_signed_${principal}`, - requestVariant: "start_process", - fieldPath: field, - form, - send: async (value) => { - const body = { - type: "start_process", - tenant, - project, - actor_agent: agent, - process: processId, - launch_attempt: launchAttempt, - restart: false, - }; - body[field] = value; - return sendHostedControl( - signedAgentWorkflowRequest(agentIdentityRecord, body, { - nonce: `hostile-agent-${principal}-${form.name}-${Date.now()}`, - }) - ); - }, - }); - } - } - for (const form of tokenForms) { - await rejectMalformed({ - principal: "agent_signed_nonce", - requestVariant: "start_process", - fieldPath: "agent_signature.nonce", - form, - token: true, - send: async (value) => { - const request = signedAgentWorkflowRequest( - agentIdentityRecord, - { - type: "start_process", - tenant, - project, - actor_agent: agent, - process: processId, - launch_attempt: launchAttempt, - restart: false, - }, - { nonce: value } - ); - assert.strictEqual( - request.agent_signature.nonce, - value, - "hostile Agent nonce was not preserved on the wire" - ); - return sendHostedControl(request); - }, - }); - } - for (const form of forms) { - await rejectMalformed({ - principal: "node_signed_heartbeat_node", - requestVariant: "node_heartbeat", - fieldPath: "node", - form, - send: async (value) => - sendHostedControl({ - type: "node_heartbeat", - tenant, - project, - node: value, - node_signature: signedNodeHeartbeat( - tenant, - project, - value, - securityNode.identity, - { - nonce: `hostile-heartbeat-node-${form.name}-${Date.now()}`, - } - ), - }), - }); - } - - const started = await sendHostedControl( - signedAgentWorkflowRequest( - agentIdentityRecord, - { - type: "start_process", - tenant, - project, - actor_agent: agent, - process: processId, - launch_attempt: launchAttempt, - restart: false, - }, - { nonce: `hostile-agent-valid-start-${suffix}` } - ) - ); - assert.strictEqual(started.type, "process_started", JSON.stringify(started)); - processStarted = true; - taskSpec.vfs_epoch = started.epoch; - - const taskSpecCases = [ - ["tenant", "task_spec.tenant"], - ["project", "task_spec.project"], - ["process", "task_spec.process"], - ["task_definition", "task_spec.task_definition"], - ["task_instance", "task_spec.task_instance"], - ]; - for (const [field, fieldPath] of taskSpecCases) { - for (const form of forms) { - await rejectMalformed({ - principal: `agent_signed_${field}`, - requestVariant: "launch_task", - fieldPath, - form, - send: async (value) => { - const malformedTaskSpec = structuredClone(taskSpec); - malformedTaskSpec[field] = value; - const body = { - type: "launch_task", - tenant, - project, - actor_agent: agent, - task_spec: malformedTaskSpec, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${mainTask}-output.txt`, - wasm_module_base64: bundle.moduleBase64, - }; - return sendHostedControl( - signedAgentWorkflowRequest(agentIdentityRecord, body, { - nonce: `hostile-task-spec-${field}-${form.name}-${Date.now()}`, - }) - ); - }, - }); - } - } - - for (const form of forms) { - await rejectMalformed({ - principal: "agent_signed_artifact_array", - requestVariant: "launch_task", - fieldPath: "task_spec.required_artifacts[0]", - form, - send: async (value) => { - const malformedTaskSpec = structuredClone(taskSpec); - malformedTaskSpec.required_artifacts = [releaseArtifact.artifact]; - malformedTaskSpec.args = [ - { - Artifact: { - id: releaseArtifact.artifact, - digest: releaseArtifact.digest, - size_bytes: Number(releaseArtifact.size_bytes || 1), - }, - }, - ]; - malformedTaskSpec.required_artifacts = [value]; - const body = { - type: "launch_task", - tenant, - project, - actor_agent: agent, - task_spec: malformedTaskSpec, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${mainTask}-artifact-output.txt`, - wasm_module_base64: bundle.moduleBase64, - }; - return sendHostedControl( - signedAgentWorkflowRequest(agentIdentityRecord, body, { - nonce: `hostile-artifact-array-${form.name}-${Date.now()}`, - }) - ); - }, - }); - } - - const mainLaunch = await sendHostedControl( - signedAgentWorkflowRequest( - agentIdentityRecord, - { - type: "launch_task", - tenant, - project, - actor_agent: agent, - task_spec: taskSpec, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${mainTask}-output.txt`, - wasm_module_base64: bundle.moduleBase64, - }, - { nonce: `hostile-agent-valid-main-${suffix}` } - ) - ); - assert.strictEqual(mainLaunch.type, "main_launched", JSON.stringify(mainLaunch)); - - const authenticatedCases = [ - { - principal: "authenticated_cli_project", - requestVariant: "select_project", - fieldPath: "request.project", - payload: (value) => ({ type: "select_project", project: value }), - }, - { - principal: "authenticated_cli_process", - requestVariant: "list_task_events", - fieldPath: "request.process", - payload: (value) => ({ type: "list_task_events", process: value }), - }, - { - principal: "authenticated_cli_task", - requestVariant: "join_task", - fieldPath: "request.task", - payload: (value) => ({ - type: "join_task", - process: processId, - task: value, - }), - }, - { - principal: "authenticated_cli_artifact", - requestVariant: "create_artifact_download_link", - fieldPath: "request.artifact", - payload: (value) => ({ - type: "create_artifact_download_link", - artifact: value, - max_bytes: Number(releaseArtifact.size_bytes || 1), - ttl_seconds: 60, - }), - }, - { - principal: "authenticated_cli_launch_attempt", - requestVariant: "abort_process", - fieldPath: "request.launch_attempt", - payload: (value) => ({ - type: "abort_process", - process: processId, - launch_attempt: value, - }), - }, - ]; - for (const testCase of authenticatedCases) { - for (const form of forms) { - await rejectMalformed({ - ...testCase, - form, - send: async (value) => - sendHostedControl( - authenticatedRequest(sessionSecret, testCase.payload(value)) - ), - }); - } - } - - const nodeCases = [ - { - principal: "node_signed_wrapper_node", - requestVariant: "poll_task_assignment", - fieldPath: "node", - send: (value, form) => - sendHostedControl( - signedNodeRequest( - value, - securityNode.identity, - "poll_task_assignment", - { - type: "poll_task_assignment", - tenant, - project, - node: securityNode.node, - }, - { nonce: `hostile-node-wrapper-${form.name}-${Date.now()}` } - ) - ), - }, - { - principal: "node_signed_poll_tenant", - requestVariant: "poll_task_assignment", - fieldPath: "request.tenant", - send: (value, form) => - sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "poll_task_assignment", - { - type: "poll_task_assignment", - tenant: value, - project, - node: securityNode.node, - }, - { nonce: `hostile-node-tenant-${form.name}-${Date.now()}` } - ) - ), - }, - { - principal: "node_signed_poll_project", - requestVariant: "poll_task_assignment", - fieldPath: "request.project", - send: (value, form) => - sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "poll_task_assignment", - { - type: "poll_task_assignment", - tenant, - project: value, - node: securityNode.node, - }, - { nonce: `hostile-node-project-${form.name}-${Date.now()}` } - ) - ), - }, - { - principal: "node_signed_poll_node", - requestVariant: "poll_task_assignment", - fieldPath: "request.node", - send: (value, form) => - sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "poll_task_assignment", - { - type: "poll_task_assignment", - tenant, - project, - node: value, - }, - { nonce: `hostile-node-inner-${form.name}-${Date.now()}` } - ) - ), - }, - { - principal: "node_signed_artifact_array", - requestVariant: "report_node_capabilities", - fieldPath: "request.artifact_locations[0]", - send: (value, form) => - sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "report_node_capabilities", - { - ...securityNode.capability_body, - artifact_locations: [value], - }, - { nonce: `hostile-node-artifact-${form.name}-${Date.now()}` } - ) - ), - }, - ]; - for (const testCase of nodeCases) { - for (const form of forms) { - await rejectMalformed({ - principal: testCase.principal, - requestVariant: testCase.requestVariant, - fieldPath: testCase.fieldPath, - form, - send: (value) => testCase.send(value, form), - }); - } - } - for (const form of tokenForms) { - await rejectMalformed({ - principal: "node_signed_nonce", - requestVariant: "node_heartbeat", - fieldPath: "node_signature.nonce", - form, - token: true, - send: async (value) => { - const request = { - type: "node_heartbeat", - tenant, - project, - node: securityNode.node, - node_signature: signedNodeHeartbeat( - tenant, - project, - securityNode.node, - securityNode.identity, - { nonce: value } - ), - }; - assert.strictEqual( - request.node_signature.nonce, - value, - "hostile Node nonce was not preserved on the wire" - ); - return sendHostedControl(request); - }, - }); - } - - const endpointFingerprint = sha256( - Buffer.from(securityNode.identity.publicKey) - ); - const rendezvous = { - type: "request_rendezvous", - scope: { - tenant, - project, - process: processId, - object: { Artifact: releaseArtifact.artifact }, - authorization_subject: `${securityNode.node}-self-transfer`, - }, - source: { - node: securityNode.node, - advertised_addr: "127.0.0.1:4433", - public_key_fingerprint: endpointFingerprint, - }, - destination: { - node: securityNode.node, - advertised_addr: "127.0.0.1:4433", - public_key_fingerprint: endpointFingerprint, - }, - direct_connectivity: true, - failure_reason: "", - }; - const rendezvousCases = [ - ["scope.tenant", (request, value) => (request.scope.tenant = value)], - ["scope.project", (request, value) => (request.scope.project = value)], - ["scope.process", (request, value) => (request.scope.process = value)], - [ - "scope.object.artifact", - (request, value) => (request.scope.object.Artifact = value), - ], - ["source.node", (request, value) => (request.source.node = value)], - [ - "destination.node", - (request, value) => (request.destination.node = value), - ], - ]; - for (const [fieldPath, mutate] of rendezvousCases) { - for (const form of forms) { - await rejectMalformed({ - principal: "node_signed_rendezvous", - requestVariant: "request_rendezvous", - fieldPath: `request.${fieldPath}`, - form, - send: async (value) => { - const body = structuredClone(rendezvous); - mutate(body, value); - return sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "request_rendezvous", - body, - { - nonce: `hostile-rendezvous-${fieldPath}-${form.name}-${Date.now()}`, - } - ) - ); - }, - }); - } - } - const validRendezvous = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "request_rendezvous", - rendezvous, - { nonce: `hostile-rendezvous-valid-${suffix}` } - ) - ); - assert.strictEqual( - validRendezvous.type, - "rendezvous_plan", - JSON.stringify(validRendezvous) - ); - - const login = await sendHostedLogin({ type: "begin_oidc_browser_login" }); - assert.strictEqual(login.type, "oidc_browser_login_started", JSON.stringify(login)); - const loginCases = [ - ["transaction_id", login.transaction_id, login.polling_secret], - ["polling_secret", login.transaction_id, login.polling_secret], - ]; - for (const [field, validTransaction, validSecret] of loginCases) { - for (const form of tokenForms) { - await rejectMalformed({ - principal: "private_hosted_login", - requestVariant: "poll_oidc_browser_login", - fieldPath: field, - form, - token: true, - send: async (value) => - sendHostedLogin({ - type: "poll_oidc_browser_login", - transaction_id: - field === "transaction_id" ? value : validTransaction, - polling_secret: field === "polling_secret" ? value : validSecret, - }), - }); - const validPoll = await sendHostedLogin({ - type: "poll_oidc_browser_login", - transaction_id: login.transaction_id, - polling_secret: login.polling_secret, - }); - assert.strictEqual( - validPoll.type, - "oidc_browser_login_pending", - `valid hosted login polling failed after malformed ${field}` - ); - } - } - - const operatorControlCases = [ - ["payload.tenant", "tenant"], - ["payload.project", "project"], - ["payload.process", "process"], - ]; - for (const [fieldPath, field] of operatorControlCases) { - for (const form of forms) { - await rejectMalformed({ - principal: "private_hosted_operator_control", - requestVariant: "stop_hosted_process", - fieldPath, - form, - send: async (value) => { - const payload = { - type: "stop_hosted_process", - tenant, - project, - process: processId, - }; - payload[field] = value; - return sendHostedControlEnvelope({ - type: "hosted_operator_request", - protocol_version: 1, - request_id: `hostile-operator-${field}-${form.name}-${Date.now()}`, - operation: "stop_hosted_process", - operator_proof: sha256(Buffer.from("invalid operator proof")), - operator_nonce: `hostile-operator-nonce-${field}-${form.name}-${Date.now()}`, - issued_at_epoch_seconds: Math.floor(Date.now() / 1000), - payload, - }); - }, - }); - } - } - - const authenticatedHealth = await sendHostedControl( - authenticatedRequest(sessionSecret, { type: "auth_status" }) - ); - assert.strictEqual(authenticatedHealth.type, "auth_status"); - assert.strictEqual(authenticatedHealth.tenant, tenant); - assert.strictEqual(authenticatedHealth.project, project); - assert.strictEqual(authenticatedHealth.actor, user); - } finally { - if (processStarted) { - try { - runJson( - clusterflux, - [ - "process", - "abort", - ...scope, - "--process", - processId, - "--yes", - ], - { cwd: projectDir } - ); - } catch (_) { - // Preserve the primary validation failure while still attempting cleanup. - } - } - if (agentRegistered) { - try { - runJson( - clusterflux, - ["key", "revoke", ...scope, "--agent", agent, "--yes"], - { cwd: projectDir } - ); - } catch (_) { - // Preserve the primary validation failure while still attempting cleanup. - } - } - } - - const coveredPrincipals = [...new Set(rejected.map((entry) => entry.principal))]; - const coveredVariants = [...new Set(rejected.map((entry) => entry.request_variant))]; - return { - principals: coveredPrincipals, - request_variants: coveredVariants, - forms: forms.map((form) => form.name), - rejected_requests: rejected, - all_rejected_for_intended_reason: rejected.every( - (entry) => - /identifier|token|Id is invalid|control characters|byte limit|empty|whitespace/i.test( - entry.observed - ) - ), - valid_after_every_rejection: rejected.every( - (entry) => entry.health_after === "pong" - ), - valid_authenticated_action_after_suite: true, - valid_signed_rendezvous_after_suite: true, - valid_private_login_poll_after_every_private_rejection: true, - duration_ms: Date.now() - scenarioStartedAt, - }; -} - -function sendHostedControlDroppingResponse(payload) { - const body = Buffer.from( - JSON.stringify(coordinatorWireRequest(payload, "strict-live-dropped-response")) - ); - const url = new URL("/api/v1/control", serviceEndpoint); - return new Promise((resolve, reject) => { - let settled = false; - const request = https.request( - url, - { - method: "POST", - headers: { - "content-type": "application/json", - "content-length": body.length, - }, - timeout: 30_000, - }, - (response) => { - settled = true; - const statusCode = response.statusCode; - response.destroy(); - resolve({ status_code: statusCode, response_body_consumed: false }); - } - ); - request.on("timeout", () => - request.destroy(new Error("hosted dropped-response request timed out")) - ); - request.on("error", (error) => { - if (!settled) reject(error); - }); - request.end(body); - }); -} - -function sendHostedLoginStatus(extraHeaders = {}) { - const body = Buffer.from( - JSON.stringify( - coordinatorWireRequest( - { type: "begin_oidc_browser_login" }, - `strict-live-login-${Date.now()}-${Math.random()}` - ) - ) - ); - const url = new URL("/api/v1/login", serviceEndpoint); - return new Promise((resolve, reject) => { - const request = https.request( - url, - { - method: "POST", - headers: { - "content-type": "application/json", - "content-length": body.length, - ...extraHeaders, - }, - timeout: 30_000, - }, - (response) => { - const chunks = []; - response.on("data", (chunk) => chunks.push(chunk)); - response.on("end", () => - resolve({ - status_code: response.statusCode, - body: Buffer.concat(chunks).toString("utf8"), - }) - ); - } - ); - request.on("timeout", () => - request.destroy(new Error("hosted login request timed out")) - ); - request.on("error", reject); - request.end(body); - }); -} - -function sendHostedLogin(payload) { - const body = Buffer.from( - JSON.stringify( - coordinatorWireRequest( - payload, - `strict-live-login-protocol-${Date.now()}-${Math.random()}` - ) - ) - ); - const url = new URL("/api/v1/login", serviceEndpoint); - return new Promise((resolve, reject) => { - const request = https.request( - url, - { - method: "POST", - headers: { - "content-type": "application/json", - "content-length": body.length, - }, - timeout: 30_000, - }, - (response) => { - const chunks = []; - response.on("data", (chunk) => chunks.push(chunk)); - response.on("end", () => { - const responseBody = Buffer.concat(chunks).toString("utf8"); - if (response.statusCode < 200 || response.statusCode >= 300) { - reject( - new Error( - `hosted login HTTP ${response.statusCode}: ${responseBody}` - ) - ); - return; - } - try { - resolve(JSON.parse(responseBody)); - } catch (error) { - reject( - new Error(`hosted login returned invalid JSON: ${error.message}`) - ); - } - }); - } - ); - request.on("timeout", () => - request.destroy(new Error("hosted login request timed out")) - ); - request.on("error", reject); - request.end(body); - }); -} - -async function runHostedLoginIsolationBeforeRestart() { - const scenarioStartedAt = Date.now(); - const controlBefore = await sendHostedControl({ type: "ping" }); - assert.strictEqual(controlBefore.type, "pong"); - const statuses = []; - let limited; - for (let index = 0; index < 128; index += 1) { - const response = await sendHostedLoginStatus(); - statuses.push(response.status_code); - if (response.status_code === 429) { - limited = response; - break; - } - assert.strictEqual(response.status_code, 200, response.body); - } - assert(limited, `hosted login route was not rate limited: ${statuses.join(",")}`); - const spoofed = await sendHostedLoginStatus({ - forwarded: "for=203.0.113.99", - "x-forwarded-for": "203.0.113.99", - "x-real-ip": "203.0.113.99", - }); - assert.strictEqual( - spoofed.status_code, - 429, - "caller-supplied forwarding headers bypassed the client rate limit" - ); - - const remoteBody = JSON.stringify( - coordinatorWireRequest( - { type: "begin_oidc_browser_login" }, - `strict-vps-login-${Date.now()}` - ) - ); - const remoteStatus = Number( - run( - "ssh", - sshArgs( - "curl", - "--silent", - "--show-error", - "--output", - "/dev/null", - "--write-out=%{http_code}", - "-HContent-Type:application/json", - `--data-binary=${remoteBody}`, - `${serviceEndpoint}/api/v1/login` - ) - ).trim() - ); - assert.strictEqual( - remoteStatus, - 200, - "one client exhausted the browser-login allowance for a different client" - ); - const controlAfter = await sendHostedControl({ type: "ping" }); - assert.strictEqual(controlAfter.type, "pong"); - return { - scenario_started_at_ms: scenarioStartedAt, - local_statuses: statuses, - local_limited_status: limited.status_code, - forwarding_spoof_status: spoofed.status_code, - independent_vps_client_status: remoteStatus, - control_route_before: controlBefore.type, - control_route_after: controlAfter.type, - }; -} - -async function finishHostedLoginIsolationAfterRestart(evidence) { - const control = await sendHostedControl({ type: "ping" }); - assert.strictEqual(control.type, "pong"); - const response = await sendHostedLoginStatus(); - assert( - [200, 429].includes(response.status_code), - `login route did not recover after service restart: ${response.status_code} ${response.body}` - ); - evidence.after_service_restart = { - control_route: control.type, - login_route_status: response.status_code, - }; - evidence.duration_ms = Date.now() - evidence.scenario_started_at_ms; - delete evidence.scenario_started_at_ms; - return evidence; -} - -function assertDenied(response, pattern, label) { - assert.strictEqual(response.type, "error", `${label}: ${JSON.stringify(response)}`); - assert.match(response.message, pattern, `${label}: ${JSON.stringify(response)}`); - return { - denied: true, - category: response.error?.category || null, - message: response.message, - }; -} - -function assertDeniedOrEmptyCollection(response, pattern, label) { - const emptyCollectionField = { - process_statuses: "processes", - task_events: "events", - }[response.type]; - if (!emptyCollectionField) { - return assertDenied(response, pattern, label); - } - assert.deepStrictEqual( - Object.keys(response).sort(), - ["actor", emptyCollectionField, "type"] - .filter((key) => key !== "actor" || Object.hasOwn(response, key)) - .sort(), - `${label}: ${JSON.stringify(response)}` - ); - assert.deepStrictEqual( - response[emptyCollectionField], - [], - `${label}: ${JSON.stringify(response)}` - ); - return { - denied: false, - scoped_empty_result: true, - response_type: response.type, - }; -} - -function readNodeCredential(projectDir, node) { - const directory = path.join(projectDir, ".clusterflux", "nodes"); - for (const file of fs.readdirSync(directory)) { - if (!file.endsWith(".json")) continue; - const absolute = path.join(directory, file); - const credential = readJson(absolute); - if (credential.node === node) return { absolute, credential }; - } - throw new Error(`persisted credential for ${node} was not found`); -} - -function directoryStats(root) { - if (!fs.existsSync(root)) return { files: 0, bytes: 0 }; - let files = 0; - let bytes = 0; - const visit = (directory) => { - for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { - const absolute = path.join(directory, entry.name); - if (entry.isDirectory()) visit(absolute); - else if (entry.isFile()) { - files += 1; - bytes += fs.statSync(absolute).size; - } - } - }; - visit(root); - return { files, bytes }; -} - -function shellQuote(argument) { - return `'${String(argument).replaceAll("'", "'\"'\"'")}'`; -} - -function sshArgs(...remoteArgs) { - assert(strictVpsHost && strictVpsIdentity); - return [ - "-i", - path.resolve(strictVpsIdentity.replace(/^~(?=\/)/, os.homedir())), - "-o", - "BatchMode=yes", - strictVpsHost, - remoteArgs.map(shellQuote).join(" "), - ]; -} - -function strictInfrastructureSample(projectDir) { - const memory = Object.fromEntries( - run( - "ssh", - sshArgs( - "systemctl", - "show", - strictServiceUnit, - "--property=MemoryCurrent", - "--property=MemoryPeak" - ) - ) - .trim() - .split(/\r?\n/) - .map((line) => line.split("=")) - ); - const serviceDisk = Number( - run( - "ssh", - sshArgs("du", "-sb", "/var/lib/clusterflux-public-release") - ) - .trim() - .split(/\s+/)[0] - ); - const database = run( - "ssh", - sshArgs( - "runuser", - "-u", - "postgres", - "--", - "psql", - "-d", - "clusterflux", - "-AtF," - ), - { - input: - "SELECT pg_database_size('clusterflux'), (SELECT count(*) FROM clusterflux_tenants), (SELECT count(*) FROM clusterflux_projects), (SELECT count(*) FROM clusterflux_node_identities), (SELECT count(*) FROM clusterflux_cli_sessions);\n", - stdio: ["pipe", "pipe", "pipe"], - } - ) - .trim() - .split(",") - .map(Number); - assert(Number.isFinite(Number(memory.MemoryCurrent))); - assert(Number.isFinite(Number(memory.MemoryPeak))); - assert.strictEqual(database.length, 5); - return { - sampled_at_epoch_ms: Date.now(), - service_memory_current_bytes: Number(memory.MemoryCurrent), - service_memory_peak_bytes: Number(memory.MemoryPeak), - service_state_disk_bytes: serviceDisk, - postgres_database_bytes: database[0], - durable_rows: { - tenants: database[1], - projects: database[2], - node_identities: database[3], - cli_sessions: database[4], - }, - local_node_state: directoryStats(path.join(projectDir, ".clusterflux")), - }; -} - -function executable(root, name) { - return path.join(root, "bin", process.platform === "win32" ? `${name}.exe` : name); -} - -function binaryArchive(manifest) { - const platform = `${os.platform()}-${os.arch()}`; - const asset = manifest.assets.find( - (candidate) => - candidate.name.startsWith("clusterflux-public-binaries-") && - candidate.name.includes(platform) - ); - assert(asset, `missing released binary archive for ${platform}`); - assert(fs.existsSync(asset.file), `missing released binary archive ${asset.file}`); - return asset.file; -} - -function publicRepoUrl(manifest) { - const url = - process.env.CLUSTERFLUX_PUBLIC_REPO_URL || - process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE || - manifest.public_repo_url || - manifest.public_repo_remote; - assert(url, "public repository URL is required"); - assert(url.includes("git.michelpaulissen.com")); - return url; -} - -function stagePublicCheckout(manifest, checkout) { - const candidateTree = process.env.CLUSTERFLUX_LIVE_PUBLIC_TREE; - if (candidateTree) { - const source = path.resolve(candidateTree); - assert.strictEqual( - source, - path.resolve(manifest.public_tree), - "explicit live candidate tree must be the tree recorded by the release manifest" - ); - fs.cpSync(source, checkout, { recursive: true }); - return { - kind: "local_filtered_release_candidate", - path: source, - published: false, - }; - } - run("git", ["clone", "--depth", "1", publicRepoUrl(manifest), checkout]); - return { - kind: "published_forgejo_checkout", - url: publicRepoUrl(manifest), - published: true, - }; -} - -function delay(milliseconds) { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); -} - -async function waitForCli(label, action, predicate, timeoutMs = 10 * 60 * 1000) { - const deadline = Date.now() + timeoutMs; - let lastValue; - let lastError; - while (Date.now() < deadline) { - try { - lastValue = action(); - if (predicate(lastValue)) return lastValue; - lastError = undefined; - } catch (error) { - lastError = error; - } - await delay(250); - } - throw new Error( - `${label} timed out; last value=${JSON.stringify(lastValue)}${ - lastError ? `; last error=${lastError.message}` : "" - }` - ); -} - -function spawnJsonLines(command, args, options) { - recordCommand(command, args); - const child = cp.spawn(command, args, { - ...options, - stdio: ["ignore", "pipe", "pipe"], - }); - let stdout = ""; - let stderr = ""; - const values = []; - const waiters = []; - - function deliver(value) { - values.push(value); - for (let index = waiters.length - 1; index >= 0; index -= 1) { - const waiter = waiters[index]; - if (waiter.predicate(value)) { - waiters.splice(index, 1); - clearTimeout(waiter.timer); - waiter.resolve(value); - } - } - } - - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - while (stdout.includes("\n")) { - const newline = stdout.indexOf("\n"); - const line = stdout.slice(0, newline).trim(); - stdout = stdout.slice(newline + 1); - if (!line) continue; - try { - deliver(JSON.parse(line)); - } catch (_) { - // Non-JSON progress stays out of the evidence report. - } - } - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - - function waitFor(predicate, label, timeoutMs = 120000) { - const existing = values.find(predicate); - if (existing) return Promise.resolve(existing); - return new Promise((resolve, reject) => { - const waiter = { predicate, resolve, reject, timer: undefined }; - waiter.timer = setTimeout(() => { - const index = waiters.indexOf(waiter); - if (index >= 0) waiters.splice(index, 1); - reject(new Error(`${label} timed out\n${stderr}`)); - }, timeoutMs); - waiters.push(waiter); - }); - } - - child.once("exit", (code) => { - for (const waiter of waiters.splice(0)) { - clearTimeout(waiter.timer); - waiter.reject(new Error(`${waiter.label || "child"} exited with ${code}\n${stderr}`)); - } - }); - return { child, values, waitFor, stderr: () => stderr }; -} - -async function stopChild(child) { - if (!child || child.exitCode !== null) return; - child.kill("SIGTERM"); - const exited = new Promise((resolve) => child.once("exit", resolve)); - const forced = delay(5000).then(() => { - if (child.exitCode === null) child.kill("SIGKILL"); - }); - await Promise.race([exited, forced]); - if (child.exitCode === null) await exited; -} - -function rawTaskEvents(report) { - return report?.events?.response?.events || []; -} - -function nodeDescriptor(status, node) { - return status?.response?.descriptors?.find( - (descriptor) => descriptor.id === node || descriptor.node === node - ); -} - -function completedFlagship(events) { - const completedDefinitions = new Set( - events - .filter((event) => event.terminal_state === "completed") - .map((event) => event.task_definition) - ); - return ( - completedDefinitions.has("prepare_source") && - completedDefinitions.has("compile_linux") && - completedDefinitions.has("package_release") && - events.some( - (event) => - event.executor === "coordinator_main" && event.terminal_state === "completed" - ) - ); -} - -function contentAddressedArtifactId(event, logicalName) { - const digest = event?.artifact_digest; - if (typeof digest !== "string" || !/^sha256:[0-9a-f]{64}$/.test(digest)) { - return null; - } - const artifactId = `${logicalName}-${digest.slice("sha256:".length)}`; - return event.artifact_path?.endsWith(`/vfs/artifacts/${artifactId}`) - ? artifactId - : null; -} - -async function prepareLiveNodeCredentialSecurity({ - clusterflux, - projectDir, - scope, - tenant, - project, - suffix, -}) { - const startedAt = Date.now(); - const node = `security-node-${suffix}`; - const grant = runJson(clusterflux, ["node", "enroll", ...scope], { - cwd: projectDir, - }); - const attach = runJson( - clusterflux, - [ - "node", - "attach", - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--node", - node, - "--enrollment-grant", - grant.enrollment_grant.grant, - "--json", - ], - { cwd: projectDir } - ); - assert.strictEqual(attach.boundary.used_enrollment_exchange, true); - const stored = readNodeCredential(projectDir, node); - const identity = nodeIdentityFromPrivateKey(stored.credential.private_key); - assert.strictEqual(identity.publicKey, stored.credential.public_key); - - const heartbeat = { - type: "node_heartbeat", - tenant, - project, - node, - node_signature: signedNodeHeartbeat(tenant, project, node, identity, { - nonce: `strict-valid-${suffix}`, - }), - }; - const valid = await sendHostedControl(heartbeat); - assert.strictEqual(valid.type, "node_heartbeat"); - const replay = assertDenied( - await sendHostedControl(heartbeat), - /nonce.*already.*used|replay/i, - "replayed node credential" - ); - - const expired = assertDenied( - await sendHostedControl({ - type: "node_heartbeat", - tenant, - project, - node, - node_signature: signedNodeHeartbeat(tenant, project, node, identity, { - nonce: `strict-expired-${suffix}`, - issuedAtEpochSeconds: Math.floor(Date.now() / 1000) - 3600, - }), - }), - /expired|clock skew/i, - "expired node credential" - ); - - const forgedIdentity = nodeIdentity("strict-forged-node", node); - const forged = assertDenied( - await sendHostedControl({ - type: "node_heartbeat", - tenant, - project, - node, - node_signature: signedNodeHeartbeat(tenant, project, node, forgedIdentity, { - nonce: `strict-forged-${suffix}`, - }), - }), - /signature|public key/i, - "forged node credential" - ); - - const originalCapabilityBody = { - type: "report_node_capabilities", - tenant, - project, - node, - capabilities: { - os: "Linux", - arch: process.arch === "x64" ? "x86_64" : process.arch, - capabilities: [], - environment_backends: [], - source_providers: [], - }, - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: false, - online: true, - }; - const modifiedEnvelope = signedNodeRequest( - node, - identity, - "report_node_capabilities", - originalCapabilityBody, - { nonce: `strict-modified-${suffix}` } - ); - modifiedEnvelope.request.online = false; - const bodyModified = assertDenied( - await sendHostedControl(modifiedEnvelope), - /signature/i, - "body-modified node credential" - ); - - return { - duration_ms: Date.now() - startedAt, - node, - identity, - credential_path: stored.absolute, - credential_digest: sha256(fs.readFileSync(stored.absolute)), - capability_body: originalCapabilityBody, - evidence: { - valid_request: valid.type, - replay, - expired, - forged, - body_modified: bodyModified, - }, - }; -} - -async function runLiveAgentCredentialSecurity({ - clusterfluxDap, - clusterflux, - projectDir, - scope, - sessionSecret, - tenant, - project, - suffix, - bundle, - securityNode, - workerRuntime, -}) { - const scenarioStartedAt = Date.now(); - const agent = `security-agent-${suffix}`; - const identity = agentIdentity("strict-live-agent", agent); - const added = runJson( - clusterflux, - ["key", "add", ...scope, "--agent", agent, "--public-key", identity.publicKey], - { cwd: projectDir } - ); - assert.strictEqual(added.command, "key add"); - - const processId = `vp-agent-security-${suffix}`; - const unsigned = { - type: "start_process", - tenant, - project, - actor_agent: agent, - process: processId, - restart: false, - }; - const validRequest = signedAgentWorkflowRequest(identity, unsigned, { - nonce: `strict-agent-valid-${suffix}`, - }); - const valid = await sendHostedControl(validRequest); - assert.strictEqual(valid.type, "process_started", JSON.stringify(valid)); - const replay = assertDenied( - await sendHostedControl(validRequest), - /nonce.*already.*used|replay/i, - "replayed agent credential" - ); - - const expired = assertDenied( - await sendHostedControl( - signedAgentWorkflowRequest( - identity, - { ...unsigned, process: `${processId}-expired` }, - { - nonce: `strict-agent-expired-${suffix}`, - issuedAtEpochSeconds: Math.floor(Date.now() / 1000) - 3600, - } - ) - ), - /expired|clock skew/i, - "expired agent credential" - ); - - const modifiedRequest = signedAgentWorkflowRequest( - identity, - { ...unsigned, process: `${processId}-modified` }, - { nonce: `strict-agent-modified-${suffix}` } - ); - modifiedRequest.restart = true; - const bodyModified = assertDenied( - await sendHostedControl(modifiedRequest), - /signature/i, - "body-modified agent credential" - ); - - const forgedIdentity = agentIdentity("strict-live-forged-agent", agent); - const forged = assertDenied( - await sendHostedControl( - signedAgentWorkflowRequest( - forgedIdentity, - { ...unsigned, process: `${processId}-forged` }, - { - nonce: `strict-agent-forged-${suffix}`, - publicKeyFingerprint: identity.publicKeyFingerprint, - } - ) - ), - /signature|public key/i, - "forged agent credential" - ); - - const fakeEnvironmentDigest = sha256( - Buffer.from(`strict-debug-missing-participant-${suffix}`) - ); - const fakeCapabilityBody = { - ...securityNode.capability_body, - cached_environment_digests: [fakeEnvironmentDigest], - online: true, - }; - const mainTask = `ti:${processId}:main`; - const fakeTask = `missing-debug-participant-${suffix}`; - const mainLaunchBody = { - type: "launch_task", - tenant, - project, - actor_agent: agent, - task_spec: { - tenant, - project, - process: processId, - task_definition: bundle.entryStableId, - task_instance: mainTask, - dispatch: { - kind: "coordinator_node_wasm", - export: bundle.entryExport, - abi: "entrypoint_v1", - }, - environment_id: null, - environment: null, - environment_digest: null, - required_capabilities: [], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [], - vfs_epoch: valid.epoch, - bundle_digest: bundle.digest, - }, - wait_for_node: true, - artifact_path: `/vfs/artifacts/${mainTask}-output.txt`, - wasm_module_base64: bundle.moduleBase64, - }; - let mainLaunch; - let directTaskV1; - let fakeLaunch; - let liveParentTask; - let liveParentAssignment; - let realDebugLaunch; - let preconfiguredBreakpoint; - let attachSourcePath; - let attachBreakpointLine; - const realDebugTask = `real-debug-participant-${suffix}`; - let workerPaused = false; - const baselineContainers = new Set( - run("podman", ["ps", "-q"]) - .trim() - .split(/\s+/) - .filter(Boolean) - ); - try { - mainLaunch = await sendHostedControl( - signedAgentWorkflowRequest(identity, mainLaunchBody, { - nonce: `strict-agent-main-${suffix}`, - }) - ); - assert.strictEqual(mainLaunch.type, "main_launched", JSON.stringify(mainLaunch)); - assert.strictEqual(mainLaunch.task_instance, mainTask); - assert.strictEqual(mainLaunch.state, "running"); - assert.strictEqual(mainLaunch.actor.kind, "agent"); - assert.strictEqual(mainLaunch.actor.authenticated_without_browser, true); - - liveParentAssignment = await workerRuntime.worker.waitFor( - (value) => { - const taskSpec = value.task_assignment_response?.task_spec; - return ( - value.node_status === "assignment_started" && - value.node === workerRuntime.node && - value.process === processId && - taskSpec?.dispatch?.abi === "task_v1" && - taskSpec.task_definition === "compile_linux" && - taskSpec.environment_id === "linux" && - typeof taskSpec.environment_digest === "string" && - typeof taskSpec.source_snapshot === "string" - ); - }, - "agent main to dispatch an environment-bound live child to the real worker", - 120000 - ); - liveParentTask = liveParentAssignment.virtual_thread; - assert.strictEqual(typeof liveParentTask, "string"); - assert.notStrictEqual(liveParentTask, ""); - assert.strictEqual( - workerRuntime.child.kill("SIGSTOP"), - true, - "failed to pause the real worker after observing its live child" - ); - workerPaused = true; - - const fakeCapabilities = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "report_node_capabilities", - fakeCapabilityBody, - { nonce: `strict-agent-fake-capabilities-${suffix}` } - ) - ); - assert.strictEqual( - fakeCapabilities.type, - "node_capabilities_recorded", - JSON.stringify(fakeCapabilities) - ); - - const fakeTaskSpec = { - tenant, - project, - process: processId, - task_definition: "task_add_one", - task_instance: fakeTask, - dispatch: { - kind: "coordinator_node_wasm", - export: null, - abi: "task_v1", - }, - environment_id: "strict-debug-missing-participant", - environment: null, - environment_digest: fakeEnvironmentDigest, - required_capabilities: [], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [{ SmallJson: 41 }], - vfs_epoch: valid.epoch, - bundle_digest: bundle.digest, - }; - directTaskV1 = assertDenied( - await sendHostedControl( - signedAgentWorkflowRequest( - identity, - { - type: "launch_task", - tenant, - project, - actor_agent: agent, - task_spec: fakeTaskSpec, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${fakeTask}.txt`, - wasm_module_base64: bundle.moduleBase64, - }, - { nonce: `strict-agent-direct-task-v1-${suffix}` } - ) - ), - /external callers.*EntrypointV1|TaskV1 requires an authenticated live parent/i, - "external direct TaskV1 launch" - ); - - const liveParentSpec = - liveParentAssignment.task_assignment_response.task_spec; - attachSourcePath = path.join(projectDir, "src/lib.rs"); - const attachSourceLines = fs - .readFileSync(attachSourcePath, "utf8") - .split(/\r?\n/); - attachBreakpointLine = - attachSourceLines.findIndex((line) => line.includes("fn abort_probe(")) + 1; - assert( - attachBreakpointLine > 0, - "agent-security fixture omitted the abort_probe debug probe" - ); - preconfiguredBreakpoint = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "set_debug_breakpoints", - process: processId, - revision: 1, - probe_symbols: ["clusterflux.probe.abort_probe"], - }) - ); - assert.strictEqual( - preconfiguredBreakpoint.type, - "debug_breakpoints", - JSON.stringify(preconfiguredBreakpoint) - ); - assert.deepStrictEqual(preconfiguredBreakpoint.probe_symbols, [ - "clusterflux.probe.abort_probe", - ]); - realDebugLaunch = await sendHostedControl( - signedNodeRequest( - workerRuntime.node, - workerRuntime.identity, - "launch_child_task", - { - type: "launch_child_task", - tenant, - project, - process: processId, - node: workerRuntime.node, - parent_task: liveParentTask, - task_spec: { - tenant, - project, - process: processId, - task_definition: "abort_probe", - task_instance: realDebugTask, - dispatch: { - kind: "coordinator_node_wasm", - export: null, - abi: "task_v1", - }, - environment_id: liveParentSpec.environment_id, - environment: liveParentSpec.environment, - environment_digest: liveParentSpec.environment_digest, - required_capabilities: ["Command"], - dependency_cache: null, - source_snapshot: liveParentSpec.source_snapshot, - required_artifacts: [], - args: liveParentSpec.args, - vfs_epoch: valid.epoch, - bundle_digest: bundle.digest, - }, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${realDebugTask}.txt`, - wasm_module_base64: bundle.moduleBase64, - }, - { nonce: `strict-real-debug-participant-${suffix}` } - ) - ); - assert.strictEqual( - realDebugLaunch.type, - "task_launched", - JSON.stringify(realDebugLaunch) - ); - - const fakeLaunchBody = { - type: "launch_child_task", - tenant, - project, - process: processId, - node: workerRuntime.node, - parent_task: liveParentTask, - task_spec: fakeTaskSpec, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${fakeTask}.txt`, - wasm_module_base64: bundle.moduleBase64, - }; - fakeLaunch = await sendHostedControl( - signedNodeRequest( - workerRuntime.node, - workerRuntime.identity, - "launch_child_task", - fakeLaunchBody, - { nonce: `strict-parent-runtime-fake-task-${suffix}` } - ) - ); - assert.strictEqual(fakeLaunch.type, "task_launched", JSON.stringify(fakeLaunch)); - assert.strictEqual(fakeLaunch.placement.node, securityNode.node); - } finally { - if (workerPaused) { - assert.strictEqual( - workerRuntime.child.kill("SIGCONT"), - true, - "failed to resume the real worker after authenticated child launch" - ); - } - } - await workerRuntime.worker.waitFor( - (value) => - value.node_status === "assignment_started" && - value.virtual_thread === realDebugTask, - "real Podman debug participant to start", - 120_000 - ); - let realDebugContainerIds = new Set(); - - const debugClient = new DapClient({ - cwd: projectDir, - command: clusterfluxDap, - args: [], - env: { ...process.env }, - }); - const initialize = debugClient.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await debugClient.response(initialize, "initialize"); - const attachRequest = debugClient.send("attach", { - entry: "build", - project: projectDir, - processId, - runtimeBackend: "live-services", - coordinatorEndpoint: serviceEndpoint, - }); - await debugClient.response(attachRequest, "attach"); - await debugClient.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - const attachBreakpointRequest = debugClient.send("setBreakpoints", { - source: { path: attachSourcePath }, - breakpoints: [{ line: attachBreakpointLine }], - }); - const attachBreakpointResponse = await debugClient.response( - attachBreakpointRequest, - "setBreakpoints" - ); - assert.strictEqual( - attachBreakpointResponse.body.breakpoints[0].verified, - false, - "attach breakpoint was verified before runtime installation" - ); - const configurationDone = debugClient.send("configurationDone"); - await debugClient.response(configurationDone, "configurationDone"); - const attachBreakpointInstalled = await debugClient.waitFor( - (message) => - message.type === "event" && - message.event === "breakpoint" && - message.body?.breakpoint?.verified === true, - 120_000 - ); - assert.strictEqual( - attachBreakpointInstalled.body.breakpoint.line, - attachBreakpointLine - ); - const attachBreakpointStop = await debugClient.waitFor( - (message) => - message.seq > attachBreakpointInstalled.seq && - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint", - 120_000 - ); - const attachStackRequest = debugClient.send("stackTrace", { - threadId: attachBreakpointStop.body.threadId, - startFrame: 0, - levels: 1, - }); - const attachStackFrames = ( - await debugClient.response(attachStackRequest, "stackTrace") - ).body.stackFrames; - assert.strictEqual( - attachStackFrames[0].line, - attachBreakpointLine, - "attach stopped somewhere other than the installed configured breakpoint" - ); - const attachContinue = debugClient.send("continue", { - threadId: attachBreakpointStop.body.threadId, - }); - const attachContinueResponse = await debugClient.response( - attachContinue, - "continue" - ); - const realDebugContainerDeadline = Date.now() + 120_000; - let lastRealDebugPodmanStates = []; - while (Date.now() < realDebugContainerDeadline) { - const containers = runJson("podman", ["ps", "--format", "json"]); - lastRealDebugPodmanStates = containers; - realDebugContainerIds = new Set( - containers - .map((container) => container.Id || container.ID || container.IdHex || "") - .filter((id) => id && !baselineContainers.has(id)) - ); - if (realDebugContainerIds.size > 0) break; - await delay(100); - } - assert( - realDebugContainerIds.size > 0, - `continued real debug participant did not start a Podman container: ${JSON.stringify( - lastRealDebugPodmanStates - )}` - ); - const attachDeadline = Date.now() + 120_000; - let attachedThreads = []; - while (Date.now() < attachDeadline) { - const threadsRequest = debugClient.send("threads"); - attachedThreads = ( - await debugClient.response(threadsRequest, "threads") - ).body.threads; - if (attachedThreads.length > 0) break; - await delay(100); - } - assert(attachedThreads.length > 0, "DAP attach reported no live threads"); - - const freezeStartedAt = Date.now(); - const pauseRequest = debugClient.send("pause", { - threadId: attachedThreads[0].id, - }); - await debugClient.response(pauseRequest, "pause"); - const dapPartialStop = await debugClient.waitFor( - (message) => - message.type === "event" && - message.seq > attachContinueResponse.seq && - message.event === "stopped" && - message.body.reason === "pause", - 30_000 - ); - assert.strictEqual(dapPartialStop.body.allThreadsStopped, false); - const epochRequest = debugClient.send("evaluate", { - expression: "debug_epoch", - context: "watch", - }); - const freeze = { - epoch: Number( - (await debugClient.response(epochRequest, "evaluate")).body.result - ), - }; - assert(Number.isSafeInteger(freeze.epoch) && freeze.epoch > 0); - const partialFreeze = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "inspect_debug_epoch", - process: processId, - epoch: freeze.epoch, - }) - ); - assert.strictEqual(partialFreeze.type, "debug_epoch_status"); - assert.strictEqual(partialFreeze.partially_frozen, true, JSON.stringify(partialFreeze)); - assert.strictEqual(partialFreeze.fully_frozen, false); - assert.strictEqual(partialFreeze.failed, true); - assert.match( - partialFreeze.failure_messages.join("; "), - /did not acknowledge frozen state within \d+ ms/ - ); - const podmanStates = runJson("podman", ["ps", "--all", "--format", "json"]); - const pausedContainers = podmanStates.filter((container) => { - const id = container.Id || container.ID || container.IdHex || ""; - const state = String(container.State || container.Status || "").toLowerCase(); - return realDebugContainerIds.has(id) && state.includes("paused"); - }); - assert( - pausedContainers.length > 0, - `partial Debug Epoch did not pause a real Podman container: ${JSON.stringify( - podmanStates - )}` - ); - const pausedContainerIds = pausedContainers.map( - (container) => container.Id || container.ID || container.IdHex - ); - - const mismatchedDigest = sha256(Buffer.from(`strict-nested-mismatch-${suffix}`)); - const mismatchedChild = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "launch_child_task", - { - type: "launch_child_task", - tenant, - project, - process: processId, - node: securityNode.node, - parent_task: fakeTask, - task_spec: { - tenant, - project, - process: processId, - task_definition: "task_add_one", - task_instance: `${fakeTask}:child:mismatched-environment`, - dispatch: { - kind: "coordinator_node_wasm", - export: null, - abi: "task_v1", - }, - environment_id: "strict-nested-mismatch", - environment: null, - environment_digest: mismatchedDigest, - required_capabilities: [], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [{ SmallJson: 41 }], - vfs_epoch: valid.epoch, - bundle_digest: bundle.digest, - }, - wait_for_node: false, - artifact_path: `/vfs/artifacts/${fakeTask}-mismatched-child.txt`, - wasm_module_base64: bundle.moduleBase64, - }, - { nonce: `strict-nested-mismatch-${suffix}` } - ) - ); - const nestedEnvironmentMismatch = assertDenied( - mismatchedChild, - /environment|digest|compatible|placement|no node/i, - "nested environment mismatch" - ); - - const continueStartedAt = Date.now(); - const continueRequest = debugClient.send("continue", { - threadId: dapPartialStop.body.threadId, - }); - await debugClient.response(continueRequest, "continue"); - const continueResponseMs = Date.now() - continueStartedAt; - assert( - continueResponseMs < 2_000, - `partial-freeze continue blocked for ${continueResponseMs} ms` - ); - await delay(1000); - const resumed = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "inspect_debug_epoch", - process: processId, - epoch: freeze.epoch, - }) - ); - assert.strictEqual(resumed.type, "debug_epoch_status"); - const resumedAcknowledgements = resumed.acknowledgements.filter( - (acknowledgement) => acknowledgement.state === "running" - ); - assert(resumedAcknowledgements.length > 0, JSON.stringify(resumed)); - const resumedPodmanStates = runJson("podman", ["ps", "--format", "json"]); - assert( - !resumedPodmanStates.some((container) => { - const id = container.Id || container.ID || container.IdHex || ""; - const state = String(container.State || container.Status || "").toLowerCase(); - return pausedContainerIds.includes(id) && state.includes("paused"); - }), - `DAP continue left a Clusterflux container paused: ${JSON.stringify( - resumedPodmanStates - )}` - ); - await debugClient.close(); - - const mainBeforeChildStartedAt = Date.now(); - const completed = await waitForCli( - "agent-authenticated coordinator main and child workflow completion", - () => - runJson(clusterflux, ["task", "list", ...scope, "--process", processId], { - cwd: projectDir, - }), - (tasks) => completedFlagship(rawTaskEvents(tasks)), - 120000 - ); - const completedEvents = rawTaskEvents(completed); - const concurrentCompileTasks = [ - ...new Set( - completedEvents - .filter( - (event) => - event.task_definition === "compile_linux" && - event.terminal_state === "completed" - ) - .map((event) => event.task) - ), - ]; - assert(concurrentCompileTasks.length >= 2, JSON.stringify(completedEvents)); - const mainCompletion = completedEvents.find( - (event) => - event.executor === "coordinator_main" && - event.terminal_state === "completed" - ); - assert(mainCompletion, "real coordinator main did not complete"); - assert( - !completedEvents.some( - (event) => - event.task === fakeTask && typeof event.terminal_state === "string" - ), - "the deliberately delayed final child completed before the coordinator main" - ); - const activeAfterMain = runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert.notStrictEqual(activeAfterMain.state, "not_active"); - assert.equal(activeAfterMain.live_process.main_state, null); - const debugStateAfterMain = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "inspect_debug_breakpoints", - process: processId, - }) - ); - assert.strictEqual( - debugStateAfterMain.type, - "debug_breakpoints", - `main completion cleared active-child debug state: ${JSON.stringify( - debugStateAfterMain - )}` - ); - const finalChildCompletion = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "task_completed", - { - type: "task_completed", - tenant, - project, - process: processId, - node: securityNode.node, - task: fakeTask, - terminal_state: "completed", - status_code: 0, - stdout_bytes: 2, - stderr_bytes: 0, - stdout_tail: "42", - stderr_tail: "", - stdout_truncated: false, - stderr_truncated: false, - artifact_path: null, - artifact_digest: null, - artifact_size_bytes: null, - result: { SmallJson: 42 }, - }, - { nonce: `strict-main-before-child-complete-${suffix}` } - ) - ); - assert.strictEqual( - finalChildCompletion.type, - "task_recorded", - JSON.stringify(finalChildCompletion) - ); - const releasedAfterFinalChild = await waitForCli( - "final delayed child to release the active process slot", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - const retainedEvents = runJson( - clusterflux, - ["task", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert( - rawTaskEvents(retainedEvents).some( - (event) => - event.task === fakeTask && event.terminal_state === "completed" - ), - "final delayed child history was not retained" - ); - const retainedArtifacts = runJson( - clusterflux, - ["artifact", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - const retainedArtifact = retainedArtifacts.artifacts.find( - (artifact) => - typeof artifact.digest === "string" && - /^sha256:[0-9a-f]{64}$/.test(artifact.digest) && - artifact.artifact.startsWith("release.tar-") - ); - assert(retainedArtifact, "real main artifact metadata was not retained"); - const subsequentRun = runJson( - clusterflux, - ["run", "park-wake", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(subsequentRun.status, "main_launched"); - const subsequentAbort = runJson( - clusterflux, - ["process", "abort", ...scope, "--process", subsequentRun.process, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(subsequentAbort.abort_request.accepted, true); - await waitForCli( - "subsequent run cleanup after final-child slot release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", subsequentRun.process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - const mainBeforeChildLifecycle = { - request: { - process: processId, - main: bundle.entryStableId, - delayed_child: fakeTask, - fault_injection: - "withhold the assigned final child's signed completion until the real coordinator main completes", - }, - expected: - "process and debug state remain until the final child completes; final cleanup retains history and real artifact metadata; a subsequent run starts", - observed: { - main_terminal_state: mainCompletion.terminal_state, - active_after_main: activeAfterMain.state !== "not_active", - debug_state_after_main: debugStateAfterMain.type, - child_terminal_state: "completed", - final_process_state: releasedAfterFinalChild.state, - retained_event_count: rawTaskEvents(retainedEvents).length, - retained_artifact: retainedArtifact, - subsequent_run_status: subsequentRun.status, - }, - duration_ms: Math.max(1, Date.now() - mainBeforeChildStartedAt), - }; - - const revoked = runJson( - clusterflux, - ["key", "revoke", ...scope, "--agent", agent, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(revoked.command, "key revoke"); - const revokedUse = assertDenied( - await sendHostedControl( - signedAgentWorkflowRequest( - identity, - { ...unsigned, process: `${processId}-revoked` }, - { nonce: `strict-agent-revoked-${suffix}` } - ) - ), - /revoked/i, - "revoked agent credential" - ); - return { - duration_ms: Date.now() - scenarioStartedAt, - agent, - valid_request: valid.type, - replay, - expired, - forged, - body_modified: bodyModified, - revoked: revokedUse, - workflow: { - process: processId, - main_launch: mainLaunch.type, - external_direct_task_v1: directTaskV1, - child_launch: fakeLaunch.type, - child_parent: liveParentTask, - real_debug_child_launch: realDebugLaunch.type, - real_debug_child: realDebugTask, - actor_kind: mainLaunch.actor.kind, - authenticated_without_browser: mainLaunch.actor.authenticated_without_browser, - flagship_completed: completedFlagship(completedEvents), - concurrent_compile_tasks: concurrentCompileTasks, - }, - main_before_child_lifecycle: mainBeforeChildLifecycle, - attach_with_preconfigured_breakpoint: { - request: { - process: processId, - source: attachSourcePath, - line: attachBreakpointLine, - }, - expected: - "preconfigured before attach, unverified until adapter installation, then a real breakpoint stop at the configured line", - observed: { - preconfigured_revision: preconfiguredBreakpoint.revision, - initially_verified: - attachBreakpointResponse.body.breakpoints[0].verified, - installation_event_verified: - attachBreakpointInstalled.body.breakpoint.verified, - stop_reason: attachBreakpointStop.body.reason, - stopped_line: attachStackFrames[0].line, - }, - duration_ms: Date.now() - scenarioStartedAt, - }, - partial_freeze: { - epoch: freeze.epoch, - elapsed_ms: Date.now() - freezeStartedAt, - partially_frozen: partialFreeze.partially_frozen, - fully_frozen: partialFreeze.fully_frozen, - dap_all_threads_stopped: dapPartialStop.body.allThreadsStopped, - dap_continue_response_ms: continueResponseMs, - podman_paused_container_ids: pausedContainerIds, - warning: partialFreeze.failure_messages, - resumed_participants: resumedAcknowledgements.map( - (acknowledgement) => acknowledgement.task - ), - }, - nested_environment_mismatch: nestedEnvironmentMismatch, - }; -} - -async function runSecondTenantIsolation({ - clusterflux, - clusterfluxNode, - firstScope, - firstHelloBuild, - firstHelloProjectDir, - workRoot, - firstSessionSecret, - firstTenant, - firstProject, - firstProcess, - firstNode, - firstArtifact, - manifest, -}) { - const startedAt = Date.now(); - const file = process.env.CLUSTERFLUX_SECOND_TENANT_SESSION_FILE; - const evidenceFile = process.env.CLUSTERFLUX_SECOND_TENANT_EVIDENCE_FILE; - const targetTenant = process.env.CLUSTERFLUX_ISOLATION_TARGET_TENANT; - const targetProject = process.env.CLUSTERFLUX_ISOLATION_TARGET_PROJECT; - if (!file && evidenceFile) { - const evidenceBytes = fs.readFileSync(path.resolve(evidenceFile)); - const previous = JSON.parse(evidenceBytes); - const isolation = previous.tenant_isolation; - assert.strictEqual(isolation?.executed, true); - assert.notStrictEqual(isolation.second_tenant, firstTenant); - assert.strictEqual(isolation.project?.denied, true); - assert.strictEqual(isolation.process_hidden, true); - assert.strictEqual(isolation.node_hidden, true); - assert.strictEqual(isolation.tasks_and_logs?.denied, true); - assert.strictEqual(isolation.debug?.denied, true); - assert.strictEqual(isolation.debug?.audited, true); - assert.strictEqual(isolation.debug?.charged_debug_read_bytes, 0); - assert.strictEqual(isolation.artifact_and_download?.denied, true); - assert.strictEqual(isolation.process_control?.denied, true); - const previousDeployment = previous.release_binding?.deployment; - const currentDeployment = deploymentProvenance(); - assert.strictEqual( - previousDeployment?.hosted_service_sha256, - currentDeployment.hosted_service_sha256, - "reused isolation evidence must target the exact deployed hosted binary" - ); - assert.deepStrictEqual( - previous.release_binding?.binary_digests, - manifest.binary_digests, - "reused isolation evidence must target the exact public binaries" - ); - return { - evidence: { - ...isolation, - duration_ms: Date.now() - startedAt, - reused_from_immutable_evidence: { - report_sha256: sha256(evidenceBytes), - source_commit: previous.source_commit, - hosted_service_sha256: currentDeployment.hosted_service_sha256, - public_binary_digests: manifest.binary_digests, - }, - }, - runtime: null, - }; - } - if (!file && targetTenant && targetProject) { - assert.notStrictEqual( - targetTenant, - firstTenant, - "single-account isolation target must name a different hosted tenant" - ); - assert.notStrictEqual( - targetProject, - firstProject, - "single-account isolation target must name a different hosted project" - ); - const call = (request) => - sendHostedControl(authenticatedRequest(firstSessionSecret, request)); - const project = assertDenied( - await call({ type: "select_project", project: targetProject }), - /outside|not visible|tenant|project|permission|unauthorized/i, - "single-account cross-tenant project selection" - ); - const processes = await call({ type: "list_processes" }); - assert.strictEqual( - processes.type, - "process_statuses", - JSON.stringify(processes) - ); - assert(!JSON.stringify(processes).includes(targetTenant)); - assert(!JSON.stringify(processes).includes(targetProject)); - const nodes = await call({ type: "list_node_descriptors" }); - assert.strictEqual(nodes.type, "node_descriptors", JSON.stringify(nodes)); - assert(!JSON.stringify(nodes).includes(targetTenant)); - assert(!JSON.stringify(nodes).includes(targetProject)); - const foreignProcess = `vp-foreign-isolation-${Date.now()}`; - const foreignArtifact = `artifact-foreign-isolation-${Date.now()}`; - const tasksAndLogsResponse = await call({ - type: "list_task_events", - process: foreignProcess, - }); - let tasksAndLogs; - if (tasksAndLogsResponse.type === "error") { - tasksAndLogs = { - ...assertDenied( - tasksAndLogsResponse, - /outside|scope|tenant|project|not active|requires an active|unknown/i, - "single-account foreign task and log listing" - ), - enforcement: "explicit_error", - }; - } else { - assert.strictEqual( - tasksAndLogsResponse.type, - "task_events", - JSON.stringify(tasksAndLogsResponse) - ); - assert.deepStrictEqual( - tasksAndLogsResponse.events, - [], - "single-account foreign-looking task listing must disclose no events" - ); - assert(!JSON.stringify(tasksAndLogsResponse).includes(targetTenant)); - assert(!JSON.stringify(tasksAndLogsResponse).includes(targetProject)); - tasksAndLogs = { - denied: true, - reason: "authenticated scope returned no visible task or log events", - enforcement: "scoped_empty_result", - response_type: tasksAndLogsResponse.type, - event_count: tasksAndLogsResponse.events.length, - }; - } - const debugResponse = await call({ - type: "debug_attach", - process: foreignProcess, - }); - assert.strictEqual( - debugResponse.type, - "debug_attach", - JSON.stringify(debugResponse) - ); - assert.strictEqual(debugResponse.authorization?.allowed, false); - assert.strictEqual(debugResponse.audit_event?.allowed, false); - assert.strictEqual(debugResponse.charged_debug_read_bytes, 0); - const artifact = assertDenied( - await call({ - type: "create_artifact_download_link", - artifact: foreignArtifact, - max_bytes: 1024, - ttl_seconds: 60, - }), - /outside|scope|tenant|project|not found|does not exist|unavailable/i, - "single-account foreign artifact download" - ); - const control = assertDenied( - await call({ type: "abort_process", process: foreignProcess }), - /outside|scope|tenant|project|not active|requires an active|unknown/i, - "single-account foreign process control" - ); - return { - evidence: { - executed: true, - mode: "single_authenticated_account_foreign_project", - second_tenant: targetTenant, - target_project: targetProject, - project, - process_hidden: true, - node_hidden: true, - tasks_and_logs: tasksAndLogs, - debug: { - denied: true, - reason: debugResponse.authorization.reason, - audited: true, - charged_debug_read_bytes: debugResponse.charged_debug_read_bytes, - }, - artifact_and_download: artifact, - process_control: control, - duration_ms: Date.now() - startedAt, - }, - runtime: null, - }; - } - if (!file) { - return { - evidence: { - executed: false, - reason: "second tenant session not supplied", - duration_ms: Math.max(1, Date.now() - startedAt), - }, - runtime: null, - }; - } - const secondSessionPath = path.resolve(file); - const second = readJson(secondSessionPath); - assert.strictEqual(second.coordinator, serviceEndpoint); - const secondSessionSecret = - second.cli_session_secret || second.session_secret; - assert(secondSessionSecret, "second tenant session omitted its session secret"); - assert.notStrictEqual( - second.tenant, - firstTenant, - "isolation proof requires a genuinely distinct hosted tenant" - ); - assert.notStrictEqual( - second.project, - firstProject, - "isolation proof requires a genuinely distinct hosted project" - ); - const call = (request) => - sendHostedControl(authenticatedRequest(secondSessionSecret, request)); - - const project = assertDenied( - await call({ type: "select_project", project: firstProject }), - /outside|not visible|tenant|project/i, - "cross-tenant project selection" - ); - const processes = await call({ type: "list_processes" }); - assert.strictEqual( - processes.type, - "process_statuses", - JSON.stringify(processes) - ); - assert(!JSON.stringify(processes).includes(firstProcess)); - const nodes = await call({ type: "list_node_descriptors" }); - assert.strictEqual(nodes.type, "node_descriptors", JSON.stringify(nodes)); - assert(!JSON.stringify(nodes).includes(firstNode)); - const tasksAndLogs = assertDenied( - await call({ type: "list_task_events", process: firstProcess }), - /outside|scope|tenant|project|not active|requires an active|unknown/i, - "cross-tenant task and log listing" - ); - const debugResponse = await call({ - type: "debug_attach", - process: firstProcess, - }); - assert.strictEqual(debugResponse.type, "debug_attach", JSON.stringify(debugResponse)); - assert.strictEqual(debugResponse.authorization?.allowed, false); - assert.strictEqual(debugResponse.audit_event?.allowed, false); - assert.match( - debugResponse.authorization?.reason || "", - /outside|scope|permission|tenant|project|not active|unknown/i - ); - assert.strictEqual(debugResponse.charged_debug_read_bytes, 0); - const debug = { - denied: true, - reason: debugResponse.authorization.reason, - audited: true, - charged_debug_read_bytes: debugResponse.charged_debug_read_bytes, - }; - const artifact = assertDenied( - await call({ - type: "create_artifact_download_link", - artifact: firstArtifact, - max_bytes: 1024, - ttl_seconds: 60, - }), - /outside|scope|tenant|project|not found|does not exist|unavailable/i, - "cross-tenant artifact download" - ); - const control = assertDenied( - await call({ type: "abort_process", process: firstProcess }), - /outside|scope|tenant|project|not active|requires an active|unknown/i, - "cross-tenant process control" - ); - - const secondCheckout = path.join(workRoot, "second-tenant-public-repo"); - stagePublicCheckout(manifest, secondCheckout); - const secondProjectDir = path.join( - secondCheckout, - "examples", - "hello-build" - ); - const secondControlDir = path.join(secondProjectDir, ".clusterflux"); - ensureDir(secondControlDir); - const secondProjectPath = path.join( - path.dirname(secondSessionPath), - "project.json" - ); - assert( - fs.existsSync(secondProjectPath), - `second tenant session is missing adjacent project.json: ${secondProjectPath}` - ); - fs.copyFileSync( - secondSessionPath, - path.join(secondControlDir, "session.json") - ); - fs.copyFileSync( - secondProjectPath, - path.join(secondControlDir, "project.json") - ); - fs.chmodSync(path.join(secondControlDir, "session.json"), 0o600); - fs.chmodSync(path.join(secondControlDir, "project.json"), 0o644); - const secondScope = [ - "--coordinator", - serviceEndpoint, - "--tenant", - second.tenant, - "--project-id", - second.project, - "--user", - second.user, - "--json", - ]; - const secondProjectList = runJson( - clusterflux, - ["project", "list", ...secondScope], - { cwd: secondProjectDir } - ); - assert(secondProjectList.project_count >= 1); - const secondProjectSelect = runJson( - clusterflux, - ["project", "select", ...secondScope, second.project], - { cwd: secondProjectDir } - ); - assert.strictEqual(secondProjectSelect.command, "project select"); - - const collisionStartedAt = Date.now(); - const secondGrant = runJson( - clusterflux, - ["node", "enroll", ...secondScope], - { cwd: secondProjectDir } - ); - const secondAttach = runJson( - clusterflux, - [ - "node", - "attach", - "--coordinator", - serviceEndpoint, - "--tenant", - second.tenant, - "--project-id", - second.project, - "--node", - firstNode, - "--enrollment-grant", - secondGrant.enrollment_grant.grant, - "--json", - ], - { cwd: secondProjectDir } - ); - assert.strictEqual(secondAttach.boundary.used_enrollment_exchange, true); - const secondStored = readNodeCredential(secondProjectDir, firstNode); - const secondCredentialDigest = sha256( - fs.readFileSync(secondStored.absolute) - ); - const secondIdentity = nodeIdentityFromPrivateKey( - secondStored.credential.private_key - ); - const secondWorkerArgs = [ - "--coordinator", - serviceEndpoint, - "--tenant", - second.tenant, - "--project-id", - second.project, - "--node", - firstNode, - "--worker", - "--project-root", - secondProjectDir, - "--assignment-poll-ms", - "500", - "--emit-ready", - ]; - const firstHelloWorker = spawnJsonLines( - clusterfluxNode, - [ - "--coordinator", - serviceEndpoint, - "--tenant", - firstTenant, - "--project-id", - firstProject, - "--node", - firstNode, - "--worker", - "--project-root", - firstHelloProjectDir, - "--assignment-poll-ms", - "500", - "--emit-ready", - ], - { - cwd: firstHelloProjectDir, - env: { ...process.env }, - } - ); - const firstHelloReady = await firstHelloWorker.waitFor( - (value) => value.node_status === "ready", - "first-tenant hello-build artifact worker ready for collision proof" - ); - assert.strictEqual(firstHelloReady.node, firstNode); - const firstCollisionHelloBuild = await runHostedHelloBuild({ - clusterflux, - projectDir: firstHelloProjectDir, - scope: firstScope, - outputFile: path.join(workRoot, "hello-clusterflux-first-tenant-collision"), - }); - assert.strictEqual( - firstCollisionHelloBuild.artifact, - firstHelloBuild.artifact, - "repeated deterministic first-tenant hello-build changed its ArtifactId" - ); - assert.strictEqual(firstCollisionHelloBuild.digest, firstHelloBuild.digest); - assert.strictEqual( - firstCollisionHelloBuild.executable_output, - firstHelloBuild.executable_output - ); - const secondWorker = spawnJsonLines(clusterfluxNode, secondWorkerArgs, { - cwd: secondProjectDir, - env: { ...process.env }, - }); - let secondHelloBuild; - try { - const secondReady = await secondWorker.waitFor( - (value) => value.node_status === "ready", - "same-name second-tenant worker ready" - ); - assert.strictEqual(secondReady.node, firstNode); - secondHelloBuild = await runHostedHelloBuild({ - clusterflux, - projectDir: secondProjectDir, - scope: secondScope, - outputFile: path.join(workRoot, "hello-clusterflux-second-tenant"), - }); - } finally { - await stopChild(secondWorker.child); - } - assert.strictEqual( - secondHelloBuild.artifact, - firstCollisionHelloBuild.artifact, - "deterministic two-tenant hello-build did not collide on ArtifactId" - ); - assert.strictEqual( - secondHelloBuild.digest, - firstCollisionHelloBuild.digest, - "deterministic two-tenant hello-build did not produce identical bytes" - ); - assert.strictEqual( - secondHelloBuild.executable_output, - firstCollisionHelloBuild.executable_output - ); - - const firstArtifactsAfterCollision = runJson( - clusterflux, - [ - "artifact", - "list", - ...firstScope, - "--process", - firstCollisionHelloBuild.process, - ], - { cwd: firstHelloProjectDir } - ); - assert( - firstArtifactsAfterCollision.artifacts.some( - (candidate) => - candidate.artifact === firstCollisionHelloBuild.artifact && - candidate.digest === firstCollisionHelloBuild.digest - ), - "the second tenant's same-ID artifact masked the first tenant's metadata" - ); - const secondCollisionLink = await call({ - type: "create_artifact_download_link", - artifact: secondHelloBuild.artifact, - max_bytes: secondHelloBuild.downloaded_bytes, - ttl_seconds: 60, - }); - assert.strictEqual( - secondCollisionLink.type, - "artifact_download_link", - JSON.stringify(secondCollisionLink) - ); - const secondCollisionLinkRevoked = await call({ - type: "revoke_artifact_download_link", - artifact: secondHelloBuild.artifact, - token_digest: secondCollisionLink.link.scoped_token_digest, - }); - assert.strictEqual( - secondCollisionLinkRevoked.type, - "artifact_download_link_revoked", - JSON.stringify(secondCollisionLinkRevoked) - ); - const firstDownloadAfterSecondLinkRevocation = runJson( - clusterflux, - [ - "artifact", - "download", - ...firstScope, - firstCollisionHelloBuild.artifact, - "--to", - path.join(workRoot, "hello-clusterflux-first-after-second-link-revoke"), - ], - { cwd: firstHelloProjectDir } - ); - assert.strictEqual( - firstDownloadAfterSecondLinkRevocation.local_download.verified_digest, - firstCollisionHelloBuild.digest - ); - await stopChild(firstHelloWorker.child); - - return { - evidence: { - executed: true, - second_tenant: second.tenant, - second_project: second.project, - project, - process_hidden: true, - node_hidden: true, - tasks_and_logs: tasksAndLogs, - debug, - artifact_and_download: artifact, - process_control: control, - scoped_node_and_artifact_collision: { - request: { - node: firstNode, - first_scope: { - tenant: firstTenant, - project: firstProject, - }, - second_scope: { - tenant: second.tenant, - project: second.project, - }, - example: "hello-build", - }, - expected: - "same-name Nodes coexist and deterministic hello-build artifacts share an ArtifactId without metadata, link, or download interference", - observed: { - first_process: firstCollisionHelloBuild.process, - second_process: secondHelloBuild.process, - same_artifact_id: secondHelloBuild.artifact, - first_digest: firstCollisionHelloBuild.digest, - second_digest: secondHelloBuild.digest, - first_downloaded_bytes: firstCollisionHelloBuild.downloaded_bytes, - second_downloaded_bytes: secondHelloBuild.downloaded_bytes, - exact_executable_output: secondHelloBuild.executable_output, - both_metadata_records_visible_to_owner: true, - cross_tenant_unique_artifact_denied: artifact.denied, - second_link_revoked: true, - first_download_survived_second_link_revocation: true, - }, - duration_ms: Math.max(1, Date.now() - collisionStartedAt), - }, - duration_ms: Math.max(1, Date.now() - startedAt), - }, - runtime: { - node: firstNode, - tenant: second.tenant, - project: second.project, - projectDir: secondProjectDir, - scope: secondScope, - workerArgs: secondWorkerArgs, - credentialPath: secondStored.absolute, - credentialDigest: secondCredentialDigest, - identity: secondIdentity, - }, - }; -} - -async function runLiveSignedHostileArtifactPath({ - clusterflux, - projectDir, - scope, - tenant, - project, - suffix, - securityNode, -}) { - const startedAt = Date.now(); - const runReport = runJson( - clusterflux, - ["run", "park-wake", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.status, "main_launched"); - const process = runReport.process; - await waitForCli( - "hostile-path probe process to become active", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", process], - { cwd: projectDir } - ), - (status) => status.state !== "not_active", - 120_000 - ); - - const invalidStartedAt = Date.now(); - const invalid = assertDenied( - await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "report_vfs_metadata", - { - type: "report_vfs_metadata", - tenant, - project, - process, - node: securityNode.node, - task: `hostile-path-${suffix}`, - artifact_path: "/vfs/artifacts/bad artifact!", - artifact_digest: sha256(Buffer.from("hostile-path-invalid")), - artifact_size_bytes: 20, - large_bytes_uploaded: false, - }, - { nonce: `strict-hostile-path-invalid-${suffix}-${Date.now()}` } - ) - ), - /invalid VFS artifact path|invalid artifact path|ArtifactId is invalid/i, - "correctly signed hostile artifact path" - ); - const invalidDurationMs = Math.max(1, Date.now() - invalidStartedAt); - - const validStartedAt = Date.now(); - const validArtifact = `strict-hostile-followup-${suffix}`; - const valid = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "report_vfs_metadata", - { - type: "report_vfs_metadata", - tenant, - project, - process, - node: securityNode.node, - task: `hostile-path-${suffix}`, - artifact_path: `/vfs/artifacts/${validArtifact}`, - artifact_digest: sha256(Buffer.from("hostile-path-valid")), - artifact_size_bytes: 18, - large_bytes_uploaded: false, - }, - { nonce: `strict-hostile-path-valid-${suffix}-${Date.now()}` } - ) - ); - assert.strictEqual(valid.type, "vfs_metadata_recorded", JSON.stringify(valid)); - const healthyHeartbeat = await sendHostedControl({ - type: "node_heartbeat", - tenant, - project, - node: securityNode.node, - node_signature: signedNodeHeartbeat( - tenant, - project, - securityNode.node, - securityNode.identity, - { nonce: `strict-hostile-path-health-${suffix}-${Date.now()}` } - ), - }); - assert.strictEqual( - healthyHeartbeat.type, - "node_heartbeat", - JSON.stringify(healthyHeartbeat) - ); - const validDurationMs = Math.max(1, Date.now() - validStartedAt); - const aborted = runJson( - clusterflux, - ["process", "abort", ...scope, "--process", process, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(aborted.abort_request.accepted, true); - await waitForCli( - "hostile-path probe process cleanup", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - return { - request: { - principal: "enrolled signed Node", - variant: "report_vfs_metadata", - process, - malformed_path: "/vfs/artifacts/bad artifact!", - }, - expected: - "structured InvalidArtifactPath rejection followed immediately by valid signed metadata and heartbeat on the same service instance", - observed: { - rejection: invalid, - valid_metadata_response: valid.type, - valid_artifact: validArtifact, - health_response: healthyHeartbeat.type, - process_cleanup: "not_active", - }, - invalid_duration_ms: invalidDurationMs, - valid_followup_duration_ms: validDurationMs, - duration_ms: Math.max(1, Date.now() - startedAt), - }; -} - -async function runLiveSoak({ - clusterflux, - projectDir, - scope, - securityNode, -}) { - if (!strictVpsRestart) { - return { executed: false, reason: "strict VPS measurement access not supplied" }; - } - const runReport = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.status, "main_launched"); - const processId = runReport.process; - const parked = await waitForCli( - "soak coordinator main to park without a capable node", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => - status.live_process?.main_state === "running" && - status.live_process?.main_wait_state === "waiting_for_task" && - status.current_task_count === 0 && - status.live_process?.connected_nodes?.length === 0, - 120000 - ); - - const pollSecurityNode = (nonce) => - sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "poll_task_assignment", - { - type: "poll_task_assignment", - tenant: securityNode.capability_body.tenant, - project: securityNode.capability_body.project, - node: securityNode.node, - }, - { nonce } - ) - ); - const drainedPriorAssignments = []; - for (let drainIndex = 0; drainIndex < 16; drainIndex += 1) { - const poll = await pollSecurityNode( - `strict-soak-drain-${drainIndex}-${Date.now()}` - ); - assert.strictEqual(poll.type, "task_assignment", JSON.stringify(poll)); - if (poll.assignment === null) break; - assert.notStrictEqual( - poll.assignment.process, - processId, - "soak process unexpectedly received a task assignment" - ); - drainedPriorAssignments.push({ - process: poll.assignment.process, - task: poll.assignment.task, - }); - assert(drainIndex < 15, "pre-soak assignment drain did not quiesce"); - } - - const startedAt = Date.now(); - const deadline = startedAt + strictSoakSeconds * 1000; - const samples = []; - let sampleIndex = 0; - while (true) { - const capabilities = await sendHostedControl( - signedNodeRequest( - securityNode.node, - securityNode.identity, - "report_node_capabilities", - securityNode.capability_body, - { nonce: `strict-soak-capabilities-${sampleIndex}-${Date.now()}` } - ) - ); - assert.strictEqual( - capabilities.type, - "node_capabilities_recorded", - JSON.stringify(capabilities) - ); - const poll = await pollSecurityNode( - `strict-soak-poll-${sampleIndex}-${Date.now()}` - ); - assert.strictEqual(poll.type, "task_assignment", JSON.stringify(poll)); - assert.strictEqual(poll.assignment, null); - const status = runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert.strictEqual(status.live_process.main_wait_state, "waiting_for_task"); - samples.push(strictInfrastructureSample(projectDir)); - sampleIndex += 1; - if (Date.now() >= deadline) break; - await delay(Math.min(30_000, deadline - Date.now())); - } - - const currentMemory = samples.map( - (sample) => sample.service_memory_current_bytes - ); - const serviceDisk = samples.map((sample) => sample.service_state_disk_bytes); - const databaseDisk = samples.map((sample) => sample.postgres_database_bytes); - const localDisk = samples.map((sample) => sample.local_node_state.bytes); - const spread = (values) => Math.max(...values) - Math.min(...values); - assert(spread(currentMemory) <= 128 * 1024 * 1024); - assert(spread(serviceDisk) <= 16 * 1024 * 1024); - assert(spread(databaseDisk) <= 32 * 1024 * 1024); - assert(spread(localDisk) <= 16 * 1024 * 1024); - assert.deepStrictEqual( - samples.at(-1).durable_rows, - samples[0].durable_rows, - "durable object counts grew during the parked-process soak" - ); - const aborted = runJson( - clusterflux, - ["process", "abort", ...scope, "--process", processId, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(aborted.abort_request.process_slot_released, true); - return { - executed: true, - process: processId, - duration_seconds: Math.floor((Date.now() - startedAt) / 1000), - sample_interval_seconds: 30, - sample_count: samples.length, - parked_main: { - main_state: parked.live_process.main_state, - main_wait_state: parked.live_process.main_wait_state, - }, - drained_prior_assignments: drainedPriorAssignments, - signed_node_poll_cycles: samples.length, - memory_spread_bytes: spread(currentMemory), - service_disk_spread_bytes: spread(serviceDisk), - postgres_disk_spread_bytes: spread(databaseDisk), - local_node_state_spread_bytes: spread(localDisk), - samples, - }; -} - -async function revokeSecurityNode({ - clusterflux, - projectDir, - scope, - securityNode, -}) { - const startedAt = Date.now(); - const revoked = runJson( - clusterflux, - ["node", "revoke", ...scope, "--node", securityNode.node, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(revoked.command, "node revoke"); - const denied = assertDenied( - await sendHostedControl({ - type: "node_heartbeat", - tenant: securityNode.capability_body.tenant, - project: securityNode.capability_body.project, - node: securityNode.node, - node_signature: signedNodeHeartbeat( - securityNode.capability_body.tenant, - securityNode.capability_body.project, - securityNode.node, - securityNode.identity, - { nonce: `strict-node-revoked-${Date.now()}` } - ), - }), - /revoked|unknown node|not recognized|not enrolled/i, - "revoked node credential" - ); - return { - node: securityNode.node, - denied, - duration_ms: Date.now() - startedAt, - }; -} - -async function runLiveQuotaPreallocation({ sessionSecret, suffix }) { - const startedAt = Date.now(); - const readSpawnQuota = async () => { - const status = await sendHostedControl( - authenticatedRequest(sessionSecret, { type: "quota_status" }) - ); - assert.strictEqual(status.type, "quota_status", JSON.stringify(status)); - const limit = status.limits?.limits?.Spawn; - const usage = status.usage?.Spawn; - const windowSeconds = status.window_seconds?.Spawn; - const windowStarted = status.window_started_epoch_seconds?.Spawn; - assert(Number.isInteger(limit) && limit > 0, JSON.stringify(status)); - assert(Number.isInteger(usage) && usage >= 0, JSON.stringify(status)); - assert( - Number.isInteger(windowSeconds) && windowSeconds > 0, - JSON.stringify(status) - ); - assert(Number.isInteger(windowStarted), JSON.stringify(status)); - return { limit, usage, windowSeconds, windowStarted }; - }; - - let spawnQuota = await readSpawnQuota(); - const windowElapsed = Math.max( - 0, - Math.floor(Date.now() / 1000) - spawnQuota.windowStarted - ); - if (spawnQuota.usage > 0 || windowElapsed > 1) { - await delay( - Math.max(1000, (spawnQuota.windowSeconds - windowElapsed + 1) * 1000) - ); - spawnQuota = await readSpawnQuota(); - } - let denial; - let deniedProcess; - let acceptedStarts = 0; - const maxAttempts = spawnQuota.limit - spawnQuota.usage + 2; - for (let index = 0; index < maxAttempts; index += 1) { - const processId = `vp-quota-${suffix}-${index}`; - const started = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "start_process", - process: processId, - restart: false, - }) - ); - if (started.type === "error") { - assert.match(started.message, /quota|spawn|limit|community tier/i); - denial = started; - deniedProcess = processId; - break; - } - assert.strictEqual(started.type, "process_started", JSON.stringify(started)); - acceptedStarts += 1; - const aborted = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "abort_process", - process: processId, - }) - ); - assert.strictEqual(aborted.type, "process_aborted", JSON.stringify(aborted)); - } - assert( - denial, - `live community-tier spawn quota was not reached in ${maxAttempts} attempts` - ); - const processes = await sendHostedControl( - authenticatedRequest(sessionSecret, { type: "list_processes" }) - ); - assert.strictEqual( - processes.type, - "process_statuses", - JSON.stringify(processes) - ); - assert( - !JSON.stringify(processes).includes(deniedProcess), - "quota-denied process was allocated before denial" - ); - const independentScope = await sendHostedControl( - authenticatedRequest(sessionSecret, { type: "list_node_descriptors" }) - ); - assert.strictEqual( - independentScope.type, - "node_descriptors", - `spawn quota exhaustion locked an independent read scope: ${JSON.stringify(independentScope)}` - ); - return { - duration_ms: Date.now() - startedAt, - limit: spawnQuota.limit, - initial_usage: spawnQuota.usage, - window_seconds: spawnQuota.windowSeconds, - accepted_starts_before_denial: acceptedStarts, - denied_process: deniedProcess, - denial: { - type: denial.type, - category: denial.error?.category || null, - message: denial.message, - }, - denied_process_allocated: false, - independent_scope: { - operation: "list_node_descriptors", - response: independentScope.type, - unaffected_by_spawn_quota: true, - }, - }; -} - -async function runLongJoinProof({ clusterflux, projectDir, scope }) { - const startedAt = Date.now(); - const runReport = runJson( - clusterflux, - ["run", "long-join", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.status, "main_launched"); - const terminal = await waitForCli( - "controlled task longer than two minutes", - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (tasks) => - rawTaskEvents(tasks).some( - (event) => - event.task_definition === "long_join_probe" && - event.terminal_state === "completed" - ), - 5 * 60 * 1000 - ); - const completed = rawTaskEvents(terminal).find( - (event) => - event.task_definition === "long_join_probe" && - event.terminal_state === "completed" - ); - const durationSeconds = Math.floor((Date.now() - startedAt) / 1000); - assert(durationSeconds > 120); - const released = await waitForCli( - "long join process automatic slot release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120000 - ); - return { - process: runReport.process, - task: completed.task, - terminal_state: completed.terminal_state, - result: completed.result, - duration_seconds: durationSeconds, - duration_ms: Math.max(1, Date.now() - startedAt), - process_state: released.state, - }; -} - -async function runRepeatedParkWakeProof({ clusterflux, projectDir, scope }) { - const runReport = runJson( - clusterflux, - ["run", "park-wake", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.status, "main_launched"); - const terminal = await waitForCli( - "repeated coordinator-main park/wake completion", - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (tasks) => { - const completed = new Set( - rawTaskEvents(tasks) - .filter( - (event) => - event.task_definition === "task_add_one" && - event.terminal_state === "completed" - ) - .map((event) => event.task) - ); - return completed.size >= 16; - }, - 120000 - ); - const completedTasks = [ - ...new Set( - rawTaskEvents(terminal) - .filter( - (event) => - event.task_definition === "task_add_one" && - event.terminal_state === "completed" - ) - .map((event) => event.task) - ), - ]; - const released = await waitForCli( - "park/wake process automatic slot release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120000 - ); - return { - process: runReport.process, - completed_cycles: completedTasks.length, - task_instances: completedTasks, - terminal_state: released.state, - }; -} - -async function runDroppedConnectionRollback({ - clusterflux, - projectDir, - scope, -}) { - const scenarioStartedAt = Date.now(); - const processId = "vp-current"; - const attempted = cp.spawnSync( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { - cwd: projectDir, - env: { - ...process.env, - CLUSTERFLUX_TEST_DROP_RESPONSE_AFTER_OPERATION: "start_process", - }, - encoding: "utf8", - timeout: 5 * 60 * 1000, - } - ); - assert.notStrictEqual( - attempted.status, - 0, - `response-loss run unexpectedly succeeded: ${attempted.stdout}` - ); - assert.match( - `${attempted.stderr}\n${attempted.stdout}`, - /closed.*without a response|transport|response/i - ); - const released = await waitForCli( - "CLI launch guard rollback after lost start response", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 30000 - ); - return { - duration_ms: Date.now() - scenarioStartedAt, - process: processId, - failure_injection: "control transport dropped attempt-owned start_process response", - cli_exit_status: attempted.status, - rollback: "automatic CLI launch guard abort_process with matching launch_attempt", - terminal_state: released.state, - }; -} - -async function runLaunchAttemptOwnershipGuards({ - clusterflux, - projectDir, - scope, - sessionSecret, - activeProcess, -}) { - const startedAt = Date.now(); - const rejectedAttempt = `launch-guard-rejected-${Date.now()}`; - const rejection = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "start_process", - process: `${activeProcess}-contender`, - launch_attempt: rejectedAttempt, - restart: false, - }) - ); - assert.strictEqual(rejection.type, "error"); - assert.match(rejection.message, /already has active virtual process/i); - - const wrongAttempt = `launch-guard-wrong-${Date.now()}`; - const deniedAbort = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "abort_process", - process: activeProcess, - launch_attempt: wrongAttempt, - }) - ); - assert.strictEqual(deniedAbort.type, "error"); - assert.match(deniedAbort.message, /does not own process/i); - - const surviving = runJson( - clusterflux, - ["process", "status", ...scope, "--process", activeProcess], - { cwd: projectDir } - ); - assert.notStrictEqual(surviving.state, "not_active"); - assert.strictEqual(surviving.process, activeProcess); - return { - duration_ms: Date.now() - startedAt, - rejected_attempt: rejectedAttempt, - rejection: rejection.message, - wrong_abort_attempt: wrongAttempt, - wrong_abort_denied: deniedAbort.message, - existing_process_survived: true, - }; -} - -async function runLiveBandwidthPreallocation({ - sessionSecret, - artifact, - maxBytes, -}) { - const scenarioStartedAt = Date.now(); - const before = relayDurableState(); - const partialLink = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "create_artifact_download_link", - artifact, - max_bytes: maxBytes, - ttl_seconds: 300, - }) - ); - assert.strictEqual( - partialLink.type, - "artifact_download_link", - JSON.stringify(partialLink) - ); - const partialToken = partialLink.link.scoped_token_digest; - let partialChunk; - const partialDeadline = Date.now() + 120_000; - while (Date.now() < partialDeadline) { - const response = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "open_artifact_download_stream", - artifact, - max_bytes: maxBytes, - token_digest: partialToken, - chunk_bytes: 16, - }) - ); - assert.strictEqual( - response.type, - "artifact_download_stream", - JSON.stringify(response) - ); - if (response.content_bytes_available === true) { - partialChunk = response; - break; - } - await delay(50); - } - assert(partialChunk, "artifact relay did not return the first partial chunk"); - assert.strictEqual(partialChunk.content_eof, false); - assert.strictEqual(partialChunk.streamed_bytes, 16); - const partialRevoked = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "revoke_artifact_download_link", - artifact, - token_digest: partialToken, - }) - ); - assert.strictEqual( - partialRevoked.type, - "artifact_download_link_revoked", - JSON.stringify(partialRevoked) - ); - const afterPartialAbandon = relayDurableState(); - assert(afterPartialAbandon.ingress_used > before.ingress_used); - assert(afterPartialAbandon.egress_used > before.egress_used); - assert( - afterPartialAbandon.abandoned_or_failed_used > - before.abandoned_or_failed_used - ); - - let denial; - const acceptedReservations = []; - for (let index = 0; index < 64; index += 1) { - const response = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "create_artifact_download_link", - artifact, - max_bytes: maxBytes, - ttl_seconds: 300, - }) - ); - if (response.type === "error") { - assert.match( - response.message, - /artifact relay.*(?:concurrency|period byte budget)|bandwidth|reservation/i - ); - denial = response; - break; - } - assert.strictEqual(response.type, "artifact_download_link", JSON.stringify(response)); - acceptedReservations.push(response.link.scoped_token_digest); - } - assert(denial, "artifact relay preallocation was not denied in 64 reservations"); - for (const tokenDigest of acceptedReservations) { - const revoked = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "revoke_artifact_download_link", - artifact, - token_digest: tokenDigest, - }) - ); - assert.strictEqual( - revoked.type, - "artifact_download_link_revoked", - JSON.stringify(revoked) - ); - } - const afterRelease = relayDurableState(); - assert.strictEqual( - Object.keys(afterRelease.reservations || {}).length, - Object.keys(before.reservations || {}).length - ); - return { - scenario_started_at_ms: scenarioStartedAt, - artifact, - accepted_reservations_before_denial: acceptedReservations.length, - bytes_served_before_denial: partialChunk.streamed_bytes, - partial_abandon: { - ingress_delta: afterPartialAbandon.ingress_used - before.ingress_used, - egress_delta: afterPartialAbandon.egress_used - before.egress_used, - abandoned_delta: - afterPartialAbandon.abandoned_or_failed_used - - before.abandoned_or_failed_used, - reservation_released: !(partialToken in afterRelease.reservations), - }, - durable_before: before, - durable_after_release: afterRelease, - denial: { - type: denial.type, - category: denial.error?.category || null, - message: denial.message, - }, - }; -} - -function relayDurableState() { - if (!strictVpsRestart) { - throw new Error("strict relay accounting requires VPS Postgres access"); - } - const output = run( - "ssh", - sshArgs( - "sudo", - "-u", - "postgres", - "psql", - "-d", - "clusterflux", - "-At", - "-c", - "SELECT record::text FROM clusterflux_artifact_relay_state WHERE singleton = TRUE" - ) - ).trim(); - assert.notStrictEqual(output, "", "artifact relay durable state was not persisted"); - return JSON.parse(output.split(/\r?\n/).filter(Boolean).at(-1)); -} - -async function waitForHostedControlReady(timeoutMs = 60_000) { - const deadline = Date.now() + timeoutMs; - let lastError; - while (Date.now() < deadline) { - try { - const ping = await sendHostedControl({ type: "ping" }); - if (ping.type === "pong") return ping; - lastError = new Error(JSON.stringify(ping)); - } catch (error) { - lastError = error; - } - await delay(500); - } - throw new Error(`hosted service did not recover: ${lastError}`); -} - -async function publishRelayProbeArtifact({ clusterflux, projectDir, scope, label }) { - const runReport = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - await waitForCli( - `${label} flagship completion`, - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (report) => completedFlagship(rawTaskEvents(report)), - 10 * 60 * 1000 - ); - const artifacts = runJson( - clusterflux, - ["artifact", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ); - const artifact = artifacts.artifacts.find((candidate) => { - const digest = candidate.digest; - return ( - typeof digest === "string" && - /^sha256:[0-9a-f]{64}$/.test(digest) && - candidate.artifact === `release.tar-${digest.slice("sha256:".length)}` - ); - }); - assert(artifact, `${label} did not publish a relay probe artifact`); - return artifact; -} - -async function runRelayEmergencyDisable({ - clusterflux, - clusterfluxNode, - projectDir, - scope, - workerArgs, - sessionSecret, - maxBytes, -}) { - const startedAt = Date.now(); - if (!strictVpsRestart) { - throw new Error("strict relay disable proof requires VPS systemd access"); - } - const dropInDir = `/run/systemd/system/${strictServiceUnit}.d`; - const dropInPath = `${dropInDir}/90-strict-relay-disable.conf`; - run("ssh", sshArgs("sudo", "mkdir", "-p", dropInDir)); - cp.execFileSync("ssh", sshArgs("sudo", "tee", dropInPath), { - cwd: repo, - input: "[Service]\nEnvironment=CLUSTERFLUX_HOSTED_RELAY_DISABLED=true\n", - stdio: ["pipe", "ignore", "inherit"], - }); - let disabled; - let disabledArtifact; - let disabledWorker; - try { - run( - "ssh", - sshArgs( - "sudo", - "systemctl", - "daemon-reload" - ) - ); - run( - "ssh", - sshArgs("sudo", "systemctl", "restart", strictServiceUnit) - ); - await waitForHostedControlReady(); - disabledWorker = spawnJsonLines(clusterfluxNode, workerArgs, { - cwd: projectDir, - env: { ...process.env }, - }); - await disabledWorker.waitFor( - (value) => value.node_status === "ready", - "relay-disabled worker ready" - ); - disabledArtifact = await publishRelayProbeArtifact({ - clusterflux, - projectDir, - scope, - label: "relay-disabled", - }); - disabled = assertDenied( - await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "create_artifact_download_link", - artifact: disabledArtifact.artifact, - max_bytes: maxBytes, - ttl_seconds: 60, - }) - ), - /artifact relay is disabled/i, - "emergency-disabled artifact relay" - ); - } finally { - if (disabledWorker) await stopChild(disabledWorker.child); - run("ssh", sshArgs("sudo", "rm", "-f", dropInPath)); - run("ssh", sshArgs("sudo", "systemctl", "daemon-reload")); - run( - "ssh", - sshArgs("sudo", "systemctl", "restart", strictServiceUnit) - ); - await waitForHostedControlReady(); - } - const restoredWorker = spawnJsonLines(clusterfluxNode, workerArgs, { - cwd: projectDir, - env: { ...process.env }, - }); - try { - await restoredWorker.waitFor( - (value) => value.node_status === "ready", - "relay-restored worker ready" - ); - const restoredArtifact = await publishRelayProbeArtifact({ - clusterflux, - projectDir, - scope, - label: "relay-restored", - }); - const restored = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "create_artifact_download_link", - artifact: restoredArtifact.artifact, - max_bytes: maxBytes, - ttl_seconds: 60, - }) - ); - assert.strictEqual(restored.type, "artifact_download_link", JSON.stringify(restored)); - const revoked = await sendHostedControl( - authenticatedRequest(sessionSecret, { - type: "revoke_artifact_download_link", - artifact: restoredArtifact.artifact, - token_digest: restored.link.scoped_token_digest, - }) - ); - assert.strictEqual(revoked.type, "artifact_download_link_revoked"); - return { - evidence: { - duration_ms: Date.now() - startedAt, - disabled, - disabled_probe_artifact: disabledArtifact.artifact, - restored: restored.type, - restored_probe_artifact: restoredArtifact.artifact, - restored_reservation_released: revoked.type, - runtime_drop_in_removed: true, - }, - worker: restoredWorker, - }; - } catch (error) { - await stopChild(restoredWorker.child); - throw error; - } -} - -function deploymentProvenance() { - if (!strictVpsRestart) return null; - const systemGeneration = run( - "ssh", - sshArgs("readlink", "-f", "/run/current-system") - ).trim(); - const mainPid = run( - "ssh", - sshArgs( - "systemctl", - "show", - strictServiceUnit, - "--property=MainPID", - "--value" - ) - ).trim(); - assert.match(mainPid, /^[1-9][0-9]*$/, "hosted service has no live MainPID"); - const executable = run( - "ssh", - sshArgs("readlink", "-f", `/proc/${mainPid}/exe`) - ).trim(); - const binarySha256 = run( - "ssh", - sshArgs("sha256sum", `/proc/${mainPid}/exe`) - ) - .trim() - .split(/\s+/)[0]; - const fragment = run( - "ssh", - sshArgs("systemctl", "show", strictServiceUnit, "--property=FragmentPath", "--value") - ).trim(); - const serviceUnitSha256 = run( - "ssh", - sshArgs("sha256sum", fragment) - ) - .trim() - .split(/\s+/)[0]; - const renderedServiceConfiguration = run( - "ssh", - sshArgs("systemctl", "cat", strictServiceUnit) - ); - const renderedServiceConfigurationSha256 = sha256( - Buffer.from(renderedServiceConfiguration) - ); - return { - system_generation: systemGeneration, - hosted_service_executable: executable, - hosted_service_sha256: `sha256:${binarySha256}`, - service_unit: fragment, - service_unit_sha256: `sha256:${serviceUnitSha256}`, - service_configuration_sha256: renderedServiceConfigurationSha256, - }; -} - -function configurationProvenance() { - const configRepo = path.resolve( - process.env.CLUSTERFLUX_DEPLOYMENT_CONFIG_REPO || - path.join(repo, "..", "michelpaulissen.com") - ); - const status = run("git", ["status", "--short"], { cwd: configRepo }).trim(); - const revision = run("git", ["rev-parse", "HEAD"], { cwd: configRepo }).trim(); - return { - repository: configRepo, - revision, - evidence_identity: sha256(Buffer.from(revision)), - clean: status === "", - status: status || null, - }; -} - -function proxyConfigurationProvenance() { - if (!strictVpsRestart) return null; - const proxyUnit = process.env.CLUSTERFLUX_STRICT_PROXY_UNIT || "nginx.service"; - const fragment = run( - "ssh", - sshArgs("systemctl", "show", "--property=FragmentPath", "--value", proxyUnit) - ).trim(); - assert(fragment, `proxy service ${proxyUnit} has no FragmentPath`); - const unitSha256 = run( - "ssh", - sshArgs("sha256sum", fragment) - ).trim().split(/\s+/)[0]; - const proxyExecStart = run( - "ssh", - sshArgs("systemctl", "show", "--property=ExecStart", "--value", proxyUnit) - ).trim(); - const nginxExecutable = proxyExecStart.match(/path=([^ ;]+)/)?.[1]; - const nginxConfiguration = proxyExecStart.match(/ argv\[\]=.* -c ([^ ;]+)/)?.[1]; - assert(nginxExecutable, `proxy service ${proxyUnit} has no executable identity`); - assert(nginxConfiguration, `proxy service ${proxyUnit} has no configuration identity`); - const renderedConfiguration = run( - "ssh", - sshArgs(nginxExecutable, "-T", "-c", nginxConfiguration) - ); - const renderedConfigurationIdentity = sha256(Buffer.from(renderedConfiguration)); - const activeState = run( - "ssh", - sshArgs("systemctl", "is-active", proxyUnit) - ).trim(); - assert.strictEqual(activeState, "active", `proxy service ${proxyUnit} is not active`); - return { - proxy_unit: proxyUnit, - proxy_unit_fragment: fragment, - proxy_unit_sha256: `sha256:${unitSha256}`, - proxy_executable: nginxExecutable, - proxy_configuration: nginxConfiguration, - rendered_configuration_sha256: renderedConfigurationIdentity, - evidence_identity: renderedConfigurationIdentity, - active_state: activeState, - }; -} - -async function restartHostedServiceAndResume({ - clusterflux, - clusterfluxNode, - projectDir, - scope, - workerArgs, - workerNode, - credentialPath, - credentialDigest, - scopedCollisionRuntime, -}) { - if (!strictVpsRestart) { - return { - executed: false, - reason: "strict VPS restart access not supplied", - worker: null, - }; - } - const before = deploymentProvenance(); - run("ssh", sshArgs("systemctl", "restart", strictServiceUnit)); - const deadline = Date.now() + 120000; - let ping; - let lastError; - while (Date.now() < deadline) { - try { - ping = await sendHostedControl({ type: "ping" }); - if (ping.type === "pong") break; - } catch (error) { - lastError = error; - } - await delay(500); - } - assert.strictEqual( - ping?.type, - "pong", - `hosted service did not recover after restart: ${lastError?.message || "no pong"}` - ); - const afterFirstRestart = deploymentProvenance(); - assert.strictEqual(afterFirstRestart.system_generation, before.system_generation); - assert.strictEqual( - afterFirstRestart.hosted_service_sha256, - before.hosted_service_sha256 - ); - - const projects = runJson(clusterflux, ["project", "list", ...scope], { - cwd: projectDir, - }); - assert(projects.project_count >= 1, "CLI session/project did not survive restart"); - const ephemeralRun = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(ephemeralRun.status, "main_launched"); - const ephemeralProcess = ephemeralRun.process; - await waitForCli( - "pre-restart ephemeral main to park", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", ephemeralProcess], - { cwd: projectDir } - ), - (status) => status.live_process?.main_wait_state === "waiting_for_node", - 120000 - ); - - run("ssh", sshArgs("systemctl", "restart", strictServiceUnit)); - const secondDeadline = Date.now() + 120000; - ping = undefined; - lastError = undefined; - while (Date.now() < secondDeadline) { - try { - ping = await sendHostedControl({ type: "ping" }); - if (ping.type === "pong") break; - } catch (error) { - lastError = error; - } - await delay(500); - } - assert.strictEqual( - ping?.type, - "pong", - `hosted service did not recover after ephemeral-state restart: ${ - lastError?.message || "no pong" - }` - ); - const after = deploymentProvenance(); - assert.strictEqual(after.system_generation, before.system_generation); - assert.strictEqual(after.hosted_service_sha256, before.hosted_service_sha256); - const oldStatus = runJson( - clusterflux, - ["process", "status", ...scope, "--process", ephemeralProcess], - { cwd: projectDir } - ); - assert.strictEqual(oldStatus.state, "not_active"); - assert.strictEqual(sha256(fs.readFileSync(credentialPath)), credentialDigest); - - const worker = spawnJsonLines(clusterfluxNode, workerArgs, { - cwd: projectDir, - env: { ...process.env }, - }); - const ready = await worker.waitFor( - (value) => value.node_status === "ready", - "persisted worker ready after hosted service restart" - ); - assert.strictEqual(ready.node, workerNode); - assert.strictEqual(sha256(fs.readFileSync(credentialPath)), credentialDigest); - - let scopedNodeCollisionAfterRestart = null; - if (scopedCollisionRuntime) { - assert.strictEqual(scopedCollisionRuntime.node, workerNode); - assert.notStrictEqual( - scopedCollisionRuntime.tenant, - readJson(path.join(projectDir, ".clusterflux", "session.json")).tenant - ); - assert.strictEqual( - sha256(fs.readFileSync(scopedCollisionRuntime.credentialPath)), - scopedCollisionRuntime.credentialDigest - ); - const secondWorker = spawnJsonLines( - clusterfluxNode, - scopedCollisionRuntime.workerArgs, - { - cwd: scopedCollisionRuntime.projectDir, - env: { ...process.env }, - } - ); - try { - const secondReady = await secondWorker.waitFor( - (value) => value.node_status === "ready", - "same-name second-tenant worker ready after hosted service restart" - ); - assert.strictEqual(secondReady.node, workerNode); - const firstStatus = await waitForCli( - "first scoped same-name Node online after restart", - () => - runJson( - clusterflux, - ["node", "status", ...scope, "--node", workerNode], - { cwd: projectDir } - ), - (status) => nodeDescriptor(status, workerNode)?.online === true, - 30_000 - ); - const secondStatus = await waitForCli( - "second scoped same-name Node online after restart", - () => - runJson( - clusterflux, - [ - "node", - "status", - ...scopedCollisionRuntime.scope, - "--node", - workerNode, - ], - { cwd: scopedCollisionRuntime.projectDir } - ), - (status) => nodeDescriptor(status, workerNode)?.online === true, - 30_000 - ); - scopedNodeCollisionAfterRestart = { - node: workerNode, - first_scope_online: - nodeDescriptor(firstStatus, workerNode)?.online === true, - second_scope_online: - nodeDescriptor(secondStatus, workerNode)?.online === true, - both_credentials_reused_without_grants: true, - distinct_credential_digests: - credentialDigest !== scopedCollisionRuntime.credentialDigest, - }; - assert.strictEqual( - scopedNodeCollisionAfterRestart.distinct_credential_digests, - true, - "same-name scoped Nodes unexpectedly reused one credential" - ); - } finally { - await stopChild(secondWorker.child); - } - } - - const restartedRun = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(restartedRun.status, "main_launched"); - const restartedProcess = restartedRun.process; - const completed = await waitForCli( - "new process completion after hosted service restart", - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", restartedProcess], - { cwd: projectDir } - ), - (tasks) => completedFlagship(rawTaskEvents(tasks)), - 5 * 60 * 1000 - ); - const completedEvent = rawTaskEvents(completed).find( - (event) => - event.executor === "coordinator_main" && - event.terminal_state === "completed" - ); - assert(completedEvent, "post-restart flagship omitted its completed main event"); - return { - executed: true, - account_project_session_preserved: true, - node_identity_preserved: true, - old_process_terminated_honestly: true, - terminated_ephemeral_process: ephemeralProcess, - new_process: restartedProcess, - new_process_result: completedEvent.result, - scoped_node_collision_after_restart: scopedNodeCollisionAfterRestart, - before, - after_first_restart: afterFirstRestart, - after, - worker, - }; -} - -async function finishScopedNodeCollisionAfterRestart({ - clusterflux, - projectDir, - scope, - workerNode, - scopedCollisionRuntime, -}) { - const startedAt = Date.now(); - assert(scopedCollisionRuntime, "scoped collision runtime evidence is required"); - const revoked = runJson( - clusterflux, - [ - "node", - "revoke", - ...scopedCollisionRuntime.scope, - "--node", - scopedCollisionRuntime.node, - "--yes", - ], - { cwd: scopedCollisionRuntime.projectDir } - ); - assert.strictEqual(revoked.command, "node revoke"); - const revokedHeartbeat = assertDenied( - await sendHostedControl({ - type: "node_heartbeat", - tenant: scopedCollisionRuntime.tenant, - project: scopedCollisionRuntime.project, - node: scopedCollisionRuntime.node, - node_signature: signedNodeHeartbeat( - scopedCollisionRuntime.tenant, - scopedCollisionRuntime.project, - scopedCollisionRuntime.node, - scopedCollisionRuntime.identity, - { - nonce: `strict-scoped-node-revoked-${Date.now()}`, - } - ), - }), - /not enrolled|unknown node|revoked|credential/i, - "revoked second scoped Node" - ); - const firstStatus = await waitForCli( - "first same-name Node remains live after scoped revocation", - () => - runJson( - clusterflux, - ["node", "status", ...scope, "--node", workerNode], - { cwd: projectDir } - ), - (status) => nodeDescriptor(status, workerNode)?.online === true, - 30_000 - ); - return { - request: { - revoked_scope: { - tenant: scopedCollisionRuntime.tenant, - project: scopedCollisionRuntime.project, - node: scopedCollisionRuntime.node, - }, - retained_node: workerNode, - }, - expected: - "revocation affects only the selected scoped Node after both same-name credentials survive restart", - observed: { - revoked_command: revoked.command, - revoked_credential_denied: revokedHeartbeat.denied, - first_scope_node_online: - nodeDescriptor(firstStatus, workerNode)?.online === true, - }, - duration_ms: Math.max(1, Date.now() - startedAt), - }; -} - -async function finishUserCredentialSecurity({ - clusterflux, - projectDir, - scope, - sessionSecret, -}) { - const startedAt = Date.now(); - const forged = assertDenied( - await sendHostedControl( - authenticatedRequest( - `forged-session-${crypto.randomBytes(24).toString("hex")}`, - { type: "list_projects" } - ) - ), - /not recognized|invalid|authentication|session/i, - "forged user session" - ); - - let expired = null; - const expiredFile = process.env.CLUSTERFLUX_EXPIRED_USER_SESSION_FILE; - if (expiredFile) { - const oldSession = readJson(path.resolve(expiredFile)); - assert(oldSession.session_secret, "expired session evidence omitted its secret"); - expired = assertDenied( - await sendHostedControl( - authenticatedRequest(oldSession.session_secret, { type: "list_projects" }) - ), - /expired|not recognized/i, - "expired user session" - ); - } else if (strictFullRelease) { - throw new Error( - "strict full release requires CLUSTERFLUX_EXPIRED_USER_SESSION_FILE for a genuinely expired hosted session" - ); - } - - const logout = runJson(clusterflux, ["logout", ...scope, "--yes"], { - cwd: projectDir, - }); - assert.strictEqual(logout.server_session_revocation.revoked, true); - const revoked = assertDenied( - await sendHostedControl( - authenticatedRequest(sessionSecret, { type: "list_projects" }) - ), - /revoked|not recognized/i, - "revoked user session" - ); - return { - forged, - expired, - revoked, - duration_ms: Date.now() - startedAt, - }; -} - -async function dapVariables(client, variablesReference) { - const request = client.send("variables", { variablesReference }); - return (await client.response(request, "variables")).body.variables; -} - -async function runSameDefinitionDapIdentity({ - clusterfluxDap, - clusterflux, - projectDir, - scope, -}) { - const scenarioStartedAt = Date.now(); - const baselineContainers = new Set( - run("podman", ["ps", "-q"]) - .trim() - .split(/\s+/) - .filter(Boolean) - ); - const client = new DapClient({ - cwd: projectDir, - command: clusterfluxDap, - args: [], - env: { - ...process.env, - CLUSTERFLUX_TEST_DAP_OBSERVER_CONNECTION_LOSS: "1", - CLUSTERFLUX_TEST_DAP_POST_COMMIT_OBSERVATION_FAILURE: "1", - }, - }); - let disconnected = false; - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await client.response(initialize, "initialize"); - const launch = client.send("launch", { - entry: "identity", - project: projectDir, - runtimeBackend: "live-services", - coordinatorEndpoint: serviceEndpoint, - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - const configurationDone = client.send("configurationDone"); - await client.response(configurationDone, "configurationDone"); - - const mainThreadDeadline = Date.now() + 5 * 60 * 1000; - let mainThread; - while (Date.now() < mainThreadDeadline) { - const threadsRequest = client.send("threads"); - const threads = (await client.response(threadsRequest, "threads")).body - .threads; - mainThread = threads.find((thread) => /coordinator main/i.test(thread.name)); - if (mainThread) break; - await delay(100); - } - assert(mainThread, "identity entry did not report its coordinator main"); - const launchWithoutBreakpointMs = Date.now() - scenarioStartedAt; - const postCommitDiagnostics = [ - "initial task observation failed after main_launched", - "initial process observation failed after main_launched", - ].map((expected) => { - const message = client.messages.find( - (candidate) => - candidate.type === "event" && - candidate.event === "output" && - String(candidate.body?.output || "").includes(expected) - ); - assert(message, `post-commit launch evidence omitted: ${expected}`); - return String(message.body.output).trim(); - }); - const prematurePostCommitEvents = client.messages.filter( - (message) => - message.type === "event" && - ["stopped", "terminated"].includes(message.event) - ); - assert.deepStrictEqual(prematurePostCommitEvents, []); - const processRequest = client.send("evaluate", { - expression: "virtual_process_id", - context: "watch", - }); - const processId = (await client.response(processRequest, "evaluate")).body - .result; - const identityContainerDeadline = Date.now() + 2 * 60 * 1000; - let identityContainerIds = new Set(); - let maximumNewContainerCount = 0; - let lastPodmanStates = []; - while (Date.now() < identityContainerDeadline) { - const containers = runJson("podman", ["ps", "--format", "json"]); - lastPodmanStates = containers; - identityContainerIds = new Set( - containers - .map((container) => container.Id || container.ID || container.IdHex || "") - .filter((id) => id && !baselineContainers.has(id)) - ); - maximumNewContainerCount = Math.max( - maximumNewContainerCount, - identityContainerIds.size - ); - if (identityContainerIds.size >= 2) break; - await delay(100); - } - const identityTaskSnapshot = - identityContainerIds.size >= 2 - ? null - : runJson( - clusterflux, - ["task", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert( - identityContainerIds.size >= 2, - `identity entry did not start two same-definition Podman containers; max=${maximumNewContainerCount} tasks=${JSON.stringify( - identityTaskSnapshot - )} podman=${JSON.stringify(lastPodmanStates)}` - ); - - const pause = client.send("pause", { threadId: mainThread.id }); - await client.response(pause, "pause"); - const paused = await client.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "pause", - 30_000 - ); - assert.strictEqual(typeof paused.body.allThreadsStopped, "boolean"); - - const podmanStates = runJson("podman", ["ps", "--all", "--format", "json"]); - const clusterfluxPausedContainers = podmanStates.filter((container) => { - const id = container.Id || container.ID || container.IdHex || ""; - const state = String(container.State || container.Status || "").toLowerCase(); - return identityContainerIds.has(id) && state.includes("paused"); - }); - assert( - clusterfluxPausedContainers.length >= 2, - `expected two newly paused Clusterflux containers: ${JSON.stringify( - podmanStates - )}` - ); - - const threadsRequest = client.send("threads"); - const threads = (await client.response(threadsRequest, "threads")).body - .threads; - const identityThreads = threads.filter((thread) => - /identity probe/i.test(thread.name) - ); - assert.strictEqual( - identityThreads.length, - 2, - `expected two same-definition DAP threads: ${JSON.stringify(threads)}` - ); - assert.notStrictEqual(identityThreads[0].id, identityThreads[1].id); - - const threadEvidence = []; - for (const threadRecord of identityThreads) { - const stackRequest = client.send("stackTrace", { - threadId: threadRecord.id, - startFrame: 0, - levels: 1, - }); - const frames = (await client.response(stackRequest, "stackTrace")).body - .stackFrames; - assert.strictEqual(frames.length, 1); - const scopesRequest = client.send("scopes", { frameId: frames[0].id }); - const scopes = (await client.response(scopesRequest, "scopes")).body.scopes; - const argsScope = scopes.find( - (scopeRecord) => scopeRecord.name === "Task Args and Handles" - ); - const runtimeScope = scopes.find( - (scopeRecord) => scopeRecord.name === "Clusterflux Runtime" - ); - assert(argsScope && runtimeScope); - const args = await dapVariables(client, argsScope.variablesReference); - const runtime = await dapVariables(client, runtimeScope.variablesReference); - const runtimeValue = (name) => - runtime.find((variable) => variable.name === name)?.value; - assert.strictEqual(runtimeValue("state"), "Frozen"); - threadEvidence.push({ - thread_id: threadRecord.id, - task_instance: runtimeValue("virtual_thread"), - attempt_id: runtimeValue("task_attempt_id"), - arguments: args.map((variable) => ({ - name: variable.name, - value: variable.value, - })), - }); - } - assert.notStrictEqual( - threadEvidence[0].task_instance, - threadEvidence[1].task_instance - ); - assert.notStrictEqual(threadEvidence[0].attempt_id, threadEvidence[1].attempt_id); - const argumentText = threadEvidence - .flatMap((record) => record.arguments.map((argument) => argument.value)) - .join(" "); - assert.match(argumentText, /slow-first/); - assert.match(argumentText, /fast-second/); - - const continued = client.send("continue", { - threadId: paused.body.threadId, - }); - await client.response(continued, "continue"); - await client.waitFor( - (message) => message.type === "event" && message.event === "terminated", - 5 * 60 * 1000 - ); - - const taskList = runJson( - clusterflux, - ["task", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - const identityEvents = rawTaskEvents(taskList).filter( - (event) => - event.task_definition === "identity_probe" && - event.terminal_state === "completed" - ); - assert.strictEqual(identityEvents.length, 2, JSON.stringify(identityEvents)); - assert.notStrictEqual(identityEvents[0].task, identityEvents[1].task); - assert.notStrictEqual(identityEvents[0].attempt_id, identityEvents[1].attempt_id); - assert.match(JSON.stringify(identityEvents[0].result), /fast-second/); - assert.match(JSON.stringify(identityEvents[1].result), /slow-first/); - - const released = await waitForCli( - "same-definition identity process release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - await client.close(); - disconnected = true; - return { - duration_ms: Date.now() - scenarioStartedAt, - process: processId, - launch_without_breakpoint: { - request: { - entry: "identity", - runtime_backend: "live-services", - configured_breakpoints: [], - }, - expected: "launch commits and reports a real coordinator-main thread", - observed: { - thread_id: mainThread.id, - thread_name: mainThread.name, - }, - duration_ms: launchWithoutBreakpointMs, - }, - post_main_launched_observation_recovery: { - request: { - entry: "identity", - fault_injections: [ - "initial task snapshot observation failure", - "initial process-status observation failure", - ], - }, - expected: - "main_launched is committed, no rollback or false stop occurs, and the observer reconnects until threads appear", - observed: { - diagnostics: postCommitDiagnostics, - main_thread: mainThread, - premature_stop_or_termination_events: - prematurePostCommitEvents.length, - }, - duration_ms: launchWithoutBreakpointMs, - }, - same_definition_identity: { - expected: - "two concurrent instances retain distinct thread, argument, attempt, output, freeze, and terminal identities", - observed: { - thread_evidence: threadEvidence, - completion_order: identityEvents.map((event) => ({ - task_instance: event.task, - attempt_id: event.attempt_id, - result: event.result, - })), - paused_container_count: clusterfluxPausedContainers.length, - terminal_state: released.state, - }, - duration_ms: Date.now() - scenarioStartedAt, - }, - thread_evidence: threadEvidence, - completion_order: identityEvents.map((event) => ({ - task_instance: event.task, - attempt_id: event.attempt_id, - result: event.result, - })), - podman_paused_container_ids: clusterfluxPausedContainers.map( - (container) => container.Id || container.ID || container.IdHex - ), - dap_all_threads_stopped: paused.body.allThreadsStopped, - terminal_state: released.state, - }; - } finally { - if (!disconnected) { - await client.close().catch(() => { - if (client.child.exitCode === null) client.child.kill("SIGKILL"); - }); - } - } -} - -async function runLiveDapEditRestart({ - clusterfluxDap, - clusterflux, - projectDir, - scope, - worker, -}) { - const scenarioStartedAt = Date.now(); - const sourcePath = fs.realpathSync(path.join(projectDir, "src/lib.rs")); - const originalSource = fs.readFileSync(sourcePath, "utf8"); - const sourceLines = originalSource.split(/\r?\n/); - const lineFor = (needle) => { - const line = sourceLines.findIndex((candidate) => candidate.includes(needle)) + 1; - assert(line > 0, `flagship source omitted ${needle}`); - return line; - }; - const mainLine = lineFor("pub async fn restart_main()"); - const taskLine = lineFor("fn task_trap("); - const client = new DapClient({ - cwd: projectDir, - command: clusterfluxDap, - args: [], - env: { - ...process.env, - CLUSTERFLUX_TEST_DAP_OBSERVER_CONNECTION_LOSS: "1", - CLUSTERFLUX_TEST_DAP_OBSERVER_SNAPSHOT_FAILURE: "1", - CLUSTERFLUX_TEST_DAP_OBSERVER_PROCESS_STATUS_FAILURE: "1", - CLUSTERFLUX_TEST_DAP_OBSERVER_FALLBACK_FAILURE: "1", - CLUSTERFLUX_TEST_DAP_OBSERVER_DEBUG_EPOCH_WAIT_FAILURE: "1", - CLUSTERFLUX_TEST_DAP_BREAKPOINT_DELAY_REVISION: "1", - CLUSTERFLUX_TEST_DAP_BREAKPOINT_DELAY_MS: "750", - CLUSTERFLUX_TEST_DAP_BREAKPOINT_INSTALLATION_FAILURE_REVISION: "3", - }, - }); - let sourceRestored = false; - let disconnected = false; - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await client.response(initialize, "initialize"); - - const launch = client.send("launch", { - entry: "restart", - project: projectDir, - runtimeBackend: "live-services", - coordinatorEndpoint: serviceEndpoint, - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const configurationStartedAt = Date.now(); - const configurationDone = client.send("configurationDone"); - const configurationResponse = await client.response( - configurationDone, - "configurationDone" - ); - const configurationResponseMs = Date.now() - configurationStartedAt; - assert( - configurationResponseMs < 2_000, - `configurationDone blocked for ${configurationResponseMs} ms` - ); - - const threadDeadline = Date.now() + 5 * 60 * 1000; - let runningThreads = []; - let threadObservationResponse; - while (Date.now() < threadDeadline) { - const threadsRequest = client.send("threads"); - threadObservationResponse = await client.response(threadsRequest, "threads"); - runningThreads = threadObservationResponse.body.threads; - if (runningThreads.length > 0) break; - await delay(100); - } - assert(runningThreads.length > 0, "asynchronous live DAP launch reported no threads"); - const initialObserverFaults = []; - for (const expected of [ - { - fault: "task snapshot read transport failure", - diagnostic: "runtime snapshot observation failed", - }, - { - fault: "process-status read transport failure", - diagnostic: "runtime process observation failed", - }, - { - fault: "breakpoint inspection and fallback event transport failures", - diagnostic: "runtime breakpoint and fallback event observation failed", - }, - ]) { - const message = await client.waitFor( - (candidate) => - candidate.seq > configurationResponse.seq && - candidate.type === "event" && - candidate.event === "output" && - String(candidate.body?.output || "").includes(expected.diagnostic), - 120_000 - ); - initialObserverFaults.push({ - ...expected, - expected: "reconnect and eventually report live threads without a stop", - observed: String(message.body.output).trim(), - }); - } - const recoveredThreadsRequest = client.send("threads"); - const recoveredThreadsResponse = await client.response( - recoveredThreadsRequest, - "threads" - ); - assert( - recoveredThreadsResponse.body.threads.length > 0, - "observer faults removed threads after recovery" - ); - const prematureLaunchEvents = client.messages.filter( - (message) => - message.seq > configurationResponse.seq && - message.seq < recoveredThreadsResponse.seq && - message.type === "event" && - ["stopped", "terminated"].includes(message.event) - ); - assert.deepStrictEqual( - prematureLaunchEvents, - [], - "post-launch observer recovery fabricated a stop or terminated the launch" - ); - const postLaunchObservationRecoveryMs = - Date.now() - configurationStartedAt; - const pauseStartedAt = Date.now(); - const pause = client.send("pause", { threadId: runningThreads[0].id }); - await client.response(pause, "pause"); - const pauseResponseMs = Date.now() - pauseStartedAt; - assert(pauseResponseMs < 2_000, `pause blocked for ${pauseResponseMs} ms`); - const mainStop = await client.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "pause" - ); - assert.strictEqual(mainStop.body.allThreadsStopped, true); - - const inspectStartedAt = Date.now(); - const commandStatus = client.send("evaluate", { - expression: "command_status", - context: "watch", - }); - const inspected = await client.response(commandStatus, "evaluate"); - const inspectionResponseMs = Date.now() - inspectStartedAt; - assert( - inspectionResponseMs < 2_000, - `inspection blocked for ${inspectionResponseMs} ms` - ); - assert.match(inspected.body.result, /debug epoch|frozen/i); - - const breakpointStartedAt = Date.now(); - const staleRevisionRequest = client.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: mainLine }], - }); - const newestRevisionRequest = client.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: taskLine }], - }); - const staleRevisionResponse = await client.response( - staleRevisionRequest, - "setBreakpoints" - ); - const newestRevisionResponse = await client.response( - newestRevisionRequest, - "setBreakpoints" - ); - const breakpointResponseMs = Date.now() - breakpointStartedAt; - assert( - breakpointResponseMs < 2_000, - `setBreakpoints blocked for ${breakpointResponseMs} ms` - ); - assert.deepStrictEqual( - staleRevisionResponse.body.breakpoints.map( - (breakpoint) => breakpoint.verified - ), - [false] - ); - assert.deepStrictEqual( - newestRevisionResponse.body.breakpoints.map( - (breakpoint) => breakpoint.verified - ), - [false] - ); - assert.deepStrictEqual( - newestRevisionResponse.body.breakpoints.map( - (breakpoint) => breakpoint.message - ), - ["Pending coordinator breakpoint installation"] - ); - const newestRevisionInstalled = await client.waitFor( - (message) => - message.seq > newestRevisionResponse.seq && - message.type === "event" && - message.event === "breakpoint" && - message.body.reason === "changed" && - message.body.breakpoint?.verified === true && - message.body.breakpoint?.line === taskLine, - 30_000 - ); - await delay(1_000); - const staleRevisionEvents = client.messages.filter( - (message) => - message.seq > newestRevisionResponse.seq && - message.type === "event" && - message.event === "breakpoint" && - message.body.reason === "changed" && - message.body.breakpoint?.line === mainLine - ); - assert.deepStrictEqual( - staleRevisionEvents, - [], - "stale breakpoint revision completion overwrote the newest set" - ); - - const rejectedRevisionRequest = client.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: taskLine }], - }); - const rejectedRevisionResponse = await client.response( - rejectedRevisionRequest, - "setBreakpoints" - ); - const rejectedBreakpoint = await client.waitFor( - (message) => - message.seq > rejectedRevisionResponse.seq && - message.type === "event" && - message.event === "breakpoint" && - message.body.reason === "changed" && - message.body.breakpoint?.verified === false && - message.body.breakpoint?.line === taskLine && - /coordinator breakpoint installation failed/i.test( - message.body.breakpoint?.message || "" - ), - 30_000 - ); - assert.strictEqual( - rejectedBreakpoint.body.breakpoint.id, - rejectedRevisionResponse.body.breakpoints[0].id - ); - const retryBreakpoints = client.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: taskLine }], - }); - const retryBreakpointResponse = await client.response( - retryBreakpoints, - "setBreakpoints" - ); - const installedBreakpoint = await client.waitFor( - (message) => - message.seq > retryBreakpointResponse.seq && - message.type === "event" && - message.event === "breakpoint" && - message.body.reason === "changed" && - message.body.breakpoint?.verified === true && - message.body.breakpoint?.line === taskLine, - 30_000 - ); - assert.strictEqual( - installedBreakpoint.body.breakpoint.id, - retryBreakpointResponse.body.breakpoints[0].id - ); - const breakpointInstallationMs = Date.now() - breakpointStartedAt; - - const continueStartedAt = Date.now(); - const mainContinue = client.send("continue", { - threadId: mainStop.body.threadId, - }); - const mainContinueResponse = await client.response(mainContinue, "continue"); - const continueResponseMs = Date.now() - continueStartedAt; - assert( - continueResponseMs < 2_000, - `continue blocked for ${continueResponseMs} ms` - ); - const taskStop = await client.waitFor( - (message) => - message.seq > mainStop.seq && - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint" - ); - const realBreakpointMs = Date.now() - breakpointStartedAt; - assert.strictEqual(taskStop.body.allThreadsStopped, true); - const observerReconnect = await client.waitFor( - (message) => - message.seq > mainContinueResponse.seq && - message.type === "event" && - message.event === "output" && - String(message.body?.output || "").includes( - "injected one transient connection loss" - ), - 30_000 - ); - assert( - observerReconnect.seq < taskStop.seq, - "observer reconnection must complete before the real breakpoint stop" - ); - assert.strictEqual( - client.messages.filter( - (message) => - message.seq > mainStop.seq && - message.seq < taskStop.seq && - message.type === "event" && - message.event === "stopped" - ).length, - 0, - "observer reconnection fabricated a stopped target before the real breakpoint" - ); - assert.notStrictEqual(taskStop.body.threadId, mainStop.body.threadId); - const reconnectDiagnostics = [ - "runtime observer injected one transient connection loss", - "runtime snapshot observation failed", - "runtime process observation failed", - "runtime breakpoint and fallback event observation failed", - "runtime Debug Epoch observation failed", - ].map((diagnostic) => { - const message = client.messages.find( - (candidate) => - candidate.seq > mainContinueResponse.seq && - candidate.seq < taskStop.seq && - candidate.type === "event" && - candidate.event === "output" && - String(candidate.body?.output || "").includes(diagnostic) - ); - assert( - message, - `observer reconnection evidence omitted diagnostic: ${diagnostic}` - ); - return String(message.body.output).trim(); - }); - - const stackTrace = client.send("stackTrace", { - threadId: taskStop.body.threadId, - startFrame: 0, - levels: 1, - }); - const taskFrames = (await client.response(stackTrace, "stackTrace")).body - .stackFrames; - assert.strictEqual(taskFrames[0].line, taskLine); - - const scopesRequest = client.send("scopes", { frameId: taskFrames[0].id }); - const scopes = (await client.response(scopesRequest, "scopes")).body.scopes; - const argsScope = scopes.find( - (candidate) => candidate.name === "Task Args and Handles" - ); - const runtimeScope = scopes.find( - (candidate) => candidate.name === "Clusterflux Runtime" - ); - assert(argsScope && runtimeScope); - const taskArgs = await dapVariables(client, argsScope.variablesReference); - assert( - taskArgs.some( - (variable) => - variable.name === "arg_0" && String(variable.value).includes("0") - ) - ); - const runtime = await dapVariables(client, runtimeScope.variablesReference); - assert( - runtime.some( - (variable) => - variable.name === "runtime_backend" && variable.value === "LiveServices" - ) - ); - assert( - runtime.some( - (variable) => variable.name === "state" && variable.value === "Frozen" - ) - ); - const dapProcess = runtime.find( - (variable) => variable.name === "virtual_process_id" - )?.value; - assert.match(dapProcess || "", /^vp-[0-9a-f]{12}$/); - - const taskContinue = client.send("continue", { threadId: taskStop.body.threadId }); - await client.response(taskContinue, "continue"); - const failedStop = await client.waitFor( - (message) => - message.seq > taskStop.seq && - message.type === "event" && - message.event === "stopped" && - message.body.reason === "exception", - 5 * 60 * 1000 - ); - assert.strictEqual(failedStop.body.allThreadsStopped, false); - - const beforeEdit = runJson( - clusterflux, - ["task", "list", ...scope, "--process", dapProcess], - { cwd: projectDir } - ); - const originalTaskEvent = rawTaskEvents(beforeEdit).find( - (event) => - event.task_definition === "task_trap" && - event.terminal_state === "failed" - ); - assert(originalTaskEvent, "DAP restart entry omitted its original child event"); - assert(originalTaskEvent.attempt_id, "failed attempt omitted its identity"); - - const originalTaskBody = `pub extern "C" fn task_trap(_input: i32) -> i32 { - #[cfg(target_arch = "wasm32")] - core::arch::wasm32::unreachable(); - #[cfg(not(target_arch = "wasm32"))] - panic!("intentional task trap") -}`; - const replacementTaskBody = `pub extern "C" fn task_trap(_input: i32) -> i32 { - _input + 42 // strict hosted compatible restart probe -}`; - const editedSource = originalSource.replace(originalTaskBody, replacementTaskBody); - assert.notStrictEqual(editedSource, originalSource); - fs.writeFileSync(sourcePath, editedSource); - - const restartFrame = client.send("restartFrame", { - frameId: taskFrames[0].id, - }); - const restartResponse = await client.response(restartFrame, "restartFrame"); - const restartedStop = await client.waitFor( - (message) => - message.seq > restartResponse.seq && - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint" - ); - assert.strictEqual(restartedStop.body.allThreadsStopped, true); - const restartedContinue = client.send("continue", { - threadId: restartedStop.body.threadId, - }); - await client.response(restartedContinue, "continue"); - const restartedNodeReport = await worker.waitFor( - (value) => - value.node_status === "completed" && - value.virtual_thread === originalTaskEvent.task && - value.task_assignment_response?.task_spec?.task_definition === - "task_trap", - "edited task to execute on the live restarted node", - 5 * 60 * 1000 - ); - assert.strictEqual( - restartedNodeReport.node_status, - "completed", - `edited task restart failed on the live node: ${JSON.stringify(restartedNodeReport)}` - ); - assert.match(restartedNodeReport.stdout_tail, /"SmallJson":42/); - const restartedTask = restartedNodeReport.virtual_thread; - - const afterEdit = await waitForCli( - "edited live task event", - () => - runJson(clusterflux, ["task", "list", ...scope, "--process", dapProcess], { - cwd: projectDir, - }), - (tasks) => - rawTaskEvents(tasks).some( - (event) => - event.task === restartedTask && - event.terminal_state === "completed" && - JSON.stringify(event.result) === JSON.stringify({ SmallJson: 42 }) - ), - 5 * 60 * 1000 - ); - const restartedEvent = rawTaskEvents(afterEdit).find( - (event) => - event.task === restartedTask && - event.terminal_state === "completed" && - JSON.stringify(event.result) === JSON.stringify({ SmallJson: 42 }) - ); - assert(restartedEvent, "replacement attempt omitted its completed event"); - assert(restartedEvent.attempt_id, "replacement attempt omitted its identity"); - assert.notStrictEqual(restartedEvent.attempt_id, originalTaskEvent.attempt_id); - await client.waitFor( - (message) => message.type === "event" && message.event === "terminated", - 5 * 60 * 1000 - ); - const disconnectStartedAt = Date.now(); - await client.close(); - disconnected = true; - const disconnectResponseMs = Date.now() - disconnectStartedAt; - assert( - disconnectResponseMs < 2_000, - `disconnect blocked for ${disconnectResponseMs} ms` - ); - fs.writeFileSync(sourcePath, originalSource); - sourceRestored = true; - - return { - duration_ms: Date.now() - scenarioStartedAt, - process: dapProcess, - main_source_line: mainLine, - task_breakpoint_line: taskLine, - launch_started_without_breakpoint: true, - configuration_response_ms: configurationResponseMs, - pause_response_ms: pauseResponseMs, - inspection_response_ms: inspectionResponseMs, - breakpoint_response_ms: breakpointResponseMs, - breakpoint_installation_ms: breakpointInstallationMs, - continue_response_ms: continueResponseMs, - disconnect_response_ms: disconnectResponseMs, - pause_all_threads_stopped: mainStop.body.allThreadsStopped, - task_all_threads_stopped: taskStop.body.allThreadsStopped, - original_task_instance: originalTaskEvent.task, - original_attempt: originalTaskEvent.attempt_id, - restarted_task_instance: restartedTask, - restarted_attempt: restartedEvent.attempt_id, - restarted_result: restartedEvent.result, - compatible_source_edit: "task_trap: trap -> input + 42", - original_arguments_preserved: true, - clean_vfs_boundary_used: true, - breakpoint_install_failure_reported: true, - real_breakpoint: { - request: { - source: sourcePath, - line: taskLine, - runtime_backend: "live-services", - }, - expected: - "coordinator installation is verified before a real all-stop breakpoint event", - observed: { - installed_line: installedBreakpoint.body.breakpoint.line, - stop_reason: taskStop.body.reason, - stopped_line: taskFrames[0].line, - all_threads_stopped: taskStop.body.allThreadsStopped, - }, - duration_ms: Math.max(1, realBreakpointMs), - }, - debug_interaction: { - request: "Pause, inspect command_status, Continue, and Disconnect", - expected: "each control remains responsive during observer recovery", - observed: { - pause_response_ms: pauseResponseMs, - inspect_response_ms: inspectionResponseMs, - continue_response_ms: continueResponseMs, - disconnect_response_ms: disconnectResponseMs, - pause_stop_reason: mainStop.body.reason, - }, - duration_ms: Math.max( - 1, - pauseResponseMs + - inspectionResponseMs + - continueResponseMs + - disconnectResponseMs - ), - }, - post_launch_observation_recovery: { - fault_injections: initialObserverFaults, - expected: - "main_launched remains committed; reconnect; threads appear; no rollback or fabricated stop", - observed: { - threads: runningThreads, - premature_stop_or_termination_events: prematureLaunchEvents.length, - terminal_state: "completed after replacement attempt", - }, - duration_ms: postLaunchObservationRecoveryMs, - }, - observer_reconnection: { - fault_injections: reconnectDiagnostics, - expected: - "all recoverable reads reconnect before the real breakpoint stop", - observed: { - real_stop_reason: taskStop.body.reason, - false_stops_before_real_stop: 0, - }, - duration_ms: Date.now() - continueStartedAt, - }, - breakpoint_revisions: { - expected: "revision 2 remains authoritative after delayed revision 1", - delayed_revision: 1, - authoritative_revision: 2, - authoritative_line: newestRevisionInstalled.body.breakpoint.line, - stale_completion_events: staleRevisionEvents.length, - failure_revision: 3, - recovery_revision: 4, - observed: "newest revision verified; stale completion ignored", - duration_ms: breakpointInstallationMs, - }, - observer_idle_request_rate_bound_per_second: 0.8, - observer_reconnected_without_false_stop: true, - observer_fallback_reconnected: true, - observer_debug_epoch_wait_reconnected: true, - }; - } finally { - if (!sourceRestored) fs.writeFileSync(sourcePath, originalSource); - if (!disconnected) { - await client.close().catch(() => { - if (client.child.exitCode === null) client.child.kill("SIGKILL"); - }); - } - } -} - -function copyProjectControlState(sourceRoot, targetRoot) { - const source = path.join(sourceRoot, ".clusterflux"); - const target = path.join(targetRoot, ".clusterflux"); - ensureDir(target); - for (const file of ["session.json", "project.json"]) { - const from = path.join(source, file); - assert(fs.existsSync(from), `missing shared project control state ${from}`); - fs.copyFileSync(from, path.join(target, file)); - } - fs.chmodSync(path.join(target, "session.json"), 0o600); - const sourceNodes = path.join(source, "nodes"); - assert(fs.existsSync(sourceNodes), "persisted node credential directory is missing"); - fs.cpSync(sourceNodes, path.join(target, "nodes"), { - recursive: true, - force: true, - }); -} - -async function runHostedHelloBuild({ - clusterflux, - projectDir, - scope, - outputFile, -}) { - const startedAt = Date.now(); - const runReport = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.status, "main_launched"); - const tasks = await waitForCli( - "hosted hello-build completion", - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (report) => { - const events = rawTaskEvents(report); - return events.some( - (event) => - event.task_definition === "compile" && - event.terminal_state === "completed" - ); - }, - 10 * 60 * 1000 - ); - const events = rawTaskEvents(tasks); - assert( - events.some( - (event) => - event.task_definition === "snapshot_current_project" && - event.terminal_state === "completed" - ) - ); - const released = await waitForCli( - "hosted hello-build process release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", runReport.process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - const artifacts = runJson( - clusterflux, - ["artifact", "list", ...scope, "--process", runReport.process], - { cwd: projectDir } - ); - const artifact = artifacts.artifacts.find( - (candidate) => - typeof candidate.digest === "string" && - /^sha256:[0-9a-f]{64}$/.test(candidate.digest) && - candidate.artifact.startsWith("hello-clusterflux-") - ); - assert(artifact, "hello-build did not retain its executable artifact"); - await waitForCli( - "hosted hello-build retaining node online", - () => runJson(clusterflux, ["node", "list", ...scope], { cwd: projectDir }), - (report) => - report.response?.descriptors?.some( - (descriptor) => - descriptor.online === true && - descriptor.artifact_locations?.includes(artifact.artifact) - ), - 120_000 - ); - const download = runJson( - clusterflux, - [ - "artifact", - "download", - ...scope, - artifact.artifact, - "--to", - outputFile, - ], - { cwd: projectDir } - ); - assert.strictEqual(download.local_download.verified_digest, artifact.digest); - assert.strictEqual(sha256(fs.readFileSync(outputFile)), artifact.digest); - fs.chmodSync(outputFile, 0o755); - const output = run(outputFile, []).trim(); - assert.strictEqual(output, "hello from a real Clusterflux build"); - return { - duration_ms: Date.now() - startedAt, - process: runReport.process, - terminal_state: released.state, - artifact: artifact.artifact, - digest: artifact.digest, - downloaded_bytes: download.local_download.bytes_written, - downloaded_sha256: sha256(fs.readFileSync(outputFile)), - executable_output: output, - }; -} - -async function runHostedRecoveryBuild({ - clusterfluxDap, - clusterflux, - projectDir, - scope, -}) { - const startedAt = Date.now(); - const sourcePath = fs.realpathSync(path.join(projectDir, "src/lib.rs")); - const original = fs.readFileSync(sourcePath, "utf8"); - const failing = '"exit 23".to_owned()'; - const replacement = - '"printf \'recovered\\n\' > /clusterflux/output/recovering.txt".to_owned()'; - assert(original.includes(failing)); - const client = new DapClient({ - cwd: projectDir, - command: clusterfluxDap, - env: { ...process.env, CLUSTERFLUX_DAP_TIMEOUT_MS: "120000" }, - }); - let restored = false; - let closed = false; - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await client.response(initialize, "initialize"); - const launch = client.send("launch", { - entry: "build", - project: projectDir, - runtimeBackend: "live-services", - coordinatorEndpoint: serviceEndpoint, - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - const configured = client.send("configurationDone"); - await client.response(configured, "configurationDone"); - const failedStop = await client.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "exception", - 10 * 60 * 1000 - ); - assert.strictEqual(failedStop.body.allThreadsStopped, false); - const threadRequest = client.send("threads"); - const threads = (await client.response(threadRequest, "threads")).body.threads; - const recoveringThread = threads.find((thread) => /build lane/.test(thread.name)); - assert(recoveringThread, "recovery-build failed lane is not visible in DAP"); - const processId = threads - .map((thread) => /vp-[0-9a-f]{12}/.exec(thread.name)?.[0]) - .find(Boolean); - assert(processId, "recovery-build DAP threads omitted the process identity"); - const before = runJson( - clusterflux, - ["task", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - const beforeEvents = rawTaskEvents(before); - const originalFailure = beforeEvents.find( - (event) => - event.task_definition === "build_lane" && - event.terminal_state === "failed" - ); - assert(originalFailure?.attempt_id); - assert( - beforeEvents.some( - (event) => - event.task_definition === "build_lane" && - event.task !== originalFailure.task && - event.terminal_state === "completed" - ) - ); - const waiting = runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert.strictEqual(waiting.live_process.main_state, "running"); - fs.writeFileSync(sourcePath, original.replace(failing, replacement)); - const restart = client.send("restartFrame", { - threadId: recoveringThread.id, - }); - await client.response(restart, "restartFrame"); - await client.waitFor( - (message) => message.type === "event" && message.event === "terminated", - 10 * 60 * 1000 - ); - assert( - client.messages.some( - (message) => - message.type === "event" && - message.event === "thread" && - message.body.reason === "exited" && - message.body.threadId === recoveringThread.id - ) - ); - const after = await waitForCli( - "hosted recovery replacement event", - () => - runJson( - clusterflux, - ["task", "list", ...scope, "--process", processId], - { cwd: projectDir } - ), - (report) => - rawTaskEvents(report).some( - (event) => - event.task === originalFailure.task && - event.terminal_state === "completed" - ), - 120_000 - ); - const replacementEvent = rawTaskEvents(after).find( - (event) => - event.task === originalFailure.task && - event.terminal_state === "completed" - ); - assert(replacementEvent?.attempt_id); - assert.notStrictEqual(replacementEvent.attempt_id, originalFailure.attempt_id); - assert( - rawTaskEvents(after).some( - (event) => - event.executor === "coordinator_main" && - event.terminal_state === "completed" - ), - "replacement result did not satisfy the original coordinator-main join" - ); - const artifacts = runJson( - clusterflux, - ["artifact", "list", ...scope, "--process", processId], - { cwd: projectDir } - ).artifacts; - assert(artifacts.some((artifact) => artifact.artifact.startsWith("stable.txt-"))); - assert( - artifacts.some((artifact) => artifact.artifact.startsWith("recovering.txt-")) - ); - const released = await waitForCli( - "hosted recovery process release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120_000 - ); - fs.writeFileSync(sourcePath, original); - restored = true; - await client.close(); - closed = true; - return { - duration_ms: Date.now() - startedAt, - process: processId, - logical_task: originalFailure.task, - original_attempt: originalFailure.attempt_id, - replacement_attempt: replacementEvent.attempt_id, - original_join_completed: true, - terminal_state: released.state, - }; - } finally { - if (!restored) fs.writeFileSync(sourcePath, original); - if (!closed) { - await client.close().catch(() => { - if (client.child.exitCode === null) client.child.kill("SIGKILL"); - }); - } - } -} - -async function main() { - requireEnabled(); - const manifest = readJson(manifestPath); - for (const asset of manifest.assets ?? []) { - asset.file = path.isAbsolute(asset.file) - ? asset.file - : path.resolve(path.dirname(manifestPath), asset.file); - } - assert.strictEqual(manifest.kind, "clusterflux-public-release"); - assert.strictEqual(manifest.default_hosted_coordinator_endpoint, serviceEndpoint); - assert.strictEqual(serviceAddr, "clusterflux.michelpaulissen.com:443"); - const qualityGates = strictQualityGateEvidence(manifest); - - const workRoot = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-cli-happy-")); - const installDir = path.join(workRoot, "install"); - const checkout = path.join(workRoot, "public-repo"); - const downloadPath = path.join(workRoot, "release.tar"); - const extractedArtifact = path.join(workRoot, "artifact"); - ensureDir(installDir); - run("tar", ["-xzf", binaryArchive(manifest), "-C", installDir]); - const publicSource = stagePublicCheckout(manifest, checkout); - - const clusterflux = executable(installDir, "clusterflux"); - const clusterfluxNode = executable(installDir, "clusterflux-node"); - const clusterfluxDap = executable(installDir, "clusterflux-debug-dap"); - const projectDir = path.join(checkout, "tests/fixtures/runtime-conformance"); - const helloProjectDir = path.join(checkout, "examples/hello-build"); - const recoveryProjectDir = path.join(checkout, "examples/recovery-build"); - const suffix = String(Date.now()); - const workerNode = `worker-${suffix}`; - - const loginStartedAt = Date.now(); - let loginSession; - let receivedDefaultProject; - if (reuseSessionFile) { - const sourceSessionPath = path.resolve(reuseSessionFile); - const sourceProjectPath = path.join(path.dirname(sourceSessionPath), "project.json"); - const sourceSession = readJson(sourceSessionPath); - const sourceProject = readJson(sourceProjectPath); - assert.strictEqual(sourceSession.kind, "human"); - assert.strictEqual(sourceSession.coordinator, serviceEndpoint); - assert.strictEqual(sourceProject.coordinator, serviceEndpoint); - assert.strictEqual(sourceProject.tenant, sourceSession.tenant); - assert.strictEqual(sourceProject.project, sourceSession.project); - assert.strictEqual(sourceProject.user, sourceSession.user); - assert( - Number(sourceSession.expires_at) > Math.floor(Date.now() / 1000) + 300, - "reused CLI session expires too soon for the live journey" - ); - const destinationConfig = path.join(projectDir, ".clusterflux"); - ensureDir(destinationConfig); - fs.copyFileSync(sourceSessionPath, path.join(destinationConfig, "session.json")); - fs.copyFileSync(sourceProjectPath, path.join(destinationConfig, "project.json")); - fs.chmodSync(path.join(destinationConfig, "session.json"), 0o600); - fs.chmodSync(path.join(destinationConfig, "project.json"), 0o644); - loginSession = sourceSession; - receivedDefaultProject = true; - } else { - const login = runJson( - clusterflux, - ["login", "--browser", "--json"], - { - cwd: projectDir, - env: { ...process.env, CLUSTERFLUX_BROWSER_OPEN_COMMAND: browserOpenCommand }, - } - ); - assert.strictEqual(login.plan.coordinator, serviceEndpoint); - assert.strictEqual(login.boundary.scoped_cli_session_received, true); - assert.strictEqual(login.boundary.provider_tokens_exposed_to_cli, false); - assert.strictEqual(login.boundary.provider_tokens_sent_to_nodes, false); - loginSession = login.coordinator_response.session; - assert(loginSession, "hosted browser login omitted its scoped session"); - receivedDefaultProject = - typeof loginSession.project === "string" && loginSession.project.length > 0; - assert(receivedDefaultProject, "login did not return its server-owned project"); - } - const sessionSecret = - loginSession.cli_session_secret || loginSession.session_secret; - const loginDurationMs = Math.max(1, Date.now() - loginStartedAt); - assert(sessionSecret, "hosted browser login omitted the CLI session credential"); - const tenant = loginSession.tenant; - const project = loginSession.project; - const user = loginSession.user; - for (const [name, value] of Object.entries({ tenant, project, user })) { - assert.strictEqual(typeof value, "string", `hosted session omitted ${name}`); - assert.notStrictEqual(value, "", `hosted session returned an empty ${name}`); - } - const scope = [ - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--user", - user, - "--json", - ]; - - if (!reuseSessionFile) { - const projectInit = runJson( - clusterflux, - [ - "project", - "init", - ...scope, - "--new-project", - project, - "--name", - "CLI Happy Path", - "--yes", - ], - { cwd: projectDir } - ); - assert.strictEqual(projectInit.command, "project init"); - assert.strictEqual(projectInit.project_config_written, true); - assert.strictEqual(projectInit.coordinator_response.type, "project_created"); - } - - const projectList = runJson(clusterflux, ["project", "list", ...scope], { - cwd: projectDir, - }); - assert(projectList.project_count >= 1); - const projectSelect = runJson( - clusterflux, - ["project", "select", ...scope, project], - { cwd: projectDir } - ); - assert.strictEqual(projectSelect.command, "project select"); - - const inspection = runJson(clusterflux, ["inspect", "--project", ".", "--json"], { - cwd: projectDir, - }); - assert( - inspection.metadata.environments.some((environment) => environment.name === "linux") - ); - assert(Array.isArray(inspection.source_provider_statuses)); - assert(inspection.source_provider_manifest); - - const runReport = runJson( - clusterflux, - ["run", "build", "--project", ".", "--json"], - { cwd: projectDir } - ); - assert.strictEqual(runReport.command, "run"); - assert.strictEqual(runReport.status, "main_launched"); - assert.strictEqual(runReport.task_launch.type, "main_launched"); - const processId = runReport.process; - - const parkedStatus = await waitForCli( - "hosted coordinator main to park before node enrollment", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => - status.live_process?.main_state === "running" && - status.live_process?.main_wait_state === "waiting_for_node" && - status.live_process?.connected_nodes?.length === 0, - 120000 - ); - const launchAttemptOwnership = await runLaunchAttemptOwnershipGuards({ - clusterflux, - projectDir, - scope, - sessionSecret, - activeProcess: processId, - }); - - const nodeLifecycleStartedAt = Date.now(); - const grant = runJson(clusterflux, ["node", "enroll", ...scope], { - cwd: projectDir, - }); - assert.strictEqual(grant.command, "node enroll"); - const attach = runJson( - clusterflux, - [ - "node", - "attach", - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--node", - workerNode, - "--enrollment-grant", - grant.enrollment_grant.grant, - "--json", - ], - { cwd: projectDir } - ); - assert.strictEqual(attach.command, "node attach"); - assert.strictEqual(attach.boundary.used_enrollment_exchange, true); - - const credentialDir = path.join(projectDir, ".clusterflux", "nodes"); - const credentialFiles = fs - .readdirSync(credentialDir) - .filter((file) => file.endsWith(".json")); - assert.strictEqual(credentialFiles.length, 1, "expected one persisted node credential"); - const credentialPath = path.join(credentialDir, credentialFiles[0]); - const credentialBefore = fs.readFileSync(credentialPath); - const credentialDigest = sha256(credentialBefore); - if (process.platform !== "win32") { - assert.strictEqual(fs.statSync(credentialPath).mode & 0o777, 0o600); - } - - const workerArgsFor = (projectRoot) => [ - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--node", - workerNode, - "--worker", - "--project-root", - projectRoot, - "--assignment-poll-ms", - "500", - "--emit-ready", - ]; - const workerArgs = workerArgsFor(projectDir); - const spawnWorker = (projectRoot = projectDir) => - spawnJsonLines(clusterfluxNode, workerArgsFor(projectRoot), { - cwd: projectRoot, - env: { ...process.env }, - }); - - let worker = spawnWorker(); - try { - const firstReady = await worker.waitFor( - (value) => value.node_status === "ready", - "first persisted worker ready" - ); - assert.strictEqual(firstReady.node, workerNode); - const initiallyOnline = runJson( - clusterflux, - ["node", "status", ...scope, "--node", workerNode], - { cwd: projectDir } - ); - assert.strictEqual(nodeDescriptor(initiallyOnline, workerNode)?.online, true); - - const completedTasks = await waitForCli( - "real hosted flagship completion", - () => - runJson(clusterflux, ["task", "list", ...scope, "--process", processId], { - cwd: projectDir, - }), - (tasks) => completedFlagship(rawTaskEvents(tasks)) - ); - const firstEvents = rawTaskEvents(completedTasks); - assert( - firstEvents - .filter((event) => event.executor === "node") - .every((event) => event.node === workerNode) - ); - assert( - firstEvents.some( - (event) => - event.task_definition === "package_release" && - event.terminal_state === "completed" && - contentAddressedArtifactId(event, "release.tar") - ) - ); - - const releasedFlagshipStatus = await waitForCli( - "completed flagship process to release its active slot", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120000 - ); - - const offlineStartedAt = Date.now(); - await stopChild(worker.child); - const observedOffline = await waitForCli( - "server-derived worker stale/offline transition", - () => - runJson(clusterflux, ["node", "status", ...scope, "--node", workerNode], { - cwd: projectDir, - }), - (status) => nodeDescriptor(status, workerNode)?.online === false, - 120000 - ); - worker = spawnWorker(); - const secondReady = await worker.waitFor( - (value) => value.node_status === "ready", - "restarted persisted worker ready" - ); - assert.strictEqual(secondReady.node, workerNode); - assert.strictEqual(sha256(fs.readFileSync(credentialPath)), credentialDigest); - - const nodeStatus = await waitForCli( - "server-derived worker online recovery", - () => - runJson(clusterflux, ["node", "status", ...scope, "--node", workerNode], { - cwd: projectDir, - }), - (status) => nodeDescriptor(status, workerNode)?.online === true, - 30000 - ); - assert(JSON.stringify(nodeStatus.response).includes(workerNode)); - assert.strictEqual(sha256(fs.readFileSync(credentialPath)), credentialDigest); - const nodeLivenessTransition = { - initial_online: nodeDescriptor(initiallyOnline, workerNode).online, - stale_offline: nodeDescriptor(observedOffline, workerNode).online, - recovered_online: nodeDescriptor(nodeStatus, workerNode).online, - offline_detection_ms: Date.now() - offlineStartedAt, - persisted_identity_reused: true, - duration_ms: Math.max(1, Date.now() - nodeLifecycleStartedAt), - }; - - const processStatus = runJson( - clusterflux, - ["process", "status", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert.strictEqual(processStatus.command, "process status"); - assert(processStatus.current_task_count >= firstEvents.length); - - const logs = runJson( - clusterflux, - ["logs", ...scope, "--process", processId], - { cwd: projectDir } - ); - assert(logs.log_entries.length >= 4); - - const artifacts = runJson( - clusterflux, - ["artifact", "list", ...scope, "--process", processId], - { cwd: projectDir } - ); - const releaseArtifact = artifacts.artifacts.find((artifact) => { - const digest = artifact.digest; - return ( - typeof digest === "string" && - /^sha256:[0-9a-f]{64}$/.test(digest) && - artifact.artifact === `release.tar-${digest.slice("sha256:".length)}` - ); - }); - assert(releaseArtifact, "hosted flagship did not publish release.tar"); - assert.strictEqual(releaseArtifact.state, "metadata_flushed"); - - const download = runJson( - clusterflux, - [ - "artifact", - "download", - ...scope, - releaseArtifact.artifact, - "--to", - downloadPath, - ], - { cwd: projectDir } - ); - assert.strictEqual(download.download_session.link_issued, true); - assert.strictEqual(download.local_download.local_bytes_written_by_cli, true); - assert.strictEqual(download.local_download.verified_digest, releaseArtifact.digest); - assert.strictEqual(sha256(fs.readFileSync(downloadPath)), releaseArtifact.digest); - - ensureDir(extractedArtifact); - const archiveEntries = run("tar", ["-tf", downloadPath]); - assert.match(archiveEntries, /(?:^|\n)hello-clusterflux(?:\n|$)/); - run("tar", ["-xf", downloadPath, "-C", extractedArtifact]); - const builtExecutable = path.join(extractedArtifact, "hello-clusterflux"); - assert(fs.existsSync(builtExecutable)); - const builtOutput = run(builtExecutable, []).trim(); - assert.strictEqual(builtOutput, "hello from a real Clusterflux build"); - - copyProjectControlState(projectDir, helloProjectDir); - copyProjectControlState(projectDir, recoveryProjectDir); - await stopChild(worker.child); - worker = spawnWorker(helloProjectDir); - await worker.waitFor( - (value) => value.node_status === "ready", - "hello-build worker ready" - ); - const helloBuild = await runHostedHelloBuild({ - clusterflux, - projectDir: helloProjectDir, - scope, - outputFile: path.join(workRoot, "hello-clusterflux"), - }); - await stopChild(worker.child); - worker = spawnWorker(recoveryProjectDir); - await worker.waitFor( - (value) => value.node_status === "ready", - "recovery-build worker ready" - ); - const recoveryBuild = await runHostedRecoveryBuild({ - clusterfluxDap, - clusterflux, - projectDir: recoveryProjectDir, - scope, - }); - await stopChild(worker.child); - worker = spawnWorker(); - await worker.waitFor( - (value) => value.node_status === "ready", - "runtime-conformance worker restored" - ); - - const dapEditRestart = await runLiveDapEditRestart({ - clusterfluxDap, - clusterflux, - projectDir, - scope, - worker, - }); - - const processCancellationStartedAt = Date.now(); - const restart = runJson( - clusterflux, - ["process", "restart", ...scope, "--process", dapEditRestart.process, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(restart.restart_request.accepted, true); - const cancel = runJson( - clusterflux, - ["process", "cancel", ...scope, "--process", dapEditRestart.process, "--yes"], - { cwd: projectDir } - ); - assert.strictEqual(cancel.cancel_request.accepted, true); - const releasedDap = await waitForCli( - "cancelled DAP process slot release", - () => - runJson( - clusterflux, - ["process", "status", ...scope, "--process", dapEditRestart.process], - { cwd: projectDir } - ), - (status) => status.state === "not_active", - 120000 - ); - assert.strictEqual(releasedDap.state, "not_active"); - const processCancellationLifecycle = { - request: { - restart_process: dapEditRestart.process, - cancel_process: dapEditRestart.process, - }, - expected: - "explicit process cancellation terminates active participants and releases the slot", - observed: { - restart_accepted: restart.restart_request.accepted, - cancel_accepted: cancel.cancel_request.accepted, - terminal_state: releasedDap.state, - }, - duration_ms: Math.max(1, Date.now() - processCancellationStartedAt), - }; - - const identityWorkerNode = `identity-worker-${suffix}`; - const identityWorkerGrant = runJson( - clusterflux, - ["node", "enroll", ...scope], - { cwd: projectDir } - ); - runJson( - clusterflux, - [ - "node", - "attach", - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--node", - identityWorkerNode, - "--enrollment-grant", - identityWorkerGrant.enrollment_grant.grant, - "--json", - ], - { cwd: projectDir } - ); - const identityWorker = spawnJsonLines( - clusterfluxNode, - [ - "--coordinator", - serviceEndpoint, - "--tenant", - tenant, - "--project-id", - project, - "--node", - identityWorkerNode, - "--worker", - "--project-root", - projectDir, - "--assignment-poll-ms", - "500", - "--emit-ready", - ], - { cwd: projectDir, env: { ...process.env } } - ); - let sameDefinitionIdentity; - try { - const identityWorkerReady = await identityWorker.waitFor( - (value) => value.node_status === "ready", - "same-definition identity worker ready" - ); - assert.strictEqual(identityWorkerReady.node, identityWorkerNode); - await waitForCli( - "same-definition identity worker online", - () => - runJson( - clusterflux, - ["node", "status", ...scope, "--node", identityWorkerNode], - { cwd: projectDir } - ), - (status) => nodeDescriptor(status, identityWorkerNode)?.online === true, - 30_000 - ); - await stopChild(worker.child); - worker = spawnWorker(); - const refreshedPrimaryReady = await worker.waitFor( - (value) => value.node_status === "ready", - "same-definition primary worker capability refresh" - ); - assert.strictEqual(refreshedPrimaryReady.node, workerNode); - const primaryStatus = await waitForCli( - "same-definition primary worker online after refresh", - () => - runJson( - clusterflux, - ["node", "status", ...scope, "--node", workerNode], - { cwd: projectDir } - ), - (status) => nodeDescriptor(status, workerNode)?.online === true, - 30_000 - ); - const identityStatus = runJson( - clusterflux, - ["node", "status", ...scope, "--node", identityWorkerNode], - { cwd: projectDir } - ); - const primarySnapshots = - nodeDescriptor(primaryStatus, workerNode)?.source_snapshots || []; - const identitySnapshots = - nodeDescriptor(identityStatus, identityWorkerNode)?.source_snapshots || []; - assert( - primarySnapshots.some((snapshot) => identitySnapshots.includes(snapshot)), - `same-definition workers do not share a current source snapshot: ${JSON.stringify({ - primarySnapshots, - identitySnapshots, - })}` - ); - sameDefinitionIdentity = await runSameDefinitionDapIdentity({ - clusterfluxDap, - clusterflux, - projectDir, - scope, - }); - } finally { - await stopChild(identityWorker.child); - runJson( - clusterflux, - ["node", "revoke", ...scope, "--node", identityWorkerNode, "--yes"], - { cwd: projectDir } - ); - } - const repeatedParkWake = await runRepeatedParkWakeProof({ - clusterflux, - projectDir, - scope, - }); - const longJoin = await runLongJoinProof({ - clusterflux, - projectDir, - scope, - }); - - await stopChild(worker.child); - const tenantIsolationResult = await runSecondTenantIsolation({ - clusterflux, - clusterfluxNode, - firstScope: scope, - firstHelloBuild: helloBuild, - firstHelloProjectDir: helloProjectDir, - workRoot, - firstSessionSecret: sessionSecret, - firstTenant: tenant, - firstProject: project, - firstProcess: dapEditRestart.process, - firstNode: workerNode, - firstArtifact: releaseArtifact.artifact, - manifest, - }); - const tenantIsolation = tenantIsolationResult.evidence; - const scopedCollisionRuntime = tenantIsolationResult.runtime; - worker = spawnWorker(); - const collisionRecoveryReady = await worker.waitFor( - (value) => value.node_status === "ready", - "primary worker restored after two-tenant collision proof" - ); - assert.strictEqual(collisionRecoveryReady.node, workerNode); - - const securityNode = await prepareLiveNodeCredentialSecurity({ - clusterflux, - projectDir, - scope, - tenant, - project, - suffix, - bundle: { - digest: runReport.bundle_digest, - moduleBase64: fs - .readFileSync( - path.resolve(projectDir, runReport.bundle_build.bundle_artifact.module) - ) - .toString("base64"), - entryExport: runReport.entry_export, - entryStableId: runReport.entry_stable_id, - }, - }); - const droppedConnectionRollback = await runDroppedConnectionRollback({ - clusterflux, - projectDir, - scope, - }); - const bandwidthPreallocation = await runLiveBandwidthPreallocation({ - sessionSecret, - artifact: releaseArtifact.artifact, - maxBytes: download.local_download.bytes_written, - }); - await stopChild(worker.child); - const relayEmergencyDisableResult = await runRelayEmergencyDisable({ - clusterflux, - clusterfluxNode, - projectDir, - scope, - workerArgs, - sessionSecret, - maxBytes: download.local_download.bytes_written, - }); - worker = relayEmergencyDisableResult.worker; - const relayEmergencyDisable = relayEmergencyDisableResult.evidence; - const agentCredentialSecurity = await runLiveAgentCredentialSecurity({ - clusterfluxDap, - clusterflux, - projectDir, - scope, - sessionSecret, - tenant, - project, - suffix, - bundle: { - digest: runReport.bundle_digest, - moduleBase64: fs - .readFileSync( - path.resolve(projectDir, runReport.bundle_build.bundle_artifact.module) - ) - .toString("base64"), - entryExport: runReport.entry_export, - entryStableId: runReport.entry_stable_id, - }, - securityNode, - workerRuntime: { - node: workerNode, - child: worker.child, - worker, - identity: nodeIdentityFromPrivateKey( - readNodeCredential(projectDir, workerNode).credential.private_key - ), - }, - }); - const mainBeforeChildLifecycle = - agentCredentialSecurity.main_before_child_lifecycle; - - await stopChild(worker.child); - const liveSoak = await runLiveSoak({ - clusterflux, - projectDir, - scope, - securityNode, - }); - const malformedIdentifiers = await runMalformedIdentifierSuite({ - clusterflux, - projectDir, - scope, - sessionSecret, - tenant, - project, - user, - suffix, - securityNode, - bundle: { - digest: runReport.bundle_digest, - moduleBase64: fs - .readFileSync( - path.resolve(projectDir, runReport.bundle_build.bundle_artifact.module) - ) - .toString("base64"), - entryExport: runReport.entry_export, - entryStableId: runReport.entry_stable_id, - }, - releaseArtifact, - }); - const signedHostileArtifactPath = await runLiveSignedHostileArtifactPath({ - clusterflux, - projectDir, - scope, - tenant, - project, - suffix, - securityNode, - }); - const revokedNodeCredential = await revokeSecurityNode({ - clusterflux, - projectDir, - scope, - securityNode, - }); - const quotaPreallocation = await runLiveQuotaPreallocation({ - sessionSecret, - suffix, - }); - const hostedLoginIsolation = await runHostedLoginIsolationBeforeRestart(); - const serviceRestart = await restartHostedServiceAndResume({ - clusterflux, - clusterfluxNode, - projectDir, - scope, - workerArgs, - workerNode, - credentialPath, - credentialDigest, - scopedCollisionRuntime, - }); - if (serviceRestart.worker) worker = serviceRestart.worker; - const scopedNodeRevocationAfterRestart = scopedCollisionRuntime - ? await finishScopedNodeCollisionAfterRestart({ - clusterflux, - projectDir, - scope, - workerNode, - scopedCollisionRuntime, - }) - : { - executed: false, - reason: "second tenant runtime session was not supplied", - duration_ms: 1, - }; - const relayAfterRestart = relayDurableState(); - assert( - relayAfterRestart.ingress_used >= - bandwidthPreallocation.durable_after_release.ingress_used - ); - assert( - relayAfterRestart.egress_used >= - bandwidthPreallocation.durable_after_release.egress_used - ); - assert( - relayAfterRestart.abandoned_or_failed_used >= - bandwidthPreallocation.durable_after_release.abandoned_or_failed_used - ); - bandwidthPreallocation.durable_after_restart = relayAfterRestart; - bandwidthPreallocation.restart_persistence = true; - bandwidthPreallocation.duration_ms = - Date.now() - bandwidthPreallocation.scenario_started_at_ms; - delete bandwidthPreallocation.scenario_started_at_ms; - await finishHostedLoginIsolationAfterRestart(hostedLoginIsolation); - const userCredentialSecurity = await finishUserCredentialSecurity({ - clusterflux, - projectDir, - scope, - sessionSecret, - }); - const configProvenance = configurationProvenance(); - const proxyConfigProvenance = proxyConfigurationProvenance(); - const concurrentCompileTasks = [ - ...new Set( - firstEvents - .filter( - (event) => - event.task_definition === "compile_linux" && - event.terminal_state === "completed" - ) - .map((event) => event.task) - ), - ]; - assert(concurrentCompileTasks.length >= 2); - const extensionAsset = manifest.assets.find((asset) => - asset.name.endsWith(".vsix") - ); - const requirement = ({ id, passed, evidence, durationMs }) => { - const result = { - id, - passed: passed === true, - evidence, - }; - if (Number.isFinite(durationMs) && durationMs > 0) { - result.duration_ms = durationMs; - } else if (strictFullRelease) { - throw new Error( - `strict release scenario ${id} omitted a measured positive duration` - ); - } - return result; - }; - const qualityCheck = (id) => qualityGates?.checks?.[id]; - const nodeEnrollmentEvidence = { - request: "one-time enrollment followed by a grant-free worker restart", - expected: "the persisted node credential is reused unchanged", - observed: { - used_enrollment_exchange: attach.boundary.used_enrollment_exchange, - restarted_node: secondReady.node, - credential_digest: credentialDigest, - liveness: nodeLivenessTransition, - service_restart_executed: serviceRestart.executed, - }, - }; - const loginEvidence = { - request: reuseSessionFile - ? "reuse a still-valid scoped browser-login session" - : "perform browser OIDC login", - expected: "server-owned default project persists and can be selected", - observed: { - fresh_login: !reuseSessionFile, - tenant, - project, - user, - received_default_project: receivedDefaultProject, - project_select_command: projectSelect.command, - }, - }; - const credentialSecurityEvidence = { - expected: - "forged, replayed, expired, body-modified, and revoked user/Node/Agent credentials are denied", - observed: { - user: userCredentialSecurity, - node: { - initial: securityNode.evidence, - revoked: revokedNodeCredential.denied, - }, - agent: { - replay: agentCredentialSecurity.replay, - expired: agentCredentialSecurity.expired, - forged: agentCredentialSecurity.forged, - body_modified: agentCredentialSecurity.body_modified, - revoked: agentCredentialSecurity.revoked, - }, - }, - }; - const credentialSecurityDurationMs = - userCredentialSecurity.duration_ms + - securityNode.duration_ms + - revokedNodeCredential.duration_ms + - agentCredentialSecurity.duration_ms; - const relaySecurityEvidence = { - expected: - "limits are scoped independently and abandoned transfer bytes remain charged without a shared soft lockout", - observed: { - spawn_quota: quotaPreallocation, - relay_accounting: bandwidthPreallocation, - emergency_disable: relayEmergencyDisable, - }, - }; - const relaySecurityDurationMs = - quotaPreallocation.duration_ms + - bandwidthPreallocation.duration_ms + - relayEmergencyDisable.duration_ms; - const strictRequirementLedger = [ - requirement({ - id: "01_formatting", - passed: qualityCheck("formatting")?.status === "passed", - evidence: qualityCheck("formatting"), - durationMs: qualityCheck("formatting")?.duration_ms, - }), - requirement({ - id: "02_clippy_warnings_denied", - passed: qualityCheck("clippy_warnings_denied")?.status === "passed", - evidence: qualityCheck("clippy_warnings_denied"), - durationMs: qualityCheck("clippy_warnings_denied")?.duration_ms, - }), - requirement({ - id: "03_public_workspace_tests", - passed: qualityCheck("public_workspace_tests")?.status === "passed", - evidence: qualityCheck("public_workspace_tests"), - durationMs: qualityCheck("public_workspace_tests")?.duration_ms, - }), - requirement({ - id: "04_private_hosted_policy_locked_tests", - passed: - qualityCheck("private_hosted_policy_locked_tests")?.status === - "passed", - evidence: qualityCheck("private_hosted_policy_locked_tests"), - durationMs: qualityCheck("private_hosted_policy_locked_tests") - ?.duration_ms, - }), - requirement({ - id: "05_wasm_example_builds", - passed: qualityCheck("wasm_example_builds")?.status === "passed", - evidence: qualityCheck("wasm_example_builds"), - durationMs: qualityCheck("wasm_example_builds")?.duration_ms, - }), - requirement({ - id: "06_filtered_public_tree_build_and_tests", - passed: - qualityCheck("filtered_public_tree_build_and_tests")?.status === - "passed", - evidence: qualityCheck("filtered_public_tree_build_and_tests"), - durationMs: qualityCheck("filtered_public_tree_build_and_tests") - ?.duration_ms, - }), - requirement({ - id: "07_final_vsix_checks", - passed: Boolean( - extensionAsset && - qualityCheck("vscode_extension_candidate")?.status === "passed" && - extensionAsset.sha256 === - manifest.release_candidate.extension_sha256 && - qualityCheck("vscode_extension_candidate")?.candidate_vsix - ?.sha256 === extensionAsset.sha256 - ), - evidence: qualityCheck("vscode_extension_candidate"), - durationMs: qualityCheck("vscode_extension_candidate")?.duration_ms, - }), - requirement({ - id: "08_browser_login_and_persistent_default_project", - passed: Boolean( - sessionSecret && - tenant && - project && - receivedDefaultProject && - projectSelect.command === "project select" - ), - evidence: loginEvidence, - durationMs: loginDurationMs, - }), - requirement({ - id: "09_one_time_node_enrollment_and_restart", - passed: - attach.boundary.used_enrollment_exchange === true && - secondReady.node === workerNode && - nodeLivenessTransition.persisted_identity_reused === true && - serviceRestart.executed === true, - evidence: nodeEnrollmentEvidence, - durationMs: nodeLivenessTransition.duration_ms, - }), - requirement({ - id: "10_real_hello_build_and_artifact_download", - passed: - helloBuild.executable_output === - "hello from a real Clusterflux build" && - helloBuild.downloaded_bytes > 0 && - helloBuild.downloaded_sha256 === helloBuild.digest, - evidence: helloBuild, - durationMs: helloBuild.duration_ms, - }), - requirement({ - id: "11_recovery_retry_and_original_join", - passed: - recoveryBuild.original_join_completed === true && - recoveryBuild.original_attempt !== - recoveryBuild.replacement_attempt && - recoveryBuild.terminal_state === "not_active", - evidence: recoveryBuild, - durationMs: recoveryBuild.duration_ms, - }), - requirement({ - id: "12_long_lived_coordinator_main", - passed: - longJoin.duration_seconds > 120 && - longJoin.terminal_state === "completed" && - longJoin.process_state === "not_active", - evidence: longJoin, - durationMs: longJoin.duration_ms, - }), - requirement({ - id: "13_main_completes_before_child_lifecycle", - passed: - mainBeforeChildLifecycle.observed.active_after_main === true && - mainBeforeChildLifecycle.observed.debug_state_after_main === - "debug_breakpoints" && - mainBeforeChildLifecycle.observed.child_terminal_state === - "completed" && - mainBeforeChildLifecycle.observed.final_process_state === - "not_active" && - mainBeforeChildLifecycle.observed.subsequent_run_status === - "main_launched" && - qualityCheck("process_lifecycle_regressions")?.status === "passed", - evidence: { - live: mainBeforeChildLifecycle, - compiled_failure_and_cancellation: - qualityCheck("process_lifecycle_regressions"), - }, - durationMs: - mainBeforeChildLifecycle.duration_ms + - (qualityCheck("process_lifecycle_regressions")?.duration_ms || 0), - }), - requirement({ - id: "14_dap_launch_without_breakpoint", - passed: - sameDefinitionIdentity.launch_without_breakpoint.observed.thread_id > - 0 && - sameDefinitionIdentity.terminal_state === "not_active", - evidence: sameDefinitionIdentity.launch_without_breakpoint, - durationMs: - sameDefinitionIdentity.launch_without_breakpoint.duration_ms, - }), - requirement({ - id: "15_real_breakpoint_installation_and_hit", - passed: - dapEditRestart.real_breakpoint.observed.stop_reason === - "breakpoint" && - dapEditRestart.real_breakpoint.observed.stopped_line === - dapEditRestart.real_breakpoint.request.line && - dapEditRestart.real_breakpoint.observed.all_threads_stopped === true, - evidence: dapEditRestart.real_breakpoint, - durationMs: dapEditRestart.real_breakpoint.duration_ms, - }), - requirement({ - id: "16_attach_with_preconfigured_breakpoint", - passed: - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .observed.initially_verified === false && - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .observed.installation_event_verified === true && - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .observed.stop_reason === "breakpoint" && - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .observed.stopped_line === - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .request.line, - evidence: - agentCredentialSecurity.attach_with_preconfigured_breakpoint, - durationMs: - agentCredentialSecurity.attach_with_preconfigured_breakpoint - .duration_ms, - }), - requirement({ - id: "17_breakpoint_revision_ordering", - passed: - dapEditRestart.breakpoint_revisions.authoritative_revision > - dapEditRestart.breakpoint_revisions.delayed_revision && - dapEditRestart.breakpoint_revisions.stale_completion_events === 0, - evidence: dapEditRestart.breakpoint_revisions, - durationMs: dapEditRestart.breakpoint_revisions.duration_ms, - }), - requirement({ - id: "18_continue_pause_inspect_disconnect", - passed: - dapEditRestart.debug_interaction.observed.pause_response_ms < - 2_000 && - dapEditRestart.debug_interaction.observed.inspect_response_ms < - 2_000 && - dapEditRestart.debug_interaction.observed.continue_response_ms < - 2_000 && - dapEditRestart.debug_interaction.observed.disconnect_response_ms < - 2_000, - evidence: dapEditRestart.debug_interaction, - durationMs: dapEditRestart.debug_interaction.duration_ms, - }), - requirement({ - id: "19_distinct_same_definition_instances", - passed: - sameDefinitionIdentity.thread_evidence.length === 2 && - sameDefinitionIdentity.completion_order.length === 2 && - sameDefinitionIdentity.thread_evidence[0].task_instance !== - sameDefinitionIdentity.thread_evidence[1].task_instance && - sameDefinitionIdentity.thread_evidence[0].attempt_id !== - sameDefinitionIdentity.thread_evidence[1].attempt_id && - concurrentCompileTasks.length >= 2, - evidence: sameDefinitionIdentity.same_definition_identity, - durationMs: - sameDefinitionIdentity.same_definition_identity.duration_ms, - }), - requirement({ - id: "20_real_podman_partial_debug_epoch", - passed: - agentCredentialSecurity.partial_freeze.partially_frozen === true && - agentCredentialSecurity.partial_freeze.dap_all_threads_stopped === - false && - agentCredentialSecurity.partial_freeze.podman_paused_container_ids - .length > 0 && - agentCredentialSecurity.partial_freeze.resumed_participants.length > - 0, - evidence: agentCredentialSecurity.partial_freeze, - durationMs: agentCredentialSecurity.partial_freeze.elapsed_ms, - }), - requirement({ - id: "21_post_main_launched_observation_recovery", - passed: - sameDefinitionIdentity.post_main_launched_observation_recovery - .observed.diagnostics.length === 2 && - sameDefinitionIdentity.post_main_launched_observation_recovery - .observed - .premature_stop_or_termination_events === 0 && - sameDefinitionIdentity.post_main_launched_observation_recovery - .observed.main_thread.id > 0, - evidence: - sameDefinitionIdentity.post_main_launched_observation_recovery, - durationMs: - sameDefinitionIdentity.post_main_launched_observation_recovery - .duration_ms, - }), - requirement({ - id: "22_observer_reconnection", - passed: - dapEditRestart.observer_reconnection.fault_injections.length === 5 && - dapEditRestart.observer_reconnection.observed - .false_stops_before_real_stop === 0 && - dapEditRestart.observer_reconnection.observed.real_stop_reason === - "breakpoint", - evidence: dapEditRestart.observer_reconnection, - durationMs: dapEditRestart.observer_reconnection.duration_ms, - }), - requirement({ - id: "23_malformed_identifiers_preserve_service", - passed: - malformedIdentifiers.valid_after_every_rejection === true && - malformedIdentifiers.all_rejected_for_intended_reason === true && - malformedIdentifiers.valid_authenticated_action_after_suite === - true && - malformedIdentifiers.valid_signed_rendezvous_after_suite === true && - malformedIdentifiers.rejected_requests.every( - (entry) => - Number.isFinite(entry.duration_ms) && entry.duration_ms > 0 - ), - evidence: malformedIdentifiers, - durationMs: malformedIdentifiers.duration_ms, - }), - requirement({ - id: "24_cross_tenant_access_denied", - passed: - tenantIsolation.executed === true && - tenantIsolation.process_hidden === true && - tenantIsolation.node_hidden === true && - tenantIsolation.tasks_and_logs.denied === true && - tenantIsolation.debug.denied === true && - tenantIsolation.artifact_and_download.denied === true, - evidence: tenantIsolation, - durationMs: tenantIsolation.duration_ms, - }), - requirement({ - id: "25_forged_replayed_expired_revoked_credentials_denied", - passed: - Boolean( - userCredentialSecurity.expired && - userCredentialSecurity.forged && - userCredentialSecurity.revoked - ) && - securityNode.evidence.replay.denied === true && - securityNode.evidence.expired.denied === true && - securityNode.evidence.forged.denied === true && - revokedNodeCredential.denied.denied === true && - agentCredentialSecurity.revoked.denied === true, - evidence: credentialSecurityEvidence, - durationMs: credentialSecurityDurationMs, - }), - requirement({ - id: "26_relay_limits_and_abandoned_transfer_charging", - passed: - quotaPreallocation.denied_process_allocated === false && - quotaPreallocation.independent_scope - .unaffected_by_spawn_quota === true && - bandwidthPreallocation.bytes_served_before_denial > 0 && - bandwidthPreallocation.partial_abandon.ingress_delta > 0 && - bandwidthPreallocation.partial_abandon.egress_delta > 0 && - bandwidthPreallocation.partial_abandon.abandoned_delta > 0 && - bandwidthPreallocation.partial_abandon.reservation_released === - true && - bandwidthPreallocation.restart_persistence === true && - relayEmergencyDisable.disabled.denied === true && - relayEmergencyDisable.runtime_drop_in_removed === true, - evidence: relaySecurityEvidence, - durationMs: relaySecurityDurationMs, - }), - requirement({ - id: "27_existing_process_rejection_preserves_process", - passed: launchAttemptOwnership.existing_process_survived === true, - evidence: launchAttemptOwnership, - durationMs: launchAttemptOwnership.duration_ms, - }), - requirement({ - id: "28_precommit_launch_failure_scoped_cleanup", - passed: - droppedConnectionRollback.cli_exit_status !== 0 && - droppedConnectionRollback.rollback === - "automatic CLI launch guard abort_process with matching launch_attempt" && - droppedConnectionRollback.terminal_state === "not_active", - evidence: droppedConnectionRollback, - durationMs: droppedConnectionRollback.duration_ms, - }), - requirement({ - id: "29_explicit_process_cancellation_cleanup", - passed: - processCancellationLifecycle.observed.restart_accepted === true && - processCancellationLifecycle.observed.cancel_accepted === true && - processCancellationLifecycle.observed.terminal_state === - "not_active", - evidence: processCancellationLifecycle, - durationMs: processCancellationLifecycle.duration_ms, - }), - requirement({ - id: "30_scoped_node_and_artifact_collision", - passed: - tenantIsolation.scoped_node_and_artifact_collision?.observed - ?.both_metadata_records_visible_to_owner === true && - tenantIsolation.scoped_node_and_artifact_collision?.observed - ?.first_download_survived_second_link_revocation === true && - tenantIsolation.scoped_node_and_artifact_collision?.observed - ?.same_artifact_id === helloBuild.artifact && - serviceRestart.scoped_node_collision_after_restart - ?.first_scope_online === true && - serviceRestart.scoped_node_collision_after_restart - ?.second_scope_online === true && - serviceRestart.scoped_node_collision_after_restart - ?.both_credentials_reused_without_grants === true && - scopedNodeRevocationAfterRestart.observed - ?.revoked_credential_denied === true && - scopedNodeRevocationAfterRestart.observed - ?.first_scope_node_online === true, - evidence: { - live_collision: - tenantIsolation.scoped_node_and_artifact_collision, - restart: - serviceRestart.scoped_node_collision_after_restart, - scoped_revocation: scopedNodeRevocationAfterRestart, - }, - durationMs: - tenantIsolation.scoped_node_and_artifact_collision?.duration_ms + - scopedNodeRevocationAfterRestart.duration_ms, - }), - requirement({ - id: "31_signed_hostile_artifact_path_preserves_service", - passed: - signedHostileArtifactPath.observed.rejection.denied === true && - signedHostileArtifactPath.observed.valid_metadata_response === - "vfs_metadata_recorded" && - signedHostileArtifactPath.observed.health_response === - "node_heartbeat" && - signedHostileArtifactPath.observed.process_cleanup === - "not_active", - evidence: signedHostileArtifactPath, - durationMs: signedHostileArtifactPath.duration_ms, - }), - ]; - const fullReleasePassed = - strictFullRelease && - proxyConfigProvenance?.active_state === "active" && - strictRequirementLedger.every((requirement) => requirement.passed === true); - const namedScenarios = strictRequirementLedger.map((requirement) => ({ - id: requirement.id, - name: requirement.id - .replace(/^\d+_/, "") - .replaceAll("_", " "), - status: requirement.passed ? "passed" : "failed", - ...(requirement.duration_ms - ? { duration_ms: requirement.duration_ms } - : {}), - })); - - const report = { - kind: "clusterflux-cli-happy-path-live", - release_name: manifest.release_name, - source_commit: manifest.source_commit, - source_tree_digest: manifest.source_tree_digest, - public_tree_identity: manifest.public_tree_identity, - binary_digests: manifest.binary_digests, - service_addr: serviceAddr, - default_hosted_coordinator_endpoint: serviceEndpoint, - public_repository_url: publicSource.published ? publicSource.url : null, - public_source: publicSource, - tenant, - project, - worker_node: workerNode, - process: processId, - signed_in: true, - fresh_hosted_login: !reuseSessionFile, - reused_scoped_cli_session: Boolean(reuseSessionFile), - received_default_project: receivedDefaultProject, - process_started_before_node: true, - parked_main_observed: { - main_state: parkedStatus.live_process.main_state, - main_wait_state: parkedStatus.live_process.main_wait_state, - connected_nodes: parkedStatus.live_process.connected_nodes, - }, - node_enrollment_grants_used: 2, - persisted_node_credential_mode: - process.platform === "win32" ? null : fs.statSync(credentialPath).mode & 0o777, - persisted_node_credential_digest: credentialDigest, - node_restarted_without_grant: true, - restarted_node_ready: secondReady.node, - node_liveness_transition: nodeLivenessTransition, - flagship_terminal_state: releasedFlagshipStatus.state, - flagship_task_definitions: [ - "prepare_source", - "compile_linux", - "package_release", - ], - rootless_podman_flagship_completed: true, - downstream_release_artifact: releaseArtifact, - artifact_download: { - bytes_written: download.local_download.bytes_written, - verified_digest: download.local_download.verified_digest, - executable_output: builtOutput, - }, - flagship_process_released_automatically: true, - concurrent_same_definition_tasks: sameDefinitionIdentity, - flagship_same_definition_task_instances: concurrentCompileTasks, - repeated_park_wake: repeatedParkWake, - long_join: longJoin, - main_before_child_lifecycle: mainBeforeChildLifecycle, - live_dap_edit_restart: dapEditRestart, - process_restart_requested: true, - process_cancel_requested: true, - dap_process_aborted: true, - process_cancellation_lifecycle: processCancellationLifecycle, - tenant_isolation: tenantIsolation, - scoped_node_revocation_after_restart: - scopedNodeRevocationAfterRestart, - credential_security: { - user: userCredentialSecurity, - node: { - node: securityNode.node, - credential_digest: securityNode.credential_digest, - ...securityNode.evidence, - revoked: revokedNodeCredential.denied, - }, - agent: agentCredentialSecurity, - }, - quota_preallocation: quotaPreallocation, - bandwidth_preallocation: bandwidthPreallocation, - relay_emergency_disable: relayEmergencyDisable, - hosted_login_isolation: hostedLoginIsolation, - dropped_connection_rollback: droppedConnectionRollback, - launch_attempt_ownership: launchAttemptOwnership, - live_soak: liveSoak, - hosted_service_restart: { - ...serviceRestart, - worker: undefined, - }, - release_binding: { - manifest: manifestPath, - source_commit: manifest.source_commit, - source_tree_digest: manifest.source_tree_digest, - source_tree_clean: manifest.source_tree_clean, - public_tree_identity: manifest.public_tree_identity, - binary_digests: manifest.binary_digests, - release_candidate: manifest.release_candidate, - deployment: serviceRestart.after || deploymentProvenance(), - configuration: configProvenance, - proxy_configuration: proxyConfigProvenance, - }, - commands, - quality_gates: qualityGates, - hello_build: helloBuild, - recovery_build: recoveryBuild, - malformed_identifiers: malformedIdentifiers, - signed_hostile_artifact_path: signedHostileArtifactPath, - named_scenarios: namedScenarios, - scenario_skips: [], - strict_requirement_ledger: strictRequirementLedger, - acceptance_result: fullReleasePassed ? "passed" : "partial", - }; - ensureDir(path.dirname(reportPath)); - fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); - if (strictFullRelease && !fullReleasePassed) { - const failed = strictRequirementLedger - .filter((requirement) => requirement.passed !== true) - .map((requirement) => requirement.id); - throw new Error(`strict full release failed: ${failed.join(", ")}`); - } - console.log(`CLI happy-path live smoke passed: ${reportPath}`); - } finally { - await stopChild(worker?.child); - } -} - -main().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/cli-install-smoke.js b/scripts/cli-install-smoke.js deleted file mode 100755 index 878543e..0000000 --- a/scripts/cli-install-smoke.js +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const temp = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-cli-install-")); -const installRoot = path.join(temp, "install"); -const targetDir = - process.env.CLUSTERFLUX_CLI_INSTALL_CARGO_TARGET_DIR || - process.env.CARGO_TARGET_DIR || - path.join(repo, "target"); -const project = path.join(repo, "tests/fixtures/runtime-conformance"); -const binName = process.platform === "win32" ? "clusterflux.exe" : "clusterflux"; -const installedBin = path.join(installRoot, "bin", binName); - -try { - cp.execFileSync( - "cargo", - [ - "install", - "--path", - "crates/clusterflux-cli", - "--bin", - "clusterflux", - "--root", - installRoot, - "--debug" - ], - { - cwd: repo, - env: { - ...process.env, - CARGO_TARGET_DIR: targetDir - }, - stdio: "inherit" - } - ); - - assert(fs.existsSync(installedBin), "installed clusterflux binary must exist"); - - const inspection = JSON.parse( - cp.execFileSync( - installedBin, - ["bundle", "inspect", "--project", project, "--json"], - { cwd: repo, encoding: "utf8" } - ) - ); - - assert.strictEqual(inspection.project, project); - assert.strictEqual(inspection.metadata.embeds_full_container_images, false); - assert(inspection.metadata.environments.some((env) => env.name === "linux")); - assert(inspection.metadata.selected_inputs.some((input) => input.path === "src/lib.rs")); -} finally { - fs.rmSync(temp, { recursive: true, force: true }); -} - -console.log("CLI install smoke passed"); diff --git a/scripts/cli-local-run-smoke.js b/scripts/cli-local-run-smoke.js deleted file mode 100755 index e2fc299..0000000 --- a/scripts/cli-local-run-smoke.js +++ /dev/null @@ -1,269 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { configurePodmanTestEnvironment } = require("./podman-test-env"); - -const repo = path.resolve(__dirname, ".."); -configurePodmanTestEnvironment(repo); -if ( - !process.env.CLUSTERFLUX_PODMAN_NIX_SHELL && - cp.spawnSync("podman", ["--version"], { stdio: "ignore" }).status !== 0 && - cp.spawnSync("nix", ["--version"], { stdio: "ignore" }).status === 0 -) { - cp.execFileSync( - "nix", - ["shell", "nixpkgs#podman", "--command", "node", __filename], - { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_PODMAN_NIX_SHELL: "1", - }, - stdio: "inherit", - } - ); - process.exit(0); -} -const project = path.join(repo, "tests/fixtures/runtime-conformance"); - -cp.execFileSync( - "cargo", - ["build", "-q", "-p", "clusterflux-node", "--bin", "clusterflux-node"], - { cwd: repo, stdio: "inherit" } -); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function runCli(args, env = {}) { - return new Promise((resolve, reject) => { - const child = cp.spawn( - "cargo", - ["run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", ...args], - { - cwd: repo, - env: { - ...process.env, - ...env - } - } - ); - const cliPid = child.pid; - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.on("exit", (code) => { - if (code !== 0) { - reject(new Error(`CLI run failed with code ${code}\n${stderr}`)); - return; - } - try { - resolve({ pid: cliPid, report: JSON.parse(stdout) }); - } catch (error) { - reject(new Error(`CLI output was not JSON: ${stdout}\n${error.stack || error.message}`)); - } - }); - }); -} - -(async () => { - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - assert(Number.isInteger(coordinator.pid)); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const { pid: cliPid, report } = await runCli([ - "run", - "--coordinator", - `${addr.host}:${addr.port}`, - "--project", - project, - "--json", - ]); - assert(Number.isInteger(cliPid)); - assert.notStrictEqual(cliPid, coordinator.pid); - assert.strictEqual(report.plan.entry, "build"); - assert.deepStrictEqual(report.plan.session, "Anonymous"); - assert.strictEqual(report.boundary.cli_process_started_node_process, true); - assert.strictEqual(report.boundary.cli_process_started_coordinator_process, false); - assert(Number.isInteger(report.boundary.spawned_node_process_id)); - assert.notStrictEqual(report.boundary.spawned_node_process_id, cliPid); - assert.notStrictEqual(report.boundary.spawned_node_process_id, coordinator.pid); - assert.strictEqual(report.boundary.node_session_requests, 0); - assert.strictEqual(report.node_report.node_status, "completed"); - assert.strictEqual(report.node_report.execution_substrate, "wasm"); - assert.strictEqual(report.node_report.task_spawn_host_import, true); - assert.strictEqual( - report.node_report.pre_node_process_status.processes.length, - 1 - ); - assert.deepStrictEqual( - report.node_report.pre_node_process_status.processes[0].connected_nodes, - [] - ); - assert.strictEqual( - report.node_report.pre_node_process_status.processes[0].main_state, - "running" - ); - assert.strictEqual( - report.node_report.pre_node_process_status.processes[0].main_wait_state, - "waiting_for_node", - "the coordinator must expose that the capless main is parked on placement before a node exists" - ); - assert.strictEqual( - report.node_report.pre_node_process_status.processes[0].main_task_instance, - report.node_report.run.task_instance - ); - assert.strictEqual(report.node_report.run.status, "main_launched"); - assert.strictEqual(report.node_report.join.type, "task_joined"); - const process = report.node_report.run.process; - assert.strictEqual(process, "vp-current"); - - const events = await send(addr, { - type: "list_task_events", - tenant: "tenant", - project: "project", - actor_user: "user", - process - }); - assert.strictEqual(events.type, "task_events"); - assert(events.events.length >= 4); - assert( - events.events - .filter((event) => event.executor === "node") - .every((event) => event.node === "node-cli-local") - ); - assert( - events.events.some( - (event) => - event.executor === "coordinator_main" && - event.node === "coordinator-main" - ) - ); - assert(events.events.every((event) => event.process === process)); - assert.deepStrictEqual( - new Set(events.events.map((event) => event.task_definition)), - new Set([ - report.node_report.run.task_definition, - "prepare_source", - "compile_linux", - "package_release", - ]) - ); - assert.strictEqual( - new Set(events.events.map((event) => event.task)).size, - events.events.length, - "every live task event must retain its unique instance identity" - ); - assert( - events.events.some( - (event) => event.task === report.node_report.run.task_instance - ) - ); - assert(events.events.some((event) => event.task.endsWith(":child:1"))); - assert(events.events.some((event) => event.task.endsWith(":child:2"))); - assert(events.events.some((event) => event.task.endsWith(":child:3"))); - assert(events.events.some((event) => event.artifact_path)); - } finally { - coordinator.kill("SIGTERM"); - } - - const { pid: autoCliPid, report: autoReport } = await runCli([ - "run", - "--local", - "--project", - project, - "--json", - ]); - assert(Number.isInteger(autoCliPid)); - assert.strictEqual(autoReport.plan.entry, "build"); - assert.deepStrictEqual(autoReport.plan.coordinator, "LocalOnly"); - assert.deepStrictEqual(autoReport.plan.session, "Anonymous"); - assert.strictEqual(autoReport.boundary.cli_process_started_node_process, true); - assert.strictEqual(autoReport.boundary.cli_process_started_coordinator_process, true); - assert.match(autoReport.boundary.coordinator_address, /^127\.0\.0\.1:\d+$/); - assert(Number.isInteger(autoReport.boundary.coordinator_process_id)); - assert(Number.isInteger(autoReport.boundary.spawned_node_process_id)); - assert.notStrictEqual(autoReport.boundary.coordinator_process_id, autoCliPid); - assert.notStrictEqual(autoReport.boundary.spawned_node_process_id, autoCliPid); - assert.notStrictEqual( - autoReport.boundary.spawned_node_process_id, - autoReport.boundary.coordinator_process_id - ); - assert.strictEqual(autoReport.boundary.node_session_requests, 0); - assert.strictEqual(autoReport.node_report.node_status, "completed"); - assert.strictEqual(autoReport.node_report.execution_substrate, "wasm"); - assert.strictEqual(autoReport.node_report.task_spawn_host_import, true); - assert.strictEqual(autoReport.node_report.run.status, "main_launched"); - assert.strictEqual(autoReport.node_report.join.type, "task_joined"); - - console.log("CLI local run smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/cli-login-smoke.js b/scripts/cli-login-smoke.js deleted file mode 100644 index 61b053b..0000000 --- a/scripts/cli-login-smoke.js +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const coordinator = "https://coord.example.test"; -const defaultHostedCoordinatorEndpoint = "https://clusterflux.michelpaulissen.com"; - -function clusterflux(args) { - return JSON.parse( - cp.execFileSync( - "cargo", - ["run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", ...args], - { cwd: repo, encoding: "utf8" } - ) - ); -} - -function clusterfluxRaw(args, env = {}) { - return cp.spawnSync( - "cargo", - ["run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", ...args], - { - cwd: repo, - encoding: "utf8", - env: { - ...process.env, - ...env, - }, - } - ); -} - -const browser = clusterflux(["login", "--plan", "--coordinator", coordinator, "--json"]); -assert.strictEqual(browser.coordinator, coordinator); -assert(browser.human_flow.Browser, "browser login should be available for human users"); -assert.strictEqual(browser.human_flow.Browser.authorization_url, null); -assert.strictEqual(browser.human_flow.Browser.server_owns_state, true); -assert.strictEqual(browser.human_flow.Browser.server_owns_nonce, true); -assert.strictEqual(browser.human_flow.Browser.pkce_required, true); -assert.strictEqual(browser.human_flow.Browser.hosted_callback, true); -assert.strictEqual(browser.human_flow.Browser.cli_receives_provider_authorization_code, false); -assert.strictEqual(browser.human_flow.Browser.cli_submits_identity_claims, false); - -const defaultBrowser = clusterflux(["login", "--plan", "--json"]); -assert.strictEqual(defaultBrowser.coordinator, defaultHostedCoordinatorEndpoint); -assert(defaultBrowser.human_flow.Browser); - -const nonInteractiveBrowser = clusterfluxRaw( - ["login", "--browser", "--non-interactive", "--coordinator", coordinator, "--json"], - { - CLUSTERFLUX_BROWSER_OPEN_COMMAND: - "node -e 'require(\"fs\").writeFileSync(\"/tmp/clusterflux-browser-should-not-open\", \"opened\")'", - } -); -assert.strictEqual(nonInteractiveBrowser.status, 20, nonInteractiveBrowser.stderr); -assert.doesNotMatch(nonInteractiveBrowser.stderr, /Opening Clusterflux browser login/); -const nonInteractiveReport = JSON.parse(nonInteractiveBrowser.stdout); -assert.strictEqual(nonInteractiveReport.status, "authentication_required"); -assert.strictEqual(nonInteractiveReport.non_interactive, true); -assert.strictEqual(nonInteractiveReport.browser_opened, false); -assert.strictEqual(nonInteractiveReport.machine_error.category, "authentication"); -assert.strictEqual(nonInteractiveReport.machine_error.stable_exit_code, 20); -assert( - nonInteractiveReport.machine_error.next_actions.includes( - "rerun without --non-interactive to open the browser" - ) -); - -console.log("CLI login smoke passed"); diff --git a/scripts/cli-output-mode-smoke.js b/scripts/cli-output-mode-smoke.js deleted file mode 100644 index 6cced83..0000000 --- a/scripts/cli-output-mode-smoke.js +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const project = path.join(repo, "tests/fixtures/runtime-conformance"); -const isolatedCwd = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-cli-output-")); -const isolatedHome = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-cli-home-")); - -function clusterflux(args, env = {}, cwd = isolatedCwd) { - return cp.execFileSync( - "cargo", - [ - "run", - "-q", - "--manifest-path", - path.join(repo, "Cargo.toml"), - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - ...args, - ], - { - cwd, - encoding: "utf8", - env: { - ...process.env, - HOME: isolatedHome, - USERPROFILE: isolatedHome, - XDG_CONFIG_HOME: path.join(isolatedHome, ".config"), - XDG_DATA_HOME: path.join(isolatedHome, ".local", "share"), - XDG_STATE_HOME: path.join(isolatedHome, ".local", "state"), - ...env, - }, - } - ); -} - -function json(args, env, cwd) { - return JSON.parse(clusterflux(args, env, cwd)); -} - -function assertHuman(name, output, requiredPatterns) { - assert( - !output.trimStart().startsWith("{"), - `${name} default output should be human-readable text, not JSON` - ); - for (const pattern of requiredPatterns) { - assert.match(output, pattern, `${name} human output missing ${pattern}`); - } -} - -const helpHuman = clusterflux(["help"]); -assertHuman("help", helpHuman, [ - /Primary workflow:/, - /clusterflux login --browser/, - /clusterflux project init/, - /clusterflux node attach; clusterflux-node --worker/, - /Clusterflux: Launch Virtual Process/, - /Hosted account creation happens in the browser login flow/, - /--json/, -]); - -const loginHuman = clusterflux([ - "login", - "--plan", - "--coordinator", - "https://coord.example.test", -]); -assertHuman("login", loginHuman, [ - /Clusterflux login/, - /flow: browser/, -]); - -const loginJson = json([ - "login", - "--plan", - "--coordinator", - "https://coord.example.test", - "--json", -]); -assert.strictEqual(loginJson.coordinator, "https://coord.example.test"); -assert(loginJson.human_flow.Browser); -assert.strictEqual(loginJson.human_flow.Browser.hosted_callback, true); -assert.strictEqual(loginJson.human_flow.Browser.cli_submits_identity_claims, false); - -const doctorHuman = clusterflux(["doctor"]); -assertHuman("doctor", doctorHuman, [ - /Clusterflux doctor/, - /coordinator reachability: not_configured/, - /dependencies:/, - /auth:/, - /node capabilities:/, - /node readiness: (ready_to_attach|local_dependencies_missing|limited_capabilities)/, - /node next:/, -]); - -const doctorJson = json(["doctor", "--json"]); -assert.strictEqual(doctorJson.coordinator_reachability.checked, false); -assert.strictEqual(doctorJson.coordinator_reachability.status, "not_configured"); -assert( - ["ready_to_attach", "local_dependencies_missing", "limited_capabilities"].includes( - doctorJson.node_readiness_summary.status - ) -); -assert.strictEqual(doctorJson.node_readiness_summary.explicit_attach_required, true); -assert.strictEqual( - doctorJson.node_readiness_summary.command_execution_capability, - true -); -assert(Array.isArray(doctorJson.node_readiness_summary.missing_local_dependencies)); -assert(doctorJson.node_readiness_summary.next_actions.length >= 2); - -const authJson = json(["auth", "status", "--json"], { - CLUSTERFLUX_TOKEN: "token", - CLUSTERFLUX_TOKEN_EXPIRES_AT: "2026-07-04T00:00:00Z", -}, isolatedCwd); -assert.strictEqual(authJson.session.kind, "human"); -assert.strictEqual(authJson.session.token_expiry_posture, "expires_at"); -assert.strictEqual(authJson.session.expires_at, "2026-07-04T00:00:00Z"); -assert.strictEqual(authJson.coordinator_account_status.checked, false); -assert.strictEqual(authJson.coordinator_account_status.account_status, "unknown"); -assert.strictEqual( - authJson.coordinator_account_status.private_moderation_details_exposed, - false -); - -const inspectHuman = clusterflux(["bundle", "inspect", "--project", project]); -assertHuman("bundle inspect", inspectHuman, [ - /Clusterflux bundle inspect/, - /bundle: sha256:/, - /environments:/, -]); - -const inspectJson = json(["bundle", "inspect", "--project", project, "--json"]); -assert.strictEqual(inspectJson.project, project); -assert.match(inspectJson.metadata.identity, /^sha256:/); -assert.match(inspectJson.metadata.wasm_code, /^sha256:/); -assert.strictEqual(inspectJson.metadata.task_metadata.default_entrypoint, "build"); -assert.deepStrictEqual(inspectJson.metadata.task_metadata.entrypoints, [ - "build", - "fail", - "identity", - "long-join", - "park-wake", - "restart", -]); -assert.strictEqual( - inspectJson.metadata.source_metadata.transfer_policy.coordinator_receives_source_bytes_by_default, - false -); -assert.strictEqual( - inspectJson.metadata.source_metadata.transfer_policy.default_full_repo_tarball, - false -); -assert.strictEqual(inspectJson.metadata.debug_metadata.dap_virtual_process, true); -assert.strictEqual( - inspectJson.metadata.large_input_policy.selected_inputs_are_content_digests, - true -); -assert.strictEqual(inspectJson.metadata.large_input_policy.selected_input_bytes_included, false); -assert.strictEqual(inspectJson.metadata.large_input_policy.full_repository_bytes_included, false); -assert.strictEqual( - inspectJson.metadata.large_input_policy.silent_task_argument_serialization, - false -); -assert(inspectJson.metadata.large_input_policy.supported_handle_types.includes("SourceSnapshot")); -assert.strictEqual( - inspectJson.metadata.restart_compatibility.source_edits_can_restart_from_clean_task_boundary, - true -); -assert.strictEqual( - inspectJson.metadata.restart_compatibility.requires_clean_checkpoint_boundary, - true -); -assert.strictEqual( - inspectJson.metadata.restart_compatibility.compares_task_abi, - inspectJson.metadata.task_metadata.task_abi -); -assert.strictEqual( - inspectJson.metadata.restart_compatibility.incompatible_changes_require_whole_process_restart, - true -); - -console.log("CLI output mode smoke passed"); diff --git a/scripts/coordinator-wire.js b/scripts/coordinator-wire.js deleted file mode 100644 index 7761736..0000000 --- a/scripts/coordinator-wire.js +++ /dev/null @@ -1,43 +0,0 @@ -let requestId = 0; - -function coordinatorWireRequest(payload, prefix = "acceptance") { - if (payload && payload.type === "coordinator_request") return payload; - if (!payload || typeof payload.type !== "string" || !payload.type.trim()) { - throw new Error("coordinator payload must have a non-empty type"); - } - requestId += 1; - return { - type: "coordinator_request", - protocol_version: 1, - request_id: `${prefix}-${process.pid}-${requestId}`, - operation: payload.type, - authentication: authenticationMetadata(payload), - payload, - }; -} - -function authenticationMetadata(payload) { - if (payload.type === "authenticated") { - return { - kind: "cli_session", - session: true, - request_operation: payload.request?.type || "unknown", - }; - } - if (payload.type === "signed_node" || payload.node_signature) { - return { kind: "node_signature", node: payload.node || null }; - } - if (payload.agent_signature) { - return { - kind: "agent_signature", - agent: payload.actor_agent || null, - fingerprint: payload.agent_public_key_fingerprint || null, - }; - } - if (payload.admin_token) { - return { kind: "admin_credential" }; - } - return { kind: "none" }; -} - -module.exports = { coordinatorWireRequest }; diff --git a/scripts/dap-client.js b/scripts/dap-client.js deleted file mode 100644 index 32d720c..0000000 --- a/scripts/dap-client.js +++ /dev/null @@ -1,135 +0,0 @@ -const cp = require("child_process"); - -class DapClient { - constructor({ - cwd = process.cwd(), - env = process.env, - command = "cargo", - args = [ - "run", - "-q", - "-p", - "clusterflux-dap", - "--bin", - "clusterflux-debug-dap", - ], - } = {}) { - this.child = cp.spawn( - command, - args, - { cwd, env } - ); - this.seq = 1; - this.buffer = Buffer.alloc(0); - this.messages = []; - this.waiters = []; - this.stderr = ""; - - this.child.stdout.on("data", (chunk) => { - this.buffer = Buffer.concat([this.buffer, chunk]); - this.parse(); - }); - this.child.stderr.on("data", (chunk) => { - this.stderr += chunk.toString(); - }); - this.child.on("exit", () => this.flushWaiters()); - } - - send(command, args = {}) { - const seq = this.seq++; - const message = { seq, type: "request", command, arguments: args }; - const payload = Buffer.from(JSON.stringify(message)); - this.child.stdin.write(`Content-Length: ${payload.length}\r\n\r\n`); - this.child.stdin.write(payload); - return seq; - } - - async response(seq, command) { - const message = await this.waitFor( - (item) => - item.type === "response" && - item.request_seq === seq && - item.command === command - ); - if (!message.success) { - throw new Error( - `DAP ${command} failed: ${message.message || JSON.stringify(message)}\nAdapter stderr:\n${this.stderr}` - ); - } - return message; - } - - async failure(seq, command) { - const message = await this.waitFor( - (item) => - item.type === "response" && - item.request_seq === seq && - item.command === command - ); - if (message.success) { - throw new Error(`DAP ${command} unexpectedly succeeded`); - } - return message; - } - - waitFor( - predicate, - timeoutMs = Number(process.env.CLUSTERFLUX_DAP_TIMEOUT_MS || 120000) - ) { - const existing = this.messages.find(predicate); - if (existing) return Promise.resolve(existing); - - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.child.kill("SIGKILL"); - const recent = this.messages - .slice(-10) - .map((message) => JSON.stringify(message)) - .join("\n"); - reject( - new Error( - `timed out waiting for DAP message\nRecent DAP messages:\n${recent}\nAdapter stderr:\n${this.stderr}` - ) - ); - }, timeoutMs); - this.waiters.push({ predicate, resolve, timer }); - }); - } - - parse() { - while (true) { - const headerEnd = this.buffer.indexOf("\r\n\r\n"); - if (headerEnd < 0) return; - const header = this.buffer.slice(0, headerEnd).toString(); - const match = header.match(/Content-Length: (\d+)/i); - if (!match) throw new Error(`bad DAP header: ${header}`); - const length = Number(match[1]); - const start = headerEnd + 4; - const end = start + length; - if (this.buffer.length < end) return; - const payload = this.buffer.slice(start, end).toString(); - this.buffer = this.buffer.slice(end); - this.messages.push(JSON.parse(payload)); - this.flushWaiters(); - } - } - - flushWaiters() { - for (const waiter of [...this.waiters]) { - const message = this.messages.find(waiter.predicate); - if (!message) continue; - clearTimeout(waiter.timer); - this.waiters.splice(this.waiters.indexOf(waiter), 1); - waiter.resolve(message); - } - } - - async close() { - if (this.child.exitCode !== null) return; - const seq = this.send("disconnect"); - await this.response(seq, "disconnect"); - this.child.stdin.end(); - } -} - -module.exports = { DapClient }; diff --git a/scripts/dap-smoke.js b/scripts/dap-smoke.js deleted file mode 100644 index 3ab3318..0000000 --- a/scripts/dap-smoke.js +++ /dev/null @@ -1,510 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -const { DapClient } = require("./dap-client"); - -(async () => { - const repo = path.resolve(__dirname, ".."); - const project = path.join(repo, "tests/fixtures/runtime-conformance"); - const sourcePath = fs.realpathSync(path.join(project, "src/lib.rs")); - const sourceLines = fs.readFileSync(sourcePath, "utf8").split(/\r?\n/); - const buildMainLine = - sourceLines.findIndex((line) => line.includes("pub async fn build_main()")) + 1; - assert(buildMainLine > 0, "flagship source must contain build_main"); - - const hostileDapClient = new DapClient(); - try { - const initialize = hostileDapClient.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await hostileDapClient.response(initialize, "initialize"); - for (const processId of [ - "", - " ", - "bad\u0000process", - "bad process!", - "x".repeat(256), - ]) { - const malformedLaunch = hostileDapClient.send("launch", { - entry: "build", - project, - runtimeBackend: "local-services", - processId, - }); - const rejection = await hostileDapClient.failure( - malformedLaunch, - "launch" - ); - assert.match( - rejection.message, - /invalid DAP processId: ProcessId is invalid/, - `unexpected malformed DAP identifier response: ${JSON.stringify(rejection)}` - ); - } - const validLaunch = hostileDapClient.send("launch", { - entry: "build", - project, - runtimeBackend: "local-services", - processId: "vp-valid-after-malformed", - }); - await hostileDapClient.response(validLaunch, "launch"); - await hostileDapClient.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - await hostileDapClient.close(); - } catch (error) { - if (hostileDapClient.child.exitCode === null) { - hostileDapClient.child.kill("SIGKILL"); - } - throw error; - } - - const asynchronousClient = new DapClient(); - try { - const initialize = asynchronousClient.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await asynchronousClient.response(initialize, "initialize"); - const launch = asynchronousClient.send("launch", { - entry: "long-join", - project, - runtimeBackend: "local-services", - }); - await asynchronousClient.response(launch, "launch"); - await asynchronousClient.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const configuredAt = Date.now(); - const configurationDone = asynchronousClient.send("configurationDone"); - await asynchronousClient.response(configurationDone, "configurationDone"); - assert( - Date.now() - configuredAt < 2_000, - "configurationDone must not wait for bundle build or runtime completion" - ); - - const threadDeadline = Date.now() + 120_000; - let runningThreads = []; - while (Date.now() < threadDeadline) { - const threadsRequest = asynchronousClient.send("threads"); - runningThreads = ( - await asynchronousClient.response(threadsRequest, "threads") - ).body.threads; - if (runningThreads.length > 0) break; - await new Promise((resolve) => setTimeout(resolve, 100)); - } - assert(runningThreads.length > 0, "asynchronous launch never reported a live thread"); - - const pauseAt = Date.now(); - const pause = asynchronousClient.send("pause", { - threadId: runningThreads[0].id, - }); - await asynchronousClient.response(pause, "pause"); - assert(Date.now() - pauseAt < 2_000, "pause response was blocked by runtime work"); - const paused = await asynchronousClient.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "pause" - ); - - const continueAt = Date.now(); - const continued = asynchronousClient.send("continue", { - threadId: paused.body.threadId, - }); - await asynchronousClient.response(continued, "continue"); - assert( - Date.now() - continueAt < 2_000, - "continue response was blocked by runtime observation" - ); - - const disconnectAt = Date.now(); - await asynchronousClient.close(); - assert( - Date.now() - disconnectAt < 2_000, - "disconnect response was blocked by runtime observation" - ); - } catch (error) { - if (asynchronousClient.child.exitCode === null) { - asynchronousClient.child.kill("SIGKILL"); - } - throw error; - } - - const client = new DapClient(); - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await client.response(initialize, "initialize"); - - const launch = client.send("launch", { - entry: "build", - project, - runtimeBackend: "local-services", - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const breakpoints = client.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: buildMainLine }], - }); - const breakpointResponse = await client.response( - breakpoints, - "setBreakpoints" - ); - assert.strictEqual(breakpointResponse.body.breakpoints.length, 1); - assert.strictEqual(breakpointResponse.body.breakpoints[0].verified, false); - - const configurationDone = client.send("configurationDone"); - await client.response(configurationDone, "configurationDone"); - const installedBreakpoint = await client.waitFor( - (message) => - message.type === "event" && - message.event === "breakpoint" && - message.body?.breakpoint?.verified === true - ); - assert.strictEqual(installedBreakpoint.body.breakpoint.line, buildMainLine); - const stopped = await client.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint" - ); - assert.strictEqual(stopped.body.allThreadsStopped, true); - assert.match(stopped.body.description, /confirmed by every active participant/i); - - const threadsRequest = client.send("threads"); - const threads = (await client.response(threadsRequest, "threads")).body - .threads; - const mainThread = threads.find((thread) => - thread.name.includes("build coordinator main") - ); - assert(mainThread, "the running Wasm entrypoint must be the DAP coordinator-main thread"); - assert.strictEqual(stopped.body.threadId, mainThread.id); - - const stackRequest = client.send("stackTrace", { - threadId: mainThread.id, - startFrame: 0, - levels: 1, - }); - const stack = (await client.response(stackRequest, "stackTrace")).body - .stackFrames; - assert.strictEqual(stack.length, 1); - assert.strictEqual(stack[0].line, buildMainLine); - assert.strictEqual(stack[0].source.path, sourcePath); - assert.match(stack[0].name, /build_main::wasm/); - assert.doesNotMatch(stack[0].name, /podman|cmd\.exe|powershell|pid|native child/i); - - const sourceRequest = client.send("source", { source: stack[0].source }); - const source = (await client.response(sourceRequest, "source")).body; - assert.match(source.content, /build_main/); - assert.match(source.mimeType, /rust/); - - const scopesRequest = client.send("scopes", { frameId: stack[0].id }); - const scopes = (await client.response(scopesRequest, "scopes")).body.scopes; - const localsScope = scopes.find((scope) => scope.name === "Source Locals"); - const wasmScope = scopes.find((scope) => scope.name === "Wasm Frame Locals"); - const argsScope = scopes.find( - (scope) => scope.name === "Task Args and Handles" - ); - const runtimeScope = scopes.find( - (scope) => scope.name === "Clusterflux Runtime" - ); - assert(localsScope && wasmScope && argsScope && runtimeScope); - - const localsRequest = client.send("variables", { - variablesReference: localsScope.variablesReference, - }); - const locals = (await client.response(localsRequest, "variables")).body - .variables; - assert( - locals.some( - (variable) => - variable.name === "unavailable-local-diagnostic" && - String(variable.value).includes("cannot be inspected") - ) - ); - - const wasmRequest = client.send("variables", { - variablesReference: wasmScope.variablesReference, - }); - const wasmLocals = (await client.response(wasmRequest, "variables")).body - .variables; - assert.deepStrictEqual( - wasmLocals.map((variable) => variable.name), - ["wasm-local-diagnostic"] - ); - assert.match(wasmLocals[0].value, /did not report inspectable Wasm frame locals/); - - const argsRequest = client.send("variables", { - variablesReference: argsScope.variablesReference, - }); - const args = (await client.response(argsRequest, "variables")).body.variables; - assert.deepStrictEqual( - args.map((variable) => variable.name), - ["runtime-boundary-diagnostic"] - ); - assert.match(args[0].value, /reported no task arguments or handles/); - - const runtimeRequest = client.send("variables", { - variablesReference: runtimeScope.variablesReference, - }); - const runtime = (await client.response(runtimeRequest, "variables")).body - .variables; - const value = (name) => runtime.find((variable) => variable.name === name)?.value; - assert.strictEqual(value("runtime_backend"), "LocalServices"); - assert.strictEqual(value("state"), "Frozen"); - assert.strictEqual(value("debug_epoch"), 1); - assert.strictEqual(value("coordinator_task_events"), 0); - assert.match( - String(value("command_status")), - /frozen through local services at executing Wasm probe/ - ); - - const step = client.send("next", { threadId: mainThread.id }); - const stepFailure = await client.failure(step, "next"); - assert.match(stepFailure.message, /source stepping is not yet available/i); - assert.match(stepFailure.message, /synthetic step/i); - - const restart = client.send("restartFrame", { frameId: stack[0].id }); - const restartFailure = await client.failure(restart, "restartFrame"); - assert.match(restartFailure.message, /checkpoint boundary|still active/i); - - const incompatibleRestart = client.send("restartFrame", { - frameId: stack[0].id, - sourceCompatibility: "incompatible", - }); - const incompatibleFailure = await client.failure( - incompatibleRestart, - "restartFrame" - ); - assert.match(incompatibleFailure.message, /incompatible source edit/i); - assert.match(incompatibleFailure.message, /whole virtual-process restart/i); - - await client.close(); - } catch (error) { - if (client.child.exitCode === null) client.child.kill("SIGKILL"); - throw error; - } - - const failMainLine = - sourceLines.findIndex((line) => line.includes("pub async fn fail_main()")) + 1; - assert(failMainLine > 0, "flagship source must contain fail_main"); - const taskTrapLine = - sourceLines.findIndex((line) => line.includes("fn task_trap(")) + 1; - assert(taskTrapLine > 0, "flagship source must contain task_trap"); - const restartClient = new DapClient(); - try { - const initialize = restartClient.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await restartClient.response(initialize, "initialize"); - const launch = restartClient.send("launch", { - entry: "fail", - project, - runtimeBackend: "local-services", - }); - await restartClient.response(launch, "launch"); - await restartClient.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - const breakpoints = restartClient.send("setBreakpoints", { - source: { path: sourcePath }, - breakpoints: [{ line: failMainLine }, { line: taskTrapLine }], - }); - const breakpointResponse = await restartClient.response( - breakpoints, - "setBreakpoints" - ); - assert.deepStrictEqual( - breakpointResponse.body.breakpoints.map((breakpoint) => breakpoint.verified), - [false, false] - ); - const configurationDone = restartClient.send("configurationDone"); - await restartClient.response(configurationDone, "configurationDone"); - const installedLines = []; - while (installedLines.length < 2) { - const installed = await restartClient.waitFor( - (message) => - message.type === "event" && - message.event === "breakpoint" && - message.body?.breakpoint?.verified === true && - !installedLines.includes(message.body.breakpoint.line) - ); - installedLines.push(installed.body.breakpoint.line); - } - assert.deepStrictEqual(installedLines.sort((a, b) => a - b), [ - failMainLine, - taskTrapLine, - ].sort((a, b) => a - b)); - const initialStop = await restartClient.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint" - ); - assert.strictEqual(initialStop.body.allThreadsStopped, true); - const threadsRequest = restartClient.send("threads"); - const threads = ( - await restartClient.response(threadsRequest, "threads") - ).body.threads; - const failThread = threads.find( - (thread) => thread.id === initialStop.body.threadId - ); - assert(failThread, "failed entrypoint must remain a virtual task thread"); - const stackRequest = restartClient.send("stackTrace", { - threadId: failThread.id, - startFrame: 0, - levels: 1, - }); - const failedStack = ( - await restartClient.response(stackRequest, "stackTrace") - ).body.stackFrames; - assert.strictEqual(failedStack[0].line, failMainLine); - - const continueRequest = restartClient.send("continue", { - threadId: failThread.id, - }); - await restartClient.response(continueRequest, "continue"); - const childStop = await restartClient.waitFor( - (message) => - message.seq > initialStop.seq && - message.type === "event" && - message.event === "stopped" && - message.body.reason === "breakpoint", - 70000 - ); - assert.strictEqual(childStop.body.allThreadsStopped, true); - - const childThreadsRequest = restartClient.send("threads"); - const childThreads = ( - await restartClient.response(childThreadsRequest, "threads") - ).body.threads; - const childThread = childThreads.find( - (thread) => thread.id === childStop.body.threadId - ); - assert(childThread, "executing child task must become a DAP virtual thread"); - assert.notStrictEqual(childThread.id, failThread.id); - assert.match(childThread.name, /task trap/i); - - const childStackRequest = restartClient.send("stackTrace", { - threadId: childThread.id, - startFrame: 0, - levels: 1, - }); - const childStack = ( - await restartClient.response(childStackRequest, "stackTrace") - ).body.stackFrames; - assert.strictEqual(childStack[0].line, taskTrapLine); - assert.match(childStack[0].name, /task_trap::wasm/); - - const childScopesRequest = restartClient.send("scopes", { - frameId: childStack[0].id, - }); - const childScopes = ( - await restartClient.response(childScopesRequest, "scopes") - ).body.scopes; - const childArgsScope = childScopes.find( - (scope) => scope.name === "Task Args and Handles" - ); - assert(childArgsScope, "child task argument scope must be present"); - const childArgsRequest = restartClient.send("variables", { - variablesReference: childArgsScope.variablesReference, - }); - const childArgs = ( - await restartClient.response(childArgsRequest, "variables") - ).body.variables; - assert( - childArgs.some( - (variable) => - variable.name === "arg_0" && - /SmallJson\(Number\(0\)\)/.test(String(variable.value)) - ), - "child task argument must come from the frozen node participant" - ); - - const parentScopesRequest = restartClient.send("scopes", { - frameId: failedStack[0].id, - }); - const parentScopes = ( - await restartClient.response(parentScopesRequest, "scopes") - ).body.scopes; - const parentArgsScope = parentScopes.find( - (scope) => scope.name === "Task Args and Handles" - ); - const parentArgsRequest = restartClient.send("variables", { - variablesReference: parentArgsScope.variablesReference, - }); - const parentArgs = ( - await restartClient.response(parentArgsRequest, "variables") - ).body.variables; - assert( - parentArgs.some( - (variable) => - /^task_handle_\d+$/.test(variable.name) && - /definition=task_trap instance=ti:.*:child:\d+ state=active/.test( - variable.value - ) && - variable.type === "runtime-handle" - ), - "parent task handle must come from its live Wasm host registry" - ); - - const continueChildRequest = restartClient.send("continue", { - threadId: childThread.id, - }); - await restartClient.response(continueChildRequest, "continue"); - await restartClient.waitFor( - (message) => - message.seq > childStop.seq && - message.type === "event" && - message.event === "terminated" - ); - - const terminalThreadsRequest = restartClient.send("threads"); - const terminalThreads = ( - await restartClient.response(terminalThreadsRequest, "threads") - ).body.threads; - assert.deepStrictEqual( - terminalThreads, - [], - "terminated processes must not retain stale virtual threads" - ); - - const restartRequest = restartClient.send("restartFrame", { - frameId: failedStack[0].id, - }); - const restartFailure = await restartClient.failure( - restartRequest, - "restartFrame" - ); - assert.match( - restartFailure.message, - /does not map to a virtual task/i, - "a frame from a terminated process must not restart a stale task" - ); - await restartClient.close(); - } catch (error) { - if (restartClient.child.exitCode === null) restartClient.child.kill("SIGKILL"); - throw error; - } - - console.log("DAP smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/deploy-release-candidate.sh b/scripts/deploy-release-candidate.sh deleted file mode 100755 index 8560767..0000000 --- a/scripts/deploy-release-candidate.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -manifest=${1:?usage: deploy-release-candidate.sh MANIFEST} -: "${CLUSTERFLUX_DEPLOY_COMMAND:?set the documented exact-candidate deployment command}" -: "${CLUSTERFLUX_STRICT_SSH_TARGET:?set the production SSH target}" - -service_unit=${CLUSTERFLUX_STRICT_SERVICE_UNIT:-clusterflux-hosted.service} -proxy_unit=${CLUSTERFLUX_STRICT_PROXY_UNIT:-nginx.service} -evidence_path=${CLUSTERFLUX_DEPLOYMENT_EVIDENCE_PATH:-target/acceptance/deployment.json} -staging=$(mktemp -d) -trap 'rm -rf "$staging"' EXIT - -IFS=$'\t' read -r archive expected_archive_sha < <( - node - "$manifest" <<'NODE' -const fs = require("fs"); -const path = require("path"); -const manifestPath = path.resolve(process.argv[2]); -const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); -const asset = (manifest.assets || []).find((entry) => entry.name.startsWith("clusterflux-hosted-")); -if (!asset) throw new Error("candidate manifest has no hosted archive"); -const file = path.isAbsolute(asset.file) - ? asset.file - : path.resolve(path.dirname(manifestPath), asset.file); -process.stdout.write(`${file}\t${asset.sha256}\n`); -NODE -) - -actual_archive_sha=$(sha256sum "$archive" | awk '{print $1}') -test "$actual_archive_sha" = "${expected_archive_sha#sha256:}" -tar -xzf "$archive" -C "$staging" -candidate_coordinator=$(find "$staging" -type f -name clusterflux-hosted-service -perm -u+x -print -quit) -test -n "$candidate_coordinator" -candidate_sha=$(sha256sum "$candidate_coordinator" | awk '{print $1}') - -export CLUSTERFLUX_CANDIDATE_ARCHIVE="$archive" -export CLUSTERFLUX_CANDIDATE_ARCHIVE_SHA256="sha256:$actual_archive_sha" -export CLUSTERFLUX_CANDIDATE_COORDINATOR="$candidate_coordinator" -export CLUSTERFLUX_CANDIDATE_COORDINATOR_SHA256="sha256:$candidate_sha" -bash -euo pipefail -c "$CLUSTERFLUX_DEPLOY_COMMAND" - -main_pid=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" systemctl show --property=MainPID --value "$service_unit") -test "$main_pid" != 0 -remote_executable=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" readlink -f "/proc/$main_pid/exe") -remote_sha=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" sha256sum "$remote_executable" | awk '{print $1}') -test "$remote_sha" = "$candidate_sha" -service_fragment=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" systemctl show --property=FragmentPath --value "$service_unit") -service_fragment_sha=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" sha256sum "$service_fragment" | awk '{print $1}') -service_configuration_sha=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" systemctl cat "$service_unit" | sha256sum | awk '{print $1}') -proxy_fragment=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" systemctl show --property=FragmentPath --value "$proxy_unit") -proxy_fragment_sha=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" sha256sum "$proxy_fragment" | awk '{print $1}') -proxy_exec_start=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" systemctl show --property=ExecStart --value "$proxy_unit") -proxy_executable=$(sed -n 's/.*path=\([^ ;]*\).*/\1/p' <<<"$proxy_exec_start") -proxy_configuration=$(sed -n 's/.* argv\[\]=.* -c \([^ ;]*\).*/\1/p' <<<"$proxy_exec_start") -test -n "$proxy_executable" -test -n "$proxy_configuration" -proxy_configuration_sha=$(ssh "$CLUSTERFLUX_STRICT_SSH_TARGET" "$proxy_executable" -T -c "$proxy_configuration" 2>/dev/null | sha256sum | awk '{print $1}') -mkdir -p "$(dirname "$evidence_path")" - -EVIDENCE_PATH="$evidence_path" SERVICE_UNIT="$service_unit" \ -SERVICE_FRAGMENT="$service_fragment" SERVICE_FRAGMENT_SHA="$service_fragment_sha" \ -SERVICE_CONFIGURATION_SHA="$service_configuration_sha" \ -REMOTE_EXECUTABLE="$remote_executable" REMOTE_SHA="$remote_sha" \ -PROXY_UNIT="$proxy_unit" PROXY_FRAGMENT="$proxy_fragment" \ -PROXY_FRAGMENT_SHA="$proxy_fragment_sha" PROXY_EXECUTABLE="$proxy_executable" \ -PROXY_CONFIGURATION="$proxy_configuration" PROXY_CONFIGURATION_SHA="$proxy_configuration_sha" node <<'NODE' -const fs = require("fs"); -fs.writeFileSync(process.env.EVIDENCE_PATH, JSON.stringify({ - kind: "clusterflux-exact-candidate-deployment", - service_unit: process.env.SERVICE_UNIT, - service_unit_fragment: process.env.SERVICE_FRAGMENT, - service_unit_sha256: `sha256:${process.env.SERVICE_FRAGMENT_SHA}`, - service_configuration_sha256: `sha256:${process.env.SERVICE_CONFIGURATION_SHA}`, - hosted_service_executable: process.env.REMOTE_EXECUTABLE, - hosted_service_sha256: `sha256:${process.env.REMOTE_SHA}`, - proxy_unit: process.env.PROXY_UNIT, - proxy_unit_fragment: process.env.PROXY_FRAGMENT, - proxy_unit_sha256: `sha256:${process.env.PROXY_FRAGMENT_SHA}`, - proxy_executable: process.env.PROXY_EXECUTABLE, - proxy_configuration: process.env.PROXY_CONFIGURATION, - proxy_configuration_sha256: `sha256:${process.env.PROXY_CONFIGURATION_SHA}`, -}, null, 2) + "\n"); -NODE diff --git a/scripts/flagship-demo-smoke.js b/scripts/flagship-demo-smoke.js deleted file mode 100644 index 98a43f2..0000000 --- a/scripts/flagship-demo-smoke.js +++ /dev/null @@ -1,80 +0,0 @@ -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const hello = path.join(repo, "examples/hello-build"); -const recovery = path.join(repo, "examples/recovery-build"); -const conformance = path.join(repo, "tests/fixtures/runtime-conformance"); -const source = fs.readFileSync(path.join(hello, "src/lib.rs"), "utf8"); -const nonblank = source.split(/\r?\n/).filter((line) => line.trim()).length; - -assert(nonblank <= 80, "hello-build source must stay below 80 nonblank lines"); -for (const forbidden of [ - "#[cfg", - "unsafe", - "extern \"C\"", - "no_mangle", - "sha256:", - ".task_id(", - "#[test]", - "unwrap()", - "expect(", -]) { - assert(!source.includes(forbidden), "hello-build leaked implementation detail: " + forbidden); -} -assert.strictEqual((source.match(/#\[clusterflux::task/g) || []).length, 1); -assert.strictEqual((source.match(/#\[clusterflux::main/g) || []).length, 1); -assert(source.includes("source::current_project().snapshot().await?")); -assert(source.includes("clusterflux::spawn!(compile(source))")); -assert(source.includes(".on(clusterflux::env!(\"linux\"))")); -assert(source.includes(".run()")); -assert(source.includes("fs::publish")); -assert(fs.existsSync(path.join(hello, "fixture/hello-clusterflux.c"))); -assert(fs.existsSync(path.join(hello, "envs/linux/Containerfile"))); - -const recoverySource = fs.readFileSync(path.join(recovery, "src/lib.rs"), "utf8"); -assert.strictEqual((recoverySource.match(/spawn!\(build_lane/g) || []).length, 2); -assert(recoverySource.includes("TaskFailurePolicy::AwaitOperator")); -assert(recoverySource.includes("\"exit 23\"")); -for (const forbidden of ["#[cfg", "unsafe", "extern \"C\"", "no_mangle", ".task_id("]) { - assert(!recoverySource.includes(forbidden), "recovery-build leaked " + forbidden); -} - -const fixtureSource = fs.readFileSync(path.join(conformance, "src/lib.rs"), "utf8"); -assert(fixtureSource.includes("task_trap")); -assert(fixtureSource.includes("cooperative_cancellation_probe")); -assert(!fs.existsSync(path.join(repo, "examples", "launch-" + "build-demo"))); -assert(!fs.existsSync(path.join(hello, "src/bin/sdk-product-runtime.rs"))); - -const args = [ - "run", - "-q", - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - "build", - "--project", - hello, - "--json", -]; -const report = JSON.parse(cp.execFileSync("cargo", args, { - cwd: repo, - env: process.env, - encoding: "utf8", -})); -assert(report.bundle_artifact); -assert(report.bundle.metadata.selected_inputs.some((input) => input.path === "src/lib.rs")); -assert(report.bundle.metadata.task_metadata.entrypoints.includes("build")); -const tasks = JSON.parse( - fs.readFileSync( - path.resolve(repo, report.bundle_artifact.directory, "task-descriptors.json"), - "utf8" - ) -); -assert(tasks.some((task) => task.name === "compile")); -assert(tasks.some((task) => task.name === "snapshot_current_project")); -console.log("primary and recovery example smoke passed"); diff --git a/scripts/hostile-input-contract-smoke.js b/scripts/hostile-input-contract-smoke.js deleted file mode 100644 index 8d5173a..0000000 --- a/scripts/hostile-input-contract-smoke.js +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -const { - agentIdentity, - signedAgentWorkflowRequest, -} = require("./agent-signing"); -const { - nodeIdentity, - signedNodeHeartbeat, -} = require("./node-signing"); - -const repo = path.resolve(__dirname, ".."); - -const signingInstrumentAgent = agentIdentity( - "hostile-input-contract-agent", - "agent-hostile-input-contract" -); -const explicitlyEmptyAgentNonce = signedAgentWorkflowRequest( - signingInstrumentAgent, - { - type: "start_process", - tenant: "tenant", - project: "project", - actor_agent: "agent-hostile-input-contract", - process: "process", - launch_attempt: "attempt", - restart: false, - }, - { nonce: "" } -); -assert.strictEqual( - explicitlyEmptyAgentNonce.agent_signature.nonce, - "", - "Agent signing instrument replaced an explicitly empty hostile nonce" -); -const signingInstrumentNode = nodeIdentity( - "hostile-input-contract-node", - "node-hostile-input-contract" -); -assert.strictEqual( - signedNodeHeartbeat( - "tenant", - "project", - "node-hostile-input-contract", - signingInstrumentNode, - { nonce: "" } - ).nonce, - "", - "Node signing instrument replaced an explicitly empty hostile nonce" -); - -function read(relativePath) { - return fs.readFileSync(path.join(repo, relativePath), "utf8"); -} - -function maybeRead(segments) { - const fullPath = path.join(repo, ...segments); - if (!fs.existsSync(fullPath)) return null; - return fs.readFileSync(fullPath, "utf8"); -} - -function expect(source, name, pattern) { - assert.match(source, pattern, `missing hostile-input evidence: ${name}`); -} - -const coreSource = read("crates/clusterflux-core/src/source.rs"); -const coreCapabilities = read("crates/clusterflux-core/src/capability.rs"); -const coordinatorService = [ - read("crates/clusterflux-coordinator/src/service.rs"), - read("crates/clusterflux-coordinator/src/service/routing.rs"), - read("crates/clusterflux-coordinator/src/service/signed_nodes.rs"), - read("crates/clusterflux-coordinator/src/service/logs.rs"), - read("crates/clusterflux-coordinator/src/service/tests.rs"), -].join("\n"); -const artifactDownloadSmoke = read("scripts/artifact-download-smoke.js"); -const operatorPanelSmoke = read("scripts/operator-panel-smoke.js"); -const schedulerSmoke = read("scripts/scheduler-placement-smoke.js"); -const sourcePreparationSmoke = read("scripts/source-preparation-smoke.js"); - -for (const [name, pattern] of [ - ["source manifests validate shape", /pub fn validate_public_mvp\(&self\)[\s\S]*self\.validate_shape\(\)\?/], - ["source manifests reject invalid digests", /SourceManifestError::InvalidDigest/], - ["source manifests reject invalid custom providers", /SourceManifestError::InvalidProviderId/], - ["source manifests reject control characters", /DescriptionControlCharacter/], - ["source manifests reject coordinator checkout access", /CoordinatorCheckoutAccess/], - ["source manifests reject default source-byte upload", /CoordinatorReceivesSourceBytes/], -]) { - expect(coreSource, name, pattern); -} - -for (const [name, pattern] of [ - ["capability reports validate public shape", /pub fn validate_public_report\(&self\)/], - ["capability reports validate architecture labels", /InvalidArchitecture/], - ["capability reports validate OS labels", /InvalidOsLabel/], - ["capability reports validate source providers", /InvalidSourceProvider/], - ["source provider ids reject path traversal", /valid_source_provider_id/], -]) { - expect(coreCapabilities, name, pattern); -} - -for (const [name, pattern] of [ - ["coordinator task log tails are bounded", /MAX_TASK_LOG_TAIL_BYTES: usize = 256 \* 1024/], - ["coordinator validates reported stdout tails", /ReportTaskLog[\s\S]*validate_task_log_tail\("stdout_tail", &stdout_tail\)\?/], - ["coordinator validates completed task stdout tails", /TaskCompleted[\s\S]*validate_task_log_tail\("stdout_tail", &stdout_tail\)\?/], - ["coordinator rejects oversized log tail in unit coverage", /"x"\.repeat\(MAX_TASK_LOG_TAIL_BYTES \+ 1\)/], -]) { - expect(coordinatorService, name, pattern); -} - -for (const [name, pattern] of [ - ["service rejects malformed node capability report", /fn service_rejects_malformed_node_capability_report\(\)/], - ["capability report rejection leaves descriptors empty", /assert!\(service\.node_descriptors\.is_empty\(\)\)/], - ["node capability report rejects cross-scope writes", /fn service_rejects_node_capability_report_outside_enrollment_scope\(\)/], - ["task completion rejects cross-scope writes", /task completion outside node scope|outside/], -]) { - expect(coordinatorService, name, pattern); -} - -for (const [name, source, patterns] of [ - [ - "artifact download smoke", - artifactDownloadSmoke, - [ - /const crossTenant = await send/, - /const crossProject = await send/, - /const guessed = await send/, - /const crossActorOpen = await send/, - /token is invalid/, - /artifact does not exist/, - ], - ], - [ - "operator panel smoke", - operatorPanelSmoke, - [ - /render_operator_panel/, - /submit_panel_event/, - /assert\(!JSON\.stringify\(panel\)\.includes\(" max_bytes[\s\S]*contains unsupported characters/], - ["tokens are bounded", /fn validate_token[\s\S]*value\.len\(\) > max_bytes[\s\S]*contains unsupported characters/], - ["control request bodies are bounded", /MAX_CONTROL_FRAME_BYTES[\s\S]*control request too large/], - ["identity protocol rejects unknown authority fields", /deny_unknown_fields/], - ]) { - expect(hostedService, name, pattern); - } - - for (const [name, pattern] of [ - ["old client identity protocol is rejected", /hosted_login_protocol_rejects_client_identity_and_provider_configuration/], - ["raw operator action is rejected", /rawOperatorDenied[\s\S]*hosted_operator_request envelope/], - ["unsigned client identity is rejected", /const forged = await sendHostedControl[\s\S]*authenticated CLI session/], - ["cross-tenant process inspection is rejected", /crossTenantTaskEventsDenied[\s\S]*scope\|denied\|unauthorized/], - ]) { - expect(hostedTests, name, pattern); - } -} - -console.log("Hostile input contract smoke passed"); diff --git a/scripts/migrate-clusterflux-state.sh b/scripts/migrate-clusterflux-state.sh deleted file mode 100755 index 356091d..0000000 --- a/scripts/migrate-clusterflux-state.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -migrate_path() { - local source="$1" - local destination="$2" - if [[ ! -e "$source" ]]; then - return - fi - if [[ -e "$destination" ]]; then - printf 'refusing to overwrite existing destination: %s\n' "$destination" >&2 - exit 1 - fi - mv -- "$source" "$destination" - printf 'migrated %s -> %s\n' "$source" "$destination" -} - -migrate_path "${HOME}/.disasmer" "${HOME}/.clusterflux" -migrate_path "${XDG_CONFIG_HOME:-${HOME}/.config}/disasmer" \ - "${XDG_CONFIG_HOME:-${HOME}/.config}/clusterflux" -migrate_path "${PWD}/.disasmer" "${PWD}/.clusterflux" -migrate_path "${PWD}/disasmer.toml" "${PWD}/clusterflux.toml" diff --git a/scripts/node-attach-smoke.js b/scripts/node-attach-smoke.js deleted file mode 100755 index c7c9dc2..0000000 --- a/scripts/node-attach-smoke.js +++ /dev/null @@ -1,307 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); - -const repo = path.resolve(__dirname, ".."); -const identities = new Map(); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function nodeIdentity(node) { - const existing = identities.get(node); - if (existing) return existing; - const { privateKey: privateKeyObject, publicKey } = - crypto.generateKeyPairSync("ed25519"); - const privateDer = privateKeyObject.export({ format: "der", type: "pkcs8" }); - const publicDer = publicKey.export({ - format: "der", - type: "spki", - }); - const privateSeed = Buffer.from(privateDer).subarray(-32); - const identity = { - privateKey: `ed25519:${privateSeed.toString("base64")}`, - publicKey: `ed25519:${Buffer.from(publicDer).subarray(-32).toString("base64")}`, - privateKeyObject, - }; - identities.set(node, identity); - return identity; -} - -function nodeSignatureMessage( - node, - requestKind, - payloadDigest, - nonce, - issuedAtEpochSeconds -) { - const parts = [ - "clusterflux-node-request-signature:v2", - node, - requestKind, - payloadDigest, - nonce, - String(issuedAtEpochSeconds), - ]; - return Buffer.concat( - parts.flatMap((part) => [ - Buffer.from(`${Buffer.byteLength(part)}:`), - Buffer.from(part), - Buffer.from("\n"), - ]) - ); -} - -function signedNodeHeartbeat(tenant, project, node, identity) { - const nonce = `node-attach-heartbeat-${process.pid}-${Date.now()}`; - const issuedAt = Math.floor(Date.now() / 1000); - const payloadDigest = `sha256:${crypto - .createHash("sha256") - .update(JSON.stringify({ node, project, tenant, type: "node_heartbeat" })) - .digest("hex")}`; - const signature = crypto.sign( - null, - nodeSignatureMessage(node, "node_heartbeat", payloadDigest, nonce, issuedAt), - identity.privateKeyObject - ); - return { - nonce, - issued_at_epoch_seconds: issuedAt, - signature: `ed25519:${signature.toString("base64")}`, - }; -} - -function runAttach(addr, grant) { - const identity = nodeIdentity("node-attach"); - return new Promise((resolve, reject) => { - const child = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - "node", - "attach", - "--coordinator", - `${addr.host}:${addr.port}`, - "--tenant", - "tenant", - "--project-id", - "project", - "--node", - "node-attach", - "--public-key", - identity.publicKey, - "--enrollment-grant", - grant, - "--cap", - "quic-direct", - "--json", - ], - { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_NODE_PRIVATE_KEY: identity.privateKey, - }, - } - ); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.on("exit", (code) => { - if (code !== 0) { - reject(new Error(`node attach failed with code ${code}\n${stderr}`)); - return; - } - try { - resolve(JSON.parse(stdout)); - } catch (error) { - reject( - new Error(`node attach output was not JSON: ${stdout}\n${error.stack || error.message}`) - ); - } - }); - }); -} - -(async () => { - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback", - ], - { cwd: repo } - ); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const grant = await send(addr, { - type: "create_node_enrollment_grant", - tenant: "tenant", - project: "project", - actor_user: "operator", - ttl_seconds: 900 - }); - assert.strictEqual(grant.type, "node_enrollment_grant_created"); - assert.strictEqual(grant.tenant, "tenant"); - assert.strictEqual(grant.project, "project"); - assert.match(grant.grant, /^node_grant_[A-Za-z0-9_-]+$/); - assert.strictEqual(grant.scope, "node:attach"); - assert(grant.expires_at_epoch_seconds > Math.floor(Date.now() / 1000)); - assert(grant.expires_at_epoch_seconds <= Math.floor(Date.now() / 1000) + 900); - - const report = await runAttach(addr, grant.grant); - assert.strictEqual(report.plan.node, "node-attach"); - assert.strictEqual(report.plan.coordinator, `${addr.host}:${addr.port}`); - assert.strictEqual(report.plan.enrollment.grant, grant.grant); - assert.match(report.plan.enrollment.public_key_fingerprint, /^sha256:[0-9a-f]{64}$/); - assert.strictEqual( - report.plan.enrollment.exchanges_short_lived_grant_for_long_lived_node_identity, - true - ); - assert.ok(report.plan.capabilities.arch.length > 0); - assert.ok(report.plan.capabilities.source_providers.includes("filesystem")); - assert.ok(report.plan.capabilities.capabilities.includes("QuicDirect")); - assert.strictEqual(report.plan.detection.auto_detected, true); - assert.strictEqual(report.plan.detection.arch, report.plan.capabilities.arch); - assert.deepStrictEqual(report.plan.detection.manual_capability_overrides, ["quic-direct"]); - assert( - report.plan.detection.recognized_capability_overrides.includes("QuicDirect") - ); - assert.strictEqual( - report.plan.detection.os_arch_capabilities_require_manual_flags, - false - ); - assert.strictEqual(report.plan.detection.command_backend, "native-command"); - assert.strictEqual(report.plan.detection.command_backend_available, true); - assert( - report.plan.detection.source_provider_backends.some( - (provider) => provider.provider === "filesystem" && provider.detected - ) - ); - assert( - report.grant_disclosures.length > 0, - "node attach should disclose capability grants before reporting capabilities" - ); - assert( - report.grant_disclosures.every( - (disclosure) => disclosure.coordinator_policy_limited === true - ), - "node attach should mark all capability grants as coordinator-policy-limited" - ); - assert( - report.grant_disclosures.some( - (disclosure) => disclosure.grant === "native_command_execution" - ), - "node attach should disclose native command execution when detected" - ); - assert( - report.grant_disclosures.some( - (disclosure) => disclosure.grant === "source_access" - ), - "node attach should disclose source access when detected" - ); - assert.strictEqual(report.boundary.cli_contacted_coordinator, true); - assert.strictEqual(report.boundary.used_enrollment_exchange, true); - assert.strictEqual(report.boundary.coordinator_session_requests, 3); - assert.strictEqual(report.coordinator_response.type, "node_enrollment_exchanged"); - assert.strictEqual(report.coordinator_response.node, "node-attach"); - assert.strictEqual(report.coordinator_response.credential.node, "node-attach"); - assert.strictEqual(report.coordinator_response.credential.scope, "node:attach"); - assert.strictEqual(report.coordinator_response.credential.credential_kind, "NodeCredential"); - assert.match( - report.coordinator_response.credential.capability_policy_digest, - /^sha256:[0-9a-f]{64}$/ - ); - assert.strictEqual(report.heartbeat_response.type, "node_heartbeat"); - assert.strictEqual(report.capability_response.type, "node_capabilities_recorded"); - - const heartbeat = await send(addr, { - type: "node_heartbeat", - tenant: "tenant", - project: "project", - node: "node-attach", - node_signature: signedNodeHeartbeat( - "tenant", - "project", - "node-attach", - nodeIdentity("node-attach") - ), - }); - assert.strictEqual(heartbeat.type, "node_heartbeat"); - assert.strictEqual(heartbeat.node, "node-attach"); - - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("Node attach smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/node-lifecycle-contract-smoke.js b/scripts/node-lifecycle-contract-smoke.js deleted file mode 100755 index 78d4387..0000000 --- a/scripts/node-lifecycle-contract-smoke.js +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); - -function read(relativePath) { - return fs.readFileSync(path.join(repo, relativePath), "utf8"); -} - -function expect(source, name, pattern) { - assert.match(source, pattern, `missing node lifecycle evidence: ${name}`); -} - -const nodeMain = read("crates/clusterflux-node/src/daemon.rs"); -const nodeIdentity = read("crates/clusterflux-node/src/node_identity.rs"); -const cliNode = read("crates/clusterflux-cli/src/node.rs"); -const nodeTaskReports = read("crates/clusterflux-node/src/task_reports.rs"); -const nodeDebugAgent = read("crates/clusterflux-node/src/debug_agent.rs"); -const nodeLib = read("crates/clusterflux-node/src/lib.rs"); -const sharedWasmtimeRuntime = `${read("crates/clusterflux-wasm-runtime/src/lib.rs")}\n${read("crates/clusterflux-wasm-runtime/src/task_host_linker.rs")}`; -const nodeRuntimeSurface = `${nodeLib}\n${sharedWasmtimeRuntime}`; -const nodeLifecycleSurface = `${nodeMain}\n${nodeIdentity}\n${nodeTaskReports}\n${nodeDebugAgent}`; -const nodeAssignmentRunner = `${read("crates/clusterflux-node/src/assignment_runner.rs")}\n${read("crates/clusterflux-node/src/assignment_runner/control_watcher.rs")}\n${read("crates/clusterflux-node/src/assignment_runner/process_runner.rs")}\n${read("crates/clusterflux-node/src/assignment_runner/validation.rs")}`; -const coordinatorCore = read("crates/clusterflux-coordinator/src/lib.rs"); -const coordinatorService = `${read("crates/clusterflux-coordinator/src/service.rs")}\n${read("crates/clusterflux-coordinator/src/service/routing.rs")}`; -const coordinatorServiceTests = read("crates/clusterflux-coordinator/src/service/tests.rs"); -const coordinatorServiceSurface = `${coordinatorService}\n${coordinatorServiceTests}`; -const cliLocalRunSmoke = read("scripts/cli-local-run-smoke.js"); -const liveSmoke = read("scripts/cli-happy-path-live-smoke.js"); -const wasmtimeSmoke = read("scripts/wasmtime-node-smoke.js"); -const debugCore = read("crates/clusterflux-core/src/debug.rs"); - -assert.strictEqual( - (nodeMain.match(/CoordinatorSession::connect/g) || []).length, - 1, - "node runtime should open one coordinator session in the local process-boundary runtime" -); - -for (const [name, pattern] of [ - ["enrollment exchange over session", /"type": "exchange_node_enrollment_grant"/], - ["persisted node identity is reused locally", /"type": "node_identity_reused"/], - ["heartbeat over session", /"type": "node_heartbeat"/], - ["node-originated requests use signed envelope", /"type": "signed_node"/], - ["capability report over session", /"type": "report_node_capabilities"/], - ["task assignment polling over session", /"type": "poll_task_assignment"/], - ["process start over session", /"type": "start_process"/], - ["reconnect over session", /"type": "reconnect_node"/], - ["debug command polling over session", /"type": "poll_debug_command"/], - ["log event over session", /"type": "report_task_log"/], - ["VFS metadata over session", /"type": "report_vfs_metadata"/], - ["task control polling over session", /"type": "poll_task_control"/], - ["completion over session", /"type": "task_completed"/], - ["cancellation uses same session", /poll_task_cancellation\(session, args, &task, node_private_key\)/], - ["request count is reported", /session\.requests\(\)/], -]) { - expect(nodeLifecycleSurface, name, pattern); -} - -expect(cliNode, "user-authorized node attach over Client session", /"type": "attach_node"/); -assert.doesNotMatch( - nodeIdentity, - /"type": "attach_node"/, - "a persisted node must authenticate with its signed identity instead of replaying Client attach" -); - -const runtimeAcceptanceSurface = `${cliLocalRunSmoke}\n${liveSmoke}\n${coordinatorServiceTests}\n${nodeLib}\n${nodeAssignmentRunner}`; -for (const [name, pattern] of [ - ["real CLI launches a coordinator main", /node_report\.run\.status, "main_launched"/], - ["real CLI observes coordinator-main task spawning", /task_spawn_host_import, true/], - ["real CLI keeps child task instances distinct", /every live task event must retain its unique instance identity/], - ["signed active Wasm parent spawns and joins child", /fn signed_active_wasm_task_can_spawn_and_join_child_in_its_process_only\(\)/], - ["controlled native process abort is exercised", /fn abort_requested[\s\S]*poll_task_control/], - ["native lifecycle freeze and resume are exercised", /linux_task_lifecycle_supports_cancel_and_all_stop_freeze_resume/], - ["strict live run requires a usable partial freeze", /partial_freeze\.partially_frozen/], - ["strict live run requires hosted restart evidence", /serviceRestart\.executed === true/], -]) { - expect(runtimeAcceptanceSurface, name, pattern); -} - -for (const [name, pattern] of [ - ["cooperative cancellation and abort are distinct", /cancel_requested: false,[\s\S]*abort_requested: true/], - ["controlled runner polls abort while command runs", /fn abort_requested[\s\S]*poll_task_control/], - ["controlled runner creates a process group", /process\.process_group\(0\)/], - ["controlled runner freezes the native process group", /libc::kill\(process_group, libc::SIGSTOP\)/], - ["controlled runner resumes the native process group", /libc::kill\(process_group, libc::SIGCONT\)/], - ["controlled runner kills the process group", /libc::kill\(process_group, libc::SIGKILL\)/], - ["Wasm code can poll cooperative cancellation", /task_control_v1/], - ["matched Wasm probes remain at a quiescent boundary", /TaskHostOperation::DebugProbe[\s\S]*enter_quiescent_host_boundary[\s\S]*leave_quiescent_host_boundary/], - ["debug snapshots use the live Wasm task handle registry", /debug_handle_snapshot[\s\S]*task_handle_\{handle_id\}[\s\S]*state=active/], - ["native command status comes from the controlled runner", /set_command_status[\s\S]*frozen command pid[\s\S]*native command exited with status/], -]) { - expect(`${coordinatorServiceSurface}\n${nodeLifecycleSurface}\n${sharedWasmtimeRuntime}\n${nodeAssignmentRunner}`, name, pattern); -} - -for (const [name, pattern] of [ - ["coordinator rejects stale process ownership", /fn node_reconnect_rejects_stale_process_epoch_after_restart\(\)/], - ["reconnect preserves scoped enrolled node identity", /reconnect_node\([\s\S]*&TenantId::from\("tenant"\),[\s\S]*&ProjectId::from\("project"\),[\s\S]*&NodeId::from\("node"\),[\s\S]*None/], - ["stale process epoch is rejected", /CoordinatorError::StaleProcessEpoch/], -]) { - expect(coordinatorCore, name, pattern); -} - -for (const [name, pattern] of [ - ["coordinator delivers cancellation to connected node", /fn service_delivers_cancellation_to_connected_node_and_records_terminal_state\(\)/], - ["node polls task control", /CoordinatorRequest::PollTaskControl/], - ["cancelled terminal state is recorded", /TaskTerminalState::Cancelled/], -]) { - expect(coordinatorServiceSurface, name, pattern); -} - -for (const [name, pattern] of [ - ["native lifecycle test exists", /fn linux_task_lifecycle_supports_cancel_and_all_stop_freeze_resume\(\)/], - ["native freeze succeeds when supported", /lifecycle\.freeze_for_debug_epoch\(\)\.unwrap\(\)/], - ["native resume succeeds", /lifecycle\.resume_after_debug_epoch\(\)/], - ["native cancel reaches lifecycle", /lifecycle\.cancel\(\)/], - ["unsupported freeze errors", /BackendError::DebugFreezeUnsupported/], - ["wasmtime runtime exposes freeze resume probe", /pub fn freeze_resume_i32_export_probe/], - ["wasmtime runtime captures Wasm frame locals", /debug_i32_export_snapshot[\s\S]*local_values/], - ["wasmtime runtime creates Wasm debug participant", /kind: DebugParticipantKind::WasmTask/], - ["wasmtime debug participant carries local values", /local_values: snapshot\.local_values\.clone\(\)/], - ["wasmtime runtime resumes after freeze", /epoch\.continue_all\(\)/], -]) { - expect(nodeRuntimeSurface, name, pattern); -} - -for (const [name, pattern] of [ - ["wasmtime smoke runs debug freeze resume mode", /--debug-freeze-resume/], - ["wasmtime smoke verifies frozen state", /debugReport\.frozen_state, "Frozen"/], - ["wasmtime smoke verifies resumed state", /debugReport\.resumed_state, "Running"/], - ["wasmtime smoke verifies frame local values", /debugReport\.local_values[\s\S]*wasm_local_0/], - ["wasmtime smoke proves node runtime reached wasm task", /node_runtime_reached_wasm_task/], - ["wasmtime smoke proves node captured locals", /node_runtime_captured_wasm_locals/], -]) { - expect(wasmtimeSmoke, name, pattern); -} - -for (const [name, pattern] of [ - ["debug model freezes wasm and command participants", /fn breakpoint_creates_all_stop_debug_epoch_for_wasm_and_command_tasks\(\)/], - ["debug model rejects unsupported freeze", /fn debug_epoch_reports_failure_when_no_participant_can_freeze\(\)/], - ["debug model resumes frozen participants", /fn continue_resumes_every_frozen_participant\(\)/], - ["debug model includes captured locals", /local_values/], - ["wasm participants are modeled", /DebugParticipantKind::WasmTask/], - ["controlled native command participants are modeled", /DebugParticipantKind::ControlledNativeCommand/], -]) { - expect(debugCore, name, pattern); -} - -console.log("Node lifecycle contract smoke passed"); diff --git a/scripts/node-signing.js b/scripts/node-signing.js deleted file mode 100644 index 3069840..0000000 --- a/scripts/node-signing.js +++ /dev/null @@ -1,181 +0,0 @@ -const crypto = require("crypto"); -const identities = new Map(); - -function nodeIdentity(identityPurpose, node) { - const identityKey = `${identityPurpose}:${node}`; - const existing = identities.get(identityKey); - if (existing) return existing; - const { privateKey: privateKeyObject, publicKey } = - crypto.generateKeyPairSync("ed25519"); - const privateDer = privateKeyObject.export({ format: "der", type: "pkcs8" }); - const publicDer = publicKey.export({ - format: "der", - type: "spki", - }); - const privateSeed = Buffer.from(privateDer).subarray(-32); - const identity = { - privateKey: `ed25519:${privateSeed.toString("base64")}`, - publicKey: `ed25519:${Buffer.from(publicDer).subarray(-32).toString("base64")}`, - privateKeyObject, - }; - identities.set(identityKey, identity); - return identity; -} - -function nodeIdentityFromPrivateKey(privateKey) { - if (typeof privateKey !== "string" || !privateKey.startsWith("ed25519:")) { - throw new Error("node private key must use ed25519: encoding"); - } - const seed = Buffer.from(privateKey.slice("ed25519:".length), "base64"); - if (seed.length !== 32) throw new Error("node private key must contain 32 bytes"); - const privateKeyObject = crypto.createPrivateKey({ - key: Buffer.concat([ - Buffer.from("302e020100300506032b657004220420", "hex"), - seed, - ]), - format: "der", - type: "pkcs8", - }); - const publicKeyObject = crypto.createPublicKey(privateKeyObject); - const publicDer = publicKeyObject.export({ format: "der", type: "spki" }); - return { - privateKey, - publicKey: `ed25519:${Buffer.from(publicDer).subarray(-32).toString("base64")}`, - privateKeyObject, - }; -} - -function canonicalSignedRequest(value, topLevel = true) { - if (Array.isArray(value)) { - return value.map((entry) => canonicalSignedRequest(entry, false)); - } - if (value && typeof value === "object") { - return Object.fromEntries( - Object.entries(value) - .filter( - ([key, entry]) => - entry !== null && - (!topLevel || !["agent_signature", "node_signature"].includes(key)) - ) - .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) - .map(([key, entry]) => [key, canonicalSignedRequest(entry, false)]) - ); - } - return value; -} - -function withWireDefaults(request) { - const value = { ...request }; - if (value.type === "report_node_capabilities") { - value.dependency_cache_digests ??= []; - } else if (value.type === "launch_task" || value.type === "launch_child_task") { - value.wait_for_node ??= false; - if (value.task_spec && typeof value.task_spec === "object") { - value.task_spec = { ...value.task_spec }; - value.task_spec.failure_policy ??= "fail_fast"; - } - } else if (value.type === "start_process") { - value.restart ??= false; - } else if (value.type === "report_debug_state") { - value.stack_frames ??= []; - value.local_values ??= []; - value.task_args ??= []; - value.handles ??= []; - value.recent_output ??= []; - } else if (value.type === "report_task_log") { - value.stdout_tail ??= ""; - value.stderr_tail ??= ""; - } else if (value.type === "task_completed") { - value.stdout_tail ??= ""; - value.stderr_tail ??= ""; - value.stdout_truncated ??= false; - value.stderr_truncated ??= false; - } - return value; -} - -function signedRequestPayloadDigest(request) { - return `sha256:${crypto - .createHash("sha256") - .update(JSON.stringify(canonicalSignedRequest(withWireDefaults(request)))) - .digest("hex")}`; -} - -function nodeSignatureMessage( - node, - requestKind, - payloadDigest, - nonce, - issuedAtEpochSeconds -) { - const parts = [ - "clusterflux-node-request-signature:v2", - node, - requestKind, - payloadDigest, - nonce, - String(issuedAtEpochSeconds), - ]; - return Buffer.concat( - parts.flatMap((part) => [ - Buffer.from(`${Buffer.byteLength(part)}:`), - Buffer.from(part), - Buffer.from("\n"), - ]) - ); -} - -function signedNodeProof(node, identity, requestKind, request, options = {}) { - const nonce = - options.nonce ?? - `${requestKind}-${process.pid}-${Date.now()}-${crypto - .randomBytes(8) - .toString("hex")}`; - const issuedAt = - options.issuedAtEpochSeconds ?? Math.floor(Date.now() / 1000); - const signature = crypto.sign( - null, - nodeSignatureMessage( - node, - requestKind, - signedRequestPayloadDigest(request), - nonce, - issuedAt - ), - identity.privateKeyObject - ); - return { - nonce, - issued_at_epoch_seconds: issuedAt, - signature: `ed25519:${signature.toString("base64")}`, - }; -} - -function signedNodeHeartbeat(tenant, project, node, identity, options = {}) { - const request = { type: "node_heartbeat", tenant, project, node }; - return signedNodeProof(node, identity, "node_heartbeat", request, options); -} - -function signedNodeRequest(node, identity, requestKind, request, options = {}) { - return { - type: "signed_node", - node, - node_signature: signedNodeProof( - node, - identity, - requestKind, - request, - options - ), - request, - }; -} - -module.exports = { - nodeIdentity, - nodeIdentityFromPrivateKey, - signedNodeProof, - signedRequestPayloadDigest, - signedNodeHeartbeat, - signedNodeRequest, -}; diff --git a/scripts/operator-panel-smoke.js b/scripts/operator-panel-smoke.js deleted file mode 100755 index b817c42..0000000 --- a/scripts/operator-panel-smoke.js +++ /dev/null @@ -1,385 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const path = require("path"); -const { nodeIdentity } = require("./node-signing"); -const { - ensureRootlessPodman, - repo, - runFlagshipWorker, - send, - startFlagship, - waitForTaskEvent, - waitForJsonLine, - waitForNodeStatus, -} = require("./real-flagship-harness"); - -const panelNode = "panel-node"; -const panelNodeIdentity = nodeIdentity("operator-panel-smoke", panelNode); -const panelProject = path.join(repo, "tests/fixtures/runtime-conformance"); - -function widget(panel, id) { - const item = panel.widgets[id]; - assert(item, `missing panel widget ${id}`); - return item; -} - -const delay = (milliseconds) => - new Promise((resolve) => setTimeout(resolve, milliseconds)); - -async function waitForBreakpointHit(addr, process) { - for (let attempt = 0; attempt < 2400; attempt += 1) { - const status = await send(addr, { - type: "inspect_debug_breakpoints", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - }); - if (status.type !== "debug_breakpoints") { - const events = await send(addr, { - type: "list_task_events", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - }); - throw new Error( - `breakpoint state disappeared: ${JSON.stringify({ status, events })}` - ); - } - if (status.hit_epoch != null) return status; - await delay(25); - } - throw new Error(`timed out waiting for package breakpoint in ${process}`); -} - -async function waitForDebugEpochFrozen(addr, process, epoch) { - for (let attempt = 0; attempt < 2400; attempt += 1) { - const status = await send(addr, { - type: "inspect_debug_epoch", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - epoch, - }); - assert.strictEqual(status.type, "debug_epoch_status", JSON.stringify(status)); - if (status.failed) { - throw new Error(status.failure_messages.join("; ")); - } - if (status.fully_frozen) return status; - await delay(25); - } - throw new Error(`timed out waiting for debug epoch ${epoch} to freeze`); -} - -(async () => { - ensureRootlessPodman(); - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - let coordinatorStderr = ""; - let worker; - coordinator.stderr.on("data", (chunk) => { - coordinatorStderr += chunk.toString(); - }); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - const projectCreated = await send(addr, { - type: "create_project", - tenant: "tenant", - actor_user: "user", - project: "project", - name: "Operator panel smoke", - }); - assert.strictEqual(projectCreated.type, "project_created"); - - worker = await runFlagshipWorker( - addr, - panelNode, - panelNodeIdentity, - panelProject - ); - const workerReady = await worker.ready; - assert.strictEqual(workerReady.node_status, "ready"); - const workerCompletion = waitForNodeStatus(worker.child, "completed"); - const flagship = startFlagship(addr, panelProject); - const configuredBreakpoints = await send(addr, { - type: "set_debug_breakpoints", - tenant: "tenant", - project: "project", - actor_user: "user", - process: flagship.process, - probe_symbols: ["clusterflux.probe.package_release"], - }); - assert.strictEqual(configuredBreakpoints.type, "debug_breakpoints"); - await waitForTaskEvent( - addr, - flagship.process, - (event) => event.task_definition === "prepare_source", - "prepare_source after breakpoint configuration" - ); - const breakpointHit = await waitForBreakpointHit(addr, flagship.process); - assert.strictEqual( - breakpointHit.hit_probe_symbol, - "clusterflux.probe.package_release" - ); - const frozenEpoch = await waitForDebugEpochFrozen( - addr, - flagship.process, - breakpointHit.hit_epoch - ); - assert(frozenEpoch.acknowledgements.length >= 2); - const compileEvent = await waitForTaskEvent( - addr, - flagship.process, - (event) => event.task_definition === "compile_linux", - "compile before the package breakpoint" - ); - const report = await workerCompletion; - assert.strictEqual(report.node_status, "completed"); - assert.strictEqual(report.coordinator_response.type, "task_recorded"); - const process = flagship.process; - - const rendered = await send(addr, { - type: "render_operator_panel", - tenant: "tenant", - project: "project", - process, - actor_user: "user", - max_download_bytes: 1024 * 1024, - stopped: false - }); - assert.strictEqual(rendered.type, "operator_panel"); - const panel = rendered.panel; - assert.strictEqual(panel.tenant, "tenant"); - assert.strictEqual(panel.project, "project"); - assert.strictEqual(panel.process, process); - assert.strictEqual(panel.program_ui_events_enabled, true); - - assert.deepStrictEqual(widget(panel, "process-status").kind, { - Text: { value: "running" } - }); - const taskProgress = widget(panel, "task-progress").kind.Progress; - assert(taskProgress.current >= 2); - assert.strictEqual(taskProgress.current, taskProgress.total); - const taskSummary = widget(panel, "task-summary").kind.Text.value; - assert.match( - taskSummary, - new RegExp(`compile_linux \\[${compileEvent.task}\\]:Some\\(0\\):panel-node`) - ); - assert.match(widget(panel, "recent-logs").kind.Text.value, /stdout=\d+ stderr=\d+/); - const downloadWidget = widget(panel, "download-artifact").kind; - const artifact = downloadWidget.ArtifactDownload.artifact; - assert( - artifact === compileEvent.artifact_path.slice("/vfs/artifacts/".length), - "panel download must point at a real flagship artifact" - ); - assert(!JSON.stringify(downloadWidget).includes("url_path")); - assert(!JSON.stringify(downloadWidget).includes("scoped_token_digest")); - assert.deepStrictEqual(widget(panel, "debug-process").kind, { - Button: { action: "debug-process" } - }); - assert.deepStrictEqual(widget(panel, "cancel-process").kind, { - Button: { action: "cancel-process" } - }); - assert.deepStrictEqual(widget(panel, "restart-selected-task").kind, { - Button: { action: "restart-task" } - }); - assert(panel.control_plane_actions.includes("DebugProcess")); - assert(panel.control_plane_actions.includes("CancelProcess")); - const restartTarget = panel.control_plane_actions.find( - (action) => action.RestartTask - )?.RestartTask; - assert( - restartTarget && taskSummary.includes(`[${restartTarget}]`), - "panel restart must target the real flagship task instance" - ); - assert( - panel.control_plane_actions.some( - (action) => action.DownloadArtifact === artifact - ) - ); - assert(!JSON.stringify(panel).includes(" action.DownloadArtifact === artifact - ) - ); - - const frozenEvent = await send(addr, { - type: "submit_panel_event", - tenant: "tenant", - project: "project", - process, - widget_id: "debug-process", - kind: "ButtonClicked", - max_events: 10 - }); - assert.strictEqual(frozenEvent.type, "error"); - assert.match(frozenEvent.message, /program UI events are disabled/i); - - const crossTenant = await send(addr, { - type: "render_operator_panel", - tenant: "other", - project: "project", - process, - actor_user: "user", - max_download_bytes: 1024 * 1024, - stopped: false - }); - assert.strictEqual(crossTenant.type, "error"); - assert.match( - crossTenant.message, - /scope|tenant|project|requires an active virtual process/i - ); - assert(!crossTenant.message.includes(process)); - - const resumed = await send(addr, { - type: "resume_debug_epoch", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - epoch: breakpointHit.hit_epoch, - }); - assert.strictEqual(resumed.type, "debug_epoch"); - const cleanup = await send(addr, { - type: "abort_process", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - }); - assert.strictEqual(cleanup.type, "process_aborted"); - } catch (error) { - if (coordinatorStderr) { - error.message = `${error.message}\ncoordinator stderr:\n${coordinatorStderr}`; - } - throw error; - } finally { - worker?.child.kill("SIGTERM"); - coordinator.kill("SIGTERM"); - } - - console.log("Operator panel smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/podman-backend-smoke.js b/scripts/podman-backend-smoke.js deleted file mode 100755 index 438c2df..0000000 --- a/scripts/podman-backend-smoke.js +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const path = require("path"); -const { configurePodmanTestEnvironment } = require("./podman-test-env"); - -const repo = path.resolve(__dirname, ".."); -const baseImage = "docker.io/library/alpine:3.20"; - -// Nix's standalone Podman package may not install the distribution-level -// containers/image policy normally found under /etc. Use an isolated test HOME -// without replacing a policy supplied by the host. -configurePodmanTestEnvironment(repo); - -function run(command, args, options = {}) { - return cp.execFileSync(command, args, { - cwd: repo, - encoding: "utf8", - stdio: options.stdio || ["ignore", "pipe", "pipe"], - }); -} - -function incomplete(reason) { - const error = new Error(`Linux Podman backend incomplete: ${reason}`); - error.code = "CLUSTERFLUX_PODMAN_INCOMPLETE"; - throw error; -} - -function ensurePodmanBaseImage() { - try { - run("podman", ["--version"]); - } catch (error) { - incomplete(`podman command is unavailable (${error.message})`); - } - - let rootless; - try { - rootless = run("podman", ["info", "--format", "{{.Host.Security.Rootless}}"]).trim(); - } catch (error) { - incomplete(`podman info did not report rootless status (${error.message})`); - } - if (rootless !== "true") { - incomplete(`podman is not running in rootless mode (reported ${JSON.stringify(rootless)})`); - } - - try { - run("podman", ["image", "exists", baseImage]); - } catch (_) { - try { - run("podman", ["pull", baseImage], { stdio: "inherit" }); - } catch (error) { - incomplete(`unable to make ${baseImage} available (${error.message})`); - } - } -} - -try { - ensurePodmanBaseImage(); - - const stdout = run("cargo", [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-podman-smoke" - ]); - const report = JSON.parse(stdout.trim().split("\n").at(-1)); - - assert.strictEqual(report.podman_status, "completed"); - assert.strictEqual(report.status_code, 0); - assert.strictEqual(report.stdout, "podman-ok:node-local source\n"); - assert.strictEqual(report.large_bytes_uploaded, false); - assert.strictEqual(report.uses_full_repo_tarball, false); - assert.strictEqual(report.coordinator_routed_file_reads, false); - assert.strictEqual(report.staged_artifact.path, "/vfs/artifacts/podman-smoke.txt"); - - console.log("Podman backend smoke passed"); -} catch (error) { - if (error.code === "CLUSTERFLUX_PODMAN_INCOMPLETE") { - console.error(error.message); - process.exit(2); - } - throw error; -} diff --git a/scripts/podman-test-env.js b/scripts/podman-test-env.js deleted file mode 100644 index 2c0dc3b..0000000 --- a/scripts/podman-test-env.js +++ /dev/null @@ -1,41 +0,0 @@ -const fs = require("fs"); -const os = require("os"); -const path = require("path"); - -function configurePodmanTestEnvironment(repo) { - const originalHome = os.homedir(); - if ( - fs.existsSync(path.join(originalHome, ".config/containers/policy.json")) || - fs.existsSync("/etc/containers/policy.json") - ) { - return; - } - - const isolatedHome = path.join(repo, "scripts/containers-home"); - const policy = path.join(isolatedHome, ".config/containers/policy.json"); - fs.mkdirSync(path.dirname(policy), { recursive: true }); - if (!fs.existsSync(policy)) { - fs.writeFileSync( - policy, - `${JSON.stringify( - { default: [{ type: "insecureAcceptAnything" }] }, - null, - 2 - )}\n` - ); - } - - process.env.CARGO_HOME ||= path.join(originalHome, ".cargo"); - process.env.RUSTUP_HOME ||= path.join(originalHome, ".rustup"); - process.env.HOME = isolatedHome; - process.env.XDG_DATA_HOME = path.join( - os.tmpdir(), - `clusterflux-containers-data-${process.getuid?.() ?? "user"}` - ); - process.env.XDG_CACHE_HOME = path.join( - os.tmpdir(), - `clusterflux-containers-cache-${process.getuid?.() ?? "user"}` - ); -} - -module.exports = { configurePodmanTestEnvironment }; diff --git a/scripts/prepare-public-release.js b/scripts/prepare-public-release.js deleted file mode 100755 index 27fa754..0000000 --- a/scripts/prepare-public-release.js +++ /dev/null @@ -1,1283 +0,0 @@ -#!/usr/bin/env node - -const crypto = require("crypto"); -const cp = require("child_process"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const outputRoot = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_DIR || - path.join(repo, "target/public-release") -); -const publicTree = path.join(outputRoot, "public-tree"); -const assetsDir = path.join(outputRoot, "assets"); -const stagingDir = path.join(outputRoot, "staging"); -const publicBuildTarget = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_BUILD_TARGET_DIR || - path.join(outputRoot, "cargo-target") -); -const hostedBuildTarget = path.resolve( - process.env.CLUSTERFLUX_HOSTED_BUILD_TARGET_DIR || - path.join(outputRoot, "hosted-cargo-target") -); -const candidateManifestPath = process.env.CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST - ? path.resolve(process.env.CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST) - : null; -const defaultHostedCoordinatorEndpoint = "https://clusterflux.michelpaulissen.com"; -const forgejoHost = "git.michelpaulissen.com"; -const args = new Set(process.argv.slice(2)); -const includeForgejoWorkflows = - args.has("--include-forgejo-workflows") || - /^(1|true|yes)$/i.test(process.env.CLUSTERFLUX_INCLUDE_FORGEJO_WORKFLOWS || ""); -const filteredTopLevel = ["private", "internal", "experiments", ".git", "target"]; -const filteredDirectoryNames = [".clusterflux"]; -const archiveIgnoredPathFallbacks = [ - "target", - ".clusterflux", - "vscode-extension/node_modules", - "scripts/containers-home", -]; -const publicRepoBranch = process.env.CLUSTERFLUX_PUBLIC_REPO_BRANCH || "main"; -const publicBinaries = [ - "clusterflux", - "clusterflux-coordinator", - "clusterflux-node", - "clusterflux-debug-dap", -]; -const hostedBinary = "clusterflux-hosted-service"; - -function commandOutput(command, args, options = {}) { - try { - const execOptions = { - cwd: repo, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - ...options, - }; - execOptions.env = commandEnv(command, options.env); - return cp - .execFileSync(command, args, execOptions) - .trim(); - } catch (_) { - return null; - } -} - -function run(command, args, options = {}) { - const execOptions = { - cwd: repo, - stdio: "inherit", - ...options, - }; - execOptions.env = commandEnv(command, options.env); - cp.execFileSync(command, args, execOptions); -} - -function nonInteractiveGitEnv(extra = {}) { - return { - ...process.env, - GIT_TERMINAL_PROMPT: "0", - GIT_ASKPASS: process.env.GIT_ASKPASS || "/bin/false", - SSH_ASKPASS: process.env.SSH_ASKPASS || "/bin/false", - GIT_SSH_COMMAND: - process.env.GIT_SSH_COMMAND || - "ssh -o BatchMode=yes -o NumberOfPasswordPrompts=0", - ...extra, - }; -} - -function commandEnv(command, env) { - if (command !== "git") { - return env; - } - return nonInteractiveGitEnv(env); -} - -function ensureDir(dir) { - fs.mkdirSync(dir, { recursive: true }); -} - -function filteredOutPatterns() { - return [ - "private/**", - "internal/**", - "experiments/**", - ".git", - "target", - "git-ignored source paths", - "root/*.md except README.md", - "**/.clusterflux/**", - ...(includeForgejoWorkflows ? [] : [".forgejo/**"]), - ]; -} - -function gitIgnoredSourcePaths() { - const output = commandOutput("git", [ - "ls-files", - "--others", - "--ignored", - "--exclude-standard", - "--directory", - "-z", - ]); - if (output === null) { - return archiveIgnoredPathFallbacks; - } - return [ - ...new Set([ - ...archiveIgnoredPathFallbacks, - ...output - .split("\0") - .filter(Boolean) - .map((relativePath) => - relativePath.replaceAll("\\", "/").replace(/\/$/, "") - ), - ]), - ]; -} - -function isGitIgnored(relativePath, ignoredSourcePaths) { - const normalized = relativePath.replaceAll(path.sep, "/"); - return ignoredSourcePaths.some( - (ignored) => normalized === ignored || normalized.startsWith(`${ignored}/`) - ); -} - -function isFilteredRootMarkdown(relativePath, entry) { - return ( - !relativePath.includes(path.sep) && - (entry.isFile() || entry.isSymbolicLink()) && - path.extname(entry.name).toLowerCase() === ".md" && - !["README.md", "SECURITY.md"].includes(entry.name) - ); -} - -function shouldFilter(entry, relativePath) { - const parts = relativePath.split(path.sep).filter(Boolean); - const topLevel = parts[0]; - if (filteredTopLevel.includes(topLevel)) return true; - if (parts.some((part) => filteredDirectoryNames.includes(part))) return true; - if (topLevel === ".forgejo" && !includeForgejoWorkflows) return true; - if (isFilteredRootMarkdown(relativePath, entry)) return true; - return false; -} - -function copyFilteredTree(src, dest, ignoredSourcePaths, relative = "") { - ensureDir(dest); - const entries = fs - .readdirSync(src, { withFileTypes: true }) - .sort((left, right) => left.name.localeCompare(right.name)); - - for (const entry of entries) { - const childRelative = relative ? path.join(relative, entry.name) : entry.name; - if ( - shouldFilter(entry, childRelative) || - isGitIgnored(childRelative, ignoredSourcePaths) - ) { - continue; - } - - const from = path.join(src, entry.name); - const to = path.join(dest, entry.name); - if (entry.isDirectory()) { - copyFilteredTree(from, to, ignoredSourcePaths, childRelative); - } else if (entry.isSymbolicLink()) { - fs.symlinkSync(fs.readlinkSync(from), to); - } else if (entry.isFile()) { - fs.copyFileSync(from, to); - fs.chmodSync(to, fs.statSync(from).mode & 0o777); - } - } -} - -function assertFilteredTree(ignoredSourcePaths) { - for (const excluded of ["private", "internal", "experiments"]) { - if (fs.existsSync(path.join(publicTree, excluded))) { - throw new Error(`${excluded}/ leaked into the public tree`); - } - } - for (const file of walkFiles(publicTree)) { - if (file.split(path.sep).includes(".clusterflux")) { - throw new Error(`generated .clusterflux view state leaked into the public tree: ${file}`); - } - } - if (!includeForgejoWorkflows && fs.existsSync(path.join(publicTree, ".forgejo"))) { - throw new Error(".forgejo/ leaked into the host-neutral public tree"); - } - if (!fs.existsSync(path.join(publicTree, "README.md"))) { - throw new Error("product README.md is missing from the public tree"); - } - for (const ignored of ignoredSourcePaths) { - if (fs.existsSync(path.join(publicTree, ...ignored.split("/")))) { - throw new Error(`Git-ignored source path leaked into the public tree: ${ignored}`); - } - } - for (const entry of fs.readdirSync(publicTree, { withFileTypes: true })) { - if (isFilteredRootMarkdown(entry.name, entry)) { - throw new Error(`internal root Markdown file leaked into the public tree: ${entry.name}`); - } - } -} - -function walkFiles(root, relative = "") { - const dir = path.join(root, relative); - const entries = fs - .readdirSync(dir, { withFileTypes: true }) - .sort((left, right) => left.name.localeCompare(right.name)); - const files = []; - for (const entry of entries) { - const childRelative = relative ? path.join(relative, entry.name) : entry.name; - if (entry.isDirectory()) { - files.push(...walkFiles(root, childRelative)); - } else if (entry.isFile()) { - files.push(childRelative); - } else if (entry.isSymbolicLink()) { - files.push(childRelative); - } - } - return files; -} - -function hashTree(root) { - const hash = crypto.createHash("sha256"); - for (const file of walkFiles(root)) { - const absolute = path.join(root, file); - const stat = fs.lstatSync(absolute); - hash.update(file.replaceAll(path.sep, "/")); - hash.update("\0"); - hash.update(String(stat.mode & 0o777)); - hash.update("\0"); - if (stat.isSymbolicLink()) { - hash.update("symlink"); - hash.update("\0"); - hash.update(fs.readlinkSync(absolute)); - } else { - hash.update(fs.readFileSync(absolute)); - } - hash.update("\0"); - } - return `sha256:${hash.digest("hex")}`; -} - -function sha256File(file) { - return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); -} - -function sha256Buffer(buffer) { - return crypto.createHash("sha256").update(buffer).digest("hex"); -} - -function sourceTreeDigest(sourceCommit) { - const archive = cp.execFileSync("git", ["archive", "--format=tar", sourceCommit], { - cwd: repo, - encoding: null, - maxBuffer: 128 * 1024 * 1024, - stdio: ["ignore", "pipe", "inherit"], - env: nonInteractiveGitEnv(), - }); - return `sha256:${sha256Buffer(archive)}`; -} - -function evidenceIdentity(value) { - const serialized = JSON.stringify(value === undefined ? null : value); - return `sha256:${sha256Buffer(Buffer.from(serialized, "utf8"))}`; -} - -function sanitizeEvidence(value, key = "") { - const secretKey = /(?:token|secret|password|cookie|authorization|private_key)/iu.test( - key - ); - if (secretKey && typeof value === "string") return "[redacted]"; - if (secretKey && Array.isArray(value)) return ["[redacted]"]; - if (Array.isArray(value)) { - return value.map((entry) => sanitizeEvidence(entry)); - } - if (value && typeof value === "object") { - return Object.fromEntries( - Object.entries(value).map(([childKey, childValue]) => [ - childKey, - sanitizeEvidence(childValue, childKey), - ]) - ); - } - return value; -} - -function renderFinalTranscript(result) { - const lines = [ - "Clusterflux final release transcript", - `Source commit: ${result.source_commit}`, - `Source tree digest: ${result.source_tree_digest}`, - `Public tree identity: ${result.public_tree_identity}`, - `Acceptance result recorded: ${result.timestamps.acceptance_result_recorded_at}`, - `Evidence packaged: ${result.timestamps.evidence_packaged_at}`, - `Deployment generation: ${result.deployment.system_generation}`, - `Deployment identity: ${result.deployment.identity}`, - `Configuration identity: ${result.configuration_identity}`, - "", - "Commands:", - ...result.release_commands.map((command) => `- ${command}`), - "", - "Binary digests:", - ...Object.entries(result.binary_digests).map( - ([name, digest]) => `- ${name}: ${digest}` - ), - "", - "Named scenarios:", - ...result.named_scenarios.map( - (scenario) => - `- ${scenario.id}: ${scenario.status} (${scenario.duration_ms} ms)` - ), - "", - "Strict requirement ledger:", - ...result.strict_requirement_ledger.map( - (requirement) => - `- ${requirement.id}: ${requirement.passed ? "passed" : "failed"}` - ), - "", - `Scenario skips: ${JSON.stringify(result.scenario_skips)}`, - `Acceptance result: ${result.acceptance_result}`, - "", - "Failure-injection and complete machine evidence:", - JSON.stringify(result, null, 2), - "", - ]; - return `${lines.join("\n")}\n`; -} - -function tarGz(output, cwd, inputs) { - run("tar", ["-czf", output, "-C", cwd, ...inputs]); -} - -function platformName() { - return `${os.platform()}-${os.arch()}`; -} - -function binaryName(name) { - return process.platform === "win32" ? `${name}.exe` : name; -} - -function buildPublicBinaries() { - run("cargo", ["build", "--locked", "--workspace", "--bins", "--release", "--jobs", "2"], { - cwd: publicTree, - env: { ...process.env, CARGO_TARGET_DIR: publicBuildTarget }, - }); -} - -function buildHostedBinary() { - run( - "cargo", - [ - "build", - "--locked", - "--manifest-path", - "private/hosted-policy/Cargo.toml", - "--bin", - hostedBinary, - "--release", - "--jobs", - "2", - ], - { - cwd: repo, - env: { ...process.env, CARGO_TARGET_DIR: hostedBuildTarget }, - } - ); -} - -function stageBinaryAssets(releaseName) { - const stageRoot = path.join(stagingDir, "binaries"); - const binDir = path.join(stageRoot, "bin"); - fs.rmSync(stageRoot, { recursive: true, force: true }); - ensureDir(binDir); - - for (const binary of publicBinaries) { - const fileName = binaryName(binary); - const built = path.join(publicBuildTarget, "release", fileName); - if (!fs.existsSync(built)) { - throw new Error(`expected release binary ${built}`); - } - const staged = path.join(binDir, fileName); - fs.copyFileSync(built, staged); - fs.chmodSync(staged, 0o755); - } - - const archive = path.join( - assetsDir, - `clusterflux-public-binaries-${releaseName}-${platformName()}.tar.gz` - ); - tarGz(archive, stageRoot, ["."]); - return archive; -} - -function stageHostedBinaryAsset(releaseName) { - const stageRoot = path.join(stagingDir, "hosted-binary"); - const binDir = path.join(stageRoot, "bin"); - fs.rmSync(stageRoot, { recursive: true, force: true }); - ensureDir(binDir); - const fileName = binaryName(hostedBinary); - const built = path.join(hostedBuildTarget, "release", fileName); - if (!fs.existsSync(built)) { - throw new Error(`expected hosted release binary ${built}`); - } - const staged = path.join(binDir, fileName); - fs.copyFileSync(built, staged); - fs.chmodSync(staged, 0o755); - const archive = path.join( - assetsDir, - `clusterflux-hosted-${releaseName}-${platformName()}.tar.gz` - ); - tarGz(archive, stageRoot, ["."]); - return archive; -} - -function publicBinaryDigests() { - return Object.fromEntries( - publicBinaries.map((binary) => { - const fileName = binaryName(binary); - const file = path.join(publicBuildTarget, "release", fileName); - if (!fs.existsSync(file)) throw new Error(`missing built release binary ${file}`); - return [fileName, `sha256:${sha256File(file)}`]; - }) - ); -} - -function candidateBinaryDigests() { - const fileName = binaryName(hostedBinary); - const file = path.join(hostedBuildTarget, "release", fileName); - if (!fs.existsSync(file)) throw new Error(`missing hosted release binary ${file}`); - return { - ...publicBinaryDigests(), - [fileName]: `sha256:${sha256File(file)}`, - }; -} - -function reuseCandidateBinaries(candidate, releaseName) { - assertCandidateManifest(candidate); - const asset = candidate.assets.find((entry) => - entry.name.startsWith("clusterflux-public-binaries-") - ); - if (!asset || !fs.existsSync(asset.file)) { - throw new Error("release candidate binary archive is missing"); - } - if (sha256File(asset.file) !== asset.sha256) { - throw new Error("release candidate binary archive digest changed after candidate creation"); - } - const archive = path.join( - assetsDir, - `clusterflux-public-binaries-${releaseName}-${platformName()}.tar.gz` - ); - fs.copyFileSync(asset.file, archive); - const extractRoot = path.join(stagingDir, "candidate-binaries"); - fs.rmSync(extractRoot, { recursive: true, force: true }); - ensureDir(extractRoot); - run("tar", ["-xzf", archive, "-C", extractRoot]); - for (const name of publicBinaries.map(binaryName)) { - const digest = candidate.binary_digests[name]; - const binary = path.join(extractRoot, "bin", name); - if (!fs.existsSync(binary) || `sha256:${sha256File(binary)}` !== digest) { - throw new Error(`release candidate binary ${name} does not match ${digest}`); - } - } - return archive; -} - -function reuseCandidateHostedBinary(candidate, releaseName) { - assertCandidateManifest(candidate); - const asset = candidate.assets.find((entry) => - entry.name.startsWith("clusterflux-hosted-") - ); - if (!asset || !fs.existsSync(asset.file)) { - throw new Error("release candidate hosted binary archive is missing"); - } - if (sha256File(asset.file) !== asset.sha256) { - throw new Error("release candidate hosted archive digest changed after creation"); - } - const archive = path.join( - assetsDir, - `clusterflux-hosted-${releaseName}-${platformName()}.tar.gz` - ); - fs.copyFileSync(asset.file, archive); - const extractRoot = path.join(stagingDir, "candidate-hosted-binary"); - fs.rmSync(extractRoot, { recursive: true, force: true }); - ensureDir(extractRoot); - run("tar", ["-xzf", archive, "-C", extractRoot]); - const name = binaryName(hostedBinary); - const binary = path.join(extractRoot, "bin", name); - const digest = candidate.binary_digests[name]; - if (!fs.existsSync(binary) || `sha256:${sha256File(binary)}` !== digest) { - throw new Error(`release candidate hosted binary ${name} does not match ${digest}`); - } - return archive; -} - -function reuseCandidateExtension(candidate) { - assertCandidateManifest(candidate); - const asset = candidate.assets.find((entry) => entry.name.endsWith(".vsix")); - if (!asset || !fs.existsSync(asset.file)) { - throw new Error("release candidate VSIX is missing"); - } - const digest = sha256File(asset.file); - if ( - digest !== asset.sha256 || - digest !== candidate.release_candidate.extension_sha256 - ) { - throw new Error("release candidate VSIX digest changed after candidate creation"); - } - const archive = path.join(assetsDir, asset.name); - fs.copyFileSync(asset.file, archive); - return archive; -} - -function assertCandidateManifest(candidate) { - if (candidate.kind !== "clusterflux-public-release") { - throw new Error("release candidate manifest has the wrong kind"); - } - if (candidate.release_candidate?.mode !== "built-once") { - throw new Error("release finalization requires a built-once candidate manifest"); - } - if (!candidate.binary_digests || !Object.keys(candidate.binary_digests).length) { - throw new Error("release candidate manifest omitted binary digests"); - } - if (!candidate.binary_digests[binaryName(hostedBinary)]) { - throw new Error("release candidate omitted the hosted service binary digest"); - } - if (!candidate.release_candidate.hosted_binary_archive_sha256) { - throw new Error("release candidate omitted the hosted service archive digest"); - } - if (!candidate.release_candidate.extension_sha256) { - throw new Error("release candidate omitted the VSIX digest"); - } -} - -function stageEvidenceAsset( - releaseName, - sourceCommit, - sourceDigest, - publicTreeIdentity, - binaryDigests, - candidateBinding, - candidateConfigurationIdentity, - candidateProxyConfigurationIdentity -) { - const stage = path.join(stagingDir, "evidence"); - fs.rmSync(stage, { recursive: true, force: true }); - ensureDir(stage); - const evidenceRoot = path.join(repo, "target/acceptance"); - const included = []; - for (const name of ["public-environment.json", "wasmtime-assignment.json"]) { - const source = path.join(evidenceRoot, name); - if (!fs.existsSync(source)) continue; - fs.copyFileSync(source, path.join(stage, name)); - included.push(name); - } - const acceptancePath = path.resolve( - process.env.CLUSTERFLUX_FINAL_RESULT_PATH || - path.join(evidenceRoot, "cli-happy-path-live.json") - ); - const legacyIncompleteEvidenceEnv = [ - "CLUSTERFLUX", - "ALLOW", - "INCOMPLETE", - "RELEASE", - "EVIDENCE", - ].join("_"); - if (process.env[legacyIncompleteEvidenceEnv]) { - throw new Error( - "the legacy incomplete-evidence environment switch is unsupported; use CLUSTERFLUX_RELEASE_STAGE=candidate or final" - ); - } - const releaseStage = - process.env.CLUSTERFLUX_RELEASE_STAGE || - (candidateManifestPath ? "final" : "candidate"); - if (!new Set(["candidate", "final"]).has(releaseStage)) { - throw new Error("CLUSTERFLUX_RELEASE_STAGE must be candidate or final"); - } - const allowIncomplete = releaseStage === "candidate"; - let finalEvidence = { - complete: false, - result: null, - transcript: null, - acceptance_result_recorded_at: null, - deployment_identity: null, - configuration_identity: null, - }; - - if (fs.existsSync(acceptancePath)) { - const liveResult = JSON.parse(fs.readFileSync(acceptancePath, "utf8")); - if (liveResult.source_commit === sourceCommit) { - if (liveResult.acceptance_result !== "passed") { - throw new Error("final live acceptance result is not passed"); - } - if (liveResult.source_tree_digest !== sourceDigest) { - throw new Error("final live acceptance source-tree digest does not match the candidate"); - } - if (liveResult.public_tree_identity !== publicTreeIdentity) { - throw new Error("final live acceptance public-tree identity does not match the candidate"); - } - if ( - JSON.stringify(liveResult.binary_digests) !== JSON.stringify(binaryDigests) || - JSON.stringify(liveResult.release_binding?.binary_digests) !== - JSON.stringify(binaryDigests) - ) { - throw new Error("final live acceptance binaries do not match the exact candidate"); - } - if (liveResult.release_binding?.source_commit !== sourceCommit) { - throw new Error("final live acceptance release binding has the wrong source commit"); - } - if (!Array.isArray(liveResult.scenario_skips) || liveResult.scenario_skips.length) { - throw new Error("final live acceptance result contains unresolved scenario skips"); - } - if ( - !Array.isArray(liveResult.named_scenarios) || - !Array.isArray(liveResult.strict_requirement_ledger) || - liveResult.named_scenarios.length !== - liveResult.strict_requirement_ledger.length || - liveResult.named_scenarios.length < 29 || - liveResult.named_scenarios.some( - (scenario) => - scenario.status !== "passed" || - !Number.isFinite(scenario.duration_ms) || - scenario.duration_ms <= 0 - ) || - new Set(liveResult.named_scenarios.map((scenario) => scenario.id)) - .size !== liveResult.named_scenarios.length - ) { - throw new Error( - "every named final live check must be unique, measured, and passed" - ); - } - if ( - !liveResult.release_binding?.deployment || - !liveResult.release_binding?.configuration || - !liveResult.release_binding?.proxy_configuration - ) { - throw new Error( - "final live evidence must bind deployment, runtime configuration, and proxy configuration identities" - ); - } - if ( - !Array.isArray(liveResult.strict_requirement_ledger) || - !liveResult.strict_requirement_ledger.length || - liveResult.strict_requirement_ledger.some( - (requirement) => - requirement.passed !== true || - !Number.isFinite(requirement.duration_ms) || - requirement.duration_ms <= 0 || - !requirement.evidence - ) || - liveResult.strict_requirement_ledger.some( - (requirement, index) => - requirement.id !== liveResult.named_scenarios[index].id - ) - ) { - throw new Error("the strict final requirement ledger must be complete and passed"); - } - const deploymentGeneration = - process.env.CLUSTERFLUX_DEPLOYMENT_SYSTEM_GENERATION || - liveResult.release_binding?.deployment?.system_generation || - null; - if (!deploymentGeneration && !allowIncomplete) { - throw new Error( - "CLUSTERFLUX_DEPLOYMENT_SYSTEM_GENERATION is required for final evidence" - ); - } - const recordedAt = fs.statSync(acceptancePath).mtime.toISOString(); - const packagedAt = new Date().toISOString(); - const sanitized = sanitizeEvidence(liveResult); - const finalResult = { - ...sanitized, - kind: "clusterflux-final-release-result", - source_commit: sourceCommit, - source_tree_digest: sourceDigest, - public_tree_identity: publicTreeIdentity, - binary_digests: binaryDigests, - release_candidate: candidateBinding, - deployment: { - system_generation: deploymentGeneration, - identity: evidenceIdentity(liveResult.release_binding?.deployment), - }, - configuration_identity: evidenceIdentity( - liveResult.release_binding?.configuration - ), - timestamps: { - acceptance_result_recorded_at: recordedAt, - evidence_packaged_at: packagedAt, - }, - release_commands: [ - "nix develop -c node scripts/release-quality-gates.js", - "node scripts/cli-happy-path-live-smoke.js (strict production-shaped environment)", - ], - }; - const resultName = "FINAL_RELEASE_RESULT.json"; - const transcriptName = "FINAL_RELEASE_TRANSCRIPT.txt"; - const resultPath = path.join(stage, resultName); - const transcriptPath = path.join(stage, transcriptName); - fs.writeFileSync(resultPath, `${JSON.stringify(finalResult, null, 2)}\n`); - fs.writeFileSync(transcriptPath, renderFinalTranscript(finalResult)); - included.push(resultName, transcriptName); - finalEvidence = { - complete: true, - result: { - name: resultName, - sha256: sha256File(resultPath), - }, - transcript: { - name: transcriptName, - sha256: sha256File(transcriptPath), - }, - acceptance_result_recorded_at: recordedAt, - deployment_identity: finalResult.deployment.identity, - configuration_identity: finalResult.configuration_identity, - }; - } else if (!allowIncomplete) { - throw new Error( - `final live acceptance commit ${liveResult.source_commit} does not match ${sourceCommit}` - ); - } - } else if (!allowIncomplete) { - throw new Error(`missing final live acceptance result: ${acceptancePath}`); - } - - const binding = { - kind: "clusterflux-release-evidence-binding", - source_commit: sourceCommit, - source_tree_digest: sourceDigest, - public_tree_identity: publicTreeIdentity, - binary_digests: binaryDigests, - release_candidate: candidateBinding, - candidate_configuration_identity: candidateConfigurationIdentity, - candidate_proxy_configuration_identity: candidateProxyConfigurationIdentity, - configuration_generation: - process.env.CLUSTERFLUX_DEPLOYMENT_SYSTEM_GENERATION || null, - final_evidence: finalEvidence, - included_evidence: included.map((name) => ({ - name, - sha256: sha256File(path.join(stage, name)), - })), - }; - fs.writeFileSync( - path.join(stage, "EVIDENCE_BINDING.json"), - `${JSON.stringify(binding, null, 2)}\n` - ); - const archive = path.join( - assetsDir, - `clusterflux-public-evidence-${releaseName}.tar.gz` - ); - tarGz(archive, stage, ["."]); - return { archive, finalEvidence }; -} - -function stageSourceAsset(releaseName) { - const archive = path.join(assetsDir, `clusterflux-public-source-${releaseName}.tar.gz`); - tarGz(archive, publicTree, ["."]); - return archive; -} - -function stageExtensionAsset() { - const extensionRoot = path.join(publicTree, "vscode-extension"); - const packageJson = JSON.parse( - fs.readFileSync(path.join(extensionRoot, "package.json"), "utf8") - ); - const archive = path.join( - assetsDir, - `${packageJson.name}-${packageJson.version}.vsix` - ); - run("npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund"], { - cwd: extensionRoot, - }); - run( - path.join(extensionRoot, "node_modules", ".bin", "vsce"), - [ - "package", - "--allow-missing-repository", - "--skip-license", - "--out", - archive, - ], - { cwd: extensionRoot } - ); - run("node", ["scripts/vscode-extension-smoke.js"], { cwd: publicTree }); - run("node", ["scripts/vscode-f5-smoke.js"], { cwd: publicTree }); - return archive; -} - -function resolverInstructions() { - if (process.env.CLUSTERFLUX_PUBLIC_RELEASE_RESOLVER_INSTRUCTIONS) { - return process.env.CLUSTERFLUX_PUBLIC_RELEASE_RESOLVER_INSTRUCTIONS.trim(); - } - if (process.env.CLUSTERFLUX_PUBLIC_RELEASE_HOSTS_ENTRY) { - return [ - "Add the controlled hosts entry supplied for this release:", - "", - "```", - process.env.CLUSTERFLUX_PUBLIC_RELEASE_HOSTS_ENTRY.trim(), - "```", - ].join("\n"); - } - if (process.env.CLUSTERFLUX_PUBLIC_RELEASE_IP) { - return [ - "Add this controlled hosts entry for the release:", - "", - "```", - `${process.env.CLUSTERFLUX_PUBLIC_RELEASE_IP} clusterflux.michelpaulissen.com`, - "```", - ].join("\n"); - } - return [ - "`clusterflux.michelpaulissen.com` should resolve through public DNS. If it", - "does not resolve yet, wait for DNS propagation or use the fallback hosts", - "entry supplied with the invitation.", - ].join("\n"); -} - -function writeGettingStartedAsset(releaseName, publicTreeIdentity, resolution) { - const file = path.join(assetsDir, `CLUSTERFLUX_GETTING_STARTED-${releaseName}.md`); - fs.writeFileSync( - file, - `# Clusterflux Getting Started - -Use the public repository and release downloads with the hosted coordinator at -\`https://clusterflux.michelpaulissen.com\`. - -## DNS - -${resolution} - -## Install - -1. Download the binary archive for your platform from the manually published GitHub release. -2. Check the archive against \`SHA256SUMS\`. -3. Extract it and put \`bin/\` on your \`PATH\`. -4. Install \`clusterflux-vscode-*.vsix\` when you want the VS Code debugger: - -\`\`\`bash -code --install-extension clusterflux-vscode-*.vsix -\`\`\` - -## Sign in and run - -\`\`\`bash -clusterflux login --browser -clusterflux auth status -clusterflux project list -clusterflux bundle inspect --project examples/hello-build -\`\`\` - -The CLI opens the server-provided Authentik authorization URL. State, nonce, -PKCE, provider code exchange, and userinfo remain on the hosted service. The CLI -stores only the resulting scoped Clusterflux session. - -Create a node enrollment grant, attach the node, and start the worker: - -\`\`\`bash -clusterflux node enroll --project-id --json -clusterflux node attach --project-id --node workstation \\ - --enrollment-grant "$ENROLLMENT_GRANT" -clusterflux-node --coordinator https://clusterflux.michelpaulissen.com \\ - --tenant --project-id --node workstation \\ - --project-root "$PWD" --worker --emit-ready -\`\`\` - -Then run the workflow: - -\`\`\`bash -clusterflux run --project examples/hello-build build -\`\`\` - -Public tree identity: \`${publicTreeIdentity}\` -Release name: \`${releaseName}\` -`, - "utf8" - ); - return file; -} - -function writeReleaseNotesAsset(releaseName, publicTreeIdentity, resolution) { - const file = path.join(assetsDir, `CLUSTERFLUX_RELEASE_NOTES-${releaseName}.md`); - const publicRepo = - process.env.CLUSTERFLUX_PUBLIC_REPO_URL || - "https://git.michelpaulissen.com/michel/clusterflux-public"; - const releaseUrl = - process.env.CLUSTERFLUX_GITHUB_RELEASE_URL || - "the manually published GitHub release"; - fs.writeFileSync( - file, - `# Clusterflux Release Notes - -Use this release with the public Clusterflux repository and hosted coordinator. - -## Links - -- Public repository: ${publicRepo} -- Release downloads: ${releaseUrl} -- Hosted coordinator: ${defaultHostedCoordinatorEndpoint} -- Public tree identity: ${publicTreeIdentity} -- Release name: ${releaseName} - -## DNS - -${resolution} - -## First run - -1. Download the archive for your platform and \`SHA256SUMS\`. -2. Extract the archive and put \`bin/\` on your \`PATH\`. -3. Optionally install the VS Code extension archive. -4. Run \`clusterflux login --browser\`. -5. Run \`clusterflux node enroll\`, attach your node, and start the worker. -6. Run \`clusterflux run --project examples/hello-build build\`. -`, - "utf8" - ); - return file; -} - -function writeSha256Sums(assets) { - const sumsPath = path.join(assetsDir, "SHA256SUMS"); - const lines = assets - .map((asset) => `${sha256File(asset)} ${path.basename(asset)}`) - .sort() - .join("\n"); - fs.writeFileSync(sumsPath, `${lines}\n`); - return sumsPath; -} - -function boolEnv(name) { - return /^(1|true|yes)$/i.test(process.env[name] || ""); -} - -function writePublicTreeProvenance(sourceCommit, releaseName) { - const provenance = { - kind: "clusterflux-filtered-public-tree", - source_commit: sourceCommit, - release_name: releaseName, - filtered_out: filteredOutPatterns(), - public_export: { - host_neutral: !includeForgejoWorkflows, - include_forgejo_workflows: includeForgejoWorkflows, - }, - forgejo_host: forgejoHost, - default_hosted_coordinator_endpoint: defaultHostedCoordinatorEndpoint, - }; - fs.writeFileSync( - path.join(publicTree, "CLUSTERFLUX_PUBLIC_TREE.json"), - `${JSON.stringify(provenance, null, 2)}\n` - ); -} - -function publishPublicTree(releaseName, sourceCommit, publicTreeIdentity) { - const remote = - process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE || - process.env.CLUSTERFLUX_PUBLIC_REPO_URL || - null; - const enabled = boolEnv("CLUSTERFLUX_PUBLISH_PUBLIC_TREE"); - const result = { - enabled, - remote, - branch: publicRepoBranch, - commit: null, - pushed: false, - }; - - if (!enabled) { - return result; - } - if (!remote) { - throw new Error( - "CLUSTERFLUX_PUBLISH_PUBLIC_TREE requires CLUSTERFLUX_PUBLIC_REPO_REMOTE or CLUSTERFLUX_PUBLIC_REPO_URL" - ); - } - if (!remote.includes(forgejoHost)) { - throw new Error(`public repo remote must point at ${forgejoHost}: ${remote}`); - } - - run("git", ["init"], { cwd: publicTree }); - run("git", ["config", "user.name", "Clusterflux release"], { - cwd: publicTree, - }); - run("git", ["config", "user.email", "release@clusterflux.invalid"], { - cwd: publicTree, - }); - run("git", ["add", "."], { cwd: publicTree }); - const tree = commandOutput("git", ["write-tree"], { cwd: publicTree }); - run("git", ["remote", "add", "public", remote], { cwd: publicTree }); - run( - "git", - [ - "fetch", - "public", - `refs/heads/${publicRepoBranch}:refs/remotes/public/${publicRepoBranch}`, - ], - { cwd: publicTree } - ); - const parent = commandOutput( - "git", - ["rev-parse", `refs/remotes/public/${publicRepoBranch}`], - { cwd: publicTree } - ); - result.commit = commandOutput( - "git", - [ - "commit-tree", - tree, - "-p", - parent, - "-m", - `Public release ${releaseName}`, - "-m", - `Source commit: ${sourceCommit}`, - "-m", - `Public tree identity: ${publicTreeIdentity}`, - ], - { cwd: publicTree } - ); - run("git", ["update-ref", `refs/heads/${publicRepoBranch}`, result.commit], { - cwd: publicTree, - }); - run("git", ["push", "public", `${result.commit}:${publicRepoBranch}`], { - cwd: publicTree, - }); - result.pushed = true; - return result; -} - -function main() { - const sourceCommit = commandOutput("git", ["rev-parse", "HEAD"]); - if (!sourceCommit || !/^[0-9a-f]{40}$/u.test(sourceCommit)) { - throw new Error("the public release requires an exact Git HEAD object id"); - } - const acceptanceCommit = process.env.CLUSTERFLUX_ACCEPTANCE_COMMIT?.trim(); - if (acceptanceCommit && acceptanceCommit !== sourceCommit) { - throw new Error( - `CLUSTERFLUX_ACCEPTANCE_COMMIT ${acceptanceCommit} does not match source HEAD ${sourceCommit}` - ); - } - const shortCommit = sourceCommit.slice(0, 12); - const releaseName = process.env.CLUSTERFLUX_PUBLIC_RELEASE_NAME || `release-${shortCommit}`; - const sourceDigest = sourceTreeDigest(sourceCommit); - const candidate = candidateManifestPath - ? JSON.parse(fs.readFileSync(candidateManifestPath, "utf8")) - : null; - if (candidate) { - for (const asset of candidate.assets ?? []) { - asset.file = path.isAbsolute(asset.file) - ? asset.file - : path.resolve(path.dirname(candidateManifestPath), asset.file); - } - } - const releaseStage = - process.env.CLUSTERFLUX_RELEASE_STAGE || - (candidateManifestPath ? "final" : "candidate"); - if (releaseStage === "final" && !candidate) { - throw new Error("final release stage requires CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST"); - } - if (releaseStage === "candidate" && candidate) { - throw new Error("candidate release stage cannot consume a prior candidate manifest"); - } - if ( - releaseStage === "candidate" && - (!process.env.CLUSTERFLUX_CANDIDATE_CONFIGURATION_IDENTITY || - !process.env.CLUSTERFLUX_CANDIDATE_PROXY_CONFIGURATION_IDENTITY) - ) { - throw new Error( - "candidate release stage requires configuration and proxy configuration identities" - ); - } - if (candidate) { - assertCandidateManifest(candidate); - if (path.dirname(candidateManifestPath) === outputRoot) { - throw new Error("candidate and finalized release must use different output directories"); - } - if (candidate.source_commit !== sourceCommit) { - throw new Error("release candidate source commit does not match Git HEAD"); - } - if (candidate.source_tree_digest !== sourceDigest) { - throw new Error("release candidate source tree digest does not match Git HEAD"); - } - if (candidate.release_name !== releaseName) { - throw new Error("release candidate name does not match the finalized release name"); - } - } - const sourceStatus = commandOutput("git", ["status", "--short"]); - if (sourceStatus === null) { - throw new Error("the public release must be prepared from a Git checkout"); - } - if (sourceStatus !== "") { - throw new Error("the public release must be prepared from a clean source tree"); - } - const sourceTreeClean = true; - - fs.rmSync(outputRoot, { recursive: true, force: true }); - ensureDir(publicTree); - ensureDir(assetsDir); - ensureDir(stagingDir); - - const ignoredSourcePaths = gitIgnoredSourcePaths(); - copyFilteredTree(repo, publicTree, ignoredSourcePaths); - assertFilteredTree(ignoredSourcePaths); - writePublicTreeProvenance(sourceCommit, releaseName); - const publicTreeIdentity = hashTree(publicTree); - if (candidate && candidate.public_tree_identity !== publicTreeIdentity) { - throw new Error("release candidate public tree identity changed before finalization"); - } - const sourceArchive = stageSourceAsset(releaseName); - - run("scripts/check-old-name.sh", [], { cwd: publicTree }); - run("node", ["scripts/check-docs.js"], { cwd: publicTree }); - run("scripts/check-code-size.sh", [], { cwd: publicTree }); - const publicTreePublish = candidate - ? candidate.public_tree_publish - : publishPublicTree(releaseName, sourceCommit, publicTreeIdentity); - let binaryArchive; - let hostedBinaryArchive; - let extensionArchive; - let binaryDigests; - let candidateBinding; - if (candidate) { - binaryArchive = reuseCandidateBinaries(candidate, releaseName); - hostedBinaryArchive = reuseCandidateHostedBinary(candidate, releaseName); - extensionArchive = reuseCandidateExtension(candidate); - binaryDigests = candidate.binary_digests; - candidateBinding = { - mode: "finalized-exact", - manifest: path.relative(outputRoot, candidateManifestPath).split(path.sep).join("/"), - manifest_sha256: sha256File(candidateManifestPath), - binary_archive_sha256: sha256File(binaryArchive), - hosted_binary_archive_sha256: sha256File(hostedBinaryArchive), - extension_sha256: sha256File(extensionArchive), - }; - } else { - buildPublicBinaries(); - buildHostedBinary(); - binaryArchive = stageBinaryAssets(releaseName); - hostedBinaryArchive = stageHostedBinaryAsset(releaseName); - extensionArchive = stageExtensionAsset(); - binaryDigests = candidateBinaryDigests(); - candidateBinding = { - mode: "built-once", - binary_archive_sha256: sha256File(binaryArchive), - hosted_binary_archive_sha256: sha256File(hostedBinaryArchive), - extension_sha256: sha256File(extensionArchive), - }; - } - const candidateConfigurationIdentity = - candidate?.candidate_configuration_identity || - process.env.CLUSTERFLUX_CANDIDATE_CONFIGURATION_IDENTITY || - null; - const candidateProxyConfigurationIdentity = - candidate?.candidate_proxy_configuration_identity || - process.env.CLUSTERFLUX_CANDIDATE_PROXY_CONFIGURATION_IDENTITY || - null; - const evidence = stageEvidenceAsset( - releaseName, - sourceCommit, - sourceDigest, - publicTreeIdentity, - binaryDigests, - candidateBinding, - candidateConfigurationIdentity, - candidateProxyConfigurationIdentity - ); - const evidenceArchive = evidence.archive; - const resolution = resolverInstructions(); - const gettingStarted = writeGettingStartedAsset( - releaseName, - publicTreeIdentity, - resolution - ); - const invite = writeReleaseNotesAsset(releaseName, publicTreeIdentity, resolution); - const assets = [ - sourceArchive, - binaryArchive, - hostedBinaryArchive, - evidenceArchive, - extensionArchive, - gettingStarted, - invite, - ]; - const sha256Sums = writeSha256Sums(assets); - - const manifest = { - kind: "clusterflux-public-release", - release_name: releaseName, - source_commit: sourceCommit, - source_tree_digest: sourceDigest, - source_tree_clean: sourceTreeClean, - public_tree_identity: publicTreeIdentity, - public_tree: publicTree, - filtered_out: filteredOutPatterns(), - public_export: { - host_neutral: !includeForgejoWorkflows, - include_forgejo_workflows: includeForgejoWorkflows, - }, - forgejo_host: forgejoHost, - public_repo_url: - process.env.CLUSTERFLUX_PUBLIC_REPO_URL || - candidate?.public_repo_url || - publicTreePublish.remote, - public_repo_remote: - process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE || candidate?.public_repo_remote || null, - public_tree_publish: publicTreePublish, - github_release_url: process.env.CLUSTERFLUX_GITHUB_RELEASE_URL || null, - forgejo_release_url: null, - default_hosted_coordinator_endpoint: defaultHostedCoordinatorEndpoint, - dns_publication_state: - process.env.CLUSTERFLUX_DNS_PUBLICATION_STATE || "published", - resolver_override: - process.env.CLUSTERFLUX_RESOLVER_OVERRIDE || "none-required-public-dns", - platform: platformName(), - binary_digests: binaryDigests, - release_candidate: candidateBinding, - candidate_configuration_identity: candidateConfigurationIdentity, - candidate_proxy_configuration_identity: candidateProxyConfigurationIdentity, - configuration_generation: - process.env.CLUSTERFLUX_DEPLOYMENT_SYSTEM_GENERATION || null, - final_evidence: evidence.finalEvidence, - tool_versions: { - node: process.version, - rustc: commandOutput("rustc", ["--version"]) || null, - cargo: commandOutput("cargo", ["--version"]) || null, - tar: commandOutput("tar", ["--version"]) || null, - }, - commands: [ - "scripts/check-old-name.sh", - "node scripts/check-docs.js", - "scripts/check-code-size.sh", - ...(publicTreePublish.enabled - ? [`git push public HEAD:${publicRepoBranch}`] - : []), - ...(candidate - ? ["finalize exact public and hosted binaries from CLUSTERFLUX_RELEASE_CANDIDATE_MANIFEST"] - : [ - "cargo build --locked --workspace --bins --release --jobs 2", - "cargo build --locked --manifest-path private/hosted-policy/Cargo.toml --bin clusterflux-hosted-service --release --jobs 2", - ]), - ], - assets: [...assets, sha256Sums].map((asset) => ({ - file: path.relative(outputRoot, asset).split(path.sep).join("/"), - name: path.basename(asset), - sha256: sha256File(asset), - })), - notes: - releaseStage === "final" - ? [ - "Publish manually to GitHub from the prepared manual release directory.", - "The manifest embeds the exact production-shaped validation evidence and candidate binding.", - "Forgejo release publication is not launch authority.", - ] - : [ - "This is a validation candidate, not a published release.", - "GitHub publication remains manual after final production-shaped validation.", - "Forgejo release publication is not launch authority.", - ], - }; - - const manifestPath = path.join(outputRoot, "public-release-manifest.json"); - fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); - console.log(JSON.stringify({ manifest: manifestPath, assets: assetsDir }, null, 2)); -} - -main(); diff --git a/scripts/private-repository-gate.sh b/scripts/private-repository-gate.sh deleted file mode 100755 index 842457e..0000000 --- a/scripts/private-repository-gate.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -cd "$repo" - -scripts/check-old-name.sh -node scripts/check-docs.js -scripts/check-code-size.sh -cargo fmt --all --check -cargo clippy --workspace --all-targets -- -D warnings -cargo test --workspace -cargo test --locked --manifest-path private/hosted-policy/Cargo.toml -node scripts/vscode-extension-smoke.js diff --git a/scripts/public-local-demo-matrix-smoke.js b/scripts/public-local-demo-matrix-smoke.js deleted file mode 100755 index 8cae940..0000000 --- a/scripts/public-local-demo-matrix-smoke.js +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); - -function read(relativePath) { - return fs.readFileSync(path.join(repo, relativePath), "utf8"); -} - -function expect(source, name, pattern) { - assert.match(source, pattern, `missing public local demo evidence: ${name}`); -} - -const publicAcceptance = read("scripts/acceptance-public.sh"); -const publicSplit = read("scripts/verify-public-split.sh"); -const cliInstall = read("scripts/cli-install-smoke.js"); -const flagship = read("scripts/flagship-demo-smoke.js"); -const cliLocalRun = read("scripts/cli-local-run-smoke.js"); -const nodeAttach = read("scripts/node-attach-smoke.js"); -const vscodeExtension = read("scripts/vscode-extension-smoke.js"); -const vscodeF5 = read("scripts/vscode-f5-smoke.js"); -const artifactDownload = read("scripts/artifact-download-smoke.js"); -const artifactExport = read("scripts/artifact-export-smoke.js"); - -for (const script of [publicAcceptance, publicSplit]) { - for (const smoke of [ - "scripts/cli-install-smoke.js", - "scripts/flagship-demo-smoke.js", - "scripts/cli-local-run-smoke.js", - "scripts/node-attach-smoke.js", - "scripts/vscode-extension-smoke.js", - "scripts/vscode-f5-smoke.js", - "scripts/artifact-download-smoke.js", - "scripts/artifact-export-smoke.js", - ]) { - assert(script.includes(`node ${smoke}`), `public demo gate must run ${smoke}`); - } -} - -expect(cliInstall, "CLI install from project path", /cargo[\s\S]*install[\s\S]*crates\/clusterflux-cli/); -expect(cliInstall, "CLI install smoke targets runtime fixture", /const project = path\.join\(repo, "tests\/fixtures\/runtime-conformance"\)/); -expect(cliInstall, "installed CLI inspects flagship project", /installedBin[\s\S]*\["bundle", "inspect", "--project", project, "--json"\]/); - -expect(flagship, "flagship project source is conventional Rust workflow", /examples\/hello-build[\s\S]*src\/lib\.rs/); -expect(flagship, "flagship source avoids implementation details", /const forbidden/); -expect(flagship, "flagship builds a real bundle", /clusterflux-cli[\s\S]*build[\s\S]*hello/); - -expect(cliLocalRun, "local run starts node process", /cli_process_started_node_process[\s\S]*true/); -expect(cliLocalRun, "local run records real task events", /events\.events\.length >= 4[\s\S]*prepare_source[\s\S]*compile_linux[\s\S]*package_release/); -expect(cliLocalRun, "local run records artifact metadata", /events\.events\.some\(\(event\) => event\.artifact_path\)/); - -expect(nodeAttach, "Linux node attach creates enrollment grant", /create_node_enrollment_grant/); -expect(nodeAttach, "Linux node attach uses enrollment exchange", /used_enrollment_exchange[\s\S]*true/); -expect(nodeAttach, "attached Linux node proves signed enrollment", /used_enrollment_exchange[\s\S]*signedNodeHeartbeat/); - -expect(vscodeExtension, "extension contributes debugger", /contributes\.debuggers[\s\S]*type === "clusterflux"/); -expect(vscodeF5, "F5 uses local-services backend", /runtimeBackend[\s\S]*local-services/); -expect(vscodeF5, "F5 exposes real coordinator main thread", /threads\.find\(\(thread\) => thread\.name\.includes\("build coordinator main"\)\)[\s\S]*real coordinator-main entrypoint thread/); -expect(vscodeF5, "F5 does not fabricate a terminal event at the entry probe", /coordinator_task_events[\s\S]*value === 0[\s\S]*must not fabricate a terminal task event/); - -expect(artifactDownload, "artifact download creates scoped link", /create_artifact_download_link/); -expect(artifactDownload, "artifact download opens stream", /open_artifact_download_stream/); -expect(artifactExport, "artifact export targets receiver node", /export_artifact_to_node[\s\S]*node-export-receiver/); -expect(artifactExport, "artifact export rejects coordinator bulk relay", /coordinator_bulk_relay_allowed[\s\S]*false/); - -console.log("Public local demo matrix smoke passed"); diff --git a/scripts/public-release-preflight.js b/scripts/public-release-preflight.js deleted file mode 100755 index 53749b9..0000000 --- a/scripts/public-release-preflight.js +++ /dev/null @@ -1,451 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const releaseRoot = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_DIR || - path.join(repo, "target/public-release") -); -const acceptanceRoot = path.join(repo, "target/acceptance"); -const manifestPath = - process.env.CLUSTERFLUX_PUBLIC_RELEASE_MANIFEST || - path.join(releaseRoot, "public-release-manifest.json"); -const reportPath = - process.env.CLUSTERFLUX_PUBLIC_RELEASE_PREFLIGHT_REPORT || - path.join(acceptanceRoot, "public-release-preflight.json"); - -function commandOutput(command, args, options = {}) { - try { - return cp - .execFileSync(command, args, { - cwd: repo, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - ...options, - }) - .trim(); - } catch (_) { - return null; - } -} - -function nonInteractiveEnv(extra = {}) { - return { - ...process.env, - GIT_TERMINAL_PROMPT: "0", - GIT_ASKPASS: process.env.GIT_ASKPASS || "/bin/false", - SSH_ASKPASS: process.env.SSH_ASKPASS || "/bin/false", - GIT_SSH_COMMAND: - process.env.GIT_SSH_COMMAND || - "ssh -o BatchMode=yes -o NumberOfPasswordPrompts=0", - ...extra, - }; -} - -function expectedSourceCommit() { - const head = commandOutput("git", ["rev-parse", "HEAD"]); - assert(head && /^[0-9a-f]{40}$/u.test(head), "preflight requires an exact Git HEAD"); - const asserted = process.env.CLUSTERFLUX_ACCEPTANCE_COMMIT; - if (asserted) { - assert.strictEqual(asserted, head, "acceptance commit must match Git HEAD"); - } - return head; -} - -function readJson(file) { - return JSON.parse(fs.readFileSync(file, "utf8")); -} - -function sha256File(file) { - return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); -} - -function sha256Buffer(buffer) { - return crypto.createHash("sha256").update(buffer).digest("hex"); -} - -function readArchiveMember(archive, member) { - return cp.execFileSync("tar", ["-xOzf", archive, `./${member}`], { - cwd: repo, - encoding: null, - maxBuffer: 128 * 1024 * 1024, - stdio: ["ignore", "pipe", "pipe"], - }); -} - -function parseSha256Sums(file) { - const sums = new Map(); - for (const line of fs.readFileSync(file, "utf8").split(/\r?\n/)) { - if (!line.trim()) continue; - const match = /^([0-9a-f]{64})\s+(.+)$/.exec(line.trim()); - assert(match, `malformed SHA256SUMS line: ${line}`); - sums.set(path.basename(match[2]), match[1]); - } - return sums; -} - -function remoteHead(remote) { - const output = commandOutput("git", ["ls-remote", remote, "HEAD", "refs/heads/main"], { - env: nonInteractiveEnv(), - timeout: Number(process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE_TIMEOUT_MS || 30000), - }); - if (!output) return null; - const lines = output.split(/\r?\n/).filter(Boolean); - const head = lines.find((line) => line.endsWith("\tHEAD")) || lines[0]; - return head && head.split(/\s+/)[0]; -} - -function publicTreeAlreadyPushed(manifest) { - return ( - (manifest.public_tree_publish && manifest.public_tree_publish.pushed === true) || - process.env.CLUSTERFLUX_PUBLIC_TREE_ALREADY_PUSHED === "1" - ); -} - -function publicTreePushSource(manifest) { - return manifest.public_tree_publish && manifest.public_tree_publish.pushed === true - ? "manifest" - : "external-env"; -} - -function publicRepoRemoteForManifest(manifest) { - return ( - manifest.public_repo_url || - manifest.public_repo_remote || - process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE || - process.env.CLUSTERFLUX_PUBLIC_REPO_URL || - null - ); -} - -function publicTreeCommitForManifest(manifest) { - return ( - (manifest.public_tree_publish && manifest.public_tree_publish.commit) || - process.env.CLUSTERFLUX_PUBLIC_TREE_COMMIT || - process.env.CLUSTERFLUX_PUBLIC_RELEASE_TARGET || - null - ); -} - -function envState(name) { - return process.env[name] ? "set" : "unset"; -} - -function staleEvidence(file, currentSourceCommit) { - if (!fs.existsSync(file)) { - return { file, status: "missing", source_commit: null, release_name: null }; - } - const evidence = readJson(file); - if (!evidence.source_commit) { - return { - file, - status: "unversioned", - source_commit: null, - release_name: evidence.release_name || null, - }; - } - return { - file, - status: evidence.source_commit === currentSourceCommit ? "current" : "stale", - source_commit: evidence.source_commit, - release_name: evidence.release_name || null, - }; -} - -assert(fs.existsSync(manifestPath), `missing public release manifest: ${manifestPath}`); -const manifest = readJson(manifestPath); -for (const asset of manifest.assets ?? []) { - asset.file = path.isAbsolute(asset.file) - ? asset.file - : path.resolve(path.dirname(manifestPath), asset.file); -} -const currentSourceCommit = expectedSourceCommit(); -const currentTreeStatus = commandOutput("git", ["status", "--short"]) || ""; -assert.strictEqual( - currentTreeStatus, - "", - "public release preflight requires a clean source tree" -); -assert.strictEqual(manifest.kind, "clusterflux-public-release"); -assert.strictEqual( - manifest.source_commit, - currentSourceCommit, - "public release manifest must be regenerated for the current acceptance commit" -); -assert.strictEqual(manifest.source_tree_clean, true, "public release prep must start clean"); -assert.strictEqual( - publicTreeAlreadyPushed(manifest), - true, - "filtered public tree must be pushed to Forgejo before release publication" -); - -const publicRepoRemote = publicRepoRemoteForManifest(manifest); -assert(publicRepoRemote, "manifest must record public repository URL or remote"); -const publicTreeCommit = publicTreeCommitForManifest(manifest); -const remoteMain = remoteHead(publicRepoRemote); -assert(remoteMain, "Forgejo public repository main branch must be readable"); -if (publicTreeCommit) { - assert.strictEqual( - remoteMain, - publicTreeCommit, - "Forgejo public repository main branch must match the prepared public tree commit" - ); -} - -assert(Array.isArray(manifest.assets) && manifest.assets.length > 0, "manifest assets missing"); -const checksumAsset = manifest.assets.find((asset) => asset.name === "SHA256SUMS"); -assert(checksumAsset, "manifest must include SHA256SUMS"); -assert(fs.existsSync(checksumAsset.file), `missing checksum asset: ${checksumAsset.file}`); -const checksums = parseSha256Sums(checksumAsset.file); -const assets = manifest.assets.map((asset) => { - assert(fs.existsSync(asset.file), `missing release asset: ${asset.file}`); - const actual = sha256File(asset.file); - const expected = checksums.get(asset.name); - if (asset.name !== "SHA256SUMS") { - assert.strictEqual(actual, expected, `checksum mismatch for ${asset.name}`); - } - return { - name: asset.name, - file: asset.file, - bytes: fs.statSync(asset.file).size, - sha256: actual, - }; -}); -const binaryAsset = manifest.assets.find((asset) => - asset.name.startsWith("clusterflux-public-binaries-") -); -const hostedBinaryAsset = manifest.assets.find((asset) => - asset.name.startsWith("clusterflux-hosted-") -); -assert(binaryAsset, "manifest must include the exact candidate binary archive"); -assert(hostedBinaryAsset, "manifest must include the exact hosted binary archive"); -for (const [name, digest] of Object.entries(manifest.binary_digests)) { - const archive = name === "clusterflux-hosted-service" ? hostedBinaryAsset : binaryAsset; - const binary = readArchiveMember(archive.file, `bin/${name}`); - assert.strictEqual( - `sha256:${sha256Buffer(binary)}`, - digest, - `candidate archive binary ${name} does not match the manifest` - ); -} - -assert( - manifest.final_evidence && manifest.final_evidence.complete === true, - "release publication requires complete final result and transcript evidence" -); -const evidenceAsset = manifest.assets.find((asset) => - asset.name.startsWith("clusterflux-public-evidence-") -); -assert(evidenceAsset, "manifest must include the final evidence archive"); -const binding = JSON.parse( - readArchiveMember(evidenceAsset.file, "EVIDENCE_BINDING.json").toString("utf8") -); -assert.strictEqual(binding.source_commit, currentSourceCommit); -assert.strictEqual(binding.source_tree_digest, manifest.source_tree_digest); -assert.strictEqual(binding.public_tree_identity, manifest.public_tree_identity); -assert.deepStrictEqual(binding.binary_digests, manifest.binary_digests); -assert(binding.final_evidence && binding.final_evidence.complete === true); -assert(Array.isArray(binding.included_evidence)); -const includedEvidence = new Map( - binding.included_evidence.map((entry) => [entry.name, entry.sha256]) -); -for (const required of ["FINAL_RELEASE_RESULT.json", "FINAL_RELEASE_TRANSCRIPT.txt"]) { - assert(includedEvidence.has(required), `final evidence archive is missing ${required}`); - const contents = readArchiveMember(evidenceAsset.file, required); - assert.strictEqual( - sha256Buffer(contents), - includedEvidence.get(required), - `final evidence digest mismatch for ${required}` - ); -} -const finalResult = JSON.parse( - readArchiveMember(evidenceAsset.file, "FINAL_RELEASE_RESULT.json").toString("utf8") -); -assert.strictEqual(finalResult.source_commit, currentSourceCommit); -assert.strictEqual(finalResult.source_tree_digest, manifest.source_tree_digest); -assert.strictEqual(finalResult.public_tree_identity, manifest.public_tree_identity); -assert.deepStrictEqual(finalResult.binary_digests, manifest.binary_digests); -assert.strictEqual( - manifest.release_candidate?.mode, - "finalized-exact", - "publication requires exact candidate finalization" -); -assert.strictEqual(finalResult.release_binding?.source_commit, currentSourceCommit); -assert.strictEqual( - finalResult.release_binding?.source_tree_digest, - manifest.source_tree_digest -); -assert.strictEqual( - finalResult.release_binding?.public_tree_identity, - manifest.public_tree_identity -); -assert.deepStrictEqual( - finalResult.release_binding?.binary_digests, - manifest.binary_digests -); -assert.deepStrictEqual( - finalResult.release_candidate, - manifest.release_candidate -); -assert.strictEqual(finalResult.acceptance_result, "passed"); -assert.deepStrictEqual(finalResult.scenario_skips, []); -assert( - finalResult.release_binding?.deployment && - finalResult.release_binding?.configuration && - finalResult.release_binding?.proxy_configuration, - "final evidence must bind deployment, runtime configuration, and proxy configuration identities" -); -if (manifest.candidate_configuration_identity) { - assert.strictEqual( - finalResult.release_binding.configuration.evidence_identity, - manifest.candidate_configuration_identity, - "live configuration identity differs from the candidate binding" - ); -} -if (manifest.candidate_proxy_configuration_identity) { - assert.strictEqual( - finalResult.release_binding.proxy_configuration.evidence_identity, - manifest.candidate_proxy_configuration_identity, - "live proxy configuration identity differs from the candidate binding" - ); -} -assert( - Array.isArray(finalResult.named_scenarios) && - finalResult.named_scenarios.length >= 29 && - finalResult.named_scenarios.length === - finalResult.strict_requirement_ledger.length && - finalResult.named_scenarios.every( - (scenario) => - scenario.status === "passed" && - Number.isFinite(scenario.duration_ms) && - scenario.duration_ms > 0 - ), - "all named final checks must be present, measured, and passed" -); -assert( - Array.isArray(finalResult.strict_requirement_ledger) && - finalResult.strict_requirement_ledger.length > 0 && - finalResult.strict_requirement_ledger.every( - (requirement) => - requirement.passed === true && - Number.isFinite(requirement.duration_ms) && - requirement.duration_ms > 0 && - requirement.evidence - ), - "the strict final requirement ledger must be present and passed" -); -const finalTranscript = readArchiveMember( - evidenceAsset.file, - "FINAL_RELEASE_TRANSCRIPT.txt" -).toString("utf8"); -for (const identity of [ - currentSourceCommit, - manifest.source_tree_digest, - manifest.public_tree_identity, - ...Object.values(manifest.binary_digests), -]) { - assert(finalTranscript.includes(identity), `final transcript is missing identity ${identity}`); -} - -const evidence = [ - staleEvidence( - path.join(acceptanceRoot, "public-release-forgejo-release.json"), - currentSourceCommit - ), - staleEvidence( - path.join(acceptanceRoot, "public-release-service.json"), - currentSourceCommit - ), - staleEvidence( - path.join(acceptanceRoot, "hosted-client-compat.json"), - currentSourceCommit - ), - staleEvidence( - path.join(acceptanceRoot, "core-coordinator-compat.json"), - currentSourceCommit - ), - staleEvidence( - path.join(acceptanceRoot, "public-release-e2e.json"), - currentSourceCommit - ), - staleEvidence( - path.join(acceptanceRoot, "public-release-final.json"), - currentSourceCommit - ), -]; - -const report = { - kind: "clusterflux-public-release-preflight", - source_commit: currentSourceCommit, - release_name: manifest.release_name, - public_tree_commit: publicTreeCommit || remoteMain, - public_tree_push_source: publicTreePushSource(manifest), - public_repo_url: publicRepoRemote, - public_repo_remote_head: remoteMain, - source_tree_clean: currentTreeStatus === "", - local_assets_ready: true, - assets, - final_evidence: { - complete: true, - binding, - }, - evidence, - external_gates: { - forgejo_release_publication: { - status: envState("CLUSTERFLUX_FORGEJO_TOKEN") === "set" ? "ready" : "pending", - env: { - CLUSTERFLUX_FORGEJO_TOKEN: envState("CLUSTERFLUX_FORGEJO_TOKEN"), - }, - }, - live_service_smoke: { - status: - envState("CLUSTERFLUX_PUBLIC_RELEASE_SERVICE_ADDR") === "set" && - envState("CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND") === "set" - ? "ready" - : "pending", - env: { - CLUSTERFLUX_PUBLIC_RELEASE_SERVICE_ADDR: envState( - "CLUSTERFLUX_PUBLIC_RELEASE_SERVICE_ADDR" - ), - CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND: envState( - "CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND" - ), - }, - }, - public_release_e2e: { - status: - envState("CLUSTERFLUX_PUBLIC_RELEASE_E2E") === "set" && - process.env.CLUSTERFLUX_PUBLIC_RELEASE_E2E === "1" && - envState("CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND") === "set" - ? "ready" - : "pending", - env: { - CLUSTERFLUX_PUBLIC_RELEASE_E2E: - process.env.CLUSTERFLUX_PUBLIC_RELEASE_E2E || "unset", - CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND: envState( - "CLUSTERFLUX_PUBLIC_RELEASE_BROWSER_OPEN_COMMAND" - ), - }, - }, - final_evidence: { - status: - envState("CLUSTERFLUX_PUBLIC_RELEASE_FINAL") === "set" && - process.env.CLUSTERFLUX_PUBLIC_RELEASE_FINAL === "1" - ? "ready" - : "pending", - env: { - CLUSTERFLUX_PUBLIC_RELEASE_FINAL: - process.env.CLUSTERFLUX_PUBLIC_RELEASE_FINAL || "unset", - }, - }, - }, -}; - -fs.mkdirSync(path.dirname(reportPath), { recursive: true }); -fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); -console.log(JSON.stringify({ report: reportPath, release_name: report.release_name }, null, 2)); diff --git a/scripts/public-repository-gate.sh b/scripts/public-repository-gate.sh deleted file mode 100755 index 333585d..0000000 --- a/scripts/public-repository-gate.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -cd "$repo" - -scripts/verify-public-split.sh diff --git a/scripts/publish-public-release.js b/scripts/publish-public-release.js deleted file mode 100755 index 8fd76e4..0000000 --- a/scripts/publish-public-release.js +++ /dev/null @@ -1,354 +0,0 @@ -#!/usr/bin/env node - -const fs = require("fs"); -const https = require("https"); -const path = require("path"); -const cp = require("child_process"); - -const repo = path.resolve(__dirname, ".."); -const releaseRoot = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_DIR || - path.join(repo, "target/public-release") -); -const manifestPath = path.join(releaseRoot, "public-release-manifest.json"); -const reportPath = path.join( - repo, - "target/acceptance/public-release-forgejo-release.json" -); -const forgejoUrl = ( - process.env.CLUSTERFLUX_FORGEJO_URL || "https://git.michelpaulissen.com" -).replace(/\/+$/, ""); -const token = process.env.CLUSTERFLUX_FORGEJO_TOKEN; -let owner = process.env.CLUSTERFLUX_PUBLIC_REPO_OWNER; -let repoName = process.env.CLUSTERFLUX_PUBLIC_REPO_NAME; - -function requireEnv(name, value) { - if (!value) { - throw new Error(`${name} is required`); - } -} - -function commandOutput(command, args) { - try { - return cp - .execFileSync(command, args, { - cwd: repo, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - }) - .trim(); - } catch (_) { - return null; - } -} - -function expectedSourceCommit() { - return ( - process.env.CLUSTERFLUX_ACCEPTANCE_COMMIT || - commandOutput("git", ["rev-parse", "HEAD"]) || - "unknown" - ); -} - -function parseForgejoRepoIdentity(remote) { - if (!remote) { - return null; - } - - let pathname = remote; - try { - pathname = new URL(remote).pathname; - } catch (_) { - const scpLike = /^[^@/]+@[^:]+:(.+)$/.exec(remote); - if (scpLike) { - pathname = scpLike[1]; - } - } - - const parts = pathname - .replace(/^\/+/, "") - .replace(/\.git$/, "") - .split("/") - .filter(Boolean); - if (parts.length < 2) { - return null; - } - return { - owner: parts[parts.length - 2], - repoName: parts[parts.length - 1], - }; -} - -function resolveRepoIdentity(manifest) { - if (owner && repoName) { - return; - } - - const inferred = parseForgejoRepoIdentity( - manifest.public_repo_url || - manifest.public_repo_remote || - process.env.CLUSTERFLUX_PUBLIC_REPO_REMOTE - ); - owner = owner || (inferred && inferred.owner); - repoName = repoName || (inferred && inferred.repoName); - if (!owner || !repoName) { - throw new Error( - "CLUSTERFLUX_PUBLIC_REPO_OWNER and CLUSTERFLUX_PUBLIC_REPO_NAME are required when the manifest does not contain a parseable Forgejo repository URL" - ); - } -} - -function publicTreeAlreadyPushed(manifest) { - return ( - (manifest.public_tree_publish && manifest.public_tree_publish.pushed === true) || - process.env.CLUSTERFLUX_PUBLIC_TREE_ALREADY_PUSHED === "1" - ); -} - -function publicTreeCommit(manifest) { - return ( - (manifest.public_tree_publish && manifest.public_tree_publish.commit) || - process.env.CLUSTERFLUX_PUBLIC_TREE_COMMIT || - process.env.CLUSTERFLUX_PUBLIC_RELEASE_TARGET || - null - ); -} - -function apiPath(pathname) { - return `/api/v1${pathname}`; -} - -function request(method, pathname, { body, headers = {} } = {}) { - const url = new URL(apiPath(pathname), forgejoUrl); - const payload = - body === undefined - ? null - : Buffer.isBuffer(body) - ? body - : Buffer.from(JSON.stringify(body)); - const requestHeaders = { - Accept: "application/json", - Authorization: `token ${token}`, - ...headers, - }; - if (payload) { - requestHeaders["Content-Length"] = payload.length; - if (!requestHeaders["Content-Type"]) { - requestHeaders["Content-Type"] = "application/json"; - } - } - - return new Promise((resolve, reject) => { - const req = https.request( - url, - { - method, - headers: requestHeaders, - }, - (res) => { - const chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => { - const text = Buffer.concat(chunks).toString("utf8"); - let parsed = null; - if (text.trim()) { - try { - parsed = JSON.parse(text); - } catch (_) { - parsed = text; - } - } - if (res.statusCode < 200 || res.statusCode >= 300) { - reject( - new Error( - `${method} ${url.pathname} failed with ${res.statusCode}: ${text}` - ) - ); - return; - } - resolve({ status: res.statusCode, body: parsed }); - }); - } - ); - req.on("error", reject); - if (payload) req.write(payload); - req.end(); - }); -} - -function multipartFile(fieldName, file) { - const boundary = `clusterflux-${Date.now()}-${Math.random().toString(16).slice(2)}`; - const name = path.basename(file); - const header = Buffer.from( - `--${boundary}\r\n` + - `Content-Disposition: form-data; name="${fieldName}"; filename="${name}"\r\n` + - "Content-Type: application/octet-stream\r\n\r\n" - ); - const footer = Buffer.from(`\r\n--${boundary}--\r\n`); - return { - body: Buffer.concat([header, fs.readFileSync(file), footer]), - contentType: `multipart/form-data; boundary=${boundary}`, - }; -} - -async function existingRelease(tagName) { - const releases = await request( - "GET", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/releases?limit=100` - ); - return (releases.body || []).find((release) => release.tag_name === tagName) || null; -} - -async function createOrReuseRelease(manifest) { - const tagName = manifest.release_name; - const found = await existingRelease(tagName); - if (found) { - return { release: found, created: false }; - } - const targetCommitish = - publicTreeCommit(manifest) || - "main"; - const body = [ - "Clusterflux public release.", - "", - `Default hosted coordinator endpoint: ${manifest.default_hosted_coordinator_endpoint}`, - `DNS publication state: ${manifest.dns_publication_state}`, - `Resolver override: ${manifest.resolver_override}`, - `Public tree identity: ${manifest.public_tree_identity}`, - `Source commit: ${manifest.source_commit}`, - ].join("\n"); - const created = await request( - "POST", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/releases`, - { - body: { - tag_name: tagName, - target_commitish: targetCommitish, - name: tagName, - body, - draft: false, - prerelease: false, - }, - } - ); - return { release: created.body, created: true }; -} - -async function loadRelease(releaseId) { - const response = await request( - "GET", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/releases/${releaseId}` - ); - return response.body; -} - -async function uploadAsset(release, asset) { - const { body, contentType } = multipartFile("attachment", asset.file); - const response = await request( - "POST", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/releases/${release.id}/assets?name=${encodeURIComponent(asset.name)}`, - { - body, - headers: { - "Content-Type": contentType, - }, - } - ); - return response.body; -} - -function existingAssetByName(release, name) { - return Array.isArray(release.assets) - ? release.assets.find((asset) => asset.name === name) || null - : null; -} - -async function main() { - requireEnv("CLUSTERFLUX_FORGEJO_TOKEN", token); - if (!fs.existsSync(manifestPath)) { - throw new Error(`missing public release manifest: ${manifestPath}`); - } - - const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - for (const asset of manifest.assets ?? []) { - asset.file = path.isAbsolute(asset.file) - ? asset.file - : path.resolve(path.dirname(manifestPath), asset.file); - } - resolveRepoIdentity(manifest); - if (manifest.kind !== "clusterflux-public-release") { - throw new Error(`unexpected public release manifest kind: ${manifest.kind}`); - } - if (manifest.source_commit !== expectedSourceCommit()) { - throw new Error( - "public release manifest is stale; regenerate it for the current acceptance commit before publishing the Forgejo Release" - ); - } - if ( - !publicTreeAlreadyPushed(manifest) - ) { - throw new Error( - "public tree must be pushed before publishing the Forgejo Release; run prepare-public-release.js with CLUSTERFLUX_PUBLISH_PUBLIC_TREE=1" - ); - } - if (!Array.isArray(manifest.assets) || manifest.assets.length === 0) { - throw new Error("public release manifest has no assets"); - } - - const { release: releaseResult, created } = await createOrReuseRelease(manifest); - const release = await loadRelease(releaseResult.id); - const uploaded = []; - const reused = []; - for (const asset of manifest.assets) { - if (!fs.existsSync(asset.file)) { - throw new Error(`missing release asset: ${asset.file}`); - } - const existing = existingAssetByName(release, asset.name); - if (existing) { - reused.push(existing); - continue; - } - uploaded.push(await uploadAsset(release, asset)); - } - - fs.mkdirSync(path.dirname(reportPath), { recursive: true }); - const report = { - kind: "clusterflux-public-release-forgejo-release", - forgejo_url: forgejoUrl, - owner, - repo: repoName, - release_id: release.id, - release_name: release.name || manifest.release_name, - tag_name: release.tag_name || manifest.release_name, - release_created: created, - default_hosted_coordinator_endpoint: manifest.default_hosted_coordinator_endpoint, - public_tree_identity: manifest.public_tree_identity, - public_tree_commit: publicTreeCommit(manifest), - source_commit: manifest.source_commit, - uploaded_assets: uploaded.map((asset) => ({ - id: asset.id, - name: asset.name, - size: asset.size, - browser_download_url: asset.browser_download_url, - })), - reused_assets: reused.map((asset) => ({ - id: asset.id, - name: asset.name, - size: asset.size, - browser_download_url: asset.browser_download_url, - })), - }; - fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); - console.log( - JSON.stringify( - { report: reportPath, uploaded: uploaded.length, reused: reused.length }, - null, - 2 - ) - ); -} - -main().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/quic-smoke.js b/scripts/quic-smoke.js deleted file mode 100755 index 5ad4634..0000000 --- a/scripts/quic-smoke.js +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); - -const repo = path.resolve(__dirname, ".."); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function rendezvousRequest(overrides = {}) { - return { - type: "request_rendezvous", - scope: { - tenant: "tenant", - project: "project", - process: "vp-quic", - object: { Artifact: "quic-artifact" }, - authorization_subject: "node-a-to-node-b", - }, - source: { - node: "node-a", - advertised_addr: "node-a.mesh.invalid:4433", - public_key_fingerprint: "sha256:node-a-public-key", - }, - destination: { - node: "node-b", - advertised_addr: "node-b.mesh.invalid:4433", - public_key_fingerprint: "sha256:node-b-public-key", - }, - direct_connectivity: true, - failure_reason: "", - ...overrides, - }; -} - -(async () => { - const output = cp.execFileSync( - "cargo", - ["run", "-q", "-p", "clusterflux-node", "--bin", "clusterflux-quic-smoke"], - { cwd: repo, encoding: "utf8" } - ); - const report = JSON.parse(output.trim().split("\n").at(-1)); - - assert.strictEqual(report.kind, "clusterflux_quic_smoke"); - assert.strictEqual(report.transport, "NativeQuic"); - assert.strictEqual(report.rust_native_quic, true); - assert.strictEqual(report.authenticated_direct_connection, true); - assert.strictEqual(report.coordinator_assisted_rendezvous, true); - assert.strictEqual(report.coordinator_bulk_relay_allowed, false); - assert.strictEqual(report.source_node, "node-a"); - assert.strictEqual(report.destination_node, "node-b"); - assert.strictEqual(report.scope.tenant, "tenant"); - assert.strictEqual(report.scope.project, "project"); - assert.strictEqual(report.scope.process, "vp-quic"); - assert.deepStrictEqual(report.scope.object, { Artifact: "quic-artifact" }); - assert.ok(report.authorization_digest.startsWith("sha256:")); - assert.ok(report.request_bytes > 0); - assert.strictEqual(report.server_received_request_bytes, report.request_bytes); - assert.ok(report.payload_bytes > 0); - - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback", - ], - { cwd: repo } - ); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - - const plan = await send(addr, rendezvousRequest()); - assert.strictEqual(plan.type, "rendezvous_plan"); - assert.strictEqual(plan.charged_rendezvous_attempts, 1); - assert.strictEqual(plan.plan.transport, "NativeQuic"); - assert.strictEqual(plan.plan.scope.tenant, "tenant"); - assert.strictEqual(plan.plan.scope.project, "project"); - assert.strictEqual(plan.plan.source.node, "node-a"); - assert.strictEqual(plan.plan.destination.node, "node-b"); - assert.strictEqual(plan.plan.coordinator_assisted_rendezvous, true); - assert.strictEqual(plan.plan.coordinator_bulk_relay_allowed, false); - assert.ok(plan.plan.authorization_digest.startsWith("sha256:")); - - const failed = await send( - addr, - rendezvousRequest({ - direct_connectivity: false, - failure_reason: "nat traversal failed", - }) - ); - assert.strictEqual(failed.type, "error"); - assert.match(failed.message, /nat traversal failed/); - assert.match(failed.message, /coordinator bulk relay is disabled/); - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("QUIC smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/real-flagship-harness.js b/scripts/real-flagship-harness.js deleted file mode 100644 index 1320f23..0000000 --- a/scripts/real-flagship-harness.js +++ /dev/null @@ -1,285 +0,0 @@ -const assert = require("assert"); -const cp = require("child_process"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { configurePodmanTestEnvironment } = require("./podman-test-env"); - -const repo = path.resolve(__dirname, ".."); -const project = path.join(repo, "examples/hello-build"); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.stderr?.on("data", (chunk) => { - stderr += chunk.toString(); - if (stderr.length > 4096) stderr = stderr.slice(-4096); - }); - child.once("exit", (code) => { - const detail = stderr.trim(); - reject(new Error( - `process exited before JSON line with code ${code}${detail ? `: ${detail}` : ""}` - )); - }); - }); -} - -function waitForNodeStatus(child, expectedStatus) { - return new Promise((resolve, reject) => { - let buffer = ""; - let stderr = ""; - const cleanup = () => { - child.stdout.off("data", onData); - child.stderr?.off("data", onStderr); - child.off("exit", onExit); - }; - const onData = (chunk) => { - buffer += chunk.toString(); - while (buffer.includes("\n")) { - const newline = buffer.indexOf("\n"); - const line = buffer.slice(0, newline).trim(); - buffer = buffer.slice(newline + 1); - if (!line) continue; - let event; - try { - event = JSON.parse(line); - } catch (error) { - cleanup(); - reject(error); - return; - } - if (event.node_status === expectedStatus) { - cleanup(); - resolve(event); - return; - } - } - }; - const onStderr = (chunk) => { - stderr += chunk.toString(); - if (stderr.length > 4096) stderr = stderr.slice(-4096); - }; - const onExit = (code) => { - cleanup(); - const detail = stderr.trim(); - reject( - new Error( - `worker exited before node status ${expectedStatus} with code ${code}${ - detail ? `: ${detail}` : "" - }` - ) - ); - }; - child.stdout.on("data", onData); - child.stderr?.on("data", onStderr); - child.once("exit", onExit); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function configureContainerPolicyHome() { - configurePodmanTestEnvironment(repo); -} - -function commandWithPodman(program, args) { - if (cp.spawnSync("podman", ["--version"], { stdio: "ignore" }).status === 0) { - return { program, args }; - } - if (cp.spawnSync("nix", ["--version"], { stdio: "ignore" }).status === 0) { - return { - program: "nix", - args: ["shell", "nixpkgs#podman", "--command", program, ...args], - }; - } - throw new Error( - "real flagship smoke requires rootless Podman (or Nix to provide it)" - ); -} - -function ensureRootlessPodman() { - configureContainerPolicyHome(); - const invocation = commandWithPodman("podman", [ - "info", - "--format", - "{{.Host.Security.Rootless}}", - ]); - const rootless = cp.execFileSync(invocation.program, invocation.args, { - cwd: repo, - env: process.env, - encoding: "utf8", - }).trim(); - assert.strictEqual(rootless, "true", "flagship worker must use rootless Podman"); -} - -async function runFlagshipWorker(addr, node, identity, projectRoot = project) { - const enrollment = await send(addr, { - type: "create_node_enrollment_grant", - tenant: "tenant", - project: "project", - actor_user: "user", - ttl_seconds: 60, - }); - assert.strictEqual(enrollment.type, "node_enrollment_grant_created"); - const cargoArgs = [ - "run", "-q", "-p", "clusterflux-node", "--bin", "clusterflux-node", "--", - "--coordinator", `${addr.host}:${addr.port}`, - "--tenant", "tenant", - "--project-id", "project", - "--node", node, - "--enrollment-grant", enrollment.grant, - "--worker", - "--emit-ready", - "--project-root", projectRoot, - "--assignment-poll-ms", "25", - ]; - const invocation = commandWithPodman("cargo", cargoArgs); - const child = cp.spawn(invocation.program, invocation.args, { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_NODE_PRIVATE_KEY: identity.privateKey, - }, - }); - return { child, ready: waitForJsonLine(child) }; -} - -const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); - -async function waitForTaskEvent(addr, process, predicate, description) { - for (let attempt = 0; attempt < 2400; attempt += 1) { - const response = await send(addr, { - type: "list_task_events", - tenant: "tenant", - project: "project", - actor_user: "user", - process, - }); - assert.strictEqual(response.type, "task_events", JSON.stringify(response)); - const event = response.events.find(predicate); - if (event) return event; - await delay(25); - } - throw new Error(`timed out waiting for real Wasm task ${description}`); -} - -function startFlagship(addr, projectRoot = project) { - const report = JSON.parse( - cp.execFileSync( - "cargo", - [ - "run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", - "run", "build", - "--coordinator", `clusterflux+tcp://${addr.host}:${addr.port}`, - "--project", projectRoot, - "--json", - ], - { cwd: repo, env: process.env, encoding: "utf8" } - ) - ); - assert.strictEqual(report.command, "run"); - assert.strictEqual(report.status, "main_launched", JSON.stringify(report)); - assert.strictEqual(report.entry, "build"); - assert.strictEqual(report.task_launch.type, "main_launched"); - assert.strictEqual(report.task_launch.task_instance, report.task_instance); - assert.strictEqual(report.task_launch.task_definition, report.task_definition); - assert.strictEqual(report.worker_placement_requested, true); - assert.match(report.bundle_digest, /^sha256:[0-9a-f]{64}$/); - assert.match(report.entry_export, /^clusterflux_entry_v1_/); - const virtualProcess = report.process; - return { report, process: virtualProcess }; -} - -async function launchFlagship(addr) { - const { report, process: virtualProcess } = startFlagship(addr); - const compileEvent = await waitForTaskEvent( - addr, - virtualProcess, - (event) => event.task_definition === "compile", - "compile" - ); - const sourceEvent = await waitForTaskEvent( - addr, - virtualProcess, - (event) => event.task_definition === "snapshot_current_project", - "snapshot_current_project" - ); - const packageEvent = compileEvent; - const buildEvent = await waitForTaskEvent( - addr, - virtualProcess, - (event) => event.task === report.task_instance && event.executor === "coordinator_main", - "coordinator build main" - ); - for (const event of [sourceEvent, compileEvent, buildEvent]) { - assert.strictEqual(event.terminal_state, "completed", JSON.stringify(event)); - } - return { - report, - process: virtualProcess, - compileEvent, - sourceEvent, - packageEvent, - buildEvent, - }; -} - -function flagshipNodeCapabilities() { - return { - os: "Linux", - arch: process.arch, - capabilities: [ - "Command", - "Containers", - "RootlessPodman", - "SourceFilesystem", - "VfsArtifacts", - ], - environment_backends: ["Container"], - source_providers: ["filesystem"], - }; -} - -module.exports = { - ensureRootlessPodman, - flagshipNodeCapabilities, - launchFlagship, - project, - repo, - runFlagshipWorker, - send, - startFlagship, - waitForTaskEvent, - waitForJsonLine, - waitForNodeStatus, -}; diff --git a/scripts/recovery-build-smoke.js b/scripts/recovery-build-smoke.js deleted file mode 100755 index 202d788..0000000 --- a/scripts/recovery-build-smoke.js +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); -const { DapClient } = require("./dap-client"); -const { configurePodmanTestEnvironment } = require("./podman-test-env"); - -const repo = path.resolve(__dirname, ".."); -const project = path.join(repo, "examples/recovery-build"); -const sourcePath = fs.realpathSync(path.join(project, "src/lib.rs")); -const original = fs.readFileSync(sourcePath, "utf8"); -const failing = "\"exit 23\".to_owned()"; -const replacement = - "\"printf 'recovered\\n' > /clusterflux/output/recovering.txt\".to_owned()"; -assert(original.includes(failing), "recovery source must contain the real failing command"); -configurePodmanTestEnvironment(repo); - -(async () => { - const client = new DapClient({ - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_DAP_TIMEOUT_MS: - process.env.CLUSTERFLUX_DAP_TIMEOUT_MS || "120000", - }, - }); - let restored = false; - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true, - }); - await client.response(initialize, "initialize"); - - const launch = client.send("launch", { - entry: "build", - project, - runtimeBackend: "local-services", - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const configured = client.send("configurationDone"); - await client.response(configured, "configurationDone"); - const failed = await client.waitFor( - (message) => - message.type === "event" && - message.event === "stopped" && - message.body.reason === "exception" - ); - assert.strictEqual(failed.body.allThreadsStopped, false); - - const threadRequest = client.send("threads"); - const threads = (await client.response(threadRequest, "threads")).body.threads; - const laneThreads = threads - .filter((thread) => /build[_ ]lane/.test(thread.name)) - .sort((left, right) => left.id - right.id); - assert.strictEqual( - laneThreads.length, - 1, - "only the failed recovering lane should remain a live DAP thread" - ); - const recoveringThread = laneThreads[0]; - const views = JSON.parse( - fs.readFileSync(path.join(project, ".clusterflux/views.json"), "utf8") - ); - const nodeReport = JSON.parse( - views.inspector.find((item) => item.label === "Node report").value - ); - const laneSnapshots = nodeReport.task_snapshots.snapshots.filter( - (snapshot) => snapshot.task_definition === "build_lane" - ); - assert.strictEqual(laneSnapshots.length, 2); - assert.notStrictEqual(laneSnapshots[0].task, laneSnapshots[1].task); - assert(laneSnapshots.some((snapshot) => snapshot.state === "completed")); - assert( - laneSnapshots.some( - (snapshot) => snapshot.state === "failed_awaiting_action" - ) - ); - const startedIds = new Set( - client.messages - .filter( - (message) => - message.type === "event" && - message.event === "thread" && - message.body.reason === "started" - ) - .map((message) => message.body.threadId) - ); - const laneStartedIds = [...startedIds] - .filter((id) => id !== 1) - .sort((left, right) => left - right) - .slice(-2); - assert.strictEqual(laneStartedIds.length, 2); - assert.notStrictEqual(laneStartedIds[0], laneStartedIds[1]); - assert(startedIds.has(recoveringThread.id)); - - fs.writeFileSync(sourcePath, original.replace(failing, replacement)); - const restart = client.send("restartFrame", { - threadId: recoveringThread.id, - }); - await client.response(restart, "restartFrame"); - const terminated = await client.waitFor( - (message) => - message.type === "event" && - message.event === "terminated" - ); - assert(terminated); - - const exitedIds = new Set( - client.messages - .filter( - (message) => - message.type === "event" && - message.event === "thread" && - message.body.reason === "exited" - ) - .map((message) => message.body.threadId) - ); - assert(exitedIds.has(laneStartedIds[0])); - assert(exitedIds.has(recoveringThread.id)); - - fs.writeFileSync(sourcePath, original); - restored = true; - await client.close(); - console.log("Recovery build DAP restart smoke passed"); - } finally { - if (!restored) fs.writeFileSync(sourcePath, original); - if (client.child.exitCode === null) client.child.kill("SIGKILL"); - } -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/release-quality-gates.js b/scripts/release-quality-gates.js deleted file mode 100755 index 5ec6343..0000000 --- a/scripts/release-quality-gates.js +++ /dev/null @@ -1,322 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const os = require("os"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const manifestPath = path.resolve( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_MANIFEST || - path.join( - process.env.CLUSTERFLUX_PUBLIC_RELEASE_DIR || - path.join(repo, "target/release-candidate"), - "public-release-manifest.json" - ) -); -const evidencePath = path.resolve( - process.env.CLUSTERFLUX_QUALITY_GATE_EVIDENCE_PATH || - path.join(repo, "target/acceptance/quality-gates.json") -); -const transcriptPath = path.resolve( - process.env.CLUSTERFLUX_QUALITY_GATE_TRANSCRIPT_PATH || - path.join(repo, "target/acceptance/quality-gates-transcript.txt") -); - -function readJson(file) { - return JSON.parse(fs.readFileSync(file, "utf8")); -} - -function sha256(file) { - return crypto - .createHash("sha256") - .update(fs.readFileSync(file)) - .digest("hex"); -} - -function commandText(command, args) { - return [command, ...args] - .map((value) => - /^[A-Za-z0-9_./:=+-]+$/.test(value) - ? value - : JSON.stringify(value) - ) - .join(" "); -} - -function main() { - assert(fs.existsSync(manifestPath), `missing release manifest ${manifestPath}`); - const manifest = readJson(manifestPath); - fs.mkdirSync(path.dirname(evidencePath), { recursive: true }); - fs.mkdirSync(path.dirname(transcriptPath), { recursive: true }); - const transcript = fs.openSync(transcriptPath, "w"); - const evidence = { - kind: "clusterflux-release-quality-gates", - source_commit: manifest.source_commit, - source_tree_digest: manifest.source_tree_digest, - public_tree_identity: manifest.public_tree_identity, - checks: {}, - }; - - const runGroup = (id, commands, extra = {}) => { - const startedAt = Date.now(); - const commandEvidence = []; - let status = "passed"; - for (const command of commands) { - const args = command.args || []; - const cwd = command.cwd || repo; - const text = commandText(command.command, args); - fs.writeSync(transcript, `\n[${id}] ${text}\n`); - const commandStartedAt = Date.now(); - const result = cp.spawnSync(command.command, args, { - cwd, - env: { ...process.env, ...(command.env || {}) }, - stdio: ["ignore", transcript, transcript], - }); - const durationMs = Math.max(1, Date.now() - commandStartedAt); - commandEvidence.push({ - command: text, - cwd, - exit_status: result.status, - duration_ms: durationMs, - }); - if (result.error || result.status !== 0) { - status = "failed"; - evidence.checks[id] = { - status, - duration_ms: Math.max(1, Date.now() - startedAt), - commands: commandEvidence, - error: result.error?.message || `command exited ${result.status}`, - ...extra, - }; - fs.writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`); - throw new Error(`${id} failed: ${text}`); - } - } - evidence.checks[id] = { - status, - duration_ms: Math.max(1, Date.now() - startedAt), - commands: commandEvidence, - ...extra, - }; - }; - - try { - runGroup("repository_structure", [ - { command: path.join(repo, "scripts/check-old-name.sh") }, - { command: "node", args: [path.join(repo, "scripts/check-docs.js")] }, - { command: path.join(repo, "scripts/check-code-size.sh") }, - ]); - runGroup("formatting", [ - { command: "cargo", args: ["fmt", "--all", "--check"] }, - { - command: "cargo", - args: [ - "fmt", - "--all", - "--manifest-path", - "private/hosted-policy/Cargo.toml", - "--check", - ], - }, - ]); - runGroup("clippy_warnings_denied", [ - { - command: "cargo", - args: ["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"], - }, - { - command: "cargo", - args: [ - "clippy", - "--manifest-path", - "private/hosted-policy/Cargo.toml", - "--all-targets", - "--", - "-D", - "warnings", - ], - }, - ]); - runGroup("public_workspace_tests", [ - { - command: "cargo", - args: ["test", "--workspace", "--all-targets"], - }, - { - command: "cargo", - args: ["build", "--workspace", "--all-targets"], - }, - ]); - runGroup("private_hosted_policy_locked_tests", [ - { - command: "cargo", - args: [ - "test", - "--locked", - "--manifest-path", - "private/hosted-policy/Cargo.toml", - "--all-targets", - ], - }, - ]); - runGroup("process_lifecycle_regressions", [ - { - command: "cargo", - args: [ - "test", - "-p", - "clusterflux-coordinator", - "completed_main_", - ], - }, - { - command: "cargo", - args: [ - "test", - "-p", - "clusterflux-coordinator", - "failed_main_aborts_unfinished_children_and_clears_process_debug_state", - ], - }, - { - command: "cargo", - args: [ - "test", - "-p", - "clusterflux-coordinator", - "service_cancels_whole_process_and_blocks_new_task_launches", - ], - }, - ]); - runGroup("wasm_example_builds", [ - { - command: "cargo", - args: [ - "build", - "-p", - "hello-build", - "--target", - "wasm32-unknown-unknown", - ], - }, - { - command: "cargo", - args: [ - "build", - "-p", - "recovery-build", - "--target", - "wasm32-unknown-unknown", - ], - }, - { - command: "cargo", - args: [ - "build", - "-p", - "runtime-conformance", - "--target", - "wasm32-unknown-unknown", - ], - }, - ]); - runGroup("filtered_public_tree_build_and_tests", [ - { command: path.join(repo, "scripts/verify-public-split.sh") }, - ]); - - const extensionAsset = manifest.assets.find((asset) => - asset.name.endsWith(".vsix") - ); - assert(extensionAsset, "candidate manifest omitted its VSIX"); - const extensionFile = path.resolve( - path.dirname(manifestPath), - extensionAsset.file - ); - assert(fs.existsSync(extensionFile), `missing candidate VSIX ${extensionFile}`); - const extensionDigest = sha256(extensionFile); - assert.strictEqual(extensionDigest, extensionAsset.sha256); - assert.strictEqual( - extensionDigest, - manifest.release_candidate.extension_sha256 - ); - const extractedVsix = fs.mkdtempSync( - path.join(os.tmpdir(), "clusterflux-tested-vsix-") - ); - try { - runGroup( - "vscode_extension_candidate", - [ - { - command: "npm", - args: ["ci", "--ignore-scripts"], - cwd: path.join(repo, "vscode-extension"), - }, - { - command: "unzip", - args: ["-q", extensionFile, "-d", extractedVsix], - }, - { - command: "node", - args: [path.join(repo, "scripts/vscode-extension-smoke.js")], - env: { - CLUSTERFLUX_VSCODE_EXTENSION_ROOT: path.join( - extractedVsix, - "extension" - ), - }, - }, - ], - { - candidate_vsix: { - file: extensionFile, - sha256: extensionDigest, - }, - } - ); - } finally { - fs.rmSync(extractedVsix, { recursive: true, force: true }); - } - - const publicCheckIds = [ - "repository_structure", - "formatting", - "clippy_warnings_denied", - "public_workspace_tests", - "process_lifecycle_regressions", - "wasm_example_builds", - "filtered_public_tree_build_and_tests", - "vscode_extension_candidate", - ]; - evidence.public = { - status: "passed", - duration_ms: publicCheckIds.reduce( - (total, id) => total + evidence.checks[id].duration_ms, - 0 - ), - independent_filtered_tree: true, - }; - evidence.private = { - status: "passed", - duration_ms: - evidence.checks.formatting.duration_ms + - evidence.checks.clippy_warnings_denied.duration_ms + - evidence.checks.private_hosted_policy_locked_tests.duration_ms, - }; - evidence.status = "passed"; - evidence.transcript = transcriptPath; - fs.writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`); - } finally { - fs.closeSync(transcript); - } - console.log(`Release quality gates passed: ${evidencePath}`); -} - -try { - main(); -} catch (error) { - console.error(error.stack || error.message); - process.exit(1); -} diff --git a/scripts/release-source-scan.sh b/scripts/release-source-scan.sh deleted file mode 100755 index d8bf013..0000000 --- a/scripts/release-source-scan.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "$repo" - -release_paths=( - Cargo.toml - Cargo.lock - README.md - crates - examples - private - scripts - vscode-extension -) - -existing_release_paths=() -for path in "${release_paths[@]}"; do - if [[ -e "$path" ]]; then - existing_release_paths+=("$path") - fi -done - -prose_scan_paths=( - README.md - crates - examples - private - scripts - vscode-extension -) - -existing_prose_scan_paths=() -for path in "${prose_scan_paths[@]}"; do - if [[ -e "$path" ]]; then - existing_prose_scan_paths+=("$path") - fi -done - -scan_globs=( - --glob '!**/target/**' - --glob '!**/node_modules/**' - --glob '!scripts/release-source-scan.sh' - --glob '!scripts/rename-to-clusterflux.sh' - --glob '!scripts/check-docs.js' -) - -placeholder_pattern='debugger-gate|experiments/debugger-gate|CLUSTERFLUX-DEMO|device-code-placeholder|artifact://demo|vp-local-demo' -if rg -n "${scan_globs[@]}" "$placeholder_pattern" "${existing_release_paths[@]}"; then - echo "release source scan failed: stale experiment/demo placeholder reference found" >&2 - exit 1 -fi - -demo_setup_pattern='undocumented manual state|hidden setup|demo-only credentials?|hard-coded local paths?' -if rg -n "${scan_globs[@]}" "$demo_setup_pattern" "${existing_prose_scan_paths[@]}"; then - echo "release source scan failed: demo requires hidden setup or demo-only state" >&2 - exit 1 -fi - -hidden_local_pattern='file://|/home/[[:alnum:]_.-]+/|/Users/[[:alnum:]_.-]+/|C:\\Users\\|https?://(localhost|127\.0\.0\.1)[^[:space:]]*/artifacts/' -if rg -n "${scan_globs[@]}" "$hidden_local_pattern" "${existing_release_paths[@]}"; then - echo "release source scan failed: hidden local path or local artifact URL found" >&2 - exit 1 -fi - -public_wording_pattern='reddit|hacker news|lobsters|launch forum|traffic source|free tier' -if rg -n "${scan_globs[@]}" "$public_wording_pattern" "${existing_prose_scan_paths[@]}"; then - echo "release source scan failed: public-facing launch-forum/free-tier wording found" >&2 - exit 1 -fi - -echo "Release source scan passed" diff --git a/scripts/resource-metering-contract-smoke.js b/scripts/resource-metering-contract-smoke.js deleted file mode 100644 index 62e593d..0000000 --- a/scripts/resource-metering-contract-smoke.js +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); - -function read(relativePath) { - return fs.readFileSync(path.join(repo, relativePath), "utf8"); -} - -function maybeRead(segments) { - const fullPath = path.join(repo, ...segments); - if (!fs.existsSync(fullPath)) return null; - return fs.readFileSync(fullPath, "utf8"); -} - -function expect(source, name, pattern) { - assert.match(source, pattern, `missing resource metering evidence: ${name}`); -} - -const coreLimits = read("crates/clusterflux-core/src/limits.rs"); -// Phase 3 keeps the protocol dispatch in service.rs and the metered operation -// implementations in focused service modules. Read the complete relevant -// boundary so this contract follows the refactor instead of one mega-file. -const coordinatorService = [ - read("crates/clusterflux-coordinator/src/service.rs"), - read("crates/clusterflux-coordinator/src/service/routing.rs"), - read("crates/clusterflux-coordinator/src/service/processes.rs"), - read("crates/clusterflux-coordinator/src/service/process_launch.rs"), - read("crates/clusterflux-coordinator/src/service/artifacts.rs"), -].join("\n"); -const coordinatorQuota = read("crates/clusterflux-coordinator/src/service/quota.rs"); -const coordinatorLogs = read("crates/clusterflux-coordinator/src/service/logs.rs"); -const coordinatorDebug = read("crates/clusterflux-coordinator/src/service/debug.rs"); -const coordinatorTests = read("crates/clusterflux-coordinator/src/service/tests.rs"); -const wasmRuntime = read("crates/clusterflux-wasm-runtime/src/lib.rs"); -const wasmRuntimeTests = read("crates/clusterflux-wasm-runtime/src/tests.rs"); -const artifactDownloadSmoke = read("scripts/artifact-download-smoke.js"); -const operatorPanelSmoke = read("scripts/operator-panel-smoke.js"); -const quicSmoke = read("scripts/quic-smoke.js"); - -for (const [name, pattern] of [ - ["API call limit kind", /\bApiCall,/], - ["spawn limit kind", /\bSpawn,/], - ["log bytes limit kind", /\bLogBytes,/], - ["metadata bytes limit kind", /\bMetadataBytes,/], - ["debug read bytes limit kind", /\bDebugReadBytes,/], - ["UI event limit kind", /\bUiEvent,/], - ["rendezvous attempt limit kind", /\bRendezvousAttempt,/], - ["artifact download bytes limit kind", /\bArtifactDownloadBytes,/], - [ - "preflight can check without consuming", - /pub fn can_charge\([\s\S]*used\.saturating_add\(amount\) > limit/, - ], - [ - "charge goes through preflight", - /pub fn charge\([\s\S]*self\.can_charge\(limits, kind, amount\)\?/, - ], -]) { - expect(coreLimits, name, pattern); -} - -for (const [name, pattern] of [ - [ - "Wasm stores enforce a concrete memory limit", - /StoreLimitsBuilder::new\(\)[\s\S]*memory_size\(runtime\.memory_bytes\)/, - ], - [ - "Wasm compute uses a refillable fuel token bucket", - /struct FuelTokenBucket[\s\S]*fractional_fuel_numerator[\s\S]*fn refill_after/, - ], - ["Wasmtime fuel consumption is enabled", /config\.consume_fuel\(true\)/], - ["Wasmtime epoch interruption is enabled", /config\.epoch_interruption\(true\)/], -]) { - expect(wasmRuntime, name, pattern); -} - -for (const [name, pattern] of [ - [ - "fuel refill preserves fractional credit", - /frequent_refills_preserve_fractional_credit/, - ], - [ - "linear memory growth is bounded per store", - /wasm_linear_memory_growth_is_bounded_per_store/, - ], - [ - "CPU-bound Wasm is interrupted without a host call", - /epoch_interruption_aborts_cpu_bound_wasm_without_a_host_call/, - ], -]) { - expect(`${wasmRuntime}\n${wasmRuntimeTests}`, name, pattern); -} - -for (const [name, pattern] of [ - [ - "rendezvous charges before transport planning", - /handle_request_rendezvous[\s\S]*charge_rendezvous_attempt\([\s\S]*&scope\.tenant[\s\S]*&scope\.project[\s\S]*now_epoch_seconds[\s\S]*plan_authenticated_direct_bulk_transfer/, - ], - [ - "artifact link creation preflights downloadable bytes before link creation", - /handle_create_artifact_download_link[\s\S]*downloadable_size[\s\S]*can_charge_download\([\s\S]*&context\.tenant[\s\S]*&context\.project[\s\S]*downloadable_size[\s\S]*create_download_link/, - ], - [ - "artifact delivery charges scoped bytes before advancing its offset", - /handle_open_artifact_download_stream[\s\S]*stream_download_chunk\([\s\S]*charge_download\([\s\S]*&context\.tenant[\s\S]*&context\.project[\s\S]*streamed_bytes[\s\S]*delivered_offset = end/, - ], -]) { - expect(coordinatorService, name, pattern); -} - -for (const [name, pattern] of [ - [ - "quota keys include tenant/project resource kind and window", - /struct ProjectQuotaScope[\s\S]*tenant: TenantId[\s\S]*project: ProjectId[\s\S]*struct MeterKey[\s\S]*kind: LimitKind[\s\S]*window: u64/, - ], - [ - "quota module discards expired windows for an accessed scope and kind", - /fn meter_mut[\s\S]*self\.meters\.retain[\s\S]*existing\.scope != key\.scope[\s\S]*existing\.kind != kind[\s\S]*existing\.window == key\.window/, - ], - [ - "quota module charges rendezvous attempts through the scoped window meter", - /fn charge_rendezvous_attempt[\s\S]*self\.charge\([\s\S]*tenant[\s\S]*project[\s\S]*LimitKind::RendezvousAttempt/, - ], - [ - "quota module charges authenticated API calls through the scoped window meter", - /fn charge_api_call[\s\S]*self\.charge\(tenant, project, LimitKind::ApiCall, 1, now_epoch_seconds\)/, - ], - [ - "quota module preflights and charges log bytes through the scoped window meter", - /fn can_charge_log_bytes[\s\S]*LimitKind::LogBytes[\s\S]*fn charge_log_bytes[\s\S]*LimitKind::LogBytes/, - ], - [ - "quota module preflights artifact download bytes through the scoped meter", - /fn can_charge_download[\s\S]*self\.can_charge\([\s\S]*tenant[\s\S]*project[\s\S]*LimitKind::ArtifactDownloadBytes/, - ], - [ - "quota status reports current scoped window usage", - /fn project_status[\s\S]*for kind in LimitKind::ALL[\s\S]*self\.used\(tenant, project, kind, now_epoch_seconds\)/, - ], -]) { - expect(coordinatorQuota, name, pattern); -} - -for (const [source, name, pattern] of [ - [ - coordinatorService, - "authenticated API calls are charged after session authorization and before dispatch", - /authenticate_cli_session[\s\S]*authorize_authenticated_user_operation[\s\S]*charge_api_call[\s\S]*match request/, - ], - [ - coordinatorLogs, - "signed node log ingestion preflights and charges bytes before accepting the report", - /handle_report_task_log[\s\S]*authorize_node_for_process_or_termination[\s\S]*can_charge_log_bytes[\s\S]*charge_log_bytes[\s\S]*TaskLogRecorded/, - ], - [ - coordinatorDebug, - "debug reads charge the scoped debug-read budget before audit state is recorded", - /record_debug_audit_event[\s\S]*charge_debug_read[\s\S]*DebugAuditEvent/, - ], - [ - coordinatorTests, - "tests prove API-call and log-byte quota enforcement and project isolation", - /authenticated_api_calls_are_metered_per_tenant_and_project_before_dispatch[\s\S]*project-a[\s\S]*project-b[\s\S]*signed_node_log_ingestion_checks_scoped_quota_before_accepting_bytes[\s\S]*LogBytes/, - ], -]) { - expect(source, name, pattern); -} - -for (const [name, source, patterns] of [ - [ - "rendezvous smoke", - quicSmoke, - [/charged_rendezvous_attempts, 1/, /coordinator bulk relay is disabled/], - ], - [ - "artifact download smoke", - artifactDownloadSmoke, - [ - /downloaded\.response\.charged_download_bytes,[\s\S]*packageEvent\.artifact_size_bytes/, - /retaining_node_reverse_stream/, - /revoked/, - ], - ], - [ - "operator panel smoke", - operatorPanelSmoke, - [ - /type: "submit_panel_event"/, - /max_events: 1/, - /used_events, 1/, - /rate limit/i, - /max_download_bytes: 1/, - /exceeds download limit/, - ], - ], -]) { - for (const pattern of patterns) { - expect(source, name, pattern); - } -} - -const privateHostedLibSource = maybeRead(["private", "hosted-policy", "src", "lib.rs"]); -const privateHostedTests = maybeRead(["private", "hosted-policy", "src", "tests.rs"]); -const privateHostedLib = privateHostedLibSource - ? [privateHostedLibSource, privateHostedTests].filter(Boolean).join("\n") - : null; -if (privateHostedLib) { - for (const [name, pattern] of [ - [ - "private hosted configuration owns exact control-plane limits and quota windows", - /community_tier_resource_limits[\s\S]*LimitKind::ApiCall[\s\S]*LimitKind::ArtifactDownloadBytes[\s\S]*community_tier_quota_configuration[\s\S]*CoordinatorQuotaConfiguration::new/, - ], - [ - "hosted zero-capability policy rejects native execution capabilities", - /hosted_zero_capability_wasm_rejects_filesystem_and_command_capabilities[\s\S]*Capability::Command[\s\S]*Capability::Network[\s\S]*Capability::ArbitrarySyscalls/, - ], - ]) { - expect(privateHostedLib, name, pattern); - } - assert.doesNotMatch( - privateHostedLib, - /HostedFuel|HostedMemoryBytes|HostedWallClockMs|HostedStateBytes/, - "decorative hosted Wasm quota kinds must not return", - ); -} - -console.log("Resource metering contract smoke passed"); diff --git a/scripts/scheduler-placement-smoke.js b/scripts/scheduler-placement-smoke.js deleted file mode 100755 index 2050403..0000000 --- a/scripts/scheduler-placement-smoke.js +++ /dev/null @@ -1,400 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); - -const repo = path.resolve(__dirname, ".."); -const digest = (value) => - `sha256:${crypto.createHash("sha256").update(value).digest("hex")}`; -const environmentDigest = digest("scheduler-linux-container"); -const dependencyDigest = digest("scheduler-toolchain-dependencies"); -const sourceDigest = digest("scheduler-source-tree"); - -function buildFlagshipBundle() { - const output = cp.execFileSync( - "cargo", - [ - "run", "-q", "-p", "clusterflux-cli", "--bin", "clusterflux", "--", - "build", "--project", "tests/fixtures/runtime-conformance", "--json", - ], - { cwd: repo, encoding: "utf8" } - ); - const report = JSON.parse(output); - const directory = path.resolve(repo, report.bundle_artifact.directory); - const manifest = JSON.parse(fs.readFileSync(path.join(directory, "manifest.json"), "utf8")); - const entrypoints = JSON.parse( - fs.readFileSync(path.join(directory, manifest.entrypoints), "utf8") - ); - const entrypoint = entrypoints.find((candidate) => candidate.name === "build"); - assert(entrypoint, "flagship bundle omitted build entrypoint"); - const taskDescriptors = JSON.parse( - fs.readFileSync(path.join(directory, manifest.task_descriptors), "utf8") - ); - const prepareSource = taskDescriptors.find( - (candidate) => candidate.name === "prepare_source" - ); - assert(prepareSource, "flagship bundle omitted prepare_source task"); - return { - digest: manifest.bundle_digest, - taskExport: prepareSource.export, - wasmModuleBase64: fs.readFileSync(path.join(directory, "module.wasm")).toString("base64"), - }; -} - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function linuxCapabilities() { - return { - os: "Linux", - arch: "x86_64", - capabilities: [ - "Command", - "Containers", - "RootlessPodman", - "SourceFilesystem", - "VfsArtifacts" - ], - environment_backends: ["Container"], - source_providers: ["filesystem"] - }; -} - -function gitCapabilities() { - const capabilities = linuxCapabilities(); - capabilities.capabilities = [...capabilities.capabilities, "SourceGit"].sort(); - capabilities.source_providers = [...capabilities.source_providers, "git"].sort(); - return capabilities; -} - -async function attachNode(addr, node) { - const identity = nodeIdentity("scheduler-placement-smoke", node); - const attached = await send(addr, { - type: "attach_node", - tenant: "tenant", - project: "project", - node, - public_key: identity.publicKey - }); - assert.strictEqual(attached.type, "node_attached"); - assert.strictEqual(attached.node, node); - return identity; -} - -async function reportNode(addr, node, identity, locality) { - const recorded = await send(addr, signedNodeRequest(node, identity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node, - capabilities: locality.capabilities || linuxCapabilities(), - cached_environment_digests: locality.cached_environment_digests, - dependency_cache_digests: locality.dependency_cache_digests, - source_snapshots: locality.source_snapshots, - artifact_locations: locality.artifact_locations, - direct_connectivity: locality.direct_connectivity !== false, - online: true - })); - assert.strictEqual( - recorded.type, - "node_capabilities_recorded", - JSON.stringify(recorded) - ); - assert.strictEqual(recorded.node, node); - return recorded; -} - -(async () => { - const bundle = buildFlagshipBundle(); - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - let coordinatorStderr = ""; - coordinator.stderr.on("data", (chunk) => { - coordinatorStderr += chunk.toString(); - }); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const coldNode = await attachNode(addr, "cold-node"); - const warmNode = await attachNode(addr, "warm-node"); - - const cold = await reportNode(addr, "cold-node", coldNode, { - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: false - }); - assert.strictEqual(cold.node_descriptors, 1); - - const warm = await reportNode(addr, "warm-node", warmNode, { - cached_environment_digests: [environmentDigest], - dependency_cache_digests: [dependencyDigest], - source_snapshots: [sourceDigest], - artifact_locations: ["toolchain-cache"] - }); - assert.strictEqual(warm.node_descriptors, 2); - const reportedNodes = new Set([cold.node, warm.node]); - assert.strictEqual(reportedNodes.size, 2); - assert(reportedNodes.has("cold-node")); - assert(reportedNodes.has("warm-node")); - - const inspected = await send(addr, { - type: "list_node_descriptors", - tenant: "tenant", - project: "project", - actor_user: "operator" - }); - assert.strictEqual(inspected.type, "node_descriptors"); - assert.strictEqual(inspected.actor, "operator"); - assert.strictEqual(inspected.descriptors.length, 2); - const warmDescriptor = inspected.descriptors.find( - (descriptor) => descriptor.id === "warm-node" - ); - assert(warmDescriptor, "warm node descriptor must be visible to inspector state"); - assert(warmDescriptor.capabilities.capabilities.includes("Command")); - assert(warmDescriptor.capabilities.capabilities.includes("RootlessPodman")); - assert(warmDescriptor.cached_environments.includes(environmentDigest)); - assert(warmDescriptor.dependency_caches.includes(dependencyDigest)); - assert(warmDescriptor.source_snapshots.includes(sourceDigest)); - assert(warmDescriptor.artifact_locations.includes("toolchain-cache")); - - const crossScopeInspection = await send(addr, { - type: "list_node_descriptors", - tenant: "other-tenant", - project: "project", - actor_user: "operator" - }); - assert.strictEqual(crossScopeInspection.type, "node_descriptors"); - assert.strictEqual(crossScopeInspection.descriptors.length, 0); - - const crossTenantReport = await send(addr, signedNodeRequest("warm-node", warmNode, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "other-tenant", - project: "project", - node: "warm-node", - capabilities: linuxCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: true, - online: true - })); - assert.strictEqual(crossTenantReport.type, "error"); - assert.match( - crossTenantReport.message, - /tenant\/project scope|node identity is not enrolled/ - ); - - const placement = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: { - os: "Linux", - arch: null, - capabilities: ["Containers", "RootlessPodman"] - }, - environment_digest: environmentDigest, - required_capabilities: ["Command"], - dependency_cache: dependencyDigest, - source_snapshot: sourceDigest, - required_artifacts: ["toolchain-cache"], - prefer_node: null - }); - assert.strictEqual(placement.type, "task_placement"); - assert.strictEqual(placement.placement.node, "warm-node"); - assert.ok(placement.placement.score > 0); - assert.ok(placement.placement.reasons.includes("warm environment cache")); - assert.ok(placement.placement.reasons.includes("warm dependency cache")); - assert.ok(placement.placement.reasons.includes("source snapshot already local")); - assert.ok( - placement.placement.reasons.includes("1 required artifact(s) already local") - ); - - const impossible = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: null, - environment_digest: null, - required_capabilities: ["WindowsCommandDev"], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - prefer_node: null - }); - assert.strictEqual(impossible.type, "error"); - assert.match(impossible.message, /WindowsCommandDev/); - - const started = await send(addr, { - type: "start_process", - tenant: "tenant", - project: "project", - actor_user: "operator", - process: "vp-wait-for-git" - }); - assert.strictEqual(started.type, "process_started"); - - const queued = await send(addr, { - type: "launch_task", - tenant: "tenant", - project: "project", - actor_user: "operator", - task_spec: { - tenant: "tenant", - project: "project", - process: "vp-wait-for-git", - task_definition: "prepare_source", - task_instance: "prepare_source-1", - dispatch: { - kind: "coordinator_node_wasm", - export: bundle.taskExport, - abi: "task_v1", - }, - environment_id: null, - environment: null, - environment_digest: null, - required_capabilities: ["SourceFilesystem", "SourceGit"], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [], - vfs_epoch: started.epoch, - bundle_digest: bundle.digest, - }, - wait_for_node: true, - artifact_path: "/vfs/artifacts/git-status.txt", - wasm_module_base64: bundle.wasmModuleBase64, - }); - assert.strictEqual(queued.type, "error"); - assert.match(queued.message, /external callers may launch only EntrypointV1/); - - const gitNode = await attachNode(addr, "git-node"); - const gitRecorded = await reportNode(addr, "git-node", gitNode, { - capabilities: gitCapabilities(), - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: false - }); - assert.strictEqual(gitRecorded.type, "node_capabilities_recorded"); - - const pendingAssignment = await send(addr, signedNodeRequest("git-node", gitNode, "poll_task_assignment", { - type: "poll_task_assignment", - tenant: "tenant", - project: "project", - node: "git-node" - })); - assert.strictEqual(pendingAssignment.type, "task_assignment"); - assert.strictEqual(pendingAssignment.assignment, null); - - const emptyAssignment = await send(addr, signedNodeRequest("git-node", gitNode, "poll_task_assignment", { - type: "poll_task_assignment", - tenant: "tenant", - project: "project", - node: "git-node" - })); - assert.strictEqual(emptyAssignment.type, "task_assignment"); - assert.strictEqual(emptyAssignment.assignment, null); - - await reportNode(addr, "warm-node", warmNode, { - cached_environment_digests: [], - dependency_cache_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: false - }); - const disconnectedTransfer = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: null, - environment_digest: null, - required_capabilities: ["Command"], - dependency_cache: null, - source_snapshot: sourceDigest, - required_artifacts: ["toolchain-cache"], - prefer_node: null - }); - assert.strictEqual(disconnectedTransfer.type, "error"); - assert.match(disconnectedTransfer.message, /source snapshot unavailable/); - assert.match(disconnectedTransfer.message, /required artifact\(s\) unavailable/); - assert.match(disconnectedTransfer.message, /direct connectivity unavailable/); - } catch (error) { - if (coordinatorStderr) { - error.message = `${error.message}\ncoordinator stderr:\n${coordinatorStderr}`; - } - throw error; - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("Scheduler placement smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/sdk-spawn-runtime-smoke.js b/scripts/sdk-spawn-runtime-smoke.js deleted file mode 100755 index 48fa978..0000000 --- a/scripts/sdk-spawn-runtime-smoke.js +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const sdk = fs.readFileSync(path.join(repo, "crates/clusterflux-sdk/src/lib.rs"), "utf8"); -const productRuntime = fs.readFileSync( - path.join(repo, "crates/clusterflux-sdk/src/sdk_runtime.rs"), - "utf8" -); - -assert.match(sdk, /pub struct RuntimeSpawnEvent/); -assert.match(sdk, /pub debugger_visible: bool/); -assert.match(sdk, /fn register_runtime_thread/); -assert.match(sdk, /register_runtime_thread\(id, self\.name, self\.env\)/); -assert.match(sdk, /pub fn debugger_visible\(&self\) -> bool/); -assert.match(sdk, /ProductRuntimeConfig::from_env\(\)/); -assert.match(sdk, /start_remote_task\(\s*config,\s*task_id/); -assert.match(sdk, /start_guest_host_task/); -assert.match(sdk, /join_remote_task\(remote\)/); -assert.doesNotMatch(productRuntime, /"type": "launch_task"/); -assert.match(productRuntime, /native SDK task spawning requires coordinator EntrypointV1 execution/); -assert.match(productRuntime, /task_start_v1/); -assert.match(productRuntime, /task_join_v1/); -assert.match(productRuntime, /command_run_v1/); -assert.match(productRuntime, /remote_completion_observed/); -assert.match(productRuntime, /TaskJoinState::Pending/); -assert.doesNotMatch( - productRuntime, - /entry\s*\(/, - "product runtime must not invoke the submitted local Rust closure" -); - -cp.execFileSync( - "cargo", - [ - "test", - "-p", - "clusterflux-sdk", - "spawn_task_start_registers_debugger_visible_runtime_thread", - ], - { cwd: repo, stdio: "inherit" } -); - -console.log("SDK spawn runtime smoke passed"); diff --git a/scripts/self-hosted-coordinator-smoke.js b/scripts/self-hosted-coordinator-smoke.js deleted file mode 100644 index 2938eac..0000000 --- a/scripts/self-hosted-coordinator-smoke.js +++ /dev/null @@ -1,666 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); - -const repo = path.resolve(__dirname, ".."); -const teamArtifactDigest = `sha256:${"a".repeat(64)}`; -const teamEnvironmentDigest = `sha256:${crypto - .createHash("sha256") - .update("env-team-linux") - .digest("hex")}`; -const teamDependencyCacheDigest = `sha256:${crypto - .createHash("sha256") - .update("cargo-cache") - .digest("hex")}`; -const teamSourceDigest = `sha256:${crypto - .createHash("sha256") - .update("source-team") - .digest("hex")}`; -const coordinatorTaskModule = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]); -const coordinatorTaskBundleDigest = `sha256:${crypto - .createHash("sha256") - .update(coordinatorTaskModule) - .digest("hex")}`; -const adminToken = "self-hosted-smoke-admin-token"; -const clientSessionSecret = "self-hosted-smoke-client-session-secret"; -const releaseManifestPath = - process.env.CLUSTERFLUX_PUBLIC_RELEASE_MANIFEST || - path.join(repo, "target/public-release/public-release-manifest.json"); - -function sha256(value) { - return `sha256:${crypto.createHash("sha256").update(value).digest("hex")}`; -} - -function digestFromParts(parts) { - const hash = crypto.createHash("sha256"); - for (const value of parts) { - const bytes = Buffer.from(String(value)); - const length = Buffer.alloc(8); - length.writeBigUInt64BE(BigInt(bytes.length)); - hash.update(length); - hash.update(bytes); - } - return `sha256:${hash.digest("hex")}`; -} - -function adminRequest(token, operation, tenant, actorUser, targetTenant, nonce) { - const issuedAtEpochSeconds = Math.floor(Date.now() / 1000); - return { - type: operation, - tenant, - actor_user: actorUser, - ...(operation === "suspend_tenant" ? { target_tenant: targetTenant } : {}), - admin_proof: digestFromParts([ - "clusterflux-admin-request-proof:v1", - sha256(token), - operation, - tenant, - actorUser, - targetTenant, - nonce, - issuedAtEpochSeconds, - ]), - admin_nonce: nonce, - issued_at_epoch_seconds: issuedAtEpochSeconds, - }; -} - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function authenticated(request, sessionSecret = clientSessionSecret) { - return { - type: "authenticated", - session_secret: sessionSecret, - request, - }; -} - -function linuxNodeCapabilities() { - return { - os: "Linux", - arch: "x86_64", - capabilities: ["Command", "RootlessPodman", "VfsArtifacts", "QuicDirect"], - environment_backends: ["Container"], - source_providers: ["filesystem", "git"] - }; -} - -function nodeIdentity(node) { - void node; - const { privateKey: privateKeyObject, publicKey } = - crypto.generateKeyPairSync("ed25519"); - const publicDer = publicKey.export({ - format: "der", - type: "spki", - }); - return { - publicKey: `ed25519:${Buffer.from(publicDer).subarray(-32).toString("base64")}`, - privateKeyObject, - }; -} - -function signedRequestPayloadDigest(request) { - const canonicalize = (value, topLevel = true) => { - if (Array.isArray(value)) return value.map((entry) => canonicalize(entry, false)); - if (value && typeof value === "object") { - return Object.fromEntries( - Object.entries(value) - .filter( - ([key, entry]) => - entry !== null && - (!topLevel || !["agent_signature", "node_signature"].includes(key)) - ) - .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) - .map(([key, entry]) => [key, canonicalize(entry, false)]) - ); - } - return value; - }; - return `sha256:${crypto - .createHash("sha256") - .update(JSON.stringify(canonicalize(request))) - .digest("hex")}`; -} - -function nodeSignatureMessage( - node, - requestKind, - payloadDigest, - nonce, - issuedAtEpochSeconds -) { - const parts = [ - "clusterflux-node-request-signature:v2", - node, - requestKind, - payloadDigest, - nonce, - String(issuedAtEpochSeconds), - ]; - return Buffer.concat( - parts.flatMap((part) => [ - Buffer.from(`${Buffer.byteLength(part)}:`), - Buffer.from(part), - Buffer.from("\n"), - ]) - ); -} - -function signedNodeHeartbeat(tenant, project, node, identity) { - const request = { type: "node_heartbeat", tenant, project, node }; - const nonce = `self-hosted-heartbeat-${process.pid}-${Date.now()}`; - const issuedAt = Math.floor(Date.now() / 1000); - const signature = crypto.sign( - null, - nodeSignatureMessage( - node, - "node_heartbeat", - signedRequestPayloadDigest(request), - nonce, - issuedAt - ), - identity.privateKeyObject - ); - return { - nonce, - issued_at_epoch_seconds: issuedAt, - signature: `ed25519:${signature.toString("base64")}`, - }; -} - -function signedNodeRequest(node, identity, requestKind, request) { - return { - type: "signed_node", - node, - node_signature: signedNodeHeartbeatForKind(node, identity, requestKind, request), - request, - }; -} - -function signedNodeHeartbeatForKind(node, identity, requestKind, request) { - const nonce = `${requestKind}-${process.pid}-${Date.now()}`; - const issuedAt = Math.floor(Date.now() / 1000); - const signature = crypto.sign( - null, - nodeSignatureMessage( - node, - requestKind, - signedRequestPayloadDigest(request), - nonce, - issuedAt - ), - identity.privateKeyObject - ); - return { - nonce, - issued_at_epoch_seconds: issuedAt, - signature: `ed25519:${signature.toString("base64")}`, - }; -} - -function commandOutput(command, args) { - try { - return cp - .execFileSync(command, args, { - cwd: repo, - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - }) - .trim(); - } catch (_) { - return null; - } -} - -function runJson(command, args, options = {}) { - return JSON.parse( - cp.execFileSync(command, args, { - cwd: options.cwd || repo, - encoding: "utf8", - input: options.input, - }) - ); -} - -function expectedSourceCommit() { - return ( - process.env.CLUSTERFLUX_ACCEPTANCE_COMMIT || - commandOutput("git", ["rev-parse", "HEAD"]) - ); -} - -function readReleaseManifest() { - if (!fs.existsSync(releaseManifestPath)) return null; - const manifest = JSON.parse(fs.readFileSync(releaseManifestPath, "utf8")); - if (manifest.kind !== "clusterflux-public-release") return null; - const expectedCommit = expectedSourceCommit(); - if (expectedCommit && manifest.source_commit !== expectedCommit) return null; - return manifest; -} - -function releaseIdentity() { - const manifest = readReleaseManifest(); - return { - sourceCommit: manifest ? manifest.source_commit : expectedSourceCommit(), - releaseName: - (manifest && manifest.release_name) || - process.env.CLUSTERFLUX_PUBLIC_RELEASE_NAME || - null, - }; -} - -async function attachTrustedNode(addr, node, capabilities = linuxNodeCapabilities()) { - const identity = nodeIdentity(node); - const grant = await send(addr, authenticated({ - type: "create_node_enrollment_grant", - ttl_seconds: 900, - })); - assert.strictEqual(grant.type, "node_enrollment_grant_created"); - - const attached = await send(addr, { - type: "exchange_node_enrollment_grant", - tenant: "team", - project: "self-hosted", - node, - public_key: identity.publicKey, - enrollment_grant: grant.grant, - }); - assert.strictEqual(attached.type, "node_enrollment_exchanged"); - - const heartbeat = await send(addr, { - type: "node_heartbeat", - tenant: "team", - project: "self-hosted", - node, - node_signature: signedNodeHeartbeat("team", "self-hosted", node, identity) - }); - assert.strictEqual(heartbeat.type, "node_heartbeat"); - - const reported = await send(addr, signedNodeRequest(node, identity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "team", - project: "self-hosted", - node, - capabilities, - cached_environment_digests: [teamEnvironmentDigest], - dependency_cache_digests: [teamDependencyCacheDigest], - source_snapshots: [teamSourceDigest], - artifact_locations: [], - direct_connectivity: true, - online: true - })); - assert.strictEqual(reported.type, "node_capabilities_recorded"); - return identity; -} - -(async () => { - const release = releaseIdentity(); - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0" - ], - { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_ADMIN_TOKEN: adminToken, - CLUSTERFLUX_SELF_HOSTED_SESSION_SECRET: clientSessionSecret, - CLUSTERFLUX_SELF_HOSTED_TENANT: "team", - CLUSTERFLUX_SELF_HOSTED_PROJECT: "self-hosted", - CLUSTERFLUX_SELF_HOSTED_USER: "developer", - }, - } - ); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual(ready.client_authority, "strict"); - assert.strictEqual(ready.self_hosted_session_bootstrapped, true); - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const forgedBodyAuthority = await send(addr, { - type: "start_process", - tenant: "victim-tenant", - project: "victim-project", - actor_user: "forged-user", - process: "vp-forged", - }); - assert.strictEqual(forgedBodyAuthority.type, "error"); - assert.match(forgedBodyAuthority.message, /body.*identity.*not authority/i); - const wrongSession = await send( - addr, - authenticated({ type: "auth_status" }, "wrong-session-secret") - ); - assert.strictEqual(wrongSession.type, "error"); - assert.match(wrongSession.message, /session.*not recognized|not recognized.*session/i); - const authStatus = await send(addr, authenticated({ type: "auth_status" })); - assert.strictEqual(authStatus.type, "auth_status"); - assert.strictEqual(authStatus.tenant, "team"); - assert.strictEqual(authStatus.project, "self-hosted"); - assert.strictEqual(authStatus.actor, "developer"); - - const missingAdminCredential = await send( - addr, - adminRequest("", "admin_status", "team", "forged-admin", "team", "admin-empty") - ); - assert.strictEqual(missingAdminCredential.type, "error"); - assert.match(missingAdminCredential.message, /admin.*proof.*invalid/i); - const wrongAdminCredential = await send( - addr, - adminRequest( - "wrong-token", - "admin_status", - "team", - "forged-admin", - "team", - "admin-wrong" - ) - ); - assert.strictEqual(wrongAdminCredential.type, "error"); - assert.match(wrongAdminCredential.message, /admin.*proof.*invalid/i); - const replayableAdminRequest = adminRequest( - adminToken, - "admin_status", - "team", - "self-hosted-admin", - "team", - "admin-replay" - ); - const directAdminStatus = await send(addr, replayableAdminRequest); - assert.strictEqual(directAdminStatus.type, "admin_status"); - const replayedAdminStatus = await send(addr, replayableAdminRequest); - assert.strictEqual(replayedAdminStatus.type, "error"); - assert.match(replayedAdminStatus.message, /nonce was already used/i); - const cargoTargetDir = path.resolve( - process.env.CARGO_TARGET_DIR || path.join(repo, "target") - ); - const cliBin = path.join( - cargoTargetDir, - "debug", - process.platform === "win32" ? "clusterflux.exe" : "clusterflux" - ); - const selfHostedCliProject = path.join( - repo, - "target/acceptance/self-hosted-cli-project" - ); - fs.rmSync(selfHostedCliProject, { recursive: true, force: true }); - fs.mkdirSync(selfHostedCliProject, { recursive: true }); - const cliConnect = runJson( - cliBin, - [ - "auth", - "connect-self-hosted", - "--coordinator", - ready.listen, - "--tenant", - "team", - "--project-id", - "self-hosted", - "--user", - "developer", - "--session-secret-stdin", - "--json", - ], - { cwd: selfHostedCliProject, input: `${clientSessionSecret}\n` } - ); - assert.strictEqual(cliConnect.status, "connected"); - assert.strictEqual(cliConnect.session_secret_read_from_stdin, true); - assert.strictEqual(cliConnect.session_secret_exposed_in_report, false); - assert.strictEqual(cliConnect.coordinator_response.type, "auth_status"); - const sessionPath = path.join( - selfHostedCliProject, - ".clusterflux/session.json" - ); - const storedSession = JSON.parse(fs.readFileSync(sessionPath, "utf8")); - assert.strictEqual(storedSession.kind, "self_hosted"); - assert.strictEqual(storedSession.session_secret, clientSessionSecret); - assert.strictEqual(storedSession.provider_tokens_exposed_to_cli, false); - assert.strictEqual(storedSession.provider_tokens_sent_to_nodes, false); - if (process.platform !== "win32") { - assert.strictEqual(fs.statSync(sessionPath).mode & 0o777, 0o600); - } - const cliAuthStatus = runJson( - cliBin, - ["auth", "status", "--json"], - { cwd: selfHostedCliProject } - ); - assert.strictEqual(cliAuthStatus.active_coordinator, ready.listen); - assert.strictEqual( - cliAuthStatus.coordinator_account_status.used_cli_session_credential, - true - ); - assert.strictEqual( - cliAuthStatus.coordinator_account_status.coordinator_response_type, - "auth_status" - ); - const cliAdminStatus = runJson(cliBin, [ - "admin", - "status", - "--coordinator", - ready.listen, - "--tenant", - "team", - "--user", - "self-hosted-admin", - "--admin-token", - adminToken, - "--json", - ]); - assert.strictEqual(cliAdminStatus.response.type, "admin_status"); - assert.strictEqual(cliAdminStatus.suspended, false); - const cliAdminSuspend = runJson(cliBin, [ - "admin", - "suspend-tenant", - "--coordinator", - ready.listen, - "--tenant", - "team", - "--user", - "self-hosted-admin", - "--target-tenant", - "admin-probe-tenant", - "--admin-token", - adminToken, - "--yes", - "--json", - ]); - assert.strictEqual(cliAdminSuspend.response.type, "tenant_suspended"); - assert.strictEqual(cliAdminSuspend.suspended, true); - const cliAdminProbeStatus = runJson(cliBin, [ - "admin", - "status", - "--coordinator", - ready.listen, - "--tenant", - "admin-probe-tenant", - "--user", - "self-hosted-admin", - "--admin-token", - adminToken, - "--json", - ]); - assert.strictEqual(cliAdminProbeStatus.suspended, true); - - const teamLinuxA = await attachTrustedNode(addr, "team-linux-a"); - const teamLinuxBCapabilities = linuxNodeCapabilities(); - teamLinuxBCapabilities.capabilities = teamLinuxBCapabilities.capabilities.filter( - (capability) => capability !== "VfsArtifacts" - ); - await attachTrustedNode(addr, "team-linux-b", teamLinuxBCapabilities); - - const placement = await send(addr, authenticated({ - type: "schedule_task", - environment: { - os: "Linux", - arch: "x86_64", - capabilities: ["Command", "QuicDirect"] - }, - environment_digest: teamEnvironmentDigest, - required_capabilities: ["VfsArtifacts"], - source_snapshot: teamSourceDigest, - required_artifacts: [], - prefer_node: "team-linux-a" - })); - assert.strictEqual(placement.type, "task_placement"); - assert.strictEqual(placement.placement.node, "team-linux-a"); - assert(placement.placement.reasons.includes("preferred node")); - assert(placement.placement.reasons.includes("warm environment cache")); - assert(placement.placement.reasons.includes("source snapshot already local")); - - const started = await send(addr, authenticated({ - type: "start_process", - process: "vp-team-build", - restart: false, - })); - assert.strictEqual(started.type, "process_started"); - - const reconnected = await send(addr, signedNodeRequest("team-linux-a", teamLinuxA, "reconnect_node", { - type: "reconnect_node", - tenant: "team", - project: "self-hosted", - node: "team-linux-a", - process: "vp-team-build", - epoch: started.epoch - })); - assert.strictEqual(reconnected.type, "node_reconnected"); - - const launched = await send(addr, authenticated({ - type: "launch_task", - task_spec: { - tenant: "team", - project: "self-hosted", - process: "vp-team-build", - task_definition: "compile-linux", - task_instance: "compile-linux", - dispatch: { - kind: "coordinator_node_wasm", - export: "compile_linux", - abi: "task_v1", - }, - environment_id: null, - environment: null, - environment_digest: null, - required_capabilities: ["VfsArtifacts"], - dependency_cache: null, - source_snapshot: null, - required_artifacts: [], - args: [], - vfs_epoch: started.epoch, - bundle_digest: coordinatorTaskBundleDigest, - }, - wait_for_node: false, - artifact_path: "/vfs/artifacts/team-output.txt", - wasm_module_base64: coordinatorTaskModule.toString("base64"), - })); - assert.strictEqual(launched.type, "error", JSON.stringify(launched)); - assert.match(launched.message, /external callers may launch only EntrypointV1/); - - const reportPath = path.join(repo, "target/acceptance/core-coordinator-compat.json"); - fs.mkdirSync(path.dirname(reportPath), { recursive: true }); - fs.writeFileSync( - reportPath, - `${JSON.stringify( - { - kind: "clusterflux-core-coordinator-compatibility", - source_commit: release.sourceCommit, - release_name: release.releaseName, - coordinator_implementation: "standalone-core-coordinator", - coordinator_addr: ready.listen, - client_authority: ready.client_authority, - authenticated_session: authStatus.authenticated, - forged_body_authority_denied: forgedBodyAuthority.type, - wrong_session_denied: wrongSession.type, - ping: "pong", - nodes: ["team-linux-a", "team-linux-b"], - task_placement: placement.type, - process_started: started.type, - external_task_v1_denied: launched.type, - self_hosted_admin: { - missing_credential_denied: missingAdminCredential.type, - wrong_credential_denied: wrongAdminCredential.type, - nonce_bound_proof_succeeded: directAdminStatus.type, - replay_denied: replayedAdminStatus.type, - cli_status: cliAdminStatus.response.type, - cli_suspend: cliAdminSuspend.response.type, - suspended_state_observed: cliAdminProbeStatus.suspended, - }, - self_hosted_cli: { - connected: cliConnect.status, - secret_read_from_stdin: cliConnect.session_secret_read_from_stdin, - secret_exposed_in_report: cliConnect.session_secret_exposed_in_report, - session_file_mode: - process.platform === "win32" - ? "windows-best-effort" - : (fs.statSync(sessionPath).mode & 0o777).toString(8), - authenticated_status: - cliAuthStatus.coordinator_account_status.coordinator_response_type, - }, - }, - null, - 2 - )}\n` - ); - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("Self-hosted coordinator smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/source-preparation-smoke.js b/scripts/source-preparation-smoke.js deleted file mode 100755 index 07be55d..0000000 --- a/scripts/source-preparation-smoke.js +++ /dev/null @@ -1,221 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); - -const repo = path.resolve(__dirname, ".."); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function sourceCapableNode(sourceProviders = ["git"]) { - return { - os: "Linux", - arch: "x86_64", - capabilities: ["Command", "SourceFilesystem", "SourceGit"], - environment_backends: [], - source_providers: sourceProviders - }; -} - -(async () => { - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - let coordinatorStderr = ""; - coordinator.stderr.on("data", (chunk) => { - coordinatorStderr += chunk.toString(); - }); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const pending = await send(addr, { - type: "request_source_preparation", - tenant: "tenant", - project: "project", - provider: "Git" - }); - assert.strictEqual(pending.type, "source_preparation"); - assert.strictEqual(pending.status.preparation.tenant, "tenant"); - assert.strictEqual(pending.status.preparation.project, "project"); - assert.strictEqual(pending.status.preparation.provider, "Git"); - assert.strictEqual( - pending.status.preparation.coordinator_requires_checkout_access, - false - ); - assert.deepStrictEqual(pending.status.preparation.required_capabilities, [ - "SourceGit" - ]); - assert.match(pending.status.disposition.Pending.reason, /waiting|node/i); - - const nodeIdentities = new Map(); - for (const node of ["source-cold", "source-ready"]) { - const identity = nodeIdentity("source-preparation-smoke", node); - nodeIdentities.set(node, identity); - const attached = await send(addr, { - type: "attach_node", - tenant: "tenant", - project: "project", - node, - public_key: identity.publicKey - }); - assert.strictEqual(attached.type, "node_attached"); - } - - const cold = await send(addr, signedNodeRequest("source-cold", nodeIdentities.get("source-cold"), "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: "source-cold", - capabilities: sourceCapableNode(), - cached_environment_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: true, - online: true - })); - assert.strictEqual(cold.type, "node_capabilities_recorded"); - - const readyReport = await send(addr, signedNodeRequest("source-ready", nodeIdentities.get("source-ready"), "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: "source-ready", - capabilities: sourceCapableNode(), - cached_environment_digests: [], - source_snapshots: [], - artifact_locations: [], - direct_connectivity: true, - online: true - })); - assert.strictEqual(readyReport.type, "node_capabilities_recorded"); - - const assigned = await send(addr, { - type: "request_source_preparation", - tenant: "tenant", - project: "project", - provider: "Git" - }); - assert.strictEqual(assigned.type, "source_preparation"); - assert(["source-cold", "source-ready"].includes(assigned.status.disposition.Assigned.node)); - assert.strictEqual( - assigned.status.preparation.coordinator_requires_checkout_access, - false - ); - - const crossTenantCompletion = await send(addr, signedNodeRequest("source-ready", nodeIdentities.get("source-ready"), "complete_source_preparation", { - type: "complete_source_preparation", - tenant: "other", - project: "project", - node: "source-ready", - provider: "Git", - source_snapshot: "sha256:source-prepared" - })); - assert.strictEqual(crossTenantCompletion.type, "error"); - assert.match( - crossTenantCompletion.message, - /tenant\/project scope|node identity is not enrolled/i - ); - - const completed = await send(addr, signedNodeRequest("source-ready", nodeIdentities.get("source-ready"), "complete_source_preparation", { - type: "complete_source_preparation", - tenant: "tenant", - project: "project", - node: "source-ready", - provider: "Git", - source_snapshot: "sha256:source-prepared" - })); - assert.strictEqual(completed.type, "source_preparation_completed"); - assert.strictEqual(completed.node, "source-ready"); - assert.strictEqual(completed.provider, "Git"); - assert.strictEqual(completed.source_snapshot, "sha256:source-prepared"); - - const placement = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: null, - environment_digest: null, - required_capabilities: ["SourceGit"], - source_snapshot: "sha256:source-prepared", - required_artifacts: [], - prefer_node: null - }); - assert.strictEqual(placement.type, "task_placement"); - assert.strictEqual(placement.placement.node, "source-ready"); - assert( - placement.placement.reasons.includes("source snapshot already local"), - "completed source preparation must update node source locality" - ); - } catch (error) { - if (coordinatorStderr) { - error.message = `${error.message}\ncoordinator stderr:\n${coordinatorStderr}`; - } - throw error; - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("Source preparation smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/tenant-isolation-contract-smoke.js b/scripts/tenant-isolation-contract-smoke.js deleted file mode 100644 index 65a1c9d..0000000 --- a/scripts/tenant-isolation-contract-smoke.js +++ /dev/null @@ -1,197 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); - -function read(relativePath) { - return fs.readFileSync(path.join(repo, relativePath), "utf8"); -} - -function maybeRead(segments) { - const fullPath = path.join(repo, ...segments); - if (!fs.existsSync(fullPath)) return null; - return fs.readFileSync(fullPath, "utf8"); -} - -function expect(source, name, pattern) { - assert.match(source, pattern, `missing tenant-isolation evidence: ${name}`); -} - -const auth = read("crates/clusterflux-core/src/auth.rs"); -const artifact = read("crates/clusterflux-core/src/artifact.rs"); -const operatorPanel = read("crates/clusterflux-core/src/operator_panel.rs"); -const source = read("crates/clusterflux-core/src/source.rs"); -const coordinatorService = [ - read("crates/clusterflux-coordinator/src/service.rs"), - read("crates/clusterflux-coordinator/src/service/routing.rs"), - read("crates/clusterflux-coordinator/src/service/nodes.rs"), - read("crates/clusterflux-coordinator/src/service/keys.rs"), - read("crates/clusterflux-coordinator/src/service/artifacts.rs"), - read("crates/clusterflux-coordinator/src/service/processes.rs"), - read("crates/clusterflux-coordinator/src/service/process_launch.rs"), - read("crates/clusterflux-coordinator/src/service/tests.rs"), -].join("\n"); -const artifactDownloadSmoke = read("scripts/artifact-download-smoke.js"); -const operatorPanelSmoke = read("scripts/operator-panel-smoke.js"); -const schedulerSmoke = read("scripts/scheduler-placement-smoke.js"); -const sourcePreparationSmoke = read("scripts/source-preparation-smoke.js"); -const liveSmoke = read("scripts/cli-happy-path-live-smoke.js"); - -for (const [name, pattern] of [ - ["auth contexts carry tenant and project", /pub struct AuthContext[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId/], - ["enrollment grants carry tenant and project", /pub struct EnrollmentGrant[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId/], - ["node credentials carry tenant and project", /pub struct NodeCredential[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId/], - ["same tenant/project denies tenant mismatch", /pub fn same_tenant_project[\s\S]*tenant mismatch/], - ["same tenant/project denies project mismatch", /pub fn same_tenant_project[\s\S]*project mismatch/], - ["auth unit denies cross-tenant access", /fn tenant_project_scope_denies_cross_tenant_access\(\)/], -]) { - expect(auth, name, pattern); -} - -for (const [name, pattern] of [ - ["artifact metadata carries tenant and project", /pub struct ArtifactMetadata[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId/], - ["download links carry tenant project process and actor", /pub struct DownloadLink[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId[\s\S]*pub process: ProcessId[\s\S]*pub actor: Actor/], - ["downloads authorize against scoped metadata", /let authz = same_tenant_project\(context, &scope\)/], - ["artifact test denies cross-tenant download", /fn cross_tenant_download_is_denied_even_with_known_artifact_id\(\)/], - ["artifact test denies cross-project download", /fn cross_project_download_is_denied_even_with_known_artifact_id\(\)/], -]) { - expect(artifact, name, pattern); -} - -for (const [name, pattern] of [ - ["panel state carries tenant project and process", /pub struct PanelState[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId[\s\S]*pub process: ProcessId/], - ["panel events carry tenant project and process", /pub struct PanelEvent[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId[\s\S]*pub process: ProcessId/], - ["panel events reject scope mismatch", /PanelError::ScopeMismatch/], - ["panel scope validation compares tenant project process", /self\.tenant != event\.tenant[\s\S]*self\.project != event\.project[\s\S]*self\.process != event\.process/], -]) { - expect(operatorPanel, name, pattern); -} - -expect( - source, - "source preparation carries tenant and project", - /pub struct SourcePreparation[\s\S]*pub tenant: TenantId[\s\S]*pub project: ProjectId/ -); - -for (const [name, pattern] of [ - ["project creation rejects foreign tenant reuse", /project id is outside the signed-in tenant scope/], - ["project selection rejects foreign tenant", /project is outside the signed-in tenant scope/], - ["project listing uses tenant-scoped context", /CoordinatorRequest::ListProjects[\s\S]*list_projects\(&context\)/], - [ - "node capability reports resolve the full enrolled scope", - /NodeScopeKey::from_refs\(&tenant, &project, &node\)[\s\S]*node_identity\(&tenant, &project, &node\)/, - ], - ["operator panel stop state is tenant/project/process keyed", /type PanelStopKey = \(TenantId, ProjectId, ProcessId\)/], - ["download service hides cross-tenant artifact existence", /cross_tenant\.to_string\(\)\.contains\("does not exist"\)/], - ["download service hides cross-project artifact existence", /cross_project\.to_string\(\)\.contains\("does not exist"\)/], - ["node capability test rejects cross-scope report", /fn service_rejects_node_capability_report_outside_enrollment_scope\(\)/], - ["source preparation test rejects cross-scope completion", /fn service_rejects_source_preparation_completion_outside_node_scope\(\)/], -]) { - expect(coordinatorService, name, pattern); -} - -for (const [name, sourceText, patterns] of [ - [ - "artifact download smoke", - artifactDownloadSmoke, - [ - /const crossTenant = await send/, - /const crossProject = await send/, - /const crossTenantOpen = await send/, - /const crossProjectOpen = await send/, - /artifact does not exist/, - /token is invalid/, - ], - ], - [ - "operator panel smoke", - operatorPanelSmoke, - [/const crossTenant = await send/, /render_operator_panel/, /scope\|tenant\|project/], - ], - [ - "scheduler and capability smoke", - schedulerSmoke, - [ - /const crossScopeInspection = await send/, - /assert\.strictEqual\(crossScopeInspection\.descriptors\.length, 0\)/, - /const crossTenantReport = await send/, - /tenant\\\/project scope/, - ], - ], - [ - "source preparation smoke", - sourcePreparationSmoke, - [/const crossTenantCompletion = await send/, /complete_source_preparation/, /tenant\\\/project scope/i], - ], -]) { - for (const pattern of patterns) { - expect(sourceText, name, pattern); - } -} - -for (const [name, pattern] of [ - [ - "live same-ID collision refreshes first-tenant metadata before the second build", - /const firstCollisionHelloBuild = await runHostedHelloBuild[\s\S]*secondHelloBuild = await runHostedHelloBuild/, - ], - [ - "live same-ID collision re-reads the fresh first-tenant process", - /"--process",[\s\S]*firstCollisionHelloBuild\.process[\s\S]*candidate\.artifact === firstCollisionHelloBuild\.artifact/, - ], -]) { - expect(liveSmoke, name, pattern); -} - -const hostedLibRoot = maybeRead(["private", "hosted-policy", "src", "lib.rs"]); -const hostedServiceSource = maybeRead([ - "private", - "hosted-policy", - "src", - "bin", - "clusterflux-hosted-service.rs", -]); -const hostedLib = hostedLibRoot; -const hostedSmoke = maybeRead([ - "private", - "hosted-policy", - "scripts", - "hosted-client-compat-smoke.js", -]); - -if (hostedLib && hostedServiceSource && hostedSmoke) { - for (const [name, pattern] of [ - ["hosted private layer is a compact identity broker", /pub struct HostedIdentityBroker[\s\S]*cli_session_ttl_seconds/], - ["hosted private layer has no parallel coordinator", /Runtime, persistence, nodes, processes,[\s\S]*remain owned by public CoordinatorService/], - ["hosted service delegates Client state to Core", /core_coordinator: CoordinatorService/], - ["hosted login creates project through Core", /issue_cli_session[\s\S]*AuthenticatedCoordinatorRequest::CreateProject/], - ]) { - expect(`${hostedLib}\n${hostedServiceSource}`, name, pattern); - } - - for (const forbidden of [ - "HostedCommunityControlPlane", - "HostedObservabilitySnapshot", - "agent_public_keys: BTreeMap", - "node_statuses: BTreeMap", - "process_statuses: BTreeMap", - "debug_sessions: BTreeMap", - ]) { - assert( - !hostedLib.includes(forbidden), - `private hosted policy must not reimplement Core state: ${forbidden}` - ); - } - - for (const [name, pattern] of [ - ["client-supplied identity is denied", /const forged = await sendHostedControl[\s\S]*authenticated CLI session/], - ["second OIDC subject receives a different tenant", /assert\.notStrictEqual\(victimLogin\.session\.tenant, session\.tenant\)/], - ["cross-tenant process events are denied", /const crossTenantTaskEventsDenied = await sendHostedControl[\s\S]*vp-victim[\s\S]*scope\|denied\|unauthorized/], - ]) { - expect(hostedSmoke, name, pattern); - } -} - -console.log("Tenant isolation contract smoke passed"); diff --git a/scripts/user-session-token-boundary-smoke.js b/scripts/user-session-token-boundary-smoke.js deleted file mode 100755 index d00a9da..0000000 --- a/scripts/user-session-token-boundary-smoke.js +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); - -function read(file) { - return fs.readFileSync(path.join(repo, file), "utf8"); -} - -function extractBalancedBlock(source, marker) { - const start = source.indexOf(marker); - assert(start >= 0, `missing marker ${marker}`); - const open = source.indexOf("{", start); - assert(open >= 0, `missing opening brace for ${marker}`); - let depth = 0; - for (let index = open; index < source.length; index += 1) { - const char = source[index]; - if (char === "{") depth += 1; - if (char === "}") { - depth -= 1; - if (depth === 0) return source.slice(start, index + 1); - } - } - throw new Error(`missing closing brace for ${marker}`); -} - -function extractEnumVariant(source, variant) { - const marker = ` ${variant} {`; - return extractBalancedBlock(source, marker); -} - -const forbiddenUserSessionCredentials = - /\b(BrowserSession|CliDeviceSession|BrowserLoginFlow|CliLoginFlow|authorization_url|verification_url|device_code|access_token|refresh_token|provider_token|provider_tokens|session_token|user_token|oauth_token)\b/i; - -function assertNoUserSessionCredential(surface, text) { - assert.doesNotMatch( - text, - forbiddenUserSessionCredentials, - `${surface} must not carry user OAuth/browser/session credentials` - ); -} - -const coordinatorService = `${read("crates/clusterflux-coordinator/src/service/protocol.rs")}\n${read("crates/clusterflux-coordinator/src/service/protocol/responses.rs")}`; -for (const variant of [ - "AdminStatus", - "SuspendTenant", - "AttachNode", - "RegisterAgentPublicKey", - "ListAgentPublicKeys", - "RotateAgentPublicKey", - "RevokeAgentPublicKey", - "NodeHeartbeat", - "ReportNodeCapabilities", - "RevokeNodeCredential", - "RequestRendezvous", - "RequestSourcePreparation", - "CompleteSourcePreparation", - "StartProcess", - "ReconnectNode", - "CancelTask", - "CancelProcess", - "PollTaskControl", - "RestartTask", - "DebugAttach", - "TaskCompleted", -]) { - assertNoUserSessionCredential( - `CoordinatorRequest::${variant}`, - extractEnumVariant(coordinatorService, variant) - ); -} - -const nodeRuntime = [ - read("crates/clusterflux-node/src/lib.rs"), - read("crates/clusterflux-node/src/command_runner.rs"), -].join("\n"); -for (const marker of [ - "pub struct LinuxCommandRunPlan", - "pub struct LinuxCommandTaskOutput", - "pub struct CapturedCommandLogs", - "pub struct VirtualThreadCommand", - "pub struct CommandOutput", -]) { - assertNoUserSessionCredential(marker, extractBalancedBlock(nodeRuntime, marker)); -} - -const coreExecution = read("crates/clusterflux-core/src/execution.rs"); -assertNoUserSessionCredential( - "CommandInvocation", - extractBalancedBlock(coreExecution, "pub struct CommandInvocation") -); - -const dapAdapter = read("crates/clusterflux-dap/src/variables.rs"); -assertNoUserSessionCredential( - "DAP variables response", - extractBalancedBlock(dapAdapter, "fn variables_response") -); - -const panel = read("crates/clusterflux-core/src/operator_panel.rs"); -assertNoUserSessionCredential( - "PanelEvent", - extractBalancedBlock(panel, "pub struct PanelEvent") -); - -const auth = read("crates/clusterflux-core/src/auth.rs"); -assert.match( - auth, - /task_credentials_do_not_contain_user_session/, - "core auth must keep the task credential user-session guard" -); -assert.match( - auth, - /CredentialKind::BrowserSession \| CredentialKind::CliDeviceSession/, - "task credential guard must reject browser and CLI sessions" -); - -console.log("User session token boundary smoke passed"); diff --git a/scripts/verify-public-split.sh b/scripts/verify-public-split.sh deleted file mode 100755 index f264477..0000000 --- a/scripts/verify-public-split.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -source_commit="$(git -C "$repo_root" rev-parse HEAD)" -export CLUSTERFLUX_ACCEPTANCE_COMMIT="$source_commit" -tmp_dir="$(mktemp -d)" -trap 'rm -rf "$tmp_dir"' EXIT - -tar \ - --exclude='./.git' \ - --exclude='./target' \ - --exclude='./private' \ - --exclude='./internal' \ - --exclude='./experiments' \ - --exclude='./.clusterflux' \ - --exclude='./vscode-extension/node_modules' \ - --exclude='./scripts/containers-home' \ - -C "$repo_root" \ - -cf - . | tar -C "$tmp_dir" -xf - - -if find "$tmp_dir" -path "$tmp_dir/private" -print -quit | grep -q .; then - echo "private directory leaked into public split" >&2 - exit 1 -fi - -if find "$tmp_dir" -path "$tmp_dir/experiments" -print -quit | grep -q .; then - echo "experiments directory leaked into public split" >&2 - exit 1 -fi - -if find "$tmp_dir" -path "$tmp_dir/internal" -print -quit | grep -q .; then - echo "internal directory leaked into public split" >&2 - exit 1 -fi - -(cd "$tmp_dir" && scripts/check-old-name.sh) -(cd "$tmp_dir" && CLUSTERFLUX_FILTERED_PUBLIC_TREE=1 node scripts/check-docs.js) -(cd "$tmp_dir" && scripts/check-code-size.sh) -(cd "$tmp_dir" && node scripts/resource-metering-contract-smoke.js) -(cd "$tmp_dir" && node scripts/hostile-input-contract-smoke.js) -(cd "$tmp_dir" && node scripts/tenant-isolation-contract-smoke.js) -(cd "$tmp_dir" && cargo fmt --all --check) -CARGO_TARGET_DIR="$tmp_dir/target" cargo test \ - --workspace \ - --all-targets \ - --manifest-path "$tmp_dir/Cargo.toml" -CARGO_TARGET_DIR="$tmp_dir/target" cargo build \ - --workspace \ - --all-targets \ - --manifest-path "$tmp_dir/Cargo.toml" -(cd "$tmp_dir" && node scripts/cli-install-smoke.js) -(cd "$tmp_dir" && node scripts/flagship-demo-smoke.js) -(cd "$tmp_dir" && node scripts/cli-local-run-smoke.js) -(cd "$tmp_dir" && node scripts/node-attach-smoke.js) -(cd "$tmp_dir" && node scripts/vscode-extension-smoke.js) -(cd "$tmp_dir" && node scripts/vscode-f5-smoke.js) -(cd "$tmp_dir" && node scripts/artifact-download-smoke.js) -(cd "$tmp_dir" && node scripts/artifact-export-smoke.js) - -public_digest="$( - find "$tmp_dir" \ - -path "$tmp_dir/target" -prune -o \ - -type f -print0 \ - | LC_ALL=C sort -z \ - | xargs -0 sha256sum \ - | sha256sum \ - | cut -d' ' -f1 -)" -printf 'Filtered public tree passed: commit=%s digest=sha256:%s\n' \ - "$source_commit" \ - "$public_digest" diff --git a/scripts/vscode-extension-smoke.js b/scripts/vscode-extension-smoke.js deleted file mode 100755 index 3a98e8d..0000000 --- a/scripts/vscode-extension-smoke.js +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/env node - -const fs = require("fs"); -const os = require("os"); -const path = require("path"); -const assert = require("assert"); - -const extensionRoot = path.resolve( - process.env.CLUSTERFLUX_VSCODE_EXTENSION_ROOT || - path.join(__dirname, "../vscode-extension") -); -const extension = require(path.join(extensionRoot, "extension.js")); -const packageJson = require(path.join(extensionRoot, "package.json")); -const extensionSource = fs.readFileSync( - path.join(extensionRoot, "extension.js"), - "utf8" -); -const repo = path.resolve(__dirname, ".."); - -assert.strictEqual(packageJson.main, "./extension.js"); -assert(fs.existsSync(path.join(extensionRoot, packageJson.main))); -assert.deepStrictEqual(packageJson.dependencies || {}, {}); -const root = fs.mkdtempSync(path.join(os.tmpdir(), "clusterflux-vscode-")); -fs.mkdirSync(path.join(root, "envs/linux"), { recursive: true }); -fs.writeFileSync(path.join(root, "envs/linux/Containerfile"), "FROM alpine\n"); -fs.mkdirSync(path.join(root, ".clusterflux"), { recursive: true }); -fs.writeFileSync( - extension.clusterfluxViewStatePath(root), - JSON.stringify({ - nodes: [{ id: "node-linux", status: "online", capabilities: "Command RootlessPodman" }], - processes: [{ id: "vp-build", status: "running", entry: "build" }], - logs: [{ task: "compile-linux", message: "stdout=12 stderr=0", bytes: 12 }], - artifacts: [{ path: "/vfs/artifacts/app.tar.zst", status: "retained", size: 12 }], - inspector: [{ label: "debug", value: "attached" }] - }) -); - -const envs = extension.discoverEnvironmentNames(root); -assert.deepStrictEqual(envs, ["linux"]); - -const diagnostics = extension.diagnoseEnvReferences( - 'let _ = env!("linux"); let _ = env!("windows");', - envs -); -assert.strictEqual(diagnostics.length, 1); -assert.strictEqual(diagnostics[0].name, "windows"); -assert.match(diagnostics[0].message, /envs\/windows\/Containerfile/); - -const inspectCommand = extension.bundleInspectCommand(root, "/repo"); -assert.strictEqual(inspectCommand.command, "cargo"); -assert.deepStrictEqual(inspectCommand.args.slice(0, 8), [ - "run", - "-q", - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - "bundle" -]); -assert(inspectCommand.args.includes("inspect")); -assert(inspectCommand.args.includes("--project")); -assert(inspectCommand.args.includes(root)); -assert(inspectCommand.args.includes("--json")); - -const refreshed = extension.refreshBundleBeforeLaunch(root, "/repo", (command, args, options) => { - assert.strictEqual(command, "cargo"); - assert(args.includes("bundle")); - assert.strictEqual(options.cwd, "/repo"); - return { - status: 0, - stdout: JSON.stringify({ metadata: { identity: "sha256:abc" } }), - stderr: "" - }; -}); -assert.strictEqual(refreshed.metadata.identity, "sha256:abc"); - -const launch = extension.resolveClusterfluxDebugConfiguration( - { uri: { fsPath: root } }, - {} -); -assert.deepStrictEqual(launch, { - name: "Clusterflux: Launch Virtual Process", - type: "clusterflux", - request: "launch", - entry: "build", - project: root, - runtimeBackend: "local-services" -}); -assert.strictEqual( - extension.clusterfluxProcessId("/workspace/app", "build"), - "vp-e4bd6ef50539" -); -assert.strictEqual( - extension.existingProcessRelationship( - { process: "vp-e4bd6ef50539", state: "running" }, - "vp-e4bd6ef50539" - ), - "same_launch_target" -); -assert.strictEqual( - extension.existingProcessRelationship( - { process: "vp-other", state: "running" }, - "vp-e4bd6ef50539" - ), - "different_launch_target" -); - -const liveProcesses = extension.loadLiveProcesses(root, "/repo", (_command, args) => { - assert.deepStrictEqual(args.slice(-3), ["process", "list", "--json"]); - return { - status: 0, - stdout: JSON.stringify({ - coordinator: "https://clusterflux.michelpaulissen.com", - tenant: "tenant-live", - project: "project-live", - user: "user-live", - processes: [{ process: "vp-live", state: "cancelling" }] - }), - stderr: "" - }; -}); -assert.deepStrictEqual(liveProcesses.processes, [ - { process: "vp-live", state: "cancelling" } -]); -assert.strictEqual(liveProcesses.project, "project-live"); - -const adapter = extension.debugAdapterExecutableSpec(root, repo); -assert.strictEqual(adapter.command, "cargo"); -assert.deepStrictEqual(adapter.args, [ - "run", - "-q", - "-p", - "clusterflux-dap", - "--bin", - "clusterflux-debug-dap" -]); -assert.deepStrictEqual(adapter.options, { cwd: repo }); - -const releasedAdapterPath = path.join(root, process.platform === "win32" ? "clusterflux-debug-dap.exe" : "clusterflux-debug-dap"); -fs.writeFileSync(releasedAdapterPath, ""); -const releasedAdapter = extension.debugAdapterExecutableSpec(root, repo); -assert.strictEqual(releasedAdapter.command, releasedAdapterPath); -assert.deepStrictEqual(releasedAdapter.args, []); -assert.deepStrictEqual(releasedAdapter.options, { cwd: root }); - -assert.throws( - () => - extension.refreshBundleBeforeLaunch(root, "/repo", () => ({ - status: 1, - stdout: "", - stderr: "missing environment linux" - })), - /missing environment linux/ -); - -assert( - packageJson.contributes.viewsContainers.activitybar.some( - (container) => container.id === "clusterflux" && container.title === "Clusterflux" - ), - "package.json must contribute a Clusterflux activity-bar container" -); -assert( - fs.existsSync(path.join(extensionRoot, "resources/clusterflux.svg")), - "Clusterflux activity-bar icon must exist" -); -const packageViewIds = packageJson.contributes.views.clusterflux.map((view) => view.id).sort(); -const descriptorViewIds = extension.clusterfluxViewDescriptors().map((view) => view.id).sort(); -assert.deepStrictEqual(descriptorViewIds, [ - "clusterflux.artifacts", - "clusterflux.inspector", - "clusterflux.logs", - "clusterflux.nodes", - "clusterflux.processes" -]); -assert.deepStrictEqual(packageViewIds, descriptorViewIds); -for (const viewId of descriptorViewIds) { - const items = extension.clusterfluxViewItems( - extension.loadClusterfluxViewState(root), - viewId - ); - assert( - items.length > 0 && !items[0].label.startsWith("No "), - `${viewId} should render state-backed items` - ); -} -assert.deepStrictEqual( - extension.clusterfluxViewItems(extension.loadClusterfluxViewState(root), "clusterflux.nodes")[0], - { - label: "node-linux", - description: "online Command RootlessPodman" - } -); - -assert( - packageJson.contributes.debuggers.some((debuggerContribution) => debuggerContribution.type === "clusterflux"), - "package.json must contribute the clusterflux debugger type" -); -for (const viewId of descriptorViewIds) { - assert( - packageJson.activationEvents.includes(`onView:${viewId}`), - `${viewId} should activate the extension when opened` - ); -} -const launchProperties = - packageJson.contributes.debuggers[0].configurationAttributes.launch.properties; -assert.strictEqual(launchProperties.runtimeBackend.default, "local-services"); -assert(launchProperties.runtimeBackend.enum.includes("live-services")); -assert.strictEqual(launchProperties.coordinatorEndpoint.default, undefined); -assert.strictEqual(launchProperties.tenant, undefined); -assert.strictEqual(launchProperties.projectId, undefined); -assert.strictEqual(launchProperties.actorUser, undefined); -assert( - packageJson.contributes.debuggers[0].configurationAttributes.attach, - "package.json must contribute an attach configuration" -); -for (const command of [ - "clusterflux.refreshProcesses", - "clusterflux.process.attach", - "clusterflux.process.cancel", - "clusterflux.process.abort" -]) { - assert( - packageJson.contributes.commands.some((entry) => entry.command === command), - `${command} must be contributed` - ); -} -assert.match(extensionSource, /registerDebugAdapterDescriptorFactory\("clusterflux"/); -assert.match(extensionSource, /clusterflux-debug-dap/); -assert.match(extensionSource, /\.clusterflux\/views\.json/); - -fs.rmSync(root, { recursive: true, force: true }); -console.log("VS Code extension smoke passed"); diff --git a/scripts/vscode-f5-smoke.js b/scripts/vscode-f5-smoke.js deleted file mode 100755 index d7b7893..0000000 --- a/scripts/vscode-f5-smoke.js +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const path = require("path"); - -const extension = require("../vscode-extension/extension"); - -class DapClient { - constructor(spec) { - this.child = cp.spawn(spec.command, spec.args, { - cwd: spec.options && spec.options.cwd, - env: spec.options && spec.options.env, - detached: process.platform !== "win32" - }); - this.seq = 1; - this.buffer = Buffer.alloc(0); - this.messages = []; - this.waiters = []; - this.stderr = ""; - - this.child.stdout.on("data", (chunk) => { - this.buffer = Buffer.concat([this.buffer, chunk]); - this.parse(); - }); - this.child.stderr.on("data", (chunk) => { - this.stderr += chunk.toString(); - }); - this.child.on("exit", () => this.flushWaiters()); - } - - send(command, args = {}) { - const seq = this.seq++; - const message = { seq, type: "request", command, arguments: args }; - const payload = Buffer.from(JSON.stringify(message)); - this.child.stdin.write(`Content-Length: ${payload.length}\r\n\r\n`); - this.child.stdin.write(payload); - return seq; - } - - async response(seq, command) { - const message = await this.waitFor( - (item) => - item.type === "response" && - item.request_seq === seq && - item.command === command - ); - if (!message.success) { - throw new Error( - `DAP ${command} failed: ${message.message || JSON.stringify(message)}\n${this.stderr}` - ); - } - return message; - } - - terminate() { - if (this.child.exitCode !== null) return; - if (process.platform === "win32") { - this.child.kill("SIGKILL"); - return; - } - try { - process.kill(-this.child.pid, "SIGKILL"); - } catch (_) { - this.child.kill("SIGKILL"); - } - } - - waitFor(predicate, timeoutMs = 240000) { - const existing = this.messages.find(predicate); - if (existing) return Promise.resolve(existing); - - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.terminate(); - reject(new Error(`timed out waiting for DAP message\n${this.stderr}`)); - }, timeoutMs); - this.waiters.push({ predicate, resolve, timer }); - }); - } - - parse() { - while (true) { - const headerEnd = this.buffer.indexOf("\r\n\r\n"); - if (headerEnd < 0) return; - const header = this.buffer.slice(0, headerEnd).toString(); - const match = header.match(/Content-Length: (\d+)/i); - if (!match) throw new Error(`bad DAP header: ${header}`); - const length = Number(match[1]); - const start = headerEnd + 4; - const end = start + length; - if (this.buffer.length < end) return; - const payload = this.buffer.slice(start, end).toString(); - this.buffer = this.buffer.slice(end); - this.messages.push(JSON.parse(payload)); - this.flushWaiters(); - } - } - - flushWaiters() { - for (const waiter of [...this.waiters]) { - const message = this.messages.find(waiter.predicate); - if (!message) continue; - clearTimeout(waiter.timer); - this.waiters.splice(this.waiters.indexOf(waiter), 1); - waiter.resolve(message); - } - } - - async close() { - if (this.child.exitCode !== null) return; - const seq = this.send("disconnect"); - await this.response(seq, "disconnect"); - this.child.stdin.end(); - } -} - -(async () => { - const repo = path.resolve(__dirname, ".."); - const project = path.join(repo, "examples/hello-build"); - const buildSourceLines = fs - .readFileSync(path.join(project, "src/lib.rs"), "utf8") - .split(/\r?\n/); - const sourceLine = (needle) => { - const index = buildSourceLines.findIndex((line) => line.includes(needle)); - assert(index >= 0, `flagship source must contain ${needle}`); - return index + 1; - }; - const buildMainLine = sourceLine("async fn build()"); - const launchConfig = extension.resolveClusterfluxDebugConfiguration( - { uri: { fsPath: project } }, - {} - ); - - assert.strictEqual(launchConfig.type, "clusterflux"); - assert.strictEqual(launchConfig.request, "launch"); - assert.strictEqual(launchConfig.entry, "build"); - assert.strictEqual(launchConfig.project, project); - assert.strictEqual(launchConfig.runtimeBackend, "local-services"); - - const inspection = extension.refreshBundleBeforeLaunch(project, repo); - assert.match(inspection.metadata.identity, /^sha256:/); - - // Keep the timed attach focused on the runtime boundary. A completely fresh - // public checkout may otherwise spend most of that window compiling the - // coordinator or node after the adapter has already started waiting. - cp.execFileSync( - "cargo", - [ - "build", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-node", - ], - { cwd: repo, stdio: "inherit" } - ); - const executableSuffix = process.platform === "win32" ? ".exe" : ""; - const adapterSpec = extension.debugAdapterExecutableSpec(repo); - adapterSpec.options = { - ...(adapterSpec.options || {}), - env: { - ...process.env, - CLUSTERFLUX_COORDINATOR_BIN: path.join( - repo, - "target", - "debug", - `clusterflux-coordinator${executableSuffix}` - ), - CLUSTERFLUX_NODE_BIN: path.join( - repo, - "target", - "debug", - `clusterflux-node${executableSuffix}` - ), - }, - }; - - const client = new DapClient(adapterSpec); - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true - }); - await client.response(initialize, "initialize"); - - const launch = client.send("launch", launchConfig); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const breakpoints = client.send("setBreakpoints", { - source: { path: path.join(project, "src/lib.rs") }, - breakpoints: [{ line: buildMainLine }] - }); - const breakpointResponse = await client.response(breakpoints, "setBreakpoints"); - assert.strictEqual(breakpointResponse.body.breakpoints[0].verified, false); - assert.match( - breakpointResponse.body.breakpoints[0].message, - /Pending coordinator breakpoint installation/ - ); - - const configurationDone = client.send("configurationDone"); - await client.response(configurationDone, "configurationDone"); - const installedBreakpoint = await client.waitFor( - (message) => - message.type === "event" && - message.event === "breakpoint" && - message.body?.breakpoint?.verified === true - ); - assert.strictEqual(installedBreakpoint.body.breakpoint.line, buildMainLine); - const stopped = await client.waitFor( - (message) => message.type === "event" && message.event === "stopped" - ); - assert.strictEqual(stopped.body.allThreadsStopped, true); - assert.strictEqual(stopped.body.reason, "breakpoint"); - - const threadsRequest = client.send("threads"); - const threads = (await client.response(threadsRequest, "threads")).body.threads; - const mainThread = threads.find((thread) => thread.name.includes("build coordinator main")); - assert(mainThread, "F5 launch must expose the real coordinator-main entrypoint thread"); - - const stackRequest = client.send("stackTrace", { - threadId: mainThread.id, - startFrame: 0, - levels: 1 - }); - const stack = (await client.response(stackRequest, "stackTrace")).body.stackFrames; - assert.strictEqual(stack[0].line, buildMainLine); - assert.strictEqual(stack[0].source.path, path.join(project, "src/lib.rs")); - assert.strictEqual(stack[0].source.sourceReference || 0, 0); - - const sourceRequest = client.send("source", { source: stack[0].source }); - const source = (await client.response(sourceRequest, "source")).body; - assert.match(source.content, /compile/); - - const scopesRequest = client.send("scopes", { frameId: stack[0].id }); - const scopes = (await client.response(scopesRequest, "scopes")).body.scopes; - const localsScope = scopes.find((scope) => scope.name === "Source Locals"); - const argsScope = scopes.find((scope) => scope.name === "Task Args and Handles"); - const runtimeScope = scopes.find((scope) => scope.name === "Clusterflux Runtime"); - const outputScope = scopes.find((scope) => scope.name === "Recent Output"); - assert(localsScope, "F5 launch must expose source locals scope"); - assert(argsScope, "F5 launch must expose task args and handles"); - assert(runtimeScope, "F5 launch must expose Clusterflux runtime state"); - assert(outputScope, "F5 launch must expose recent output state"); - - const localsRequest = client.send("variables", { - variablesReference: localsScope.variablesReference - }); - const locals = (await client.response(localsRequest, "variables")).body.variables; - assert( - locals.some( - (variable) => - variable.name === "unavailable-local-diagnostic" && - String(variable.value).includes("cannot be inspected") - ), - "source locals scope must report unavailable real Rust locals explicitly" - ); - - const runtimeRequest = client.send("variables", { - variablesReference: runtimeScope.variablesReference - }); - const runtime = (await client.response(runtimeRequest, "variables")).body.variables; - assert( - runtime.some( - (variable) => variable.name === "runtime_backend" && variable.value === "LocalServices" - ), - "extension-resolved F5 launch must use the real local-services backend" - ); - assert( - runtime.some( - (variable) => variable.name === "coordinator_task_events" && variable.value === 0 - ), - "a task frozen at its entry probe must not fabricate a terminal task event" - ); - assert( - runtime.some( - (variable) => - variable.name === "command_status" && - String(variable.value).includes( - "frozen through local services at executing Wasm probe" - ) - ) - ); - assert( - runtime.some( - (variable) => variable.name === "state" && variable.value === "Frozen" - ), - "F5 must expose the node-acknowledged frozen participant state" - ); - assert(runtime.some((variable) => variable.name === "command_spec")); - assert(runtime.some((variable) => variable.name === "stdout_tail")); - assert(runtime.some((variable) => variable.name === "stderr_tail")); - - const outputRequest = client.send("variables", { - variablesReference: outputScope.variablesReference - }); - const output = (await client.response(outputRequest, "variables")).body.variables; - assert(output.some((variable) => variable.name === "stdout_tail")); - assert(output.some((variable) => variable.name === "stderr_tail")); - - await client.close(); - } catch (error) { - client.terminate(); - throw error; - } - - console.log("VS Code F5 smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/wasmtime-assignment-smoke.js b/scripts/wasmtime-assignment-smoke.js deleted file mode 100755 index 9ec2683..0000000 --- a/scripts/wasmtime-assignment-smoke.js +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const sdkRuntime = fs.readFileSync( - path.join(repo, "crates/clusterflux-sdk/src/sdk_runtime.rs"), - "utf8" -); - -assert.doesNotMatch( - sdkRuntime, - /"type": "launch_task"/, - "native SDK code must not submit external TaskV1 work" -); -assert.match( - sdkRuntime, - /native SDK task spawning requires coordinator EntrypointV1 execution/ -); - -cp.execFileSync("node", ["scripts/cli-local-run-smoke.js"], { - cwd: repo, - stdio: "inherit", -}); -cp.execFileSync( - "cargo", - ["test", "-p", "clusterflux-node", "wasmtime_runtime_runs_named_task_export"], - { cwd: repo, stdio: "inherit" } -); -cp.execFileSync( - "cargo", - [ - "test", - "-p", - "clusterflux-coordinator", - "signed_active_wasm_task_can_spawn_and_join_child_in_its_process_only", - ], - { cwd: repo, stdio: "inherit" } -); - -console.log("Wasmtime assignment smoke passed"); diff --git a/scripts/wasmtime-node-smoke.js b/scripts/wasmtime-node-smoke.js deleted file mode 100644 index 7cbb1ac..0000000 --- a/scripts/wasmtime-node-smoke.js +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const fs = require("fs"); -const path = require("path"); - -const repo = path.resolve(__dirname, ".."); -const wasmTarget = path.join( - repo, - "target", - "wasm32-unknown-unknown", - "release", - "runtime_conformance.wasm" -); - -cp.execFileSync( - "cargo", - [ - "build", - "--release", - "-p", - "runtime-conformance", - "--target", - "wasm32-unknown-unknown", - ], - { - cwd: repo, - stdio: "inherit", - env: { - ...process.env, - CARGO_PROFILE_RELEASE_OPT_LEVEL: "z", - CARGO_PROFILE_RELEASE_LTO: "thin", - CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "1", - }, - } -); - -assert(fs.existsSync(wasmTarget), `missing compiled Wasm module at ${wasmTarget}`); - -const output = cp.execFileSync( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-wasmtime-smoke", - "--", - wasmTarget, - "task_add_one", - "41", - "42", - ], - { cwd: repo, encoding: "utf8" } -); - -const report = JSON.parse(output); -assert.strictEqual(report.type, "wasmtime_task_smoke"); -assert.strictEqual(report.export, "task_add_one"); -assert.strictEqual(report.arg, 41); -assert.strictEqual(report.result, 42); - -const debugOutput = cp.execFileSync( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-wasmtime-smoke", - "--", - "--debug-freeze-resume", - wasmTarget, - "task_add_one", - "41", - "42", - ], - { cwd: repo, encoding: "utf8" } -); -const debugReport = JSON.parse(debugOutput); -assert.strictEqual(debugReport.type, "wasmtime_debug_freeze_resume_smoke"); -assert.strictEqual(debugReport.export, "task_add_one"); -assert.strictEqual(debugReport.task, "task_add_one"); -assert.strictEqual(debugReport.frozen_state, "Frozen"); -assert.strictEqual(debugReport.resumed_state, "Running"); -assert(debugReport.stack_frames.some((frame) => String(frame).includes("task_add_one"))); -assert( - debugReport.local_values.some( - ([name, value]) => name === "wasm_local_0" && String(value).includes("41") - ), - "Wasmtime debug snapshot must expose the real i32 argument as a frame local" -); -assert.strictEqual(debugReport.node_runtime_captured_wasm_locals, true); -assert.strictEqual(debugReport.result, 42); -assert.strictEqual(debugReport.node_runtime_reached_wasm_task, true); - -const hostCommandOutput = cp.execFileSync( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-wasmtime-smoke", - "--", - "--host-command", - wasmTarget, - "compile_linux", - ], - { cwd: repo, encoding: "utf8" } -); -const hostCommandReport = JSON.parse(hostCommandOutput); -assert.strictEqual(hostCommandReport.type, "wasmtime_host_command_smoke"); -assert.strictEqual(hostCommandReport.task, "compile_linux"); -assert.match(hostCommandReport.export, /^clusterflux_task_v1_[0-9a-f]{64}$/); -assert.strictEqual(hostCommandReport.program, "cc"); -assert.deepStrictEqual(hostCommandReport.args, [ - "-Os", - "-static", - "-s", - "fixture/hello-clusterflux.c", - "-o", - "/clusterflux/output/hello-clusterflux", -]); -assert.strictEqual(hostCommandReport.working_directory, "/workspace"); -assert.deepStrictEqual(hostCommandReport.environment_variables, { - SOURCE_DATE_EPOCH: "0", -}); -assert.strictEqual(hostCommandReport.timeout_ms, 180000); -assert.strictEqual(hostCommandReport.network, "disabled"); -assert.strictEqual(hostCommandReport.status_code, 0); -assert.strictEqual(hostCommandReport.stdout, ""); -assert.strictEqual(hostCommandReport.artifact_name, "hello-clusterflux"); -assert.strictEqual(hostCommandReport.artifact_size_bytes, "hello-clusterflux".length); -assert.match(hostCommandReport.artifact_digest, /^sha256:[0-9a-f]{64}$/); -assert.strictEqual(hostCommandReport.node_host_import, "clusterflux.command_run_v1"); -assert.strictEqual(hostCommandReport.artifact_host_import, "clusterflux.vfs_operation_v1"); -assert.strictEqual(hostCommandReport.flagship_linux_build_task, true); -assert.strictEqual(hostCommandReport.node_executed_host_command, true); -assert.strictEqual(hostCommandReport.hosted_control_plane_ran_command, false); - -const artifactOutput = cp.execFileSync( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-wasmtime-smoke", - "--", - "--task-artifact", - wasmTarget, - "package_release", - ], - { cwd: repo, encoding: "utf8" } -); -const artifactReport = JSON.parse(artifactOutput); -assert.strictEqual(artifactReport.type, "wasmtime_task_artifact_smoke"); -assert.strictEqual(artifactReport.task, "package_release"); -assert.strictEqual(artifactReport.artifact_name, "release.tar"); -assert.strictEqual(artifactReport.artifact_size_bytes, "release.tar".length); -assert.match(artifactReport.artifact_digest, /^sha256:[0-9a-f]{64}$/); -assert.strictEqual(artifactReport.host_import, "clusterflux.vfs_operation_v1"); -assert.strictEqual(artifactReport.host_issued_handle_returned, true); -assert.ok(artifactReport.artifact.id.endsWith(artifactReport.artifact_digest.slice("sha256:".length))); - -console.log("Wasmtime node smoke passed"); diff --git a/scripts/windows-best-effort-smoke.js b/scripts/windows-best-effort-smoke.js deleted file mode 100755 index 839582a..0000000 --- a/scripts/windows-best-effort-smoke.js +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); - -const repo = path.resolve(__dirname, ".."); -const digest = (value) => - `sha256:${crypto.createHash("sha256").update(value).digest("hex")}`; -const environmentDigest = digest("windows-command-dev-environment"); -const sourceDigest = digest("windows-best-effort-source"); -const windowsArtifactBytes = Buffer.from("windows-output-data"); -const windowsArtifactDigest = digest(windowsArtifactBytes); -const emptyWasm = Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]); -const emptyWasmDigest = digest(emptyWasm); -const nodeDaemon = fs.readFileSync(path.join(repo, "crates/clusterflux-node/src/daemon.rs"), "utf8"); -const taskReports = fs.readFileSync( - path.join(repo, "crates/clusterflux-node/src/task_reports.rs"), - "utf8" -); -const nodeLib = fs.readFileSync(path.join(repo, "crates/clusterflux-node/src/lib.rs"), "utf8"); -const windowsDev = fs.readFileSync( - path.join(repo, "crates/clusterflux-node/src/windows_dev.rs"), - "utf8" -); -const executionCore = fs.readFileSync( - path.join(repo, "crates/clusterflux-core/src/execution.rs"), - "utf8" -); -const dapSource = [ - fs.readFileSync(path.join(repo, "crates/clusterflux-dap/src/demo_backend.rs"), "utf8"), - fs.readFileSync(path.join(repo, "crates/clusterflux-dap/src/tests.rs"), "utf8"), -].join("\n"); -const windowsNode = "windows-node"; -const windowsIdentity = nodeIdentity("windows-best-effort-smoke", windowsNode); - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function windowsCapabilities() { - return { - os: "Windows", - arch: "x86_64", - capabilities: ["Command", "VfsArtifacts", "WindowsCommandDev"], - environment_backends: ["WindowsCommandDev"], - source_providers: ["filesystem"] - }; -} - -function assertWindowsBackendBoundary() { - assert.match(nodeDaemon, /CoordinatorSession::connect\(&args\.coordinator\)/); - assert.match(nodeDaemon, /record_completed_task\(/); - assert.match(taskReports, /"type": "task_completed"/); - assert.doesNotMatch(nodeDaemon, /WindowsCommandDev|windows-command-dev|cfg\(windows\)/); - - assert.match(nodeLib, /impl CommandBackend for LinuxRootlessPodmanBackend/); - assert.match(nodeLib, /mod windows_dev/); - assert.match(nodeLib, /pub use windows_dev::\{WindowsCommandDevBackend, WindowsSandboxStubBackend\}/); - assert.match(windowsDev, /impl CommandBackend for WindowsCommandDevBackend/); - assert.match(windowsDev, /impl CommandBackend for WindowsSandboxStubBackend/); - assert.doesNotMatch(windowsDev, /LinuxRootlessPodmanBackend/); - assert.match(executionCore, /\bLinuxRootlessPodman\b/); - assert.match(executionCore, /\bWindowsCommandDev\b/); - assert.match(executionCore, /\bStubbedWindowsSandbox\b/); - - assert.match(dapSource, /thread\(WINDOWS_THREAD, "compile-windows", "compile windows"/); - assert.match(dapSource, /fn launch_threads_include_windows_task_in_same_virtual_process\(\)/); - assert.match(dapSource, /fn windows_thread_runtime_variables_share_virtual_process\(\)/); -} - -(async () => { - assertWindowsBackendBoundary(); - - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - let coordinatorStderr = ""; - coordinator.stderr.on("data", (chunk) => { - coordinatorStderr += chunk.toString(); - }); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const attached = await send(addr, { - type: "attach_node", - tenant: "tenant", - project: "project", - node: windowsNode, - public_key: windowsIdentity.publicKey - }); - assert.strictEqual(attached.type, "node_attached"); - assert.strictEqual(attached.node, windowsNode); - - const recorded = await send(addr, signedNodeRequest(windowsNode, windowsIdentity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: windowsNode, - capabilities: windowsCapabilities(), - cached_environment_digests: [environmentDigest], - dependency_cache_digests: [], - source_snapshots: [sourceDigest], - artifact_locations: [], - direct_connectivity: true, - online: true - })); - assert.strictEqual(recorded.type, "node_capabilities_recorded"); - assert.strictEqual(recorded.node, windowsNode); - - const placement = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: { - os: "Windows", - arch: null, - capabilities: ["WindowsCommandDev"] - }, - environment_digest: environmentDigest, - required_capabilities: ["Command"], - dependency_cache: null, - source_snapshot: sourceDigest, - required_artifacts: [], - prefer_node: null - }); - assert.strictEqual(placement.type, "task_placement"); - assert.strictEqual(placement.placement.node, windowsNode); - assert.ok(placement.placement.reasons.includes("warm environment cache")); - assert.ok(placement.placement.reasons.includes("source snapshot already local")); - - const started = await send(addr, { - type: "start_process", - tenant: "tenant", - project: "project", - process: "vp-windows" - }); - assert.strictEqual(started.type, "process_started"); - assert.strictEqual(started.process, "vp-windows"); - - const reconnected = await send(addr, signedNodeRequest(windowsNode, windowsIdentity, "reconnect_node", { - type: "reconnect_node", - tenant: "tenant", - project: "project", - node: windowsNode, - process: "vp-windows", - epoch: started.epoch - })); - assert.strictEqual(reconnected.type, "node_reconnected"); - - const launched = await send(addr, { - type: "launch_task", - tenant: "tenant", - project: "project", - actor_user: "operator", - task_spec: { - tenant: "tenant", - project: "project", - process: "vp-windows", - task_definition: "windows-command-dev", - task_instance: "windows-command-dev", - dispatch: { - kind: "coordinator_node_wasm", - export: "windows_command_dev", - abi: "task_v1", - }, - environment_id: "windows", - environment: { - os: "Windows", - arch: null, - capabilities: ["WindowsCommandDev"], - }, - environment_digest: environmentDigest, - required_capabilities: ["Command", "WindowsCommandDev"], - dependency_cache: null, - source_snapshot: sourceDigest, - required_artifacts: [], - args: [{ SourceSnapshot: sourceDigest }], - vfs_epoch: started.epoch, - bundle_digest: emptyWasmDigest, - }, - wait_for_node: false, - artifact_path: "/vfs/artifacts/windows-output.txt", - wasm_module_base64: emptyWasm.toString("base64"), - }); - assert.strictEqual(launched.type, "error", JSON.stringify(launched)); - assert.match(launched.message, /external callers may launch only EntrypointV1/); - - const recordedTask = await send(addr, signedNodeRequest(windowsNode, windowsIdentity, "task_completed", { - type: "task_completed", - tenant: "tenant", - project: "project", - process: "vp-windows", - node: windowsNode, - task: "windows-command-dev", - status_code: 0, - stdout_bytes: 18, - stderr_bytes: 0, - stdout_tail: "", - stderr_tail: "", - stdout_truncated: false, - stderr_truncated: false, - artifact_path: "/vfs/artifacts/windows-output.txt", - artifact_digest: windowsArtifactDigest, - artifact_size_bytes: windowsArtifactBytes.length - })); - assert.strictEqual(recordedTask.type, "error"); - assert.match(recordedTask.message, /coordinator-issued task instance|issued active task|active task/); - - const events = await send(addr, { - type: "list_task_events", - tenant: "tenant", - project: "project", - actor_user: "user", - process: "vp-windows" - }); - assert.strictEqual(events.type, "task_events"); - assert.strictEqual(events.events.length, 0); - - const link = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact: "windows-output.txt", - max_bytes: 1024 - }); - assert.strictEqual(link.type, "error"); - assert.match(link.message, /does not exist|not found|unavailable/); - } catch (error) { - if (coordinatorStderr) { - error.message = `${error.message}\ncoordinator stderr:\n${coordinatorStderr}`; - } - throw error; - } finally { - coordinator.kill("SIGTERM"); - } - - console.log("Windows best-effort smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/scripts/windows-runner-smoke.js b/scripts/windows-runner-smoke.js deleted file mode 100755 index b7b3628..0000000 --- a/scripts/windows-runner-smoke.js +++ /dev/null @@ -1,479 +0,0 @@ -#!/usr/bin/env node - -const assert = require("assert"); -const cp = require("child_process"); -const crypto = require("crypto"); -const fs = require("fs"); -const net = require("net"); -const path = require("path"); -const { coordinatorWireRequest } = require("./coordinator-wire"); -const { nodeIdentity, signedNodeRequest } = require("./node-signing"); - -const repo = path.resolve(__dirname, ".."); -const forgejoWindowsNode = "forgejo-windows-node"; -const forgejoWindowsIdentity = nodeIdentity("windows-runner-smoke", forgejoWindowsNode); -const windowsEnvironmentDigest = `sha256:${crypto - .createHash("sha256") - .update("clusterflux/windows-command-dev/v1") - .digest("hex")}`; -const sourceSnapshot = `sha256:${crypto - .createHash("sha256") - .update("clusterflux/windows-runner/source/v1") - .digest("hex")}`; - -class DapClient { - constructor() { - this.child = cp.spawn( - "cargo", - ["run", "-q", "-p", "clusterflux-dap", "--bin", "clusterflux-debug-dap"], - { cwd: repo } - ); - this.seq = 1; - this.buffer = Buffer.alloc(0); - this.messages = []; - this.waiters = []; - this.stderr = ""; - - this.child.stdout.on("data", (chunk) => { - this.buffer = Buffer.concat([this.buffer, chunk]); - this.parse(); - }); - this.child.stderr.on("data", (chunk) => { - this.stderr += chunk.toString(); - }); - this.child.on("exit", () => this.flushWaiters()); - } - - send(command, args = {}) { - const seq = this.seq++; - const message = { seq, type: "request", command, arguments: args }; - const payload = Buffer.from(JSON.stringify(coordinatorWireRequest(message))); - this.child.stdin.write(`Content-Length: ${payload.length}\r\n\r\n`); - this.child.stdin.write(payload); - return seq; - } - - async response(seq, command) { - const message = await this.waitFor( - (item) => - item.type === "response" && - item.request_seq === seq && - item.command === command - ); - if (!message.success) { - throw new Error(`DAP ${command} failed: ${message.message || JSON.stringify(coordinatorWireRequest(message))}`); - } - return message; - } - - waitFor(predicate, timeoutMs = 120000) { - const existing = this.messages.find(predicate); - if (existing) return Promise.resolve(existing); - - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.child.kill("SIGKILL"); - reject(new Error(`timed out waiting for DAP message\n${this.stderr}`)); - }, timeoutMs); - this.waiters.push({ predicate, resolve, timer }); - }); - } - - parse() { - while (true) { - const headerEnd = this.buffer.indexOf("\r\n\r\n"); - if (headerEnd < 0) return; - const header = this.buffer.slice(0, headerEnd).toString(); - const match = header.match(/Content-Length: (\d+)/i); - if (!match) throw new Error(`bad DAP header: ${header}`); - const length = Number(match[1]); - const start = headerEnd + 4; - const end = start + length; - if (this.buffer.length < end) return; - const payload = this.buffer.slice(start, end).toString(); - this.buffer = this.buffer.slice(end); - this.messages.push(JSON.parse(payload)); - this.flushWaiters(); - } - } - - flushWaiters() { - for (const waiter of [...this.waiters]) { - const message = this.messages.find(waiter.predicate); - if (!message) continue; - clearTimeout(waiter.timer); - this.waiters.splice(this.waiters.indexOf(waiter), 1); - waiter.resolve(message); - } - } - - async close() { - if (this.child.exitCode !== null) return; - const seq = this.send("disconnect"); - await this.response(seq, "disconnect"); - this.child.stdin.end(); - } -} - -function waitForJsonLine(child) { - return new Promise((resolve, reject) => { - let buffer = ""; - child.stdout.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - try { - resolve(JSON.parse(buffer.slice(0, newline).trim())); - } catch (error) { - reject(error); - } - }); - child.once("exit", (code) => { - reject(new Error(`process exited before JSON line with code ${code}`)); - }); - }); -} - -function send(addr, message) { - return new Promise((resolve, reject) => { - const socket = net.connect(addr.port, addr.host, () => { - socket.write(`${JSON.stringify(coordinatorWireRequest(message))}\n`); - }); - let buffer = ""; - socket.on("data", (chunk) => { - buffer += chunk.toString(); - const newline = buffer.indexOf("\n"); - if (newline < 0) return; - socket.end(); - try { - resolve(JSON.parse(buffer.slice(0, newline))); - } catch (error) { - reject(error); - } - }); - socket.on("error", reject); - }); -} - -function runWindowsAttach(addr, grant) { - return new Promise((resolve, reject) => { - const child = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-cli", - "--bin", - "clusterflux", - "--", - "node", - "attach", - "--coordinator", - `${addr.host}:${addr.port}`, - "--tenant", - "tenant", - "--project-id", - "project", - "--node", - forgejoWindowsNode, - "--public-key", - forgejoWindowsIdentity.publicKey, - "--enrollment-grant", - grant, - "--cap", - "windows-command-dev", - "--json" - ], - { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_NODE_PRIVATE_KEY: forgejoWindowsIdentity.privateKey, - }, - } - ); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.on("exit", (code) => { - if (code !== 0) { - reject(new Error(`Windows node attach failed with code ${code}\n${stderr}`)); - return; - } - try { - resolve(JSON.parse(stdout)); - } catch (error) { - reject( - new Error(`Windows node attach output was not JSON: ${stdout}\n${error.stack || error.message}`) - ); - } - }); - }); -} - -function runWindowsNode(addr, grant) { - return new Promise((resolve, reject) => { - const child = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-node", - "--bin", - "clusterflux-node", - "--", - "--coordinator", - `${addr.host}:${addr.port}`, - "--tenant", - "tenant", - "--project-id", - "project", - "--node", - forgejoWindowsNode, - "--public-key", - forgejoWindowsIdentity.publicKey, - "--enrollment-grant", - grant, - "--process", - "vp-forgejo-windows", - "--task", - "windows-command-dev", - "--command", - "cmd", - "--arg", - "/C", - "--arg", - "echo clusterflux-windows-runner", - "--artifact", - "/vfs/artifacts/windows-runner-output.txt" - ], - { - cwd: repo, - env: { - ...process.env, - CLUSTERFLUX_NODE_PRIVATE_KEY: forgejoWindowsIdentity.privateKey, - }, - } - ); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk) => { - stdout += chunk.toString(); - }); - child.stderr.on("data", (chunk) => { - stderr += chunk.toString(); - }); - child.on("exit", (code) => { - if (code !== 0) { - reject(new Error(`Windows node smoke failed with code ${code}\n${stderr}`)); - return; - } - try { - resolve(JSON.parse(stdout.trim().split(/\r?\n/).at(-1))); - } catch (error) { - reject(new Error(`node output was not JSON: ${stdout}\n${error.stack || error.message}`)); - } - }); - }); -} - -async function assertDebuggerShowsWindowsThread() { - const client = new DapClient(); - try { - const initialize = client.send("initialize", { - adapterID: "clusterflux", - linesStartAt1: true, - columnsStartAt1: true - }); - await client.response(initialize, "initialize"); - - const launch = client.send("launch", { - entry: "build", - project: path.join(repo, "tests/fixtures/runtime-conformance"), - runtimeBackend: "simulated" - }); - await client.response(launch, "launch"); - await client.waitFor( - (message) => message.type === "event" && message.event === "initialized" - ); - - const configurationDone = client.send("configurationDone"); - await client.response(configurationDone, "configurationDone"); - - const threadsRequest = client.send("threads"); - const threads = (await client.response(threadsRequest, "threads")).body.threads; - assert( - threads.some((thread) => thread.name.includes("compile windows")), - "debugger must represent the Windows task as a virtual thread" - ); - - await client.close(); - } catch (error) { - client.child.kill("SIGKILL"); - throw error; - } -} - -(async () => { - if (process.platform !== "win32") { - throw new Error( - `Windows runner validation requires win32; current platform is ${process.platform}` - ); - } - - const coordinator = cp.spawn( - "cargo", - [ - "run", - "-q", - "-p", - "clusterflux-coordinator", - "--bin", - "clusterflux-coordinator", - "--", - "--listen", - "127.0.0.1:0", - "--allow-local-trusted-loopback" - ], - { cwd: repo } - ); - let coordinatorStderr = ""; - coordinator.stderr.on("data", (chunk) => { - coordinatorStderr += chunk.toString(); - }); - - try { - const ready = await waitForJsonLine(coordinator); - const [host, portText] = ready.listen.split(":"); - const addr = { host, port: Number(portText) }; - assert.strictEqual((await send(addr, { type: "ping" })).type, "pong"); - - const attachGrant = await send(addr, { - type: "create_node_enrollment_grant", - tenant: "tenant", - project: "project", - actor_user: "operator", - ttl_seconds: 900 - }); - assert.strictEqual(attachGrant.type, "node_enrollment_grant_created"); - assert.strictEqual(attachGrant.scope, "node:attach"); - - const attach = await runWindowsAttach(addr, attachGrant.grant); - assert.strictEqual(attach.plan.node, forgejoWindowsNode); - assert.strictEqual(attach.boundary.cli_contacted_coordinator, true); - assert.strictEqual(attach.boundary.used_enrollment_exchange, true); - assert.strictEqual(attach.coordinator_response.type, "node_enrollment_exchanged"); - assert.strictEqual(attach.coordinator_response.credential.scope, "node:attach"); - assert(attach.plan.capabilities.capabilities.includes("WindowsCommandDev")); - - const runtimeGrant = await send(addr, { - type: "create_node_enrollment_grant", - tenant: "tenant", - project: "project", - actor_user: "operator", - ttl_seconds: 900 - }); - assert.strictEqual(runtimeGrant.type, "node_enrollment_grant_created"); - - const report = await runWindowsNode(addr, runtimeGrant.grant); - assert.strictEqual(report.node_status, "completed"); - assert.strictEqual(report.virtual_thread, "windows-command-dev"); - assert.strictEqual(report.status_code, 0); - assert.strictEqual(report.large_bytes_uploaded, false); - assert.strictEqual( - report.staged_artifact.path, - "/vfs/artifacts/windows-runner-output.txt" - ); - assert.strictEqual(report.registration_response.type, "node_enrollment_exchanged"); - assert.strictEqual(report.registration_response.credential.scope, "node:attach"); - assert.strictEqual(report.coordinator_response.type, "task_recorded"); - - const recorded = await send(addr, signedNodeRequest(forgejoWindowsNode, forgejoWindowsIdentity, "report_node_capabilities", { - type: "report_node_capabilities", - tenant: "tenant", - project: "project", - node: forgejoWindowsNode, - capabilities: { - os: "Windows", - arch: "x86_64", - capabilities: ["Command", "WindowsCommandDev", "VfsArtifacts"], - environment_backends: ["WindowsCommandDev"], - source_providers: ["filesystem"] - }, - cached_environment_digests: [windowsEnvironmentDigest], - source_snapshots: [sourceSnapshot], - artifact_locations: ["windows-runner-output.txt"], - direct_connectivity: true, - online: true - })); - assert.strictEqual(recorded.type, "node_capabilities_recorded"); - - const placement = await send(addr, { - type: "schedule_task", - tenant: "tenant", - project: "project", - environment: { - os: "Windows", - arch: null, - capabilities: ["WindowsCommandDev"] - }, - environment_digest: windowsEnvironmentDigest, - required_capabilities: ["Command"], - source_snapshot: sourceSnapshot, - required_artifacts: ["windows-runner-output.txt"], - prefer_node: null - }); - assert.strictEqual(placement.type, "task_placement"); - assert.strictEqual(placement.placement.node, "forgejo-windows-node"); - - const link = await send(addr, { - type: "create_artifact_download_link", - tenant: "tenant", - project: "project", - actor_user: "user", - artifact: "windows-runner-output.txt", - max_bytes: 1024 - }); - assert.strictEqual(link.type, "artifact_download_link"); - assert.deepStrictEqual(link.link.source, { - RetainedNode: "forgejo-windows-node" - }); - } catch (error) { - if (coordinatorStderr) { - error.message = `${error.message}\ncoordinator stderr:\n${coordinatorStderr}`; - } - throw error; - } finally { - coordinator.kill("SIGTERM"); - } - - await assertDebuggerShowsWindowsThread(); - - const outDir = path.join(repo, "target", "acceptance"); - fs.mkdirSync(outDir, { recursive: true }); - fs.writeFileSync( - path.join(outDir, "windows-runner.json"), - `${JSON.stringify( - { - kind: "clusterflux_windows_runner_validation", - platform: process.platform, - runner: process.env.FORGEJO_RUNNER_NAME || process.env.RUNNER_NAME || null, - validated: true - }, - null, - 2 - )}\n` - ); - - console.log("Windows runner smoke passed"); -})().catch((error) => { - console.error(error.stack || error.message); - process.exit(1); -}); diff --git a/tests/fixtures/runtime-conformance/Cargo.toml b/tests/fixtures/runtime-conformance/Cargo.toml deleted file mode 100644 index 8558f01..0000000 --- a/tests/fixtures/runtime-conformance/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "runtime-conformance" -version = "0.1.0" -edition.workspace = true -license.workspace = true -repository.workspace = true -publish = false - -[lib] -crate-type = ["rlib", "cdylib"] - -[dependencies] -clusterflux = { package = "clusterflux-sdk", path = "../../../crates/clusterflux-sdk" } -futures-executor.workspace = true -serde.workspace = true -serde_json.workspace = true diff --git a/tests/fixtures/runtime-conformance/README.md b/tests/fixtures/runtime-conformance/README.md deleted file mode 100644 index 15eed25..0000000 --- a/tests/fixtures/runtime-conformance/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Runtime conformance fixture - -This is test-only coverage for raw task ABI, cancellation, long joins, placement, -debug probes, and failure injection. It is intentionally not a public SDK -example. Start with examples/hello-build. diff --git a/tests/fixtures/runtime-conformance/envs/linux/Containerfile b/tests/fixtures/runtime-conformance/envs/linux/Containerfile deleted file mode 100644 index ba87ba3..0000000 --- a/tests/fixtures/runtime-conformance/envs/linux/Containerfile +++ /dev/null @@ -1,3 +0,0 @@ -FROM docker.io/library/alpine:3.20 -RUN apk add --no-cache build-base tar zstd -WORKDIR /workspace diff --git a/tests/fixtures/runtime-conformance/envs/windows/Dockerfile b/tests/fixtures/runtime-conformance/envs/windows/Dockerfile deleted file mode 100644 index 2978ba6..0000000 --- a/tests/fixtures/runtime-conformance/envs/windows/Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -# User-attached Windows development execution contract. -# This is not a managed untrusted Windows sandbox. diff --git a/tests/fixtures/runtime-conformance/fixture/hello-clusterflux.c b/tests/fixtures/runtime-conformance/fixture/hello-clusterflux.c deleted file mode 100644 index 79b67fd..0000000 --- a/tests/fixtures/runtime-conformance/fixture/hello-clusterflux.c +++ /dev/null @@ -1,6 +0,0 @@ -#include - -int main(void) { - puts("hello from a real Clusterflux build"); - return 0; -} diff --git a/tests/fixtures/runtime-conformance/src/lib.rs b/tests/fixtures/runtime-conformance/src/lib.rs deleted file mode 100644 index 91cf21f..0000000 --- a/tests/fixtures/runtime-conformance/src/lib.rs +++ /dev/null @@ -1,501 +0,0 @@ -use clusterflux::{Artifact, EnvRef, SourceSnapshot}; -use serde::{Deserialize, Serialize}; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, clusterflux::TaskArg)] -pub struct BuildReport { - pub linux_thread: u64, - pub linux_parallel_thread: u64, - pub package_thread: u64, - pub linux_artifact: Artifact, - pub package_artifact: Artifact, - pub source: SourceSnapshot, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, clusterflux::TaskArg)] -pub struct PackageInput { - pub release_name: String, - pub source: SourceSnapshot, - pub executable: Option, - pub inputs: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, clusterflux::TaskArg)] -pub struct IdentityProbeInput { - pub source: SourceSnapshot, - pub label: String, - pub delay_seconds: u64, -} - -pub fn linux_env() -> EnvRef { - clusterflux::env!("linux") -} - -pub fn windows_env() -> EnvRef { - clusterflux::env!("windows") -} - -#[clusterflux::task(capabilities = "source_filesystem")] -pub async fn prepare_source() -> SourceSnapshot { - #[cfg(target_arch = "wasm32")] - { - return clusterflux::source::snapshot() - .await - .expect("the source task should snapshot the node checkout it was placed on"); - } - #[cfg(not(target_arch = "wasm32"))] - SourceSnapshot { - digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - .to_owned(), - } -} - -#[clusterflux::task(capabilities = "command")] -pub async fn compile_linux(source: SourceSnapshot) -> Artifact { - let _ = &source; - #[cfg(target_arch = "wasm32")] - { - let executable = clusterflux::fs::output_path("hello-clusterflux") - .expect("the executable output path should be task-local"); - let output = clusterflux::command::Command::new("cc") - .args([ - "-Os", - "-static", - "-s", - "fixture/hello-clusterflux.c", - "-o", - executable.as_str(), - ]) - .current_dir("/workspace") - .env("SOURCE_DATE_EPOCH", "0") - .timeout(std::time::Duration::from_secs(180)) - .network_disabled() - .output() - .await - .expect("the declared Linux environment should provide a real C compiler"); - assert_eq!(output.status_code, Some(0)); - return clusterflux::fs::flush(&executable) - .await - .expect("the command-created executable should flush to node artifact storage"); - } - #[cfg(not(target_arch = "wasm32"))] - Artifact { - id: "hello-clusterflux-native-test".to_owned(), - digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - .to_owned(), - size_bytes: 0, - } -} - -#[clusterflux::task] -#[unsafe(no_mangle)] -pub extern "C" fn task_add_one(input: i32) -> i32 { - input + 1 -} - -#[clusterflux::task] -#[unsafe(no_mangle)] -pub extern "C" fn task_trap(_input: i32) -> i32 { - #[cfg(target_arch = "wasm32")] - core::arch::wasm32::unreachable(); - #[cfg(not(target_arch = "wasm32"))] - panic!("intentional task trap") -} - -#[clusterflux::task(capabilities = "command")] -pub async fn package_release(input: PackageInput) -> Artifact { - #[cfg(target_arch = "wasm32")] - { - assert_eq!(input.release_name, "release.tar"); - let executable = input - .executable - .as_ref() - .expect("the package input should contain the compiler artifact"); - assert!(input.inputs.iter().any(|artifact| artifact == executable)); - let executable = clusterflux::fs::materialize(&executable, "package/hello-clusterflux") - .await - .expect("the retaining node should materialize the compiler artifact locally"); - let release = clusterflux::fs::output_path("release.tar") - .expect("the release output path should be task-local"); - let output = clusterflux::command::Command::new("tar") - .args([ - "--sort=name", - "--mtime=@0", - "--owner=0", - "--group=0", - "--numeric-owner", - "--mode=0755", - "-cf", - release.as_str(), - "-C", - "/clusterflux/output/package", - "hello-clusterflux", - ]) - .current_dir("/workspace") - .env("SOURCE_DATE_EPOCH", "0") - .timeout(std::time::Duration::from_secs(180)) - .network_disabled() - .output() - .await - .expect("the declared Linux environment should package the materialized executable"); - assert_eq!(output.status_code, Some(0)); - assert_eq!( - executable.as_str(), - "/clusterflux/output/package/hello-clusterflux" - ); - return clusterflux::fs::flush(&release) - .await - .expect("the command-created release archive should flush as the final artifact"); - } - #[cfg(not(target_arch = "wasm32"))] - { - let _ = input; - Artifact { - id: "release-native-test".to_owned(), - digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - .to_owned(), - size_bytes: 0, - } - } -} - -#[clusterflux::task(capabilities = "command")] -pub async fn abort_probe(source: SourceSnapshot) -> i32 { - let _ = &source; - #[cfg(target_arch = "wasm32")] - { - let output = clusterflux::command::Command::new("sh") - .args(["-c", "sleep 90"]) - .timeout(std::time::Duration::from_secs(120)) - .network_disabled() - .output() - .await - .expect("abort probe command should either finish or be stopped by process abort"); - return output.status_code.unwrap_or(-1); - } - #[cfg(not(target_arch = "wasm32"))] - 0 -} - -#[clusterflux::task(capabilities = "command")] -pub async fn long_join_probe(source: SourceSnapshot) -> i32 { - let _ = &source; - #[cfg(target_arch = "wasm32")] - { - let output = clusterflux::command::Command::new("sh") - .args(["-c", "sleep 125"]) - .timeout(std::time::Duration::from_secs(180)) - .network_disabled() - .output() - .await - .expect("the controlled long-running command should complete normally"); - return output.status_code.unwrap_or(-1); - } - #[cfg(not(target_arch = "wasm32"))] - 0 -} - -#[clusterflux::task(capabilities = "command")] -pub async fn identity_probe(input: IdentityProbeInput) -> String { - let _ = &input.source; - #[cfg(target_arch = "wasm32")] - { - let script = format!( - "sleep {}; printf '%s' '{}'", - input.delay_seconds, input.label - ); - let output = clusterflux::command::Command::new("sh") - .args(["-c", script.as_str()]) - .timeout(std::time::Duration::from_secs(60)) - .network_disabled() - .output() - .await - .expect("identity probe command should complete"); - assert_eq!(output.status_code, Some(0)); - return input.label; - } - #[cfg(not(target_arch = "wasm32"))] - input.label -} - -#[clusterflux::task] -pub fn cooperative_cancellation_probe() -> i32 { - #[cfg(target_arch = "wasm32")] - loop { - if clusterflux::process::cancellation_requested() - .expect("task control should remain available while the Wasm task is running") - { - // Cancellation is a request observed and handled by task code. Returning - // normally is intentionally distinct from the runtime's forced abort path. - return 17; - } - } - #[cfg(not(target_arch = "wasm32"))] - 17 -} - -#[clusterflux::task] -pub fn debug_child_probe() -> i32 { - #[cfg(target_arch = "wasm32")] - loop { - if clusterflux::process::cancellation_requested() - .expect("child debug participant should retain task control") - { - return 23; - } - } - #[cfg(not(target_arch = "wasm32"))] - 23 -} - -#[clusterflux::task] -pub async fn debug_parent_probe() -> i32 { - #[cfg(target_arch = "wasm32")] - { - let child = clusterflux::spawn::task(debug_child_probe) - .name("debug child participant") - .start() - .await - .expect("parent debug participant should spawn its child"); - return child - .join() - .await - .expect("parent debug participant should join its child"); - } - #[cfg(not(target_arch = "wasm32"))] - 23 -} - -#[clusterflux::main] -pub async fn build_main() -> BuildReport { - run_build_workflow().await -} - -#[clusterflux::main(name = "fail")] -pub async fn fail_main() -> Result { - #[cfg(target_arch = "wasm32")] - { - let child = clusterflux::spawn::task_with_arg(0_i32, |value| task_trap(value)) - .task_id("task_trap") - .name("intentional failing child") - .start() - .await - .map_err(|error| format!("failing entrypoint could not launch its child: {error}"))?; - return child - .join() - .await - .map_err(|error| format!("intentional child failure: {error}")); - } - #[cfg(not(target_arch = "wasm32"))] - Err("intentional child failure".to_owned()) -} - -#[clusterflux::main(name = "restart")] -pub async fn restart_main() -> i32 { - #[cfg(target_arch = "wasm32")] - { - return clusterflux::spawn::task_with_arg(0_i32, |value| task_trap(value)) - .task_id("task_trap") - .name("edited restart probe") - .failure_policy(clusterflux::spawn::TaskFailurePolicy::AwaitOperator) - .start() - .await - .expect("restart probe should launch its child") - .join() - .await - .expect("restart probe child should complete"); - } - #[cfg(not(target_arch = "wasm32"))] - task_add_one(41) -} - -#[clusterflux::main(name = "park-wake")] -pub async fn park_wake_main() -> i32 { - #[cfg(target_arch = "wasm32")] - { - let mut value = 0_i32; - for _ in 0..16 { - let next = clusterflux::spawn::task_with_arg(value, |input| task_add_one(input)) - .task_id("task_add_one") - .name("park/wake fuel refill probe") - .start() - .await - .expect("park/wake probe should launch") - .join() - .await - .expect("park/wake probe should complete"); - value = i32::try_from(next).expect("park/wake result should remain in i32 range"); - } - return value; - } - #[cfg(not(target_arch = "wasm32"))] - 16 -} - -#[clusterflux::main(name = "long-join")] -pub async fn long_join_main() -> i32 { - #[cfg(target_arch = "wasm32")] - { - let source = clusterflux::spawn::async_task(prepare_source) - .name("prepare source for controlled long-running task") - .start() - .await - .expect("long join source preparation should launch") - .join() - .await - .expect("long join source preparation should complete"); - return clusterflux::spawn::async_task_with_arg(source, long_join_probe) - .name("controlled task longer than two minutes") - .env(linux_env()) - .start() - .await - .expect("long join probe should launch") - .join() - .await - .expect("long join probe should remain joinable beyond two minutes"); - } - #[cfg(not(target_arch = "wasm32"))] - 0 -} - -#[clusterflux::main(name = "identity")] -pub async fn identity_main() -> Vec { - #[cfg(target_arch = "wasm32")] - { - let source = clusterflux::spawn::async_task(prepare_source) - .name("prepare source for identity probes") - .start() - .await - .expect("identity source preparation should launch") - .join() - .await - .expect("identity source preparation should complete"); - let slow = clusterflux::spawn::async_task_with_arg( - IdentityProbeInput { - source: source.clone(), - label: "slow-first".to_owned(), - delay_seconds: 30, - }, - identity_probe, - ) - .name("identity probe slow") - .env(linux_env()) - .start() - .await - .expect("slow identity probe should launch"); - let fast = clusterflux::spawn::async_task_with_arg( - IdentityProbeInput { - source, - label: "fast-second".to_owned(), - delay_seconds: 20, - }, - identity_probe, - ) - .name("identity probe fast") - .env(linux_env()) - .start() - .await - .expect("fast identity probe should launch"); - let fast_result = fast - .join() - .await - .expect("fast identity probe should complete first"); - let slow_result = slow - .join() - .await - .expect("slow identity probe should remain independently joinable"); - return vec![fast_result, slow_result]; - } - #[cfg(not(target_arch = "wasm32"))] - vec!["fast-second".to_owned(), "slow-first".to_owned()] -} - -pub async fn run_build_workflow() -> BuildReport { - let source = clusterflux::spawn::async_task(prepare_source) - .name("prepare source snapshot") - .start() - .await - .unwrap() - .join() - .await - .unwrap(); - let linux = clusterflux::spawn::async_task_with_arg(source.clone(), compile_linux) - .name("compile linux") - .env(linux_env()) - .start() - .await - .unwrap(); - let linux_parallel = clusterflux::spawn::async_task_with_arg(source.clone(), compile_linux) - .name("compile linux in parallel") - .env(linux_env()) - .start() - .await - .unwrap(); - let linux_thread = linux.virtual_thread_id(); - let linux_parallel_thread = linux_parallel.virtual_thread_id(); - let linux_artifact = linux.join().await.unwrap(); - let linux_parallel_artifact = linux_parallel.join().await.unwrap(); - assert_eq!(linux_artifact.digest, linux_parallel_artifact.digest); - let package = clusterflux::spawn::async_task_with_arg( - PackageInput { - release_name: "release.tar".to_owned(), - source: source.clone(), - executable: Some(linux_artifact.clone()), - inputs: vec![linux_artifact.clone()], - }, - package_release, - ) - .name("package artifacts") - .env(linux_env()) - .start() - .await - .unwrap(); - - let package_thread = package.virtual_thread_id(); - let package_artifact = package.join().await.unwrap(); - - BuildReport { - linux_thread, - linux_parallel_thread, - package_thread, - linux_artifact, - package_artifact, - source, - } -} - -#[cfg(test)] -mod tests { - use futures_executor::block_on; - - use super::*; - - #[test] - fn flagship_workflow_is_rust_source_with_spawned_virtual_tasks() { - let main_report = block_on(build_main()); - assert_eq!( - main_report.linux_artifact.id, - "hello-clusterflux-native-test" - ); - assert_eq!(task_add_one(41), 42); - assert_eq!(block_on(restart_main()), 42); - assert_eq!(block_on(park_wake_main()), 16); - assert_eq!(block_on(long_join_main()), 0); - assert_eq!( - block_on(identity_main()), - vec!["fast-second".to_owned(), "slow-first".to_owned()] - ); - assert_eq!(linux_env().name, "linux"); - assert_eq!(windows_env().name, "windows"); - - let report = block_on(run_build_workflow()); - - assert_ne!(report.linux_thread, report.package_thread); - assert_ne!(report.linux_thread, report.linux_parallel_thread); - assert_eq!(report.linux_artifact.id, "hello-clusterflux-native-test"); - assert_eq!(report.package_artifact.id, "release-native-test"); - assert_eq!( - report.source.digest, - "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - } -}