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
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

`cargo +nightly fmt --check` and `cargo clippy --all-targets --locked` pass clean, and `cargo test` is green for every driver combo your change touches. The pre-push hook in `.githooks/` runs fmt and clippy; wire it up once per clone with `git config core.hooksPath .githooks`. Release tooling changes also need `node --test scripts/*.test.mjs`.

## Performance

Speed and a small memory footprint are why this server exists, so every change keeps them. Hot paths (block uploads, downloads, lookups) stream payloads and spend no more database round trips than the request needs. A change to a hot path runs the benchmark (see Commands) against an image of the base branch, and the PR reports both results.

## Tests

Every test starts its own server on a free port. `cargo test` alone runs against SQLite and filesystem storage. For another combo, start its services with `scripts/test-services.sh <db> <storage>` (`sqlite`, `postgres`, `mysql` Γ— `filesystem`, `s3`, `gcs`, `azblob`), then pick it with `TEST_DB_DRIVER` and `TEST_STORAGE_DRIVER`:
Expand Down
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ clap = { version = "4", default-features = false, features = ["derive", "env", "
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
http-range-header = "0.4"
futures-util = { version = "0.3", default-features = false, features = ["std"] }
getrandom = "0.4"
mimalloc = { version = "0.1", default-features = false }
jsonwebtoken = { version = "11", default-features = false, features = ["aws_lc_rs"] }
object_store = { version = "0.14", default-features = false, features = ["aws", "gcp", "azure"] }
Expand All @@ -29,6 +30,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_qs = "1"
sha2 = "0.10"
subtle = "2"
sqlx = { version = "0.9", default-features = false, features = ["mysql", "mysql-rsa", "postgres", "sqlite-bundled", "runtime-tokio", "tls-rustls-aws-lc-rs"] }
thiserror = "2"
twirp = "0.12"
Expand Down
3 changes: 3 additions & 0 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ _Avoid_: Cache age
**Upload**:
Cache data that is being received but has not yet become a Cache Entry.

**Upload Capability**:
The random secret in an Upload's URL that authorizes storing its Parts. Only its hash is stored.

**Storage Location**:
The stored data belonging to a Cache Entry.

Expand Down
11 changes: 11 additions & 0 deletions docs/adr/0012-upload-urls-carry-a-per-upload-capability.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
status: accepted
---

# Upload URLs carry a per-upload capability

The upload id in `signed_upload_url` was the only thing a Part upload had to know, so anyone who could reach the server and guess or observe a ten digit id could write into another workflow's upload (#259, #299). `CreateCacheEntry` now appends 256 random bits as `?sig=` to the URL, like the SAS on an Azure Blob URL, and stores only its SHA-256 in `uploads.capabilityHash`. Single-shot, block and block list requests must present it; a mismatch, compared in constant time, is a 403.

`@actions/cache` and BuildKit build their requests with the Azure SDK, which keeps a SAS query, so clients need no change. We rejected HMAC-signed, expiring URLs (#259) because they need a signing secret per deployment and a rotation story, while a random capability per upload needs no configuration and dies with its upload.

The column is nullable so replicas still on the previous version can insert during a rollout. Their uploads, and uploads in flight during the upgrade, have no hash, so this version refuses their Parts: those saves fail once and the next run saves again. Until the rollout completes, previous-version replicas still accept Parts without the capability.
13 changes: 4 additions & 9 deletions examples/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ impl Client {
let len = remaining.min(BLOCK_BYTES);
let block_id = BASE64.encode(format!("{}{index:012}", uuid::Uuid::new_v4()));
self.http
.put(format!("{url}?comp=block&blockid={}", urlencode(&block_id)))
.put(url)
.query(&[("comp", "block"), ("blockid", &block_id)])
.body(block.slice(..len as usize))
.send()
.await?
Expand All @@ -207,7 +208,8 @@ impl Client {
index += 1;
}
self.http
.put(format!("{url}?comp=blocklist"))
.put(url)
.query(&[("comp", "blocklist")])
.body("")
.send()
.await?
Expand Down Expand Up @@ -254,13 +256,6 @@ impl Client {
}
}

fn urlencode(value: &str) -> String {
value
.replace('+', "%2B")
.replace('/', "%2F")
.replace('=', "%3D")
}

fn token() -> Result<String> {
let claims = json!({
"ac": json!([{ "Scope": "refs/heads/main", "Permission": 3 }]).to_string(),
Expand Down
3 changes: 3 additions & 0 deletions src/db/entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ pub(crate) mod uploads {
pub(crate) folder_name: String,
/// Nullable so replicas still on the previous version can insert during a rollout.
pub(crate) reservation_hash: Option<String>,
/// SHA-256 of the capability in the upload's URL; uploads from before it was added have
/// none.
pub(crate) capability_hash: Option<String>,
}

impl ActiveModelBehavior for ActiveModel {}
Expand Down
6 changes: 5 additions & 1 deletion src/db/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! rebuild, so it is dropped and recreated, and storage is cleared with it.

mod baseline;
mod upload_capabilities;

use sea_orm::ActiveValue::Set;
use sea_orm::sea_query::{Order, Query, Table};
Expand All @@ -20,7 +21,10 @@ struct Migrator;

impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(baseline::Migration)]
vec![
Box::new(baseline::Migration),
Box::new(upload_capabilities::Migration),
]
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/db/migrations/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ async fn v9_database(applied: &[&str]) -> (tempfile::TempDir, Db) {
let db = Db::open(&Config::from_vars(vars).unwrap().db)
.await
.unwrap();
Migrator::up(&db.pool, None).await.unwrap();
// The baseline alone is v9.10's schema.
Migrator::up(&db.pool, Some(1)).await.unwrap();
Migrator::uninstall(&db.pool).await.unwrap();
db.pool
.execute_unprepared("create table kysely_migration (name varchar(255) primary key)")
Expand Down
31 changes: 31 additions & 0 deletions src/db/migrations/upload_capabilities.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//! Stores the hash of each upload's capability, which its URL must carry (ADR-0012).

use sea_orm_migration::prelude::*;
use sea_orm_migration::schema::char_len_null;

pub(super) struct Migration;

impl MigrationName for Migration {
fn name(&self) -> &'static str {
"m0002_upload_capabilities"
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
#[expect(
elided_lifetimes_in_paths,
reason = "`async_trait` rejects the trait's elided lifetime spelled out"
)]
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
// Nullable: uploads created before have none and are refused until cleanup removes them.
manager
.alter_table(
Table::alter()
.table("uploads")
.add_column(char_len_null("capabilityHash", 64))
.take(),
)
.await
}
}
19 changes: 11 additions & 8 deletions src/routes/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,17 @@ impl crate::twirp::CacheService for AppState {
let CreateCacheEntryRequest { key, version } = req.into_body();
let identity = save_identity(&scope, key, version)?;
match self.storage.create_upload(&identity).await? {
CreatedUpload::Created { id } => Ok(twirp::Response::new(CreateCacheEntryResponse {
ok: true,
signed_upload_url: format!(
"{}/devstoreaccount1/upload/{id}",
self.config.api_base_url
),
message: String::new(),
})),
CreatedUpload::Created { upload, capability } => {
Ok(twirp::Response::new(CreateCacheEntryResponse {
ok: true,
// The capability is base64url, so it needs no escaping.
signed_upload_url: format!(
"{}/devstoreaccount1/upload/{}?sig={capability}",
self.config.api_base_url, upload.id
),
message: String::new(),
}))
}
// GitHub answers a duplicate reservation with 409, not 200 with ok: false.
CreatedUpload::AlreadyExists => Err(twirp::already_exists(
"cache entry with the same key, version, and scope already exists",
Expand Down
36 changes: 29 additions & 7 deletions src/routes/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ use serde::Deserialize;

use super::AppState;
use crate::http::HttpError;
use crate::storage::{DownloadError, EndPosition, Extent, RangeRequest, StartPosition};
use crate::storage::{
DownloadError, EndPosition, Extent, RangeRequest, StartPosition, UploadAccess,
};

/// Clients without a request id intermittently fail with EOF (tonistiigi/go-actions-cache).
const REQUEST_ID: HeaderName = HeaderName::from_static("x-ms-request-id");
Expand Down Expand Up @@ -61,11 +63,13 @@ fn chunk_index(block_id: &str) -> Option<u32> {
}
}

/// Query of an Azure `Put Block` / `Put Block List` request.
/// Query of an Azure `Put Blob` / `Put Block` / `Put Block List` request.
#[derive(Debug, Deserialize)]
pub(super) struct BlockQuery {
comp: Option<String>,
blockid: Option<String>,
/// The upload's capability, kept by Azure clients like the `sig` of a SAS URL.
sig: Option<String>,
}

pub(super) async fn upload(
Expand All @@ -78,6 +82,20 @@ pub(super) async fn upload(
let Path(upload_id) = upload_id.map_err(|_rejection| {
HttpError::bad_request("Invalid path parameters: uploadId must be a number")
})?;
let upload = match state
.storage
.authorize_upload(upload_id, query.sig.as_deref())
.await?
{
UploadAccess::Granted(upload) => upload,
UploadAccess::Forbidden => {
return Err(HttpError::new(
StatusCode::FORBIDDEN,
"Invalid upload signature",
));
}
UploadAccess::NotFound => return Err(upload_not_found(upload_id)),
};
if query.comp.as_deref() == Some("blocklist") {
return Ok(created());
}
Expand All @@ -94,17 +112,21 @@ pub(super) async fn upload(
let stream = body.into_data_stream().map_err(io::Error::other).boxed();
if !state
.storage
.upload_part(upload_id, index, stream, length)
.upload_part(&upload, index, stream, length)
.await?
{
return Err(HttpError::new(
StatusCode::NOT_FOUND,
format!("Upload not found: {upload_id}"),
));
return Err(upload_not_found(upload_id));
}
Ok(created())
}

fn upload_not_found(upload_id: i64) -> HttpError {
HttpError::new(
StatusCode::NOT_FOUND,
format!("Upload not found: {upload_id}"),
)
}

/// A single range; multi-range requests and invalid headers, which includes inverted ranges, are
/// served whole.
fn parse_range(headers: &HeaderMap) -> Option<RangeRequest> {
Expand Down
Loading
Loading