From c175c2c77d7d359b3add5970e3dd30df6028a8bd Mon Sep 17 00:00:00 2001 From: Abdelhadi Sabani Date: Sat, 14 Nov 2026 00:28:25 +0000 Subject: [PATCH 1/5] feat(auth): per-team tokens from TURBO_TOKENS_DIR With one shared TURBO_TOKEN, any team that can use the cache can read and overwrite every other team's artifacts by changing TURBO_TEAM. TURBO_TOKENS_DIR binds each token to one team: the directory holds one file per team, named after the team, containing the SHA-256 hex of that team's token. - A request must name its team (slug, else teamId, the same extraction storage uses) and carry that team's token. No header or an unknown token is 401; a token of another team, or no team named, is 403. - The directory is re-read every 10 seconds, so teams can be added, removed or rotated without a restart; dotfiles (Kubernetes' ..data links) are ignored. An unreadable directory at start stops the server; later, the last good set is kept. - Setting both TURBO_TOKEN and TURBO_TOKENS_DIR stops the server. - With TURBO_TOKENS_DIR unset, behaviour is unchanged. The health check stays open. --- Cargo.lock | 1 + Cargo.toml | 1 + src/app_settings.rs | 13 ++ src/auth/mod.rs | 1 + src/auth/team_tokens.rs | 369 +++++++++++++++++++++++++++++++++++++++ src/auth/turbo_token.rs | 105 ++++++++--- src/routes/artifacts.rs | 43 ++++- src/startup.rs | 12 +- src/storage.rs | 2 + tests/e2e/helpers.rs | 9 + tests/e2e/main.rs | 1 + tests/e2e/team_tokens.rs | 355 +++++++++++++++++++++++++++++++++++++ 12 files changed, 878 insertions(+), 34 deletions(-) create mode 100644 src/auth/team_tokens.rs create mode 100644 tests/e2e/team_tokens.rs diff --git a/Cargo.lock b/Cargo.lock index 2aaf277..3ae080b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -722,6 +722,7 @@ dependencies = [ "rust-s3", "secrecy", "serde", + "sha2", "subtle", "sysinfo 0.40.3", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 4af55c3..65c2053 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ tonic = "0.14.2" secrecy = "0.10.3" tracing-actix-web = "0.7" subtle = "2" +sha2 = "0.10" [dev-dependencies] pretty_assertions = "1.4.1" diff --git a/src/app_settings.rs b/src/app_settings.rs index 8890c8d..76dd4ab 100644 --- a/src/app_settings.rs +++ b/src/app_settings.rs @@ -1,7 +1,11 @@ use secrecy::SecretString; use std::env; use std::fmt; +use std::path::PathBuf; use std::str::FromStr; +use std::time::Duration; + +use crate::auth::team_tokens::DEFAULT_RELOAD_INTERVAL; /// Server-side encryption algorithms supported by AWS S3. /// See: https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html @@ -73,7 +77,13 @@ pub struct AppSettings { pub s3_bucket_name: String, /// The server-side encryption algorithm to use for the S3 bucket. pub s3_server_side_encryption: Option, + /// One token shared by every team. Cannot be combined with `turbo_tokens_dir`. pub turbo_token: Option, + /// A directory with one file per team holding the SHA-256 hex of that + /// team's token. Cannot be combined with `turbo_token`. + pub turbo_tokens_dir: Option, + /// How often `turbo_tokens_dir` is re-read. + pub turbo_tokens_reload_interval: Duration, } pub fn get_settings() -> AppSettings { @@ -101,6 +111,7 @@ pub fn get_settings() -> AppSettings { let s3_bucket_name = env::var("S3_BUCKET_NAME").unwrap_or("turbo".to_owned()); let turbo_token = env::var("TURBO_TOKEN").ok().map(SecretString::from); + let turbo_tokens_dir = env::var_os("TURBO_TOKENS_DIR").map(PathBuf::from); AppSettings { host, @@ -113,6 +124,8 @@ pub fn get_settings() -> AppSettings { s3_use_path_style, s3_server_side_encryption, turbo_token, + turbo_tokens_dir, + turbo_tokens_reload_interval: DEFAULT_RELOAD_INTERVAL, } } diff --git a/src/auth/mod.rs b/src/auth/mod.rs index f03291a..3f4dea2 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -1 +1,2 @@ +pub mod team_tokens; pub mod turbo_token; diff --git a/src/auth/team_tokens.rs b/src/auth/team_tokens.rs new file mode 100644 index 0000000..17cf35e --- /dev/null +++ b/src/auth/team_tokens.rs @@ -0,0 +1,369 @@ +use std::{ + collections::HashMap, + fmt, fs, io, + path::{Path, PathBuf}, + sync::{Arc, RwLock}, + time::Duration, +}; + +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +/// How often the server re-reads `TURBO_TOKENS_DIR` by default. +pub const DEFAULT_RELOAD_INTERVAL: Duration = Duration::from_secs(10); + +/// A SHA-256 digest of one team's token. +type TokenHash = [u8; 32]; + +/// What a presented token proves about a request. +#[derive(Debug, PartialEq, Eq)] +pub enum TeamCheck { + /// The token belongs to the team the request names. + Valid, + /// The token belongs to another team, or the request names no team. + OtherTeam, + /// The token belongs to no team. + UnknownToken, +} + +/// Per-team tokens read from `TURBO_TOKENS_DIR`. +/// +/// The directory holds one file per team: the file name is the team (the +/// `TURBO_TEAM` value Turborepo sends as `slug` or `teamId`) and the content +/// is the lowercase hex SHA-256 of that team's token. The server only ever +/// holds hashes, so the directory can be shared without the tokens. +pub struct TeamTokens { + dir: PathBuf, + hashes: RwLock>>, +} + +impl fmt::Debug for TeamTokens { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Team names only; the hashes stay out of Debug output. + f.debug_struct("TeamTokens") + .field("dir", &self.dir) + .field("teams", &self.current().len()) + .finish() + } +} + +impl TeamTokens { + /// Reads the directory once. An unreadable directory is an error, so the + /// server refuses to start rather than reject every request. + pub fn load(dir: impl Into) -> io::Result { + let dir = dir.into(); + let hashes = read_dir(&dir)?; + tracing::info!(teams = hashes.len(), "Loaded per-team tokens"); + Ok(Self { + dir, + hashes: RwLock::new(Arc::new(hashes)), + }) + } + + /// Re-reads the directory. When it cannot be read, the last good set stays + /// in use: a transient failure must not lock every team out. + pub fn reload(&self) { + match read_dir(&self.dir) { + Ok(hashes) => { + if *self.current() != hashes { + tracing::info!(teams = hashes.len(), "Reloaded per-team tokens"); + *self.hashes.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(hashes); + } + } + Err(error) => { + tracing::error!( + error = %error, + "Could not re-read TURBO_TOKENS_DIR. Keeping the last good tokens" + ); + } + } + } + + /// Re-reads the directory every `interval` for as long as the runtime + /// runs. Kubernetes updates a mounted Secret by swapping a symlink, which + /// a poll sees without any file watcher. + pub fn watch(self: Arc, interval: Duration) { + tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval); + // The first tick fires at once; `load` has just read the directory. + ticker.tick().await; + loop { + ticker.tick().await; + let tokens = Arc::clone(&self); + if let Err(error) = tokio::task::spawn_blocking(move || tokens.reload()).await { + tracing::error!(error = %error, "Per-team token reload failed"); + } + } + }); + } + + /// Checks a token against the team a request names. + /// + /// Every stored hash is compared in constant time, so the answer does not + /// depend on how many bytes of a guess were right. + pub fn check(&self, token: &str, team: Option<&str>) -> TeamCheck { + let presented: TokenHash = Sha256::digest(token.as_bytes()).into(); + let hashes = self.current(); + + let mut known = false; + let mut for_team = false; + for (name, expected) in hashes.iter() { + if bool::from(presented.ct_eq(expected)) { + known = true; + for_team |= team == Some(name.as_str()); + } + } + + match (for_team, known) { + (true, _) => TeamCheck::Valid, + (false, true) => TeamCheck::OtherTeam, + (false, false) => TeamCheck::UnknownToken, + } + } + + fn current(&self) -> Arc> { + Arc::clone(&self.hashes.read().unwrap_or_else(|e| e.into_inner())) + } +} + +/// Reads every team file in `dir`. Names starting with `.` are skipped: they +/// are Kubernetes' `..data` links and timestamped directories, or editor files. +/// A file whose content is not a SHA-256 hex digest is skipped with a warning. +fn read_dir(dir: &Path) -> io::Result> { + let mut hashes = HashMap::new(); + for entry in fs::read_dir(dir)? { + let entry = entry?; + let Some(team) = entry.file_name().to_str().map(str::to_owned) else { + tracing::warn!("Skipping a TURBO_TOKENS_DIR entry whose name is not UTF-8"); + continue; + }; + if team.starts_with('.') { + continue; + } + + // Follows symlinks: a mounted Secret's keys link into `..data/`. + let path = entry.path(); + if !fs::metadata(&path)?.is_file() { + continue; + } + + match parse_sha256_hex(&fs::read_to_string(&path)?) { + Some(hash) => { + hashes.insert(team, hash); + } + None => { + tracing::warn!( + team = %team, + "Skipping a team whose token file is not a SHA-256 hex digest" + ); + } + } + } + Ok(hashes) +} + +/// Parses 64 hex characters, ignoring trailing whitespace such as a newline. +fn parse_sha256_hex(content: &str) -> Option { + let hex = content.trim_end().as_bytes(); + if hex.len() != 64 { + return None; + } + + let mut hash = [0u8; 32]; + let (pairs, _) = hex.as_chunks::<2>(); + for (byte, [high, low]) in hash.iter_mut().zip(pairs) { + let high = char::from(*high).to_digit(16)?; + let low = char::from(*low).to_digit(16)?; + *byte = u8::try_from(high << 4 | low).ok()?; + } + Some(hash) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + /// An arbitrary SHA-256 hex digest. + const ALPHA_HASH: &str = "8f0f7ba4b0e3e0e0c6a4c0fd6ab1a7a5fb1d1f7d2f3c1a0b8e2f1c0d9e8f7a6b"; + + fn hash_hex(token: &str) -> String { + Sha256::digest(token.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("decay-team-tokens-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn tokens_for(name: &str, teams: &[(&str, &str)]) -> (PathBuf, TeamTokens) { + let dir = temp_dir(name); + for (team, token) in teams { + fs::write(dir.join(team), format!("{}\n", hash_hex(token))).unwrap(); + } + let tokens = TeamTokens::load(&dir).unwrap(); + (dir, tokens) + } + + #[test] + fn parses_a_lowercase_digest_with_a_trailing_newline() { + let hash = parse_sha256_hex(&format!("{ALPHA_HASH}\n")).unwrap(); + assert_eq!(hash[0], 0x8f); + assert_eq!(hash[31], 0x6b); + } + + #[test] + fn rejects_content_that_is_not_a_digest() { + assert_eq!(parse_sha256_hex(""), None); + assert_eq!(parse_sha256_hex("abc"), None); + assert_eq!(parse_sha256_hex(&ALPHA_HASH[..63]), None); + assert_eq!(parse_sha256_hex(&format!("{ALPHA_HASH}00")), None); + assert_eq!(parse_sha256_hex(&ALPHA_HASH.replace('8', "g")), None); + assert_eq!(parse_sha256_hex(&format!(" {}", &ALPHA_HASH[1..])), None); + } + + #[test] + fn accepts_the_token_of_the_named_team() { + let (_, tokens) = tokens_for("valid", &[("alpha", "alpha-token")]); + assert_eq!(tokens.check("alpha-token", Some("alpha")), TeamCheck::Valid); + } + + #[test] + fn rejects_the_token_of_another_team() { + let (_, tokens) = tokens_for("other", &[("alpha", "alpha-token"), ("beta", "beta-token")]); + assert_eq!( + tokens.check("beta-token", Some("alpha")), + TeamCheck::OtherTeam + ); + } + + #[test] + fn rejects_a_known_token_when_no_team_is_named() { + let (_, tokens) = tokens_for("no-team", &[("alpha", "alpha-token")]); + assert_eq!(tokens.check("alpha-token", None), TeamCheck::OtherTeam); + } + + #[test] + fn rejects_an_unknown_token() { + let (_, tokens) = tokens_for("unknown", &[("alpha", "alpha-token")]); + assert_eq!( + tokens.check("guess", Some("alpha")), + TeamCheck::UnknownToken + ); + assert_eq!(tokens.check("guess", None), TeamCheck::UnknownToken); + } + + #[test] + fn rejects_a_team_that_has_no_file() { + let (_, tokens) = tokens_for("missing-team", &[("alpha", "alpha-token")]); + assert_eq!( + tokens.check("alpha-token", Some("gamma")), + TeamCheck::OtherTeam + ); + } + + #[test] + fn accepts_teams_that_share_a_token() { + let (_, tokens) = tokens_for("shared", &[("alpha", "same-token"), ("beta", "same-token")]); + assert_eq!(tokens.check("same-token", Some("alpha")), TeamCheck::Valid); + assert_eq!(tokens.check("same-token", Some("beta")), TeamCheck::Valid); + } + + #[test] + fn skips_dotfiles_directories_and_malformed_files() { + let dir = temp_dir("skips"); + fs::write(dir.join(".hidden"), hash_hex("hidden-token")).unwrap(); + fs::create_dir(dir.join("..2026_11_14")).unwrap(); + fs::create_dir(dir.join("nested")).unwrap(); + fs::write(dir.join("broken"), "not a digest").unwrap(); + fs::write(dir.join("alpha"), hash_hex("alpha-token")).unwrap(); + + let tokens = TeamTokens::load(&dir).unwrap(); + + assert_eq!(tokens.current().len(), 1); + assert_eq!( + tokens.check("hidden-token", Some(".hidden")), + TeamCheck::UnknownToken + ); + assert_eq!(tokens.check("alpha-token", Some("alpha")), TeamCheck::Valid); + } + + /// Kubernetes mounts a Secret as `..data -> ../` with one + /// ` -> ..data/` link per key, and swaps `..data` on update. + #[cfg(unix)] + #[test] + fn reads_a_mounted_secret_through_its_symlinks() { + use std::os::unix::fs::symlink; + + let dir = temp_dir("secret-mount"); + let first = dir.join("..2026_11_14_first"); + fs::create_dir(&first).unwrap(); + fs::write(first.join("alpha"), hash_hex("alpha-token")).unwrap(); + symlink("..2026_11_14_first", dir.join("..data")).unwrap(); + symlink("..data/alpha", dir.join("alpha")).unwrap(); + + let tokens = TeamTokens::load(&dir).unwrap(); + assert_eq!(tokens.check("alpha-token", Some("alpha")), TeamCheck::Valid); + + let second = dir.join("..2026_11_14_second"); + fs::create_dir(&second).unwrap(); + fs::write(second.join("alpha"), hash_hex("rotated-token")).unwrap(); + symlink("..2026_11_14_second", dir.join("..data_tmp")).unwrap(); + fs::rename(dir.join("..data_tmp"), dir.join("..data")).unwrap(); + tokens.reload(); + + assert_eq!( + tokens.check("alpha-token", Some("alpha")), + TeamCheck::UnknownToken + ); + assert_eq!( + tokens.check("rotated-token", Some("alpha")), + TeamCheck::Valid + ); + } + + #[test] + fn picks_up_new_and_removed_teams_on_reload() { + let (dir, tokens) = tokens_for("reload", &[("alpha", "alpha-token")]); + + fs::write(dir.join("beta"), hash_hex("beta-token")).unwrap(); + fs::remove_file(dir.join("alpha")).unwrap(); + tokens.reload(); + + assert_eq!(tokens.check("beta-token", Some("beta")), TeamCheck::Valid); + assert_eq!( + tokens.check("alpha-token", Some("alpha")), + TeamCheck::UnknownToken + ); + } + + #[test] + fn keeps_the_last_good_tokens_when_the_directory_goes_away() { + let (dir, tokens) = tokens_for("gone", &[("alpha", "alpha-token")]); + + fs::remove_dir_all(&dir).unwrap(); + tokens.reload(); + + assert_eq!(tokens.check("alpha-token", Some("alpha")), TeamCheck::Valid); + } + + #[test] + fn fails_to_load_a_missing_directory() { + let dir = temp_dir("missing").join("does-not-exist"); + assert!(TeamTokens::load(dir).is_err()); + } + + #[test] + fn keeps_hashes_out_of_debug_output() { + let (_, tokens) = tokens_for("debug", &[("alpha", "alpha-token")]); + let debug = format!("{tokens:?}"); + assert!(debug.contains("teams: 1"), "{debug}"); + assert!(!debug.contains(&hash_hex("alpha-token")), "{debug}"); + } +} diff --git a/src/auth/turbo_token.rs b/src/auth/turbo_token.rs index 625e944..fc0756b 100644 --- a/src/auth/turbo_token.rs +++ b/src/auth/turbo_token.rs @@ -1,3 +1,5 @@ +use std::{io, sync::Arc}; + use actix_web::{ Error, HttpResponse, body::MessageBody, @@ -7,53 +9,104 @@ use actix_web::{ web::Data, }; -use secrecy::ExposeSecret; +use secrecy::{ExposeSecret, SecretString}; use serde::Serialize; use subtle::ConstantTimeEq; -use crate::app_settings::AppSettings; +use crate::{ + app_settings::AppSettings, + auth::team_tokens::{TeamCheck, TeamTokens}, + routes::team_from_query, +}; #[derive(Serialize)] struct AuthError { error: &'static str, } +/// How the server authenticates artifact requests. +pub enum TokenAuth { + /// Neither `TURBO_TOKEN` nor `TURBO_TOKENS_DIR` is set: every request is accepted. + Open, + /// `TURBO_TOKEN`: one token shared by every team. + Shared(SecretString), + /// `TURBO_TOKENS_DIR`: each team has its own token, valid for that team only. + PerTeam(Arc), +} + +impl TokenAuth { + /// Picks the mode from the settings and reads `TURBO_TOKENS_DIR` once. + /// Fails when both variables are set, since either reading of that is a + /// guess, and when the tokens directory cannot be read. + pub fn from_settings(settings: &AppSettings) -> io::Result { + match (&settings.turbo_token, &settings.turbo_tokens_dir) { + (Some(_), Some(_)) => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "TURBO_TOKEN and TURBO_TOKENS_DIR are both set. Set only one", + )), + (Some(token), None) => Ok(Self::Shared(token.clone())), + (None, Some(dir)) => TeamTokens::load(dir) + .map(|tokens| Self::PerTeam(Arc::new(tokens))) + .map_err(|error| { + io::Error::new( + error.kind(), + format!("Could not read TURBO_TOKENS_DIR {}: {error}", dir.display()), + ) + }), + (None, None) => Ok(Self::Open), + } + } +} + /// What the middleware decided about the incoming request. enum Outcome { - /// No `TURBO_TOKEN` is configured, so the server accepts every request. + /// No token is configured, so the server accepts every request. NoTokenConfigured, Valid, MissingHeader, InvalidToken, + /// A per-team token that is valid, but not for the team the request names. + WrongTeam, } -/// Rejects requests that do not carry the configured `TURBO_TOKEN` as a Bearer token. -/// Lets every request through when no token is configured. +/// Rejects requests that do not carry a valid token as a Bearer token: the +/// shared `TURBO_TOKEN`, or the token of the team the request names when +/// `TURBO_TOKENS_DIR` is set. Lets every request through when neither is configured. pub async fn validate_turbo_token( req: ServiceRequest, next: Next, ) -> Result, Error> { // Scoped so no borrow of `req` outlives the decision and blocks the move below. let outcome = { - let app_settings = req - .app_data::>() - .expect("AppSettings must be registered as app data"); - - match &app_settings.turbo_token { - None => Outcome::NoTokenConfigured, - Some(expected) => { - let provided = req - .headers() - .get(header::AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .and_then(parse_bearer_token); - - match provided { - None => Outcome::MissingHeader, - Some(token) if tokens_match(token, expected.expose_secret()) => Outcome::Valid, - Some(_) => Outcome::InvalidToken, + let token_auth = req + .app_data::>() + .expect("TokenAuth must be registered as app data"); + + let provided = || { + req.headers() + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .and_then(parse_bearer_token) + }; + + match token_auth.as_ref() { + TokenAuth::Open => Outcome::NoTokenConfigured, + TokenAuth::Shared(expected) => match provided() { + None => Outcome::MissingHeader, + Some(token) if tokens_match(token, expected.expose_secret()) => Outcome::Valid, + Some(_) => Outcome::InvalidToken, + }, + TokenAuth::PerTeam(tokens) => match provided() { + None => Outcome::MissingHeader, + Some(token) => { + let team = team_from_query(req.query_string()); + match tokens.check(token, team.as_deref()) { + TeamCheck::Valid => Outcome::Valid, + TeamCheck::OtherTeam => Outcome::WrongTeam, + TeamCheck::UnknownToken => Outcome::InvalidToken, + } } - } + }, } }; @@ -74,6 +127,12 @@ pub async fn validate_turbo_token( tracing::warn!("Rejected request with an invalid TURBO_TOKEN"); Ok(unauthorized(req, "Invalid TURBO_TOKEN")) } + Outcome::WrongTeam => { + tracing::warn!("Rejected request with a TURBO_TOKEN of another team"); + Ok(req.into_response(HttpResponse::Forbidden().json(AuthError { + error: "TURBO_TOKEN is not for this team", + }))) + } } } diff --git a/src/routes/artifacts.rs b/src/routes/artifacts.rs index f3a28ae..f3ca314 100644 --- a/src/routes/artifacts.rs +++ b/src/routes/artifacts.rs @@ -178,19 +178,25 @@ pub async fn get_file(req: HttpRequest, cache: Data) -> impl Resp builder.streaming(stream) } -fn extract_team_from_req(req: &HttpRequest) -> String { - let query_string = Query::>::from_query(req.query_string()).unwrap(); - let default_team_name = "no_team".to_owned(); - query_string - .get("slug") - .or_else(|| query_string.get("teamId")) - .unwrap_or(&default_team_name) - .to_string() +/// The namespace of a request that names no team. Per-team tokens reject such +/// requests before they reach a handler, so only an open or shared-token server +/// stores artifacts here. +const DEFAULT_TEAM: &str = "no_team"; + +/// The team a request names: its `slug` query value, else its `teamId`. +/// Storage and per-team token checks both read the team from here, so a token +/// is always checked against the namespace the artifact is stored in. +pub fn team_from_query(query: &str) -> Option { + let mut query = Query::>::from_query(query) + .ok()? + .into_inner(); + query.remove("slug").or_else(|| query.remove("teamId")) } fn artifact_id_from_request(req: &HttpRequest) -> Option { let hash = req.match_info().get("hash")?.to_owned(); - ArtifactId::new(extract_team_from_req(req), hash) + let team = team_from_query(req.query_string()).unwrap_or_else(|| DEFAULT_TEAM.to_owned()); + ArtifactId::new(team, hash) } const DUMMY_CACHE_STATUS: CacheStatus = CacheStatus { status: "enabled" }; @@ -237,6 +243,25 @@ mod tests { assert_eq!(artifact_id_from_request(&no_team).unwrap().team, "no_team"); } + #[test] + fn reads_the_team_from_slug_then_team_id() { + assert_eq!( + team_from_query("teamId=fallback&slug=preferred"), + Some("preferred".to_owned()) + ); + assert_eq!(team_from_query("teamId=chosen"), Some("chosen".to_owned())); + assert_eq!(team_from_query("other=value"), None); + assert_eq!(team_from_query(""), None); + } + + #[test] + fn decodes_a_percent_encoded_team() { + assert_eq!( + team_from_query("slug=my%20team"), + Some("my team".to_owned()) + ); + } + #[test] fn reads_both_artifact_headers_from_the_request() { let req = TestRequest::default() diff --git a/src/startup.rs b/src/startup.rs index edf99ee..7255706 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -4,14 +4,14 @@ use actix_web::{ middleware::{Logger, from_fn}, web, }; -use std::net::TcpListener; +use std::{net::TcpListener, sync::Arc}; use tracing_actix_web::TracingLogger; use crate::{ app_settings::AppSettings, artifact_cache::ArtifactCache, - auth::turbo_token::validate_turbo_token, + auth::turbo_token::{TokenAuth, validate_turbo_token}, http_span::DecayRootSpanBuilder, routes::{ HEALTH_CHECK_PATH, artifacts_status, get_file, head_check_file, health_check, post_events, @@ -20,7 +20,14 @@ use crate::{ storage::Storage, }; +/// Must be called from within a Tokio runtime: with `TURBO_TOKENS_DIR` set, +/// it starts the task that re-reads the tokens directory. pub fn run(listener: TcpListener, app_settings: AppSettings) -> Result { + let token_auth = TokenAuth::from_settings(&app_settings)?; + if let TokenAuth::PerTeam(tokens) = &token_auth { + Arc::clone(tokens).watch(app_settings.turbo_tokens_reload_interval); + } + let token_auth = web::Data::new(token_auth); let cache = web::Data::new(ArtifactCache::new(Storage::new(&app_settings))); let port = listener .local_addr() @@ -46,6 +53,7 @@ pub fn run(listener: TcpListener, app_settings: AppSettings) -> Result, + /// Sets `TURBO_TOKENS_DIR`, re-read every 100 ms so tests see changes quickly. + pub turbo_tokens_dir: Option, /// Replaces the mock S3 endpoint. Point it at a dead address to exercise /// the path where the bucket cannot be reached. pub s3_endpoint: Option, } +/// How often a test server re-reads its tokens directory. +pub const TOKENS_RELOAD_INTERVAL: Duration = Duration::from_millis(100); + #[allow(clippy::let_underscore_future)] pub async fn spawn_app(config: Option) -> TestApp { dotenv().ok(); @@ -47,6 +54,8 @@ pub async fn spawn_app(config: Option) -> TestApp { app_settings.s3_access_key = Some("mock_access_key".into()); app_settings.s3_secret_key = Some("mock_secret_key".into()); app_settings.turbo_token = config.turbo_token.map(SecretString::from); + app_settings.turbo_tokens_dir = config.turbo_tokens_dir; + app_settings.turbo_tokens_reload_interval = TOKENS_RELOAD_INTERVAL; let server = decay::startup::run(listener, app_settings).expect("Could not bind to listener"); let _ = tokio::spawn(server); diff --git a/tests/e2e/main.rs b/tests/e2e/main.rs index 6be3c6a..e68e109 100644 --- a/tests/e2e/main.rs +++ b/tests/e2e/main.rs @@ -2,3 +2,4 @@ mod artifacts; mod auth; mod health_check; mod helpers; +mod team_tokens; diff --git a/tests/e2e/team_tokens.rs b/tests/e2e/team_tokens.rs new file mode 100644 index 0000000..451964e --- /dev/null +++ b/tests/e2e/team_tokens.rs @@ -0,0 +1,355 @@ +use std::fs; +use std::net::TcpListener; +use std::path::PathBuf; + +use decay::app_settings::get_settings; +use pretty_assertions::assert_eq; +use reqwest::{Method, Response}; +use sha2::{Digest, Sha256}; +use wiremock::{ + Mock, ResponseTemplate, + matchers::{method, path}, +}; + +use crate::helpers::{TOKENS_RELOAD_INTERVAL, TestApp, TestAppConfig, spawn_app}; + +const ALPHA_TOKEN: &str = "alpha-token"; +const BETA_TOKEN: &str = "beta-token"; + +/// The content of a team file: the token's SHA-256 as lowercase hex, with the +/// trailing newline `sha256sum` and most editors leave. +fn hash_line(token: &str) -> String { + let hex: String = Sha256::digest(token.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + format!("{hex}\n") +} + +/// A fresh tokens directory with one file per `(team, token)`. +fn tokens_dir(name: &str, teams: &[(&str, &str)]) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "decay-e2e-team-tokens-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + for (team, token) in teams { + fs::write(dir.join(team), hash_line(token)).unwrap(); + } + dir +} + +async fn spawn_with_teams(name: &str) -> (TestApp, PathBuf) { + let dir = tokens_dir(name, &[("alpha", ALPHA_TOKEN), ("beta", BETA_TOKEN)]); + let app = spawn_app(Some(TestAppConfig { + turbo_tokens_dir: Some(dir.clone()), + ..Default::default() + })) + .await; + (app, dir) +} + +async fn request( + app: &TestApp, + method: Method, + endpoint: &str, + auth_header: Option, +) -> Response { + let client = reqwest::Client::new(); + let mut request = client.request(method, format!("{}{}", app.address, endpoint)); + if let Some(value) = auth_header { + request = request.header("Authorization", value); + } + request + .send() + .await + .unwrap_or_else(|_| panic!("Failed to request {endpoint}")) +} + +fn bearer(token: &str) -> Option { + Some(format!("Bearer {token}")) +} + +async fn mount_bucket_object(app: &TestApp, team: &str, hash: &str) { + Mock::given(path(format!("/{}/{team}/{hash}", app.bucket_name))) + .and(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes("artifact")) + .mount(&app.storage_server) + .await; +} + +#[tokio::test] +async fn reads_an_artifact_with_the_token_of_its_team() { + let (app, _) = spawn_with_teams("read").await; + mount_bucket_object(&app, "alpha", "abc123").await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(ALPHA_TOKEN), + ) + .await; + + assert_eq!(response.status(), 200); + assert_eq!(response.text().await.unwrap(), "artifact"); +} + +#[tokio::test] +async fn stores_an_artifact_under_the_team_the_token_was_checked_for() { + let (app, _) = spawn_with_teams("store").await; + + Mock::given(path(format!("/{}/alpha/abc123", app.bucket_name))) + .and(method("PUT")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&app.storage_server) + .await; + + // `slug` wins over `teamId` for both the check and the object key. + let response = reqwest::Client::new() + .put(format!( + "{}/v8/artifacts/abc123?teamId=beta&slug=alpha", + app.address + )) + .header("Authorization", format!("Bearer {ALPHA_TOKEN}")) + .body("artifact") + .send() + .await + .unwrap(); + + assert_eq!(response.status(), 201); +} + +#[tokio::test] +async fn accepts_the_team_as_team_id() { + let (app, _) = spawn_with_teams("team-id").await; + mount_bucket_object(&app, "beta", "abc123").await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?teamId=beta", + bearer(BETA_TOKEN), + ) + .await; + + assert_eq!(response.status(), 200); +} + +#[tokio::test] +async fn forbidden_when_the_token_is_for_another_team() { + let (app, _) = spawn_with_teams("other-team").await; + + for method in [Method::GET, Method::PUT, Method::HEAD] { + let response = request( + &app, + method.clone(), + "/v8/artifacts/abc123?slug=alpha", + bearer(BETA_TOKEN), + ) + .await; + assert_eq!(response.status(), 403, "{method}"); + } + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(BETA_TOKEN), + ) + .await; + assert_eq!( + response.text().await.unwrap(), + r#"{"error":"TURBO_TOKEN is not for this team"}"# + ); + + // Nothing reached the bucket. + assert!( + app.storage_server + .received_requests() + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn forbidden_when_the_request_names_no_team() { + let (app, _) = spawn_with_teams("no-team").await; + + for endpoint in ["/v8/artifacts/abc123", "/v8/artifacts/status"] { + let response = request(&app, Method::GET, endpoint, bearer(ALPHA_TOKEN)).await; + assert_eq!(response.status(), 403, "{endpoint}"); + } + assert!( + app.storage_server + .received_requests() + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn forbidden_when_the_team_has_no_token_file() { + let (app, _) = spawn_with_teams("unknown-team").await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=gamma", + bearer(ALPHA_TOKEN), + ) + .await; + + assert_eq!(response.status(), 403); +} + +#[tokio::test] +async fn unauthorized_when_the_token_is_missing() { + let (app, _) = spawn_with_teams("missing").await; + + let response = request(&app, Method::GET, "/v8/artifacts/abc123?slug=alpha", None).await; + + assert_eq!(response.status(), 401); +} + +#[tokio::test] +async fn unauthorized_when_the_token_is_unknown() { + let (app, _) = spawn_with_teams("unknown").await; + + for endpoint in ["/v8/artifacts/abc123?slug=alpha", "/v8/artifacts/abc123"] { + let response = request(&app, Method::GET, endpoint, bearer("not-a-token")).await; + assert_eq!(response.status(), 401, "{endpoint}"); + } +} + +#[tokio::test] +async fn unauthorized_with_the_plain_hash_as_token() { + let (app, _) = spawn_with_teams("hash-as-token").await; + + let hash = hash_line(ALPHA_TOKEN); + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(hash.trim_end()), + ) + .await; + + assert_eq!(response.status(), 401); +} + +#[tokio::test] +async fn health_check_needs_no_token() { + let (app, _) = spawn_with_teams("health").await; + + let response = request(&app, Method::GET, "/management/health", None).await; + + assert_eq!(response.status(), 200); +} + +#[tokio::test] +async fn accepts_a_team_added_after_start() { + let (app, dir) = spawn_with_teams("added").await; + mount_bucket_object(&app, "gamma", "abc123").await; + + fs::write(dir.join("gamma"), hash_line("gamma-token")).unwrap(); + tokio::time::sleep(TOKENS_RELOAD_INTERVAL * 5).await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=gamma", + bearer("gamma-token"), + ) + .await; + assert_eq!(response.status(), 200); +} + +#[tokio::test] +async fn rejects_a_token_after_it_is_rotated() { + let (app, dir) = spawn_with_teams("rotated").await; + + fs::write(dir.join("alpha"), hash_line("new-alpha-token")).unwrap(); + tokio::time::sleep(TOKENS_RELOAD_INTERVAL * 5).await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(ALPHA_TOKEN), + ) + .await; + assert_eq!(response.status(), 401); +} + +#[tokio::test] +async fn keeps_the_last_tokens_when_the_directory_becomes_unreadable() { + let (app, dir) = spawn_with_teams("unreadable").await; + mount_bucket_object(&app, "alpha", "abc123").await; + + fs::remove_dir_all(&dir).unwrap(); + tokio::time::sleep(TOKENS_RELOAD_INTERVAL * 5).await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(ALPHA_TOKEN), + ) + .await; + assert_eq!(response.status(), 200); +} + +fn start(turbo_token: Option<&str>, turbo_tokens_dir: Option) -> std::io::Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let mut settings = get_settings(); + settings.turbo_token = turbo_token.map(Into::into); + settings.turbo_tokens_dir = turbo_tokens_dir; + decay::startup::run(listener, settings).map(drop) +} + +#[tokio::test] +async fn refuses_to_start_with_both_a_shared_token_and_a_tokens_dir() { + let dir = tokens_dir("both", &[("alpha", ALPHA_TOKEN)]); + + let error = start(Some("shared-token"), Some(dir)).unwrap_err(); + + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); + assert!( + error + .to_string() + .contains("TURBO_TOKEN and TURBO_TOKENS_DIR") + ); +} + +#[tokio::test] +async fn refuses_to_start_when_the_tokens_dir_cannot_be_read() { + let dir = tokens_dir("absent", &[]).join("does-not-exist"); + + let error = start(None, Some(dir)).unwrap_err(); + + assert!(error.to_string().contains("TURBO_TOKENS_DIR"), "{error}"); +} + +#[tokio::test] +async fn starts_with_an_empty_tokens_dir_and_rejects_every_token() { + let dir = tokens_dir("empty", &[]); + let app = spawn_app(Some(TestAppConfig { + turbo_tokens_dir: Some(dir), + ..Default::default() + })) + .await; + + let response = request( + &app, + Method::GET, + "/v8/artifacts/abc123?slug=alpha", + bearer(ALPHA_TOKEN), + ) + .await; + assert_eq!(response.status(), 401); +} From af9d914fea644351993f6ec0d8ce78bd3574bd1e Mon Sep 17 00:00:00 2001 From: Abdelhadi Sabani Date: Sat, 14 Nov 2026 00:35:14 +0000 Subject: [PATCH 2/5] build: embed the dependency list with cargo-auditable The release image is scratch plus one static binary, so an SBOM of it listed no crates. cargo-auditable records the binary's dependency tree in a section of the binary, which Syft and Trivy read: the SBOM now lists the crates the server runs with, and no dev-dependencies. --- .github/workflows/warm-build-cache.yml | 15 --------------- Dockerfile | 7 +++++-- 2 files changed, 5 insertions(+), 17 deletions(-) delete mode 100644 .github/workflows/warm-build-cache.yml diff --git a/.github/workflows/warm-build-cache.yml b/.github/workflows/warm-build-cache.yml deleted file mode 100644 index 5d08f8f..0000000 --- a/.github/workflows/warm-build-cache.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Warm build caches -on: - push: - branches: [main] - -concurrency: - group: warm-build-cache-${{ github.ref }} - cancel-in-progress: false - -jobs: - build: - permissions: - contents: read - packages: write - uses: ./.github/workflows/build-binaries.yml diff --git a/Dockerfile b/Dockerfile index 290190b..f26886a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,7 +3,8 @@ ARG RUST_VERSION=1.100.0 FROM rust:${RUST_VERSION}-alpine AS chef WORKDIR /app RUN apk add --no-cache musl-dev perl make && \ - cargo install --locked cargo-chef --version 0.1.78 + cargo install --locked cargo-chef --version 0.1.78 && \ + cargo install --locked cargo-auditable --version 0.7.7 FROM chef AS planner COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ @@ -17,7 +18,9 @@ RUN cargo chef cook --release --locked --recipe-path recipe.json COPY Cargo.toml Cargo.lock rust-toolchain.toml ./ COPY src ./src COPY tests ./tests -RUN cargo build --release --locked --bin decay +# cargo-auditable embeds the dependency tree in the binary, so SBOM tools +# (Syft, Trivy) list the crates the server actually runs with. +RUN cargo auditable build --release --locked --bin decay # Export a binary directly; no image registry or temporary container needed. FROM scratch AS artifact From 7471ed937d181c82c5b57390d821f21ea201df4c Mon Sep 17 00:00:00 2001 From: Abdelhadi Sabani Date: Sat, 14 Nov 2026 00:35:14 +0000 Subject: [PATCH 3/5] docs: lead with multi-tenancy and per-team tokens The README now presents the fork: one cache shared by many teams, each with a token bound to its namespace. It covers the problem a shared token leaves open, the model, tokens and hashes, Kubernetes, adding, removing and rotating tenants without a restart, cleanup, migration from a shared TURBO_TOKEN and security notes. The shared-token and open modes follow as also supported, unchanged. Upstream is credited, and images and the Action point at this repository. --- AGENTS.md | 4 +- README.md | 433 ++++++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 354 insertions(+), 83 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5b4ef5b..8d983db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Read this file before changing the repository. Keep these instructions short and - `src/startup.rs` composes the Actix app, routes, middleware, settings, and storage. - `src/routes/` handles the HTTP contract; `src/routes/artifacts.rs` maps artifact requests, responses, and metadata. - `src/storage.rs` owns S3 operations and translates storage failures. -- `src/auth/` handles the optional shared `TURBO_TOKEN`. +- `src/auth/` handles authentication: the optional shared `TURBO_TOKEN`, or per-team tokens from `TURBO_TOKENS_DIR` (`team_tokens.rs`). - `src/app_settings.rs` reads environment settings; `src/telemetry.rs` sets up tracing and metrics. - `tests/e2e/` exercises the server over HTTP with a Wiremock S3 endpoint. - `action/`, `Dockerfile`, and `.github/workflows/` package, test, and release the server. @@ -21,7 +21,7 @@ Read this file before changing the repository. Keep these instructions short and - Keep this one crate unless a concrete change needs a new module or crate. Put domain decisions in Rust types and functions close to the behavior they govern. Do not copy a database-oriented DDD layer structure into this server. - Keep HTTP parsing, status codes, and response shapes at the route seam; keep bucket access and S3 error translation in `storage.rs`. Wire concrete dependencies in `startup.rs`. - Preserve streaming for artifact uploads and downloads. Do not buffer whole artifacts merely to simplify a change. -- Treat request paths, query values, headers, and stored metadata as untrusted. Keep team and artifact key handling consistent across PUT, GET, and HEAD. A team name is a storage namespace, not an authenticated account: `TURBO_TOKEN` is one optional shared server token. +- Treat request paths, query values, headers, and stored metadata as untrusted. Keep team and artifact key handling consistent across PUT, GET, and HEAD. A team name is a storage namespace. With `TURBO_TOKEN` (one shared token) or no token, it is not authenticated; with `TURBO_TOKENS_DIR`, each token is bound to one team, so the team the token is checked for must be the namespace the request reads or writes (`team_from_query` serves both). - Do not log tokens, credentials, artifact contents, or unbounded client-supplied values. Keep secrets out of `Debug` output and tracing fields. - Prefer an existing dependency or a small local function before adding a crate. Record a consequential architecture choice and its reason in the PR or a short ADR when it needs lasting explanation. - Add a focused regression test for changed behavior. A prose rule that can be checked reliably should become a test or CI check when it matters. diff --git a/README.md b/README.md index 4e05185..7eb0357 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,288 @@


Turbo engine

-

Turbo Cache Server

+

Multi-tenant Turborepo Remote Cache

- Turborepo remote cache server, API-compliant as a GitHub Action or Docker with S3-compatible storage support. + One self-hosted, S3-backed Turborepo remote cache, shared safely by many teams or projects: each one has its own token, and that token only reads and writes its own namespace.

+

+ A fork of brunojppb/turbo-cache-server. +

+ +The server speaks Turborepo's +[remote cache API](https://turborepo.dev/docs/core-concepts/remote-caching#self-hosting), +stores artifacts in any S3-compatible bucket, and runs as a container, a +plain binary or a GitHub Action. It is stateless, so it scales horizontally. + +- [Why this fork](#why-this-fork) +- [Multi-tenancy: per-team tokens](#multi-tenancy-per-team-tokens) +- [Also supported: one shared token, or no authentication](#also-supported-one-shared-token-or-no-authentication) +- [Running it](#running-it): [GitHub Action](#github-action), [Docker](#docker), [Kubernetes](#deploying-to-kubernetes) +- [Releases and images](#releases-and-images) + +## Why this fork + +[brunojppb/turbo-cache-server](https://github.com/brunojppb/turbo-cache-server) +is a solid, small Turborepo cache server with one optional token shared by +every client. That fits one team. When several teams or projects share one +server, a shared token means every one of them can read, and overwrite, +everyone else's cache. This fork adds per-team tokens so one server can serve +them all safely, and publishes its own stable, signed releases. + +Everything else stays compatible with upstream: the same environment +variables, the same behaviour when `TURBO_TOKENS_DIR` is unset, and the same +GitHub Action. The per-team tokens feature is proposed upstream; if it is +merged there, this fork will follow upstream again. Credit for the server +goes to [Bruno Paulino](https://github.com/brunojppb) and upstream's +contributors; the license is unchanged ([MIT](LICENSE)). + +## Multi-tenancy: per-team tokens + +### The problem + +Turborepo sends its team (`TURBO_TEAM`) with every request, and the server +stores each artifact under that team's prefix in the bucket: +`//`. With one shared `TURBO_TOKEN`, the team is just a +label the client picks. Any project holding the shared token can set another +team's `TURBO_TEAM` and: + +- read that team's artifacts (build outputs, which may embed secrets or + unreleased code); +- **poison** that team's cache: upload a crafted artifact under a hash the + other team will request, and Turborepo restores it into their build. + +Turborepo's artifact signing (`remoteCache.signature`) detects tampering only +if every team keeps its own signing key and turns it on. Per-team tokens stop +the cross-team access at the server. + +### The model + +- **A team is a namespace.** Its artifacts live under `/` in the + bucket. The team is the request's `slug` query parameter, else its + `teamId`, the same value used for the storage key. +- **A token is bound to its team.** Each team has its own token. A request + must carry the token of the team it names, or it is rejected before it + reaches the bucket. +- **The server only holds hashes.** It reads `TURBO_TOKENS_DIR`: one file + per team, the file name is the team, the content is the lowercase hex + SHA-256 of that team's token. The tokens themselves live only with the + teams that use them. + +| Request | Response | +| --- | --- | +| No `Authorization: Bearer` header | `401` | +| Token that belongs to no team | `401` | +| Token of another team | `403` `{"error":"TURBO_TOKEN is not for this team"}` | +| Valid token, but the request names no team | `403` (there is no default namespace in this mode) | +| Token of the team the request names | handled as usual | + +The check applies to every route under `/v8/artifacts`, including +`/v8/artifacts/status`. `GET /management/health` stays open for probes. + +| Variable | Meaning | +| --- | --- | +| `TURBO_TOKENS_DIR` | Directory of per-team token hashes. Re-read every 10 seconds. | + +`TURBO_TOKENS_DIR` and `TURBO_TOKEN` cannot be combined: with both set, the +server refuses to start. If the directory cannot be read at start, the server +refuses to start; if it becomes unreadable later, the server keeps the last +set it read and logs an error. Names starting with `.` are ignored +(Kubernetes keeps `..data` links in a mounted Secret), and so is a file whose +content is not a SHA-256 hex digest (with a warning in the log). + +### Creating a token and its hash + +Use a long random token: 32 random bytes is plenty. + +```shell +TOKEN=$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=') +printf %s "$TOKEN" | sha256sum | cut -d' ' -f1 +# on macOS: printf %s "$TOKEN" | shasum -a 256 | cut -d' ' -f1 +``` + +`printf %s` matters: `echo` would add a newline to the hashed value. The hash +file may end with a newline; trailing whitespace is ignored. + +Give the token to the team's CI as `TURBO_TOKEN`, with `TURBO_TEAM` set to +the team's name. Turborepo sends `TURBO_TEAM` as `slug` (as `teamId` when it +starts with `team_`); the file name must match it exactly, including case. + +```shell +export TURBO_API="http://turbo-cache.example.internal:8000" +export TURBO_TEAM="web-app" +export TURBO_TOKEN="" +``` + +Locally, a directory with one file per team is enough: + +```shell +mkdir -p tokens +printf %s "$TOKEN" | sha256sum | cut -d' ' -f1 > tokens/web-app +TURBO_TOKENS_DIR=$PWD/tokens decay +``` + +### Setting it up in Kubernetes + +Keep the hashes in a Secret, one key per team, and mount it as a directory. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: turbo-cache-tokens +type: Opaque +stringData: + # key: the team (TURBO_TEAM); value: sha256 hex of that team's token + web-app: "" + api: "" +``` + +In the Deployment, mount it and point `TURBO_TOKENS_DIR` at it (and do not +set `TURBO_TOKEN`): + +```yaml + containers: + - name: turbo-cache-server + image: ghcr.io/13axis/turbo-cache-server:5.1 + env: + - name: TURBO_TOKENS_DIR + value: /etc/turbo-cache/tokens + # S3_* variables as in "Deploying to Kubernetes" below + volumeMounts: + - name: tokens + mountPath: /etc/turbo-cache/tokens + readOnly: true + volumes: + - name: tokens + secret: + secretName: turbo-cache-tokens +``` + +Do not mount it with `subPath`: Kubernetes does not update `subPath` mounts, +so new teams would need a restart. The full Deployment, Service and probes are +in [Deploying to Kubernetes](#deploying-to-kubernetes). + +### Adding or removing a tenant without a restart + +Change the Secret; the kubelet updates the mounted files (usually within a +minute or two) and the server picks the change up within 10 seconds after +that. + +```shell +# add or replace a team +kubectl patch secret turbo-cache-tokens --type merge \ + -p "{\"stringData\":{\"web-app\":\"$(printf %s "$TOKEN" | sha256sum | cut -d' ' -f1)\"}}" + +# remove a team: its token stops working +kubectl patch secret turbo-cache-tokens --type json \ + -p '[{"op":"remove","path":"/data/web-app"}]' +``` + +Outside Kubernetes, write or delete the team's file in `TURBO_TOKENS_DIR`. +Write the new file next to it and rename it into place, so the server never +reads a half-written file (a malformed file is skipped until it is complete). + +### Rotating a token + +Create a new token, replace the team's hash with the new one's, then update +the team's CI secret. The old token stops working as soon as the server +reloads; jobs that are already running with it get `401` on their remaining +cache requests, which Turborepo treats as cache misses, so rotate when the +team's pipelines are quiet. Two teams may share a token if you want them to; +each still needs its own file. + +### Cleaning up a tenant + +Removing a team's file only revokes its token. Its artifacts stay in the +bucket under `/`; delete that prefix to free the space: + +```shell +aws s3 rm "s3:///web-app/" --recursive +# S3-compatible stores: add --endpoint-url https://your-s3-endpoint +``` + +For routine cleanup of every tenant, set an expiration lifecycle rule on the +bucket (see [Managing Cache Storage with Lifecycle Rules](#managing-cache-storage-with-lifecycle-rules)); +a rule with a `/` prefix filter gives one tenant its own retention. + +### Migrating from a shared `TURBO_TOKEN` + +Artifacts are already stored per team, so nothing in the bucket moves. + +1. List the teams in use: the top-level prefixes in the bucket + (`aws s3 ls s3:///`). +2. Create a token and hash for each team and write the hashes to the tokens + directory or Secret. +3. Give each team its own token as `TURBO_TOKEN` in its CI. Until the server + switches, it still accepts only the shared token, so keep the shared value + until step 4 and switch each team's secret right after it. +4. On the server, remove `TURBO_TOKEN` and set `TURBO_TOKENS_DIR` (both set + makes it refuse to start), then roll it out. +5. Artifacts under `no_team/` (requests without a team) are no longer + reachable; delete that prefix. + +A team without a file gets `403` from then on: that is how a forgotten +project shows up. + +### Security notes + +- The server stores unsalted SHA-256 hashes. That is safe for long random + tokens like the ones above, not for passwords: never use a short or + memorable token. +- Tokens are compared in constant time, against every team's hash. +- Isolation is enforced by the server, not by the bucket: the server's S3 + credentials can reach every team's prefix. Keep those credentials, and the + bucket, out of the teams' reach. +- Keep the tokens directory readable only by the server. It holds hashes, + not tokens, but there is no reason to share it. +- Tokens travel in an HTTP header. Use TLS whenever the cache is reached over + a network you do not fully control. +- Team names are case-sensitive, and a team name cannot contain `/` or `\` + or be `.` or `..`. +- Per-team tokens control who may read and write each namespace. They do not + sign artifacts: turn on Turborepo's `remoteCache.signature` as well if you + want clients to verify what they restore. + +## Also supported: one shared token, or no authentication + +Without `TURBO_TOKENS_DIR`, the server behaves exactly like upstream. + +### One shared token (`TURBO_TOKEN`) + +The server runs **without authentication by default**. This is an +intentional design decision: in the vast majority of deployments the server +sits behind a private network (a VPC, a Kubernetes cluster, or a GitHub +Actions runner) where only trusted sources can reach it, and requiring a +shared token adds overhead without a meaningful security benefit. + +To enable authentication, set the `TURBO_TOKEN` environment variable on the +server. When set, every incoming request must include an +`Authorization: Bearer ` header or it will be rejected with +`401 Unauthorized`. Turborepo clients read their own `TURBO_TOKEN` env var +and send this header automatically, so the server-side and client-side +values must match. -## Trusted by folks at +The server reads the `Bearer` scheme in any case, as HTTP requires. It +compares the token itself in constant time, so the time a rejection takes +does not tell an attacker how much of a guess was correct. A rejected +request returns a JSON body that says whether the header was missing or the +token was wrong: + +```json +{ "error": "Invalid TURBO_TOKEN" } +``` + +When `TURBO_TOKEN` is unset on the server, the authentication middleware is +bypassed entirely and any `Authorization` header on incoming requests is +ignored. + +> [!TIP] +> If you expose the cache server to the public internet, or to networks you +> do not fully control, set `TURBO_TOKEN` on the server. If more than one team +> or project uses the server, use [per-team tokens](#multi-tenancy-per-team-tokens) +> instead. -
- -
+## Running it -### How can I use this in my monorepo? +### GitHub Action Make sure that you have an S3-compatible storage available. We currently tested with: @@ -30,7 +302,7 @@ The GitHub Action supports both **Linux** (`x64` and `arm64`) and **macOS Apple # TURBO_TOKEN is required by Turborepo to enable remote caching. # The cache server only validates it when TURBO_TOKEN is also set # on the server itself — otherwise the server accepts any value. - # See the "Authentication" section below for details. + # See "Also supported: one shared token, or no authentication" above. TURBO_TOKEN: "secret-turbo-token" ``` @@ -43,10 +315,10 @@ The GitHub Action supports both **Linux** (`x64` and `arm64`) and **macOS Apple - name: Turborepo Cache Server # Pin the action to a release commit SHA; keep its version in the comment. - # As we don't ship the latest versions of the binary on the main branch - # PLEASE see the latest versions here: - # https://github.com/brunojppb/turbo-cache-server/releases - uses: brunojppb/turbo-cache-server@2b77989368f018dcd51ecfa31712f9b2d8a1aed6 # 4.0.21 + # The binaries are only committed on release tags, not on main, so + # pick a release here: + # https://github.com/13axis/turbo-cache-server/releases + uses: 13axis/turbo-cache-server@ # v5.1.0 env: PORT: "8585" S3_BUCKET_NAME: your-bucket-name-here @@ -75,7 +347,10 @@ The GitHub Action supports both **Linux** (`x64` and `arm64`) and **macOS Apple ``` ```` -And that is all you need to use our remote cache server for Turborepo. As a +The Action runs one server for one workflow, so it does not need per-team +tokens; they are for a server that many projects share. + +And that is all you need to use the remote cache server for Turborepo. As a reference, take a look at [this example workflow file](https://github.com/brunojppb/turbo-decay/blob/main/.github/workflows/ci.yml) for inspiration. @@ -88,7 +363,7 @@ for inspiration. > [read more about this here](https://turbo.build/repo/docs/ci#setup) on the > Turborepo official docs. -## Gitlab support +### Docker For folks using Gitlab or any other CI environment that supports Docker, you can run the Turbo Cache Server as a docker container: @@ -101,45 +376,14 @@ docker run \ -e S3_ENDPOINT=https://s3_endpoint_here \ -e S3_REGION=eu \ -e S3_SERVER_SIDE_ENCRYPTION=AES256 \ - # Optional: enables authentication. See "Authentication" below. - -e TURBO_TOKEN=secret-turbo-token \ + # Optional: per-team tokens, see "Multi-tenancy" above + # (mount the directory with -v), or one shared TURBO_TOKEN. + -e TURBO_TOKENS_DIR=/etc/turbo-cache/tokens \ + -v "$PWD/tokens:/etc/turbo-cache/tokens:ro" \ -p "8000:8000" \ - ghcr.io/brunojppb/turbo-cache-server:latest + ghcr.io/13axis/turbo-cache-server:5.1 ``` -## Authentication - -Turbo Cache Server runs **without authentication by default**. This is an -intentional design decision: in the vast majority of deployments the server -sits behind a private network (a VPC, a Kubernetes cluster, or a GitHub -Actions runner) where only trusted sources can reach it, and requiring a -shared token adds overhead without a meaningful security benefit. - -To enable authentication, set the `TURBO_TOKEN` environment variable on the -server. When set, every incoming request must include an -`Authorization: Bearer ` header or it will be rejected with -`401 Unauthorized`. Turborepo clients read their own `TURBO_TOKEN` env var -and send this header automatically, so the server-side and client-side -values must match. - -The server reads the `Bearer` scheme in any case, as HTTP requires. It -compares the token itself in constant time, so the time a rejection takes -does not tell an attacker how much of a guess was correct. A rejected -request returns a JSON body that says whether the header was missing or the -token was wrong: - -```json -{ "error": "Invalid TURBO_TOKEN" } -``` - -When `TURBO_TOKEN` is unset on the server, the authentication middleware is -bypassed entirely and any `Authorization` header on incoming requests is -ignored. - -> [!TIP] -> If you expose the cache server to the public internet, or to networks you -> do not fully control, you should set `TURBO_TOKEN` on the server. - ## Deploying to Kubernetes Turbo Cache Server is a cloud-native, stateless application that runs seamlessly in Kubernetes environments. This makes it ideal for horizontally scaled deployments across multiple pods. @@ -167,7 +411,8 @@ type: Opaque stringData: S3_ACCESS_KEY: "your-access-key-here" S3_SECRET_KEY: "your-secret-key-here" - # Optional: omit to run without authentication. See "Authentication" above. + # Optional: one shared token. For several teams, leave it out and use + # per-team tokens instead (see "Setting it up in Kubernetes" above). TURBO_TOKEN: "secret-turbo-token" ``` @@ -197,7 +442,7 @@ spec: spec: containers: - name: turbo-cache-server - image: ghcr.io/brunojppb/turbo-cache-server:latest + image: ghcr.io/13axis/turbo-cache-server:5.1 ports: - containerPort: 8000 name: http @@ -640,14 +885,36 @@ ulimit -n 1024 ``` -## Building and releasing +## Releases and images + +Releases follow [SemVer](https://semver.org) and are listed in +[CHANGELOG.md](CHANGELOG.md). Tags are `v`; this fork's line +continues from upstream's 5.0.4 (see the changelog for the upstream version +each release is based on). + +| Image tag | Moves | +| --- | --- | +| `ghcr.io/13axis/turbo-cache-server:5.1.0` | never | +| `ghcr.io/13axis/turbo-cache-server:5.1` | to each 5.1.x patch release | +| `ghcr.io/13axis/turbo-cache-server:latest` | to each stable release | + +Images are multi-arch (`linux/amd64`, `linux/arm64`), built on `scratch` +with the static binary and CA certificates. Pin a digest in production. Each +release image carries: + +- a CycloneDX SBOM per platform, attached to the image digest as an OCI 1.1 + referrer: `oras discover ghcr.io/13axis/turbo-cache-server@`. The + binary is built with [cargo-auditable](https://github.com/rust-secure-code/cargo-auditable), + so the SBOM lists the crates it contains; +- build provenance: `gh attestation verify oci://ghcr.io/13axis/turbo-cache-server@ -R 13axis/turbo-cache-server`. -Release builds compile three executables in parallel: static Linux AMD64 and ARM64 -on native Linux runners, and macOS ARM64 on an Apple Silicon runner. The Linux -executables are reused for both GitHub downloads and the GHCR images; image -publication only adds the executable and CA certificates to `scratch`. +The GitHub release has static Linux binaries (x86-64, ARM64), a macOS Apple +Silicon binary, `SHA256SUMS`, the SBOMs, and provenance attestations for the +binaries. -`Dockerfile` remains a standalone source build. For example: +## Building and releasing + +`Dockerfile` is a standalone source build. For example: ```sh docker build -t decay . @@ -661,27 +928,31 @@ Cross-platform source builds need a matching native builder or QEMU; release CI uses native runners. `Dockerfile.release` is for packaging an already-built `linux/amd64/decay` and `linux/arm64/decay` context, without compilation. +Workflows, kept to what is needed: + +- `ci.yml`: format, lint and tests on every pull request. +- `build.yml`: the release build on pull requests that change packaging. +- `release.yml`, run by hand from `main` with a version (e.g. `5.1.0`): builds + the static Linux AMD64 and ARM64 executables and the macOS ARM64 one in + parallel on native runners, commits them on a release commit tagged + `v` (the GitHub Action runs the binaries in `action/`, which `main` + does not carry), pushes the image with its SBOMs and provenance, and creates + the GitHub release from the changelog entry. +- `snapshot.yml`, run by hand on any branch: an amd64 test image tagged + `sha-`, with its SBOM, for trying a change before it is released. + +To release: add the version's entry to `CHANGELOG.md` on `main`, then run +`release.yml` with that version. + Linux builds store Cargo Chef's intermediate dependency layers in GHCR under -`ghcr.io/brunojppb/turbo-cache-server:buildcache-amd64` and `:buildcache-arm64`, -using BuildKit's registry cache with `mode=max`. These cache tags remain available -between releases weeks apart, unless explicitly deleted or removed by a cleanup -policy. Keep them excluded from registry cleanup rules. Changing dependencies, -build flags or the Rust toolchain can invalidate cached layers. - -Trusted pushes to `main` and releases update the cache using `GITHUB_TOKEN` with -`packages: write`. PR builds restore anonymously from the existing public GHCR -package and never publish caches; fork PRs need no registry credentials. Writes -are serialized per architecture on the same branch. A missing cache causes a -normal cold build, and the first trusted run populates the cache tags. - -macOS still uses a separate GitHub Actions Cargo cache; it is subject to GitHub's -seven-day inactivity eviction and may rebuild dependencies after several idle -weeks. GHCR layer caching applies to the Linux Docker builds. - -Release images keep `ghcr.io/brunojppb/turbo-cache-server:` and `:latest`. -The macOS download is now `decay-aarch64-apple-darwin`, and the Action bundles -`decay-darwin-arm64`. Intel macOS and the universal download are discontinued; -older release tags remain available for Intel users. - -See [the release build analysis](docs/release-build-research.md) for measured -baseline timings, architecture alternatives, caching details, and sources. +`ghcr.io//turbo-cache-server:buildcache-amd64` and `:buildcache-arm64`, +using BuildKit's registry cache with `mode=max`. Keep them excluded from +registry cleanup rules. Releases update the cache using `GITHUB_TOKEN` with +`packages: write`; pull request builds restore anonymously and never publish +caches. A missing cache causes a normal cold build. + +macOS uses a separate GitHub Actions Cargo cache; it is subject to GitHub's +seven-day inactivity eviction and may rebuild dependencies after idle weeks. + +See [the release build analysis](docs/release-build-research.md) (upstream's) +for measured timings, architecture alternatives, caching details, and sources. From b9c04295e4b4d6fcacb129469896dbc34273cc98 Mon Sep 17 00:00:00 2001 From: Abdelhadi Sabani Date: Sat, 14 Nov 2026 00:35:15 +0000 Subject: [PATCH 4/5] ci: releases for this fork, with SBOMs and provenance - release.yml, run by hand from main with a version: tags v on a release commit carrying the Action's binaries, pushes the multi-arch image as , . and latest with BuildKit provenance, a build provenance attestation and a CycloneDX SBOM per platform attached as an OCI referrer (Syft and ORAS pinned and checksum-checked), and creates the GitHub release from CHANGELOG.md. - snapshot.yml, by hand: an amd64 test image sha- with its SBOM. - ci.yml on pull requests only; build.yml only when packaging changes; warm-build-cache.yml removed. The build cache lives in this repository's package. - CHANGELOG.md (5.1.0, based on upstream 5.0.4), SECURITY.md and a pull request template. --- .github/pull_request_template.md | 11 ++ .github/workflows/build-binaries.yml | 4 +- .github/workflows/build.yml | 9 + .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 277 ++++++++++++++++++--------- .github/workflows/snapshot.yml | 91 +++++++++ CHANGELOG.md | 44 +++++ SECURITY.md | 30 +++ 8 files changed, 379 insertions(+), 92 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/snapshot.yml create mode 100644 CHANGELOG.md create mode 100644 SECURITY.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..8ff461f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,11 @@ +## What and why + + + +## Checks + +- [ ] `cargo fmt --all -- --check` +- [ ] `cargo clippy --locked --all-targets -- -D warnings` +- [ ] `cargo test --all-features --locked` +- [ ] Tests added for the changed behaviour +- [ ] README and CHANGELOG.md (under "Unreleased") updated if users see the change diff --git a/.github/workflows/build-binaries.yml b/.github/workflows/build-binaries.yml index 9b48f4b..ed6a57c 100644 --- a/.github/workflows/build-binaries.yml +++ b/.github/workflows/build-binaries.yml @@ -30,8 +30,8 @@ jobs: group: linux-buildcache-${{ matrix.arch }}-${{ github.ref }} cancel-in-progress: false env: - # Keep caches in the existing public package so fork PRs can restore anonymously. - CACHE_REF: ghcr.io/brunojppb/turbo-cache-server:buildcache-${{ matrix.arch }} + # Keep caches in the repository's public package so fork PRs can restore anonymously. + CACHE_REF: ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Stage release version diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 39faac4..c322d81 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,6 +1,15 @@ name: Build binary +# Only when the packaging could change: it builds on three runners. on: pull_request: + paths: + - Cargo.toml + - Cargo.lock + - rust-toolchain.toml + - Dockerfile + - Dockerfile.release + - .github/workflows/build*.yml + - .github/scripts/** concurrency: group: build-${{ github.ref }} cancel-in-progress: false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c5209a..9c9cab7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,8 @@ name: "CI Checks" +# Pull requests only: main only changes through them. on: - push: - branches: - - main pull_request: + workflow_dispatch: jobs: packaging-contract: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index aab6e2e..9f8efef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,19 +1,36 @@ -name: Release new tag +# Publishes a release: run by hand from main with a SemVer (no "v"). +# +# It builds the binaries once, then from that one build: +# - commits them, with the version, on a release commit off main and tags it +# v: the GitHub Action runs the binaries in action/, so users pin +# that tag (or its commit), and main itself stays free of binaries; +# - pushes the multi-arch image (linux/amd64, linux/arm64) as +# ghcr.io//turbo-cache-server:, :. and :latest +# (the last two not for a pre-release such as 5.1.0-rc.1), with BuildKit's +# provenance and a GitHub build provenance attestation; +# - attaches a CycloneDX SBOM per platform (Syft) to the image digest as an +# OCI 1.1 referrer (ORAS); `oras discover` lists them; +# - creates the GitHub release with the binaries, their SHA256SUMS, the SBOMs +# and provenance attestations for the binaries. +# +# Why a manual run creates the tag rather than a pushed tag starting the run: +# the Action needs the binaries in the tagged commit, and a tag pushed by hand +# points at a commit without them. +name: Release on: workflow_dispatch: inputs: semver: - description: "The SemVer value used by this release" + description: "The SemVer of this release, without a v (e.g. 5.1.0)" type: string required: true concurrency: - group: release-${{ github.ref }} + group: release cancel-in-progress: false permissions: - contents: write - packages: write + contents: read jobs: sanity-check: @@ -25,11 +42,18 @@ jobs: env: RELEASE_VERSION: ${{ inputs.semver }} run: python3 .github/scripts/set-version.py "$RELEASE_VERSION" - - name: Verify main branch - if: github.ref != 'refs/heads/main' + - name: Verify main branch and a new tag + env: + RELEASE_VERSION: ${{ inputs.semver }} run: | - echo "Releases should only run from the main branch" - exit 1 + if [ "$GITHUB_REF" != refs/heads/main ]; then + echo "Releases run from the main branch only" >&2 + exit 1 + fi + if git ls-remote --exit-code --tags origin "refs/tags/v$RELEASE_VERSION" >/dev/null; then + echo "Tag v$RELEASE_VERSION exists already" >&2 + exit 1 + fi build: needs: [sanity-check] @@ -38,23 +62,43 @@ jobs: packages: write uses: ./.github/workflows/build-binaries.yml with: - version: ${{ github.event.inputs.semver }} + version: ${{ inputs.semver }} release: - name: Release Turbo Cache Server + name: Release needs: [build] runs-on: ubuntu-latest - + timeout-minutes: 30 + permissions: + contents: write + packages: write + id-token: write + attestations: write + env: + VERSION: ${{ inputs.semver }} steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - name: Stage release version + - name: Image name and tags + id: meta env: - RELEASE_VERSION: ${{ inputs.semver }} - run: python3 .github/scripts/set-version.py "$RELEASE_VERSION" + REPOSITORY: ${{ github.repository }} + run: | + set -euo pipefail + image="ghcr.io/${REPOSITORY,,}" + tags="$image:$VERSION" + # A pre-release (5.1.0-rc.1) gets its own tag only. + if [[ "$VERSION" != *-* ]]; then + minor="${VERSION%.*}" + tags="$tags"$'\n'"$image:$minor"$'\n'"$image:latest" + fi + echo "image=$image" >> "$GITHUB_OUTPUT" + { echo "tags<> "$GITHUB_OUTPUT" + + - name: Stage release version + run: python3 .github/scripts/set-version.py "$VERSION" - name: Download all binaries uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 @@ -64,15 +108,12 @@ jobs: merge-multiple: true - name: Make binaries executable - run: | - chmod +x action/decay-arm64 - chmod +x action/decay-x64 - chmod +x action/decay-darwin-arm64 + run: chmod +x action/decay-arm64 action/decay-x64 action/decay-darwin-arm64 - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - name: login to Github Container registry + - name: Log in to the GitHub Container Registry uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io @@ -85,35 +126,95 @@ jobs: cp action/decay-x64 release-image/linux/amd64/decay cp action/decay-arm64 release-image/linux/arm64/decay - - name: Package and push Docker image (no compilation) + - name: Package and push the image (no compilation) + id: push uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: release-image file: Dockerfile.release platforms: linux/arm64,linux/amd64 push: true - tags: | - ghcr.io/brunojppb/turbo-cache-server:${{ inputs.semver }} - ghcr.io/brunojppb/turbo-cache-server:latest + provenance: mode=max + tags: ${{ steps.meta.outputs.tags }} + labels: | + org.opencontainers.image.source=https://github.com/${{ github.repository }} + org.opencontainers.image.version=${{ inputs.semver }} + org.opencontainers.image.revision=${{ github.sha }} + org.opencontainers.image.licenses=MIT - - name: Commit new binary + - name: Attest the image's build provenance + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-name: ${{ steps.meta.outputs.image }} + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true + + # One SBOM per platform, read back from the pushed image by Syft and + # attached to the image digest as an OCI 1.1 referrer by ORAS (GHCR has + # no referrers API: ORAS keeps the index in the fallback tag + # sha256-, which `oras discover` reads). The binaries are built + # with cargo-auditable, so the SBOM lists the crates they contain. Both + # tools are pinned and checked against their release checksums. + - name: SBOM env: - CACHE_SERVER_VERSION: ${{ github.event.inputs.semver }} + IMAGE: ${{ steps.meta.outputs.image }} + DIGEST: ${{ steps.push.outputs.digest }} + TOKEN: ${{ secrets.GITHUB_TOKEN }} + ACTOR: ${{ github.actor }} + SYFT_VERSION: 1.54.1 + SYFT_SHA256: c069905b391cc4c20a5ba65ad5c10be2a7ba074f8ea6ad203e24d14e303dad47 + ORAS_VERSION: 1.3.4 + ORAS_SHA256: f27adb935022d94df8dc77719c322dda592c78a0d57a6f7dcdd8d900b248c454 run: | - git config --global user.name "${GITHUB_ACTOR}" - git config --global user.email "${GITHUB_ACTOR}@users.noreply.github.com" - git add action/decay-arm64 - git add action/decay-x64 - git add action/decay-darwin-arm64 Cargo.toml Cargo.lock - # Older release tags may contain the universal executable. - git rm --ignore-unmatch action/decay-darwin-universal - git commit -am "Release ${CACHE_SERVER_VERSION}" - git tag -a "${CACHE_SERVER_VERSION}" -m "Release ${CACHE_SERVER_VERSION}" - - - name: Push new tag - env: - CACHE_SERVER_VERSION: ${{ github.event.inputs.semver }} - run: git push origin "${CACHE_SERVER_VERSION}" + set -euo pipefail + [[ "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "no digest: '$DIGEST'" >&2; exit 1; } + bin="$RUNNER_TEMP/sbom-tools" + mkdir -p "$bin" sbom + curl -fsSL -o "$bin/syft.tgz" "https://github.com/anchore/syft/releases/download/v$SYFT_VERSION/syft_${SYFT_VERSION}_linux_amd64.tar.gz" + curl -fsSL -o "$bin/oras.tgz" "https://github.com/oras-project/oras/releases/download/v$ORAS_VERSION/oras_${ORAS_VERSION}_linux_amd64.tar.gz" + printf '%s %s\n' "$SYFT_SHA256" "$bin/syft.tgz" "$ORAS_SHA256" "$bin/oras.tgz" | sha256sum -c --quiet + tar -xzf "$bin/syft.tgz" -C "$bin" syft + tar -xzf "$bin/oras.tgz" -C "$bin" oras + ref="$IMAGE@$DIGEST" + for arch in amd64 arm64; do + file="sbom/turbo-cache-server-$VERSION-linux-$arch.cdx.json" + SYFT_CHECK_FOR_APP_UPDATE=false \ + SYFT_REGISTRY_AUTH_AUTHORITY=ghcr.io \ + SYFT_REGISTRY_AUTH_USERNAME="$ACTOR" \ + SYFT_REGISTRY_AUTH_PASSWORD="$TOKEN" \ + "$bin/syft" scan "registry:$ref" --platform "linux/$arch" --quiet \ + --select-catalogers +sbom-cataloger -o "cyclonedx-json=$file" + components=$(jq '.components | length' "$file") + # The binary's embedded dependency list, not just the base files. + jq -e 'any(.components[]; .name == "actix-web")' "$file" >/dev/null \ + || { echo "$file lists no Rust crates ($components components)" >&2; exit 1; } + printf '%s' "$TOKEN" | "$bin/oras" attach --no-tty \ + -u "$ACTOR" --password-stdin \ + --artifact-type application/vnd.cyclonedx+json \ + --annotation "org.opencontainers.image.platform=linux/$arch" \ + --format go-template --template '{{.digest}}' \ + "$ref" "$file:application/vnd.cyclonedx+json" > "sbom/$arch.digest" + echo "SBOM linux/$arch: CycloneDX, $components components, attached as \`$(cat "sbom/$arch.digest")\`" >> "$GITHUB_STEP_SUMMARY" + done + # Read back: the digest lists both among its referrers. + printf '%s' "$TOKEN" | "$bin/oras" discover --no-tty -u "$ACTOR" --password-stdin \ + --artifact-type application/vnd.cyclonedx+json --format json "$ref" > referrers.json + for arch in amd64 arm64; do + jq -e --arg d "$(cat "sbom/$arch.digest")" 'any(.referrers[]; .digest == $d)' referrers.json >/dev/null \ + || { echo "SBOM for linux/$arch not among the referrers of $ref" >&2; cat referrers.json >&2; exit 1; } + done + rm sbom/*.digest + echo "### Image" >> "$GITHUB_STEP_SUMMARY" + echo "\`$ref\`" >> "$GITHUB_STEP_SUMMARY" + + - name: Commit the binaries and tag the release + run: | + git config user.name "github-actions[bot]" + git config user.email "41898283+github-actions[bot]@users.noreply.github.com" + git add action/decay-arm64 action/decay-x64 action/decay-darwin-arm64 Cargo.toml Cargo.lock + git commit -m "Release v${VERSION}" + git tag -a "v${VERSION}" -m "Release v${VERSION}" + git push origin "v${VERSION}" - name: Stage release binaries run: | @@ -122,53 +223,55 @@ jobs: cp action/decay-arm64 release-assets/decay-aarch64-unknown-linux-musl cp action/decay-darwin-arm64 release-assets/decay-aarch64-apple-darwin chmod +x release-assets/* - cd release-assets && sha256sum decay-* > SHA256SUMS + cp sbom/*.cdx.json release-assets/ + cd release-assets && sha256sum decay-* ./*.cdx.json > SHA256SUMS + + - name: Attest the binaries' build provenance + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: "release-assets/decay-*" - name: Create GitHub Release env: - CACHE_SERVER_VERSION: ${{ github.event.inputs.semver }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + IMAGE: ${{ steps.meta.outputs.image }} + DIGEST: ${{ steps.push.outputs.digest }} + REPOSITORY: ${{ github.repository }} run: | - PREV_TAG=$(gh release list --limit 1 --json tagName --jq '.[0].tagName // empty') - - NOTES_FILE=$(mktemp) - echo "## What's Changed" > "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - - if [ -n "$PREV_TAG" ]; then - git log "${PREV_TAG}..${CACHE_SERVER_VERSION}" \ - --pretty=format:"* %s (%h)" \ - --grep="^Release " --invert-grep >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${CACHE_SERVER_VERSION}" >> "$NOTES_FILE" - else - git log "${CACHE_SERVER_VERSION}" \ - --pretty=format:"* %s (%h)" >> "$NOTES_FILE" - fi - - echo "" >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "## Downloads" >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "Prebuilt binaries for running \`decay\` without Docker (e.g. as a systemd service)." >> "$NOTES_FILE" - echo "The Linux binaries are statically linked (musl) and run on any modern x86-64/ARM64 Linux distro." >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "| Platform | Architecture | Asset |" >> "$NOTES_FILE" - echo "| --- | --- | --- |" >> "$NOTES_FILE" - DOWNLOAD_URL="https://github.com/${{ github.repository }}/releases/download/${CACHE_SERVER_VERSION}" - echo "| Linux (musl) | x86-64 | [decay-x86_64-unknown-linux-musl](${DOWNLOAD_URL}/decay-x86_64-unknown-linux-musl) |" >> "$NOTES_FILE" - echo "| Linux (musl) | ARM64 | [decay-aarch64-unknown-linux-musl](${DOWNLOAD_URL}/decay-aarch64-unknown-linux-musl) |" >> "$NOTES_FILE" - echo "| macOS | Apple Silicon (ARM64) | [decay-aarch64-apple-darwin](${DOWNLOAD_URL}/decay-aarch64-apple-darwin) |" >> "$NOTES_FILE" - echo "" >> "$NOTES_FILE" - echo "Verify a download against \`SHA256SUMS\`, e.g. \`sha256sum -c SHA256SUMS --ignore-missing\`." >> "$NOTES_FILE" - - gh release create "${CACHE_SERVER_VERSION}" \ - --title "${CACHE_SERVER_VERSION}" \ - --notes-file "$NOTES_FILE" \ - release-assets/decay-x86_64-unknown-linux-musl \ - release-assets/decay-aarch64-unknown-linux-musl \ - release-assets/decay-aarch64-apple-darwin \ - release-assets/SHA256SUMS - - rm -f "$NOTES_FILE" + set -euo pipefail + tag="v$VERSION" + notes=$(mktemp) + # The CHANGELOG entry for this version, when there is one. + awk -v v="$VERSION" ' + $0 ~ "^## \\[?v?" v "\\]?([^0-9.-]|$)" { on = 1; next } + on && /^## / { exit } + on { print } + ' CHANGELOG.md > "$notes" + { + echo + echo "## Image" + echo + echo "\`$IMAGE:$VERSION\` (linux/amd64, linux/arm64)" + echo + echo "\`$IMAGE@$DIGEST\`" + echo + echo "The SBOMs (CycloneDX) are attached to the image digest; list them with" + echo "\`oras discover $IMAGE@$DIGEST\`. Verify the provenance with" + echo "\`gh attestation verify oci://$IMAGE@$DIGEST -R $REPOSITORY\`." + echo + echo "## Downloads" + echo + echo "| Platform | Architecture | Asset |" + echo "| --- | --- | --- |" + url="https://github.com/$REPOSITORY/releases/download/$tag" + echo "| Linux (musl, static) | x86-64 | [decay-x86_64-unknown-linux-musl]($url/decay-x86_64-unknown-linux-musl) |" + echo "| Linux (musl, static) | ARM64 | [decay-aarch64-unknown-linux-musl]($url/decay-aarch64-unknown-linux-musl) |" + echo "| macOS | Apple Silicon (ARM64) | [decay-aarch64-apple-darwin]($url/decay-aarch64-apple-darwin) |" + echo + echo "Verify a download against \`SHA256SUMS\` (\`sha256sum -c SHA256SUMS --ignore-missing\`)" + echo "or its provenance with \`gh attestation verify -R $REPOSITORY\`." + } >> "$notes" + prerelease=() + if [[ "$VERSION" == *-* ]]; then prerelease=(--prerelease); fi + gh release create "$tag" --verify-tag --title "$tag" --notes-file "$notes" "${prerelease[@]}" \ + release-assets/* diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 0000000..d864f15 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,91 @@ +# A test image of any commit, between releases: run by hand on a branch. +# +# It builds the image from source (./Dockerfile, linux/amd64 only, one +# runner) and pushes it as ghcr.io//turbo-cache-server:sha-, +# never as a version or latest, with its CycloneDX SBOM (Syft) attached to +# the pushed digest as an OCI 1.1 referrer (ORAS). Releases are release.yml. +name: Snapshot image +on: + workflow_dispatch: + +permissions: + contents: read + packages: write + +concurrency: + group: snapshot-${{ github.ref }} + cancel-in-progress: false + +jobs: + image: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Build and push + id: push + env: + REPOSITORY: ${{ github.repository }} + TOKEN: ${{ secrets.GITHUB_TOKEN }} + ACTOR: ${{ github.actor }} + run: | + set -euo pipefail + image="ghcr.io/${REPOSITORY,,}" + tag="$image:sha-${GITHUB_SHA::12}" + rust=$(python3 -c 'import tomllib; print(tomllib.load(open("rust-toolchain.toml", "rb"))["toolchain"]["channel"])') + # The source label links the package to this repository, which is + # what lets this job's token push to it. + docker build --build-arg RUST_VERSION="$rust" \ + --label "org.opencontainers.image.source=https://github.com/$REPOSITORY" \ + --label "org.opencontainers.image.revision=$GITHUB_SHA" \ + -t "$tag" . + echo "$TOKEN" | docker login ghcr.io -u "$ACTOR" --password-stdin + docker push "$tag" + digest=$(docker image inspect --format '{{index .RepoDigests 0}}' "$tag") + echo "### Snapshot image" >> "$GITHUB_STEP_SUMMARY" + echo "\`$tag@${digest#*@}\`" >> "$GITHUB_STEP_SUMMARY" + echo "image=$image" >> "$GITHUB_OUTPUT" + echo "digest=${digest#*@}" >> "$GITHUB_OUTPUT" + + # Same tools, versions and checks as release.yml. + - name: SBOM + env: + IMAGE: ${{ steps.push.outputs.image }} + DIGEST: ${{ steps.push.outputs.digest }} + TOKEN: ${{ secrets.GITHUB_TOKEN }} + ACTOR: ${{ github.actor }} + SYFT_VERSION: 1.54.1 + SYFT_SHA256: c069905b391cc4c20a5ba65ad5c10be2a7ba074f8ea6ad203e24d14e303dad47 + ORAS_VERSION: 1.3.4 + ORAS_SHA256: f27adb935022d94df8dc77719c322dda592c78a0d57a6f7dcdd8d900b248c454 + run: | + set -euo pipefail + [[ "$DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "no digest: '$DIGEST'" >&2; exit 1; } + bin="$RUNNER_TEMP/sbom-tools" + mkdir -p "$bin" + curl -fsSL -o "$bin/syft.tgz" "https://github.com/anchore/syft/releases/download/v$SYFT_VERSION/syft_${SYFT_VERSION}_linux_amd64.tar.gz" + curl -fsSL -o "$bin/oras.tgz" "https://github.com/oras-project/oras/releases/download/v$ORAS_VERSION/oras_${ORAS_VERSION}_linux_amd64.tar.gz" + printf '%s %s\n' "$SYFT_SHA256" "$bin/syft.tgz" "$ORAS_SHA256" "$bin/oras.tgz" | sha256sum -c --quiet + tar -xzf "$bin/syft.tgz" -C "$bin" syft + tar -xzf "$bin/oras.tgz" -C "$bin" oras + ref="$IMAGE@$DIGEST" + cd "$RUNNER_TEMP" + SYFT_CHECK_FOR_APP_UPDATE=false \ + SYFT_REGISTRY_AUTH_AUTHORITY=ghcr.io \ + SYFT_REGISTRY_AUTH_USERNAME="$ACTOR" \ + SYFT_REGISTRY_AUTH_PASSWORD="$TOKEN" \ + "$bin/syft" scan "registry:$ref" --quiet --select-catalogers +sbom-cataloger \ + -o cyclonedx-json=turbo-cache-server.cdx.json + jq -e 'any(.components[]; .name == "actix-web")' turbo-cache-server.cdx.json >/dev/null \ + || { echo "the SBOM lists no Rust crates" >&2; exit 1; } + printf '%s' "$TOKEN" | "$bin/oras" attach --no-tty \ + -u "$ACTOR" --password-stdin \ + --artifact-type application/vnd.cyclonedx+json \ + --format go-template --template '{{.digest}}' \ + "$ref" turbo-cache-server.cdx.json:application/vnd.cyclonedx+json > sbom-digest + printf '%s' "$TOKEN" | "$bin/oras" discover --no-tty -u "$ACTOR" --password-stdin \ + --artifact-type application/vnd.cyclonedx+json --format json "$ref" > referrers.json + jq -e --arg d "$(cat sbom-digest)" 'any(.referrers[]; .digest == $d)' referrers.json >/dev/null \ + || { echo "SBOM $(cat sbom-digest) not among the referrers of $ref" >&2; cat referrers.json >&2; exit 1; } + echo "SBOM: CycloneDX, $(jq '.components | length' turbo-cache-server.cdx.json) components, attached as \`$(cat sbom-digest)\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0c89fb6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +All notable changes to this fork are listed here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and releases follow +[Semantic Versioning](https://semver.org/). + +This fork continues the version line of +[brunojppb/turbo-cache-server](https://github.com/brunojppb/turbo-cache-server): +each release names the upstream version it is based on. Its tags start with +`v` (`v5.1.0`), upstream's do not (`5.0.4`). Changes made upstream are in +[upstream's releases](https://github.com/brunojppb/turbo-cache-server/releases). + +## [Unreleased] + +## [5.1.0] + +Based on upstream 5.0.4. + +### Added + +- Multi-tenancy: per-team tokens. `TURBO_TOKENS_DIR` names a directory with + one file per team (the file name is the team, the content the SHA-256 hex + of its token). A request must carry the token of the team it names: no or + an unknown token is `401`, another team's token or no team named is `403`. + The directory is re-read every 10 seconds, so teams are added, removed and + rotated without a restart. See "Multi-tenancy: per-team tokens" in the + README. +- Release images carry a CycloneDX SBOM per platform, attached to the image + digest as an OCI 1.1 referrer, and a build provenance attestation; release + binaries have provenance attestations too. +- Images are also tagged `.`. + +### Changed + +- The server refuses to start when both `TURBO_TOKEN` and `TURBO_TOKENS_DIR` + are set, or when `TURBO_TOKENS_DIR` cannot be read. With + `TURBO_TOKENS_DIR` unset, behaviour is the same as upstream 5.0.4. +- Binaries are built with cargo-auditable, which embeds their dependency list + for SBOM and vulnerability scanners. +- Images are published as `ghcr.io/13axis/turbo-cache-server`, and the GitHub + Action is `13axis/turbo-cache-server@v`. + +[Unreleased]: https://github.com/13axis/turbo-cache-server/compare/v5.1.0...HEAD +[5.1.0]: https://github.com/13axis/turbo-cache-server/releases/tag/v5.1.0 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c905ad2 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,30 @@ +# Security policy + +## Reporting a vulnerability + +Please report vulnerabilities privately, through +[GitHub's private vulnerability reporting](https://github.com/13axis/turbo-cache-server/security/advisories/new) +for this repository. Do not open a public issue. + +Include what is affected (version or commit, and the mode: per-team tokens, +one shared token, or no authentication), how to reproduce it, and the impact +you see. We aim to acknowledge a report within three working days and to +agree on a disclosure date with you once a fix is ready. + +If the issue also affects +[brunojppb/turbo-cache-server](https://github.com/brunojppb/turbo-cache-server), +we will coordinate with its maintainer. + +## Supported versions + +Security fixes go into the latest release. Use the newest `v.` +image tag, or pin a digest and update it when a release is published. + +## Scope + +In scope: the server (authentication, team isolation, the artifact routes and +storage keys), the images and binaries released here, and the GitHub Action. + +Out of scope: running without authentication on a network others can reach, +weak tokens (see "Security notes" in the README), and the security of your +S3-compatible storage itself. From 91233c8afe2ae75fde5dba9235e3378e5293eb40 Mon Sep 17 00:00:00 2001 From: Abdelhadi Sabani Date: Sat, 14 Nov 2026 00:36:59 +0000 Subject: [PATCH 5/5] docs: keep the docker run example runnable --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7eb0357..9228e74 100644 --- a/README.md +++ b/README.md @@ -368,6 +368,10 @@ for inspiration. For folks using Gitlab or any other CI environment that supports Docker, you can run the Turbo Cache Server as a docker container: +TURBO_TOKENS_DIR and its volume are optional: per-team tokens, see +[Multi-tenancy](#multi-tenancy-per-team-tokens). Use `-e TURBO_TOKEN=...` +instead for one shared token, or neither for no authentication. + ```shell docker run \ -e S3_ACCESS_KEY=KEY \ @@ -376,8 +380,6 @@ docker run \ -e S3_ENDPOINT=https://s3_endpoint_here \ -e S3_REGION=eu \ -e S3_SERVER_SIDE_ENCRYPTION=AES256 \ - # Optional: per-team tokens, see "Multi-tenancy" above - # (mount the directory with -v), or one shared TURBO_TOKEN. -e TURBO_TOKENS_DIR=/etc/turbo-cache/tokens \ -v "$PWD/tokens:/etc/turbo-cache/tokens:ro" \ -p "8000:8000" \