Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 94 additions & 8 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ on:
env:
SKILLD_ROOT_KEY_ID: ${{ vars.SKILLD_ROOT_KEY_ID }}
SKILLD_ROOT_PUBLIC_KEY: ${{ vars.SKILLD_ROOT_PUBLIC_KEY }}
SKILLD_BACKUP_ROOT_KEY_ID: ${{ vars.SKILLD_BACKUP_ROOT_KEY_ID }}
SKILLD_BACKUP_ROOT_PUBLIC_KEY: ${{ vars.SKILLD_BACKUP_ROOT_PUBLIC_KEY }}
SKILLD_RELEASE_PUBLIC_KEY: ${{ vars.SKILLD_RELEASE_PUBLIC_KEY }}

jobs:
Expand All @@ -26,21 +28,105 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: lts/*
- name: Require the trusted root
- name: Require the trusted roots
shell: bash
run: |
test -n "$SKILLD_ROOT_KEY_ID" || {
echo 'SKILLD_ROOT_KEY_ID is required.' >&2
exit 1
}
test -n "$SKILLD_ROOT_PUBLIC_KEY" || {
echo 'SKILLD_ROOT_PUBLIC_KEY is required.' >&2
# Root key ids use only unreserved URL characters, so a URL path
# holds them without encoding.
id_pattern='^[A-Za-z0-9._~-]{1,100}$'
# 32 bytes in canonical unpadded base64url: 43 characters, and the
# last one leaves its two padding bits unset.
key_pattern='^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$'
for root in SKILLD_ROOT SKILLD_BACKUP_ROOT; do
key_id_name="${root}_KEY_ID"
public_key_name="${root}_PUBLIC_KEY"
key_id="${!key_id_name}"
public_key="${!public_key_name}"
if [[ ! $key_id =~ $id_pattern || $key_id == . || $key_id == .. ]]; then
echo "$key_id_name must be 1 to 100 characters from A-Z, a-z, 0-9, '.', '_', '~', and '-'." >&2
exit 1
fi
if [[ $key_id == skilld-root-2026 ]]; then
echo "$key_id_name names skilld-root-2026. Its private key is lost." >&2
exit 1
fi
if [[ ! $public_key =~ $key_pattern ]]; then
echo "$public_key_name must be a 32-byte Ed25519 public key in canonical unpadded base64url." >&2
exit 1
fi
done
if [[ $SKILLD_BACKUP_ROOT_KEY_ID == "$SKILLD_ROOT_KEY_ID" \
|| $SKILLD_BACKUP_ROOT_PUBLIC_KEY == "$SKILLD_ROOT_PUBLIC_KEY" ]]; then
echo 'The backup root must have its own key id and public key.' >&2
exit 1
}
fi
test -n "$SKILLD_RELEASE_PUBLIC_KEY" || {
echo 'SKILLD_RELEASE_PUBLIC_KEY is required. Run node scripts/release/release-signing.mjs generate-key.' >&2
exit 1
}
- name: Require skilld.dev to serve both pinned roots
timeout-minutes: 5
shell: bash
run: |
probe="$(mktemp -d)"
trap 'rm -rf "$probe"' EXIT
# Resolve this release's public Skill through the deployed service.
# Both roots must verify the same attestation before any native build.
jq -n --arg commit "$GITHUB_SHA" \
'{source: {provider: "github", owner: "skilld-dev", repository: "skilld",
selector: {type: "path", path: "skills/skilld"}, ref: {type: "commit", value: $commit}}}' \
> "$probe/request.json"
status="$(curl --fail --silent --show-error --proto '=https' --max-time 30 \
--output "$probe/resolution.json" --write-out '%{http_code}' \
--header 'Content-Type: application/json' --header 'Skilld-Capabilities: linked-files' \
--header "Idempotency-Key: release-$GITHUB_SHA-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" \
--data-binary "@$probe/request.json" 'https://skilld.dev/api/v1/resolutions')"
[[ $status == 200 || $status == 202 ]]
resolution_id="$(jq -er '.resolutionId | select(test("^[A-Za-z0-9_-]{1,100}$"))' "$probe/resolution.json")"
for attempt in {1..60}; do
state="$(jq -er --arg id "$resolution_id" 'select(.resolutionId == $id) | .state' "$probe/resolution.json")"
if [[ $state == ready ]]; then
break
fi
[[ $state == pending ]]
sleep 2
status="$(curl --fail --silent --show-error --proto '=https' --max-time 30 \
--output "$probe/resolution.json" --write-out '%{http_code}' \
"https://skilld.dev/api/v1/resolutions/$resolution_id")"
[[ $status == 200 ]]
done
jq -e --arg commit "$GITHUB_SHA" --arg id "$resolution_id" \
'select(.state == "ready" and .resolutionId == $id)
| .artifact | select(.visibility == "public" and .artifactId == .attestation.artifactId)
| .attestation | select(.source.owner == "skilld-dev" and .source.repository == "skilld"
and .source.skillPath == "skills/skilld" and .source.commitSha == $commit
and .source.visibility == "public")' \
"$probe/resolution.json" > "$probe/attestation.json"
# The CLI asks for each pinned root by its id. A root that skilld.dev
# does not serve leaves the release with one root or none.
require_served_root() (
local key_id_name="$1" public_key_name="$2"
local key_id="${!key_id_name}" public_key="${!public_key_name}"
local body status
body="$probe/$key_id_name.json"
# No --location: a redirect fails this check.
status="$(curl --fail --silent --show-error --proto '=https' \
--retry 3 --max-time 30 --output "$body" --write-out '%{http_code}' \
"https://skilld.dev/api/v1/trusted-roots/$key_id")" || {
echo "skilld.dev does not serve the trusted root $key_id from $key_id_name." >&2
exit 1
}
if [[ $status != 200 ]]; then
echo "skilld.dev answered HTTP $status for the trusted root $key_id from $key_id_name." >&2
exit 1
fi
)
require_served_root SKILLD_ROOT_KEY_ID SKILLD_ROOT_PUBLIC_KEY
require_served_root SKILLD_BACKUP_ROOT_KEY_ID SKILLD_BACKUP_ROOT_PUBLIC_KEY
cargo run --locked --quiet --package skilld-core --example verify-release-root \
-- "$probe/SKILLD_ROOT_KEY_ID.json" "$SKILLD_ROOT_KEY_ID" "$SKILLD_ROOT_PUBLIC_KEY" \
"$probe/attestation.json" \
"$probe/SKILLD_BACKUP_ROOT_KEY_ID.json" "$SKILLD_BACKUP_ROOT_KEY_ID" "$SKILLD_BACKUP_ROOT_PUBLIC_KEY"
- id: matrix
name: Read native package matrix
shell: bash
Expand Down
175 changes: 143 additions & 32 deletions crates/skilld-command/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use skilld_core::{
ArtifactAttestation, CheckOutcome, CommitAuthor, CommitSha, CommitSummary, ListedOrigin,
ListedSkill, LockedSource, MultiSkillRef, PreparedFile, RemoteError, RemoteSelector,
RepositoryVisibility, SearchResponse, SkillListing, SkillName, SourceRef, SourceRequest,
SourceSelector, SourceStatus, TrustedRoot, TrustedRootPin, VerifiedArtifact,
SourceSelector, SourceStatus, TrustedRoot, TrustedRootPin, TrustedRootPins, VerifiedArtifact,
VerifiedTrustedRoot, declared_skill_name, parse_search_response, prepare_unverified_files,
verify_artifact, verify_attestation, verify_linked_file, verify_trusted_root,
with_linked_files,
Expand Down Expand Up @@ -770,10 +770,59 @@ struct GithubCommitAuthor {

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum NativeRemoteConfig {
Pinned(TrustedRootPin),
Pinned(TrustedRootPins),
Unconfigured,
}

impl NativeRemoteConfig {
/// The trusted roots a build pins, from its compiled build variables.
///
/// An empty value counts as missing, because an unset GitHub Actions
/// variable arrives as an empty string. A build without a whole primary
/// root is unconfigured. A build with half a backup root, or a backup root
/// without a primary one, is unconfigured too, so it fails closed.
pub fn from_build_variables(
root_key_id: Option<&str>,
root_public_key: Option<&str>,
backup_root_key_id: Option<&str>,
backup_root_public_key: Option<&str>,
) -> Self {
match (
build_pin(root_key_id, root_public_key),
build_pin(backup_root_key_id, backup_root_public_key),
) {
(BuildPin::Whole(primary), BuildPin::Missing) => {
Self::Pinned(TrustedRootPins::new(primary, None))
}
(BuildPin::Whole(primary), BuildPin::Whole(backup)) => {
Self::Pinned(TrustedRootPins::new(primary, Some(backup)))
}
_ => Self::Unconfigured,
}
}
}

/// One trusted root pin as a build names it: both variables, neither, or one.
enum BuildPin {
Missing,
Whole(TrustedRootPin),
Partial,
}

fn build_pin(key_id: Option<&str>, public_key: Option<&str>) -> BuildPin {
match (
key_id.filter(|value| !value.is_empty()),
public_key.filter(|value| !value.is_empty()),
) {
(None, None) => BuildPin::Missing,
(Some(key_id), Some(public_key)) => BuildPin::Whole(TrustedRootPin {
key_id: key_id.to_owned(),
public_key: public_key.to_owned(),
}),
_ => BuildPin::Partial,
}
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum RemoteProgressStage {
Expand Down Expand Up @@ -942,15 +991,33 @@ impl SkilldRemote {
/// needs. Without either, the adapter applies its own limit.
fn execute_bounded(
&self,
mut request: HttpRequest,
request: HttpRequest,
allowed: AllowedOrigin,
deadline: Option<&mut ResolutionDeadline>,
transfer_timeout: Option<Duration>,
max_retries: usize,
) -> Result<HttpResponse, RemoteError> {
let response =
self.send_bounded(request, &allowed, deadline, transfer_timeout, max_retries)?;
if !(200..300).contains(&response.status) {
return Err(status_error(&response, &allowed));
}
Ok(response)
}

/// [`Self::execute_bounded`] without the status check: the final response
/// after retries and redirects, whatever its status.
fn send_bounded(
&self,
mut request: HttpRequest,
allowed: &AllowedOrigin,
mut deadline: Option<&mut ResolutionDeadline>,
transfer_timeout: Option<Duration>,
max_retries: usize,
) -> Result<HttpResponse, RemoteError> {
let mut redirects = 0_usize;
loop {
validate_request_url(&request.url, &allowed)?;
validate_request_url(&request.url, allowed)?;
let mut retry = 0_usize;
let response = loop {
if self.cancellation.is_cancelled() {
Expand Down Expand Up @@ -1016,7 +1083,7 @@ impl SkilldRemote {
let next = current.join(location).map_err(|_| {
RemoteError::new("REDIRECT_REJECTED", "the redirect URL is invalid")
})?;
validate_url(&next, &allowed)?;
validate_url(&next, allowed)?;
if matches!(allowed, AllowedOrigin::GithubTarball)
&& next.host_str() != Some("codeload.github.com")
{
Expand All @@ -1029,17 +1096,6 @@ impl SkilldRemote {
redirects += 1;
continue;
}
if !(200..300).contains(&response.status) {
return Err(match allowed {
AllowedOrigin::Github
| AllowedOrigin::GithubTarball
| AllowedOrigin::GithubFile => github_error(&response),
AllowedOrigin::Service(_) | AllowedOrigin::Artifact(_) => {
problem_error(&response)
}
AllowedOrigin::Api(_) => api::api_problem_error(&response),
});
}
return Ok(response);
}
}
Expand Down Expand Up @@ -1072,23 +1128,52 @@ impl SkilldRemote {
})
}

/// The trusted root of the first pin that skilld.dev serves, verified
/// against that pin.
///
/// skilld asks for each pinned root by its id, in pin order. Only a 404
/// moves on to the next pin. Any other failure, or a served root that
/// fails verification, stops here.
fn verified_root(&self) -> Result<VerifiedTrustedRoot, RemoteError> {
let NativeRemoteConfig::Pinned(pin) = &self.root_pin else {
let NativeRemoteConfig::Pinned(pins) = &self.root_pin else {
return Err(RemoteError::new(
"TRUSTED_ROOT_UNCONFIGURED",
"this build has no trusted root pin",
));
};
let request = HttpRequest {
method: HttpMethod::Get,
url: self.service_url("/api/v1/trusted-root")?.into(),
headers: vec![],
body: vec![],
response_limit: JSON_LIMIT,
};
let response = self.execute(request, AllowedOrigin::Service(self.endpoint.clone()))?;
let root: TrustedRoot = parse_json(&response.body)?;
verify_trusted_root(root, pin)
let allowed = AllowedOrigin::Service(self.endpoint.clone());
for pin in pins.iter() {
let request = HttpRequest {
method: HttpMethod::Get,
url: self.trusted_root_url(&pin.key_id)?,
headers: vec![],
body: vec![],
response_limit: JSON_LIMIT,
};
let response = self.send_bounded(request, &allowed, None, None, MAX_RETRIES)?;
if response.status == 404 {
continue;
}
if !(200..300).contains(&response.status) {
return Err(status_error(&response, &allowed));
}
let root: TrustedRoot = parse_json(&response.body)?;
return verify_trusted_root(root, pin);
}
Err(RemoteError::new(
"TRUSTED_ROOT_MISMATCH",
"skilld.dev serves no trusted root that this build pins",
))
}

/// `/api/v1/trusted-roots/{rootKeyId}`, with the id percent-encoded.
fn trusted_root_url(&self, key_id: &str) -> Result<String, RemoteError> {
let mut url = self.service_url("/")?;
url.path_segments_mut()
.map_err(|()| RemoteError::new("INVALID_ENDPOINT", "the API route is invalid"))?
.clear()
.extend(["api", "v1", "trusted-roots", key_id]);
Ok(url.into())
}

/// Resolve one source, and request a new Resolution when one fails for a
Expand Down Expand Up @@ -3031,8 +3116,8 @@ impl RemoteProvider for SkilldRemote {
commit_sha: &str,
) -> Result<RemoteSourceState, RemoteError> {
let descriptor = self.resolve(selector.source())?.descriptor;
let root = self.verified_root()?;
verify_attestation(&descriptor.attestation, &root)?;
let root = self.verified_root().map_err(untrusted_root)?;
verify_attestation(&descriptor.attestation, &root).map_err(untrusted_root)?;
if descriptor.artifact_id == artifact_id
&& descriptor.attestation.source.commit_sha == commit_sha
{
Expand Down Expand Up @@ -3061,8 +3146,8 @@ impl RemoteProvider for SkilldRemote {
});
}
let descriptor = self.resolve(selector.source())?.descriptor;
let root = self.verified_root()?;
verify_attestation(&descriptor.attestation, &root)?;
let root = self.verified_root().map_err(untrusted_root)?;
verify_attestation(&descriptor.attestation, &root).map_err(untrusted_root)?;
let access = match descriptor.visibility {
RepositoryVisibility::Public => RemoteComparisonAccess::PublicGithub,
RepositoryVisibility::Private => RemoteComparisonAccess::Hosted,
Expand Down Expand Up @@ -3678,7 +3763,7 @@ fn unverifiable_artifact(error: RemoteError, source_url: &str) -> RemoteError {
"The Skill did not cause this failure. skilld.dev is changing its signing key. Run the same command again in a minute.".to_owned()
}
"TRUSTED_ROOT_MISMATCH" | "TRUSTED_ROOT_INVALID" | "TRUSTED_ROOT_SIGNATURE_INVALID" => {
"Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to run skilld upgrade, then run the same command again.".to_owned()
return untrusted_root(error);
}
"HTTP_TRANSPORT" | "SERVICE_UNAVAILABLE" | "RATE_LIMITED" | "CANCELLED" => return error,
_ => format!(
Expand All @@ -3688,6 +3773,21 @@ fn unverifiable_artifact(error: RemoteError, source_url: &str) -> RemoteError {
error.with_next_step(next_step)
}

/// Add the upgrade step to a failure that means this build does not trust
/// the skilld.dev keys. Every other failure passes through unchanged.
fn untrusted_root(error: RemoteError) -> RemoteError {
match error.code {
"TRUSTED_ROOT_MISMATCH" | "TRUSTED_ROOT_INVALID" | "TRUSTED_ROOT_SIGNATURE_INVALID"
if error.next_step.is_none() =>
{
error.with_next_step(
"Do not retry. This skilld build does not trust the skilld.dev keys. Tell the user to upgrade skilld with npx skilld@latest or npm i -g skilld@latest. Then run the same command again.",
)
}
_ => error,
}
}

fn is_transfer_mismatch(code: &str) -> bool {
matches!(code, "ARTIFACT_SIZE_MISMATCH" | "ARTIFACT_DIGEST_MISMATCH")
}
Expand Down Expand Up @@ -3722,6 +3822,17 @@ struct Problem {
instance: Option<String>,
}

/// The error for a final response outside 2xx, in the shape its origin uses.
fn status_error(response: &HttpResponse, allowed: &AllowedOrigin) -> RemoteError {
match allowed {
AllowedOrigin::Github | AllowedOrigin::GithubTarball | AllowedOrigin::GithubFile => {
github_error(response)
}
AllowedOrigin::Service(_) | AllowedOrigin::Artifact(_) => problem_error(response),
AllowedOrigin::Api(_) => api::api_problem_error(response),
}
}

fn problem_error(response: &HttpResponse) -> RemoteError {
serde_json::from_slice::<Problem>(&response.body).map_or_else(
|_| service_unavailable_error(response),
Expand Down
Loading