diff --git a/.gitattributes b/.gitattributes index 672d49e71..801bde392 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,6 +5,11 @@ # the Sigstore attestation that ships next to them. crates/lpm-cli/tests/fixtures/release_manifests/*-SHA256SUMS.txt -text +# Sigstore's trust root and TUF metadata are checked against the lengths and +# hashes Sigstore signed, so a CRLF checkout must not rewrite them. +crates/lpm-cli/assets/sigstore_*.json -text +crates/lpm-cli/tests/fixtures/sigstore_tuf/*.json -text + # Lifecycle-script fixtures are the exact script bytes the static gate # classifies; a CRLF checkout would hand it a `\r` no package.json string has. crates/lpm-security/tests/fixtures/postinstall-scripts/scripts/*.txt -text diff --git a/Cargo.lock b/Cargo.lock index 17210cee5..df1ea77bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3572,6 +3572,7 @@ dependencies = [ "diffy", "dirs", "ecdsa", + "ed25519-dalek", "ferralk-glob", "flate2", "futures", diff --git a/crates/lpm-cli/Cargo.toml b/crates/lpm-cli/Cargo.toml index 5544ee36b..bd8e9ebc2 100644 --- a/crates/lpm-cli/Cargo.toml +++ b/crates/lpm-cli/Cargo.toml @@ -145,6 +145,7 @@ rayon = { workspace = true } p256 = { workspace = true } # p384 for the Fulcio root chain (Phase 1.3) — Fulcio roots are P-384. p384 = { workspace = true } +ed25519-dalek = { workspace = true } ecdsa = { workspace = true } # Phase 46 P4: x509 cert parsing for Sigstore attestation SAN extraction diff --git a/crates/lpm-cli/assets/sigstore_tuf_root.json b/crates/lpm-cli/assets/sigstore_tuf_root.json new file mode 100644 index 000000000..bc73a8b9b --- /dev/null +++ b/crates/lpm-cli/assets/sigstore_tuf_root.json @@ -0,0 +1,141 @@ +{ + "signatures": [ + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3045022065c68f28ebe44d0a4e047a6e287f9669c8e3b31e08536396c67a1483326be8c6022100e7524a889e40de0df84231dd40e1fcc57fbbbf62055c17076568307dbc509046" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "304502206fedc4a382a0c5155e812c9b7461fe388ef704fef9e093c5c236e20abbf8e6620221008bbec36b63bf9baebc03a83c770cf9387efc90907eb83070b7a875129512d687" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "30450220468f4219db51c7e815e1e3d33d9987878aa12aeaf331604d5180dd60b19dfb350221009f778ef5e96647c08bd23d63f69c0cce6fc353d747b9d51f35dc0f8678de9fef" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "3045022029e2518a7bcac05ec0b227809ce0c969406743412f90dc5255401afb13363f4602210087a64182249e41dd11de91c9f385a33659bd60147a93d13c86b7a64e447f9826" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "30450221008051c456ed2bf48aa5fc5742928ab0904266c1d6bdde5fc75ae20f12d098a95502203cc683bd86793808e6c9f89e2ca93f80b00c6ea64880ac4e37db69e2e86b24e3" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2027-04-22T19:27:31Z", + "keys": { + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms:projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp/cryptoKeyVersions/1" + }, + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMxpPOJCIZ5otG4106fGJseEQi3V9\npkMYQ4uyV9Tj1M7WHXIyLG+jkfvuG0glQ1JZbRZZBV3gAR4sojdGHISeow==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@lance" + }, + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 6 + } + }, + "spec_version": "1.0", + "version": 16, + "x-tuf-on-ci-expiry-period": 197, + "x-tuf-on-ci-signing-period": 46 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/src/commands/publish/npm_artifact.rs b/crates/lpm-cli/src/commands/publish/npm_artifact.rs index a37a51128..c4affad32 100644 --- a/crates/lpm-cli/src/commands/publish/npm_artifact.rs +++ b/crates/lpm-cli/src/commands/publish/npm_artifact.rs @@ -81,20 +81,20 @@ pub(crate) async fn prepare_npm_target_artifact( }) } -pub(crate) fn load_provenance_file(path: &Path) -> Result { +pub(crate) async fn load_provenance_file(path: &Path) -> Result { let file = open_provenance_file(path)?; let bytes = read_open_provenance_file(file, path)?; - parse_provenance_file_bytes(path, bytes) + parse_provenance_file_bytes(path, bytes).await } -pub(super) fn load_provenance_bytes( +pub(super) async fn load_provenance_bytes( path: &Path, bytes: Vec, ) -> Result { if bytes.len() as u64 > PROVENANCE_FILE_MAX_BYTES { return Err(provenance_file_too_large(path, bytes.len() as u64)); } - parse_provenance_file_bytes(path, bytes) + parse_provenance_file_bytes(path, bytes).await } pub(super) fn read_open_provenance_file( @@ -138,7 +138,7 @@ fn provenance_file_too_large(path: &Path, size: u64) -> LpmError { )) } -fn parse_provenance_file_bytes( +async fn parse_provenance_file_bytes( path: &Path, bytes: Vec, ) -> Result { @@ -160,11 +160,13 @@ fn parse_provenance_file_bytes( let statement = provenance_statement_from_bundle(&bundle)?; validate_slsa_provenance_statement(&statement)?; - let verified = crate::sigstore_verify::verify_sigstore_bundle( + let verified = crate::sigstore_verify::verify_sigstore_bundle_refreshing( data.as_bytes(), &crate::sigstore_verify::IdentityExpectations::none(), crate::sigstore_verify::VerifyOptions::npm_attestation(), + crate::sigstore_verify::TrustRefresh::WhenMissing, ) + .await .map_err(|e| { LpmError::Registry(format!( "provenance file {} failed Sigstore verification: {e}", @@ -629,22 +631,24 @@ mod tests { assert!(error.to_string().contains("signing identity")); } - #[test] - fn load_provenance_file_rejects_oversized_regular_file() { + #[tokio::test] + async fn load_provenance_file_rejects_oversized_regular_file() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("too-large.sigstore"); let file = std::fs::File::create(&path).unwrap(); file.set_len(PROVENANCE_FILE_MAX_BYTES + 1).unwrap(); - let err = load_provenance_file(&path).unwrap_err(); + let err = load_provenance_file(&path).await.unwrap_err(); assert!(err.to_string().contains("too large")); } #[cfg(unix)] - #[test] - fn load_provenance_file_rejects_special_file() { - let err = load_provenance_file(Path::new("/dev/null")).unwrap_err(); + #[tokio::test] + async fn load_provenance_file_rejects_special_file() { + let err = load_provenance_file(Path::new("/dev/null")) + .await + .unwrap_err(); assert!(err.to_string().contains("regular file")); } @@ -665,8 +669,8 @@ mod tests { } #[cfg(unix)] - #[test] - fn load_provenance_file_rejects_fifo_without_blocking() { + #[tokio::test] + async fn load_provenance_file_rejects_fifo_without_blocking() { use std::ffi::CString; use std::os::unix::ffi::OsStrExt; @@ -678,7 +682,7 @@ mod tests { let rc = unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }; assert_eq!(rc, 0, "mkfifo must create the test fifo"); - let err = load_provenance_file(&path).unwrap_err(); + let err = load_provenance_file(&path).await.unwrap_err(); assert!(err.to_string().contains("regular file")); } diff --git a/crates/lpm-cli/src/commands/publish/orchestrator.rs b/crates/lpm-cli/src/commands/publish/orchestrator.rs index 6b6ff8b42..68c8810d0 100644 --- a/crates/lpm-cli/src/commands/publish/orchestrator.rs +++ b/crates/lpm-cli/src/commands/publish/orchestrator.rs @@ -2621,7 +2621,7 @@ async fn precompute_file_provenance_artifacts( let ProvenanceRequest::File(request) = input.provenance_request else { return Ok(HashMap::new()); }; - let file = load_provenance_request_file(request)?; + let file = load_provenance_request_file(request).await?; let provenance = ResolvedProvenance::File(file); let npm_target_count = input .targets diff --git a/crates/lpm-cli/src/commands/publish/provenance.rs b/crates/lpm-cli/src/commands/publish/provenance.rs index bac5b4c80..f25a07dc6 100644 --- a/crates/lpm-cli/src/commands/publish/provenance.rs +++ b/crates/lpm-cli/src/commands/publish/provenance.rs @@ -47,6 +47,7 @@ pub(crate) async fn materialize_provenance_request( match request { ProvenanceRequest::Disabled => Ok(None), ProvenanceRequest::File(file) => load_provenance_request_file(&file) + .await .map(ResolvedProvenance::File) .map(Some), ProvenanceRequest::Generate => { @@ -59,11 +60,11 @@ pub(crate) async fn materialize_provenance_request( } } -pub(super) fn load_provenance_request_file( +pub(super) async fn load_provenance_request_file( request: &ProvenanceFileRequest, ) -> Result { match request { - ProvenanceFileRequest::AmbientPath(path) => load_provenance_file(path), + ProvenanceFileRequest::AmbientPath(path) => load_provenance_file(path).await, ProvenanceFileRequest::ProjectFile { display_path, relative_path, @@ -75,7 +76,7 @@ pub(super) fn load_provenance_request_file( &display_path.to_string_lossy(), )?; let bytes = read_open_provenance_file_with_known_size(file, display_path, known_size)?; - load_provenance_bytes(display_path, bytes) + load_provenance_bytes(display_path, bytes).await } } } @@ -1317,8 +1318,8 @@ mod tests { // replacement cannot happen there; see `publish_common`'s // `an_open_tarball_source_root_keeps_its_directory_in_place`. #[cfg(unix)] - #[test] - fn project_relative_provenance_keeps_the_selected_project_generation() { + #[tokio::test] + async fn project_relative_provenance_keeps_the_selected_project_generation() { let root = tempfile::tempdir().unwrap(); let project = root.path().join("project"); let displaced = root.path().join("displaced"); @@ -1348,6 +1349,7 @@ mod tests { }; let error = load_provenance_request_file(&request) + .await .expect_err("the selected invalid provenance generation must be loaded") .to_string(); diff --git a/crates/lpm-cli/src/commands/self_update.rs b/crates/lpm-cli/src/commands/self_update.rs index 25cce581c..e5a53c51a 100644 --- a/crates/lpm-cli/src/commands/self_update.rs +++ b/crates/lpm-cli/src/commands/self_update.rs @@ -5,8 +5,9 @@ use crate::release_lookup::{ is_newer_semver, operating_system_home_dir, probe_release, read_cache_at, write_cache_at, }; use crate::sigstore_verify::{ - CertificateBuildClaims, IdentityExpectations, VerifiedProvenance, VerifyError, VerifyOptions, - extract_subject_digest_from_statement, verify_sigstore_bundle, + CertificateBuildClaims, IdentityExpectations, TrustRefresh, VerifiedProvenance, VerifyError, + VerifyOptions, extract_subject_digest_from_statement, verify_sigstore_bundle_refreshing, + verify_sigstore_bundle_with_built_in_trust_root, }; use lpm_common::LpmError; use lpm_common::color::Painted; @@ -2218,19 +2219,41 @@ struct VerifiedReleaseManifest { entries: HashMap, } +/// The signing identity of LPM's release workflow. +fn release_signing_identity() -> IdentityExpectations { + IdentityExpectations { + expected_issuer: Some("https://token.actions.githubusercontent.com".to_string()), + expected_san_uri_prefix: Some("https://github.com/lpm-dev/rust-client/".to_string()), + expected_workflow_path: Some(".github/workflows/release.yml".to_string()), + } +} + +/// Verify a release's `SHA256SUMS.txt` against the trust root built into +/// this binary only. `lpm internal-verify-release` uses it so a release that +/// passes verifies even for a client that can't reach Sigstore's repository. fn verify_release_manifest( version: &str, manifest_bytes: &[u8], bundle_bytes: &[u8], release: &GithubRelease, ) -> Result { - let expectations = IdentityExpectations { - expected_issuer: Some("https://token.actions.githubusercontent.com".to_string()), - expected_san_uri_prefix: Some("https://github.com/lpm-dev/rust-client/".to_string()), - expected_workflow_path: Some(".github/workflows/release.yml".to_string()), - }; - let options = VerifyOptions::strict(); + let verified = verify_sigstore_bundle_with_built_in_trust_root( + bundle_bytes, + &release_signing_identity(), + VerifyOptions::strict(), + ) + .map_err(map_verify_error)?; + check_release_manifest(version, manifest_bytes, verified, release) +} +/// Check what a verified Sigstore bundle attests against the release and +/// its `SHA256SUMS.txt`. +fn check_release_manifest( + version: &str, + manifest_bytes: &[u8], + verified: VerifiedProvenance, + release: &GithubRelease, +) -> Result { let VerifiedProvenance { snapshot, build, @@ -2239,7 +2262,7 @@ fn verify_release_manifest( leaf_cert_sha256, log_id, log_index, - } = verify_sigstore_bundle(bundle_bytes, &expectations, options).map_err(map_verify_error)?; + } = verified; let source_commit = validate_release_provenance( version, @@ -3522,7 +3545,15 @@ async fn fetch_verified_release_manifest( if human_output { install_ui::phase("Verifying Sigstore attestation"); } - verify_release_manifest(version, &manifest_bytes, &bundle_bytes, &release) + let verified = verify_sigstore_bundle_refreshing( + &bundle_bytes, + &release_signing_identity(), + VerifyOptions::strict(), + TrustRefresh::BeforeVerifying, + ) + .await + .map_err(map_verify_error)?; + check_release_manifest(version, &manifest_bytes, verified, &release) } /// Why a standalone release couldn't be staged: it didn't verify, or @@ -5130,7 +5161,7 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 #[test] fn real_v0_84_0_certificate_names_its_build() { let (_, bundle) = real_v0_84_0_release_assets(); - let verified = verify_sigstore_bundle( + let verified = crate::sigstore_verify::verify_sigstore_bundle( &bundle, &IdentityExpectations::none(), VerifyOptions::strict(), @@ -5177,7 +5208,7 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 verified.source_commit, "faa77c3cb0ccea39886f12e7005575bae4273505" ); - let certificate = verify_sigstore_bundle( + let certificate = crate::sigstore_verify::verify_sigstore_bundle( &bundle, &IdentityExpectations::none(), VerifyOptions::strict(), @@ -5203,7 +5234,7 @@ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb lpm-linux-x64 verified.source_commit, "daa536a898e160442cbab72191131164c3e7656a" ); - let certificate = verify_sigstore_bundle( + let certificate = crate::sigstore_verify::verify_sigstore_bundle( &bundle, &IdentityExpectations::none(), VerifyOptions::strict(), diff --git a/crates/lpm-cli/src/provenance_bundle.rs b/crates/lpm-cli/src/provenance_bundle.rs index 7a6967bd7..30e2b79e2 100644 --- a/crates/lpm-cli/src/provenance_bundle.rs +++ b/crates/lpm-cli/src/provenance_bundle.rs @@ -539,15 +539,49 @@ pub(crate) fn verify_bundle_or_err( body: &[u8], url: &str, expectation: &NpmArtifactExpectation, +) -> Result { + use crate::sigstore_verify::{IdentityExpectations, VerifyOptions, verify_sigstore_bundle}; + let outcome = verify_sigstore_bundle( + body, + &IdentityExpectations::none(), + VerifyOptions::npm_attestation(), + ); + npm_provenance_from(body, url, expectation, outcome) +} + +/// [`verify_bundle_or_err`] for a bundle just fetched from the registry: +/// when the Sigstore trust root this machine holds lacks a key the bundle +/// needs, Sigstore's current trust root is fetched before the bundle is +/// judged. +pub(crate) async fn verify_fetched_bundle_or_err( + body: &[u8], + url: &str, + expectation: &NpmArtifactExpectation, ) -> Result { use crate::sigstore_verify::{ - IdentityExpectations, VerifyOptions, extract_npm_subject_sha512, verify_sigstore_bundle, + IdentityExpectations, TrustRefresh, VerifyOptions, verify_sigstore_bundle_refreshing, }; - match verify_sigstore_bundle( + let outcome = verify_sigstore_bundle_refreshing( body, &IdentityExpectations::none(), VerifyOptions::npm_attestation(), - ) { + TrustRefresh::WhenMissing, + ) + .await; + npm_provenance_from(body, url, expectation, outcome) +} + +fn npm_provenance_from( + body: &[u8], + url: &str, + expectation: &NpmArtifactExpectation, + outcome: Result< + crate::sigstore_verify::VerifiedProvenance, + crate::sigstore_verify::VerifyError, + >, +) -> Result { + use crate::sigstore_verify::extract_npm_subject_sha512; + match outcome { Ok(verified) => { let (subject_name, subject_sha512) = extract_npm_subject_sha512(body).map_err(|error| { diff --git a/crates/lpm-cli/src/provenance_fetch.rs b/crates/lpm-cli/src/provenance_fetch.rs index f5be1ef1e..2d9ee3e39 100644 --- a/crates/lpm-cli/src/provenance_fetch.rs +++ b/crates/lpm-cli/src/provenance_fetch.rs @@ -34,7 +34,8 @@ use crate::provenance_bundle::{ AttestationUrlPolicy, FetchBundleError, NpmArtifactExpectation, ProvenanceHttpClient, - fetch_bundle_bytes, parse_sigstore_bundle, read_cache, verify_bundle_or_err, write_cache, + fetch_bundle_bytes, parse_sigstore_bundle, read_cache, verify_fetched_bundle_or_err, + write_cache, }; use futures::StreamExt; use lpm_common::LpmError; @@ -846,7 +847,7 @@ pub(crate) async fn fetch_provenance_evidence( // claimed signed provenance but failed crypto). Transport-class // failures are already absorbed above at `fetch_bundle_bytes`. let verify_start = Instant::now(); - let evidence = verify_bundle_or_err(&buf, url, &expectation)?; + let evidence = verify_fetched_bundle_or_err(&buf, url, &expectation).await?; if let Some(t) = timings { t.record_verify(name, version, verify_start.elapsed()); } diff --git a/crates/lpm-cli/src/relay_trust.rs b/crates/lpm-cli/src/relay_trust.rs index be9591105..23469f937 100644 --- a/crates/lpm-cli/src/relay_trust.rs +++ b/crates/lpm-cli/src/relay_trust.rs @@ -1,8 +1,8 @@ //! Relay key authorization anchored to LPM's GitHub Actions signing identity. use crate::sigstore_verify::{ - IdentityExpectations, VerifiedProvenance, VerifyOptions, extract_subject_digest_from_statement, - verify_sigstore_bundle, + IdentityExpectations, TrustRefresh, VerifiedProvenance, VerifyOptions, + extract_subject_digest_from_statement, verify_sigstore_bundle_refreshing, }; use lpm_common::LpmError; use sha2::{Digest, Sha256}; @@ -45,6 +45,7 @@ async fn fetch_approved_pins() -> Result, LpmError> { &bundle, lpm_common::Timestamp::now().unix_seconds(), ) + .await } async fn fetch_asset( @@ -64,7 +65,11 @@ async fn fetch_asset( .map_err(trust_error) } -fn verify_approved_pins(manifest: &[u8], bundle: &[u8], now: i64) -> Result, LpmError> { +async fn verify_approved_pins( + manifest: &[u8], + bundle: &[u8], + now: i64, +) -> Result, LpmError> { if manifest.len() > MANIFEST_CAP || bundle.len() > BUNDLE_CAP { return Err(trust_error("the signed key list exceeds the size limit")); } @@ -73,8 +78,14 @@ fn verify_approved_pins(manifest: &[u8], bundle: &[u8], now: i64) -> Result>()); diff --git a/crates/lpm-cli/src/release_lookup.rs b/crates/lpm-cli/src/release_lookup.rs index 2220c5fda..02acbcfd7 100644 --- a/crates/lpm-cli/src/release_lookup.rs +++ b/crates/lpm-cli/src/release_lookup.rs @@ -143,7 +143,7 @@ fn resolve_release_url(env_var: &str, default_url: &str) -> String { /// Accept an override URL if it's HTTPS (any host) or HTTP pointed at /// a loopback address (tests + local dev mirrors). Anything else /// (HTTP non-loopback, unsupported scheme, malformed URL) is refused. -fn accept_override(url: &str) -> bool { +pub(crate) fn accept_override(url: &str) -> bool { let parsed = match reqwest::Url::parse(url) { Ok(u) => u, Err(_) => return false, diff --git a/crates/lpm-cli/src/sigstore_verify/bundle.rs b/crates/lpm-cli/src/sigstore_verify/bundle.rs index a7476bcd2..e0019912f 100644 --- a/crates/lpm-cli/src/sigstore_verify/bundle.rs +++ b/crates/lpm-cli/src/sigstore_verify/bundle.rs @@ -19,6 +19,7 @@ use super::{ /// Verifier-time options. Currently carries the /// [`RekorInclusionProofPolicy`] only; future knobs can live here /// without breaking the public API. +#[derive(Debug, Clone, Copy)] pub struct VerifyOptions { pub rekor_inclusion_policy: RekorInclusionProofPolicy, } @@ -192,6 +193,17 @@ pub fn verify_sigstore_bundle( body: &[u8], expectations: &IdentityExpectations, options: VerifyOptions, +) -> Result { + let trust = trust_root()?; + verify_sigstore_bundle_with(body, expectations, options, &trust) +} + +/// [`verify_sigstore_bundle`] against a given trust root. +pub(super) fn verify_sigstore_bundle_with( + body: &[u8], + expectations: &IdentityExpectations, + options: VerifyOptions, + trust: &TrustRoot, ) -> Result { // Dot-namespaced span names match the existing Tracy integration // convention (`linker.prepare`, `linker.one`, etc.) so Tracy @@ -204,7 +216,7 @@ pub fn verify_sigstore_bundle( let _span = tracing::debug_span!("provenance.verify.parse").entered(); parse_bundle_components(body)? }; - let trust = trust_root()?; + trust.check_expiry(SystemTime::now())?; let at_time = parse_integrated_time(&components.tlog_entry.integrated_time)?; let log_index = parse_log_index(&components.tlog_entry.log_index)?; @@ -249,7 +261,7 @@ pub fn verify_sigstore_bundle( // fall back to the active trust anchors. Chain validation has // already cleared the path, so a match is guaranteed. let issuer_spki_der = - find_leaf_issuer_spki(&leaf_parsed, &components.chain_der, &trust, at_time)?; + find_leaf_issuer_spki(&leaf_parsed, &components.chain_der, trust, at_time)?; { let _span = tracing::debug_span!("provenance.verify.sct").entered(); verify_embedded_sct( diff --git a/crates/lpm-cli/src/sigstore_verify/chain.rs b/crates/lpm-cli/src/sigstore_verify/chain.rs index 7ee2e133c..76235648a 100644 --- a/crates/lpm-cli/src/sigstore_verify/chain.rs +++ b/crates/lpm-cli/src/sigstore_verify/chain.rs @@ -68,9 +68,10 @@ pub fn verify_cert_chain( ))); } if fulcio_roots.is_empty() { - return Err(VerifyError::Chain( - "no Fulcio roots active at integratedTime — cannot anchor any chain".into(), - )); + return Err(VerifyError::MissingTrustMaterial { + check: "X.509 chain", + detail: "no Fulcio roots active at integratedTime — cannot anchor any chain".into(), + }); } let at_time_dt: Timestamp = at_time.into(); @@ -162,12 +163,15 @@ pub fn verify_cert_chain( } } - Err(VerifyError::Chain(format!( - "bundle chain's top cert does not match any trusted Fulcio root and \ - is not signed by any trusted Fulcio root \ - ({} candidate root(s) active at integratedTime)", - fulcio_roots.len() - ))) + Err(VerifyError::MissingTrustMaterial { + check: "X.509 chain", + detail: format!( + "bundle chain's top cert does not match any trusted Fulcio root and \ + is not signed by any trusted Fulcio root \ + ({} candidate root(s) active at integratedTime)", + fulcio_roots.len() + ), + }) } /// X.509 extension enforcement for a cert acting as a CA — every diff --git a/crates/lpm-cli/src/sigstore_verify/error.rs b/crates/lpm-cli/src/sigstore_verify/error.rs index eeb258fcd..84b2eeba8 100644 --- a/crates/lpm-cli/src/sigstore_verify/error.rs +++ b/crates/lpm-cli/src/sigstore_verify/error.rs @@ -44,17 +44,15 @@ pub enum VerifyError { #[error("Rekor body is malformed: {0}")] RekorBodyMalformed(String), - /// The vendored Sigstore trust root could not be parsed (JSON - /// shape drift, base64 decode failure on cert / key material, - /// missing required field, etc.). - #[error("vendored Sigstore trust root failed to load: {0}")] + /// A Sigstore trust root could not be parsed (JSON shape drift, + /// base64 decode failure on cert / key material, missing required + /// field, etc.). + #[error("Sigstore trust root failed to load: {0}")] TrustRoot(String), - /// The vendored trust root no longer has at least one currently- + /// The trust root in use no longer has at least one currently- /// active key for every role (Fulcio CA, Rekor signing key, CT - /// log key). The artifact is stale; the user must update `lpm` - /// to a release that ships a refreshed root before any Sigstore - /// verification can succeed. + /// log key). Sigstore's current trust root may have newer ones. /// /// Trust roots intentionally carry retired entries alongside /// active ones so that bundles signed during retired windows @@ -62,17 +60,30 @@ pub enum VerifyError { /// — so a single past `validFor.end` is NOT expiry; the /// artifact is expired when an entire role has gone retired- /// only. - #[error( - "vendored Sigstore trust root has no currently-active key for role(s): {missing_roles}; \ - update lpm to refresh" - )] + #[error("Sigstore trust root has no currently-active key for role(s): {missing_roles}")] TrustRootExpired { missing_roles: String }, + /// The bundle names a Fulcio certificate authority, Rekor log or + /// CT log that the trust root in use doesn't hold, or holds only + /// for other times than the bundle's `integratedTime`. Sigstore's + /// current trust root may hold it. `check` names the verification + /// step that needed it. + #[error("{check} verification failed: {detail}")] + MissingTrustMaterial { check: &'static str, detail: String }, + + /// The trust root lacked what the bundle needs, and fetching + /// Sigstore's current trust root to look for it failed. + #[error("{error} (Sigstore's current trust root could not be fetched: {refresh})")] + TrustRootNotRefreshed { + error: Box, + refresh: String, + }, + /// Rekor SET (Signed Entry Timestamp) verification failed: - /// signature did not verify under the pinned Rekor key, the - /// pinned key for the entry's `logID` is absent / not active at - /// `integratedTime`, the SET signature was not valid DER, or the - /// pinned key's SPKI did not decode as ECDSA P-256. + /// signature did not verify under the pinned Rekor key, the SET + /// signature was not valid DER, or the pinned key's SPKI did not + /// decode as ECDSA P-256. A `logID` the trust root has no key for + /// is [`Self::MissingTrustMaterial`]. #[error("Rekor SET verification failed: {0}")] RekorSet(String), @@ -104,8 +115,9 @@ pub enum VerifyError { /// X.509 chain validation failed: a cert's notBefore/notAfter /// window did not contain `integratedTime`, an issuer/subject /// pair didn't line up, a link's signature didn't verify under - /// its parent, no path to a trusted Fulcio root could be built, - /// or the chain used an unsupported signature algorithm. + /// its parent, or the chain used an unsupported signature + /// algorithm. A chain no trusted Fulcio root anchors is + /// [`Self::MissingTrustMaterial`]. /// AIA fetch is intentionally NOT implemented (the verifier /// refuses to fetch missing intermediates from the URL embedded /// in the cert — Sigstore bundles always ship the full chain, @@ -117,10 +129,11 @@ pub enum VerifyError { /// failed: leaf cert has no SCT extension at the documented /// OID, the SCT list TLS encoding was malformed, the precert /// signed-input could not be reconstructed (TBS DER manipulation - /// failed), no pinned CT log key matched the SCT's `logId` at - /// `integratedTime`, the SCT signature did not verify under the - /// pinned key, or zero SCTs in the list verified (the threshold - /// is "at least one valid"). + /// failed), the SCT signature did not verify under the pinned + /// key, or zero SCTs in the list verified (the threshold is "at + /// least one valid"). When none verifies and one names a CT log + /// the trust root has no key for, the error is + /// [`Self::MissingTrustMaterial`]. #[error("SCT verification failed: {0}")] Sct(String), @@ -149,6 +162,18 @@ pub enum VerifyError { }, } +impl VerifyError { + /// Whether a newer trust root from Sigstore could make the bundle + /// verify: the trust root in use lacks a key or certificate + /// authority the bundle needs. + pub fn is_missing_trust_material(&self) -> bool { + matches!( + self, + Self::MissingTrustMaterial { .. } | Self::TrustRootExpired { .. } + ) + } +} + /// Policy for which Rekor inclusion artifacts a bundle must carry to /// be considered verifiable. Threaded through [`verify_rekor_set`] and /// [`verify_inclusion_proof`]; the composed diff --git a/crates/lpm-cli/src/sigstore_verify/inclusion.rs b/crates/lpm-cli/src/sigstore_verify/inclusion.rs index 3de74bcb6..08c6004ca 100644 --- a/crates/lpm-cli/src/sigstore_verify/inclusion.rs +++ b/crates/lpm-cli/src/sigstore_verify/inclusion.rs @@ -38,11 +38,12 @@ pub fn verify_inclusion_proof( let rekor_key = rekor_keys .iter() .find(|k| k.log_id == log_id_bytes && k.valid_for.contains(integrated_time)) - .ok_or_else(|| { - VerifyError::InclusionProof(format!( + .ok_or_else(|| VerifyError::MissingTrustMaterial { + check: "Rekor inclusion proof", + detail: format!( "no pinned Rekor key for logId={} valid at integratedTime={}", tlog_entry.log_id.key_id, tlog_entry.integrated_time, - )) + ), })?; let checkpoint_envelope = extract_checkpoint_envelope(&proof.checkpoint)?; diff --git a/crates/lpm-cli/src/sigstore_verify/mod.rs b/crates/lpm-cli/src/sigstore_verify/mod.rs index 0b865d3a3..747169033 100644 --- a/crates/lpm-cli/src/sigstore_verify/mod.rs +++ b/crates/lpm-cli/src/sigstore_verify/mod.rs @@ -4,7 +4,8 @@ //! in-toto statement attached to a Sigstore bundle. The data schema in //! [`crate::sigstore`] is the precondition for these checks: //! -//! - vendored Sigstore trust root. +//! - Sigstore trust root: built into the binary, refreshed from +//! Sigstore's TUF repository when a signature needs newer keys. //! - DSSE envelope verification against the leaf cert. //! - X.509 chain validation at `integratedTime`. //! - embedded SCT verification. @@ -30,6 +31,8 @@ mod sct; #[cfg(test)] mod tests; mod trust_root; +mod trust_store; +pub(crate) mod tuf; pub use self::bundle::{ CertificateBuildClaims, IdentityExpectations, VerifiedProvenance, VerifyOptions, @@ -45,6 +48,10 @@ pub use self::rekor_body::verify_rekor_body; pub use self::rekor_set::verify_rekor_set; pub use self::sct::verify_embedded_sct; pub use self::trust_root::{CtLogKey, FulcioRoot, RekorKey, TrustRoot, trust_root}; +pub use self::trust_store::{ + TrustRefresh, verify_sigstore_bundle_refreshing, + verify_sigstore_bundle_with_built_in_trust_root, +}; #[cfg(test)] use self::bundle::{ diff --git a/crates/lpm-cli/src/sigstore_verify/rekor_set.rs b/crates/lpm-cli/src/sigstore_verify/rekor_set.rs index 8fed2513b..2ddbf3a1d 100644 --- a/crates/lpm-cli/src/sigstore_verify/rekor_set.rs +++ b/crates/lpm-cli/src/sigstore_verify/rekor_set.rs @@ -38,11 +38,12 @@ pub fn verify_rekor_set( let rekor_key = rekor_keys .iter() .find(|k| k.log_id == log_id_bytes && k.valid_for.contains(integrated_time)) - .ok_or_else(|| { - VerifyError::RekorSet(format!( + .ok_or_else(|| VerifyError::MissingTrustMaterial { + check: "Rekor SET", + detail: format!( "no pinned Rekor key for logId={} valid at integratedTime={}", tlog_entry.log_id.key_id, tlog_entry.integrated_time, - )) + ), })?; let verifying_key = p256_verifying_key_from_spki(&rekor_key.spki_der).map_err(|e| { diff --git a/crates/lpm-cli/src/sigstore_verify/sct.rs b/crates/lpm-cli/src/sigstore_verify/sct.rs index a3778c9c3..ba9e02465 100644 --- a/crates/lpm-cli/src/sigstore_verify/sct.rs +++ b/crates/lpm-cli/src/sigstore_verify/sct.rs @@ -104,6 +104,7 @@ pub fn verify_embedded_sct( // Per-SCT verification. Threshold: ≥1 must verify. let mut verified = 0usize; + let mut saw_unknown_log = false; let mut last_err: Option = None; for (i, serialized) in sct_serialized_list.iter().enumerate() { let parsed = match parse_serialized_sct(serialized) { @@ -117,6 +118,7 @@ pub fn verify_embedded_sct( .iter() .find(|k| k.log_id == parsed.log_id && k.valid_for.contains(at_time)) else { + saw_unknown_log = true; last_err = Some(format!( "sct[{i}]: no pinned CT log key matches logId={} valid at integratedTime", hex::encode(&parsed.log_id) @@ -130,12 +132,20 @@ pub fn verify_embedded_sct( verified += 1; } if verified == 0 { - return Err(VerifyError::Sct(format!( + let detail = format!( "no SCT in the leaf cert's extension verified under any pinned CT log key (\ {} candidate(s) in list); last error: {}", sct_serialized_list.len(), last_err.unwrap_or_else(|| "unknown".into()) - ))); + ); + return Err(if saw_unknown_log { + VerifyError::MissingTrustMaterial { + check: "SCT", + detail, + } + } else { + VerifyError::Sct(detail) + }); } Ok(()) } diff --git a/crates/lpm-cli/src/sigstore_verify/tests/mod.rs b/crates/lpm-cli/src/sigstore_verify/tests/mod.rs index da6da77ac..2f7c5749c 100644 --- a/crates/lpm-cli/src/sigstore_verify/tests/mod.rs +++ b/crates/lpm-cli/src/sigstore_verify/tests/mod.rs @@ -1273,11 +1273,14 @@ fn rejects_bundle_with_unknown_rekor_log_id() { ) .expect_err("unknown logId must reject"); match err { - VerifyError::RekorSet(msg) => assert!( - msg.contains("no pinned Rekor key"), - "expected unknown-logId diagnostic, got: {msg}" + VerifyError::MissingTrustMaterial { + check: "Rekor SET", + detail, + } => assert!( + detail.contains("no pinned Rekor key"), + "expected unknown-logId diagnostic, got: {detail}" ), - other => panic!("expected VerifyError::RekorSet, got: {other:?}"), + other => panic!("expected Rekor SET MissingTrustMaterial, got: {other:?}"), } } @@ -1305,8 +1308,11 @@ fn rejects_bundle_with_rekor_key_outside_validity_at_integrated_time() { ) .expect_err("out-of-window key must reject"); let msg = match err { - VerifyError::RekorSet(msg) => msg, - other => panic!("expected VerifyError::RekorSet, got: {other:?}"), + VerifyError::MissingTrustMaterial { + check: "Rekor SET", + detail, + } => detail, + other => panic!("expected Rekor SET MissingTrustMaterial, got: {other:?}"), }; assert!( msg.contains("no pinned Rekor key"), @@ -2126,11 +2132,14 @@ fn rejects_inclusion_proof_with_wrong_pinned_rekor_key_for_log_id() { let err = verify_inclusion_proof(&tlog, std::slice::from_ref(&other_key)) .expect_err("logId without a pinned key must reject"); match err { - VerifyError::InclusionProof(msg) => assert!( - msg.contains("no pinned Rekor key"), - "expected unknown-logId diagnostic, got: {msg}" + VerifyError::MissingTrustMaterial { + check: "Rekor inclusion proof", + detail, + } => assert!( + detail.contains("no pinned Rekor key"), + "expected unknown-logId diagnostic, got: {detail}" ), - other => panic!("expected InclusionProof, got: {other:?}"), + other => panic!("expected inclusion-proof MissingTrustMaterial, got: {other:?}"), } } @@ -2244,11 +2253,14 @@ fn rejects_chain_when_top_cert_not_signed_by_any_trusted_root() { let err = verify_cert_chain(&chain, &roots, ts_year(2025)) .expect_err("chain to an untrusted root must reject"); match err { - VerifyError::Chain(msg) => assert!( - msg.contains("does not match any trusted Fulcio root"), - "expected anchor-rejection diagnostic, got: {msg}" + VerifyError::MissingTrustMaterial { + check: "X.509 chain", + detail, + } => assert!( + detail.contains("does not match any trusted Fulcio root"), + "expected anchor-rejection diagnostic, got: {detail}" ), - other => panic!("expected Chain, got: {other:?}"), + other => panic!("expected chain MissingTrustMaterial, got: {other:?}"), } } @@ -2319,10 +2331,13 @@ fn rejects_chain_when_no_trust_anchors_active_at_integrated_time() { let err = verify_cert_chain(&chain, &[], ts_year(2025)) .expect_err("empty trust-anchor set must reject"); match err { - VerifyError::Chain(msg) => { - assert!(msg.contains("no Fulcio roots active"), "got: {msg}") + VerifyError::MissingTrustMaterial { + check: "X.509 chain", + detail, + } => { + assert!(detail.contains("no Fulcio roots active"), "got: {detail}") } - other => panic!("expected Chain, got: {other:?}"), + other => panic!("expected chain MissingTrustMaterial, got: {other:?}"), } } @@ -2542,11 +2557,14 @@ fn rejects_anchor_lacking_ca_flag_during_try_anchor_signature_path() { // not "anchor misconfigured" (security through robust // failure mode). match err { - VerifyError::Chain(msg) => assert!( - msg.contains("does not match any trusted Fulcio root"), - "expected unanchored diagnostic, got: {msg}" + VerifyError::MissingTrustMaterial { + check: "X.509 chain", + detail, + } => assert!( + detail.contains("does not match any trusted Fulcio root"), + "expected unanchored diagnostic, got: {detail}" ), - other => panic!("expected VerifyError::Chain, got: {other:?}"), + other => panic!("expected chain MissingTrustMaterial, got: {other:?}"), } } @@ -2818,11 +2836,14 @@ fn rejects_sct_with_unknown_log_id() { ) .expect_err("unknown logId must reject"); match err { - VerifyError::Sct(msg) => assert!( - msg.contains("no SCT in the leaf cert's extension verified"), - "got: {msg}" + VerifyError::MissingTrustMaterial { + check: "SCT", + detail, + } => assert!( + detail.contains("no SCT in the leaf cert's extension verified"), + "got: {detail}" ), - other => panic!("expected VerifyError::Sct, got: {other:?}"), + other => panic!("expected SCT MissingTrustMaterial, got: {other:?}"), } } diff --git a/crates/lpm-cli/src/sigstore_verify/trust_root.rs b/crates/lpm-cli/src/sigstore_verify/trust_root.rs index 3621a38c4..dbb1436e0 100644 --- a/crates/lpm-cli/src/sigstore_verify/trust_root.rs +++ b/crates/lpm-cli/src/sigstore_verify/trust_root.rs @@ -2,7 +2,7 @@ use base64::Engine as _; use base64::engine::general_purpose::STANDARD as BASE64; use lpm_common::Timestamp; use lpm_common::timestamp::Duration; -use std::sync::{Arc, OnceLock}; +use std::sync::Arc; use std::time::SystemTime; use super::VerifyError; @@ -14,8 +14,8 @@ pub(super) const EMBEDDED_TRUST_ROOT_JSON: &[u8] = /// only — does not affect fail-closed behaviour. pub(super) const TRUST_ROOT_EXPIRY_WARN_DAYS: i64 = 30; -/// Vendored Sigstore trust root. Parsed once at startup from -/// `assets/sigstore_trusted_root.json` and cached via [`trust_root`]. +/// A parsed Sigstore trust root: the Fulcio certificate authorities, +/// Rekor logs and CT logs bundles are verified against. #[allow(dead_code)] #[derive(Debug)] pub struct TrustRoot { @@ -81,11 +81,47 @@ impl ValidityWindow { #[derive(Debug, serde::Deserialize)] struct TrustedRootJson { #[serde(rename = "certificateAuthorities", default)] - certificate_authorities: Vec, + certificate_authorities: Vec, #[serde(default)] - tlogs: Vec, + tlogs: Vec, #[serde(default)] - ctlogs: Vec, + ctlogs: Vec, +} + +fn deserialize_entry( + value: serde_json::Value, +) -> Result { + serde_json::from_value(value).map_err(|e| VerifyError::TrustRoot(format!("JSON parse: {e}"))) +} + +const FULCIO_ROLE: &str = "Fulcio CA"; +const REKOR_ROLE: &str = "Rekor signing key"; +const CT_LOG_ROLE: &str = "CT log key"; + +fn collect_entries( + values: Vec, + skipped: &mut Option>, + role: &'static str, + parse: impl Fn(serde_json::Value) -> Result, +) -> Result, VerifyError> { + let mut entries = Vec::with_capacity(values.len()); + for value in values { + match (parse(value), skipped.as_mut()) { + (Ok(entry), _) => entries.push(entry), + (Err(error), Some(skipped)) => { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + %error, + "skipping a Sigstore trust root entry this version can't read", + ); + if !skipped.contains(&role) { + skipped.push(role); + } + } + (Err(error), None) => return Err(error), + } + } + Ok(entries) } #[derive(Debug, serde::Deserialize)] @@ -150,47 +186,56 @@ impl From for ValidityWindow { #[allow(dead_code)] impl TrustRoot { /// Parse a trust root from raw JSON bytes. Pure — no I/O, no - /// global state. Use [`trust_root`] for the production - /// embedded-bytes entry; this is the test seam and is also - /// available for future code that wants to consume a non-embedded - /// root. Callers that accept non-embedded roots must preserve the - /// same fail-closed validation semantics as the embedded path. + /// global state. Use [`trust_root`] for the one verification + /// uses; bytes passed here must come from the binary or from + /// Sigstore's TUF repository through [`super::tuf`]. pub fn parse(bytes: &[u8]) -> Result { + Self::parse_entries(bytes, &mut None) + } + + /// Parse a trust root from Sigstore's TUF repository, skipping any + /// entry this version can't read rather than refusing the whole + /// root. Sigstore can add entries in shapes newer than this + /// version, and the entries it can read must stay usable. + /// + /// Also returns the roles, named as [`Self::check_expiry`] names + /// them, that had an entry skipped. + pub fn parse_skipping_unreadable( + bytes: &[u8], + ) -> Result<(TrustRoot, Vec<&'static str>), VerifyError> { + let mut skipped = Some(Vec::new()); + let root = Self::parse_entries(bytes, &mut skipped)?; + Ok((root, skipped.unwrap_or_default())) + } + + /// `skipped` is `None` to refuse an unreadable entry, or collects the + /// roles whose unreadable entries were skipped. + fn parse_entries( + bytes: &[u8], + skipped: &mut Option>, + ) -> Result { let raw: TrustedRootJson = serde_json::from_slice(bytes) .map_err(|e| VerifyError::TrustRoot(format!("JSON parse: {e}")))?; - - let fulcio_roots = raw - .certificate_authorities - .into_iter() - .map(parse_fulcio_root) - .collect::, _>>()?; - - let rekor_keys = raw - .tlogs - .into_iter() - .map(parse_log_key) - .collect::, _>>()? - .into_iter() - .map(|(log_id, spki_der, valid_for)| RekorKey { + let fulcio_roots = + collect_entries(raw.certificate_authorities, skipped, FULCIO_ROLE, |value| { + parse_fulcio_root(deserialize_entry(value)?) + })?; + let rekor_keys = collect_entries(raw.tlogs, skipped, REKOR_ROLE, |value| { + let (log_id, spki_der, valid_for) = parse_log_key(deserialize_entry(value)?)?; + Ok(RekorKey { log_id, spki_der, valid_for, }) - .collect(); - - let ctlog_keys = raw - .ctlogs - .into_iter() - .map(parse_log_key) - .collect::, _>>()? - .into_iter() - .map(|(log_id, spki_der, valid_for)| CtLogKey { + })?; + let ctlog_keys = collect_entries(raw.ctlogs, skipped, CT_LOG_ROLE, |value| { + let (log_id, spki_der, valid_for) = parse_log_key(deserialize_entry(value)?)?; + Ok(CtLogKey { log_id, spki_der, valid_for, }) - .collect(); - + })?; Ok(TrustRoot { fulcio_roots, rekor_keys, @@ -234,16 +279,7 @@ impl TrustRoot { /// `start <= now` and (`end is None` OR `end > now`). Retired /// entries (end <= now) don't count. pub fn check_expiry(&self, now: SystemTime) -> Result<(), VerifyError> { - let mut missing: Vec<&str> = Vec::new(); - if !self.fulcio_roots.iter().any(|r| r.valid_for.contains(now)) { - missing.push("Fulcio CA"); - } - if !self.rekor_keys.iter().any(|k| k.valid_for.contains(now)) { - missing.push("Rekor signing key"); - } - if !self.ctlog_keys.iter().any(|k| k.valid_for.contains(now)) { - missing.push("CT log key"); - } + let missing = self.roles_without_active_key(now); if missing.is_empty() { return Ok(()); } @@ -252,6 +288,36 @@ impl TrustRoot { }) } + /// The roles with no entry at all, active or retired. + pub fn roles_without_entries(&self) -> Vec<&'static str> { + let mut empty = Vec::new(); + if self.fulcio_roots.is_empty() { + empty.push(FULCIO_ROLE); + } + if self.rekor_keys.is_empty() { + empty.push(REKOR_ROLE); + } + if self.ctlog_keys.is_empty() { + empty.push(CT_LOG_ROLE); + } + empty + } + + /// The roles with no key active at `now`. + pub fn roles_without_active_key(&self, now: SystemTime) -> Vec<&'static str> { + let mut missing = Vec::new(); + if !self.fulcio_roots.iter().any(|r| r.valid_for.contains(now)) { + missing.push(FULCIO_ROLE); + } + if !self.rekor_keys.iter().any(|k| k.valid_for.contains(now)) { + missing.push(REKOR_ROLE); + } + if !self.ctlog_keys.iter().any(|k| k.valid_for.contains(now)) { + missing.push(CT_LOG_ROLE); + } + missing + } + /// Soonest "next currently-active key retirement" date. Per /// role, the role's retirement date is the LATEST `end` among /// currently-active keys (because the artifact remains useful @@ -286,9 +352,9 @@ impl TrustRoot { } /// Whether [`Self::next_role_retirement_at`] is within - /// `TRUST_ROOT_EXPIRY_WARN_DAYS` of `now`. Used by [`trust_root`]'s - /// startup `tracing::warn`. Returns `None` when no anchor or - /// when the anchor is further out than the warn window. + /// `TRUST_ROOT_EXPIRY_WARN_DAYS` of `now`, for the trust store's + /// diagnostic log when it loads a trust root. Returns `None` when no + /// anchor or when the anchor is further out than the warn window. pub fn within_warn_window(&self, now: SystemTime) -> Option { let soonest = self.next_role_retirement_at(now)?; let now_dt: Timestamp = now.into(); @@ -330,45 +396,9 @@ fn parse_log_key(raw: TrustedRootLog) -> Result<(Vec, Vec, ValidityWindo Ok((log_id, spki_der, raw.public_key.valid_for.into())) } -/// Cached parsed trust root, populated on first [`trust_root`] call. -static TRUST_ROOT_CELL: OnceLock, String>> = OnceLock::new(); - -/// Production accessor: lazily loads the embedded trust root, runs -/// the startup expiry check, and emits the 30-day warn if applicable. -/// Subsequent calls return a cheap `Arc::clone` of the cached root. -/// -/// Error semantics: parse failures and post-expiry rejection are both -/// surfaced via the cached `Err` variant — once this function -/// returns an error for the process lifetime, it always will. That's -/// load-bearing: a verifier path that succeeded the first call must -/// not silently start failing mid-install because something flapped. -#[allow(dead_code)] // wired into provenance_bundle +/// The trust root verification uses: the newest one Sigstore's TUF +/// repository has delivered to this machine, or the one built into the +/// binary. See [`super::trust_store`]. pub fn trust_root() -> Result, VerifyError> { - let cached = TRUST_ROOT_CELL.get_or_init(|| { - let parsed = - TrustRoot::parse(EMBEDDED_TRUST_ROOT_JSON).map_err(|e| format!("parse failed: {e}"))?; - let now = SystemTime::now(); - - if let Some(expires) = parsed.within_warn_window(now) { - tracing::warn!( - target: "lpm_cli::sigstore_verify", - expires_at = %expires.to_plain_utc(), - "vendored Sigstore trust root expires within {} days; update lpm to refresh", - TRUST_ROOT_EXPIRY_WARN_DAYS, - ); - } - - if let Err(VerifyError::TrustRootExpired { missing_roles }) = parsed.check_expiry(now) { - return Err(format!( - "vendored Sigstore trust root has no currently-active key for role(s) \ - {missing_roles}; update lpm to refresh" - )); - } - - Ok(Arc::new(parsed)) - }); - match cached { - Ok(arc) => Ok(Arc::clone(arc)), - Err(msg) => Err(VerifyError::TrustRoot(msg.clone())), - } + super::trust_store::global().current() } diff --git a/crates/lpm-cli/src/sigstore_verify/trust_store.rs b/crates/lpm-cli/src/sigstore_verify/trust_store.rs new file mode 100644 index 000000000..74f9d67e9 --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/trust_store.rs @@ -0,0 +1,544 @@ +//! Which Sigstore trust root verification uses, and how it stays current. +//! +//! Verification uses the newest trust root this machine holds: one that +//! Sigstore's TUF repository delivered on an earlier run and that still +//! verifies, or the one built into the binary when that is newer or nothing +//! usable is cached. When a bundle needs a key or certificate authority that +//! trust root lacks, the store fetches Sigstore's current trust root, at most +//! once an hour, and verifies again. Self-update fetches it before +//! verifying a release, so keys Sigstore has retired stop counting there. +//! +//! A failed fetch never weakens verification: the store keeps the trust root +//! it had, which is never older than the one built into the binary. + +use super::bundle::verify_sigstore_bundle_with; +use super::trust_root::EMBEDDED_TRUST_ROOT_JSON; +use super::tuf::{self, Fetcher, Freshness, TrustedMetadata}; +use super::{IdentityExpectations, TrustRoot, VerifiedProvenance, VerifyError, VerifyOptions}; +use serde::{Deserialize, Serialize}; +use std::borrow::Cow; +use std::io::Read; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock}; +use std::time::{Duration, Instant, SystemTime}; + +/// Version of Sigstore's targets metadata that signed the trust root built +/// into the binary. A cached trust root from older targets metadata is +/// ignored. +pub(crate) const EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION: u64 = 14; + +const EMBEDDED_TUF_ROOT: &[u8] = include_bytes!("../../assets/sigstore_tuf_root.json"); + +const DEFAULT_REPOSITORY_URL: &str = "https://tuf-repo-cdn.sigstore.dev"; + +/// Points refreshes at a mirror of Sigstore's TUF repository, or turns them +/// off with `off`. Everything fetched is verified against the TUF root built +/// into the binary, so a mirror can withhold updates but can't forge them. +pub(crate) const REPOSITORY_URL_OVERRIDE_ENV: &str = "LPM_SIGSTORE_TUF_URL_OVERRIDE"; + +const CACHE_FILE_NAME: &str = "sigstore-trust.json"; +const CACHE_SCHEMA_VERSION: u32 = 1; +const CACHE_MAX_BYTES: u64 = 16 * 1024 * 1024; + +/// How long one fetch's outcome stands before a signature that needs newer +/// keys may fetch again. Most commands finish well within it; it bounds what +/// a long-running process, such as an MCP server, misses. +const REFETCH_AFTER: Duration = Duration::from_secs(60 * 60); + +/// How long a failed fetch's outcome stands, so a long-running process +/// recovers soon after the network does. +const RETRY_FAILED_FETCH_AFTER: Duration = Duration::from_secs(60); + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +const REFRESH_TIMEOUT: Duration = Duration::from_secs(30); + +/// When a verification fetches Sigstore's current trust root. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrustRefresh { + /// Fetch it before verifying, so keys Sigstore has retired since the + /// trust root this machine holds stop counting. A failed fetch falls + /// back to the trust root already held. + BeforeVerifying, + /// Fetch it only when the trust root held lacks a key or certificate + /// authority the bundle needs. + WhenMissing, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Repository { + Url(String), + Disabled, +} + +#[derive(Serialize, Deserialize)] +struct CacheFile { + schema_version: u32, + /// When a process fetched this metadata, in seconds since the Unix + /// epoch. Other processes skip their own fetch within + /// [`REFETCH_AFTER`] of it. + fetched_at: u64, + metadata: TrustedMetadata, +} + +pub(crate) struct TrustStore { + embedded_tuf_root: Cow<'static, [u8]>, + embedded_trusted_root: Cow<'static, [u8]>, + embedded_targets_version: u64, + cache_file: Option, + repository: Repository, + current: RwLock>>, + last_fetch: tokio::sync::Mutex)>>, + /// The last metadata this process verified, the rollback baseline when + /// the cache can't be written or another process wrote an older one. + last_metadata: Mutex>, +} + +/// The store every verification in this process shares. +pub(crate) fn global() -> &'static TrustStore { + static STORE: OnceLock = OnceLock::new(); + STORE.get_or_init(TrustStore::from_environment) +} + +/// Verify `body` like [`super::verify_sigstore_bundle`], fetching +/// Sigstore's current trust root as `refresh` says. +pub async fn verify_sigstore_bundle_refreshing( + body: &[u8], + expectations: &IdentityExpectations, + options: VerifyOptions, + refresh: TrustRefresh, +) -> Result { + global().verify(body, expectations, options, refresh).await +} + +/// Verify `body` against the trust root built into this binary, ignoring +/// any fetched one. The release gate uses it, so a release it accepts +/// verifies even on a machine that has never reached Sigstore's repository. +pub fn verify_sigstore_bundle_with_built_in_trust_root( + body: &[u8], + expectations: &IdentityExpectations, + options: VerifyOptions, +) -> Result { + let built_in = TrustRoot::parse(EMBEDDED_TRUST_ROOT_JSON)?; + verify_sigstore_bundle_with(body, expectations, options, &built_in) +} + +impl TrustStore { + fn from_environment() -> Self { + // Unit tests build their own stores; the shared one must not read + // the developer's cache, so it verifies with the built-in root. + let cache_file = (!cfg!(test)) + .then(|| lpm_common::LpmRoot::from_env().ok()) + .flatten() + .map(|root| root.cache_metadata().join(CACHE_FILE_NAME)); + Self { + embedded_tuf_root: Cow::Borrowed(EMBEDDED_TUF_ROOT), + embedded_trusted_root: Cow::Borrowed(EMBEDDED_TRUST_ROOT_JSON), + embedded_targets_version: EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION, + cache_file, + repository: repository_from_environment(), + current: RwLock::new(None), + last_fetch: tokio::sync::Mutex::new(None), + last_metadata: Mutex::new(None), + } + } + + /// The trust root verification uses now. + pub(crate) fn current(&self) -> Result, VerifyError> { + if let Some(root) = self + .current + .read() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + { + return Ok(Arc::clone(root)); + } + let loaded = Arc::new(self.load()?); + let mut slot = self.current.write().unwrap_or_else(PoisonError::into_inner); + Ok(Arc::clone(slot.get_or_insert(loaded))) + } + + pub(crate) async fn verify( + &self, + body: &[u8], + expectations: &IdentityExpectations, + options: VerifyOptions, + refresh: TrustRefresh, + ) -> Result { + if refresh == TrustRefresh::BeforeVerifying + && let Err(error) = self.refresh().await + { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + %error, + "verifying with the Sigstore trust root this machine holds", + ); + } + let used = self.current()?; + let missing = match verify_sigstore_bundle_with(body, expectations, options, &used) { + Err(error) if error.is_missing_trust_material() => error, + outcome => return outcome, + }; + let refreshed = self.refresh().await; + let latest = self.current()?; + if !Arc::ptr_eq(&used, &latest) { + return verify_sigstore_bundle_with(body, expectations, options, &latest); + } + match refreshed { + Ok(()) => Err(missing), + Err(refresh) => Err(VerifyError::TrustRootNotRefreshed { + error: Box::new(missing), + refresh, + }), + } + } + + /// Fetch Sigstore's current trust root and use it from now on. + /// + /// Concurrent calls share one fetch. A call within [`REFETCH_AFTER`] of + /// a fetch in this process, or within [`RETRY_FAILED_FETCH_AFTER`] of a + /// failed one, returns that outcome. When another process cached a fetch + /// within [`REFETCH_AFTER`], its trust root is used without fetching. + async fn refresh(&self) -> Result<(), String> { + let mut last_fetch = self.last_fetch.lock().await; + if let Some((at, outcome)) = last_fetch.as_ref() { + let stands_for = if outcome.is_ok() { + REFETCH_AFTER + } else { + RETRY_FAILED_FETCH_AFTER + }; + if at.elapsed() < stands_for { + return outcome.clone(); + } + } + let outcome = match self.recently_fetched_root() { + Some(root) => { + *self.current.write().unwrap_or_else(PoisonError::into_inner) = + Some(Arc::new(root)); + Ok(()) + } + None => self.fetch_current().await, + }; + *last_fetch = Some((Instant::now(), outcome.clone())); + outcome + } + + async fn fetch_current(&self) -> Result<(), String> { + let Repository::Url(url) = &self.repository else { + return Err(format!( + "fetching it is turned off by {REPOSITORY_URL_OVERRIDE_ENV}=off" + )); + }; + let fetcher = HttpFetcher::new(url)?; + let stored = self.newest_stored_metadata(); + let metadata = tokio::time::timeout( + REFRESH_TIMEOUT, + tuf::refresh( + &self.embedded_tuf_root, + stored.as_ref(), + &fetcher, + SystemTime::now(), + ), + ) + .await + .map_err(|_| { + format!( + "{url} didn't finish answering within {} seconds", + REFRESH_TIMEOUT.as_secs() + ) + })? + .map_err(|error| error.to_string())?; + let verified = metadata + .verified_trusted_root(&self.embedded_tuf_root) + .map_err(|error| error.to_string())?; + if verified.targets_version < self.embedded_targets_version { + return Err(format!( + "{url} serves targets metadata version {}, older than the version {} \ + that signed the trust root built into LPM", + verified.targets_version, self.embedded_targets_version + )); + } + let root = usable_trust_root(&verified.bytes, SystemTime::now())?; + *self + .last_metadata + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(metadata.clone()); + self.write_cache(metadata).await; + *self.current.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(root)); + tracing::debug!( + target: "lpm_cli::sigstore_verify", + targets_version = verified.targets_version, + "using Sigstore's current trust root", + ); + Ok(()) + } + + fn load(&self) -> Result { + let root = match self + .read_cache_file() + .and_then(|cache| self.usable_cached_root(cache)) + { + Some(root) => root, + None => TrustRoot::parse(&self.embedded_trusted_root)?, + }; + if let Some(retires) = root.within_warn_window(SystemTime::now()) { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + retires_at = %retires.to_plain_utc(), + "a role in the Sigstore trust root in use retires soon; \ + a signature that needs a newer key fetches Sigstore's current trust root", + ); + } + Ok(root) + } + + /// The cached trust root, if a process cached it within + /// [`REFETCH_AFTER`] and it is one this store would use. + fn recently_fetched_root(&self) -> Option { + let cache = self.read_cache_file()?; + let now = lpm_common::Timestamp::now().unix_seconds(); + let age = u64::try_from(now).ok()?.checked_sub(cache.fetched_at)?; + if age >= REFETCH_AFTER.as_secs() { + return None; + } + self.usable_cached_root(cache) + } + + /// The trust root a cache file holds, when it verifies against the + /// built-in TUF root, is no older than the built-in trust root, and has a + /// usable key for every role. + fn usable_cached_root(&self, cache: CacheFile) -> Option { + let ignore = |error: String| { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + %error, + "ignoring the cached Sigstore trust root", + ); + }; + let cached = cache + .metadata + .verified_trusted_root(&self.embedded_tuf_root) + .map_err(|error| ignore(error.to_string())) + .ok()?; + if cached.targets_version < self.embedded_targets_version { + return None; + } + usable_trust_root(&cached.bytes, SystemTime::now()) + .map_err(ignore) + .ok() + } + + fn read_cached_metadata(&self) -> Option { + self.read_cache_file().map(|cache| cache.metadata) + } + + fn read_cache_file(&self) -> Option { + let path = self.cache_file.as_ref()?; + let file = match std::fs::File::open(path) { + Ok(file) => file, + Err(error) => { + if error.kind() != std::io::ErrorKind::NotFound { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + path = %path.display(), + %error, + "can't read the cached Sigstore trust root", + ); + } + return None; + } + }; + let mut bytes = Vec::new(); + file.take(CACHE_MAX_BYTES + 1) + .read_to_end(&mut bytes) + .ok()?; + if bytes.len() as u64 > CACHE_MAX_BYTES { + return None; + } + let cache: CacheFile = serde_json::from_slice(&bytes).ok()?; + (cache.schema_version == CACHE_SCHEMA_VERSION).then_some(cache) + } + + /// The newer of the cached metadata and what this process last verified, + /// whichever still verifies. + fn newest_stored_metadata(&self) -> Option { + let in_memory = self + .last_metadata + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + [self.read_cached_metadata(), in_memory] + .into_iter() + .flatten() + .filter_map(|metadata| Some((self.freshness(&metadata)?, metadata))) + .max_by_key(|(freshness, _)| *freshness) + .map(|(_, metadata)| metadata) + } + + fn freshness(&self, metadata: &TrustedMetadata) -> Option { + metadata.freshness(&self.embedded_tuf_root).ok() + } + + /// Cache `metadata` unless another process already cached newer + /// metadata, so concurrent fetches that finish out of order never roll + /// the cache back. + async fn write_cache(&self, metadata: TrustedMetadata) { + let Some(path) = &self.cache_file else { + return; + }; + let Some(ours) = self.freshness(&metadata) else { + return; + }; + let written = async { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(lpm_common::LpmError::Io)?; + } + lpm_common::with_exclusive_lock_async(path.with_extension("lock"), async { + let cached = self + .read_cached_metadata() + .and_then(|cached| self.freshness(&cached)); + if cached.is_some_and(|cached| cached > ours) { + return Ok(()); + } + let cache = CacheFile { + schema_version: CACHE_SCHEMA_VERSION, + fetched_at: u64::try_from(lpm_common::Timestamp::now().unix_seconds()) + .unwrap_or_default(), + metadata, + }; + let bytes = serde_json::to_vec(&cache) + .map_err(|error| lpm_common::LpmError::Io(std::io::Error::other(error)))?; + if bytes.len() as u64 > CACHE_MAX_BYTES { + return Ok(()); + } + lpm_common::write_file_atomic_with_options( + path, + bytes, + lpm_common::AtomicWriteOptions::new().unix_mode(0o600), + ) + .map_err(lpm_common::LpmError::Io) + }) + .await + } + .await; + if let Err(error) = written { + tracing::debug!( + target: "lpm_cli::sigstore_verify", + path = %path.display(), + %error, + "can't cache Sigstore's current trust root; the next run fetches it again", + ); + } + } +} + +/// Parse a trust root Sigstore's repository delivered, refusing one in which +/// a role has no usable key because its entries are missing or in a form +/// this version can't read, as after a schema change. Using it would fail +/// every verification the held trust root still passes. A role whose +/// readable keys Sigstore retired is a decision, and stands. +fn usable_trust_root(bytes: &[u8], now: SystemTime) -> Result { + let (root, skipped) = + TrustRoot::parse_skipping_unreadable(bytes).map_err(|error| error.to_string())?; + let empty = root.roles_without_entries(); + let unusable: Vec<&str> = root + .roles_without_active_key(now) + .into_iter() + .filter(|role| skipped.contains(role) || empty.contains(role)) + .collect(); + if unusable.is_empty() { + Ok(root) + } else { + Err(format!( + "it has no {} entry this version of LPM can read", + unusable.join(", ") + )) + } +} + +fn repository_from_environment() -> Repository { + // Unit tests build their own stores; the shared one never reaches the + // network. + if cfg!(test) { + return Repository::Disabled; + } + repository_from_override(std::env::var(REPOSITORY_URL_OVERRIDE_ENV).ok()) +} + +fn repository_from_override(value: Option) -> Repository { + let Some(value) = value.filter(|value| !value.is_empty()) else { + return Repository::Url(DEFAULT_REPOSITORY_URL.to_string()); + }; + if value.eq_ignore_ascii_case("off") { + return Repository::Disabled; + } + let shown = crate::install_ui::safe_url_origin(&value); + if crate::release_lookup::accept_override(&value) { + tracing::warn!( + env_var = REPOSITORY_URL_OVERRIDE_ENV, + override_url = %shown, + "fetching Sigstore's trust root from an overridden repository", + ); + Repository::Url(value) + } else { + tracing::warn!( + env_var = REPOSITORY_URL_OVERRIDE_ENV, + override_url = %shown, + "ignoring a Sigstore repository override that is neither https:// nor loopback", + ); + Repository::Url(DEFAULT_REPOSITORY_URL.to_string()) + } +} + +struct HttpFetcher { + client: reqwest::Client, + base: String, +} + +impl HttpFetcher { + fn new(base: &str) -> Result { + let client = lpm_http::client_builder() + .https_only( + reqwest::Url::parse(base) + .map_err(|error| error.to_string())? + .scheme() + == "https", + ) + .connect_timeout(CONNECT_TIMEOUT) + .timeout(REQUEST_TIMEOUT) + .build() + .map_err(|error| error.to_string())?; + Ok(Self { + client, + base: base.trim_end_matches('/').to_string(), + }) + } +} + +impl Fetcher for HttpFetcher { + async fn fetch(&self, path: &str, max_bytes: u64) -> Result>, String> { + let response = self + .client + .get(format!("{}/{path}", self.base)) + .send() + .await + .map_err(|error| error.to_string())?; + let status = response.status(); + // TUF clients read both as "no such file": some static hosts answer + // 403 for a missing object. + if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::FORBIDDEN { + return Ok(None); + } + if !status.is_success() { + return Err(format!("HTTP {status}")); + } + let cap = usize::try_from(max_bytes).unwrap_or(usize::MAX); + lpm_http::read_body_capped(response, cap) + .await + .map(Some) + .map_err(|error| error.to_string()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/lpm-cli/src/sigstore_verify/trust_store/tests.rs b/crates/lpm-cli/src/sigstore_verify/trust_store/tests.rs new file mode 100644 index 000000000..463757cea --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/trust_store/tests.rs @@ -0,0 +1,725 @@ +use super::*; +use crate::sigstore_verify::tuf::test_support::{RoleSet, repository_files}; +use std::collections::BTreeMap; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +const AXIOS_BUNDLE: &[u8] = + include_bytes!("../../../tests/fixtures/sigstore_bundles/20-real-npm-axios-1.14.0.json"); + +/// The built-in trust root without the Rekor log that recorded the axios +/// bundle: what a copy of LPM built before Sigstore added that log holds. +fn trust_root_without_the_axios_log() -> Vec { + let mut root: serde_json::Value = serde_json::from_slice(EMBEDDED_TRUST_ROOT_JSON).unwrap(); + let logs = root["tlogs"].as_array_mut().unwrap(); + let before = logs.len(); + logs.retain(|log| log["baseUrl"] != "https://rekor.sigstore.dev"); + assert_eq!(logs.len(), before - 1); + serde_json::to_vec(&root).unwrap() +} + +async fn serve(files: BTreeMap>) -> MockServer { + let server = MockServer::start().await; + mount(&server, files).await; + server +} + +async fn mount(server: &MockServer, files: BTreeMap>) { + for (file, bytes) in files { + Mock::given(method("GET")) + .and(path(format!("/{file}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes)) + .mount(server) + .await; + } +} + +/// A repository that serves `trusted_root` under targets version +/// `targets_version`. +async fn sigstore_serving( + roles: &RoleSet, + trusted_root: &[u8], + targets_version: u64, +) -> MockServer { + serve(repository_files( + roles, + targets_version, + targets_version, + targets_version, + trusted_root, + )) + .await +} + +async fn failing_repository() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(500)) + .mount(&server) + .await; + server +} + +fn store_holding( + roles: &RoleSet, + held: Vec, + embedded_targets_version: u64, + cache_file: Option, + repository: Repository, +) -> TrustStore { + TrustStore { + embedded_tuf_root: Cow::Owned(roles.signed_root(1)), + embedded_trusted_root: Cow::Owned(held), + embedded_targets_version, + cache_file, + repository, + current: RwLock::new(None), + last_fetch: tokio::sync::Mutex::new(None), + last_metadata: Mutex::new(None), + } +} + +async fn verify_axios( + store: &TrustStore, + refresh: TrustRefresh, +) -> Result { + store + .verify( + AXIOS_BUNDLE, + &IdentityExpectations::none(), + VerifyOptions::npm_attestation(), + refresh, + ) + .await +} + +fn assert_missing_rekor_key(error: &VerifyError) { + assert!( + matches!( + error, + VerifyError::MissingTrustMaterial { + check: "Rekor SET", + .. + } + ), + "{error:?}" + ); +} + +async fn timestamp_requests(server: &MockServer) -> usize { + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|request| request.url.path() == "/timestamp.json") + .count() +} + +#[tokio::test] +async fn a_bundle_from_a_log_the_held_root_lacks_verifies_after_fetching_sigstores_current_root() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let cache = tempfile::tempdir().unwrap(); + let cache_file = cache.path().join("metadata").join(CACHE_FILE_NAME); + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(server.uri()), + ); + + verify_axios(&store, TrustRefresh::WhenMissing) + .await + .expect("the fetched trust root holds the log"); + + let offline = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file), + Repository::Disabled, + ); + verify_axios(&offline, TrustRefresh::WhenMissing) + .await + .expect("the cached trust root holds the log"); +} + +#[tokio::test] +async fn the_held_root_alone_does_not_verify_a_bundle_from_a_log_it_lacks() { + let roles = RoleSet::new(); + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + None, + Repository::Disabled, + ); + + let error = verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + + let VerifyError::TrustRootNotRefreshed { error, refresh } = error else { + panic!("{error:?}"); + }; + assert_missing_rekor_key(&error); + assert!( + refresh.contains(&format!("{REPOSITORY_URL_OVERRIDE_ENV}=off")), + "{refresh}" + ); +} + +#[tokio::test] +async fn a_failed_fetch_keeps_the_held_root_and_says_why() { + let roles = RoleSet::new(); + let server = failing_repository().await; + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + None, + Repository::Url(server.uri()), + ); + + let error = verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + + let VerifyError::TrustRootNotRefreshed { error, refresh } = error else { + panic!("{error:?}"); + }; + assert_missing_rekor_key(&error); + assert!(refresh.contains("HTTP 500"), "{refresh}"); +} + +#[tokio::test] +async fn a_failed_fetch_before_verifying_falls_back_to_the_held_root() { + let roles = RoleSet::new(); + let server = failing_repository().await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + + verify_axios(&store, TrustRefresh::BeforeVerifying) + .await + .expect("the held trust root verifies the bundle"); + + let asked = server.received_requests().await.unwrap(); + assert_eq!(asked.len(), 1, "{asked:?}"); + assert_eq!(asked[0].url.path(), "/2.root.json"); +} + +#[tokio::test] +async fn sigstores_current_root_is_fetched_at_most_once_an_hour() { + let roles = RoleSet::new(); + let stale = trust_root_without_the_axios_log(); + let server = sigstore_serving(&roles, &stale, 1).await; + let store = store_holding(&roles, stale, 1, None, Repository::Url(server.uri())); + + for _ in 0..2 { + let error = verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + assert_missing_rekor_key(&error); + } + + assert_eq!(timestamp_requests(&server).await, 1); +} + +#[tokio::test] +async fn a_cached_trust_root_that_no_longer_verifies_is_ignored() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let cache = tempfile::tempdir().unwrap(); + let cache_file = cache.path().join(CACHE_FILE_NAME); + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(server.uri()), + ); + verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap(); + let mut cached: CacheFile = + serde_json::from_slice(&std::fs::read(&cache_file).unwrap()).unwrap(); + cached.metadata.trusted_root = cached.metadata.trusted_root.replacen("rekor", "rekr", 1); + std::fs::write(&cache_file, serde_json::to_vec(&cached).unwrap()).unwrap(); + + let offline = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file), + Repository::Disabled, + ); + let error = verify_axios(&offline, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + + assert!( + matches!(error, VerifyError::TrustRootNotRefreshed { .. }), + "{error:?}" + ); +} + +#[tokio::test] +async fn a_cached_trust_root_older_than_the_built_in_one_is_ignored() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let cache = tempfile::tempdir().unwrap(); + let cache_file = cache.path().join(CACHE_FILE_NAME); + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(server.uri()), + ); + verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap(); + + let newer_binary = store_holding( + &roles, + trust_root_without_the_axios_log(), + 2, + Some(cache_file), + Repository::Disabled, + ); + let error = verify_axios(&newer_binary, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + + assert!( + matches!(error, VerifyError::TrustRootNotRefreshed { .. }), + "{error:?}" + ); +} + +#[tokio::test] +async fn a_repository_older_than_the_built_in_trust_root_is_not_used() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 2, + None, + Repository::Url(server.uri()), + ); + + let error = verify_axios(&store, TrustRefresh::WhenMissing) + .await + .unwrap_err(); + + let VerifyError::TrustRootNotRefreshed { refresh, .. } = error else { + panic!("{error:?}"); + }; + assert!(refresh.contains("older than"), "{refresh}"); +} + +const LPM_RELEASE_BUNDLE: &[u8] = + include_bytes!("../../../tests/fixtures/sigstore_bundles/21-real-lpm-release-v0.84.0.json"); + +async fn verify_lpm_release( + store: &TrustStore, + refresh: TrustRefresh, +) -> Result { + let release_workflow = IdentityExpectations { + expected_issuer: Some("https://token.actions.githubusercontent.com".into()), + expected_san_uri_prefix: Some("https://github.com/lpm-dev/rust-client/".into()), + expected_workflow_path: Some(".github/workflows/release.yml".into()), + }; + store + .verify( + LPM_RELEASE_BUNDLE, + &release_workflow, + VerifyOptions::strict(), + refresh, + ) + .await +} + +#[tokio::test] +async fn a_release_signed_after_sigstore_added_a_log_verifies_on_a_copy_built_before() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + None, + Repository::Url(server.uri()), + ); + + verify_lpm_release(&store, TrustRefresh::BeforeVerifying) + .await + .expect("the fetched trust root holds the log that recorded the release"); +} + +/// The built-in trust root with the log that recorded the bundles retired +/// before they were signed, as Sigstore would publish it after retiring a +/// compromised key. +fn trust_root_retiring_the_axios_log() -> Vec { + let mut root: serde_json::Value = serde_json::from_slice(EMBEDDED_TRUST_ROOT_JSON).unwrap(); + let log = root["tlogs"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|log| log["baseUrl"] == "https://rekor.sigstore.dev") + .unwrap(); + log["publicKey"]["validFor"]["end"] = serde_json::json!("2022-01-01T00:00:00Z"); + serde_json::to_vec(&root).unwrap() +} + +#[tokio::test] +async fn a_log_key_sigstore_retired_stops_counting_when_fetching_before_verifying() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, &trust_root_retiring_the_axios_log(), 1).await; + let store = |repository| { + store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + repository, + ) + }; + + let error = verify_lpm_release( + &store(Repository::Url(server.uri())), + TrustRefresh::BeforeVerifying, + ) + .await + .unwrap_err(); + assert_missing_rekor_key(&error); + + verify_lpm_release( + &store(Repository::Url(server.uri())), + TrustRefresh::WhenMissing, + ) + .await + .expect("without fetching first, the held trust root still counts the key"); +} + +#[tokio::test] +async fn a_release_verifies_with_the_held_root_when_sigstores_repository_fails() { + let roles = RoleSet::new(); + let server = failing_repository().await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + + verify_lpm_release(&store, TrustRefresh::BeforeVerifying) + .await + .expect("the held trust root verifies the release"); +} + +/// The built-in trust root with every CT log entry in a shape this version +/// can't read, as a future schema change might publish them. +fn trust_root_with_unreadable_ct_logs() -> Vec { + let mut root: serde_json::Value = serde_json::from_slice(EMBEDDED_TRUST_ROOT_JSON).unwrap(); + for log in root["ctlogs"].as_array_mut().unwrap() { + log["publicKey"] = serde_json::json!({"keyDetails": "PKIX_FUTURE", "validFor": {"start": "2022-10-20T00:00:00Z"}}); + } + serde_json::to_vec(&root).unwrap() +} + +/// The built-in trust root with every CT log retired. +fn trust_root_retiring_every_ct_log() -> Vec { + let mut root: serde_json::Value = serde_json::from_slice(EMBEDDED_TRUST_ROOT_JSON).unwrap(); + for log in root["ctlogs"].as_array_mut().unwrap() { + log["publicKey"]["validFor"]["end"] = serde_json::json!("2023-01-01T00:00:00Z"); + } + serde_json::to_vec(&root).unwrap() +} + +#[tokio::test] +async fn a_fetched_trust_root_this_version_cannot_use_keeps_the_held_one() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, &trust_root_with_unreadable_ct_logs(), 1).await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + + verify_lpm_release(&store, TrustRefresh::BeforeVerifying) + .await + .expect("the held trust root still verifies the release"); + + let refresh = store.refresh().await.unwrap_err(); + assert!(refresh.contains("CT log"), "{refresh}"); +} + +#[tokio::test] +async fn a_role_sigstore_retired_entirely_stops_counting() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, &trust_root_retiring_every_ct_log(), 1).await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + + let error = verify_lpm_release(&store, TrustRefresh::BeforeVerifying) + .await + .unwrap_err(); + + assert!( + matches!(error, VerifyError::TrustRootExpired { .. }), + "{error:?}" + ); +} + +#[tokio::test] +async fn an_older_fetch_never_replaces_a_newer_cached_trust_root() { + let roles = RoleSet::new(); + let newer = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 2).await; + let older = sigstore_serving(&roles, &trust_root_without_the_axios_log(), 1).await; + let cache = tempfile::tempdir().unwrap(); + let cache_file = cache.path().join(CACHE_FILE_NAME); + let slower = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(older.uri()), + ); + let fetched_before_the_update = tuf::refresh( + &roles.signed_root(1), + None, + &HttpFetcher::new(&older.uri()).unwrap(), + SystemTime::now(), + ) + .await + .unwrap(); + let faster = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(newer.uri()), + ); + verify_axios(&faster, TrustRefresh::WhenMissing) + .await + .unwrap(); + + slower.write_cache(fetched_before_the_update).await; + + let offline = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file), + Repository::Disabled, + ); + verify_axios(&offline, TrustRefresh::WhenMissing) + .await + .expect("the cache still holds the newer trust root"); +} + +#[tokio::test] +async fn a_process_that_cannot_cache_still_refuses_a_rollback() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 5).await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + store.refresh().await.unwrap(); + + server.reset().await; + mount( + &server, + repository_files(&roles, 4, 4, 4, EMBEDDED_TRUST_ROOT_JSON), + ) + .await; + *store.last_fetch.lock().await = None; + let refresh = store.refresh().await.unwrap_err(); + + assert!(refresh.contains("went back"), "{refresh}"); +} + +#[tokio::test] +async fn a_fetched_trust_root_missing_a_role_keeps_the_held_one() { + let roles = RoleSet::new(); + let mut renamed: serde_json::Value = serde_json::from_slice(EMBEDDED_TRUST_ROOT_JSON).unwrap(); + let logs = renamed.as_object_mut().unwrap().remove("tlogs").unwrap(); + renamed["transparencyLogs"] = logs; + let server = sigstore_serving(&roles, &serde_json::to_vec(&renamed).unwrap(), 1).await; + let store = store_holding( + &roles, + EMBEDDED_TRUST_ROOT_JSON.to_vec(), + 1, + None, + Repository::Url(server.uri()), + ); + + verify_lpm_release(&store, TrustRefresh::BeforeVerifying) + .await + .expect("the held trust root still verifies the release"); + let refresh = store.refresh().await.unwrap_err(); + assert!(refresh.contains("Rekor"), "{refresh}"); +} + +#[tokio::test] +async fn a_fetch_another_process_made_within_the_hour_is_reused() { + let roles = RoleSet::new(); + let server = sigstore_serving(&roles, EMBEDDED_TRUST_ROOT_JSON, 1).await; + let cache = tempfile::tempdir().unwrap(); + let cache_file = cache.path().join(CACHE_FILE_NAME); + let first = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file.clone()), + Repository::Url(server.uri()), + ); + first.refresh().await.unwrap(); + let second = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + Some(cache_file), + Repository::Url(server.uri()), + ); + + verify_lpm_release(&second, TrustRefresh::BeforeVerifying) + .await + .unwrap(); + + assert_eq!(timestamp_requests(&server).await, 1); +} + +#[tokio::test] +async fn a_failed_fetch_is_retried_after_a_minute_not_an_hour() { + let roles = RoleSet::new(); + let server = failing_repository().await; + let store = store_holding( + &roles, + trust_root_without_the_axios_log(), + 1, + None, + Repository::Url(server.uri()), + ); + store.refresh().await.unwrap_err(); + server.reset().await; + mount( + &server, + repository_files(&roles, 1, 1, 1, EMBEDDED_TRUST_ROOT_JSON), + ) + .await; + + store.refresh().await.unwrap_err(); + let failed_at = store.last_fetch.lock().await.as_ref().unwrap().0; + *store.last_fetch.lock().await = Some(( + failed_at - RETRY_FAILED_FETCH_AFTER, + Err("an earlier failure".into()), + )); + + store.refresh().await.unwrap(); +} + +#[tokio::test] +async fn the_release_gate_verifies_with_the_built_in_trust_root_only() { + let release_workflow = IdentityExpectations { + expected_issuer: Some("https://token.actions.githubusercontent.com".into()), + expected_san_uri_prefix: Some("https://github.com/lpm-dev/rust-client/".into()), + expected_workflow_path: Some(".github/workflows/release.yml".into()), + }; + + verify_sigstore_bundle_with_built_in_trust_root( + LPM_RELEASE_BUNDLE, + &release_workflow, + VerifyOptions::strict(), + ) + .expect("the built-in trust root verifies a release"); +} + +#[test] +fn repository_overrides_must_be_https_or_loopback() { + let default = Repository::Url(DEFAULT_REPOSITORY_URL.to_string()); + assert_eq!(repository_from_override(None), default); + assert_eq!(repository_from_override(Some(String::new())), default); + assert_eq!( + repository_from_override(Some("OFF".into())), + Repository::Disabled + ); + assert_eq!( + repository_from_override(Some("http://mirror.example.com".into())), + default + ); + for accepted in [ + "https://mirror.example.com/sigstore", + "http://127.0.0.1:8080", + ] { + assert_eq!( + repository_from_override(Some(accepted.into())), + Repository::Url(accepted.into()) + ); + } +} + +/// Run daily by the release trust monitor. Sigstore's live repository must +/// still verify under the TUF root built into LPM and serve the trust root +/// built into LPM, so a release ships Sigstore's current keys. +#[tokio::test] +#[ignore = "reaches Sigstore's live TUF repository"] +async fn sigstores_live_repository_serves_the_built_in_trust_root() { + let fetcher = HttpFetcher::new(DEFAULT_REPOSITORY_URL).unwrap(); + + let metadata = tuf::refresh(EMBEDDED_TUF_ROOT, None, &fetcher, SystemTime::now()) + .await + .expect("Sigstore's live repository verifies under the built-in TUF root"); + + let verified = metadata.verified_trusted_root(EMBEDDED_TUF_ROOT).unwrap(); + assert!( + verified.targets_version >= EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION, + "targets version {} is older than the built-in {EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION}", + verified.targets_version + ); + assert!( + metadata.roots.is_empty(), + "Sigstore published {} TUF root version(s) newer than the built-in one. Replace \ + crates/lpm-cli/assets/sigstore_tuf_root.json with the newest root.", + metadata.roots.len() + ); + for (role, supported, threshold) in metadata.key_support(EMBEDDED_TUF_ROOT).unwrap() { + assert!( + supported > threshold, + "Sigstore's {role} role has {supported} key(s) LPM can verify, against a threshold \ + of {threshold}. One more change to a key type LPM can't verify stops refreshes; \ + add support for the new key type." + ); + } + assert!( + verified.bytes == EMBEDDED_TRUST_ROOT_JSON, + "Sigstore published a new trust root under targets version {}. Replace \ + crates/lpm-cli/assets/sigstore_trusted_root.json with it, set \ + EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION to that version, and replace \ + assets/sigstore_tuf_root.json with Sigstore's newest root ({} newer than the \ + built-in one).", + verified.targets_version, + metadata.roots.len() + ); +} diff --git a/crates/lpm-cli/src/sigstore_verify/tuf/canonical.rs b/crates/lpm-cli/src/sigstore_verify/tuf/canonical.rs new file mode 100644 index 000000000..82fdfaf50 --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/tuf/canonical.rs @@ -0,0 +1,114 @@ +//! The canonical JSON form TUF signs: the OLPC encoding that +//! securesystemslib and go-securesystemslib produce. +//! +//! Object keys are sorted by code point, nothing is indented, strings escape +//! only `\` and `"` and keep every other character as raw UTF-8, and numbers +//! must be integers. `serde_json` can't produce this itself: it escapes +//! control characters, and with `preserve_order` it keeps keys in document +//! order. + +use serde_json::Value; + +/// Append the canonical encoding of `value` to `out`. +/// +/// Fails on a number that isn't an integer, which TUF metadata never holds. +pub(super) fn encode(value: &Value, out: &mut Vec) -> Result<(), String> { + match value { + Value::Null => out.extend_from_slice(b"null"), + Value::Bool(true) => out.extend_from_slice(b"true"), + Value::Bool(false) => out.extend_from_slice(b"false"), + Value::Number(number) => { + if let Some(unsigned) = number.as_u64() { + out.extend_from_slice(unsigned.to_string().as_bytes()); + } else if let Some(signed) = number.as_i64() { + out.extend_from_slice(signed.to_string().as_bytes()); + } else { + return Err(format!("{number} is not an integer")); + } + } + Value::String(text) => encode_string(text, out), + Value::Array(items) => { + out.push(b'['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(b','); + } + encode(item, out)?; + } + out.push(b']'); + } + Value::Object(map) => { + let mut entries: Vec<(&String, &Value)> = map.iter().collect(); + entries.sort_unstable_by_key(|(key, _)| *key); + out.push(b'{'); + for (index, (key, item)) in entries.into_iter().enumerate() { + if index > 0 { + out.push(b','); + } + encode_string(key, out); + out.push(b':'); + encode(item, out)?; + } + out.push(b'}'); + } + } + Ok(()) +} + +fn encode_string(text: &str, out: &mut Vec) { + out.reserve(text.len() + 2); + out.push(b'"'); + for byte in text.bytes() { + if byte == b'\\' || byte == b'"' { + out.push(b'\\'); + } + out.push(byte); + } + out.push(b'"'); +} + +#[cfg(test)] +mod tests { + use super::encode; + use serde_json::json; + + fn canonical(value: serde_json::Value) -> String { + let mut out = Vec::new(); + encode(&value, &mut out).unwrap(); + String::from_utf8(out).unwrap() + } + + #[test] + fn object_keys_are_sorted_by_code_point_at_every_level() { + let value: serde_json::Value = + serde_json::from_str(r#"{"b":1,"a":{"é":true,"z":null,"A":[3,{"y":2,"x":1}]}}"#) + .unwrap(); + assert_eq!( + canonical(value), + r#"{"a":{"A":[3,{"x":1,"y":2}],"z":null,"é":true},"b":1}"# + ); + } + + #[test] + fn strings_escape_only_backslash_and_quote() { + let value = json!({"k": "tab\there \"quoted\" back\\slash\nnewline\u{0001}"}); + assert_eq!( + canonical(value), + "{\"k\":\"tab\there \\\"quoted\\\" back\\\\slash\nnewline\u{0001}\"}" + ); + } + + #[test] + fn negative_and_large_integers_keep_their_digits() { + assert_eq!( + canonical(json!([-7, 0, 18446744073709551615u64])), + "[-7,0,18446744073709551615]" + ); + } + + #[test] + fn a_fractional_number_is_refused() { + let mut out = Vec::new(); + assert!(encode(&json!({"threshold": 1.5}), &mut out).is_err()); + } +} diff --git a/crates/lpm-cli/src/sigstore_verify/tuf/metadata.rs b/crates/lpm-cli/src/sigstore_verify/tuf/metadata.rs new file mode 100644 index 000000000..c62be0433 --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/tuf/metadata.rs @@ -0,0 +1,430 @@ +//! TUF metadata documents, their signatures, and the checks every role +//! shares. + +use super::TufError; +use super::canonical; +use lpm_common::Timestamp as Time; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use sha2::{Digest, Sha256, Sha512}; +use std::collections::BTreeMap; +use std::time::SystemTime; + +/// A signed metadata document: the typed `signed` object, the canonical +/// bytes its signatures cover, and those signatures. +#[derive(Debug, Clone)] +pub(super) struct Signed { + pub(super) signed: T, + canonical: Vec, + signatures: Vec, +} + +#[derive(Deserialize)] +struct RawEnvelope { + signed: serde_json::Value, + signatures: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +struct RawSignature { + keyid: String, + sig: String, +} + +/// The fields every top-level role's metadata carries. +pub(super) trait Role: DeserializeOwned { + const NAME: &'static str; + fn common(&self) -> &Common; +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Common { + #[serde(rename = "_type")] + kind: String, + spec_version: String, + pub(super) version: u64, + expires: String, +} + +// Keys, roles, files and targets this client can't read are left out +// rather than refusing the whole document: Sigstore can add entries in +// shapes newer than this client, and the ones it reads must stay usable. +// A key left out never counts toward a threshold, and a file left out is +// reported missing only when the client needs it. + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Root { + #[serde(flatten)] + pub(super) common: Common, + #[serde(deserialize_with = "readable_entries")] + keys: BTreeMap, + #[serde(deserialize_with = "readable_entries")] + roles: BTreeMap, + #[serde(default)] + pub(super) consistent_snapshot: bool, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Timestamp { + #[serde(flatten)] + pub(super) common: Common, + #[serde(deserialize_with = "readable_entries")] + pub(super) meta: BTreeMap, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Snapshot { + #[serde(flatten)] + pub(super) common: Common, + #[serde(deserialize_with = "readable_entries")] + pub(super) meta: BTreeMap, +} + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Targets { + #[serde(flatten)] + pub(super) common: Common, + #[serde(deserialize_with = "readable_entries")] + pub(super) targets: BTreeMap, +} + +fn readable_entries<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: DeserializeOwned, +{ + let raw = BTreeMap::::deserialize(deserializer)?; + Ok(raw + .into_iter() + .filter_map(|(name, value)| Some((name, serde_json::from_value(value).ok()?))) + .collect()) +} + +#[derive(Debug, Clone, Deserialize)] +struct Key { + keytype: String, + scheme: String, + keyval: KeyValue, +} + +#[derive(Debug, Clone, Deserialize)] +struct KeyValue { + public: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +struct RoleKeys { + keyids: Vec, + threshold: u32, +} + +/// What a snapshot or timestamp records about another metadata file. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct MetaFile { + pub(super) version: u64, + pub(super) length: Option, + pub(super) hashes: Option>, +} + +/// What the targets role records about a target file. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct TargetFile { + pub(super) length: u64, + pub(super) hashes: BTreeMap, +} + +macro_rules! impl_role { + ($ty:ty, $name:literal) => { + impl Role for $ty { + const NAME: &'static str = $name; + fn common(&self) -> &Common { + &self.common + } + } + }; +} + +impl_role!(Root, "root"); +impl_role!(Timestamp, "timestamp"); +impl_role!(Snapshot, "snapshot"); +impl_role!(Targets, "targets"); + +impl Signed { + /// Parse a metadata document and check that it is the role it claims + /// to be, in a TUF 1.x format. Signatures are checked separately with + /// [`Self::verify_with`]. + pub(super) fn parse(bytes: &[u8]) -> Result { + let malformed = |detail: String| TufError::Malformed { + role: T::NAME, + detail, + }; + let raw: RawEnvelope = + serde_json::from_slice(bytes).map_err(|error| malformed(error.to_string()))?; + let mut canonical = Vec::with_capacity(bytes.len()); + canonical::encode(&raw.signed, &mut canonical).map_err(malformed)?; + let signed = T::deserialize(&raw.signed).map_err(|error| malformed(error.to_string()))?; + let common = signed.common(); + if common.kind != T::NAME { + return Err(malformed(format!("its _type is {:?}", common.kind))); + } + if common.version == 0 { + return Err(malformed("its version is 0".into())); + } + if common.spec_version.split('.').next() != Some("1") { + return Err(malformed(format!( + "it uses TUF specification {}, and this client supports 1.x", + common.spec_version + ))); + } + Ok(Self { + signed, + canonical, + signatures: raw.signatures, + }) + } + + pub(super) fn version(&self) -> u64 { + self.signed.common().version + } + + /// Check that `delegator`'s keys for this role signed the document at + /// least as many times as the role's threshold requires. + /// + /// Each key counts once, however many signatures name it and under + /// however many key IDs or encodings it is listed. + pub(super) fn verify_with(&self, delegator: &Root) -> Result<(), TufError> { + let role = delegator + .roles + .get(T::NAME) + .ok_or_else(|| TufError::Malformed { + role: Root::NAME, + detail: format!("it defines no {} role", T::NAME), + })?; + if role.threshold == 0 { + return Err(TufError::Malformed { + role: Root::NAME, + detail: format!("the {} role has a threshold of 0", T::NAME), + }); + } + let mut counted: Vec> = Vec::with_capacity(role.keyids.len()); + for keyid in &role.keyids { + let Some(key) = delegator.keys.get(keyid) else { + continue; + }; + let Some(identity) = key.identity() else { + continue; + }; + if counted.contains(&identity) { + continue; + } + let signed_by_key = self + .signatures + .iter() + .filter(|signature| &signature.keyid == keyid) + .any(|signature| key.verifies(&self.canonical, &signature.sig)); + if signed_by_key { + counted.push(identity); + } + } + let threshold = role.threshold as usize; + if counted.len() >= threshold { + Ok(()) + } else { + Err(TufError::Threshold { + role: T::NAME, + valid: counted.len(), + threshold, + }) + } + } + + /// Refuse metadata whose expiry has passed at `now`. + pub(super) fn ensure_unexpired(&self, now: SystemTime) -> Result<(), TufError> { + let expires = &self.signed.common().expires; + let parsed = Time::parse_rfc3339(expires).map_err(|error| TufError::Malformed { + role: T::NAME, + detail: format!("its expiry {expires:?} is not an RFC 3339 time: {error}"), + })?; + let now: Time = now.into(); + if now < parsed { + Ok(()) + } else { + Err(TufError::Expired { + role: T::NAME, + expires: expires.clone(), + }) + } + } +} + +impl Root { + /// Whether the keys or threshold for `role` differ between two roots. + /// How many distinct keys of `role` this client can verify, and the + /// role's threshold. + #[cfg(test)] + pub(super) fn supported_keys(&self, role: &str) -> (usize, usize) { + self.role_keys(role) + .map_or((0, 0), |(identities, threshold)| { + (identities.len(), threshold as usize) + }) + } + + pub(super) fn role_keys_differ(&self, other: &Root, role: &str) -> bool { + self.role_keys(role) != other.role_keys(role) + } + + fn role_keys(&self, role: &str) -> Option<(Vec>, u32)> { + self.roles.get(role).map(|keys| { + let mut identities: Vec> = keys + .keyids + .iter() + .filter_map(|keyid| self.keys.get(keyid)) + .filter_map(Key::identity) + .collect(); + identities.sort_unstable(); + identities.dedup(); + (identities, keys.threshold) + }) + } +} + +impl Key { + /// The key itself, independent of how the metadata encodes it: the + /// scheme and the DER public key or raw Ed25519 bytes. `None` for a key + /// this client can't use. + fn identity(&self) -> Option> { + use p256::pkcs8::{DecodePublicKey, EncodePublicKey}; + let (tag, bytes) = match (self.keytype.as_str(), self.scheme.as_str()) { + ("ecdsa" | "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256") => ( + b'1', + p256::ecdsa::VerifyingKey::from_public_key_pem(&self.keyval.public) + .ok()? + .to_public_key_der() + .ok()? + .into_vec(), + ), + ("ecdsa" | "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp384") => ( + b'3', + p384::ecdsa::VerifyingKey::from_public_key_pem(&self.keyval.public) + .ok()? + .to_public_key_der() + .ok()? + .into_vec(), + ), + ("ed25519", "ed25519") => (b'e', hex::decode(&self.keyval.public).ok()?), + _ => return None, + }; + let mut identity = Vec::with_capacity(bytes.len() + 1); + identity.push(tag); + identity.extend_from_slice(&bytes); + Some(identity) + } + + /// Whether `signature_hex` is this key's signature over `message`. + /// + /// Supports the key types securesystemslib signs TUF metadata with; + /// a key of any other type never verifies, so it can't count toward a + /// threshold. + fn verifies(&self, message: &[u8], signature_hex: &str) -> bool { + let Ok(signature) = hex::decode(signature_hex) else { + return false; + }; + match (self.keytype.as_str(), self.scheme.as_str()) { + ("ecdsa" | "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256") => { + verify_p256(&self.keyval.public, message, &signature) + } + ("ecdsa" | "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp384") => { + verify_p384(&self.keyval.public, message, &signature) + } + ("ed25519", "ed25519") => verify_ed25519(&self.keyval.public, message, &signature), + _ => false, + } + } +} + +fn verify_p256(public_pem: &str, message: &[u8], signature_der: &[u8]) -> bool { + use ecdsa::signature::hazmat::PrehashVerifier; + use p256::pkcs8::DecodePublicKey; + let Ok(key) = p256::ecdsa::VerifyingKey::from_public_key_pem(public_pem) else { + return false; + }; + let Ok(signature) = p256::ecdsa::Signature::from_der(signature_der) else { + return false; + }; + key.verify_prehash(&Sha256::digest(message), &signature) + .is_ok() +} + +fn verify_p384(public_pem: &str, message: &[u8], signature_der: &[u8]) -> bool { + use ecdsa::signature::hazmat::PrehashVerifier; + use p384::pkcs8::DecodePublicKey; + let Ok(key) = p384::ecdsa::VerifyingKey::from_public_key_pem(public_pem) else { + return false; + }; + let Ok(signature) = p384::ecdsa::Signature::from_der(signature_der) else { + return false; + }; + key.verify_prehash(&sha2::Sha384::digest(message), &signature) + .is_ok() +} + +fn verify_ed25519(public_hex: &str, message: &[u8], signature: &[u8]) -> bool { + let Ok(public) = hex::decode(public_hex) else { + return false; + }; + let (Ok(public), Ok(signature)) = ( + <[u8; 32]>::try_from(public.as_slice()), + <[u8; 64]>::try_from(signature), + ) else { + return false; + }; + let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(&public) else { + return false; + }; + key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(&signature)) + .is_ok() +} + +/// Check `bytes` against a recorded length and set of hashes. +/// +/// Every recorded SHA-256 or SHA-512 hash must match. Hashes in other +/// algorithms are skipped, but at least one hash must be one this client +/// computes when `require_hash` is set. +pub(super) fn check_length_and_hashes( + bytes: &[u8], + length: Option, + hashes: Option<&BTreeMap>, + require_hash: bool, + name: &str, +) -> Result<(), TufError> { + let mismatch = |detail: String| TufError::Mismatch { + name: name.to_string(), + detail, + }; + if let Some(length) = length + && bytes.len() as u64 != length + { + return Err(mismatch(format!( + "it is {} bytes, and {length} were expected", + bytes.len() + ))); + } + let mut checked = 0usize; + for (algorithm, expected) in hashes.into_iter().flatten() { + let actual = match algorithm.as_str() { + "sha256" => hex::encode(Sha256::digest(bytes)), + "sha512" => hex::encode(Sha512::digest(bytes)), + _ => continue, + }; + if !actual.eq_ignore_ascii_case(expected) { + return Err(mismatch(format!("its {algorithm} hash differs"))); + } + checked += 1; + } + if require_hash && checked == 0 { + return Err(mismatch( + "no SHA-256 or SHA-512 hash is recorded for it".into(), + )); + } + Ok(()) +} diff --git a/crates/lpm-cli/src/sigstore_verify/tuf/mod.rs b/crates/lpm-cli/src/sigstore_verify/tuf/mod.rs new file mode 100644 index 000000000..0c2736d1c --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/tuf/mod.rs @@ -0,0 +1,455 @@ +//! Client for Sigstore's TUF repository, the signed channel through which +//! Sigstore publishes its trust root. +//! +//! An LPM binary holds the trust root that was current when it was built. +//! Sigstore rotates the keys and certificate authorities in it, so a copy +//! that never refreshed would end up unable to verify new signatures, +//! including the ones on later LPM releases. This client refreshes the +//! trust root the way Sigstore's own clients do: it starts from the TUF root +//! built into the binary, follows the root rotations Sigstore signed, and +//! accepts only a trust root whose hashes the current targets role signed. +//! +//! It implements the TUF 1.x client workflow for the four top-level roles +//! and the one target LPM needs. Delegated targets are not followed. + +mod canonical; +mod metadata; +#[cfg(test)] +pub(crate) mod test_support; +#[cfg(test)] +mod tests; + +use metadata::{Root, Signed, Snapshot, Targets, Timestamp, check_length_and_hashes}; +use serde::{Deserialize, Serialize}; +use std::time::SystemTime; + +/// The target that holds Sigstore's trust root. +pub(crate) const TRUSTED_ROOT_TARGET: &str = "trusted_root.json"; + +/// Size limits, from python-tuf's client defaults. The trust root itself is +/// a few kilobytes. +const ROOT_MAX_BYTES: u64 = 512_000; +const TIMESTAMP_MAX_BYTES: u64 = 16_384; +const SNAPSHOT_MAX_BYTES: u64 = 2_000_000; +const TARGETS_MAX_BYTES: u64 = 5_000_000; +const TRUSTED_ROOT_MAX_BYTES: u64 = 1_048_576; + +/// Most root versions one refresh follows. Sigstore has published one or +/// two a year. +const MAX_ROOT_ROTATIONS: u64 = 256; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub(crate) enum TufError { + #[error("Sigstore's {role} metadata is malformed: {detail}")] + Malformed { role: &'static str, detail: String }, + #[error( + "Sigstore's {role} metadata has {valid} valid signature(s), and {threshold} are required" + )] + Threshold { + role: &'static str, + valid: usize, + threshold: usize, + }, + #[error("Sigstore's {role} metadata is version {actual}, and version {expected} was expected")] + Version { + role: &'static str, + expected: u64, + actual: u64, + }, + #[error("Sigstore's {role} metadata went back from version {trusted} to {offered}")] + Rollback { + role: &'static str, + trusted: u64, + offered: u64, + }, + #[error("Sigstore's {role} metadata expired at {expires}")] + Expired { role: &'static str, expires: String }, + #[error("{name} doesn't match what Sigstore's metadata records: {detail}")] + Mismatch { name: String, detail: String }, + #[error("Sigstore's repository has no {0}")] + Missing(String), + #[error("fetching {path} from Sigstore's repository failed: {detail}")] + Fetch { path: String, detail: String }, +} + +/// Where a refresh reads repository files from. +pub(crate) trait Fetcher { + /// Fetch the repository file at `path`, refusing more than `max_bytes`. + /// `Ok(None)` means the repository has no such file. + async fn fetch(&self, path: &str, max_bytes: u64) -> Result>, String>; +} + +/// The verified metadata a refresh produced, kept between runs. +/// +/// Each document is stored exactly as Sigstore served it, and everything is +/// checked again when it is read back, so the cache is never trusted on its +/// own: a forged entry fails the signature checks anchored in the TUF root +/// built into the binary. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct TrustedMetadata { + /// Root metadata newer than the embedded root, oldest first. + pub(crate) roots: Vec, + pub(crate) timestamp: String, + pub(crate) snapshot: String, + pub(crate) targets: String, + pub(crate) trusted_root: String, +} + +/// How recent verified metadata is: a later root first, then a later +/// targets, snapshot and timestamp version. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct Freshness { + root: u64, + targets: u64, + snapshot: u64, + timestamp: u64, +} + +/// A trust root that Sigstore's targets role signed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct VerifiedTrustedRoot { + pub(crate) bytes: Vec, + /// Version of the targets metadata that recorded it. + pub(crate) targets_version: u64, +} + +impl TrustedMetadata { + /// Check stored metadata again and return the trust root it holds. + /// + /// Expiry is not enforced here. Stored metadata stands in for the trust + /// root built into the binary when Sigstore's repository can't be + /// reached, and it is never older than what that binary was built with. + /// Check stored metadata again and say how recent it is. + pub(crate) fn freshness(&self, embedded_root: &[u8]) -> Result { + let root = follow_roots(Signed::::parse(embedded_root)?, &self.roots)?; + let targets = Signed::::parse(self.targets.as_bytes())?; + targets.verify_with(&root.signed)?; + let snapshot = Signed::::parse(self.snapshot.as_bytes())?; + snapshot.verify_with(&root.signed)?; + let timestamp = Signed::::parse(self.timestamp.as_bytes())?; + timestamp.verify_with(&root.signed)?; + Ok(Freshness { + root: root.version(), + targets: targets.version(), + snapshot: snapshot.version(), + timestamp: timestamp.version(), + }) + } + + /// For the root and targets roles of the newest stored root: how many + /// of their keys this client can verify, and the role's threshold. + #[cfg(test)] + pub(crate) fn key_support( + &self, + embedded_root: &[u8], + ) -> Result, TufError> { + let root = follow_roots(Signed::::parse(embedded_root)?, &self.roots)?; + Ok(["root", "targets"] + .into_iter() + .map(|role| { + let (supported, threshold) = root.signed.supported_keys(role); + (role, supported, threshold) + }) + .collect()) + } + + pub(crate) fn verified_trusted_root( + &self, + embedded_root: &[u8], + ) -> Result { + let root = follow_roots(Signed::::parse(embedded_root)?, &self.roots)?; + let targets = Signed::::parse(self.targets.as_bytes())?; + targets.verify_with(&root.signed)?; + check_trusted_root(&targets, self.trusted_root.as_bytes())?; + Ok(VerifiedTrustedRoot { + bytes: self.trusted_root.clone().into_bytes(), + targets_version: targets.version(), + }) + } +} + +/// Run the TUF client workflow against `fetcher` and return the metadata it +/// verified. +/// +/// `stored` is what an earlier refresh returned. It anchors the rollback +/// checks, and its roots spare refetching every rotation since the embedded +/// root. Stored metadata that no longer verifies is ignored. +pub(crate) async fn refresh( + embedded_root: &[u8], + stored: Option<&TrustedMetadata>, + fetcher: &F, + now: SystemTime, +) -> Result { + let embedded = Signed::::parse(embedded_root)?; + let stored = stored.and_then(|stored| { + follow_roots(embedded.clone(), &stored.roots) + .ok() + .map(|root| (stored, root)) + }); + // Stored roots older than the built-in one stay, so a binary built with + // an older TUF root can still follow them. + let (mut root, mut roots) = match &stored { + Some((stored, root)) => (root.clone(), stored.roots.clone()), + None => (embedded, Vec::new()), + }; + // A root that replaced the timestamp or snapshot keys may restart those + // roles' version numbers, so the old versions no longer bound them. Each + // step counts: keys rotated away and back may have restarted too. + let mut keys_rotated = false; + for _ in 0..MAX_ROOT_ROTATIONS { + let next = root.version() + 1; + let path = format!("{next}.root.json"); + let Some(bytes) = fetch(fetcher, &path, ROOT_MAX_BYTES).await? else { + break; + }; + let rotated = rotate_root(&root, &bytes)?; + keys_rotated |= root.signed.role_keys_differ(&rotated.signed, "timestamp") + || root.signed.role_keys_differ(&rotated.signed, "snapshot"); + root = rotated; + roots.push(into_text(bytes, &path)?); + } + root.ensure_unexpired(now)?; + let previous = stored + .filter(|_| !keys_rotated) + .map(|(stored, _)| PreviousVersions::from_stored(stored, &root.signed)); + + let timestamp_text = fetch_required(fetcher, "timestamp.json", TIMESTAMP_MAX_BYTES).await?; + let timestamp = Signed::::parse(×tamp_text)?; + timestamp.verify_with(&root.signed)?; + let snapshot_meta = + timestamp + .signed + .meta + .get("snapshot.json") + .ok_or_else(|| TufError::Malformed { + role: "timestamp", + detail: "it records no snapshot.json".into(), + })?; + if let Some(previous) = previous.as_ref().and_then(|p| p.timestamp.as_ref()) { + not_older("timestamp", previous.version(), timestamp.version())?; + if let Some(old) = previous.signed.meta.get("snapshot.json") { + not_older("snapshot", old.version, snapshot_meta.version)?; + } + } + timestamp.ensure_unexpired(now)?; + + let snapshot_path = versioned_path(&root, snapshot_meta.version, "snapshot.json"); + let snapshot_text = fetch_required( + fetcher, + &snapshot_path, + capped(snapshot_meta.length, SNAPSHOT_MAX_BYTES), + ) + .await?; + check_length_and_hashes( + &snapshot_text, + snapshot_meta.length, + snapshot_meta.hashes.as_ref(), + false, + "snapshot.json", + )?; + let snapshot = Signed::::parse(&snapshot_text)?; + snapshot.verify_with(&root.signed)?; + expect_version("snapshot", snapshot_meta.version, snapshot.version())?; + let targets_meta = + snapshot + .signed + .meta + .get("targets.json") + .ok_or_else(|| TufError::Malformed { + role: "snapshot", + detail: "it records no targets.json".into(), + })?; + // Only targets.json matters to this client, so delegated roles Sigstore + // adds or removes don't affect it. + if let Some(old) = previous + .as_ref() + .and_then(|p| p.snapshot.as_ref()) + .and_then(|snapshot| snapshot.signed.meta.get("targets.json")) + { + not_older("targets", old.version, targets_meta.version)?; + } + snapshot.ensure_unexpired(now)?; + let targets_path = versioned_path(&root, targets_meta.version, "targets.json"); + let targets_text = fetch_required( + fetcher, + &targets_path, + capped(targets_meta.length, TARGETS_MAX_BYTES), + ) + .await?; + check_length_and_hashes( + &targets_text, + targets_meta.length, + targets_meta.hashes.as_ref(), + false, + "targets.json", + )?; + let targets = Signed::::parse(&targets_text)?; + targets.verify_with(&root.signed)?; + expect_version("targets", targets_meta.version, targets.version())?; + targets.ensure_unexpired(now)?; + + let target = trusted_root_entry(&targets)?; + if target.length > TRUSTED_ROOT_MAX_BYTES { + return Err(TufError::Mismatch { + name: TRUSTED_ROOT_TARGET.into(), + detail: format!( + "it is recorded as {} bytes, over the {TRUSTED_ROOT_MAX_BYTES}-byte limit", + target.length + ), + }); + } + let target_path = if root.signed.consistent_snapshot { + let prefix = target + .hashes + .get("sha256") + .or_else(|| target.hashes.get("sha512")) + .ok_or_else(|| TufError::Mismatch { + name: TRUSTED_ROOT_TARGET.into(), + detail: "no SHA-256 or SHA-512 hash is recorded for it".into(), + })?; + format!("targets/{prefix}.{TRUSTED_ROOT_TARGET}") + } else { + format!("targets/{TRUSTED_ROOT_TARGET}") + }; + let trusted_root = fetch_required(fetcher, &target_path, target.length).await?; + check_trusted_root(&targets, &trusted_root)?; + + Ok(TrustedMetadata { + roots, + timestamp: into_text(timestamp_text, "timestamp.json")?, + snapshot: into_text(snapshot_text, &snapshot_path)?, + targets: into_text(targets_text, &targets_path)?, + trusted_root: into_text(trusted_root, &target_path)?, + }) +} + +/// Timestamp and snapshot metadata from the previous refresh that still +/// verify under the current root. +struct PreviousVersions { + timestamp: Option>, + snapshot: Option>, +} + +impl PreviousVersions { + fn from_stored(stored: &TrustedMetadata, root: &Root) -> Self { + fn verified(text: &str, root: &Root) -> Option> { + let parsed = Signed::::parse(text.as_bytes()).ok()?; + parsed.verify_with(root).ok()?; + Some(parsed) + } + Self { + timestamp: verified(&stored.timestamp, root), + snapshot: verified(&stored.snapshot, root), + } + } +} + +/// Accept `bytes` as the root that follows `trusted` if a threshold of the +/// trusted root's keys and a threshold of its own keys signed it. +fn rotate_root(trusted: &Signed, bytes: &[u8]) -> Result, TufError> { + let next = Signed::::parse(bytes)?; + next.verify_with(&trusted.signed)?; + next.verify_with(&next.signed)?; + expect_version("root", trusted.version() + 1, next.version())?; + Ok(next) +} + +/// Follow stored roots from `root`. Stored roots no newer than `root` are +/// skipped: a binary built with a newer TUF root reads a cache written by +/// an older one. +fn follow_roots(mut root: Signed, newer: &[String]) -> Result, TufError> { + for text in newer { + let stored = Signed::::parse(text.as_bytes())?; + if stored.version() <= root.version() { + continue; + } + root = rotate_root(&root, text.as_bytes())?; + } + Ok(root) +} + +fn trusted_root_entry(targets: &Signed) -> Result<&metadata::TargetFile, TufError> { + targets + .signed + .targets + .get(TRUSTED_ROOT_TARGET) + .ok_or_else(|| TufError::Missing(format!("{TRUSTED_ROOT_TARGET} among its targets"))) +} + +fn check_trusted_root(targets: &Signed, bytes: &[u8]) -> Result<(), TufError> { + let target = trusted_root_entry(targets)?; + check_length_and_hashes( + bytes, + Some(target.length), + Some(&target.hashes), + true, + TRUSTED_ROOT_TARGET, + ) +} + +fn versioned_path(root: &Signed, version: u64, name: &str) -> String { + if root.signed.consistent_snapshot { + format!("{version}.{name}") + } else { + name.to_string() + } +} + +fn capped(recorded: Option, limit: u64) -> u64 { + recorded.map_or(limit, |length| length.min(limit)) +} + +fn expect_version(role: &'static str, expected: u64, actual: u64) -> Result<(), TufError> { + if expected == actual { + Ok(()) + } else { + Err(TufError::Version { + role, + expected, + actual, + }) + } +} + +fn not_older(role: &'static str, trusted: u64, offered: u64) -> Result<(), TufError> { + if offered >= trusted { + Ok(()) + } else { + Err(TufError::Rollback { + role, + trusted, + offered, + }) + } +} + +async fn fetch( + fetcher: &F, + path: &str, + max_bytes: u64, +) -> Result>, TufError> { + fetcher + .fetch(path, max_bytes) + .await + .map_err(|detail| TufError::Fetch { + path: path.to_string(), + detail, + }) +} + +async fn fetch_required( + fetcher: &F, + path: &str, + max_bytes: u64, +) -> Result, TufError> { + fetch(fetcher, path, max_bytes) + .await? + .ok_or_else(|| TufError::Missing(path.to_string())) +} + +fn into_text(bytes: Vec, path: &str) -> Result { + String::from_utf8(bytes).map_err(|_| TufError::Mismatch { + name: path.to_string(), + detail: "it is not UTF-8 text".into(), + }) +} diff --git a/crates/lpm-cli/src/sigstore_verify/tuf/test_support.rs b/crates/lpm-cli/src/sigstore_verify/tuf/test_support.rs new file mode 100644 index 000000000..5faa87c6d --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/tuf/test_support.rs @@ -0,0 +1,231 @@ +//! Synthetic TUF repositories signed with test keys. + +use super::canonical; +use ecdsa::signature::hazmat::PrehashSigner; +use p256::pkcs8::{EncodePublicKey, LineEnding}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// A signing key for a synthetic repository. +#[derive(Clone)] +pub(crate) enum TestKey { + P256(p256::ecdsa::SigningKey), + Ed25519(ed25519_dalek::SigningKey), +} + +impl TestKey { + pub(crate) fn p256(seed: u8) -> Self { + Self::P256(p256::ecdsa::SigningKey::from_slice(&[seed; 32]).unwrap()) + } + + pub(crate) fn ed25519(seed: u8) -> Self { + Self::Ed25519(ed25519_dalek::SigningKey::from_bytes(&[seed; 32])) + } + + fn metadata(&self) -> Value { + match self { + Self::P256(key) => json!({ + "keytype": "ecdsa", + "scheme": "ecdsa-sha2-nistp256", + "keyval": {"public": key.verifying_key().to_public_key_pem(LineEnding::LF).unwrap()}, + }), + Self::Ed25519(key) => json!({ + "keytype": "ed25519", + "scheme": "ed25519", + "keyval": {"public": hex::encode(key.verifying_key().as_bytes())}, + }), + } + } + + pub(crate) fn keyid(&self) -> String { + hex::encode(Sha256::digest(self.metadata().to_string())) + } + + fn sign(&self, message: &[u8]) -> String { + match self { + Self::P256(key) => { + let signature: p256::ecdsa::Signature = + key.sign_prehash(&Sha256::digest(message)).unwrap(); + hex::encode(signature.to_der().as_bytes()) + } + Self::Ed25519(key) => { + use ed25519_dalek::Signer; + hex::encode(key.sign(message).to_bytes()) + } + } + } +} + +pub(crate) fn envelope(signed: Value, signers: &[&TestKey]) -> Vec { + let mut canonical_bytes = Vec::new(); + canonical::encode(&signed, &mut canonical_bytes).unwrap(); + let signatures: Vec = signers + .iter() + .map(|key| json!({"keyid": key.keyid(), "sig": key.sign(&canonical_bytes)})) + .collect(); + serde_json::to_vec_pretty(&json!({"signed": signed, "signatures": signatures})).unwrap() +} + +/// The keys of each top-level role in a synthetic root. +#[derive(Clone)] +pub(crate) struct RoleSet { + pub(crate) root: Vec, + pub(crate) root_threshold: u32, + pub(crate) timestamp: TestKey, + pub(crate) snapshot: TestKey, + pub(crate) targets: TestKey, + pub(crate) consistent_snapshot: bool, +} + +impl RoleSet { + pub(crate) fn new() -> Self { + Self { + root: vec![TestKey::p256(1)], + root_threshold: 1, + timestamp: TestKey::p256(2), + snapshot: TestKey::p256(3), + targets: TestKey::p256(4), + consistent_snapshot: true, + } + } + + pub(crate) fn root(&self, version: u64, signers: &[&TestKey]) -> Vec { + let mut keys = serde_json::Map::new(); + let all = self + .root + .iter() + .chain([&self.timestamp, &self.snapshot, &self.targets]); + for key in all { + keys.insert(key.keyid(), key.metadata()); + } + let role = |keys: &[&TestKey], threshold: u32| json!({"keyids": keys.iter().map(|key| key.keyid()).collect::>(), "threshold": threshold}); + let root_keys: Vec<&TestKey> = self.root.iter().collect(); + envelope( + json!({ + "_type": "root", + "spec_version": "1.0", + "version": version, + "expires": "2099-01-01T00:00:00Z", + "consistent_snapshot": self.consistent_snapshot, + "keys": keys, + "roles": { + "root": role(&root_keys, self.root_threshold), + "timestamp": role(&[&self.timestamp], 1), + "snapshot": role(&[&self.snapshot], 1), + "targets": role(&[&self.targets], 1), + }, + }), + signers, + ) + } + + pub(crate) fn signed_root(&self, version: u64) -> Vec { + let signers: Vec<&TestKey> = self.root.iter().collect(); + self.root(version, &signers) + } +} + +/// The files of a synthetic repository whose timestamp, snapshot and +/// targets carry the given versions, and whose `trusted_root.json` is +/// `trusted_root`. +pub(crate) fn repository_files( + roles: &RoleSet, + timestamp_version: u64, + snapshot_version: u64, + targets_version: u64, + trusted_root: &[u8], +) -> BTreeMap> { + repository_files_listing( + roles, + timestamp_version, + snapshot_version, + targets_version, + trusted_root, + &[], + ) +} + +/// [`repository_files`] whose snapshot also lists `delegated` roles at +/// version 1. +pub(crate) fn repository_files_listing( + roles: &RoleSet, + timestamp_version: u64, + snapshot_version: u64, + targets_version: u64, + trusted_root: &[u8], + delegated: &[&str], +) -> BTreeMap> { + let mut meta = serde_json::Map::new(); + meta.insert("targets.json".into(), json!({"version": targets_version})); + for role in delegated { + meta.insert(format!("{role}.json"), json!({"version": 1})); + } + let target_hash = hex::encode(Sha256::digest(trusted_root)); + let targets = envelope( + json!({ + "_type": "targets", + "spec_version": "1.0", + "version": targets_version, + "expires": "2099-01-01T00:00:00Z", + "targets": { + "trusted_root.json": {"length": trusted_root.len(), "hashes": {"sha256": target_hash}}, + }, + }), + &[&roles.targets], + ); + let snapshot = envelope( + json!({ + "_type": "snapshot", + "spec_version": "1.0", + "version": snapshot_version, + "expires": "2099-01-01T00:00:00Z", + "meta": meta, + }), + &[&roles.snapshot], + ); + let timestamp = envelope( + json!({ + "_type": "timestamp", + "spec_version": "1.0", + "version": timestamp_version, + "expires": "2099-01-01T00:00:00Z", + "meta": {"snapshot.json": { + "version": snapshot_version, + "length": snapshot.len(), + "hashes": {"sha256": hex::encode(Sha256::digest(&snapshot))}, + }}, + }), + &[&roles.timestamp], + ); + let (snapshot_path, targets_path, target_path) = if roles.consistent_snapshot { + ( + format!("{snapshot_version}.snapshot.json"), + format!("{targets_version}.targets.json"), + format!("targets/{target_hash}.trusted_root.json"), + ) + } else { + ( + "snapshot.json".into(), + "targets.json".into(), + "targets/trusted_root.json".into(), + ) + }; + BTreeMap::from([ + ("timestamp.json".to_string(), timestamp), + (snapshot_path, snapshot), + (targets_path, targets), + (target_path, trusted_root.to_vec()), + ]) +} + +/// Re-sign `document` with `signers` after `edit` changes its signed part. +pub(crate) fn resigned( + document: &[u8], + signers: &[&TestKey], + edit: impl FnOnce(&mut Value), +) -> Vec { + let mut parsed: Value = serde_json::from_slice(document).unwrap(); + edit(&mut parsed["signed"]); + envelope(parsed["signed"].take(), signers) +} diff --git a/crates/lpm-cli/src/sigstore_verify/tuf/tests.rs b/crates/lpm-cli/src/sigstore_verify/tuf/tests.rs new file mode 100644 index 000000000..ee3aa1217 --- /dev/null +++ b/crates/lpm-cli/src/sigstore_verify/tuf/tests.rs @@ -0,0 +1,786 @@ +use super::test_support::{RoleSet, TestKey, repository_files, repository_files_listing, resigned}; +use super::*; +use lpm_common::Timestamp as Time; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::sync::Mutex; + +const REAL_ROOT_13: &[u8] = include_bytes!("../../../tests/fixtures/sigstore_tuf/13.root.json"); +const REAL_ROOT_14: &[u8] = include_bytes!("../../../tests/fixtures/sigstore_tuf/14.root.json"); +const REAL_ROOT_15: &[u8] = include_bytes!("../../../tests/fixtures/sigstore_tuf/15.root.json"); +const REAL_ROOT_16: &[u8] = include_bytes!("../../../tests/fixtures/sigstore_tuf/16.root.json"); +const REAL_TIMESTAMP: &[u8] = include_bytes!("../../../tests/fixtures/sigstore_tuf/timestamp.json"); +const REAL_SNAPSHOT_166: &[u8] = + include_bytes!("../../../tests/fixtures/sigstore_tuf/166.snapshot.json"); +const REAL_TARGETS_14: &[u8] = + include_bytes!("../../../tests/fixtures/sigstore_tuf/14.targets.json"); +const EMBEDDED_TUF_ROOT: &[u8] = include_bytes!("../../../assets/sigstore_tuf_root.json"); +const EMBEDDED_TRUSTED_ROOT: &[u8] = include_bytes!("../../../assets/sigstore_trusted_root.json"); + +fn at(text: &str) -> SystemTime { + Time::parse_rfc3339(text).unwrap().into() +} + +/// A time at which the real timestamp fixture, valid for a week, is current. +fn while_real_metadata_is_current() -> SystemTime { + at("2026-11-26T00:00:00Z") +} + +/// An in-memory repository that records which paths were requested. +#[derive(Default)] +struct Repository { + files: BTreeMap>, + requested: Mutex>, +} + +impl Repository { + fn with(mut self, path: &str, bytes: impl Into>) -> Self { + self.files.insert(path.to_string(), bytes.into()); + self + } + + fn requested(&self) -> Vec { + self.requested.lock().unwrap().clone() + } +} + +impl Fetcher for Repository { + async fn fetch(&self, path: &str, max_bytes: u64) -> Result>, String> { + self.requested.lock().unwrap().push(path.to_string()); + match self.files.get(path) { + Some(bytes) if bytes.len() as u64 > max_bytes => { + Err(format!("{path} is over {max_bytes} bytes")) + } + Some(bytes) => Ok(Some(bytes.clone())), + None => Ok(None), + } + } +} + +fn trusted_root_path(bytes: &[u8]) -> String { + format!( + "targets/{}.trusted_root.json", + hex::encode(Sha256::digest(bytes)) + ) +} + +/// Sigstore's real repository as it stood when the fixtures were captured, +/// seen by a client whose newest root is version 13. +fn real_repository() -> Repository { + Repository::default() + .with("14.root.json", REAL_ROOT_14) + .with("15.root.json", REAL_ROOT_15) + .with("16.root.json", REAL_ROOT_16) + .with("timestamp.json", REAL_TIMESTAMP) + .with("166.snapshot.json", REAL_SNAPSHOT_166) + .with("14.targets.json", REAL_TARGETS_14) + .with( + &trusted_root_path(EMBEDDED_TRUSTED_ROOT), + EMBEDDED_TRUSTED_ROOT, + ) +} + +fn refreshed( + embedded_root: &[u8], + stored: Option<&TrustedMetadata>, + repository: &Repository, + now: SystemTime, +) -> Result { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(refresh(embedded_root, stored, repository, now)) +} + +#[test] +fn real_sigstore_metadata_refreshes_through_three_root_rotations() { + let repository = real_repository(); + + let metadata = refreshed( + REAL_ROOT_13, + None, + &repository, + while_real_metadata_is_current(), + ) + .unwrap(); + + assert_eq!(metadata.roots.len(), 3); + assert_eq!(metadata.trusted_root.as_bytes(), EMBEDDED_TRUSTED_ROOT); + assert_eq!( + repository.requested(), + [ + "14.root.json", + "15.root.json", + "16.root.json", + "17.root.json", + "timestamp.json", + "166.snapshot.json", + "14.targets.json", + &trusted_root_path(EMBEDDED_TRUSTED_ROOT), + ] + ); + let verified = metadata.verified_trusted_root(REAL_ROOT_13).unwrap(); + assert_eq!(verified.bytes, EMBEDDED_TRUSTED_ROOT); + assert_eq!(verified.targets_version, 14); +} + +#[test] +fn the_embedded_tuf_root_signs_the_embedded_trust_root() { + assert_eq!(EMBEDDED_TUF_ROOT, REAL_ROOT_16); + let stored = TrustedMetadata { + roots: Vec::new(), + timestamp: String::from_utf8(REAL_TIMESTAMP.to_vec()).unwrap(), + snapshot: String::from_utf8(REAL_SNAPSHOT_166.to_vec()).unwrap(), + targets: String::from_utf8(REAL_TARGETS_14.to_vec()).unwrap(), + trusted_root: String::from_utf8(EMBEDDED_TRUSTED_ROOT.to_vec()).unwrap(), + }; + + let verified = stored.verified_trusted_root(EMBEDDED_TUF_ROOT).unwrap(); + + assert_eq!(verified.bytes, EMBEDDED_TRUSTED_ROOT); + assert_eq!( + verified.targets_version, + crate::sigstore_verify::trust_store::EMBEDDED_TRUSTED_ROOT_TARGETS_VERSION + ); +} + +#[test] +fn stored_roots_are_not_fetched_again() { + let repository = real_repository(); + let first = refreshed( + REAL_ROOT_13, + None, + &repository, + while_real_metadata_is_current(), + ) + .unwrap(); + let repository = real_repository(); + + let second = refreshed( + REAL_ROOT_13, + Some(&first), + &repository, + while_real_metadata_is_current(), + ) + .unwrap(); + + assert_eq!(second, first); + assert_eq!(repository.requested()[0], "17.root.json"); +} + +#[test] +fn a_root_its_predecessor_did_not_sign_is_refused() { + let mut tampered: Value = serde_json::from_slice(REAL_ROOT_15).unwrap(); + tampered["signed"]["expires"] = json!("2099-01-01T00:00:00Z"); + let repository = real_repository().with("15.root.json", serde_json::to_vec(&tampered).unwrap()); + + let error = refreshed( + REAL_ROOT_13, + None, + &repository, + while_real_metadata_is_current(), + ) + .unwrap_err(); + + assert!( + matches!( + error, + TufError::Threshold { + role: "root", + valid: 0, + .. + } + ), + "{error}" + ); +} + +#[test] +fn a_root_served_under_the_next_version_must_carry_that_version() { + let repository = real_repository().with("17.root.json", REAL_ROOT_16); + + let error = refreshed( + REAL_ROOT_13, + None, + &repository, + while_real_metadata_is_current(), + ) + .unwrap_err(); + + assert_eq!( + error, + TufError::Version { + role: "root", + expected: 17, + actual: 16 + } + ); +} + +#[test] +fn expired_timestamp_metadata_is_refused() { + let error = refreshed( + REAL_ROOT_13, + None, + &real_repository(), + at("2026-12-03T00:00:00Z"), + ) + .unwrap_err(); + + assert!( + matches!( + error, + TufError::Expired { + role: "timestamp", + .. + } + ), + "{error}" + ); +} + +#[test] +fn an_expired_final_root_is_refused_even_when_everything_else_verifies() { + let error = refreshed( + REAL_ROOT_13, + None, + &real_repository(), + at("2027-05-01T00:00:00Z"), + ) + .unwrap_err(); + + assert!( + matches!(error, TufError::Expired { role: "root", .. }), + "{error}" + ); +} + +#[test] +fn a_trust_root_that_differs_from_the_signed_hash_is_refused() { + let mut altered = EMBEDDED_TRUSTED_ROOT.to_vec(); + let last = altered.len() - 2; + altered[last] = b' '; + let repository = real_repository().with(&trusted_root_path(EMBEDDED_TRUSTED_ROOT), altered); + + let error = refreshed( + REAL_ROOT_13, + None, + &repository, + while_real_metadata_is_current(), + ) + .unwrap_err(); + + assert!( + matches!(&error, TufError::Mismatch { name, .. } if name == TRUSTED_ROOT_TARGET), + "{error}" + ); +} + +#[test] +fn stored_metadata_with_an_altered_trust_root_does_not_verify() { + let mut stored = refreshed( + REAL_ROOT_13, + None, + &real_repository(), + while_real_metadata_is_current(), + ) + .unwrap(); + stored.trusted_root = stored + .trusted_root + .replace("https://rekor.sigstore.dev", "https://rekor.example.com"); + + let error = stored.verified_trusted_root(REAL_ROOT_13).unwrap_err(); + + assert!(matches!(error, TufError::Mismatch { .. }), "{error}"); +} + +// ── Synthetic repositories ───────────────────────────────────── + +const SYNTHETIC_TRUSTED_ROOT: &[u8] = br#"{"mediaType":"synthetic"}"#; + +fn synthetic_repository( + roles: &RoleSet, + timestamp_version: u64, + snapshot_version: u64, + targets_version: u64, +) -> Repository { + Repository { + files: repository_files( + roles, + timestamp_version, + snapshot_version, + targets_version, + SYNTHETIC_TRUSTED_ROOT, + ), + requested: Mutex::default(), + } +} + +fn now() -> SystemTime { + at("2030-01-01T00:00:00Z") +} + +#[test] +fn a_repository_without_consistent_snapshots_is_read_by_plain_names() { + let roles = RoleSet { + consistent_snapshot: false, + ..RoleSet::new() + }; + let repository = synthetic_repository(&roles, 1, 1, 1); + + let metadata = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap(); + + assert_eq!(metadata.trusted_root.as_bytes(), SYNTHETIC_TRUSTED_ROOT); + assert!( + repository + .requested() + .contains(&"targets/trusted_root.json".to_string()) + ); +} + +#[test] +fn ed25519_keys_sign_metadata() { + let roles = RoleSet { + root: vec![TestKey::ed25519(9)], + timestamp: TestKey::ed25519(10), + snapshot: TestKey::ed25519(11), + targets: TestKey::ed25519(12), + ..RoleSet::new() + }; + + let metadata = refreshed( + &roles.signed_root(1), + None, + &synthetic_repository(&roles, 1, 1, 1), + now(), + ) + .unwrap(); + + assert_eq!(metadata.trusted_root.as_bytes(), SYNTHETIC_TRUSTED_ROOT); +} + +#[test] +fn an_older_timestamp_than_the_stored_one_is_refused() { + let roles = RoleSet::new(); + let embedded = roles.signed_root(1); + let stored = refreshed( + &embedded, + None, + &synthetic_repository(&roles, 5, 5, 5), + now(), + ) + .unwrap(); + + let error = refreshed( + &embedded, + Some(&stored), + &synthetic_repository(&roles, 4, 5, 5), + now(), + ) + .unwrap_err(); + + assert_eq!( + error, + TufError::Rollback { + role: "timestamp", + trusted: 5, + offered: 4 + } + ); +} + +#[test] +fn an_older_targets_version_than_the_stored_snapshot_records_is_refused() { + let roles = RoleSet::new(); + let embedded = roles.signed_root(1); + let stored = refreshed( + &embedded, + None, + &synthetic_repository(&roles, 5, 5, 5), + now(), + ) + .unwrap(); + + let error = refreshed( + &embedded, + Some(&stored), + &synthetic_repository(&roles, 6, 6, 4), + now(), + ) + .unwrap_err(); + + assert_eq!( + error, + TufError::Rollback { + role: "targets", + trusted: 5, + offered: 4 + } + ); +} + +#[test] +fn a_root_that_replaces_the_timestamp_key_lets_its_versions_restart() { + let roles = RoleSet::new(); + let embedded = roles.signed_root(1); + let stored = refreshed( + &embedded, + None, + &synthetic_repository(&roles, 5, 5, 5), + now(), + ) + .unwrap(); + let rotated = RoleSet { + timestamp: TestKey::p256(20), + snapshot: TestKey::p256(21), + ..roles + }; + let repository = + synthetic_repository(&rotated, 1, 1, 6).with("2.root.json", rotated.signed_root(2)); + + let metadata = refreshed(&embedded, Some(&stored), &repository, now()).unwrap(); + + assert_eq!(metadata.roots.len(), 1); +} + +#[test] +fn a_root_rotation_needs_the_previous_root_keys() { + let roles = RoleSet::new(); + let takeover = RoleSet { + root: vec![TestKey::p256(30)], + ..roles.clone() + }; + let repository = + synthetic_repository(&roles, 1, 1, 1).with("2.root.json", takeover.signed_root(2)); + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 0, + threshold: 1 + } + ); +} + +#[test] +fn a_key_listed_twice_counts_once_toward_the_threshold() { + let key = TestKey::p256(1); + let roles = RoleSet { + root: vec![key.clone(), key.clone()], + root_threshold: 2, + ..RoleSet::new() + }; + let embedded = roles.signed_root(1); + let next = roles.root(2, &[&key, &key]); + let repository = synthetic_repository(&roles, 1, 1, 1).with("2.root.json", next); + + let error = refreshed(&embedded, None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 1, + threshold: 2 + } + ); +} + +#[test] +fn targets_signed_by_another_key_are_refused() { + let roles = RoleSet::new(); + let impostor = RoleSet { + targets: TestKey::p256(40), + ..roles.clone() + }; + let honest = synthetic_repository(&roles, 1, 1, 1); + let forged = synthetic_repository(&impostor, 1, 1, 1); + let repository = honest.with("1.targets.json", forged.files["1.targets.json"].clone()); + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "targets", + valid: 0, + threshold: 1 + } + ); +} + +#[test] +fn stored_roots_must_still_chain_from_the_embedded_root() { + let roles = RoleSet::new(); + let takeover = RoleSet { + root: vec![TestKey::p256(50)], + ..roles.clone() + }; + let stored = TrustedMetadata { + roots: vec![String::from_utf8(takeover.signed_root(2)).unwrap()], + ..refreshed( + &takeover.signed_root(1), + None, + &synthetic_repository(&takeover, 1, 1, 1), + now(), + ) + .unwrap() + }; + + let error = stored + .verified_trusted_root(&roles.signed_root(1)) + .unwrap_err(); + + assert!( + matches!(error, TufError::Threshold { role: "root", .. }), + "{error}" + ); +} + +#[test] +fn a_missing_trust_root_target_is_reported() { + let roles = RoleSet::new(); + let mut repository = synthetic_repository(&roles, 1, 1, 1); + repository + .files + .retain(|path, _| !path.starts_with("targets/")); + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert!(matches!(error, TufError::Missing(_)), "{error}"); +} + +#[test] +fn one_key_under_two_ids_and_encodings_counts_once_toward_the_threshold() { + let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]); + let public = hex::encode(key.verifying_key().as_bytes()); + let root_with = |version: u64| { + json!({ + "_type": "root", + "spec_version": "1.0", + "version": version, + "expires": "2099-01-01T00:00:00Z", + "consistent_snapshot": true, + "keys": { + "lower": {"keytype": "ed25519", "scheme": "ed25519", "keyval": {"public": public}}, + "upper": {"keytype": "ed25519", "scheme": "ed25519", "keyval": {"public": public.to_uppercase()}}, + }, + "roles": { + "root": {"keyids": ["lower", "upper"], "threshold": 2}, + "timestamp": {"keyids": ["lower"], "threshold": 1}, + "snapshot": {"keyids": ["lower"], "threshold": 1}, + "targets": {"keyids": ["lower"], "threshold": 1}, + }, + }) + }; + let signed_by_both_ids = |signed: Value| { + use ed25519_dalek::Signer; + let mut message = Vec::new(); + canonical::encode(&signed, &mut message).unwrap(); + let sig = hex::encode(key.sign(&message).to_bytes()); + serde_json::to_vec(&json!({ + "signed": signed, + "signatures": [{"keyid": "lower", "sig": sig}, {"keyid": "upper", "sig": sig}], + })) + .unwrap() + }; + let repository = Repository::default().with("2.root.json", signed_by_both_ids(root_with(2))); + + let error = refreshed(&signed_by_both_ids(root_with(1)), None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 1, + threshold: 2 + } + ); +} + +#[test] +fn a_cache_written_before_the_built_in_root_was_updated_still_verifies() { + let roles = RoleSet::new(); + let repository = + synthetic_repository(&roles, 1, 1, 1).with("2.root.json", roles.signed_root(2)); + let stored = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap(); + assert_eq!(stored.roots.len(), 1); + + let verified = stored.verified_trusted_root(&roles.signed_root(2)).unwrap(); + + assert_eq!(verified.bytes, SYNTHETIC_TRUSTED_ROOT); +} + +#[test] +fn a_delegated_role_sigstore_drops_does_not_block_refreshes() { + let roles = RoleSet::new(); + let embedded = roles.signed_root(1); + let with_delegation = Repository { + files: repository_files_listing( + &roles, + 1, + 1, + 1, + SYNTHETIC_TRUSTED_ROOT, + &["registry.npmjs.org"], + ), + requested: Mutex::default(), + }; + let stored = refreshed(&embedded, None, &with_delegation, now()).unwrap(); + + refreshed( + &embedded, + Some(&stored), + &synthetic_repository(&roles, 2, 2, 2), + now(), + ) + .expect("only targets.json is held to its stored version"); +} + +#[test] +fn a_root_listing_a_key_this_client_cannot_read_still_verifies() { + let roles = RoleSet::new(); + let root_signers: Vec<&TestKey> = roles.root.iter().collect(); + let next = resigned(&roles.signed_root(2), &root_signers, |signed| { + signed["keys"]["future"] = json!({"keytype": "post-quantum", "keyval": {"x": [1, 2]}}); + }); + let repository = synthetic_repository(&roles, 1, 1, 1).with("2.root.json", next); + + let metadata = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap(); + + assert_eq!(metadata.roots.len(), 1); +} + +#[test] +fn a_root_whose_own_keys_did_not_sign_it_is_refused() { + let roles = RoleSet::new(); + let successor = RoleSet { + root: vec![TestKey::p256(60)], + ..roles.clone() + }; + let old_keys: Vec<&TestKey> = roles.root.iter().collect(); + let repository = + synthetic_repository(&roles, 1, 1, 1).with("2.root.json", successor.root(2, &old_keys)); + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 0, + threshold: 1 + } + ); +} + +#[test] +fn a_threshold_of_two_is_met_by_two_distinct_keys_only() { + let roles = RoleSet { + root: vec![TestKey::p256(70), TestKey::ed25519(71)], + root_threshold: 2, + ..RoleSet::new() + }; + let both: Vec<&TestKey> = roles.root.iter().collect(); + let one = [&roles.root[0]]; + let accepted = synthetic_repository(&roles, 1, 1, 1).with("2.root.json", roles.root(2, &both)); + let refused = synthetic_repository(&roles, 1, 1, 1).with("2.root.json", roles.root(2, &one)); + + refreshed(&roles.root(1, &both), None, &accepted, now()).unwrap(); + let error = refreshed(&roles.root(1, &both), None, &refused, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 1, + threshold: 2 + } + ); +} + +#[test] +fn a_key_of_an_unsupported_type_never_counts() { + let roles = RoleSet::new(); + let root_signers: Vec<&TestKey> = roles.root.iter().collect(); + let keyid = roles.root[0].keyid(); + let next = resigned(&roles.signed_root(2), &root_signers, |signed| { + signed["keys"][&keyid]["keytype"] = json!("rsa"); + signed["keys"][&keyid]["scheme"] = json!("rsassa-pss-sha256"); + }); + let repository = synthetic_repository(&roles, 1, 1, 1).with("2.root.json", next); + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert_eq!( + error, + TufError::Threshold { + role: "root", + valid: 0, + threshold: 1 + } + ); +} + +#[test] +fn metadata_of_version_zero_or_another_specification_is_refused() { + let roles = RoleSet::new(); + let root_signers: Vec<&TestKey> = roles.root.iter().collect(); + for (field, value) in [("version", json!(0)), ("spec_version", json!("2.0"))] { + let embedded = resigned(&roles.signed_root(1), &root_signers, |signed| { + signed[field] = value.clone(); + }); + + let error = refreshed( + &embedded, + None, + &synthetic_repository(&roles, 1, 1, 1), + now(), + ) + .unwrap_err(); + + assert!( + matches!(error, TufError::Malformed { role: "root", .. }), + "{field}: {error}" + ); + } +} + +#[test] +fn a_snapshot_that_differs_from_its_recorded_hash_is_refused() { + let roles = RoleSet::new(); + let mut repository = synthetic_repository(&roles, 1, 1, 1); + let snapshot = repository.files.get_mut("1.snapshot.json").unwrap(); + let space = snapshot.iter().position(|&byte| byte == b' ').unwrap(); + snapshot[space] = b'\t'; + + let error = refreshed(&roles.signed_root(1), None, &repository, now()).unwrap_err(); + + assert!( + matches!(&error, TufError::Mismatch { name, .. } if name == "snapshot.json"), + "{error}" + ); +} + +#[test] +fn a_cache_a_newer_binary_wrote_still_verifies_for_an_older_one() { + let roles = RoleSet::new(); + let older_built_in = roles.signed_root(1); + let newer_built_in = roles.signed_root(2); + let repository = synthetic_repository(&roles, 1, 1, 1) + .with("2.root.json", roles.signed_root(2)) + .with("3.root.json", roles.signed_root(3)); + let written_by_older = refreshed(&older_built_in, None, &repository, now()).unwrap(); + + let written_by_newer = + refreshed(&newer_built_in, Some(&written_by_older), &repository, now()).unwrap(); + + let verified = written_by_newer + .verified_trusted_root(&older_built_in) + .unwrap(); + assert_eq!(verified.bytes, SYNTHETIC_TRUSTED_ROOT); +} diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/13.root.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/13.root.json new file mode 100644 index 000000000..a50bcb233 --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/13.root.json @@ -0,0 +1,145 @@ +{ + "signatures": [ + { + "keyid": "6f260089d5923daf20166ca657c543af618346ab971884a99962b01988bbe0c3", + "sig": "" + }, + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3045022100bbddd464f8066ceb88ba787375c12cd6330680e08c2910703e6538c71cc79ad202205190b06e4537fe961b3ef81fe68edcd0089c19f919afed423b9aafd700641153" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "3044022069306cd5257f732a740c1afe60a8e433c5de58eafeadbe99c336c9c71d198cf802200d773953ae7dbc48d3e5bad9a6f64bafff196b7e2ad4a52a19519367d47dc042" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "304402204d21a2ec80df66e61f6fe2912951dc47df836036f8c0ab10816d375e71dbf79e0220547adce1afdf04e6794efa203dd5264c6f7e0ef78e57fe934b0d26cb994eec76" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "3045022060826496557144eb1649893ed5f6f4ea54536feb0ca82f8b89ae641be39743e5022100ad7118b5e9d4837326206e412fc6da2999925d110328a7c166b06c624336c93f" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "3046022100d8179439c2e73eb0c1733abee7faf832dcaea7263edcb4919891c3a247f05923022100e1a437e0797e803f9b72dc9d2d92155b0a2270c24efdd5f4b3a5d8f0b0f431a7" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2026-01-22T13:05:59Z", + "keys": { + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms:projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp/cryptoKeyVersions/1" + }, + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMxpPOJCIZ5otG4106fGJseEQi3V9\npkMYQ4uyV9Tj1M7WHXIyLG+jkfvuG0glQ1JZbRZZBV3gAR4sojdGHISeow==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@lance" + }, + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 6 + } + }, + "spec_version": "1.0", + "version": 13, + "x-tuf-on-ci-expiry-period": 197, + "x-tuf-on-ci-signing-period": 46 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.root.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.root.json new file mode 100644 index 000000000..93e19f3a0 --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.root.json @@ -0,0 +1,141 @@ +{ + "signatures": [ + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3046022100e04c9706299be5d8c2b14fb50bcd5b9c241f10597153dfe22f943efe896b5150022100cfd7b9f06a5900784e312d02b8e336edbb3b2fab61ac14550b3112b4f9e33df4" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "3045022100cc308ae7d390fa782ee3376ddfaa929835016e86dad81f69e2de7ec1e174432e02205fb19906a31cce146c29624443c0d0c2f33ee80dac39d72114f939607cc22937" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "304502203f8aff7a30e05a8c3d904b671ab1a6e4e8a6f508b7cfa0c780e72976bee7a227022100f64c9b765526f34d9ea16339cf238893e1c3368b4f0910a61a1af27dda01ebb9" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "304502202363ca249aefa6d5f61c408a32cdd079b034a7888ddf2136dc4515ed4a728418022100b04eca42bc510ccbbf5d30783aaa936b1f137ca7a017ee9d90d3710432da0427" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2026-06-22T13:27:01Z", + "keys": { + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms:projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp/cryptoKeyVersions/1" + }, + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMxpPOJCIZ5otG4106fGJseEQi3V9\npkMYQ4uyV9Tj1M7WHXIyLG+jkfvuG0glQ1JZbRZZBV3gAR4sojdGHISeow==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@lance" + }, + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 6 + } + }, + "spec_version": "1.0", + "version": 14, + "x-tuf-on-ci-expiry-period": 197, + "x-tuf-on-ci-signing-period": 46 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.targets.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.targets.json new file mode 100644 index 000000000..5ad0d090f --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/14.targets.json @@ -0,0 +1,173 @@ +{ + "signatures": [ + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "30440220560777f2e8093ef4e6289975f0ad5fbfb85dbb03e6bf98bff935737ddeeca80802206a85e2904843a842c7e651e46e7fe49874de99fa94f5051639a6dc6b5aee4f29" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "30450221008c1befccad604a4818eccc59d670f74f66b69f4bab38aca744777f304d4c176c022062d56c5c6a50504b73145ec08a2e102a0a5fd0476b097d32766f6580110348ff" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "3046022100d298094a3195317c1c3329ee31468f129d4ea28a7f049a410d4f443f01953472022100dfcc5b8bd15db6fb0e7c857d8c53d71706381c22f76f5c951ce8b411d0b08bc0" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "3046022100c1d91fe98b8a0a63dd2e98eb1048ff579990c29dad890fe8061a293e90a26113022100f843667831e0c69a7ba41f2a974e082e457ff8d5aebef06bd7be6d34bc2ac092" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "304402206e1d9520e65d9074ea5bd5e20dca600aeb3beb3f93f1699a9b1897101f7f3f01022018335bb010edacb9f8f0a9101438b53d4481324ada04bf656718beed11d21c53" + } + ], + "signed": { + "_type": "targets", + "delegations": { + "keys": { + "5e3a4021b11a425fd0a444f1670457ce5b15bbe036144f2417426f7f4b9721da": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVfei1dXQRVeArCMcTDgxJtYg+Fs7\nV87DjhQbGlRJPyC7SW5TbNNkmvpmi4LeTv6moLVZ7T2nVqiRZbSkD+cf8w==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "azurekms://npm-tuf-delegate.vault.azure.net/keys/npm-tuf-delegate-2024-08/e2772c1d01ca400da571096889f1660e" + } + }, + "roles": [ + { + "keyids": [ + "5e3a4021b11a425fd0a444f1670457ce5b15bbe036144f2417426f7f4b9721da" + ], + "name": "registry.npmjs.org", + "paths": [ + "registry.npmjs.org/*" + ], + "terminating": true, + "threshold": 1 + } + ] + }, + "expires": "2036-05-09T09:00:52Z", + "spec_version": "1.0", + "targets": { + "artifact.pub": { + "custom": { + "sigstore": { + "status": "Active", + "usage": "Unknown" + } + }, + "hashes": { + "sha256": "59ebf97a9850aecec4bc39c1f5c1dc46e6490a6b5fd2a6cacdcac0c3a6fc4cbf" + }, + "length": 177 + }, + "ctfe.pub": { + "custom": { + "sigstore": { + "status": "Active", + "uri": "https://ctfe.sigstore.dev/test", + "usage": "CTFE" + } + }, + "hashes": { + "sha256": "7fcb94a5d0ed541260473b990b99a6c39864c1fb16f3f3e594a5a3cebbfe138a" + }, + "length": 177 + }, + "ctfe_2022.pub": { + "custom": { + "sigstore": { + "status": "Active", + "uri": "https://ctfe.sigstore.dev/2022", + "usage": "CTFE" + } + }, + "hashes": { + "sha256": "270488a309d22e804eeb245493e87c667658d749006b9fee9cc614572d4fbbdc" + }, + "length": 178 + }, + "fulcio.crt.pem": { + "custom": { + "sigstore": { + "status": "Expired", + "uri": "https://fulcio.sigstore.dev", + "usage": "Fulcio" + } + }, + "hashes": { + "sha256": "f360c53b2e13495a628b9b8096455badcb6d375b185c4816d95a5d746ff29908" + }, + "length": 744 + }, + "fulcio_intermediate_v1.crt.pem": { + "custom": { + "sigstore": { + "status": "Active", + "uri": "https://fulcio.sigstore.dev", + "usage": "Fulcio" + } + }, + "hashes": { + "sha256": "f8cbecf186db7714624a5f4e99da31a917cbef70a94dd6921f5c3ca969dfe30a" + }, + "length": 789 + }, + "fulcio_v1.crt.pem": { + "custom": { + "sigstore": { + "status": "Active", + "uri": "https://fulcio.sigstore.dev", + "usage": "Fulcio" + } + }, + "hashes": { + "sha256": "f989aa23def87c549404eadba767768d2a3c8d6d30a8b793f9f518a8eafd2cf5" + }, + "length": 740 + }, + "rekor.pub": { + "custom": { + "sigstore": { + "status": "Active", + "uri": "https://rekor.sigstore.dev", + "usage": "Rekor" + } + }, + "hashes": { + "sha256": "dce5ef715502ec9f3cdfd11f8cc384b31a6141023d3e7595e9908a81cb6241bd" + }, + "length": 178 + }, + "signing_config.json": { + "hashes": { + "sha256": "d358c75d032833f4193500f5b01b5760409410558fac962c599439adbb268b0f" + }, + "length": 219 + }, + "signing_config.v0.2.json": { + "hashes": { + "sha256": "9711a6d5375706957a4859af31c5866a4474f81f0544f9f4b76c9c4f4c8a539c" + }, + "length": 1034 + }, + "signing_config_rekor_v2.v0.2.json": { + "hashes": { + "sha256": "0f5f38554e29e770d4d5d6f0e1b51fcbf84f61dc6934530a09b7a901eaad5bee" + }, + "length": 1230 + }, + "trusted_root.json": { + "hashes": { + "sha256": "6494e21ea73fa7ee769f85f57d5a3e6a08725eae1e38c755fc3517c9e6bc0b66" + }, + "length": 6787 + } + }, + "version": 14, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 31 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/15.root.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/15.root.json new file mode 100644 index 000000000..55115df10 --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/15.root.json @@ -0,0 +1,141 @@ +{ + "signatures": [ + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3045022100ea2f374f409810e2db950749d9cfed09a15b6a5e25f3d5ffd0799459d7bee167022028d3acdde6dbd5034cfad222d31b41090ee21894e2c46cb8974198ab0377db44" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "304402207ebb24e3237e470691d7875903a7754d0ef2ae7e7b5024a7888c9a38a52deecd02206ed5ad1c6f4fab46995843ab6b23f9420c5a4cf6ce1cb2cb2a6fc2e87e2ef3e1" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "304602210089d9dfd8e106cc958088a4da3c8cf7254ab6f65a9647d37ada730ef4763c5163022100d882ee744615be79861e214e1eeb9e1eddf6a1e203a201b4c5d03f5224d71d16" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "304502210088bd4b88e83f586ce568d27d04214c4ab3fd1894178ef015303d56afa939205302205538ebab93876abb9075ad77114bff28a0d79a7cc229b534a0c5ced5526b48e7" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "3045022100f35b07e938d4949caf82e69e86cc9db3b69b6dbc6740c1f343d06893f996fbeb022001e847d816259a96a49e42779a2350dab97b71c8ae7e26b2380c6fa7f58131b3" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2026-11-20T13:58:18Z", + "keys": { + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms:projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp/cryptoKeyVersions/1" + }, + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMxpPOJCIZ5otG4106fGJseEQi3V9\npkMYQ4uyV9Tj1M7WHXIyLG+jkfvuG0glQ1JZbRZZBV3gAR4sojdGHISeow==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@lance" + }, + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 6 + } + }, + "spec_version": "1.0", + "version": 15, + "x-tuf-on-ci-expiry-period": 197, + "x-tuf-on-ci-signing-period": 46 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/16.root.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/16.root.json new file mode 100644 index 000000000..bc73a8b9b --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/16.root.json @@ -0,0 +1,141 @@ +{ + "signatures": [ + { + "keyid": "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "sig": "3045022065c68f28ebe44d0a4e047a6e287f9669c8e3b31e08536396c67a1483326be8c6022100e7524a889e40de0df84231dd40e1fcc57fbbbf62055c17076568307dbc509046" + }, + { + "keyid": "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "sig": "304502206fedc4a382a0c5155e812c9b7461fe388ef704fef9e093c5c236e20abbf8e6620221008bbec36b63bf9baebc03a83c770cf9387efc90907eb83070b7a875129512d687" + }, + { + "keyid": "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "sig": "30450220468f4219db51c7e815e1e3d33d9987878aa12aeaf331604d5180dd60b19dfb350221009f778ef5e96647c08bd23d63f69c0cce6fc353d747b9d51f35dc0f8678de9fef" + }, + { + "keyid": "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "sig": "3045022029e2518a7bcac05ec0b227809ce0c969406743412f90dc5255401afb13363f4602210087a64182249e41dd11de91c9f385a33659bd60147a93d13c86b7a64e447f9826" + }, + { + "keyid": "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632", + "sig": "30450221008051c456ed2bf48aa5fc5742928ab0904266c1d6bdde5fc75ae20f12d098a95502203cc683bd86793808e6c9f89e2ca93f80b00c6ea64880ac4e37db69e2e86b24e3" + } + ], + "signed": { + "_type": "root", + "consistent_snapshot": true, + "expires": "2027-04-22T19:27:31Z", + "keys": { + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWRiGr5+j+3J5SsH+Ztr5nE2H2wO7\nBV+nO3s93gLca18qTOzHY1oWyAGDykMSsGTUBSt9D+An0KfKsD2mfSM42Q==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-online-uri": "gcpkms:projects/sigstore-root-signing/locations/global/keyRings/root/cryptoKeys/timestamp/cryptoKeyVersions/1" + }, + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632": { + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEMxpPOJCIZ5otG4106fGJseEQi3V9\npkMYQ4uyV9Tj1M7WHXIyLG+jkfvuG0glQ1JZbRZZBV3gAR4sojdGHISeow==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@lance" + }, + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzBzVOmHCPojMVLSI364WiiV8NPrD\n6IgRxVliskz/v+y3JER5mcVGcONliDcWMC5J2lfHmjPNPhb4H7xm8LzfSA==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@santiagotorres" + }, + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEinikSsAQmYkNeH5eYq/CnIzLaacO\nxlSaawQDOwqKy/tCqxq5xxPSJc21K4WIhs9GyOkKfzueY3GILzcMJZ4cWw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@bobcallaway" + }, + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0ghrh92Lw1Yr3idGV5WqCtMDB8Cx\n+D8hdC4w2ZLNIplVRoVGLskYa3gheMyOjiJ8kPi15aQ2//7P+oj7UvJPGw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@joshuagl" + }, + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2": { + "keyid_hash_algorithms": [ + "sha256", + "sha512" + ], + "keytype": "ecdsa", + "keyval": { + "public": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEXsz3SZXFb8jMV42j6pJlyjbjR8K\nN3Bwocexq6LMIb5qsWKOQvLN16NUefLc4HswOoumRsVVaajSpQS6fobkRw==\n-----END PUBLIC KEY-----\n" + }, + "scheme": "ecdsa-sha2-nistp256", + "x-tuf-on-ci-keyowner": "@mnm678" + } + }, + "roles": { + "root": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "snapshot": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 3650, + "x-tuf-on-ci-signing-period": 365 + }, + "targets": { + "keyids": [ + "e71a54d543835ba86adad9460379c7641fb8726d164ea766801a1c522aba7ea2", + "22f4caec6d8e6f9555af66b3d4c3cb06a3bb23fdc7e39c916c61f462e6f52b06", + "61643838125b440b40db6942f5cb5a31c0dc04368316eb2aaa58b95904a58222", + "a687e5bf4fab82b0ee58d46e05c9535145a2c9afb458f43d42b45ca0fdce2a70", + "183e64f37670dc13ca0d28995a3053f3740954ddce44321a41e46534cf44e632" + ], + "threshold": 3 + }, + "timestamp": { + "keyids": [ + "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5" + ], + "threshold": 1, + "x-tuf-on-ci-expiry-period": 7, + "x-tuf-on-ci-signing-period": 6 + } + }, + "spec_version": "1.0", + "version": 16, + "x-tuf-on-ci-expiry-period": 197, + "x-tuf-on-ci-signing-period": 46 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/166.snapshot.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/166.snapshot.json new file mode 100644 index 000000000..07325e4a2 --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/166.snapshot.json @@ -0,0 +1,54 @@ +{ + "signatures": [ + { + "keyid": "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5", + "sig": "3045022100a794d63a83037365ea3190890729e539c9f3f0fca041c7fa1264c1cb79a990a302205d7d4743fb6122acedfd253b7d494d1dab05f9d5092494e99cc41d856d7c5600" + } + ], + "signed": { + "_type": "snapshot", + "expires": "2036-10-04T08:51:19Z", + "meta": { + "registry.npmjs.org.json": { + "version": 9 + }, + "rekor.json": { + "hashes": { + "sha256": "9d2e1a5842937d8e0d3e3759170b0ad15c56c5df36afc5cf73583ddd283a463b", + "sha512": "176e9e710ddddd1b357a7d7970831bae59763395a0c18976110cbd35b25e5412dc50f356ec421a7a30265670cf7aec9ed84ee944ba700ec2394b9c876645b960" + }, + "length": 797, + "version": 3 + }, + "revocation.json": { + "hashes": { + "sha256": "6f60848ba8fb0955a02abfd1232fb3845dc9ee9f418bf03521a7ddb48217e040", + "sha512": "a965dddd0d0edef6c59e84cf02ecf5a53299f633fd339b2b61814a4219ab4df672a6390f265b8b29e1c8cea9368ea3440df013790759d50231a30df1c1f02551" + }, + "length": 800, + "version": 2 + }, + "root.json": { + "hashes": { + "sha256": "f5ad897c9414cca99629f400ac3585e41bd8ebb44c5af07fb08dd636a9eced9c", + "sha512": "7445ddfdd338ef786c324fc3d68f75be28cb95b7fb581d2a383e3e5dde18aa17029a5636ec0a22e9631931bbcb34057788311718ea41e21e7cdd3c0de13ede42" + }, + "length": 5297, + "version": 2 + }, + "staging.json": { + "hashes": { + "sha256": "cda57759abac5375397eea3531d7ca51e3a67da9a2dc93f2cdab749e2ae73149", + "sha512": "e9e59587bde453144c7079884a880c706f1d43f26e8bb23fac2b96a99569a2a30ae6cf51ec51c2454f760ce83d4c20915e062aede7f319b3da6a6ed1d26ca281" + }, + "length": 401, + "version": 2 + }, + "targets.json": { + "version": 14 + } + }, + "spec_version": "1.0", + "version": 166 + } +} \ No newline at end of file diff --git a/crates/lpm-cli/tests/fixtures/sigstore_tuf/timestamp.json b/crates/lpm-cli/tests/fixtures/sigstore_tuf/timestamp.json new file mode 100644 index 000000000..dee77146e --- /dev/null +++ b/crates/lpm-cli/tests/fixtures/sigstore_tuf/timestamp.json @@ -0,0 +1,19 @@ +{ + "signatures": [ + { + "keyid": "0c87432c3bf09fd99189fdc32fa5eaedf4e4a5fac7bab73fa04a2e0fc64af6f5", + "sig": "304502203ee86d10f76de69291c5ea08a2bd5aff87f8e73dc0458df063348a171a03a9b0022100973c727a7fc0590ff008763310aa5fbefba2521058c2098985279a38bc52d4de" + } + ], + "signed": { + "_type": "timestamp", + "expires": "2026-12-02T07:21:41Z", + "meta": { + "snapshot.json": { + "version": 166 + } + }, + "spec_version": "1.0", + "version": 844 + } +} \ No newline at end of file diff --git a/tests/workflows/tests/support/mod.rs b/tests/workflows/tests/support/mod.rs index a2264bd90..c15724dea 100644 --- a/tests/workflows/tests/support/mod.rs +++ b/tests/workflows/tests/support/mod.rs @@ -983,6 +983,10 @@ fn apply_lpm_env(cmd: &mut S, project: &TempProject) { // Disable update check (would make network calls) cmd.set_env("LPM_NO_UPDATE_CHECK", OsStr::new("1")); + // Verify against the Sigstore trust root built into the binary and never + // fetch Sigstore's current one. Tests of that fetch set their own value. + cmd.set_env("LPM_SIGSTORE_TUF_URL_OVERRIDE", OsStr::new("off")); + // Workflow tests use the shipped npm route. Requests addressed to // registry.npmjs.org go to the mock the project last targeted, or else to // a closed local port, so no test reaches the real registry. Lockfiles