From f8c0f32c15719aa2df22929976a7d108ffc5c677 Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 18 Nov 2026 23:27:16 +1100 Subject: [PATCH 1/7] feat(cli): pin a backup trusted root and fetch roots by id The root private key for skilld-root-2026 is lost, so the next release must pin a new primary root and a backup root. Each pinned root is fetched from /api/v1/trusted-roots/{rootKeyId}; only a 404 moves to the next pin, so a served root that fails verification never falls through. The release refuses to build unless skilld.dev serves the pinned primary root. --- .github/workflows/release.yml | 34 +++ crates/skilld-command/src/remote.rs | 152 +++++++++--- crates/skilld-command/tests/remote.rs | 235 +++++++++++++++++-- crates/skilld-core/src/lib.rs | 6 +- crates/skilld-core/src/remote.rs | 27 +++ crates/skilld-native/src/main.rs | 14 +- crates/skilld-native/tests/run_flow.rs | 56 ++++- docs/migrate-v2-to-v3.md | 14 +- packages/protocol/openapi/skilld-v1.yaml | 35 +++ packages/protocol/src/generated/skilld-v1.ts | 50 +++- 10 files changed, 563 insertions(+), 60 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 91fb8ffc..154f8b0a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,8 @@ on: env: SKILLD_ROOT_KEY_ID: ${{ vars.SKILLD_ROOT_KEY_ID }} SKILLD_ROOT_PUBLIC_KEY: ${{ vars.SKILLD_ROOT_PUBLIC_KEY }} + SKILLD_BACKUP_ROOT_KEY_ID: ${{ vars.SKILLD_BACKUP_ROOT_KEY_ID }} + SKILLD_BACKUP_ROOT_PUBLIC_KEY: ${{ vars.SKILLD_BACKUP_ROOT_PUBLIC_KEY }} SKILLD_RELEASE_PUBLIC_KEY: ${{ vars.SKILLD_RELEASE_PUBLIC_KEY }} jobs: @@ -37,10 +39,42 @@ jobs: echo 'SKILLD_ROOT_PUBLIC_KEY is required.' >&2 exit 1 } + test -n "$SKILLD_BACKUP_ROOT_KEY_ID" || { + echo 'SKILLD_BACKUP_ROOT_KEY_ID is required.' >&2 + exit 1 + } + test -n "$SKILLD_BACKUP_ROOT_PUBLIC_KEY" || { + echo 'SKILLD_BACKUP_ROOT_PUBLIC_KEY is required.' >&2 + exit 1 + } + if test "$SKILLD_BACKUP_ROOT_KEY_ID" = "$SKILLD_ROOT_KEY_ID" \ + || test "$SKILLD_BACKUP_ROOT_PUBLIC_KEY" = "$SKILLD_ROOT_PUBLIC_KEY"; then + echo 'The backup root must have its own key id and public key.' >&2 + exit 1 + fi test -n "$SKILLD_RELEASE_PUBLIC_KEY" || { echo 'SKILLD_RELEASE_PUBLIC_KEY is required. Run node scripts/release/release-signing.mjs generate-key.' >&2 exit 1 } + - name: Require skilld.dev to serve the primary root + shell: bash + run: | + # The CLI asks for its primary root first. If skilld.dev does not + # serve it, the released CLI depends on the backup root alone. + key_id="$(jq -rn --arg value "$SKILLD_ROOT_KEY_ID" '$value | @uri')" + root="$(curl --fail --silent --show-error --location \ + --proto '=https' --proto-redir '=https' --retry 3 --max-time 30 \ + "https://skilld.dev/api/v1/trusted-roots/$key_id")" || { + echo "skilld.dev does not serve the trusted root $SKILLD_ROOT_KEY_ID." >&2 + exit 1 + } + printf '%s' "$root" | jq -e \ + --arg key_id "$SKILLD_ROOT_KEY_ID" \ + --arg public_key "$SKILLD_ROOT_PUBLIC_KEY" \ + '.rootKeyId == $key_id and .rootPublicKey == $public_key' >/dev/null || { + echo "The skilld.dev trusted root $SKILLD_ROOT_KEY_ID does not match SKILLD_ROOT_PUBLIC_KEY." >&2 + exit 1 + } - id: matrix name: Read native package matrix shell: bash diff --git a/crates/skilld-command/src/remote.rs b/crates/skilld-command/src/remote.rs index 334799be..66d4ddba 100644 --- a/crates/skilld-command/src/remote.rs +++ b/crates/skilld-command/src/remote.rs @@ -14,7 +14,7 @@ use skilld_core::{ ArtifactAttestation, CheckOutcome, CommitAuthor, CommitSha, CommitSummary, ListedOrigin, ListedSkill, LockedSource, MultiSkillRef, PreparedFile, RemoteError, RemoteSelector, RepositoryVisibility, SearchResponse, SkillListing, SkillName, SourceRef, SourceRequest, - SourceSelector, SourceStatus, TrustedRoot, TrustedRootPin, VerifiedArtifact, + SourceSelector, SourceStatus, TrustedRoot, TrustedRootPin, TrustedRootPins, VerifiedArtifact, VerifiedTrustedRoot, declared_skill_name, parse_search_response, prepare_unverified_files, verify_artifact, verify_attestation, verify_linked_file, verify_trusted_root, with_linked_files, @@ -770,10 +770,59 @@ struct GithubCommitAuthor { #[derive(Clone, Debug, Eq, PartialEq)] pub enum NativeRemoteConfig { - Pinned(TrustedRootPin), + Pinned(TrustedRootPins), Unconfigured, } +impl NativeRemoteConfig { + /// The trusted roots a build pins, from its compiled build variables. + /// + /// An empty value counts as missing, because an unset GitHub Actions + /// variable arrives as an empty string. A build without a whole primary + /// root is unconfigured. A build with half a backup root, or a backup root + /// without a primary one, is unconfigured too, so it fails closed. + pub fn from_build_variables( + root_key_id: Option<&str>, + root_public_key: Option<&str>, + backup_root_key_id: Option<&str>, + backup_root_public_key: Option<&str>, + ) -> Self { + match ( + build_pin(root_key_id, root_public_key), + build_pin(backup_root_key_id, backup_root_public_key), + ) { + (BuildPin::Whole(primary), BuildPin::Missing) => { + Self::Pinned(TrustedRootPins::new(primary, None)) + } + (BuildPin::Whole(primary), BuildPin::Whole(backup)) => { + Self::Pinned(TrustedRootPins::new(primary, Some(backup))) + } + _ => Self::Unconfigured, + } + } +} + +/// One trusted root pin as a build names it: both variables, neither, or one. +enum BuildPin { + Missing, + Whole(TrustedRootPin), + Partial, +} + +fn build_pin(key_id: Option<&str>, public_key: Option<&str>) -> BuildPin { + match ( + key_id.filter(|value| !value.is_empty()), + public_key.filter(|value| !value.is_empty()), + ) { + (None, None) => BuildPin::Missing, + (Some(key_id), Some(public_key)) => BuildPin::Whole(TrustedRootPin { + key_id: key_id.to_owned(), + public_key: public_key.to_owned(), + }), + _ => BuildPin::Partial, + } +} + #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum RemoteProgressStage { @@ -942,15 +991,33 @@ impl SkilldRemote { /// needs. Without either, the adapter applies its own limit. fn execute_bounded( &self, - mut request: HttpRequest, + request: HttpRequest, allowed: AllowedOrigin, + deadline: Option<&mut ResolutionDeadline>, + transfer_timeout: Option, + max_retries: usize, + ) -> Result { + let response = + self.send_bounded(request, &allowed, deadline, transfer_timeout, max_retries)?; + if !(200..300).contains(&response.status) { + return Err(status_error(&response, &allowed)); + } + Ok(response) + } + + /// [`Self::execute_bounded`] without the status check: the final response + /// after retries and redirects, whatever its status. + fn send_bounded( + &self, + mut request: HttpRequest, + allowed: &AllowedOrigin, mut deadline: Option<&mut ResolutionDeadline>, transfer_timeout: Option, max_retries: usize, ) -> Result { let mut redirects = 0_usize; loop { - validate_request_url(&request.url, &allowed)?; + validate_request_url(&request.url, allowed)?; let mut retry = 0_usize; let response = loop { if self.cancellation.is_cancelled() { @@ -1016,7 +1083,7 @@ impl SkilldRemote { let next = current.join(location).map_err(|_| { RemoteError::new("REDIRECT_REJECTED", "the redirect URL is invalid") })?; - validate_url(&next, &allowed)?; + validate_url(&next, allowed)?; if matches!(allowed, AllowedOrigin::GithubTarball) && next.host_str() != Some("codeload.github.com") { @@ -1029,17 +1096,6 @@ impl SkilldRemote { redirects += 1; continue; } - if !(200..300).contains(&response.status) { - return Err(match allowed { - AllowedOrigin::Github - | AllowedOrigin::GithubTarball - | AllowedOrigin::GithubFile => github_error(&response), - AllowedOrigin::Service(_) | AllowedOrigin::Artifact(_) => { - problem_error(&response) - } - AllowedOrigin::Api(_) => api::api_problem_error(&response), - }); - } return Ok(response); } } @@ -1072,23 +1128,52 @@ impl SkilldRemote { }) } + /// The trusted root of the first pin that skilld.dev serves, verified + /// against that pin. + /// + /// skilld asks for each pinned root by its id, in pin order. Only a 404 + /// moves on to the next pin. Any other failure, or a served root that + /// fails verification, stops here. fn verified_root(&self) -> Result { - let NativeRemoteConfig::Pinned(pin) = &self.root_pin else { + let NativeRemoteConfig::Pinned(pins) = &self.root_pin else { return Err(RemoteError::new( "TRUSTED_ROOT_UNCONFIGURED", "this build has no trusted root pin", )); }; - let request = HttpRequest { - method: HttpMethod::Get, - url: self.service_url("/api/v1/trusted-root")?.into(), - headers: vec![], - body: vec![], - response_limit: JSON_LIMIT, - }; - let response = self.execute(request, AllowedOrigin::Service(self.endpoint.clone()))?; - let root: TrustedRoot = parse_json(&response.body)?; - verify_trusted_root(root, pin) + let allowed = AllowedOrigin::Service(self.endpoint.clone()); + for pin in pins.iter() { + let request = HttpRequest { + method: HttpMethod::Get, + url: self.trusted_root_url(&pin.key_id)?, + headers: vec![], + body: vec![], + response_limit: JSON_LIMIT, + }; + let response = self.send_bounded(request, &allowed, None, None, MAX_RETRIES)?; + if response.status == 404 { + continue; + } + if !(200..300).contains(&response.status) { + return Err(status_error(&response, &allowed)); + } + let root: TrustedRoot = parse_json(&response.body)?; + return verify_trusted_root(root, pin); + } + Err(RemoteError::new( + "TRUSTED_ROOT_MISMATCH", + "skilld.dev serves no trusted root that this build pins", + )) + } + + /// `/api/v1/trusted-roots/{rootKeyId}`, with the id percent-encoded. + fn trusted_root_url(&self, key_id: &str) -> Result { + let mut url = self.service_url("/")?; + url.path_segments_mut() + .map_err(|()| RemoteError::new("INVALID_ENDPOINT", "the API route is invalid"))? + .clear() + .extend(["api", "v1", "trusted-roots", key_id]); + Ok(url.into()) } /// Resolve one source, and request a new Resolution when one fails for a @@ -3678,7 +3763,7 @@ fn unverifiable_artifact(error: RemoteError, source_url: &str) -> RemoteError { "The Skill did not cause this failure. skilld.dev is changing its signing key. Run the same command again in a minute.".to_owned() } "TRUSTED_ROOT_MISMATCH" | "TRUSTED_ROOT_INVALID" | "TRUSTED_ROOT_SIGNATURE_INVALID" => { - "Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to run skilld upgrade, then run the same command again.".to_owned() + "Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to upgrade skilld with npx skilld@latest or npm i -g skilld@latest. Then run the same command again.".to_owned() } "HTTP_TRANSPORT" | "SERVICE_UNAVAILABLE" | "RATE_LIMITED" | "CANCELLED" => return error, _ => format!( @@ -3722,6 +3807,17 @@ struct Problem { instance: Option, } +/// The error for a final response outside 2xx, in the shape its origin uses. +fn status_error(response: &HttpResponse, allowed: &AllowedOrigin) -> RemoteError { + match allowed { + AllowedOrigin::Github | AllowedOrigin::GithubTarball | AllowedOrigin::GithubFile => { + github_error(response) + } + AllowedOrigin::Service(_) | AllowedOrigin::Artifact(_) => problem_error(response), + AllowedOrigin::Api(_) => api::api_problem_error(response), + } +} + fn problem_error(response: &HttpResponse) -> RemoteError { serde_json::from_slice::(&response.body).map_or_else( |_| service_unavailable_error(response), diff --git a/crates/skilld-command/tests/remote.rs b/crates/skilld-command/tests/remote.rs index 6adfa259..6e580b6e 100644 --- a/crates/skilld-command/tests/remote.rs +++ b/crates/skilld-command/tests/remote.rs @@ -24,7 +24,7 @@ use skilld_core::{ InstallRequest, InstallScope, InstallSource, LinkedFile, ListedOrigin, ListedSkill, LockedSource, MultiSkillRef, PreparedFile, RemoteError, RemoteSelector, RepositoryVisibility, ResolvedSource, SearchResponse, SignatureAlgorithm, SourceProvider, SourceStatus, - TrustedRootPin, UpdatePlanItem, UpdatePlanV1, UpdateRelation, + TrustedRootPin, TrustedRootPins, UpdatePlanItem, UpdatePlanV1, UpdateRelation, }; const ROOT_DOMAIN: &[u8] = b"skilld-trusted-key-v1\0"; @@ -2334,7 +2334,7 @@ fn an_unknown_pending_stage_does_not_abort_the_resolution() { let remote = SkilldRemote::new( Arc::new(FakeHttp::with(responses)), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -2532,7 +2532,7 @@ fn a_verified_remote_install_uses_resolution_root_grant_and_content_in_order() { let remote = SkilldRemote::new( http.clone(), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -2549,7 +2549,10 @@ fn a_verified_remote_install_uses_resolution_root_grant_and_content_in_order() { let requests = http.requests.lock().unwrap(); assert_eq!(requests.len(), 4); assert!(requests[0].url.ends_with("/api/v1/resolutions")); - assert!(requests[1].url.ends_with("/api/v1/trusted-root")); + assert_eq!( + requests[1].url, + "http://127.0.0.1:8787/api/v1/trusted-roots/root-1" + ); assert!(requests[2].url.contains("/api/v1/artifacts/")); assert!(requests[2].url.ends_with("/grants")); assert!(requests[2].headers.iter().any(|header| { @@ -2561,13 +2564,13 @@ fn a_verified_remote_install_uses_resolution_root_grant_and_content_in_order() { fn linking_remote( responses: Vec, - pin: TrustedRootPin, + pins: impl Into, ) -> (Arc, SkilldRemote) { let http = Arc::new(FakeHttp::with(responses)); let remote = SkilldRemote::new( http.clone(), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pins.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -2575,6 +2578,210 @@ fn linking_remote( (http, remote) } +/// A pin for a root that the scripted site does not serve. +fn unserved_pin(key_id: &str) -> TrustedRootPin { + TrustedRootPin { + key_id: key_id.to_owned(), + public_key: URL_SAFE_NO_PAD.encode( + SigningKey::from_bytes(&[3_u8; 32]) + .verifying_key() + .to_bytes(), + ), + } +} + +/// What skilld.dev answers for a root id it does not serve. +fn root_not_found() -> HttpResponse { + let mut answer = response( + 404, + serde_json::to_vec(&json!({ + "type": "https://skilld.dev/problems/source-not-found", + "title": "Source not found", + "status": 404, + "detail": "Trusted root not found", + "code": "SOURCE_NOT_FOUND" + })) + .unwrap(), + ); + answer.headers.insert( + "content-type".to_owned(), + "application/problem+json".to_owned(), + ); + answer +} + +#[test] +fn a_primary_root_that_skilld_dev_does_not_serve_falls_back_to_the_backup_root() { + let (backup, mut responses) = verified_remote_responses(); + responses.insert(1, root_not_found()); + let (http, remote) = linking_remote( + responses, + TrustedRootPins::new(unserved_pin("root-2026-11"), Some(backup)), + ); + + let prepared = remote + .prepare( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap(); + + assert!(matches!( + prepared.source_status, + SourceStatus::Verified { .. } + )); + assert_eq!( + request_paths(&http)[1..3], + [ + "/api/v1/trusted-roots/root-2026-11", + "/api/v1/trusted-roots/root-1" + ] + ); +} + +#[test] +fn a_primary_root_failure_other_than_404_never_asks_for_the_backup_root() { + let failures = [ + vec![response(403, b"forbidden".to_vec())], + vec![ + response(503, b"unavailable".to_vec()), + response(503, b"unavailable".to_vec()), + response(503, b"unavailable".to_vec()), + ], + ]; + for failure in failures { + let (backup, mut responses) = verified_remote_responses(); + responses.splice(1..2, failure); + let (http, remote) = linking_remote( + responses, + TrustedRootPins::new(unserved_pin("root-2026-11"), Some(backup)), + ); + + let error = remote + .prepare( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap_err(); + + assert_eq!(error.code, "SERVICE_UNAVAILABLE"); + assert!( + request_paths(&http) + .iter() + .skip(1) + .all(|path| path == "/api/v1/trusted-roots/root-2026-11"), + "{:?}", + request_paths(&http) + ); + } +} + +#[test] +fn a_served_primary_root_that_fails_verification_never_asks_for_the_backup_root() { + let (served, responses) = verified_remote_responses(); + let primary = TrustedRootPin { + public_key: unserved_pin("root-1").public_key, + ..served + }; + let (http, remote) = linking_remote( + responses, + TrustedRootPins::new(primary, Some(unserved_pin("root-backup"))), + ); + + let error = remote + .prepare( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap_err(); + + assert_eq!(error.code, "TRUSTED_ROOT_MISMATCH"); + assert_eq!(request_paths(&http)[1..], ["/api/v1/trusted-roots/root-1"]); +} + +#[test] +fn every_pinned_root_unknown_to_skilld_dev_fails_closed_and_names_the_upgrade() { + let (_, responses) = verified_remote_responses(); + let (http, remote) = linking_remote( + vec![responses[0].clone(), root_not_found(), root_not_found()], + TrustedRootPins::new( + unserved_pin("skilld root/2026"), + Some(unserved_pin("root-backup")), + ), + ); + + let error = remote + .prepare( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap_err(); + + assert_eq!(error.code, "TRUSTED_ROOT_MISMATCH"); + assert_eq!( + error.next_step.as_deref(), + Some( + "Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to upgrade skilld with npx skilld@latest or npm i -g skilld@latest. Then run the same command again." + ) + ); + assert_eq!( + request_paths(&http)[1..], + [ + "/api/v1/trusted-roots/skilld%20root%2F2026", + "/api/v1/trusted-roots/root-backup" + ] + ); +} + +#[test] +fn a_build_pins_its_primary_root_then_its_backup_root() { + let pin = |key_id: &str, public_key: &str| TrustedRootPin { + key_id: key_id.to_owned(), + public_key: public_key.to_owned(), + }; + + assert_eq!( + NativeRemoteConfig::from_build_variables( + Some("root-a"), + Some("key-a"), + Some("root-b"), + Some("key-b") + ), + NativeRemoteConfig::Pinned(TrustedRootPins::new( + pin("root-a", "key-a"), + Some(pin("root-b", "key-b")) + )) + ); + assert_eq!( + NativeRemoteConfig::from_build_variables(Some("root-a"), Some("key-a"), None, Some("")), + NativeRemoteConfig::Pinned(pin("root-a", "key-a").into()) + ); +} + +#[test] +fn a_build_with_part_of_a_root_pin_is_unconfigured() { + let unconfigured = [ + (None, None, None, None), + (Some(""), Some(""), None, None), + (Some("root-a"), None, None, None), + (None, None, Some("root-b"), Some("key-b")), + (Some("root-a"), Some("key-a"), Some("root-b"), None), + (Some("root-a"), Some("key-a"), Some(""), Some("key-b")), + ]; + for (root_key_id, root_public_key, backup_key_id, backup_public_key) in unconfigured { + assert_eq!( + NativeRemoteConfig::from_build_variables( + root_key_id, + root_public_key, + backup_key_id, + backup_public_key + ), + NativeRemoteConfig::Unconfigured, + "{root_key_id:?} {root_public_key:?} {backup_key_id:?} {backup_public_key:?}" + ); + } +} + #[test] fn a_resolution_request_says_this_cli_reads_linked_files() { let (pin, responses) = verified_remote_responses(); @@ -2654,7 +2861,7 @@ fn prepared_with_page_header(header: Option<&str>) -> Option { let remote = SkilldRemote::new( Arc::new(FakeHttp::with(responses)), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -2746,7 +2953,7 @@ fn a_public_grant_may_serve_content_from_a_service_subdomain() { let remote = SkilldRemote::new( http.clone(), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("https://skilld.dev") .unwrap() @@ -2796,7 +3003,7 @@ fn artifact_download_errors_preserve_problem_details_and_http_fallbacks() { let remote = SkilldRemote::new( Arc::new(FakeHttp::with(responses)), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("https://skilld.dev") .unwrap() @@ -2820,7 +3027,7 @@ fn a_public_grant_on_an_unrelated_origin_is_rejected_before_download() { let remote = SkilldRemote::new( http.clone(), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("https://skilld.dev") .unwrap() @@ -2853,7 +3060,7 @@ fn a_private_grant_refuses_public_access_without_an_account() { let remote = SkilldRemote::new( Arc::new(FakeHttp::with(responses)), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("https://skilld.dev") .unwrap() @@ -2889,7 +3096,7 @@ fn a_private_artifact_download_sends_the_account_and_one_time_grant() { let remote = SkilldRemote::new( http.clone(), Arc::new(FixedToken), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -3097,7 +3304,7 @@ fn prepare_exact_keeps_a_matching_selector_commit_as_provenance() { let remote = SkilldRemote::new( http.clone(), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() @@ -5082,7 +5289,7 @@ fn pinned_remote( SkilldRemote::new( http, Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(pin), + NativeRemoteConfig::Pinned(pin.into()), ) .with_endpoint("http://127.0.0.1:8787") .unwrap() diff --git a/crates/skilld-core/src/lib.rs b/crates/skilld-core/src/lib.rs index 4671cd3c..62c638e9 100644 --- a/crates/skilld-core/src/lib.rs +++ b/crates/skilld-core/src/lib.rs @@ -28,9 +28,9 @@ pub use remote::{ MAX_LINKED_BYTES, PreparedFile, RemoteError, RemoteSelector, RepositoryVisibility, ResolvedSource, SearchResponse, SearchResult, SignatureAlgorithm, SourceProvider, SourceRef, SourceRequest, SourceSelector, TrustedKey, TrustedKeyStatus, TrustedRoot, TrustedRootPin, - VerifiedArtifact, VerifiedTrustedRoot, declared_skill_name, parse_search_response, - prepare_unverified_files, skill_identity, verify_artifact, verify_attestation, - verify_linked_file, verify_trusted_root, with_linked_files, + TrustedRootPins, VerifiedArtifact, VerifiedTrustedRoot, declared_skill_name, + parse_search_response, prepare_unverified_files, skill_identity, verify_artifact, + verify_attestation, verify_linked_file, verify_trusted_root, with_linked_files, }; use serde::{Deserialize, Serialize}; pub use target::{ diff --git a/crates/skilld-core/src/remote.rs b/crates/skilld-core/src/remote.rs index 310be416..a6d0bd5e 100644 --- a/crates/skilld-core/src/remote.rs +++ b/crates/skilld-core/src/remote.rs @@ -609,6 +609,33 @@ pub struct TrustedRootPin { pub public_key: String, } +/// The trusted roots one skilld build pins, in the order skilld asks for them. +/// +/// The primary root comes first. A backup root follows it only if the build +/// pins one, so no build pins a backup without a primary. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct TrustedRootPins { + primary: TrustedRootPin, + backup: Option, +} + +impl TrustedRootPins { + pub const fn new(primary: TrustedRootPin, backup: Option) -> Self { + Self { primary, backup } + } + + /// The primary pin, then the backup pin. + pub fn iter(&self) -> impl Iterator { + std::iter::once(&self.primary).chain(self.backup.as_ref()) + } +} + +impl From for TrustedRootPins { + fn from(primary: TrustedRootPin) -> Self { + Self::new(primary, None) + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub struct VerifiedTrustedRoot(TrustedRoot); diff --git a/crates/skilld-native/src/main.rs b/crates/skilld-native/src/main.rs index 5cef1199..a896a11f 100644 --- a/crates/skilld-native/src/main.rs +++ b/crates/skilld-native/src/main.rs @@ -20,7 +20,7 @@ use skilld_command::{ }; use skilld_core::{ InstallScope, InstallSource, ReleasePin, SearchResponse, SearchResult, SourceProvider, - SourceRequest, SourceSelector, TrustedRootPin, VERSION, + SourceRequest, SourceSelector, VERSION, }; use skilld_native::behavior_prompt::TtyBehaviorConfirmer; use skilld_native::select_ui::TtySkillChooser; @@ -573,16 +573,12 @@ impl Host for SearchOutputProbe { } fn native_remote_config() -> NativeRemoteConfig { - match ( + NativeRemoteConfig::from_build_variables( option_env!("SKILLD_ROOT_KEY_ID"), option_env!("SKILLD_ROOT_PUBLIC_KEY"), - ) { - (Some(key_id), Some(public_key)) => NativeRemoteConfig::Pinned(TrustedRootPin { - key_id: key_id.to_owned(), - public_key: public_key.to_owned(), - }), - _ => NativeRemoteConfig::Unconfigured, - } + option_env!("SKILLD_BACKUP_ROOT_KEY_ID"), + option_env!("SKILLD_BACKUP_ROOT_PUBLIC_KEY"), + ) } fn target_roots() -> TargetRoots { diff --git a/crates/skilld-native/tests/run_flow.rs b/crates/skilld-native/tests/run_flow.rs index 8fd449f3..7b8be2e2 100644 --- a/crates/skilld-native/tests/run_flow.rs +++ b/crates/skilld-native/tests/run_flow.rs @@ -13,7 +13,7 @@ use ed25519_dalek::{Signer as _, SigningKey}; use serde_json::json; use sha2::{Digest as _, Sha256}; use skilld_command::{NativeRemoteConfig, NoTokenProvider, RemoteProvider, SkilldRemote}; -use skilld_core::{RemoteSelector, SourceStatus, TrustedRootPin}; +use skilld_core::{RemoteSelector, SourceStatus, TrustedRootPin, TrustedRootPins}; use skilld_native::NativeHttpAdapter; const RESOLUTION_ID: &str = "018f47a4-2d38-7c5f-8d3e-1c5a6b7d8e9f"; @@ -307,7 +307,7 @@ fn a_run_survives_a_bad_gateway_a_pending_answer_and_a_dropped_download() { 200, site.ready.clone(), ), - answer("GET /api/v1/trusted-root", 200, site.root.clone()), + answer("GET /api/v1/trusted-roots/root-1 ", 200, site.root.clone()), answer("POST /api/v1/artifacts/sha256%3A", 200, site.grant.clone()), dropped, answer("GET /content", 200, site.archive.clone()), @@ -316,7 +316,7 @@ fn a_run_survives_a_bad_gateway_a_pending_answer_and_a_dropped_download() { let remote = SkilldRemote::new( Arc::new(NativeHttpAdapter::new()), Arc::new(NoTokenProvider), - NativeRemoteConfig::Pinned(site.pin), + NativeRemoteConfig::Pinned(site.pin.into()), ) .with_endpoint(&format!("http://{address}")) .unwrap(); @@ -336,3 +336,53 @@ fn a_run_survives_a_bad_gateway_a_pending_answer_and_a_dropped_download() { assert_eq!(prepared.omitted_files[0].path, "assets/demo.mp4"); assert_eq!(prepared.omitted_files[0].bytes, Some(9_311_232)); } + +#[test] +fn a_run_verifies_with_the_backup_root_when_skilld_dev_does_not_serve_the_primary() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let site = site(&format!("http://{address}/content")); + let not_found = serde_json::to_vec(&json!({ + "type": "https://skilld.dev/problems/source-not-found", + "title": "Source not found", + "status": 404, + "detail": "Trusted root not found", + "code": "SOURCE_NOT_FOUND" + })) + .unwrap(); + let server = serve( + listener, + vec![ + answer("POST /api/v1/resolutions", 200, site.ready.clone()), + answer("GET /api/v1/trusted-roots/root-2026-11 ", 404, not_found), + answer("GET /api/v1/trusted-roots/root-1 ", 200, site.root.clone()), + answer("POST /api/v1/artifacts/sha256%3A", 200, site.grant.clone()), + answer("GET /content", 200, site.archive.clone()), + ], + ); + let primary = TrustedRootPin { + key_id: "root-2026-11".to_owned(), + public_key: URL_SAFE_NO_PAD.encode( + SigningKey::from_bytes(&[3_u8; 32]) + .verifying_key() + .to_bytes(), + ), + }; + let remote = SkilldRemote::new( + Arc::new(NativeHttpAdapter::new()), + Arc::new(NoTokenProvider), + NativeRemoteConfig::Pinned(TrustedRootPins::new(primary, Some(site.pin))), + ) + .with_endpoint(&format!("http://{address}")) + .unwrap(); + let selector = RemoteSelector::parse("better-auth/skills/emailandpassword").unwrap(); + + let prepared = remote.prepare(&selector, false); + + let lines = server.join().unwrap(); + assert!(matches!( + prepared.unwrap().source_status, + SourceStatus::Verified { .. } + )); + assert_eq!(lines.len(), 5); +} diff --git a/docs/migrate-v2-to-v3.md b/docs/migrate-v2-to-v3.md index 2de59840..f2c65b4b 100644 --- a/docs/migrate-v2-to-v3.md +++ b/docs/migrate-v2-to-v3.md @@ -179,9 +179,19 @@ Set these GitHub Actions repository variables before creating a v3 tag: - `SKILLD_ROOT_KEY_ID` - `SKILLD_ROOT_PUBLIC_KEY` +- `SKILLD_BACKUP_ROOT_KEY_ID` +- `SKILLD_BACKUP_ROOT_PUBLIC_KEY` -The public key must be the pinned Ed25519 root public key in canonical base64url form. -Keep the root private key outside this repository and GitHub Actions. +Each public key must be a pinned Ed25519 root public key in canonical base64url form. +The backup root needs its own key id and its own key pair. +Keep each root private key outside this repository and GitHub Actions. + +The CLI asks skilld.dev for the primary root at `/api/v1/trusted-roots/{rootKeyId}`. +If skilld.dev answers 404, the CLI asks for the backup root. +Any other failure stops verification. + +The release stops before it builds if skilld.dev does not serve the primary root. +The served `rootKeyId` and `rootPublicKey` must equal the primary variables. The release tag must match the root `package.json` version exactly. The CLI, native packages, and Harness use that same version. diff --git a/packages/protocol/openapi/skilld-v1.yaml b/packages/protocol/openapi/skilld-v1.yaml index 23292cc9..5a9de0b3 100644 --- a/packages/protocol/openapi/skilld-v1.yaml +++ b/packages/protocol/openapi/skilld-v1.yaml @@ -196,6 +196,9 @@ paths: operationId: getTrustedRoot tags: [Trust] summary: Get attestation verification keys + description: >- + The root that skilld CLI releases before 3.7.0 pin. Later releases + read `/api/v1/trusted-roots/{rootKeyId}`. security: - {} responses: @@ -209,6 +212,38 @@ paths: $ref: '#/components/responses/Problem' '503': $ref: '#/components/responses/Problem' + /api/v1/trusted-roots/{rootKeyId}: + get: + operationId: getTrustedRootByKeyId + tags: [Trust] + summary: Get the attestation verification keys of one root + description: >- + The CLI asks for each root it pins by its id, in pin order. A 404 means + the service does not serve that root, and the CLI asks for the next + pinned root. + security: + - {} + parameters: + - name: rootKeyId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 100 + responses: + '200': + description: Active and overlapping verification keys that this root signed. + content: + application/json: + schema: + $ref: '#/components/schemas/TrustedRoot' + '404': + $ref: '#/components/responses/Problem' + '429': + $ref: '#/components/responses/Problem' + '503': + $ref: '#/components/responses/Problem' components: securitySchemes: bearerAuth: diff --git a/packages/protocol/src/generated/skilld-v1.ts b/packages/protocol/src/generated/skilld-v1.ts index 5625077b..6fb03e6b 100644 --- a/packages/protocol/src/generated/skilld-v1.ts +++ b/packages/protocol/src/generated/skilld-v1.ts @@ -96,7 +96,10 @@ export interface paths { path?: never; cookie?: never; }; - /** Get attestation verification keys */ + /** + * Get attestation verification keys + * @description The root that skilld CLI releases before 3.7.0 pin. Later releases read `/api/v1/trusted-roots/{rootKeyId}`. + */ get: operations["getTrustedRoot"]; put?: never; post?: never; @@ -106,6 +109,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/trusted-roots/{rootKeyId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get the attestation verification keys of one root + * @description The CLI asks for each root it pins by its id, in pin order. A 404 means the service does not serve that root, and the CLI asks for the next pinned root. + */ + get: operations["getTrustedRootByKeyId"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -578,4 +601,29 @@ export interface operations { 503: components["responses"]["Problem"]; }; }; + getTrustedRootByKeyId: { + parameters: { + query?: never; + header?: never; + path: { + rootKeyId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Active and overlapping verification keys that this root signed. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["TrustedRoot"]; + }; + }; + 404: components["responses"]["Problem"]; + 429: components["responses"]["Problem"]; + 503: components["responses"]["Problem"]; + }; + }; } From 416f5d780b110967223c6279614dddf2a65b4dac Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 18 Nov 2026 23:47:52 +1100 Subject: [PATCH 2/7] test(cli): prove an unreadable primary root never reaches the backup Only a 404 may move verification to the backup pin. These cases cover a served root for the wrong pin, invalid JSON, a transport failure, and a rejected redirect at the primary path. --- crates/skilld-command/tests/remote.rs | 66 +++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/crates/skilld-command/tests/remote.rs b/crates/skilld-command/tests/remote.rs index 6e580b6e..44ade7f5 100644 --- a/crates/skilld-command/tests/remote.rs +++ b/crates/skilld-command/tests/remote.rs @@ -2699,6 +2699,72 @@ fn a_served_primary_root_that_fails_verification_never_asks_for_the_backup_root( assert_eq!(request_paths(&http)[1..], ["/api/v1/trusted-roots/root-1"]); } +#[test] +fn a_primary_root_that_cannot_be_read_or_verified_never_asks_for_the_backup_root() { + let (backup, responses) = verified_remote_responses(); + let (ready, backup_root) = (responses[0].clone(), responses[1].clone()); + let transport = || { + Err(RemoteError::new( + "HTTP_TRANSPORT", + "the connection was reset", + )) + }; + let mut redirect = response(302, Vec::new()); + redirect.headers.insert( + "location".to_owned(), + "https://elsewhere.example/api/v1/trusted-roots/root-2026-11".to_owned(), + ); + let cases = [ + // skilld.dev serves the backup root at the primary path. + ("TRUSTED_ROOT_MISMATCH", vec![Ok(backup_root.clone())]), + ( + "INVALID_RESPONSE", + vec![Ok(response(200, b"not json".to_vec()))], + ), + ( + "HTTP_TRANSPORT", + vec![transport(), transport(), transport()], + ), + ("REMOTE_ORIGIN_REJECTED", vec![Ok(redirect)]), + ]; + for (code, primary) in cases { + // The backup root stays queued, so a fall through would verify. + let queue = std::iter::once(Ok(ready.clone())) + .chain(primary) + .chain([Ok(backup_root.clone())]) + .collect(); + let http = Arc::new(FakeHttp { + responses: Mutex::new(queue), + ..FakeHttp::default() + }); + let remote = SkilldRemote::new( + http.clone(), + Arc::new(NoTokenProvider), + NativeRemoteConfig::Pinned(TrustedRootPins::new( + unserved_pin("root-2026-11"), + Some(backup.clone()), + )), + ) + .with_endpoint("http://127.0.0.1:8787") + .unwrap() + .with_sleeper(Arc::new(NoSleep)); + + let error = remote + .prepare( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap_err(); + + assert_eq!(error.code, code); + assert!( + !request_paths(&http).contains(&"/api/v1/trusted-roots/root-1".to_owned()), + "{code}: {:?}", + request_paths(&http) + ); + } +} + #[test] fn every_pinned_root_unknown_to_skilld_dev_fails_closed_and_names_the_upgrade() { let (_, responses) = verified_remote_responses(); From 37816b0f4fdafcaba5cb030956d1a6269e7ee7ca Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 18 Nov 2026 23:47:52 +1100 Subject: [PATCH 3/7] fix(cli): name the upgrade when an update check distrusts roots Update checks verify the trusted root too, but only skilld run and install added the upgrade step to a TRUSTED_ROOT_* failure. --- crates/skilld-command/src/remote.rs | 25 ++++++++++++++++++++----- crates/skilld-command/tests/remote.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/skilld-command/src/remote.rs b/crates/skilld-command/src/remote.rs index 66d4ddba..a83baf68 100644 --- a/crates/skilld-command/src/remote.rs +++ b/crates/skilld-command/src/remote.rs @@ -3116,8 +3116,8 @@ impl RemoteProvider for SkilldRemote { commit_sha: &str, ) -> Result { let descriptor = self.resolve(selector.source())?.descriptor; - let root = self.verified_root()?; - verify_attestation(&descriptor.attestation, &root)?; + let root = self.verified_root().map_err(untrusted_root)?; + verify_attestation(&descriptor.attestation, &root).map_err(untrusted_root)?; if descriptor.artifact_id == artifact_id && descriptor.attestation.source.commit_sha == commit_sha { @@ -3146,8 +3146,8 @@ impl RemoteProvider for SkilldRemote { }); } let descriptor = self.resolve(selector.source())?.descriptor; - let root = self.verified_root()?; - verify_attestation(&descriptor.attestation, &root)?; + let root = self.verified_root().map_err(untrusted_root)?; + verify_attestation(&descriptor.attestation, &root).map_err(untrusted_root)?; let access = match descriptor.visibility { RepositoryVisibility::Public => RemoteComparisonAccess::PublicGithub, RepositoryVisibility::Private => RemoteComparisonAccess::Hosted, @@ -3763,7 +3763,7 @@ fn unverifiable_artifact(error: RemoteError, source_url: &str) -> RemoteError { "The Skill did not cause this failure. skilld.dev is changing its signing key. Run the same command again in a minute.".to_owned() } "TRUSTED_ROOT_MISMATCH" | "TRUSTED_ROOT_INVALID" | "TRUSTED_ROOT_SIGNATURE_INVALID" => { - "Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to upgrade skilld with npx skilld@latest or npm i -g skilld@latest. Then run the same command again.".to_owned() + return untrusted_root(error); } "HTTP_TRANSPORT" | "SERVICE_UNAVAILABLE" | "RATE_LIMITED" | "CANCELLED" => return error, _ => format!( @@ -3773,6 +3773,21 @@ fn unverifiable_artifact(error: RemoteError, source_url: &str) -> RemoteError { error.with_next_step(next_step) } +/// Add the upgrade step to a failure that means this build does not trust +/// the skilld.dev keys. Every other failure passes through unchanged. +fn untrusted_root(error: RemoteError) -> RemoteError { + match error.code { + "TRUSTED_ROOT_MISMATCH" | "TRUSTED_ROOT_INVALID" | "TRUSTED_ROOT_SIGNATURE_INVALID" + if error.next_step.is_none() => + { + error.with_next_step( + "Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to upgrade skilld with npx skilld@latest or npm i -g skilld@latest. Then run the same command again.", + ) + } + _ => error, + } +} + fn is_transfer_mismatch(code: &str) -> bool { matches!(code, "ARTIFACT_SIZE_MISMATCH" | "ARTIFACT_DIGEST_MISMATCH") } diff --git a/crates/skilld-command/tests/remote.rs b/crates/skilld-command/tests/remote.rs index 44ade7f5..273673bb 100644 --- a/crates/skilld-command/tests/remote.rs +++ b/crates/skilld-command/tests/remote.rs @@ -2799,6 +2799,32 @@ fn every_pinned_root_unknown_to_skilld_dev_fails_closed_and_names_the_upgrade() ); } +#[test] +fn an_update_check_that_trusts_no_served_root_names_the_upgrade() { + let (_, responses) = verified_remote_responses(); + let (_, remote) = linking_remote( + vec![responses[0].clone(), root_not_found()], + unserved_pin("root-2026-11"), + ); + + let error = remote + .latest_commit( + &RemoteSelector::parse("skilld-dev/skills/example").unwrap(), + false, + ) + .unwrap_err(); + + assert_eq!(error.code, "TRUSTED_ROOT_MISMATCH"); + assert!( + error + .next_step + .as_deref() + .is_some_and(|step| step.contains("npx skilld@latest")), + "{:?}", + error.next_step + ); +} + #[test] fn a_build_pins_its_primary_root_then_its_backup_root() { let pin = |key_id: &str, public_key: &str| TrustedRootPin { From 8b4a829bc39338fb011b1d1bfe5d5db85eb1b1ca Mon Sep 17 00:00:00 2001 From: Harlan Wilton Date: Wed, 18 Nov 2026 23:47:52 +1100 Subject: [PATCH 4/7] ci(release): validate and require both served trusted roots The guard checked only the primary root, so a wrong backup value could ship unnoticed. It now checks each id and key format, rejects the lost skilld-root-2026, and requires skilld.dev to serve both roots without a redirect. --- .github/workflows/release.yml | 89 +++++++++++++++++++++-------------- docs/migrate-v2-to-v3.md | 9 ++-- 2 files changed, 60 insertions(+), 38 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 154f8b0a..cf55b83b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,27 +28,35 @@ jobs: - uses: actions/setup-node@v7 with: node-version: lts/* - - name: Require the trusted root + - name: Require the trusted roots shell: bash run: | - test -n "$SKILLD_ROOT_KEY_ID" || { - echo 'SKILLD_ROOT_KEY_ID is required.' >&2 - exit 1 - } - test -n "$SKILLD_ROOT_PUBLIC_KEY" || { - echo 'SKILLD_ROOT_PUBLIC_KEY is required.' >&2 - exit 1 - } - test -n "$SKILLD_BACKUP_ROOT_KEY_ID" || { - echo 'SKILLD_BACKUP_ROOT_KEY_ID is required.' >&2 - exit 1 - } - test -n "$SKILLD_BACKUP_ROOT_PUBLIC_KEY" || { - echo 'SKILLD_BACKUP_ROOT_PUBLIC_KEY is required.' >&2 - exit 1 - } - if test "$SKILLD_BACKUP_ROOT_KEY_ID" = "$SKILLD_ROOT_KEY_ID" \ - || test "$SKILLD_BACKUP_ROOT_PUBLIC_KEY" = "$SKILLD_ROOT_PUBLIC_KEY"; then + # Root key ids use only unreserved URL characters, so a URL path + # holds them without encoding. + id_pattern='^[A-Za-z0-9._~-]{1,100}$' + # 32 bytes in canonical unpadded base64url: 43 characters, and the + # last one leaves its two padding bits unset. + key_pattern='^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$' + for root in SKILLD_ROOT SKILLD_BACKUP_ROOT; do + key_id_name="${root}_KEY_ID" + public_key_name="${root}_PUBLIC_KEY" + key_id="${!key_id_name}" + public_key="${!public_key_name}" + if [[ ! $key_id =~ $id_pattern || $key_id == . || $key_id == .. ]]; then + echo "$key_id_name must be 1 to 100 characters from A-Z, a-z, 0-9, '.', '_', '~', and '-'." >&2 + exit 1 + fi + if [[ $key_id == skilld-root-2026 ]]; then + echo "$key_id_name names skilld-root-2026. Its private key is lost." >&2 + exit 1 + fi + if [[ ! $public_key =~ $key_pattern ]]; then + echo "$public_key_name must be a 32-byte Ed25519 public key in canonical unpadded base64url." >&2 + exit 1 + fi + done + if [[ $SKILLD_BACKUP_ROOT_KEY_ID == "$SKILLD_ROOT_KEY_ID" \ + || $SKILLD_BACKUP_ROOT_PUBLIC_KEY == "$SKILLD_ROOT_PUBLIC_KEY" ]]; then echo 'The backup root must have its own key id and public key.' >&2 exit 1 fi @@ -56,25 +64,36 @@ jobs: echo 'SKILLD_RELEASE_PUBLIC_KEY is required. Run node scripts/release/release-signing.mjs generate-key.' >&2 exit 1 } - - name: Require skilld.dev to serve the primary root + - name: Require skilld.dev to serve both pinned roots shell: bash run: | - # The CLI asks for its primary root first. If skilld.dev does not - # serve it, the released CLI depends on the backup root alone. - key_id="$(jq -rn --arg value "$SKILLD_ROOT_KEY_ID" '$value | @uri')" - root="$(curl --fail --silent --show-error --location \ - --proto '=https' --proto-redir '=https' --retry 3 --max-time 30 \ - "https://skilld.dev/api/v1/trusted-roots/$key_id")" || { - echo "skilld.dev does not serve the trusted root $SKILLD_ROOT_KEY_ID." >&2 - exit 1 - } - printf '%s' "$root" | jq -e \ - --arg key_id "$SKILLD_ROOT_KEY_ID" \ - --arg public_key "$SKILLD_ROOT_PUBLIC_KEY" \ - '.rootKeyId == $key_id and .rootPublicKey == $public_key' >/dev/null || { - echo "The skilld.dev trusted root $SKILLD_ROOT_KEY_ID does not match SKILLD_ROOT_PUBLIC_KEY." >&2 - exit 1 + # The CLI asks for each pinned root by its id. A root that skilld.dev + # does not serve leaves the release with one root or none. + require_served_root() { + local key_id_name="$1" public_key_name="$2" + local key_id="${!key_id_name}" public_key="${!public_key_name}" + local body status + body="$(mktemp)" + # No --location: a redirect fails this check. + status="$(curl --fail --silent --show-error --proto '=https' \ + --retry 3 --max-time 30 --output "$body" --write-out '%{http_code}' \ + "https://skilld.dev/api/v1/trusted-roots/$key_id")" || { + echo "skilld.dev does not serve the trusted root $key_id from $key_id_name." >&2 + exit 1 + } + if [[ $status != 200 ]]; then + echo "skilld.dev answered HTTP $status for the trusted root $key_id from $key_id_name." >&2 + exit 1 + fi + jq -e --arg key_id "$key_id" --arg public_key "$public_key" \ + '.version == 1 and .rootKeyId == $key_id and .rootPublicKey == $public_key + and (.keys | type == "array" and length > 0)' "$body" >/dev/null || { + echo "The skilld.dev trusted root $key_id does not match $key_id_name and $public_key_name, or lists no keys." >&2 + exit 1 + } } + require_served_root SKILLD_ROOT_KEY_ID SKILLD_ROOT_PUBLIC_KEY + require_served_root SKILLD_BACKUP_ROOT_KEY_ID SKILLD_BACKUP_ROOT_PUBLIC_KEY - id: matrix name: Read native package matrix shell: bash diff --git a/docs/migrate-v2-to-v3.md b/docs/migrate-v2-to-v3.md index f2c65b4b..e0eccc7f 100644 --- a/docs/migrate-v2-to-v3.md +++ b/docs/migrate-v2-to-v3.md @@ -182,7 +182,9 @@ Set these GitHub Actions repository variables before creating a v3 tag: - `SKILLD_BACKUP_ROOT_KEY_ID` - `SKILLD_BACKUP_ROOT_PUBLIC_KEY` -Each public key must be a pinned Ed25519 root public key in canonical base64url form. +Each key id has 1 to 100 characters from `A-Z`, `a-z`, `0-9`, `.`, `_`, `~`, and `-`. +Neither key id may be `skilld-root-2026`, whose private key is lost. +Each public key must be a 32-byte Ed25519 root public key in canonical unpadded base64url. The backup root needs its own key id and its own key pair. Keep each root private key outside this repository and GitHub Actions. @@ -190,8 +192,9 @@ The CLI asks skilld.dev for the primary root at `/api/v1/trusted-roots/{rootKeyI If skilld.dev answers 404, the CLI asks for the backup root. Any other failure stops verification. -The release stops before it builds if skilld.dev does not serve the primary root. -The served `rootKeyId` and `rootPublicKey` must equal the primary variables. +The release stops before it builds unless skilld.dev serves both roots. +Each served root must have `version` 1, at least one key, and the `rootKeyId` and `rootPublicKey` of its variables. +A redirect also stops the release. The release tag must match the root `package.json` version exactly. The CLI, native packages, and Harness use that same version. From 02e203b510abd37096b3a47a99353507f2838b9f Mon Sep 17 00:00:00 2001 From: Harlan GitHub Agent Date: Thu, 19 Nov 2026 01:00:45 +1100 Subject: [PATCH 5/7] fix(release): verify both pinned root signatures before builds --- .github/workflows/release.yml | 13 +-- .../examples/verify-release-root.rs | 15 +++ tests/loader/trusted-root-preflight.test.ts | 91 +++++++++++++++++++ 3 files changed, 111 insertions(+), 8 deletions(-) create mode 100644 crates/skilld-core/examples/verify-release-root.rs create mode 100644 tests/loader/trusted-root-preflight.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf55b83b..119f2e79 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -69,11 +69,12 @@ jobs: run: | # The CLI asks for each pinned root by its id. A root that skilld.dev # does not serve leaves the release with one root or none. - require_served_root() { + require_served_root() ( local key_id_name="$1" public_key_name="$2" local key_id="${!key_id_name}" public_key="${!public_key_name}" local body status body="$(mktemp)" + trap 'rm -f "$body"' EXIT # No --location: a redirect fails this check. status="$(curl --fail --silent --show-error --proto '=https' \ --retry 3 --max-time 30 --output "$body" --write-out '%{http_code}' \ @@ -85,13 +86,9 @@ jobs: echo "skilld.dev answered HTTP $status for the trusted root $key_id from $key_id_name." >&2 exit 1 fi - jq -e --arg key_id "$key_id" --arg public_key "$public_key" \ - '.version == 1 and .rootKeyId == $key_id and .rootPublicKey == $public_key - and (.keys | type == "array" and length > 0)' "$body" >/dev/null || { - echo "The skilld.dev trusted root $key_id does not match $key_id_name and $public_key_name, or lists no keys." >&2 - exit 1 - } - } + cargo run --locked --quiet --package skilld-core --example verify-release-root \ + -- "$body" "$key_id" "$public_key" + ) require_served_root SKILLD_ROOT_KEY_ID SKILLD_ROOT_PUBLIC_KEY require_served_root SKILLD_BACKUP_ROOT_KEY_ID SKILLD_BACKUP_ROOT_PUBLIC_KEY - id: matrix diff --git a/crates/skilld-core/examples/verify-release-root.rs b/crates/skilld-core/examples/verify-release-root.rs new file mode 100644 index 00000000..b52b6390 --- /dev/null +++ b/crates/skilld-core/examples/verify-release-root.rs @@ -0,0 +1,15 @@ +use skilld_core::{TrustedRoot, TrustedRootPin, verify_trusted_root}; +use std::{env, error::Error, fs}; + +// Release preflight uses the same wire type and verifier as hosted CLI operations. +fn main() -> Result<(), Box> { + let mut args = env::args().skip(1); + let path = args.next().ok_or("trusted root document is required")?; + let pin = TrustedRootPin { + key_id: args.next().ok_or("root key id is required")?, + public_key: args.next().ok_or("root public key is required")?, + }; + let root: TrustedRoot = serde_json::from_slice(&fs::read(path)?)?; + verify_trusted_root(root, &pin)?; + Ok(()) +} diff --git a/tests/loader/trusted-root-preflight.test.ts b/tests/loader/trusted-root-preflight.test.ts new file mode 100644 index 00000000..a7c00eed --- /dev/null +++ b/tests/loader/trusted-root-preflight.test.ts @@ -0,0 +1,91 @@ +import { spawnSync } from 'node:child_process' +import { createHash, generateKeyPairSync, sign } from 'node:crypto' +import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { parse } from 'yaml' + +function rootFixture(rootKeyId: string) { + const { publicKey, privateKey } = generateKeyPairSync('ed25519') + const rootPublicKey = publicKey.export({ format: 'jwk' }).x! + const key = { + keyId: 'signer-1', + algorithm: 'Ed25519', + publicKey: rootPublicKey, + notBefore: '2026-01-01T00:00:00.000Z', + notAfter: '2027-01-01T00:00:00.000Z', + status: 'active', + } + const statement = Buffer.from(JSON.stringify({ version: 1, rootKeyId, ...key })) + const message = Buffer.concat([ + Buffer.from('skilld-trusted-key-v1\0'), + createHash('sha256').update(statement).digest(), + ]) + return { + version: 1, + rootKeyId, + rootPublicKey, + fetchedAt: '2026-11-18T00:00:00.000Z', + keys: [{ + ...key, + statement: statement.toString('base64url'), + rootSignature: sign(null, message, privateKey).toString('base64url'), + }], + } +} + +it('stops release preflight for an invalid signature on either pin and accepts valid roots', () => { + const directory = mkdtempSync(join(tmpdir(), 'skilld-root-preflight-')) + try { + const workflow = parse(readFileSync('.github/workflows/release.yml', 'utf8')) + const step = workflow.jobs['release-plan'].steps.find( + (step: { name?: string }) => step.name === 'Require skilld.dev to serve both pinned roots', + ) + const primary = rootFixture('primary-root') + const backup = rootFixture('backup-root') + const fixtures = [primary, backup] + // Replace only the HTTP boundary. Run the real workflow gate and verifier. + writeFileSync(join(directory, 'curl.ts'), `#!/usr/bin/env -S node --experimental-strip-types +import { copyFileSync } from 'node:fs' +import { join } from 'node:path' +const args = process.argv.slice(2) +const id = new URL(args.at(-1)!).pathname.split('/').at(-1)! +copyFileSync(join(process.env.ROOT_FIXTURES!, id + '.json'), args[args.indexOf('--output') + 1]!) +process.stdout.write('200') +`, { mode: 0o755 }) + symlinkSync('curl.ts', join(directory, 'curl')) + const run = () => spawnSync('bash', ['-e', '-c', `${step.run}\nprintf 'native-build-reached'`], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH}`, + ROOT_FIXTURES: directory, + SKILLD_ROOT_KEY_ID: primary.rootKeyId, + SKILLD_ROOT_PUBLIC_KEY: primary.rootPublicKey, + SKILLD_BACKUP_ROOT_KEY_ID: backup.rootKeyId, + SKILLD_BACKUP_ROOT_PUBLIC_KEY: backup.rootPublicKey, + }, + }) + for (const fixture of fixtures) + writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) + + for (const fixture of fixtures) { + const validSignature = fixture.keys[0]!.rootSignature + fixture.keys[0]!.rootSignature = Buffer.alloc(64).toString('base64url') + writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) + const invalid = run() + expect(invalid.status, invalid.stderr).not.toBe(0) + expect(invalid.stdout).not.toContain('native-build-reached') + expect(invalid.stderr).toContain('TRUSTED_ROOT_SIGNATURE_INVALID') + fixture.keys[0]!.rootSignature = validSignature + writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) + } + const valid = run() + expect(valid.status, valid.stderr).toBe(0) + expect(valid.stdout).toContain('native-build-reached') + } + finally { + rmSync(directory, { recursive: true, force: true }) + } +}, 120_000) From 767d3c2557772a625c868feb847f20b7a355d35c Mon Sep 17 00:00:00 2001 From: Harlan GitHub Agent Date: Thu, 19 Nov 2026 01:13:39 +1100 Subject: [PATCH 6/7] fix(release): verify service attestation against both roots --- .github/workflows/release.yml | 37 +++- .../examples/verify-release-root.rs | 9 +- docs/migrate-v2-to-v3.md | 10 + tests/loader/trusted-root-preflight.test.ts | 179 ++++++++++++++---- 4 files changed, 197 insertions(+), 38 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 119f2e79..085c1da3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -65,8 +65,43 @@ jobs: exit 1 } - name: Require skilld.dev to serve both pinned roots + timeout-minutes: 5 shell: bash run: | + probe="$(mktemp -d)" + trap 'rm -rf "$probe"' EXIT + # Resolve this release's public Skill through the deployed service. + # Both roots must verify the same attestation before any native build. + jq -n --arg commit "$GITHUB_SHA" \ + '{source: {provider: "github", owner: "skilld-dev", repository: "skilld", + selector: {type: "path", path: "skills/skilld"}, ref: {type: "commit", value: $commit}}}' \ + > "$probe/request.json" + status="$(curl --fail --silent --show-error --proto '=https' --max-time 30 \ + --output "$probe/resolution.json" --write-out '%{http_code}' \ + --header 'Content-Type: application/json' --header 'Skilld-Capabilities: linked-files' \ + --header "Idempotency-Key: release-$GITHUB_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" \ + --data-binary "@$probe/request.json" 'https://skilld.dev/api/v1/resolutions')" + [[ $status == 200 || $status == 202 ]] + resolution_id="$(jq -er '.resolutionId | select(test("^[A-Za-z0-9_-]{1,100}$"))' "$probe/resolution.json")" + for attempt in {1..60}; do + state="$(jq -er --arg id "$resolution_id" 'select(.resolutionId == $id) | .state' "$probe/resolution.json")" + if [[ $state == ready ]]; then + break + fi + [[ $state == pending ]] + sleep 2 + status="$(curl --fail --silent --show-error --proto '=https' --max-time 30 \ + --output "$probe/resolution.json" --write-out '%{http_code}' \ + "https://skilld.dev/api/v1/resolutions/$resolution_id")" + [[ $status == 200 ]] + done + jq -e --arg commit "$GITHUB_SHA" --arg id "$resolution_id" \ + 'select(.state == "ready" and .resolutionId == $id) + | .artifact | select(.visibility == "public" and .artifactId == .attestation.artifactId) + | .attestation | select(.source.owner == "skilld-dev" and .source.repository == "skilld" + and .source.skillPath == "skills/skilld" and .source.commitSha == $commit + and .source.visibility == "public")' \ + "$probe/resolution.json" > "$probe/attestation.json" # The CLI asks for each pinned root by its id. A root that skilld.dev # does not serve leaves the release with one root or none. require_served_root() ( @@ -87,7 +122,7 @@ jobs: exit 1 fi cargo run --locked --quiet --package skilld-core --example verify-release-root \ - -- "$body" "$key_id" "$public_key" + -- "$body" "$key_id" "$public_key" "$probe/attestation.json" ) require_served_root SKILLD_ROOT_KEY_ID SKILLD_ROOT_PUBLIC_KEY require_served_root SKILLD_BACKUP_ROOT_KEY_ID SKILLD_BACKUP_ROOT_PUBLIC_KEY diff --git a/crates/skilld-core/examples/verify-release-root.rs b/crates/skilld-core/examples/verify-release-root.rs index b52b6390..6ba2becb 100644 --- a/crates/skilld-core/examples/verify-release-root.rs +++ b/crates/skilld-core/examples/verify-release-root.rs @@ -1,4 +1,6 @@ -use skilld_core::{TrustedRoot, TrustedRootPin, verify_trusted_root}; +use skilld_core::{ + ArtifactAttestation, TrustedRoot, TrustedRootPin, verify_attestation, verify_trusted_root, +}; use std::{env, error::Error, fs}; // Release preflight uses the same wire type and verifier as hosted CLI operations. @@ -10,6 +12,9 @@ fn main() -> Result<(), Box> { public_key: args.next().ok_or("root public key is required")?, }; let root: TrustedRoot = serde_json::from_slice(&fs::read(path)?)?; - verify_trusted_root(root, &pin)?; + let root = verify_trusted_root(root, &pin)?; + let attestation_path = args.next().ok_or("Artifact attestation is required")?; + let attestation: ArtifactAttestation = serde_json::from_slice(&fs::read(attestation_path)?)?; + verify_attestation(&attestation, &root)?; Ok(()) } diff --git a/docs/migrate-v2-to-v3.md b/docs/migrate-v2-to-v3.md index e0eccc7f..93c3a88f 100644 --- a/docs/migrate-v2-to-v3.md +++ b/docs/migrate-v2-to-v3.md @@ -196,6 +196,16 @@ The release stops before it builds unless skilld.dev serves both roots. Each served root must have `version` 1, at least one key, and the `rootKeyId` and `rootPublicKey` of its variables. A redirect also stops the release. +Preflight resolves `skills/skilld` from `skilld-dev/skilld` at the release commit through the deployed service. +Both pinned roots must verify the returned Artifact attestation with the CLI's parser and verifier. +An unknown signing key, invalid signature, or invalid signing window stops the release. +If resolution fails, becomes blocked, or does not finish within the preflight deadline, the release stops. + +Keep every supported Artifact signing key available under both roots, including keys for existing Artifacts. +Use the same signing key id, public key, validity window, and supported status under each root. +Each root signs its own key statements with its own root private key. +Before changing the deployed signer, publish its verification key under both roots. + The release tag must match the root `package.json` version exactly. The CLI, native packages, and Harness use that same version. The protocol package has an independent version. diff --git a/tests/loader/trusted-root-preflight.test.ts b/tests/loader/trusted-root-preflight.test.ts index a7c00eed..ec178196 100644 --- a/tests/loader/trusted-root-preflight.test.ts +++ b/tests/loader/trusted-root-preflight.test.ts @@ -1,3 +1,4 @@ +import type { KeyObject } from 'node:crypto' import { spawnSync } from 'node:child_process' import { createHash, generateKeyPairSync, sign } from 'node:crypto' import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' @@ -6,22 +7,25 @@ import { join } from 'node:path' import { expect, it } from 'vitest' import { parse } from 'yaml' -function rootFixture(rootKeyId: string) { +function signed(domain: string, statement: Buffer, privateKey: KeyObject) { + return sign(null, Buffer.concat([ + Buffer.from(`${domain}\0`), + createHash('sha256').update(statement).digest(), + ]), privateKey).toString('base64url') +} + +function rootFixture(rootKeyId: string, signer: { publicKey: KeyObject }, keyId = 'signer-1') { const { publicKey, privateKey } = generateKeyPairSync('ed25519') const rootPublicKey = publicKey.export({ format: 'jwk' }).x! const key = { - keyId: 'signer-1', + keyId, algorithm: 'Ed25519', - publicKey: rootPublicKey, + publicKey: signer.publicKey.export({ format: 'jwk' }).x!, notBefore: '2026-01-01T00:00:00.000Z', notAfter: '2027-01-01T00:00:00.000Z', status: 'active', } const statement = Buffer.from(JSON.stringify({ version: 1, rootKeyId, ...key })) - const message = Buffer.concat([ - Buffer.from('skilld-trusted-key-v1\0'), - createHash('sha256').update(statement).digest(), - ]) return { version: 1, rootKeyId, @@ -30,62 +34,167 @@ function rootFixture(rootKeyId: string) { keys: [{ ...key, statement: statement.toString('base64url'), - rootSignature: sign(null, message, privateKey).toString('base64url'), + rootSignature: signed('skilld-trusted-key-v1', statement, privateKey), }], } } -it('stops release preflight for an invalid signature on either pin and accepts valid roots', () => { +function preflightFixture() { const directory = mkdtempSync(join(tmpdir(), 'skilld-root-preflight-')) - try { - const workflow = parse(readFileSync('.github/workflows/release.yml', 'utf8')) - const step = workflow.jobs['release-plan'].steps.find( - (step: { name?: string }) => step.name === 'Require skilld.dev to serve both pinned roots', - ) - const primary = rootFixture('primary-root') - const backup = rootFixture('backup-root') - const fixtures = [primary, backup] - // Replace only the HTTP boundary. Run the real workflow gate and verifier. - writeFileSync(join(directory, 'curl.ts'), `#!/usr/bin/env -S node --experimental-strip-types -import { copyFileSync } from 'node:fs' + const workflow = parse(readFileSync('.github/workflows/release.yml', 'utf8')) + const step = workflow.jobs['release-plan'].steps.find( + (step: { name?: string }) => step.name === 'Require skilld.dev to serve both pinned roots', + ) + const signer = generateKeyPairSync('ed25519') + const primary = rootFixture('primary-root', signer) + const backup = rootFixture('backup-root', signer) + const fixture = JSON.parse(readFileSync('contracts/fixtures/v1/artifact-attestation.json', 'utf8')) + const { statement: _statement, signature: _signature, ...claims } = fixture + const statement = Buffer.from(JSON.stringify(claims)) + const attestation = { + ...claims, + statement: statement.toString('base64url'), + signature: { algorithm: 'Ed25519', keyId: 'signer-1', value: signed('skilld-attestation-v1', statement, signer.privateKey) }, + } + // Replace only HTTP. Execute the release gate and the CLI's Rust verifiers. + writeFileSync(join(directory, 'curl.ts'), `#!/usr/bin/env -S node --experimental-strip-types +import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' const args = process.argv.slice(2) -const id = new URL(args.at(-1)!).pathname.split('/').at(-1)! +const path = new URL(args.at(-1)!).pathname +if (path === '/api/v1/resolutions') { + const request = JSON.parse(readFileSync(args[args.indexOf('--data-binary') + 1]!.slice(1), 'utf8')) + if (request.source.ref.value !== process.env.GITHUB_SHA || request.source.selector.path !== 'skills/skilld') + process.exit(1) +} +const id = path.startsWith('/api/v1/resolutions') ? 'resolution' : path.split('/').at(-1)! +if (path === '/api/v1/resolutions' && existsSync(join(process.env.ROOT_FIXTURES!, 'pending'))) { + writeFileSync(args[args.indexOf('--output') + 1]!, JSON.stringify({ state: 'pending', resolutionId: 'res_release_probe' })) + process.stdout.write('202') + process.exit(0) +} copyFileSync(join(process.env.ROOT_FIXTURES!, id + '.json'), args[args.indexOf('--output') + 1]!) process.stdout.write('200') `, { mode: 0o755 }) - symlinkSync('curl.ts', join(directory, 'curl')) - const run = () => spawnSync('bash', ['-e', '-c', `${step.run}\nprintf 'native-build-reached'`], { + symlinkSync('curl.ts', join(directory, 'curl')) + const save = (root: typeof primary) => writeFileSync(join(directory, `${root.rootKeyId}.json`), JSON.stringify(root)) + save(primary) + save(backup) + const resolution = { + state: 'ready', + resolutionId: 'res_release_probe', + artifact: { artifactId: claims.artifactId, visibility: 'public', attestation }, + } + const saveResolution = () => writeFileSync(join(directory, 'resolution.json'), JSON.stringify(resolution)) + saveResolution() + return { + primary, + backup, + save, + resolution, + saveResolution, + pending: () => writeFileSync(join(directory, 'pending'), ''), + run: () => spawnSync('bash', ['-e', '-c', `${step.run}\nprintf 'native-build-reached'`], { encoding: 'utf8', env: { ...process.env, PATH: `${directory}:${process.env.PATH}`, ROOT_FIXTURES: directory, + GITHUB_SHA: claims.source.commitSha, + GITHUB_RUN_ID: '1', + GITHUB_RUN_ATTEMPT: '1', SKILLD_ROOT_KEY_ID: primary.rootKeyId, SKILLD_ROOT_PUBLIC_KEY: primary.rootPublicKey, SKILLD_BACKUP_ROOT_KEY_ID: backup.rootKeyId, SKILLD_BACKUP_ROOT_PUBLIC_KEY: backup.rootPublicKey, }, - }) - for (const fixture of fixtures) - writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) + }), + cleanup: () => rmSync(directory, { recursive: true, force: true }), + } +} - for (const fixture of fixtures) { - const validSignature = fixture.keys[0]!.rootSignature - fixture.keys[0]!.rootSignature = Buffer.alloc(64).toString('base64url') - writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) - const invalid = run() +it.each(['primary', 'backup'] as const)('rejects a valid %s root whose signer cannot verify the service attestation', (pin) => { + const fixture = preflightFixture() + try { + const incompatible = rootFixture(fixture[pin].rootKeyId, generateKeyPairSync('ed25519')) + Object.assign(fixture[pin], incompatible) + fixture.save(incompatible) + const result = fixture.run() + expect(result.status, result.stderr).not.toBe(0) + expect(result.stdout).not.toContain('native-build-reached') + expect(result.stderr).toContain('ATTESTATION_SIGNATURE_INVALID') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it.each(['primary', 'backup'] as const)('rejects an unknown service signer under the %s root', (pin) => { + const fixture = preflightFixture() + try { + const incompatible = rootFixture(fixture[pin].rootKeyId, generateKeyPairSync('ed25519'), 'other-signer') + Object.assign(fixture[pin], incompatible) + fixture.save(incompatible) + const result = fixture.run() + expect(result.status, result.stderr).not.toBe(0) + expect(result.stderr).toContain('SIGNING_KEY_UNKNOWN') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it('waits for a pending service attestation before verifying both roots', () => { + const fixture = preflightFixture() + try { + fixture.pending() + const result = fixture.run() + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toContain('native-build-reached') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it.each(['blocked', 'invalid-signature'])('stops release preflight for a %s service attestation', (failure) => { + const fixture = preflightFixture() + try { + if (failure === 'blocked') + fixture.resolution.state = 'blocked' + else + fixture.resolution.artifact.attestation.signature.value = Buffer.alloc(64).toString('base64url') + fixture.saveResolution() + const result = fixture.run() + expect(result.status, result.stderr).not.toBe(0) + expect(result.stdout).not.toContain('native-build-reached') + if (failure === 'invalid-signature') + expect(result.stderr).toContain('ATTESTATION_SIGNATURE_INVALID') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it('stops release preflight for an invalid root signature and accepts roots that both verify the service attestation', () => { + const fixture = preflightFixture() + try { + for (const root of [fixture.primary, fixture.backup]) { + const validSignature = root.keys[0]!.rootSignature + root.keys[0]!.rootSignature = Buffer.alloc(64).toString('base64url') + fixture.save(root) + const invalid = fixture.run() expect(invalid.status, invalid.stderr).not.toBe(0) expect(invalid.stdout).not.toContain('native-build-reached') expect(invalid.stderr).toContain('TRUSTED_ROOT_SIGNATURE_INVALID') - fixture.keys[0]!.rootSignature = validSignature - writeFileSync(join(directory, `${fixture.rootKeyId}.json`), JSON.stringify(fixture)) + root.keys[0]!.rootSignature = validSignature + fixture.save(root) } - const valid = run() + const valid = fixture.run() expect(valid.status, valid.stderr).toBe(0) expect(valid.stdout).toContain('native-build-reached') } finally { - rmSync(directory, { recursive: true, force: true }) + fixture.cleanup() } }, 120_000) From 5c05b0a233746eb2d2a3f9b7ce1bb3346ef6da06 Mon Sep 17 00:00:00 2001 From: Harlan GitHub Agent Date: Thu, 19 Nov 2026 01:39:15 +1100 Subject: [PATCH 7/7] fix(release): require equivalent Artifact signer policies --- .github/workflows/release.yml | 9 +- .../examples/verify-release-root.rs | 52 +++++++-- tests/loader/trusted-root-preflight.test.ts | 102 ++++++++++++++++-- 3 files changed, 146 insertions(+), 17 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 085c1da3..9fdabbbd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -108,8 +108,7 @@ jobs: local key_id_name="$1" public_key_name="$2" local key_id="${!key_id_name}" public_key="${!public_key_name}" local body status - body="$(mktemp)" - trap 'rm -f "$body"' EXIT + body="$probe/$key_id_name.json" # No --location: a redirect fails this check. status="$(curl --fail --silent --show-error --proto '=https' \ --retry 3 --max-time 30 --output "$body" --write-out '%{http_code}' \ @@ -121,11 +120,13 @@ jobs: echo "skilld.dev answered HTTP $status for the trusted root $key_id from $key_id_name." >&2 exit 1 fi - cargo run --locked --quiet --package skilld-core --example verify-release-root \ - -- "$body" "$key_id" "$public_key" "$probe/attestation.json" ) require_served_root SKILLD_ROOT_KEY_ID SKILLD_ROOT_PUBLIC_KEY require_served_root SKILLD_BACKUP_ROOT_KEY_ID SKILLD_BACKUP_ROOT_PUBLIC_KEY + cargo run --locked --quiet --package skilld-core --example verify-release-root \ + -- "$probe/SKILLD_ROOT_KEY_ID.json" "$SKILLD_ROOT_KEY_ID" "$SKILLD_ROOT_PUBLIC_KEY" \ + "$probe/attestation.json" \ + "$probe/SKILLD_BACKUP_ROOT_KEY_ID.json" "$SKILLD_BACKUP_ROOT_KEY_ID" "$SKILLD_BACKUP_ROOT_PUBLIC_KEY" - id: matrix name: Read native package matrix shell: bash diff --git a/crates/skilld-core/examples/verify-release-root.rs b/crates/skilld-core/examples/verify-release-root.rs index 6ba2becb..5317bf09 100644 --- a/crates/skilld-core/examples/verify-release-root.rs +++ b/crates/skilld-core/examples/verify-release-root.rs @@ -1,20 +1,60 @@ use skilld_core::{ - ArtifactAttestation, TrustedRoot, TrustedRootPin, verify_attestation, verify_trusted_root, + ArtifactAttestation, TrustedKeyStatus, TrustedRoot, TrustedRootPin, VerifiedTrustedRoot, + verify_attestation, verify_trusted_root, }; -use std::{env, error::Error, fs}; +use std::{collections::BTreeMap, env, error::Error, fs}; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; // Release preflight uses the same wire type and verifier as hosted CLI operations. -fn main() -> Result<(), Box> { - let mut args = env::args().skip(1); +fn read_root( + args: &mut impl Iterator, +) -> Result> { let path = args.next().ok_or("trusted root document is required")?; let pin = TrustedRootPin { key_id: args.next().ok_or("root key id is required")?, public_key: args.next().ok_or("root public key is required")?, }; let root: TrustedRoot = serde_json::from_slice(&fs::read(path)?)?; - let root = verify_trusted_root(root, &pin)?; + Ok(verify_trusted_root(root, &pin)?) +} + +// Compare the complete acceptance policy, not just the live probe's signer. +// Active and overlapping keys both verify Artifacts. Retired and revoked keys do not. +fn supported_signers( + root: &VerifiedTrustedRoot, +) -> Result, time::error::Parse> { + root.root() + .keys + .iter() + .filter(|key| { + matches!( + key.status, + TrustedKeyStatus::Active | TrustedKeyStatus::Overlapping + ) + }) + .map(|key| { + Ok(( + key.key_id.as_str(), + ( + key.public_key.as_str(), + OffsetDateTime::parse(&key.not_before, &Rfc3339)?, + OffsetDateTime::parse(&key.not_after, &Rfc3339)?, + ), + )) + }) + .collect() +} + +fn main() -> Result<(), Box> { + let mut args = env::args().skip(1); + let primary = read_root(&mut args)?; let attestation_path = args.next().ok_or("Artifact attestation is required")?; let attestation: ArtifactAttestation = serde_json::from_slice(&fs::read(attestation_path)?)?; - verify_attestation(&attestation, &root)?; + verify_attestation(&attestation, &primary)?; + let backup = read_root(&mut args)?; + verify_attestation(&attestation, &backup)?; + if supported_signers(&primary)? != supported_signers(&backup)? { + return Err("the pinned roots' supported Artifact signers differ".into()); + } Ok(()) } diff --git a/tests/loader/trusted-root-preflight.test.ts b/tests/loader/trusted-root-preflight.test.ts index ec178196..73be4695 100644 --- a/tests/loader/trusted-root-preflight.test.ts +++ b/tests/loader/trusted-root-preflight.test.ts @@ -14,7 +14,13 @@ function signed(domain: string, statement: Buffer, privateKey: KeyObject) { ]), privateKey).toString('base64url') } -function rootFixture(rootKeyId: string, signer: { publicKey: KeyObject }, keyId = 'signer-1') { +function rootFixture(rootKeyId: string, signer: { publicKey: KeyObject }, keyId = 'signer-1', additionalKeys: Partial<{ + keyId: string + publicKey: string + notBefore: string + notAfter: string + status: string +}>[] = []) { const { publicKey, privateKey } = generateKeyPairSync('ed25519') const rootPublicKey = publicKey.export({ format: 'jwk' }).x! const key = { @@ -25,17 +31,19 @@ function rootFixture(rootKeyId: string, signer: { publicKey: KeyObject }, keyId notAfter: '2027-01-01T00:00:00.000Z', status: 'active', } - const statement = Buffer.from(JSON.stringify({ version: 1, rootKeyId, ...key })) return { version: 1, rootKeyId, rootPublicKey, fetchedAt: '2026-11-18T00:00:00.000Z', - keys: [{ - ...key, - statement: statement.toString('base64url'), - rootSignature: signed('skilld-trusted-key-v1', statement, privateKey), - }], + keys: [key, ...additionalKeys.map(extra => ({ ...key, ...extra }))].map((key) => { + const statement = Buffer.from(JSON.stringify({ version: 1, rootKeyId, ...key })) + return { + ...key, + statement: statement.toString('base64url'), + rootSignature: signed('skilld-trusted-key-v1', statement, privateKey), + } + }), } } @@ -90,6 +98,7 @@ process.stdout.write('200') return { primary, backup, + signer, save, resolution, saveResolution, @@ -113,6 +122,85 @@ process.stdout.write('200') } } +it.each(['primary', 'backup'] as const)('rejects an overlapping signer present only under the %s root despite a valid probe', (pin) => { + const fixture = preflightFixture() + try { + const root = rootFixture(fixture[pin].rootKeyId, fixture.signer, 'signer-1', [{ + keyId: 'signer-2', + publicKey: generateKeyPairSync('ed25519').publicKey.export({ format: 'jwk' }).x!, + status: 'overlapping', + }]) + Object.assign(fixture[pin], root) + fixture.save(root) + const result = fixture.run() + expect(result.status, result.stderr).not.toBe(0) + expect(result.stdout).not.toContain('native-build-reached') + expect(result.stderr).toContain('supported Artifact signers differ') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it.each(['public-key', 'start', 'end', 'retired', 'revoked'] as const)('rejects different %s acceptance for a signer outside the probe', (difference) => { + const fixture = preflightFixture() + try { + const extra = { + keyId: 'signer-2', + publicKey: generateKeyPairSync('ed25519').publicKey.export({ format: 'jwk' }).x!, + status: 'overlapping', + } + const changed = { + ...extra, + ...(difference === 'public-key' ? { publicKey: fixture.signer.publicKey.export({ format: 'jwk' }).x! } : {}), + ...(difference === 'start' ? { notBefore: '2026-06-01T00:00:00Z' } : {}), + ...(difference === 'end' ? { notAfter: '2026-12-01T00:00:00Z' } : {}), + ...(['retired', 'revoked'].includes(difference) ? { status: difference } : {}), + } + for (const pin of ['primary', 'backup'] as const) { + const root = rootFixture(fixture[pin].rootKeyId, fixture.signer, 'signer-1', [pin === 'primary' ? extra : changed]) + Object.assign(fixture[pin], root) + fixture.save(root) + } + const result = fixture.run() + expect(result.status, result.stderr).not.toBe(0) + expect(result.stdout).not.toContain('native-build-reached') + expect(result.stderr).toContain('supported Artifact signers differ') + } + finally { + fixture.cleanup() + } +}, 120_000) + +it('accepts equivalent signer policies regardless of key order, accepted status, or timestamp format', () => { + const fixture = preflightFixture() + try { + const extra = { + keyId: 'signer-2', + publicKey: generateKeyPairSync('ed25519').publicKey.export({ format: 'jwk' }).x!, + status: 'overlapping', + } + const primary = rootFixture(fixture.primary.rootKeyId, fixture.signer, 'signer-1', [extra, { keyId: 'retired', status: 'retired' }]) + const backup = rootFixture(fixture.backup.rootKeyId, fixture.signer, 'signer-1', [{ + ...extra, + status: 'active', + notBefore: '2026-01-01T01:00:00+01:00', + notAfter: '2027-01-01T00:00:00Z', + }]) + backup.keys.reverse() + for (const root of [primary, backup]) { + Object.assign(root.rootKeyId === primary.rootKeyId ? fixture.primary : fixture.backup, root) + fixture.save(root) + } + const result = fixture.run() + expect(result.status, result.stderr).toBe(0) + expect(result.stdout).toContain('native-build-reached') + } + finally { + fixture.cleanup() + } +}, 120_000) + it.each(['primary', 'backup'] as const)('rejects a valid %s root whose signer cannot verify the service attestation', (pin) => { const fixture = preflightFixture() try {