From 136f946e656ed0bdf96f38a39bf762f3c1bbdcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 00:25:50 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20an=20OCI=20container=20regi?= =?UTF-8?q?stry=20per=20user=20and=20org?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Includes: ✨ feat: a cargo registry per user and org --- Cargo.lock | 2 + crates/forge-core/Cargo.toml | 2 + .../forge-core/migrations/0061_packages.sql | 35 + crates/forge-core/migrations/0062_oci.sql | 47 + .../{0061_web_push.sql => 0063_web_push.sql} | 0 ...1_merge_queue.sql => 0064_merge_queue.sql} | 0 crates/forge-core/src/cargo.rs | 310 ++++++ crates/forge-core/src/lib.rs | 3 + crates/forge-core/src/names.rs | 1 + crates/forge-core/src/oci.rs | 296 ++++++ crates/forge-core/src/packages.rs | 89 ++ crates/forge-core/src/store/migrate.rs | 6 +- crates/forge-core/src/store/mod.rs | 2 + crates/forge-core/src/store/oci.rs | 332 ++++++ crates/forge-core/src/store/packages.rs | 332 ++++++ crates/forge-core/src/store/web_push.rs | 2 +- crates/forge-web/src/api/mod.rs | 34 +- crates/forge-web/src/api/packages.rs | 367 +++++++ crates/forge-web/src/blobs.rs | 9 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/i18n/mod.rs | 1 + crates/forge-web/src/i18n/packages.rs | 141 +++ crates/forge-web/src/main.rs | 3 + crates/forge-web/src/oci/auth.rs | 217 ++++ crates/forge-web/src/oci/blobs.rs | 458 +++++++++ crates/forge-web/src/oci/gc.rs | 38 + crates/forge-web/src/oci/manifests.rs | 365 +++++++ crates/forge-web/src/oci/mod.rs | 467 +++++++++ crates/forge-web/src/package_ops.rs | 323 ++++++ crates/forge-web/src/packages_live.rs | 80 ++ crates/forge-web/src/pages/mod.rs | 2 + crates/forge-web/src/pages/packages.rs | 460 +++++++++ crates/forge-web/src/pages/packages_oci.rs | 195 ++++ crates/forge-web/src/pages/profile.rs | 53 +- crates/forge-web/src/pages/repo.rs | 6 + .../forge-web/src/pages/settings_security.rs | 1 + crates/forge-web/src/pages/settings_tokens.rs | 15 +- crates/forge-web/src/state.rs | 1 + crates/forge-web/src/test_support.rs | 1 + crates/forge-web/tests/oci_e2e.rs | 972 ++++++++++++++++++ crates/forge-web/tests/packages_e2e.rs | 604 +++++++++++ docs/packages.md | 217 ++++ style/main.scss | 34 + 43 files changed, 6509 insertions(+), 15 deletions(-) create mode 100644 crates/forge-core/migrations/0061_packages.sql create mode 100644 crates/forge-core/migrations/0062_oci.sql rename crates/forge-core/migrations/{0061_web_push.sql => 0063_web_push.sql} (100%) rename crates/forge-core/migrations/{0061_merge_queue.sql => 0064_merge_queue.sql} (100%) create mode 100644 crates/forge-core/src/cargo.rs create mode 100644 crates/forge-core/src/oci.rs create mode 100644 crates/forge-core/src/packages.rs create mode 100644 crates/forge-core/src/store/oci.rs create mode 100644 crates/forge-core/src/store/packages.rs create mode 100644 crates/forge-web/src/api/packages.rs create mode 100644 crates/forge-web/src/i18n/packages.rs create mode 100644 crates/forge-web/src/oci/auth.rs create mode 100644 crates/forge-web/src/oci/blobs.rs create mode 100644 crates/forge-web/src/oci/gc.rs create mode 100644 crates/forge-web/src/oci/manifests.rs create mode 100644 crates/forge-web/src/oci/mod.rs create mode 100644 crates/forge-web/src/package_ops.rs create mode 100644 crates/forge-web/src/packages_live.rs create mode 100644 crates/forge-web/src/pages/packages.rs create mode 100644 crates/forge-web/src/pages/packages_oci.rs create mode 100644 crates/forge-web/tests/oci_e2e.rs create mode 100644 crates/forge-web/tests/packages_e2e.rs create mode 100644 docs/packages.md diff --git a/Cargo.lock b/Cargo.lock index 0328713..c3dfd95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2136,6 +2136,7 @@ dependencies = [ "argon2", "base64 0.23.1", "chacha20poly1305", + "flate2", "forge-ci", "hex", "hmac 0.13.0", @@ -2149,6 +2150,7 @@ dependencies = [ "sha1 0.11.0", "sha2 0.11.1", "subtle", + "tar", "tempfile", "thiserror 2.0.21", "time", diff --git a/crates/forge-core/Cargo.toml b/crates/forge-core/Cargo.toml index 2573685..2273a29 100644 --- a/crates/forge-core/Cargo.toml +++ b/crates/forge-core/Cargo.toml @@ -32,6 +32,8 @@ tracing.workspace = true serde_json.workspace = true semver = { workspace = true } zip = { workspace = true } +flate2.workspace = true +tar.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/forge-core/migrations/0061_packages.sql b/crates/forge-core/migrations/0061_packages.sql new file mode 100644 index 0000000..ade4f16 --- /dev/null +++ b/crates/forge-core/migrations/0061_packages.sql @@ -0,0 +1,35 @@ +-- Package registries: the packages an owner (user or org) publishes, and their versions. `kind` +-- names the registry format ('cargo' now; a container registry would add 'oci' rows beside them). +-- `name_key` is the lowercase name that the index and the URLs use; `name` keeps the spelling of +-- the first publish. The .crate bytes live in blob storage under `packages/`; a +-- version row keeps the checksum, the index line and the README text. `repo_id` links a package +-- to a repo on this forge, found from the crate's `repository` field. + +CREATE TABLE packages ( + id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + name TEXT NOT NULL, + name_key TEXT NOT NULL, + repo_id TEXT REFERENCES repos(id) ON DELETE SET NULL, + private INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE (owner_id, kind, name_key) +); +CREATE INDEX packages_repo ON packages(repo_id); + +CREATE TABLE package_versions ( + id TEXT PRIMARY KEY, + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, + version TEXT NOT NULL, + yanked INTEGER NOT NULL DEFAULT 0, + checksum TEXT NOT NULL, + size INTEGER NOT NULL, + index_json TEXT NOT NULL, + description TEXT, + readme TEXT, + publisher_id TEXT NOT NULL REFERENCES users(id), + created_at TEXT NOT NULL, + UNIQUE (package_id, version) +); diff --git a/crates/forge-core/migrations/0062_oci.sql b/crates/forge-core/migrations/0062_oci.sql new file mode 100644 index 0000000..e7bec14 --- /dev/null +++ b/crates/forge-core/migrations/0062_oci.sql @@ -0,0 +1,47 @@ +-- Container registry (OCI Distribution). An image is a package of kind 'oci' whose name_key is +-- the repository path below the owner (`app` for `tahinli/app`, `a/b` for `tahinli/a/b`). +-- Blob bytes live in blob storage under `oci/`, shared by digest; the rows here say which +-- package may use which digest. Manifests keep their exact bytes, so the digest stays valid. + +-- The blobs a package may read (layers, configs and uploads it has linked). Child manifests of an +-- index are not blobs; they live in oci_manifests. `created_at` is when the package linked it. +CREATE TABLE oci_blobs ( + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, + digest TEXT NOT NULL, + size INTEGER NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (package_id, digest) +); +CREATE INDEX oci_blobs_digest ON oci_blobs(digest); + +-- Manifests by digest. `content` is the manifest JSON as pushed. `size` is the total of the +-- image's config and layers (the manifest's own length for an index). +CREATE TABLE oci_manifests ( + id TEXT PRIMARY KEY, + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, + digest TEXT NOT NULL, + media_type TEXT NOT NULL, + content TEXT NOT NULL, + size INTEGER NOT NULL, + created_at TEXT NOT NULL, + UNIQUE (package_id, digest) +); + +-- Tags point at one manifest of their package. +CREATE TABLE oci_tags ( + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, + tag TEXT NOT NULL, + manifest_id TEXT NOT NULL REFERENCES oci_manifests(id) ON DELETE CASCADE, + updated_at TEXT NOT NULL, + PRIMARY KEY (package_id, tag) +); +CREATE INDEX oci_tags_manifest ON oci_tags(manifest_id); + +-- What each manifest refers to: config and layer digests (blobs), or child manifest digests of an +-- index. The mark step of garbage collection reads these rows. +CREATE TABLE oci_manifest_refs ( + manifest_id TEXT NOT NULL REFERENCES oci_manifests(id) ON DELETE CASCADE, + digest TEXT NOT NULL, + PRIMARY KEY (manifest_id, digest) +); +CREATE INDEX oci_manifest_refs_digest ON oci_manifest_refs(digest); diff --git a/crates/forge-core/migrations/0061_web_push.sql b/crates/forge-core/migrations/0063_web_push.sql similarity index 100% rename from crates/forge-core/migrations/0061_web_push.sql rename to crates/forge-core/migrations/0063_web_push.sql diff --git a/crates/forge-core/migrations/0061_merge_queue.sql b/crates/forge-core/migrations/0064_merge_queue.sql similarity index 100% rename from crates/forge-core/migrations/0061_merge_queue.sql rename to crates/forge-core/migrations/0064_merge_queue.sql diff --git a/crates/forge-core/src/cargo.rs b/crates/forge-core/src/cargo.rs new file mode 100644 index 0000000..5922c75 --- /dev/null +++ b/crates/forge-core/src/cargo.rs @@ -0,0 +1,310 @@ +//! Cargo registry rules, pure and without IO: crate and version names, the publish body, the +//! index line written for each version, the index file path of a crate, and the README and +//! repository link found in a `.crate` file. The wire formats follow the Cargo book's registry +//! chapters: the publish body, the index format (version 2) and the sparse index layout. + +use std::io::Read; + +use flate2::read::GzDecoder; +use serde_json::{Map, Value, json}; + +use crate::error::{Error, Result}; + +/// Longest crate name, in characters. +pub const MAX_NAME_CHARS: usize = 64; +/// Largest README read out of a `.crate` file, in bytes. +pub const MAX_README_BYTES: u64 = 256 * 1024; + +/// Checks a crate name and returns its lowercase key. The key names the index file, so it is +/// what routes and storage use; the name as published is kept for display and the index. +pub fn crate_name_key(name: &str) -> Result { + let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()); + let chars_ok = name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if !starts_alpha || !chars_ok || name.len() > MAX_NAME_CHARS { + return Err(Error::InvalidName(format!( + "`{name}` is not a valid crate name: start with a letter, then letters, digits, `-` or `_`, at most {MAX_NAME_CHARS} characters" + ))); + } + Ok(name.to_ascii_lowercase()) +} + +/// The sparse index path of a crate key, relative to the index URL (`1/a`, `2/ab`, `3/a/abc`, +/// `ab/cd/abcdef`). The key is ASCII, checked by [`crate_name_key`]. +pub fn index_path(key: &str) -> String { + match key.len() { + 1 => format!("1/{key}"), + 2 => format!("2/{key}"), + 3 => format!("3/{}/{key}", &key[..1]), + _ => format!("{}/{}/{key}", &key[..2], &key[2..4]), + } +} + +/// Parses a version as semver. Cargo versions are semver, with build metadata kept as written. +pub fn parse_version(version: &str) -> Result { + semver::Version::parse(version) + .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}"))) +} + +/// A publish body split into its parts. The metadata is the JSON document, the crate the +/// gzipped tarball whose sha256 the index records. +pub struct Publish<'a> { + pub metadata: Value, + pub crate_file: &'a [u8], +} + +/// Splits a publish body: a little-endian u32 length and the JSON metadata, then a little-endian +/// u32 length and the `.crate` bytes. Both lengths must match the body exactly. +pub fn parse_publish(body: &[u8]) -> Result> { + let (json_len, rest) = take_len(body)?; + if json_len > rest.len() { + return Err(Error::Invalid( + "publish body is shorter than its metadata length".into(), + )); + } + let (json_bytes, rest) = rest.split_at(json_len); + let metadata: Value = serde_json::from_slice(json_bytes) + .map_err(|e| Error::Invalid(format!("publish metadata is not JSON: {e}")))?; + if !metadata.is_object() { + return Err(Error::Invalid( + "publish metadata must be a JSON object".into(), + )); + } + let (crate_len, rest) = take_len(rest)?; + if crate_len != rest.len() { + return Err(Error::Invalid( + "crate length does not match the body".into(), + )); + } + Ok(Publish { + metadata, + crate_file: rest, + }) +} + +fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> { + let Some((head, rest)) = bytes.split_first_chunk::<4>().map(|(h, r)| (*h, r)) else { + return Err(Error::Invalid("publish body is truncated".into())); + }; + let len = usize::try_from(u32::from_le_bytes(head)) + .map_err(|_| Error::Invalid("length does not fit".into()))?; + Ok((len, rest)) +} + +/// Text field of the metadata, or `None` when absent or not a string. +pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> { + meta.get(key).and_then(Value::as_str) +} + +/// The dependencies of an index line, from the publish metadata. A renamed dependency +/// (`explicit_name_in_toml`) is listed under its local name, with the real crate in `package`. +pub fn index_deps(meta: &Value) -> Vec { + let deps = meta.get("deps").and_then(Value::as_array); + deps.map_or_else(Vec::new, |list| { + list.iter() + .map(|dep| { + let crate_name = meta_str(dep, "name").unwrap_or_default(); + let renamed = meta_str(dep, "explicit_name_in_toml"); + json!({ + "name": renamed.unwrap_or(crate_name), + "req": dep.get("version_req").cloned().unwrap_or(Value::Null), + "features": dep.get("features").cloned().unwrap_or_else(|| json!([])), + "optional": dep.get("optional").and_then(Value::as_bool).unwrap_or(false), + "default_features": dep.get("default_features").and_then(Value::as_bool).unwrap_or(true), + "target": dep.get("target").cloned().unwrap_or(Value::Null), + "kind": dep.get("kind").and_then(Value::as_str).unwrap_or("normal"), + "registry": dep.get("registry").cloned().unwrap_or(Value::Null), + "package": renamed.map(|_| crate_name), + }) + }) + .collect() + }) +} + +/// The index line of one version (format version 2). Features that use the `dep:` or `?` +/// syntax go to `features2`, as the format requires; the rest stay in `features`. +pub fn index_line(meta: &Value, checksum: &str) -> Result { + let name = + meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?; + let vers = + meta_str(meta, "vers").ok_or_else(|| Error::Invalid("metadata has no vers".into()))?; + let mut features = Map::new(); + let mut features2 = Map::new(); + if let Some(declared) = meta.get("features").and_then(Value::as_object) { + for (feature, members) in declared { + let modern = members.as_array().is_some_and(|list| { + list.iter() + .filter_map(Value::as_str) + .any(|m| m.starts_with("dep:") || m.contains('?')) + }); + if modern { + features2.insert(feature.clone(), members.clone()); + } else { + features.insert(feature.clone(), members.clone()); + } + } + } + let mut line = json!({ + "name": name, + "vers": vers, + "deps": index_deps(meta), + "cksum": checksum, + "features": features, + "yanked": false, + "links": meta.get("links").cloned().unwrap_or(Value::Null), + "v": 2, + }); + if !features2.is_empty() { + line["features2"] = Value::Object(features2); + } + if let Some(rust_version) = meta_str(meta, "rust_version") { + line["rust_version"] = json!(rust_version); + } + Ok(line) +} + +/// The `(owner, repo)` a `repository` URL names on this forge, when it points at a repo under +/// `base_url` (for example `https://git.tahinli.com/`). Any other URL links nothing. +pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> { + let base = base_url.trim_end_matches('/'); + let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?; + let rest = rest.trim_end_matches('/'); + let rest = rest.strip_suffix(".git").unwrap_or(rest); + let mut parts = rest.split('/'); + let owner = parts.next().filter(|s| !s.is_empty())?; + let repo = parts.next().filter(|s| !s.is_empty())?; + if parts.next().is_some() { + return None; + } + Some((owner.to_owned(), repo.to_owned())) +} + +/// The README of a `.crate` file: the first `README*` file at the top of the package directory +/// (`-/README.md`). Read at most [`MAX_README_BYTES`] bytes. Returns `None` when +/// the archive is not a gzipped tarball or has no README. +pub fn crate_readme(crate_file: &[u8]) -> Option { + let mut archive = tar::Archive::new(GzDecoder::new(crate_file)); + let entries = archive.entries().ok()?; + for entry in entries { + let entry = entry.ok()?; + let path = entry.path().ok()?.into_owned(); + let mut parts = path.components(); + parts.next()?; + let file = parts.next()?; + let is_top = parts.next().is_none(); + let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase(); + if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() { + let mut bytes = Vec::new(); + entry.take(MAX_README_BYTES).read_to_end(&mut bytes).ok()?; + return Some(String::from_utf8_lossy(&bytes).into_owned()); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_follow_crate_rules_and_lowercase() { + assert_eq!(crate_name_key("Serde_json").unwrap(), "serde_json"); + assert!(crate_name_key("").is_err()); + assert!(crate_name_key("1abc").is_err()); + assert!(crate_name_key("a b").is_err()); + assert!(crate_name_key("a.b").is_err()); + assert!(crate_name_key(&"a".repeat(65)).is_err()); + assert!(crate_name_key(&"a".repeat(64)).is_ok()); + } + + #[test] + fn index_paths_match_the_sparse_layout() { + assert_eq!(index_path("a"), "1/a"); + assert_eq!(index_path("ab"), "2/ab"); + assert_eq!(index_path("abc"), "3/a/abc"); + assert_eq!(index_path("serde"), "se/rd/serde"); + } + + #[test] + fn publish_body_round_trips_and_rejects_bad_lengths() { + let meta = br#"{"name":"demo","vers":"0.1.0"}"#; + let krate = b"gz-bytes"; + let mut body = Vec::new(); + body.extend_from_slice(&(meta.len() as u32).to_le_bytes()); + body.extend_from_slice(meta); + body.extend_from_slice(&(krate.len() as u32).to_le_bytes()); + body.extend_from_slice(krate); + let parsed = parse_publish(&body).unwrap(); + assert_eq!(parsed.metadata["name"], "demo"); + assert_eq!(parsed.crate_file, krate); + + let mut short = body.clone(); + short.pop(); + assert!(parse_publish(&short).is_err()); + assert!(parse_publish(&body[..3]).is_err()); + } + + #[test] + fn index_line_renames_deps_and_splits_features() { + let meta = json!({ + "name": "demo", "vers": "0.2.0", "links": null, "rust_version": "1.80", + "deps": [ + {"name": "serde", "version_req": "^1", "features": ["derive"], "optional": false, + "default_features": true, "target": null, "kind": "normal", "registry": null, + "explicit_name_in_toml": null}, + {"name": "tokio", "version_req": "1", "features": [], "optional": true, + "default_features": false, "target": null, "kind": "dev", "registry": null, + "explicit_name_in_toml": "rt"} + ], + "features": {"default": ["serde"], "net": ["dep:tokio"]} + }); + let line = index_line(&meta, "abc").unwrap(); + assert_eq!(line["cksum"], "abc"); + assert_eq!(line["yanked"], false); + assert_eq!(line["v"], 2); + assert_eq!(line["rust_version"], "1.80"); + assert_eq!(line["deps"][1]["name"], "rt"); + assert_eq!(line["deps"][1]["package"], "tokio"); + assert_eq!(line["deps"][0]["package"], Value::Null); + assert_eq!(line["features"]["default"], json!(["serde"])); + assert_eq!(line["features2"]["net"], json!(["dep:tokio"])); + } + + #[test] + fn repository_links_only_forge_repos() { + let base = "https://git.tahinli.com/"; + assert_eq!( + repo_link("https://git.tahinli.com/tahinli/forge.git", base), + Some(("tahinli".into(), "forge".into())) + ); + assert_eq!(repo_link("https://github.com/tahinli/forge", base), None); + assert_eq!(repo_link("https://git.tahinli.com/tahinli", base), None); + assert_eq!(repo_link("https://git.tahinli.com/a/b/c", base), None); + } + + #[test] + fn readme_is_read_from_the_package_directory() { + let mut tar_bytes = Vec::new(); + { + let mut builder = tar::Builder::new(&mut tar_bytes); + let body = b"# Demo\n\nHello."; + let mut header = tar::Header::new_gnu(); + header.set_size(body.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder + .append_data(&mut header, "demo-0.1.0/README.md", &body[..]) + .unwrap(); + builder.finish().unwrap(); + } + let mut gz = Vec::new(); + { + let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast()); + std::io::Write::write_all(&mut enc, &tar_bytes).unwrap(); + enc.finish().unwrap(); + } + assert_eq!(crate_readme(&gz).as_deref(), Some("# Demo\n\nHello.")); + assert_eq!(crate_readme(b"not gzip"), None); + } +} diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 58b086c..9d694e9 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -5,6 +5,7 @@ pub mod alerts; pub mod audit; pub mod authz; pub mod avatar; +pub mod cargo; pub mod ci; pub mod config; pub mod discussions; @@ -18,6 +19,8 @@ pub mod mirrors; pub mod model; pub mod names; pub mod notifications; +pub mod oci; +pub mod packages; pub mod password; pub mod protection; pub mod pulls; diff --git a/crates/forge-core/src/names.rs b/crates/forge-core/src/names.rs index 6ebb53e..368ca2f 100644 --- a/crates/forge-core/src/names.rs +++ b/crates/forge-core/src/names.rs @@ -7,6 +7,7 @@ use crate::error::{Error, Result}; /// Names that may not be used as owners or repos (they collide with routes). pub const RESERVED: &[&str] = &[ "api", + "v2", "admin", "auth", "assets", diff --git a/crates/forge-core/src/oci.rs b/crates/forge-core/src/oci.rs new file mode 100644 index 0000000..b1a1ef9 --- /dev/null +++ b/crates/forge-core/src/oci.rs @@ -0,0 +1,296 @@ +//! Container registry rules shared by the web layer: repository names, digests, tags, the +//! manifest media types, the reference scan of a manifest, and the short-lived bearer token that +//! `docker login` and `podman` exchange for their credentials. +//! +//! Token format: `base64url("oci1||") + "." + base64url(hmac)`. The +//! MAC covers the payload under its own domain tag, so an LFS token never verifies here. + +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; +use hmac::{Hmac, KeyInit, Mac}; +use serde_json::Value; +use sha2::Sha256; +use subtle::ConstantTimeEq; + +type HmacSha256 = Hmac; + +/// The media types a manifest may be pushed as. +pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ + "application/vnd.oci.image.manifest.v1+json", + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", + "application/vnd.docker.distribution.manifest.list.v2+json", +]; + +/// Longest repository name the spec allows. +const MAX_REPO_NAME: usize = 255; +/// Longest tag the spec allows. +const MAX_TAG: usize = 128; + +/// True for one of [`MANIFEST_MEDIA_TYPES`]. +pub fn is_manifest_media_type(media_type: &str) -> bool { + MANIFEST_MEDIA_TYPES.contains(&media_type) +} + +/// True for one path segment of a repository name: lowercase letters and digits, joined by a +/// single `.` or `_`, or by runs of `-`, and starting and ending with a letter or digit. +fn valid_segment(segment: &str) -> bool { + let bytes = segment.as_bytes(); + if bytes.is_empty() { + return false; + } + let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); + if !alnum(bytes[0]) || !alnum(bytes[bytes.len() - 1]) { + return false; + } + let mut prev_sep = false; + for &b in bytes { + if alnum(b) { + prev_sep = false; + } else if matches!(b, b'.' | b'_' | b'-') { + if prev_sep && b != b'-' { + return false; + } + prev_sep = true; + } else { + return false; + } + } + true +} + +/// The owner and the image path of a repository name such as `tahinli/app` or `tahinli/a/b`. +/// `None` when the name has no owner segment or no image segment, or a segment is malformed. +pub fn split_repo_name(name: &str) -> Option<(&str, &str)> { + if name.len() > MAX_REPO_NAME { + return None; + } + let (owner, image) = name.split_once('/')?; + if !image.split('/').all(valid_segment) || !valid_segment(owner) { + return None; + } + Some((owner, image)) +} + +/// The lowercase `sha256:` digest, returned as its 64 hex characters. `None` for any other +/// algorithm or a malformed value. +pub fn parse_digest(digest: &str) -> Option<&str> { + let hex = digest.strip_prefix("sha256:")?; + let valid = hex.len() == 64 + && hex + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + valid.then_some(hex) +} + +/// True for a tag: up to 128 characters from `[A-Za-z0-9_.-]`, not starting with `.` or `-`. +pub fn valid_tag(tag: &str) -> bool { + let bytes = tag.as_bytes(); + !bytes.is_empty() + && bytes.len() <= MAX_TAG + && !matches!(bytes[0], b'.' | b'-') + && bytes + .iter() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) +} + +/// What a manifest refers to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ManifestRefs { + /// `sha256:` digests of the config and layers, or of the child manifests of an index. + pub digests: Vec, + /// Bytes of the image: its config and layers. For an index, the manifest's own length. + pub total_size: u64, + /// True for an index or manifest list, whose digests name manifests rather than blobs. + pub is_index: bool, +} + +/// Reads the digests a manifest names. A manifest with a `manifests` array is an index. Any other +/// manifest must name a `config` and may name layers. Every digest must be `sha256:`. +pub fn scan_manifest(bytes: &[u8]) -> Result { + let value: Value = + serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?; + if !value.is_object() { + return Err("manifest is not a JSON object".into()); + } + if let Some(children) = value.get("manifests").and_then(Value::as_array) { + let digests = children + .iter() + .map(descriptor_digest) + .collect::, _>>()?; + return Ok(ManifestRefs { + digests, + total_size: bytes.len() as u64, + is_index: true, + }); + } + let config = value + .get("config") + .ok_or_else(|| "manifest has no config".to_owned())?; + let mut digests = vec![descriptor_digest(config)?]; + let mut total = descriptor_size(config); + if let Some(layers) = value.get("layers") { + let layers = layers + .as_array() + .ok_or_else(|| "manifest layers is not an array".to_owned())?; + for layer in layers { + digests.push(descriptor_digest(layer)?); + total = total.saturating_add(descriptor_size(layer)); + } + } + Ok(ManifestRefs { + digests, + total_size: total, + is_index: false, + }) +} + +fn descriptor_digest(descriptor: &Value) -> Result { + let digest = descriptor + .get("digest") + .and_then(Value::as_str) + .ok_or_else(|| "a descriptor has no digest".to_owned())?; + parse_digest(digest) + .map(|hex| format!("sha256:{hex}")) + .ok_or_else(|| format!("unsupported digest {digest}")) +} + +fn descriptor_size(descriptor: &Value) -> u64 { + descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) +} + +fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 { + // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail. + let mut mac = + ::new_from_slice(key).expect("HMAC accepts any key length"); + mac.update(b"oci\0"); + mac.update(payload); + mac +} + +/// Issues a bearer token for `subject` (a user id, or `None` for anonymous), valid until +/// `expires_unix` seconds since the epoch. +pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { + let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); + let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes(); + format!( + "{}.{}", + BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), + BASE64_URL_SAFE_NO_PAD.encode(tag) + ) +} + +/// Checks a bearer token at `now_unix`. Returns the subject it names (`None` for anonymous), or +/// `None` when the token is malformed, forged, or expired. +pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option> { + let (payload_b64, mac_b64) = token.split_once('.')?; + let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?; + let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?; + let expected = mac_for(key, &payload).finalize().into_bytes(); + if !bool::from(expected.as_slice().ct_eq(&tag)) { + return None; + } + let payload = std::str::from_utf8(&payload).ok()?; + let mut parts = payload.split('|'); + if parts.next()? != "oci1" { + return None; + } + let subject = parts.next()?; + let expires: i64 = parts.next()?.parse().ok()?; + if parts.next().is_some() || now_unix >= expires { + return None; + } + Some((!subject.is_empty()).then(|| subject.to_owned())) +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: [u8; 32] = [3; 32]; + const NOW: i64 = 1_700_000_000; + const HEX: &str = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393"; + + #[test] + fn repo_names_need_an_owner_and_an_image() { + assert_eq!(split_repo_name("tahinli/app"), Some(("tahinli", "app"))); + assert_eq!(split_repo_name("tahinli/a/b"), Some(("tahinli", "a/b"))); + assert_eq!(split_repo_name("tahinli"), None); + assert_eq!(split_repo_name("Tahinli/app"), None); + assert_eq!(split_repo_name("tahinli/app/"), None); + assert_eq!(split_repo_name("tahinli//app"), None); + assert_eq!(split_repo_name("tahinli/app__/x"), None); + assert_eq!( + split_repo_name("tahinli/my.app-v2_x"), + Some(("tahinli", "my.app-v2_x")) + ); + assert_eq!(split_repo_name("tahinli/a..b"), None); + } + + #[test] + fn digests_must_be_lowercase_sha256_hex() { + assert_eq!(parse_digest(&format!("sha256:{HEX}")), Some(HEX)); + assert_eq!(parse_digest(HEX), None); + assert_eq!(parse_digest(&format!("sha512:{HEX}")), None); + assert_eq!( + parse_digest(&format!("sha256:{}", HEX.to_uppercase())), + None + ); + assert_eq!(parse_digest(&format!("sha256:{}", &HEX[..63])), None); + } + + #[test] + fn tags_follow_the_spec_charset() { + assert!(valid_tag("latest")); + assert!(valid_tag("v1.2.3-rc_1")); + assert!(!valid_tag("")); + assert!(!valid_tag(".hidden")); + assert!(!valid_tag("a/b")); + assert!(!valid_tag(&"a".repeat(129))); + } + + #[test] + fn an_image_manifest_names_its_config_and_layers() { + let manifest = format!( + r#"{{"schemaVersion":2,"config":{{"digest":"sha256:{HEX}","size":10}}, + "layers":[{{"digest":"sha256:{HEX}","size":100}}]}}"# + ); + let refs = scan_manifest(manifest.as_bytes()).unwrap(); + assert!(!refs.is_index); + assert_eq!(refs.digests, vec![format!("sha256:{HEX}"); 2]); + assert_eq!(refs.total_size, 110); + } + + #[test] + fn an_index_names_child_manifests() { + let manifest = format!(r#"{{"manifests":[{{"digest":"sha256:{HEX}","size":5}}]}}"#); + let refs = scan_manifest(manifest.as_bytes()).unwrap(); + assert!(refs.is_index); + assert_eq!(refs.digests, vec![format!("sha256:{HEX}")]); + } + + #[test] + fn bad_manifests_are_refused() { + assert!(scan_manifest(b"not json").is_err()); + assert!(scan_manifest(b"[]").is_err()); + assert!(scan_manifest(b"{}").is_err()); + assert!(scan_manifest(br#"{"config":{"digest":"md5:x"}}"#).is_err()); + } + + #[test] + fn a_token_round_trips_for_a_user_and_for_anonymous() { + let token = issue_token(&KEY, Some("user-1"), NOW + 60); + assert_eq!(verify_token(&KEY, &token, NOW), Some(Some("user-1".into()))); + let anon = issue_token(&KEY, None, NOW + 60); + assert_eq!(verify_token(&KEY, &anon, NOW), Some(None)); + } + + #[test] + fn a_token_is_refused_when_expired_forged_or_from_another_key() { + let token = issue_token(&KEY, Some("user-1"), NOW + 60); + assert_eq!(verify_token(&KEY, &token, NOW + 60), None); + assert_eq!(verify_token(&[9; 32], &token, NOW), None); + assert_eq!(verify_token(&KEY, "garbage", NOW), None); + let forged = token.replacen(&BASE64_URL_SAFE_NO_PAD.encode("oci1|user-1|"), "x", 1); + assert_eq!(verify_token(&KEY, &forged, NOW), None); + } +} diff --git a/crates/forge-core/src/packages.rs b/crates/forge-core/src/packages.rs new file mode 100644 index 0000000..d9b0f32 --- /dev/null +++ b/crates/forge-core/src/packages.rs @@ -0,0 +1,89 @@ +//! Package registries. An owner (user or org) holds packages of one `kind`; each package has +//! versions. The stored shape is in migrations/0061_packages.sql, the store functions in +//! store/packages.rs. Bytes of a `.crate` live in blob storage under `packages/`; +//! only metadata is stored here. Kinds are `cargo` and `oci` (container images). + +/// The Cargo registry kind. +pub const KIND_CARGO: &str = "cargo"; +/// The container registry kind. Its packages are images; their tags and manifests are in the +/// `oci_*` tables (migrations/0062_oci.sql), not in `package_versions`. +pub const KIND_OCI: &str = "oci"; + +/// A package. `name_key` is the lowercase name the index uses; `private` hides the package and +/// its index from everyone but the owner's members. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Package { + pub id: String, + pub owner_id: String, + pub kind: String, + pub name: String, + pub name_key: String, + pub repo_id: Option, + pub private: bool, + pub created_at: String, + pub updated_at: String, +} + +/// One published version of a package. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PackageVersion { + pub id: String, + pub package_id: String, + pub version: String, + pub yanked: bool, + /// Lowercase hex sha256 of the `.crate` file. + pub checksum: String, + pub size: u64, + /// The index line as published, with `yanked` false. Served with the current yank state. + pub index_json: String, + pub description: Option, + pub readme: Option, + pub publisher_id: String, + pub created_at: String, +} + +/// A package with what its list shows: how many versions it has and the newest one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PackageSummary { + pub package: Package, + pub version_count: u64, + pub latest_version: Option, + pub latest_description: Option, +} + +/// Input for `Store::publish_package_version`. +#[derive(Debug, Clone, Copy)] +pub struct NewPackageVersion<'a> { + pub package_id: &'a str, + pub version: &'a str, + pub checksum: &'a str, + pub size: u64, + pub index_json: &'a str, + pub description: Option<&'a str>, + pub readme: Option<&'a str>, + pub publisher_id: &'a str, +} + +/// A container manifest as pushed. `content` is the exact JSON, so its digest still checks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OciManifest { + pub id: String, + pub package_id: String, + pub digest: String, + pub media_type: String, + pub content: String, + /// The image's config and layers in bytes, or the manifest's length for an index. + pub size: u64, + pub created_at: String, +} + +/// One tag of a container image, with the manifest it points at. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OciTag { + pub tag: String, + pub digest: String, + pub media_type: String, + pub size: u64, + pub created_at: String, + pub updated_at: String, +} diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 6e9803f..134dc0a 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -100,8 +100,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (58, include_str!("../../migrations/0058_passkeys.sql")), (59, include_str!("../../migrations/0059_admin_alerts.sql")), (60, include_str!("../../migrations/0060_runner_memory.sql")), - (61, include_str!("../../migrations/0061_web_push.sql")), - (61, include_str!("../../migrations/0061_merge_queue.sql")), + (61, include_str!("../../migrations/0061_packages.sql")), + (62, include_str!("../../migrations/0062_oci.sql")), + (63, include_str!("../../migrations/0063_web_push.sql")), + (64, include_str!("../../migrations/0064_merge_queue.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 9fb32af..0e62717 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -23,7 +23,9 @@ pub mod migrate; pub mod mirrors; pub mod notifications; pub mod notifications_extra; +pub mod oci; pub mod orgs; +pub mod packages; pub mod passkeys; pub mod pinned; pub mod profile_pins; diff --git a/crates/forge-core/src/store/oci.rs b/crates/forge-core/src/store/oci.rs new file mode 100644 index 0000000..0335564 --- /dev/null +++ b/crates/forge-core/src/store/oci.rs @@ -0,0 +1,332 @@ +//! Container registry storage: the blobs a package may read, its manifests, the tags that name +//! them, and the references each manifest makes. Blob bytes are not here; the web layer writes and +//! deletes them under `oci/` in the blob store. + +use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id}; +use crate::error::{Error, Result}; +use crate::packages::{OciManifest, OciTag}; +use crate::time::now_stamp; + +const MANIFEST_COLS: &str = "id, package_id, digest, media_type, content, size, created_at"; + +fn map_manifest(row: &turso::Row) -> Result { + Ok(OciManifest { + id: col_text(row, 0)?, + package_id: col_text(row, 1)?, + digest: col_text(row, 2)?, + media_type: col_text(row, 3)?, + content: col_text(row, 4)?, + size: to_u64(col_int(row, 5)?)?, + created_at: col_text(row, 6)?, + }) +} + +fn to_u64(value: i64) -> Result { + u64::try_from(value).map_err(|_| Error::Database("negative size".into())) +} + +impl Store { + /// Records that `package_id` may read the blob `digest` of `size` bytes. Linking a digest the + /// package already has changes nothing. + pub async fn oci_link_blob(&self, package_id: &str, digest: &str, size: u64) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO oci_blobs (package_id, digest, size, created_at) \ + VALUES (?1, ?2, ?3, ?4)", + ( + package_id.to_string(), + digest.to_string(), + i64::try_from(size).unwrap_or(i64::MAX), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The size of blob `digest` as `package_id` links it, or `None` when it does not. + pub async fn oci_blob_size(&self, package_id: &str, digest: &str) -> Result> { + let conn = self.read_conn().await; + let size = fetch_opt( + &conn, + "SELECT size FROM oci_blobs WHERE package_id = ?1 AND digest = ?2 LIMIT 1", + (package_id.to_string(), digest.to_string()), + |row| col_int(row, 0), + ) + .await?; + size.map(to_u64).transpose() + } + + /// True when any package links `digest`. Its bytes are kept while this holds. + pub async fn oci_digest_linked(&self, digest: &str) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM oci_blobs WHERE digest = ?1", + (digest.to_string(),), + |row| col_int(row, 0), + ) + .await?; + Ok(count.unwrap_or(0) > 0) + } + + /// Stores a manifest of `package_id` under `digest`, with the digests it refers to. A manifest + /// already stored under that digest is kept as it is. + pub async fn oci_put_manifest( + &self, + package_id: &str, + digest: &str, + media_type: &str, + content: &str, + size: u64, + refs: &[String], + ) -> Result { + { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO oci_manifests (id, package_id, digest, media_type, content, \ + size, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + ( + new_id(), + package_id.to_string(), + digest.to_string(), + media_type.to_string(), + content.to_string(), + i64::try_from(size).unwrap_or(i64::MAX), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + } + let manifest = self + .oci_manifest(package_id, digest) + .await? + .ok_or_else(missing_row)?; + let conn = self.inner.conn.lock().await; + for dep in refs { + conn.execute( + "INSERT OR IGNORE INTO oci_manifest_refs (manifest_id, digest) VALUES (?1, ?2)", + (manifest.id.clone(), dep.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(manifest) + } + + /// The manifest of `package_id` stored under `digest`. + pub async fn oci_manifest( + &self, + package_id: &str, + digest: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {MANIFEST_COLS} FROM oci_manifests WHERE package_id = ?1 AND digest = ?2 \ + LIMIT 1" + ), + (package_id.to_string(), digest.to_string()), + map_manifest, + ) + .await + } + + /// The manifest the tag `tag` of `package_id` points at. + pub async fn oci_tag_manifest( + &self, + package_id: &str, + tag: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT m.id, m.package_id, m.digest, m.media_type, m.content, m.size, m.created_at \ + FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ + WHERE t.package_id = ?1 AND t.tag = ?2 LIMIT 1", + (package_id.to_string(), tag.to_string()), + map_manifest, + ) + .await + } + + /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target. + pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", + (package_id.to_string(), tag.to_string()), + ) + .await + .map_err(db_err)?; + conn.execute( + "INSERT INTO oci_tags (package_id, tag, manifest_id, updated_at) \ + VALUES (?1, ?2, ?3, ?4)", + ( + package_id.to_string(), + tag.to_string(), + manifest_id.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Removes `tag` from `package_id`. Returns the manifest id it pointed at, or `None` when the + /// tag did not exist. + pub async fn oci_delete_tag(&self, package_id: &str, tag: &str) -> Result> { + let manifest_id = { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT manifest_id FROM oci_tags WHERE package_id = ?1 AND tag = ?2 LIMIT 1", + (package_id.to_string(), tag.to_string()), + |row| col_text(row, 0), + ) + .await? + }; + let Some(manifest_id) = manifest_id else { + return Ok(None); + }; + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", + (package_id.to_string(), tag.to_string()), + ) + .await + .map_err(db_err)?; + Ok(Some(manifest_id)) + } + + /// How many tags point at a manifest. + pub async fn oci_manifest_tag_count(&self, manifest_id: &str) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM oci_tags WHERE manifest_id = ?1", + (manifest_id.to_string(),), + |row| col_int(row, 0), + ) + .await?; + to_u64(count.unwrap_or(0)) + } + + /// True when a manifest of `package_id` names `digest`: an index names its children, and a + /// manifest names its blobs. + pub async fn oci_digest_referenced(&self, package_id: &str, digest: &str) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM oci_manifest_refs r JOIN oci_manifests m ON m.id = r.manifest_id \ + WHERE m.package_id = ?1 AND r.digest = ?2", + (package_id.to_string(), digest.to_string()), + |row| col_int(row, 0), + ) + .await?; + Ok(count.unwrap_or(0) > 0) + } + + /// Removes a manifest by id. Its tags and references go with it. + pub async fn oci_delete_manifest(&self, manifest_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM oci_manifests WHERE id = ?1", + (manifest_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Tag names of `package_id` after `last` (empty for the first page), in order, at most + /// `limit` of them. + pub async fn oci_tag_names( + &self, + package_id: &str, + last: &str, + limit: u64, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT tag FROM oci_tags WHERE package_id = ?1 AND tag > ?2 ORDER BY tag LIMIT ?3", + ( + package_id.to_string(), + last.to_string(), + i64::try_from(limit).unwrap_or(i64::MAX), + ), + |row| col_text(row, 0), + ) + .await + } + + /// Every tag of `package_id`, most recently updated first, with its manifest. + pub async fn oci_tags(&self, package_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT t.tag, m.digest, m.media_type, m.size, m.created_at, t.updated_at \ + FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ + WHERE t.package_id = ?1 ORDER BY t.updated_at DESC, t.tag", + (package_id.to_string(),), + |row| { + Ok(OciTag { + tag: col_text(row, 0)?, + digest: col_text(row, 1)?, + media_type: col_text(row, 2)?, + size: to_u64(col_int(row, 3)?)?, + created_at: col_text(row, 4)?, + updated_at: col_text(row, 5)?, + }) + }, + ) + .await + } + + /// The sweep of garbage collection for one package (mark and sweep). Drops every blob link of + /// `package_id` that no manifest of the package refers to, and returns the digests dropped. + /// The caller deletes the bytes of each digest that no package links any more. + pub async fn oci_sweep_unreferenced(&self, package_id: &str) -> Result> { + let unreferenced = { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT digest FROM oci_blobs WHERE package_id = ?1 AND digest NOT IN \ + (SELECT r.digest FROM oci_manifest_refs r JOIN oci_manifests m \ + ON m.id = r.manifest_id WHERE m.package_id = ?1)", + (package_id.to_string(),), + |row| col_text(row, 0), + ) + .await? + }; + let conn = self.inner.conn.lock().await; + for digest in &unreferenced { + conn.execute( + "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", + (package_id.to_string(), digest.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(unreferenced) + } + + /// Removes the link of `digest` from `package_id`. Returns true when there was one. + pub async fn oci_unlink_blob(&self, package_id: &str, digest: &str) -> Result { + let changed = { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", + (package_id.to_string(), digest.to_string()), + ) + .await + .map_err(db_err)? + }; + Ok(changed == 1) + } +} diff --git a/crates/forge-core/src/store/packages.rs b/crates/forge-core/src/store/packages.rs new file mode 100644 index 0000000..0e0c047 --- /dev/null +++ b/crates/forge-core/src/store/packages.rs @@ -0,0 +1,332 @@ +//! Package storage: packages, their versions and the link to a repo. Blob bytes are not here; +//! the web layer writes and deletes them, under the ids this module returns. + +use turso::{Row, Value}; + +use super::{ + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row, + new_id, +}; +use crate::error::{Error, Result}; +use crate::packages::{NewPackageVersion, Package, PackageSummary, PackageVersion}; +use crate::time::now_stamp; + +const PACKAGE_COLS: &str = "p.id, p.owner_id, p.kind, p.name, p.name_key, p.repo_id, p.private, \ + p.created_at, p.updated_at"; + +const VERSION_COLS: &str = "id, package_id, version, yanked, checksum, size, index_json, \ + description, readme, publisher_id, created_at"; + +/// Newest first, by publish time. +const VERSION_ORDER: &str = "created_at DESC, id DESC"; + +fn map_package(row: &Row) -> Result { + Ok(Package { + id: col_text(row, 0)?, + owner_id: col_text(row, 1)?, + kind: col_text(row, 2)?, + name: col_text(row, 3)?, + name_key: col_text(row, 4)?, + repo_id: col_opt_text(row, 5)?, + private: col_int(row, 6)? != 0, + created_at: col_text(row, 7)?, + updated_at: col_text(row, 8)?, + }) +} + +fn map_summary(row: &Row) -> Result { + let count = col_int(row, 9)?; + Ok(PackageSummary { + package: map_package(row)?, + version_count: u64::try_from(count) + .map_err(|_| Error::Database("negative count".into()))?, + latest_version: col_opt_text(row, 10)?, + latest_description: col_opt_text(row, 11)?, + }) +} + +fn map_version(row: &Row) -> Result { + let size = col_int(row, 5)?; + Ok(PackageVersion { + id: col_text(row, 0)?, + package_id: col_text(row, 1)?, + version: col_text(row, 2)?, + yanked: col_int(row, 3)? != 0, + checksum: col_text(row, 4)?, + size: u64::try_from(size).map_err(|_| Error::Database("negative size".into()))?, + index_json: col_text(row, 6)?, + description: col_opt_text(row, 7)?, + readme: col_opt_text(row, 8)?, + publisher_id: col_text(row, 9)?, + created_at: col_text(row, 10)?, + }) +} + +impl Store { + /// The package `name_key` of `owner_id` in `kind`, created when it does not exist yet. The + /// name as first published is kept. + pub async fn ensure_package( + &self, + owner_id: &str, + kind: &str, + name: &str, + name_key: &str, + ) -> Result { + { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO packages (id, owner_id, kind, name, name_key, private, \ + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?6)", + ( + new_id(), + owner_id.to_string(), + kind.to_string(), + name.to_string(), + name_key.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + } + self.package_by_name(owner_id, kind, name_key) + .await? + .ok_or_else(missing_row) + } + + /// One package by id. + pub async fn package(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {PACKAGE_COLS} FROM packages p WHERE p.id = ?1 LIMIT 1"), + (id.to_string(),), + map_package, + ) + .await + } + + /// The package of `owner_id` called `name_key` in `kind`. + pub async fn package_by_name( + &self, + owner_id: &str, + kind: &str, + name_key: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {PACKAGE_COLS} FROM packages p \ + WHERE p.owner_id = ?1 AND p.kind = ?2 AND p.name_key = ?3 LIMIT 1" + ), + (owner_id.to_string(), kind.to_string(), name_key.to_string()), + map_package, + ) + .await + } + + /// Every package of an owner in `kind`, by name, with its version count and newest version. For + /// an `oci` image the versions are its tags, newest first by update, and it has no description. + pub async fn list_packages(&self, owner_id: &str, kind: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {PACKAGE_COLS}, \ + CASE WHEN p.kind = 'oci' THEN \ + (SELECT COUNT(*) FROM oci_tags t WHERE t.package_id = p.id) \ + ELSE (SELECT COUNT(*) FROM package_versions v WHERE v.package_id = p.id) END, \ + CASE WHEN p.kind = 'oci' THEN \ + (SELECT t.tag FROM oci_tags t WHERE t.package_id = p.id \ + ORDER BY t.updated_at DESC, t.tag LIMIT 1) \ + ELSE (SELECT v.version FROM package_versions v WHERE v.package_id = p.id \ + ORDER BY {VERSION_ORDER} LIMIT 1) END, \ + CASE WHEN p.kind = 'oci' THEN NULL \ + ELSE (SELECT v.description FROM package_versions v WHERE v.package_id = p.id \ + ORDER BY {VERSION_ORDER} LIMIT 1) END \ + FROM packages p WHERE p.owner_id = ?1 AND p.kind = ?2 ORDER BY p.name_key" + ), + (owner_id.to_string(), kind.to_string()), + map_summary, + ) + .await + } + + /// The packages linked to a repo, by name. + pub async fn packages_for_repo(&self, repo_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {PACKAGE_COLS} FROM packages p WHERE p.repo_id = ?1 ORDER BY p.name_key" + ), + (repo_id.to_string(),), + map_package, + ) + .await + } + + /// True when the owner has at least one private package in any kind. A registry with one + /// must ask every client for credentials. + pub async fn owner_has_private_packages(&self, owner_id: &str) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT COUNT(*) FROM packages WHERE owner_id = ?1 AND private = 1", + (owner_id.to_string(),), + |row| col_int(row, 0), + ) + .await?; + Ok(count.unwrap_or(0) > 0) + } + + /// Links a package to a repo on this forge, or unlinks it with `None`. + pub async fn set_package_repo(&self, package_id: &str, repo_id: Option<&str>) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE packages SET repo_id = ?2, updated_at = ?3 WHERE id = ?1", + ( + package_id.to_string(), + repo_id.map_or(Value::Null, |id| Value::Text(id.to_string())), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Sets whether a package is private. + pub async fn set_package_private(&self, package_id: &str, private: bool) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE packages SET private = ?2, updated_at = ?3 WHERE id = ?1", + (package_id.to_string(), i64::from(private), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The versions of a package, newest first, yanked ones included. + pub async fn package_versions(&self, package_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 \ + ORDER BY {VERSION_ORDER}" + ), + (package_id.to_string(),), + map_version, + ) + .await + } + + /// One version of a package. + pub async fn package_version( + &self, + package_id: &str, + version: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 AND version = ?2 \ + LIMIT 1" + ), + (package_id.to_string(), version.to_string()), + map_version, + ) + .await + } + + /// Adds a version row. A version that is already published is `Conflict`. The row is + /// written before the bytes, so the caller removes it with [`Store::delete_package_version`] + /// when the blob write fails. + pub async fn publish_package_version( + &self, + new: &NewPackageVersion<'_>, + ) -> Result { + let now = now_stamp(); + { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO package_versions (id, package_id, version, yanked, checksum, size, \ + index_json, description, readme, publisher_id, created_at) \ + VALUES (?1, ?2, ?3, 0, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + ( + new_id(), + new.package_id.to_string(), + new.version.to_string(), + new.checksum.to_string(), + i64::try_from(new.size).unwrap_or(i64::MAX), + new.index_json.to_string(), + new.description + .map_or(Value::Null, |d| Value::Text(d.to_string())), + new.readme + .map_or(Value::Null, |r| Value::Text(r.to_string())), + new.publisher_id.to_string(), + now.clone(), + ), + ) + .await + .map_err(|e| insert_err(e, "this version is already published"))?; + conn.execute( + "UPDATE packages SET updated_at = ?2 WHERE id = ?1", + (new.package_id.to_string(), now), + ) + .await + .map_err(db_err)?; + } + self.package_version(new.package_id, new.version) + .await? + .ok_or_else(missing_row) + } + + /// Removes a version row, for when its bytes could not be stored. + pub async fn delete_package_version(&self, package_id: &str, version: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM package_versions WHERE package_id = ?1 AND version = ?2", + (package_id.to_string(), version.to_string()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Sets the yank state of a version. Returns false when the version does not exist. + pub async fn set_package_version_yanked( + &self, + package_id: &str, + version: &str, + yanked: bool, + ) -> Result { + let changed = { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE package_versions SET yanked = ?3 WHERE package_id = ?1 AND version = ?2", + ( + package_id.to_string(), + version.to_string(), + i64::from(yanked), + ), + ) + .await + .map_err(db_err)? + }; + if changed == 1 { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE packages SET updated_at = ?2 WHERE id = ?1", + (package_id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + } + Ok(changed == 1) + } +} diff --git a/crates/forge-core/src/store/web_push.rs b/crates/forge-core/src/store/web_push.rs index f6fd89d..c85dfe8 100644 --- a/crates/forge-core/src/store/web_push.rs +++ b/crates/forge-core/src/store/web_push.rs @@ -1,4 +1,4 @@ -//! Web Push (migration 0061): the instance's VAPID key pair and each user's push subscriptions. +//! Web Push (migration 0063): the instance's VAPID key pair and each user's push subscriptions. //! The store keeps the private key sealed; the web crate seals and opens it with the instance key. use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index a09b4f5..f3db2ec 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -8,6 +8,7 @@ pub mod gitea; #[cfg(test)] mod gitea_tests; +pub mod packages; pub mod releases; pub mod statuses; @@ -101,6 +102,28 @@ pub async fn authenticate( ip: IpAddr, headers: &HeaderMap, ) -> Result, Refusal> { + let Some((user, token_id, scopes)) = authenticate_token(state, ip, headers).await? else { + return Ok(None); + }; + if !scopes.iter().any(|scope| scope == REPO_SCOPE) { + return Err(Box::new(error( + StatusCode::FORBIDDEN, + "the token lacks the repo scope", + ))); + } + if let Err(e) = state.store.touch_token(&token_id).await { + return Err(internal(e)); + } + Ok(Some(user)) +} + +/// The user a token names, with the token's id and scopes. `None` when the request carries no +/// Authorization header. The scope is not checked and the token is not touched: the caller does both. +pub(crate) async fn authenticate_token( + state: &AppState, + ip: IpAddr, + headers: &HeaderMap, +) -> Result)>, Refusal> { if !headers.contains_key(AUTHORIZATION) { return Ok(None); } @@ -137,16 +160,7 @@ pub async fn authenticate( } Err(e) => return Err(internal(e)), }; - if !access.scopes.iter().any(|scope| scope == REPO_SCOPE) { - return Err(Box::new(error( - StatusCode::FORBIDDEN, - "the token lacks the repo scope", - ))); - } - if let Err(e) = state.store.touch_token(&access.id).await { - return Err(internal(e)); - } - Ok(Some(user)) + Ok(Some((user, access.id, access.scopes))) } /// Maps a refused action. Anonymous callers always get 401, whether the repo is hidden, missing, diff --git a/crates/forge-web/src/api/packages.rs b/crates/forge-web/src/api/packages.rs new file mode 100644 index 0000000..c458085 --- /dev/null +++ b/crates/forge-web/src/api/packages.rs @@ -0,0 +1,367 @@ +//! The Cargo registry protocol under `/api/packages/{owner}/cargo/`: the sparse index and +//! `config.json` that cargo reads, the `.crate` downloads, and the web API that `cargo publish`, +//! `cargo yank` and `cargo owner --list` call. Documented for users in docs/packages.md. +//! +//! Cargo sends the bare token in `Authorization`, so a token with no scheme is accepted here +//! and read as a Bearer token. Reads are public for public packages. Private packages, and any +//! write, need a token with the `packages` scope. Errors use cargo's body, `{"errors":[{"detail":...}]}`. + +use forge_core::User; +use futures_util::StreamExt; +use http::HeaderMap; +use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; +use http_body::Frame; +use http_body_util::StreamBody; +use serde_json::{Value, json}; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, path_param, route}; + +use crate::api::{self, Refusal}; +use crate::client_ip::client_ip; +use crate::package_ops::{self, PackageError}; +use crate::state::AppState; + +/// The scope a token needs for registry writes and private reads. +pub const PACKAGES_SCOPE: &str = "packages"; + +path_param!(owner); +path_param!(name); +path_param!(version); + +/// The caller of a registry request. Reads with a token that lacks the scope are served as +/// anonymous, so a token made for another purpose cannot break a public install. Writes refuse. +async fn caller(cx: &Cx, scope_required: bool) -> Result, Refusal> { + let state = app_context::(cx); + let normalized = bare_token_as_bearer(headers(cx)); + let (user, token_id, scopes) = + match api::authenticate_token(state, client_ip(cx), &normalized).await { + Ok(Some(found)) => found, + Ok(None) => return Ok(None), + Err(refusal) => { + return Err(Box::new(cargo_error( + refusal.status(), + "authentication required", + ))); + } + }; + if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) { + return if scope_required { + Err(Box::new(cargo_error( + StatusCode::FORBIDDEN, + "the token lacks the packages scope", + ))) + } else { + Ok(None) + }; + } + if let Err(e) = state.store.touch_token(&token_id).await { + return Err(Box::new(failure(PackageError::Internal(e.to_string())))); + } + Ok(Some(user)) +} + +/// The headers with a bare token rewritten to `Bearer `. Anything with a scheme is left +/// as it was. +fn bare_token_as_bearer(headers: &HeaderMap) -> HeaderMap { + let mut out = headers.clone(); + let bare = headers + .get(AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty() && !value.contains(' ')) + .map(str::to_owned); + if let Some(token) = bare + && let Ok(value) = HeaderValue::from_str(&format!("Bearer {token}")) + { + out.insert(AUTHORIZATION, value); + } + out +} + +/// A cargo-style error response. +fn cargo_error(status: StatusCode, detail: &str) -> Response { + api::json(status, &json!({ "errors": [{ "detail": detail }] })) +} + +/// Maps a registry failure to its status and cargo error body. +fn failure(e: PackageError) -> Response { + match e { + PackageError::Invalid(msg) => cargo_error(StatusCode::BAD_REQUEST, &msg), + PackageError::NotFound => cargo_error(StatusCode::NOT_FOUND, "not found"), + PackageError::Forbidden => cargo_error( + StatusCode::FORBIDDEN, + "you do not have permission to publish to this registry", + ), + PackageError::Conflict(msg) => cargo_error(StatusCode::CONFLICT, &msg), + PackageError::TooLarge => cargo_error( + StatusCode::PAYLOAD_TOO_LARGE, + "the crate is larger than the registry accepts", + ), + PackageError::Internal(cause) => { + tracing::error!(error = %cause, "package request failed"); + cargo_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error") + } + } +} + +/// A plain text response, used for index files. +fn text(body: String) -> Response { + let mut res = Response::new(Body::from(body)); + *res.status_mut() = StatusCode::OK; + res.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + res +} + +/// Loads the registry owner named in the path, as the caller may see it. A missing owner is 404. +async fn owner_of(cx: &Cx) -> Result { + let state = app_context::(cx); + match package_ops::owner_named(state, path_param::(cx)).await { + Ok(Some(found)) => Ok(found), + Ok(_) => Err(Box::new(failure(PackageError::NotFound))), + Err(e) => Err(Box::new(failure(e))), + } +} + +#[route(GET "/api/packages/{owner}/cargo/config.json")] +async fn config(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + if let Err(res) = caller(cx, false).await { + return Ok(*res); + } + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return Ok(*res), + }; + match package_ops::config_json(state, &owner).await { + Ok(value) => Ok(api::json(StatusCode::OK, &value)), + Err(e) => Ok(failure(e)), + } +} + +/// The index file of a one-letter crate. +#[route(GET "/api/packages/{owner}/cargo/1/{name}")] +async fn index_one(cx: &Cx) -> topcoat::Result { + Ok(index_response(cx).await) +} + +/// The index file of a two-letter crate. +#[route(GET "/api/packages/{owner}/cargo/2/{name}")] +async fn index_two(cx: &Cx) -> topcoat::Result { + Ok(index_response(cx).await) +} + +/// The index file of a crate with three or more letters. The prefix segments are derived from +/// the name, so only the name is looked up. +#[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")] +async fn index_long(cx: &Cx) -> topcoat::Result { + Ok(index_response(cx).await) +} + +async fn index_response(cx: &Cx) -> Response { + let state = app_context::(cx); + let actor = match caller(cx, false).await { + Ok(actor) => actor, + Err(res) => return *res, + }; + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return *res, + }; + let package = + match package_ops::readable_package(state, actor.as_ref(), &owner, path_param::(cx)) + .await + { + Ok(package) => package, + Err(e) => return failure(e), + }; + match package_ops::index_file(state, &package).await { + Ok(body) => text(body), + Err(e) => failure(e), + } +} + +/// The `.crate` file of one version, streamed from the blob store. +#[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")] +async fn download(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let actor = match caller(cx, false).await { + Ok(actor) => actor, + Err(res) => return Ok(*res), + }; + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return Ok(*res), + }; + let read = match package_ops::download( + state, + actor.as_ref(), + &owner, + path_param::(cx), + path_param::(cx), + ) + .await + { + Ok(read) => read, + Err(e) => return Ok(failure(e)), + }; + let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); + let mut res = Response::new(Body::new(StreamBody::new(chunks))); + *res.status_mut() = StatusCode::OK; + res.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_static("application/octet-stream"), + ); + res.headers_mut() + .insert(CONTENT_LENGTH, HeaderValue::from(read.size)); + Ok(res) +} + +/// `cargo publish`. The body is the publish format: a length-prefixed JSON document and a +/// length-prefixed `.crate`. It is read whole, up to the publish limit. +#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] +async fn publish(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let actor = match caller(cx, true).await { + Ok(Some(actor)) => actor, + Ok(None) => { + return Ok(cargo_error( + StatusCode::UNAUTHORIZED, + "authentication required", + )); + } + Err(res) => return Ok(*res), + }; + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return Ok(*res), + }; + let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await { + Ok(bytes) => bytes, + Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))), + }; + match package_ops::publish(state, &owner, &actor, &bytes).await { + Ok(()) => Ok(api::json( + StatusCode::OK, + &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }), + )), + Err(e) => Ok(failure(e)), + } +} + +fn read_failure(e: &impl std::fmt::Display) -> String { + format!("the request body could not be read: {e}") +} + +/// `cargo yank`: marks a version yanked. It stays in the index and downloadable. +#[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")] +async fn yank(cx: &Cx) -> topcoat::Result { + set_yank(cx, true).await +} + +/// `cargo yank --undo`. +#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")] +async fn unyank(cx: &Cx) -> topcoat::Result { + set_yank(cx, false).await +} + +async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result { + let state = app_context::(cx); + let actor = match caller(cx, true).await { + Ok(Some(actor)) => actor, + Ok(None) => { + return Ok(cargo_error( + StatusCode::UNAUTHORIZED, + "authentication required", + )); + } + Err(res) => return Ok(*res), + }; + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return Ok(*res), + }; + match package_ops::set_yanked( + state, + &owner, + &actor, + path_param::(cx), + path_param::(cx), + yanked, + ) + .await + { + Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))), + Err(e) => Ok(failure(e)), + } +} + +/// `cargo owner --list`: the people who may publish. For a user registry that is the user; for +/// an org, its owners. Read-only: adding or removing owners is done in the forge. +#[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")] +async fn owners(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let actor = match caller(cx, false).await { + Ok(actor) => actor, + Err(res) => return Ok(*res), + }; + let owner = match owner_of(cx).await { + Ok(owner) => owner, + Err(res) => return Ok(*res), + }; + if let Err(e) = + package_ops::readable_package(state, actor.as_ref(), &owner, path_param::(cx)).await + { + return Ok(failure(e)); + } + let people: Vec = if owner.is_org() { + match state.store.org_members(&owner.id).await { + Ok(members) => members + .into_iter() + .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner) + .map(|(user, _)| user) + .collect(), + Err(e) => return Ok(failure(e.into())), + } + } else { + vec![owner.clone()] + }; + let users: Vec = people + .iter() + .map(|user| { + json!({ + "id": user.id, + "login": user.username, + "name": user.display_name, + "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username), + }) + }) + .collect(); + Ok(api::json(StatusCode::OK, &json!({ "users": users }))) +} + +#[cfg(test)] +mod tests { + use http::HeaderValue; + + use super::*; + + #[test] + fn a_bare_token_becomes_a_bearer_token() { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc")); + let rewritten = bare_token_as_bearer(&headers); + assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc"); + + let mut bearer = HeaderMap::new(); + bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc")); + assert_eq!( + bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(), + "Bearer forge_abc" + ); + } +} diff --git a/crates/forge-web/src/blobs.rs b/crates/forge-web/src/blobs.rs index ac90aaa..1687e74 100644 --- a/crates/forge-web/src/blobs.rs +++ b/crates/forge-web/src/blobs.rs @@ -178,6 +178,15 @@ impl BlobStore { } } + /// True when `key` holds a blob. Reads only the metadata, not the bytes. + pub async fn exists(&self, key: &str) -> Result { + match self.store.head(&ObjectPath::from(key)).await { + Ok(_) => Ok(true), + Err(object_store::Error::NotFound { .. }) => Ok(false), + Err(e) => Err(storage_err(e)), + } + } + /// Moves `from` to `to`, replacing `to`. Used to give a finished upload its final key. pub async fn rename(&self, from: &str, to: &str) -> Result<()> { self.store diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 5aa0fdc..4e56572 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -136,6 +136,7 @@ pub async fn serve( ci_live: Arc::new(crate::ci::CiLive::default()), live: Arc::new(crate::live::LiveHub::default()), push_live: Arc::new(crate::web_push::PushLive::default()), + packages_live: Arc::new(crate::packages_live::PackagesLive::default()), }; if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { tracing::error!(error = %e, "building the SSH allowed-signers file failed"); diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index a17b56a..7d84a56 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -32,6 +32,7 @@ pub mod merge_queue; pub mod migrate; pub mod misc; pub mod orgs; +pub mod packages; pub mod pulls; pub mod pulls_review; pub mod push; diff --git a/crates/forge-web/src/i18n/packages.rs b/crates/forge-web/src/i18n/packages.rs new file mode 100644 index 0000000..f26f11e --- /dev/null +++ b/crates/forge-web/src/i18n/packages.rs @@ -0,0 +1,141 @@ +//! Strings for the package registry pages: the Packages tab, the package page, the install +//! snippet and the token scope. One variant per phrase and an exhaustive `t` match. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + TabPackages, + PackagesHeading, + PackagesHelp, + NoPackages, + PackageVersions, + PackageVersionCount, + PackageVersionCountOne, + PackagePrivate, + PackageRepoLink, + VersionYanked, + Install, + InstallHelp, + InstallRegistryConfig, + InstallAdd, + InstallPublish, + InstallLogin, + CopyCommand, + Readme, + NoReadme, + ScopePackages, + ScopePackagesHelp, + Cancel, + ContainerKind, + ContainerInstallHelp, + ContainerLogin, + ContainerPull, + ContainerPush, + ContainerTags, + ContainerTag, + ContainerDigest, + ContainerSize, + ContainerCreated, + DeleteTag, + DeleteTagMessage, + DeleteTagConfirm, + NoTags, + PackageTagCount, + PackageTagCountOne, +} + +pub fn t(lang: Lang, key: K) -> &'static str { + use K::*; + use Lang::*; + match (key, lang) { + (Cancel, En) => "Cancel", + (Cancel, Tr) => "Vazgeç", + (ContainerKind, En) => "Container", + (ContainerKind, Tr) => "Konteyner", + (ContainerInstallHelp, En) => { + "Log in with your username and a personal access token that has the packages scope." + } + (ContainerInstallHelp, Tr) => { + "Kullanıcı adınız ve packages kapsamına sahip bir kişisel erişim belirteciyle giriş yapın." + } + (ContainerLogin, En) => "Log in", + (ContainerLogin, Tr) => "Giriş yap", + (ContainerPull, En) => "Pull the image", + (ContainerPull, Tr) => "İmajı çek", + (ContainerPush, En) => "Push a tag", + (ContainerPush, Tr) => "Bir etiket gönder", + (ContainerTags, En) => "Tags", + (ContainerTags, Tr) => "Etiketler", + (ContainerTag, En) => "Tag", + (ContainerTag, Tr) => "Etiket", + (ContainerDigest, En) => "Digest", + (ContainerDigest, Tr) => "Özet", + (ContainerSize, En) => "Size", + (ContainerSize, Tr) => "Boyut", + (ContainerCreated, En) => "Created", + (ContainerCreated, Tr) => "Oluşturuldu", + (DeleteTag, En) => "Delete", + (DeleteTag, Tr) => "Sil", + (DeleteTagMessage, En) => "Delete this tag? An image left with no tag is removed too.", + (DeleteTagMessage, Tr) => "Bu etiket silinsin mi? Etiketsiz kalan imaj da kaldırılır.", + (DeleteTagConfirm, En) => "Yes, delete", + (DeleteTagConfirm, Tr) => "Evet, sil", + (NoTags, En) => "No tags yet. Push an image to see it here.", + (NoTags, Tr) => "Henüz etiket yok. Burada görmek için bir imaj gönderin.", + (PackageTagCount, En) => "tags", + (PackageTagCount, Tr) => "etiket", + (PackageTagCountOne, En) => "tag", + (PackageTagCountOne, Tr) => "etiket", + (TabPackages, En) => "Packages", + (TabPackages, Tr) => "Paketler", + (PackagesHeading, En) => "Packages", + (PackagesHeading, Tr) => "Paketler", + (PackagesHelp, En) => "Packages this owner publishes: Cargo crates and container images.", + (PackagesHelp, Tr) => { + "Bu sahibin yayımladığı paketler: Cargo crate'leri ve konteyner imajları." + } + (NoPackages, En) => "No packages yet.", + (NoPackages, Tr) => "Henüz paket yok.", + (PackageVersions, En) => "Versions", + (PackageVersions, Tr) => "Sürümler", + (PackageVersionCount, En) => "versions", + (PackageVersionCount, Tr) => "sürüm", + (PackageVersionCountOne, En) => "version", + (PackageVersionCountOne, Tr) => "sürüm", + (PackagePrivate, En) => "Private", + (PackagePrivate, Tr) => "Özel", + (PackageRepoLink, En) => "Repository", + (PackageRepoLink, Tr) => "Depo", + (VersionYanked, En) => "yanked", + (VersionYanked, Tr) => "geri çekildi", + (Install, En) => "Install", + (Install, Tr) => "Kurulum", + (InstallHelp, En) => "Add this registry to your Cargo config, then add the crate.", + (InstallHelp, Tr) => { + "Bu kayıt defterini Cargo yapılandırmanıza ekleyin, sonra crate'i ekleyin." + } + (InstallRegistryConfig, En) => "Registry config", + (InstallRegistryConfig, Tr) => "Kayıt defteri yapılandırması", + (InstallAdd, En) => "Add the crate", + (InstallAdd, Tr) => "Crate'i ekle", + (InstallPublish, En) => "Publish", + (InstallPublish, Tr) => "Yayımla", + (InstallLogin, En) => "Log in with a token", + (InstallLogin, Tr) => "Bir belirteçle giriş yapın", + (CopyCommand, En) => "Copy", + (CopyCommand, Tr) => "Kopyala", + (Readme, En) => "README", + (Readme, Tr) => "README", + (NoReadme, En) => "This crate has no README.", + (NoReadme, Tr) => "Bu crate'in README'si yok.", + (ScopePackages, En) => "Packages", + (ScopePackages, Tr) => "Paketler", + (ScopePackagesHelp, En) => { + "Read private packages, publish, yank and unyank crates in the owner's registry." + } + (ScopePackagesHelp, Tr) => { + "Özel paketleri okuma, sahibin kayıt defterine crate yayımlama, geri çekme ve geri alma." + } + } +} diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 7254119..75a5253 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -39,6 +39,9 @@ mod merge_queue; mod mirrors; mod notify; mod notify_hub; +mod oci; +mod package_ops; +mod packages_live; mod pages; mod post_update; mod pulls_sync; diff --git a/crates/forge-web/src/oci/auth.rs b/crates/forge-web/src/oci/auth.rs new file mode 100644 index 0000000..d5bcffc --- /dev/null +++ b/crates/forge-web/src/oci/auth.rs @@ -0,0 +1,217 @@ +//! Who may use the container registry, and the challenge that asks a client for credentials. +//! +//! A request may carry no credentials (anonymous), a personal access token as HTTP Basic or as a +//! Bearer token (the `packages` scope is needed for anything but public reads), or a short-lived +//! bearer token that `GET /v2/token` issued. Permissions are checked on every request against the +//! identity, so a bearer token only names who is calling and expires quickly. + +use forge_core::User; +use forge_core::oci as rules; +use forge_core::packages::{KIND_OCI, Package}; +use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; +use topcoat::context::{Cx, app_context}; +use topcoat::router::StatusCode; +use topcoat::router::request::headers; +use topcoat::router::response::Response; + +use super::oci_error; +use crate::api::{self, Refusal}; +use crate::client_ip::client_ip; +use crate::package_ops::{self, PackageError}; +use crate::state::AppState; + +/// Lifetime of a bearer token from `GET /v2/token`, in seconds. +pub const TOKEN_TTL_SECS: i64 = 300; + +/// The scope the challenge names for a repository. +const ACTIONS: &str = "pull,push"; + +/// The caller of a registry request. `user` is `None` for anonymous callers. +pub struct Caller { + pub user: Option, +} + +/// The repository a request names, as its owner and package stand now. +pub struct Target { + pub owner: User, + pub image: String, + pub package: Option, +} + +/// Resolves the caller from the `Authorization` header. A bearer token this forge issued is +/// verified here; anything else goes to the personal access token check the API uses. A bad +/// credential is a 401 with the challenge, so the client can ask again. +pub async fn caller(cx: &Cx) -> Result { + let state = app_context::(cx); + let headers = headers(cx); + let Some(value) = headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()) else { + return Ok(Caller { user: None }); + }; + if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) + && !bearer.starts_with("forge_") + { + let now = unix_now(); + return match rules::verify_token(&state.key, bearer, now) { + Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { + Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), + Ok(_) => Err(Box::new(challenge(state, None))), + Err(e) => Err(Box::new(internal(e))), + }, + Some(None) => Ok(Caller { user: None }), + None => Err(Box::new(challenge(state, None))), + }; + } + match api::authenticate_token(state, client_ip(cx), headers).await { + Ok(Some((user, token_id, scopes))) => { + if !scopes + .iter() + .any(|s| s == crate::api::packages::PACKAGES_SCOPE) + { + return Ok(Caller { user: None }); + } + if let Err(e) = state.store.touch_token(&token_id).await { + return Err(Box::new(internal(e))); + } + Ok(Caller { user: Some(user) }) + } + Ok(None) => Ok(Caller { user: None }), + Err(_) => Err(Box::new(challenge(state, None))), + } +} + +/// Resolves the repository `name` for `caller`. A write needs the owner, an org owner, or the +/// instance admin, and a signed-in caller. A read of a missing or private image is refused +/// without saying which: anonymous callers get the challenge, signed-in ones 404 or 403. +pub async fn authorize( + state: &AppState, + caller: &Caller, + name: &str, + write: bool, +) -> Result { + let Some((owner_name, image)) = rules::split_repo_name(name) else { + return Err(Box::new(oci_error( + StatusCode::BAD_REQUEST, + "NAME_INVALID", + "invalid repository name", + ))); + }; + let anonymous = caller.user.is_none(); + if write && anonymous { + return Err(Box::new(challenge(state, Some(name)))); + } + let owner = state + .store + .user_by_username(owner_name) + .await + .map_err(internal)?; + let Some(owner) = owner else { + return Err(Box::new(if anonymous { + challenge(state, Some(name)) + } else { + oci_error( + StatusCode::NOT_FOUND, + "NAME_UNKNOWN", + "repository name not known to registry", + ) + })); + }; + let package = state + .store + .package_by_name(&owner.id, KIND_OCI, image) + .await + .map_err(internal)?; + let target = Target { + owner: owner.clone(), + image: image.to_owned(), + package: package.clone(), + }; + if write { + let user = caller.user.as_ref().expect("checked above"); + if !package_ops::may_publish(state, user, &owner) + .await + .map_err(package_failure)? + { + return Err(Box::new(denied())); + } + return Ok(target); + } + match package { + Some(package) => { + let readable = package_ops::may_read(state, caller.user.as_ref(), &owner, &package) + .await + .map_err(package_failure)?; + if readable { + Ok(target) + } else if anonymous { + Err(Box::new(challenge(state, Some(name)))) + } else { + Err(Box::new(denied())) + } + } + None if anonymous => Err(Box::new(challenge(state, Some(name)))), + None => Err(Box::new(oci_error( + StatusCode::NOT_FOUND, + "NAME_UNKNOWN", + "repository name not known to registry", + ))), + } +} + +/// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when +/// the request names one. +pub fn challenge(state: &AppState, name: Option<&str>) -> Response { + let base = state.config.base_url.trim_end_matches('/'); + let host = base.split_once("://").map_or(base, |(_, rest)| rest); + let mut value = format!("Bearer realm=\"{base}/v2/token\",service=\"{host}\""); + if let Some(name) = name { + value.push_str(&format!(",scope=\"repository:{name}:{ACTIONS}\"")); + } + let mut res = oci_error( + StatusCode::UNAUTHORIZED, + "UNAUTHORIZED", + "authentication required", + ); + if let Ok(header) = HeaderValue::from_str(&value) { + res.headers_mut().insert(WWW_AUTHENTICATE, header); + } + res +} + +/// The 403 for a signed-in caller who may not do the thing. +pub fn denied() -> Response { + oci_error( + StatusCode::FORBIDDEN, + "DENIED", + "requested access to the resource is denied", + ) +} + +/// Logs an internal failure and answers 500 in the registry's error body. +pub fn internal(error: impl std::fmt::Display) -> Response { + tracing::error!(error = %error, "oci request failed"); + oci_error( + StatusCode::INTERNAL_SERVER_ERROR, + "UNKNOWN", + "internal server error", + ) +} + +/// Maps a package permission failure to a refusal. +pub fn package_failure(error: PackageError) -> Refusal { + match error { + PackageError::Internal(cause) => Box::new(internal(cause)), + _ => Box::new(denied()), + } +} + +/// Logs an internal failure and boxes the 500 as a refusal. +pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal { + Box::new(internal(error)) +} + +/// The current time in seconds since the epoch. +pub fn unix_now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) +} diff --git a/crates/forge-web/src/oci/blobs.rs b/crates/forge-web/src/oci/blobs.rs new file mode 100644 index 0000000..c5e9511 --- /dev/null +++ b/crates/forge-web/src/oci/blobs.rs @@ -0,0 +1,458 @@ +//! Blobs of the container registry: upload sessions, the digest check, the blob store writes, and +//! the blob reads. +//! +//! An upload session is a temp file under `/oci/uploads`, named by a ULID, with a +//! sidecar `.repo` that names the repository it belongs to. Chunks are appended to it. When +//! the client finishes, the file's sha256 must match the digest it names; then the bytes move into +//! the blob store under `oci/`, shared by every package that links the digest. A session that +//! is never finished is removed once it is a day old; the check runs when a new session starts, so +//! no timer is needed. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +use forge_core::oci as rules; +use forge_core::packages::{KIND_OCI, Package}; +use futures_util::StreamExt; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; +use http_body::Frame; +use http_body_util::StreamBody; +use sha2::{Digest, Sha256}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode}; + +use super::auth::{self, Caller, Target, internal, internal_refusal}; +use super::{gc, oci_error}; +use crate::api::Refusal; +use crate::state::AppState; + +/// Largest blob accepted, in bytes. +pub const MAX_BLOB_BYTES: u64 = 10 * 1024 * 1024 * 1024; +/// Bytes read from a temp file at a time. +const CHUNK: usize = 1024 * 1024; +/// How long an unfinished upload is kept. +const SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60); + +/// The directory of upload sessions: `/oci/uploads`. +pub fn uploads_dir(data_dir: &Path) -> PathBuf { + data_dir.join("oci").join("uploads") +} + +/// The blob store key of a digest's bytes. +pub fn blob_key(hex: &str) -> String { + format!("oci/{hex}") +} + +/// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a +/// session, so no id can name a path outside the uploads directory. +pub fn valid_session_id(id: &str) -> bool { + id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) +} + +fn session_path(dir: &Path, id: &str) -> PathBuf { + dir.join(id) +} + +fn sidecar_path(dir: &Path, id: &str) -> PathBuf { + dir.join(format!("{id}.repo")) +} + +/// Starts a session for `name`, after removing sessions that were left unfinished for a day. +pub async fn new_session(data_dir: &Path, name: &str) -> std::io::Result { + let dir = uploads_dir(data_dir); + tokio::fs::create_dir_all(&dir).await?; + remove_stale(&dir).await; + let id = ulid::Ulid::generate().to_string(); + tokio::fs::File::create_new(session_path(&dir, &id)).await?; + tokio::fs::write(sidecar_path(&dir, &id), name).await?; + Ok(id) +} + +/// Removes every session whose file has not changed for [`SESSION_TTL`]. Failures are ignored: a +/// session that cannot be removed now is tried again at the next start. +async fn remove_stale(dir: &Path) { + let Ok(mut entries) = tokio::fs::read_dir(dir).await else { + return; + }; + let now = SystemTime::now(); + while let Ok(Some(entry)) = entries.next_entry().await { + let path = entry.path(); + if path.extension().is_some_and(|ext| ext == "repo") { + continue; + } + let Ok(meta) = entry.metadata().await else { + continue; + }; + let age = meta + .modified() + .ok() + .and_then(|at| now.duration_since(at).ok()); + if age.is_some_and(|age| age > SESSION_TTL) { + if let Some(id) = path.file_name().and_then(|n| n.to_str()) { + let _ = tokio::fs::remove_file(sidecar_path(dir, id)).await; + } + let _ = tokio::fs::remove_file(&path).await; + } + } +} + +/// True when session `id` exists and belongs to repository `name`. +pub async fn session_belongs_to(data_dir: &Path, id: &str, name: &str) -> bool { + if !valid_session_id(id) { + return false; + } + let dir = uploads_dir(data_dir); + match tokio::fs::read_to_string(sidecar_path(&dir, id)).await { + Ok(owner) => owner == name && tokio::fs::metadata(session_path(&dir, id)).await.is_ok(), + Err(_) => false, + } +} + +/// Removes a session's files, once it is finished or cancelled. +pub async fn remove_session(data_dir: &Path, id: &str) { + let dir = uploads_dir(data_dir); + let _ = tokio::fs::remove_file(sidecar_path(&dir, id)).await; + let _ = tokio::fs::remove_file(session_path(&dir, id)).await; +} + +/// The size of a session file so far. +pub async fn session_size(data_dir: &Path, id: &str) -> std::io::Result { + let meta = tokio::fs::metadata(session_path(&uploads_dir(data_dir), id)).await?; + Ok(meta.len()) +} + +/// Appends the request body to a session. `expected_start` is the offset a `Content-Range` names, +/// when the client sent one; a mismatch is refused without writing. Returns the new size. +pub async fn append( + data_dir: &Path, + id: &str, + body: Body, + expected_start: Option, +) -> Result> { + let path = session_path(&uploads_dir(data_dir), id); + let mut file = tokio::fs::OpenOptions::new() + .append(true) + .open(&path) + .await + .map_err(|e| Box::new(internal(e)))?; + let size = file + .metadata() + .await + .map_err(|e| Box::new(internal(e)))? + .len(); + if expected_start.is_some_and(|start| start != size) { + return Err(Box::new(range_not_satisfiable(size))); + } + let mut written = size; + let mut stream = std::pin::pin!(body.into_data_stream()); + while let Some(chunk) = stream.next().await { + let Ok(chunk) = chunk else { + return Err(Box::new(oci_error( + StatusCode::BAD_REQUEST, + "BLOB_UPLOAD_INVALID", + "the request body could not be read", + ))); + }; + written = written.saturating_add(chunk.len() as u64); + if written > MAX_BLOB_BYTES { + return Err(Box::new(oci_error( + StatusCode::PAYLOAD_TOO_LARGE, + "SIZE_INVALID", + "the blob is larger than the registry accepts", + ))); + } + file.write_all(&chunk) + .await + .map_err(|e| Box::new(internal(e)))?; + } + file.flush().await.map_err(|e| Box::new(internal(e)))?; + Ok(written) +} + +/// The sha256 of a file, hex. +pub async fn file_sha256(path: &Path) -> std::io::Result { + let mut file = tokio::fs::File::open(path).await?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; CHUNK]; + loop { + let read = file.read(&mut buf).await?; + if read == 0 { + break; + } + hasher.update(&buf[..read]); + } + Ok(hex::encode(hasher.finalize())) +} + +/// Links `digest` to `package` once its bytes are in the blob store. Holds the garbage collection +/// lock, so a sweep cannot remove bytes between the check and the link. +pub async fn link( + state: &AppState, + package: &Package, + hex: &str, + size: u64, + source: Option<&Path>, +) -> Result<(), Refusal> { + let _gc = gc::lock().await; + let key = blob_key(hex); + let exists = state.blobs.exists(&key).await.map_err(internal_refusal)?; + if !exists { + let Some(source) = source else { + return Err(Box::new(oci_error( + StatusCode::NOT_FOUND, + "BLOB_UNKNOWN", + "blob unknown to registry", + ))); + }; + copy_into_store(state, &key, source).await?; + } + state + .store + .oci_link_blob(&package.id, &format!("sha256:{hex}"), size) + .await + .map_err(internal_refusal) +} + +async fn copy_into_store(state: &AppState, key: &str, source: &Path) -> Result<(), Refusal> { + let mut file = tokio::fs::File::open(source) + .await + .map_err(internal_refusal)?; + let mut writer = state + .blobs + .begin(key, MAX_BLOB_BYTES) + .await + .map_err(internal_refusal)?; + let mut buf = vec![0u8; CHUNK]; + loop { + let read = match file.read(&mut buf).await { + Ok(read) => read, + Err(e) => { + writer.abort().await; + return Err(internal_refusal(e)); + } + }; + if read == 0 { + break; + } + if let Err(e) = writer.push(&buf[..read]).await { + writer.abort().await; + return Err(internal_refusal(e)); + } + } + writer.finish().await.map_err(internal_refusal)?; + Ok(()) +} + +/// The response that closes an upload with its blob's location. +pub fn created(name: &str, hex: &str) -> Response { + let digest = format!("sha256:{hex}"); + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::CREATED; + insert(&mut res, "location", &format!("/v2/{name}/blobs/{digest}")); + insert(&mut res, "docker-content-digest", &digest); + res +} + +/// A 202 for an upload still open, with the bytes received so far. +pub fn upload_progress(name: &str, id: &str, size: u64) -> Response { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::ACCEPTED; + insert( + &mut res, + "location", + &format!("/v2/{name}/blobs/uploads/{id}"), + ); + insert(&mut res, "docker-upload-uuid", id); + insert(&mut res, "range", &range_of(size)); + res +} + +/// The `Range` a registry answers with: the bytes received, `0-n`, or `0-0` when none. +pub fn range_of(size: u64) -> String { + format!("0-{}", size.saturating_sub(1)) +} + +fn range_not_satisfiable(size: u64) -> Response { + let mut res = oci_error( + StatusCode::RANGE_NOT_SATISFIABLE, + "BLOB_UPLOAD_INVALID", + "the chunk does not start where the upload ends", + ); + insert(&mut res, "range", &range_of(size)); + res +} + +/// Sets a header from a string value. A value that is not a valid header is left out. +pub fn insert(res: &mut Response, name: &'static str, value: &str) { + if let Ok(value) = HeaderValue::from_str(value) { + res.headers_mut() + .insert(http::HeaderName::from_static(name), value); + } +} + +/// A blob GET or HEAD. The blob must be linked to the package the caller may read. +pub async fn get_blob( + state: &AppState, + caller: &Caller, + name: &str, + digest: &str, + head: bool, +) -> Response { + let target = match auth::authorize(state, caller, name, false).await { + Ok(target) => target, + Err(res) => return *res, + }; + let Some(hex) = rules::parse_digest(digest) else { + return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); + }; + let Some(package) = target.package.as_ref() else { + return unknown_blob(); + }; + let size = match state.store.oci_blob_size(&package.id, digest).await { + Ok(Some(size)) => size, + Ok(None) => return unknown_blob(), + Err(e) => return internal(e), + }; + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::OK; + insert(&mut res, "docker-content-digest", digest); + res.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_static("application/octet-stream"), + ); + res.headers_mut() + .insert(CONTENT_LENGTH, HeaderValue::from(size)); + if head { + return res; + } + match state.blobs.read(&blob_key(hex)).await { + Ok(Some(read)) => { + let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); + *res.body_mut() = Body::new(StreamBody::new(chunks)); + res + } + // Linked but missing from the store: the store is damaged, not the request. + Ok(None) => internal("a linked blob is missing from the blob store"), + Err(e) => internal(e), + } +} + +fn unknown_blob() -> Response { + oci_error( + StatusCode::NOT_FOUND, + "BLOB_UNKNOWN", + "blob unknown to registry", + ) +} + +/// Unlinks a blob from the repository. A blob a manifest of the repo still names is kept, so no +/// image breaks; the caller deletes the manifest first. Bytes no package links are removed. +pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Response { + let Some(hex) = rules::parse_digest(digest) else { + return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); + }; + let Some(package) = target.package.as_ref() else { + return unknown_blob(); + }; + match state.store.oci_blob_size(&package.id, digest).await { + Ok(Some(_)) => {} + Ok(None) => return unknown_blob(), + Err(e) => return internal(e), + } + match state.store.oci_digest_referenced(&package.id, digest).await { + Ok(true) => { + return oci_error( + StatusCode::BAD_REQUEST, + "UNSUPPORTED", + "a manifest still uses this blob; delete the manifest first", + ); + } + Ok(false) => {} + Err(e) => return internal(e), + } + let _gc = gc::lock().await; + if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await { + return internal(e); + } + match state.store.oci_digest_linked(digest).await { + Ok(false) => { + if let Err(e) = state.blobs.delete(&blob_key(hex)).await { + return internal(e); + } + } + Ok(true) => {} + Err(e) => return internal(e), + } + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::ACCEPTED; + res +} + +/// The package a write goes to, created on first use. +pub async fn write_package(state: &AppState, target: &Target) -> Result { + if let Some(package) = target.package.as_ref() { + return Ok(package.clone()); + } + state + .store + .ensure_package(&target.owner.id, KIND_OCI, &target.image, &target.image) + .await + .map_err(internal_refusal) +} + +/// Mounts `digest` from repository `from` into the target when the caller may read `from` and +/// the blob is there. Returns false when the mount is not possible, so the caller starts an upload. +pub async fn try_mount( + state: &AppState, + caller: &Caller, + target: &Target, + digest: &str, + from: &str, +) -> Result { + let Some(hex) = rules::parse_digest(digest) else { + return Ok(false); + }; + let Ok(source) = auth::authorize(state, caller, from, false).await else { + return Ok(false); + }; + let Some(source_package) = source.package.as_ref() else { + return Ok(false); + }; + let Some(size) = state + .store + .oci_blob_size(&source_package.id, digest) + .await + .map_err(internal_refusal)? + else { + return Ok(false); + }; + if !state + .blobs + .exists(&blob_key(hex)) + .await + .map_err(internal_refusal)? + { + return Ok(false); + } + let package = write_package(state, target).await?; + link(state, &package, hex, size, None).await?; + Ok(true) +} + +/// Reads the digest a request names, or the 400 when it is malformed. +pub fn digest_arg(digest: &str) -> Result<&str, Box> { + rules::parse_digest(digest).ok_or_else(|| { + Box::new(oci_error( + StatusCode::BAD_REQUEST, + "DIGEST_INVALID", + "invalid digest", + )) + }) +} + +/// The offset a `Content-Range` header starts at, when the client sent one. +pub fn content_range_start(headers: &http::HeaderMap) -> Option { + let value = headers.get("content-range")?.to_str().ok()?; + value.split('-').next()?.trim().parse().ok() +} diff --git a/crates/forge-web/src/oci/gc.rs b/crates/forge-web/src/oci/gc.rs new file mode 100644 index 0000000..d1cc608 --- /dev/null +++ b/crates/forge-web/src/oci/gc.rs @@ -0,0 +1,38 @@ +//! Garbage collection of the container registry: a mark and sweep that runs after a manifest or a +//! tag is deleted, never on a timer. +//! +//! Mark: the digests a package's manifests refer to. Sweep: the blob links of that package that no +//! manifest refers to are dropped. Then each dropped digest whose bytes no package links any more +//! is deleted from the blob store. A blob pushed but not yet named by a manifest is swept too, so a +//! push that races a delete fails at its manifest with `MANIFEST_BLOB_UNKNOWN` and can be retried. +//! +//! One process-wide lock serializes the sweep with the links and the manifest writes that depend +//! on the blobs they check, so a sweep never removes bytes between a check and the link after it. + +use tokio::sync::{Mutex, MutexGuard}; + +use super::blobs::blob_key; +use crate::state::AppState; + +static LOCK: Mutex<()> = Mutex::const_new(()); + +/// Takes the registry's garbage collection lock. +pub async fn lock() -> MutexGuard<'static, ()> { + LOCK.lock().await +} + +/// Drops the blob links of `package_id` that no manifest names, and deletes the bytes of the +/// digests that no package links any more. Returns how many digests were dropped. +pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result { + let _guard = lock().await; + let dropped = state.store.oci_sweep_unreferenced(package_id).await?; + for digest in &dropped { + if state.store.oci_digest_linked(digest).await? { + continue; + } + if let Some(hex) = digest.strip_prefix("sha256:") { + state.blobs.delete(&blob_key(hex)).await?; + } + } + Ok(dropped.len()) +} diff --git a/crates/forge-web/src/oci/manifests.rs b/crates/forge-web/src/oci/manifests.rs new file mode 100644 index 0000000..4cbdd09 --- /dev/null +++ b/crates/forge-web/src/oci/manifests.rs @@ -0,0 +1,365 @@ +//! Manifests and tags of the container registry: push, pull, delete and the tag list. A manifest +//! is stored as its exact bytes under its digest; a tag names one manifest of its package. + +use forge_core::User; +use forge_core::oci as rules; +use forge_core::packages::Package; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, to_bytes}; + +use super::auth::{self, Caller, internal}; +use super::blobs::{insert, write_package}; +use super::{gc, oci_error}; +use crate::state::AppState; + +/// Largest manifest accepted, in bytes. +pub const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; + +/// What a manifest reference names: a digest, or a tag. +pub enum Reference<'a> { + Digest(&'a str), + Tag(&'a str), +} + +/// Reads a reference from a path segment. A reference with a colon is a digest, anything else a +/// tag. The error is the response to send. +pub fn parse_reference(reference: &str) -> Result, Box> { + if reference.contains(':') { + if rules::parse_digest(reference).is_some() { + Ok(Reference::Digest(reference)) + } else { + Err(Box::new(oci_error( + StatusCode::BAD_REQUEST, + "DIGEST_INVALID", + "invalid digest", + ))) + } + } else if rules::valid_tag(reference) { + Ok(Reference::Tag(reference)) + } else { + Err(Box::new(oci_error( + StatusCode::BAD_REQUEST, + "TAG_INVALID", + "invalid tag", + ))) + } +} + +fn sha256_of(bytes: &[u8]) -> String { + format!("sha256:{}", hex::encode(Sha256::digest(bytes))) +} + +fn manifest_unknown() -> Response { + oci_error( + StatusCode::NOT_FOUND, + "MANIFEST_UNKNOWN", + "manifest unknown to registry", + ) +} + +fn name_unknown() -> Response { + oci_error( + StatusCode::NOT_FOUND, + "NAME_UNKNOWN", + "repository name not known to registry", + ) +} + +/// `PUT /v2/{name}/manifests/{reference}`. The referenced blobs must already be in the package, so +/// a manifest never names bytes the registry lacks. The digest of the bytes is the manifest's id. +pub async fn put_manifest( + state: &AppState, + caller: &Caller, + name: &str, + reference: &str, + content_type: Option<&str>, + body: Body, +) -> Response { + let target = match auth::authorize(state, caller, name, true).await { + Ok(target) => target, + Err(res) => return *res, + }; + let reference = match parse_reference(reference) { + Ok(reference) => reference, + Err(res) => return *res, + }; + let media_type = content_type + .and_then(|value| value.split(';').next()) + .map(str::trim) + .unwrap_or_default() + .to_owned(); + if !rules::is_manifest_media_type(&media_type) { + return oci_error( + StatusCode::BAD_REQUEST, + "MANIFEST_INVALID", + "unsupported manifest media type", + ); + } + let bytes = match to_bytes(body, MAX_MANIFEST_BYTES).await { + Ok(bytes) => bytes, + Err(_) => { + return oci_error( + StatusCode::PAYLOAD_TOO_LARGE, + "SIZE_INVALID", + "the manifest is larger than the registry accepts", + ); + } + }; + let digest = sha256_of(&bytes); + if let Reference::Digest(wanted) = reference + && wanted != digest + { + return oci_error( + StatusCode::BAD_REQUEST, + "DIGEST_INVALID", + "the manifest does not match its digest", + ); + } + let Ok(content) = String::from_utf8(bytes.to_vec()) else { + return oci_error( + StatusCode::BAD_REQUEST, + "MANIFEST_INVALID", + "manifest is not UTF-8", + ); + }; + let refs = match rules::scan_manifest(&bytes) { + Ok(refs) => refs, + Err(message) => { + return oci_error(StatusCode::BAD_REQUEST, "MANIFEST_INVALID", &message); + } + }; + + let _gc = gc::lock().await; + let package = match write_package(state, &target).await { + Ok(package) => package, + Err(res) => return *res, + }; + for dep in &refs.digests { + let present = if refs.is_index { + state + .store + .oci_manifest(&package.id, dep) + .await + .map(|m| m.is_some()) + } else { + state + .store + .oci_blob_size(&package.id, dep) + .await + .map(|size| size.is_some()) + }; + match present { + Ok(true) => {} + Ok(false) => { + return oci_error( + StatusCode::BAD_REQUEST, + "MANIFEST_BLOB_UNKNOWN", + &format!("blob unknown to registry: {dep}"), + ); + } + Err(e) => return internal(e), + } + } + let stored = match state + .store + .oci_put_manifest( + &package.id, + &digest, + &media_type, + &content, + refs.total_size, + &refs.digests, + ) + .await + { + Ok(stored) => stored, + Err(e) => return internal(e), + }; + if let Reference::Tag(tag) = reference + && let Err(e) = state.store.oci_set_tag(&package.id, tag, &stored.id).await + { + return internal(e); + } + state.packages_live.bump(&target.owner.id); + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::CREATED; + insert( + &mut res, + "location", + &format!("/v2/{name}/manifests/{digest}"), + ); + insert(&mut res, "docker-content-digest", &digest); + res +} + +/// `GET` and `HEAD` of a manifest, by tag or digest. +pub async fn get_manifest( + state: &AppState, + caller: &Caller, + name: &str, + reference: &str, + head: bool, +) -> Response { + let target = match auth::authorize(state, caller, name, false).await { + Ok(target) => target, + Err(res) => return *res, + }; + let reference = match parse_reference(reference) { + Ok(reference) => reference, + Err(res) => return *res, + }; + let Some(package) = target.package.as_ref() else { + return name_unknown(); + }; + let found = match reference { + Reference::Digest(digest) => state.store.oci_manifest(&package.id, digest).await, + Reference::Tag(tag) => state.store.oci_tag_manifest(&package.id, tag).await, + }; + let manifest = match found { + Ok(Some(manifest)) => manifest, + Ok(None) => return manifest_unknown(), + Err(e) => return internal(e), + }; + let mut res = Response::new(if head { + Body::empty() + } else { + Body::from(manifest.content.clone()) + }); + *res.status_mut() = StatusCode::OK; + if let Ok(value) = HeaderValue::from_str(&manifest.media_type) { + res.headers_mut().insert(CONTENT_TYPE, value); + } + insert(&mut res, "docker-content-digest", &manifest.digest); + res.headers_mut() + .insert(CONTENT_LENGTH, HeaderValue::from(manifest.content.len())); + res +} + +/// `DELETE` of a manifest by digest, which removes it and every tag on it, or by tag, which +/// removes the tag. A manifest left with no tag and no index naming it is removed as well. +pub async fn delete_manifest( + state: &AppState, + caller: &Caller, + name: &str, + reference: &str, +) -> Response { + let target = match auth::authorize(state, caller, name, true).await { + Ok(target) => target, + Err(res) => return *res, + }; + let reference = match parse_reference(reference) { + Ok(reference) => reference, + Err(res) => return *res, + }; + let Some(package) = target.package.as_ref() else { + return name_unknown(); + }; + match reference { + Reference::Digest(digest) => { + let manifest = match state.store.oci_manifest(&package.id, digest).await { + Ok(Some(manifest)) => manifest, + Ok(None) => return manifest_unknown(), + Err(e) => return internal(e), + }; + { + let _gc = gc::lock().await; + if let Err(e) = state.store.oci_delete_manifest(&manifest.id).await { + return internal(e); + } + } + if let Err(e) = gc::sweep(state, &package.id).await { + return internal(e); + } + } + Reference::Tag(tag) => match remove_tag(state, &target.owner, package, tag).await { + Ok(true) => {} + Ok(false) => return manifest_unknown(), + Err(e) => return internal(e), + }, + } + state.packages_live.bump(&target.owner.id); + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::ACCEPTED; + res +} + +/// Removes `tag` from the package. A manifest left with no tag, and not named by an index, goes +/// too, and the sweep follows. Returns false when the tag does not exist. +pub async fn remove_tag( + state: &AppState, + owner: &User, + package: &Package, + tag: &str, +) -> forge_core::Result { + let Some(manifest) = state.store.oci_tag_manifest(&package.id, tag).await? else { + return Ok(false); + }; + { + let _gc = gc::lock().await; + state.store.oci_delete_tag(&package.id, tag).await?; + let tags_left = state.store.oci_manifest_tag_count(&manifest.id).await?; + let named = state + .store + .oci_digest_referenced(&package.id, &manifest.digest) + .await?; + if tags_left == 0 && !named { + state.store.oci_delete_manifest(&manifest.id).await?; + } + } + gc::sweep(state, &package.id).await?; + state.packages_live.bump(&owner.id); + Ok(true) +} + +/// `GET /v2/{name}/tags/list`, with `n` and `last` for pages. A page that is not the last names +/// the next page in a `Link` header. +pub async fn list_tags( + state: &AppState, + caller: &Caller, + name: &str, + n: Option, + last: Option<&str>, +) -> Response { + let target = match auth::authorize(state, caller, name, false).await { + Ok(target) => target, + Err(res) => return *res, + }; + let Some(package) = target.package.as_ref() else { + return name_unknown(); + }; + let last = last.unwrap_or(""); + let wanted = n.map(|n| n.saturating_add(1)); + let names = match state + .store + .oci_tag_names(&package.id, last, wanted.unwrap_or(u64::MAX)) + .await + { + Ok(names) => names, + Err(e) => return internal(e), + }; + let mut names = names; + let mut link = None; + if let Some(n) = n { + let n = usize::try_from(n).unwrap_or(usize::MAX); + if names.len() > n { + names.truncate(n); + if let Some(last_kept) = names.last() { + link = Some(format!( + "; rel=\"next\"" + )); + } + } + } + let body = json!({ "name": name, "tags": names }); + let mut res = Response::new(Body::from(body.to_string())); + *res.status_mut() = StatusCode::OK; + res.headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + if let Some(link) = link { + insert(&mut res, "link", &link); + } + res +} diff --git a/crates/forge-web/src/oci/mod.rs b/crates/forge-web/src/oci/mod.rs new file mode 100644 index 0000000..3a3d202 --- /dev/null +++ b/crates/forge-web/src/oci/mod.rs @@ -0,0 +1,467 @@ +//! The container registry: images pushed and pulled with `docker` or `podman`, speaking the OCI +//! Distribution spec v1.1 under `/v2/`. +//! +//! An image is a package of kind `oci` owned by a user or an org; its name is `{owner}/{image}`, +//! and the image may have nested segments (`{owner}/{a}/{b}`). Blobs are content-addressed bytes +//! in the blob store, shared by digest ([`blobs`]). Manifests and tags live in the database +//! ([`manifests`]). Unreferenced blobs are removed by a mark and sweep after deletes ([`gc`]). +//! Credentials come through `GET /v2/token` ([`auth`]); the Packages tab and the package page show +//! the images ([`crate::pages::packages`]). +//! +//! The `/v2/` path must reach the forge unchanged, with a large body limit and no request +//! buffering, since layers are big. docs/packages.md says how a proxy is set up. + +pub mod auth; +pub mod blobs; +pub mod gc; +pub mod manifests; + +use forge_core::oci as rules; +use http::header::{CONTENT_TYPE, HeaderValue}; +use serde_json::{Value, json}; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{headers, method, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, StatusCode, path_param, route}; + +use crate::state::AppState; +use auth::{Caller, unix_now}; + +path_param!(*rest); + +/// The API version header every `/v2/` answer carries. +const API_VERSION: &str = "docker-distribution-api-version"; + +/// One OCI error response: `{"errors":[{"code","message","detail"}]}`. +pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response { + let body = json!({ "errors": [{ "code": code, "message": message, "detail": Value::Null }] }); + json_response(status, &body) +} + +fn json_response(status: StatusCode, value: &Value) -> Response { + let mut res = Response::new(Body::from(value.to_string())); + *res.status_mut() = status; + res.headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + res.headers_mut() + .insert(API_VERSION, HeaderValue::from_static("registry/2.0")); + res +} + +/// What a `/v2/` path names. +#[derive(Debug, PartialEq, Eq)] +enum Op { + Tags { name: String }, + Manifest { name: String, reference: String }, + UploadStart { name: String }, + Upload { name: String, id: String }, + Blob { name: String, digest: String }, +} + +/// Reads the operation of a path below `/v2/`. The repository name is every segment before the +/// keyword `tags`, `manifests` or `blobs` that begins a valid operation, so nested names work. +fn parse_op(segments: &[&str]) -> Option { + for (i, keyword) in segments.iter().enumerate().skip(1) { + let name = segments[..i].join("/"); + let rest = &segments[i + 1..]; + let op = match *keyword { + "tags" if rest == ["list"] => Op::Tags { name }, + "manifests" if rest.len() == 1 => Op::Manifest { + name, + reference: rest[0].to_owned(), + }, + "blobs" if rest == ["uploads"] => Op::UploadStart { name }, + "blobs" if rest.len() == 2 && rest[0] == "uploads" => Op::Upload { + name, + id: rest[1].to_owned(), + }, + "blobs" if rest.len() == 1 => Op::Blob { + name, + digest: rest[0].to_owned(), + }, + _ => continue, + }; + return Some(op); + } + None +} + +/// The query string as pairs, decoded. +fn query_pairs(cx: &Cx) -> Vec<(String, String)> { + uri(cx) + .query() + .map(|q| { + form_urlencoded::parse(q.as_bytes()) + .map(|(k, v)| (k.into_owned(), v.into_owned())) + .collect() + }) + .unwrap_or_default() +} + +fn query_value(pairs: &[(String, String)], key: &str) -> Option { + pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) +} + +/// `GET /v2/`: the probe. A caller with valid credentials gets 200; anyone else the challenge. +#[route(GET "/v2/")] +async fn root(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + Ok(match auth::caller(cx).await { + Ok(Caller { user: Some(_) }) => json_response(StatusCode::OK, &json!({})), + Ok(_) => auth::challenge(state, None), + Err(res) => *res, + }) +} + +/// `GET /v2/token`: exchanges Basic credentials (a personal access token as the password) for a +/// short-lived bearer token. Anonymous callers get an anonymous token, which reads public images. +#[route(GET "/v2/token")] +async fn token(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let caller = match auth::caller(cx).await { + Ok(caller) => caller, + Err(res) => return Ok(*res), + }; + let subject = caller.user.as_ref().map(|user| user.id.as_str()); + let now = unix_now(); + let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS); + // Clients parse `issued_at` as an RFC 3339 time, so a number is refused. + let issued_at = time::OffsetDateTime::now_utc() + .format(&time::format_description::well_known::Rfc3339) + .unwrap_or_default(); + Ok(json_response( + StatusCode::OK, + &json!({ + "token": token, + "access_token": token, + "expires_in": auth::TOKEN_TTL_SECS, + "issued_at": issued_at, + }), + )) +} + +#[route(GET "/v2/{*rest}")] +async fn get_v2(cx: &Cx, body: Body) -> topcoat::Result { + Ok(dispatch(cx, body).await) +} + +#[route(POST "/v2/{*rest}")] +async fn post_v2(cx: &Cx, body: Body) -> topcoat::Result { + Ok(dispatch(cx, body).await) +} + +#[route(PUT "/v2/{*rest}")] +async fn put_v2(cx: &Cx, body: Body) -> topcoat::Result { + Ok(dispatch(cx, body).await) +} + +#[route(PATCH "/v2/{*rest}")] +async fn patch_v2(cx: &Cx, body: Body) -> topcoat::Result { + Ok(dispatch(cx, body).await) +} + +#[route(DELETE "/v2/{*rest}")] +async fn delete_v2(cx: &Cx, body: Body) -> topcoat::Result { + Ok(dispatch(cx, body).await) +} + +/// Routes a request below `/v2/` to its operation. The caller is resolved first, so every answer +/// about a repository comes from the same identity. +async fn dispatch(cx: &Cx, body: Body) -> Response { + let state = app_context::(cx); + let segments: Vec = path_param::(cx).map(str::to_owned).collect(); + let mut parts: Vec<&str> = segments.iter().map(String::as_str).collect(); + while parts.last() == Some(&"") { + parts.pop(); + } + let caller = match auth::caller(cx).await { + Ok(caller) => caller, + Err(res) => return *res, + }; + let method = method(cx).clone(); + let read = method == http::Method::GET || method == http::Method::HEAD; + let head = method == http::Method::HEAD; + let pairs = query_pairs(cx); + let headers = headers(cx).clone(); + let Some(op) = parse_op(&parts) else { + return oci_error(StatusCode::NOT_FOUND, "NAME_UNKNOWN", "not found"); + }; + match op { + Op::Tags { name } if read => { + let n = query_value(&pairs, "n").and_then(|v| v.parse::().ok()); + let last = query_value(&pairs, "last"); + manifests::list_tags(state, &caller, &name, n, last.as_deref()).await + } + Op::Manifest { name, reference } => match method { + http::Method::GET | http::Method::HEAD => { + manifests::get_manifest(state, &caller, &name, &reference, head).await + } + http::Method::PUT => { + let content_type = headers + .get(CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned); + manifests::put_manifest( + state, + &caller, + &name, + &reference, + content_type.as_deref(), + body, + ) + .await + } + http::Method::DELETE => { + manifests::delete_manifest(state, &caller, &name, &reference).await + } + _ => unsupported(), + }, + Op::Blob { name, digest } => match method { + http::Method::GET | http::Method::HEAD => { + blobs::get_blob(state, &caller, &name, &digest, head).await + } + http::Method::DELETE => match auth::authorize(state, &caller, &name, true).await { + Ok(target) => blobs::delete_blob(state, &target, &digest).await, + Err(res) => *res, + }, + _ => unsupported(), + }, + Op::UploadStart { name } if method == http::Method::POST => { + start_upload(state, &caller, &name, &pairs, body).await + } + Op::Upload { name, id } => { + upload_step(state, &caller, &name, &id, &method, &headers, &pairs, body).await + } + _ => unsupported(), + } +} + +fn unsupported() -> Response { + oci_error( + StatusCode::METHOD_NOT_ALLOWED, + "UNSUPPORTED", + "the operation is unsupported", + ) +} + +/// `POST /v2/{name}/blobs/uploads/`: a cross-repo mount when `mount` and `from` are given and +/// possible, a monolithic upload when `digest` is given with the body, and otherwise a new session. +async fn start_upload( + state: &AppState, + caller: &Caller, + name: &str, + pairs: &[(String, String)], + body: Body, +) -> Response { + let target = match auth::authorize(state, caller, name, true).await { + Ok(target) => target, + Err(res) => return *res, + }; + if let (Some(mount), Some(from)) = (query_value(pairs, "mount"), query_value(pairs, "from")) { + match blobs::try_mount(state, caller, &target, &mount, &from).await { + Ok(true) => { + let hex = rules::parse_digest(&mount).unwrap_or_default(); + state.packages_live.bump(&target.owner.id); + return blobs::created(name, hex); + } + Ok(false) => {} + Err(res) => return *res, + } + } + let data_dir = state.config.data_dir.clone(); + let id = match blobs::new_session(&data_dir, name).await { + Ok(id) => id, + Err(e) => return auth::internal(e), + }; + let Some(digest) = query_value(pairs, "digest") else { + return blobs::upload_progress(name, &id, 0); + }; + let hex = match blobs::digest_arg(&digest) { + Ok(hex) => hex.to_owned(), + Err(res) => { + blobs::remove_session(&data_dir, &id).await; + return *res; + } + }; + if let Err(res) = blobs::append(&data_dir, &id, body, None).await { + blobs::remove_session(&data_dir, &id).await; + return *res; + } + finish_upload(state, &target, name, &id, &hex).await +} + +/// Checks the session and the digest of a finished upload, links the blob to the package and +/// removes the session. A digest that does not match refuses the upload and removes it. +async fn finish_upload( + state: &AppState, + target: &auth::Target, + name: &str, + id: &str, + hex: &str, +) -> Response { + let data_dir = state.config.data_dir.clone(); + let path = blobs::uploads_dir(&data_dir).join(id); + let actual = match blobs::file_sha256(&path).await { + Ok(actual) => actual, + Err(e) => return auth::internal(e), + }; + if actual != hex { + blobs::remove_session(&data_dir, id).await; + return oci_error( + StatusCode::BAD_REQUEST, + "DIGEST_INVALID", + "the content does not match the digest", + ); + } + let size = match tokio::fs::metadata(&path).await { + Ok(meta) => meta.len(), + Err(e) => return auth::internal(e), + }; + let package = match blobs::write_package(state, target).await { + Ok(package) => package, + Err(res) => return *res, + }; + if let Err(res) = blobs::link(state, &package, hex, size, Some(&path)).await { + blobs::remove_session(&data_dir, id).await; + return *res; + } + blobs::remove_session(&data_dir, id).await; + state.packages_live.bump(&target.owner.id); + blobs::created(name, hex) +} + +/// The steps of an open upload: `GET` its status, `PATCH` a chunk, `PUT` the last chunk with the +/// digest, and `DELETE` it. +#[allow(clippy::too_many_arguments)] +async fn upload_step( + state: &AppState, + caller: &Caller, + name: &str, + id: &str, + method: &http::Method, + headers: &http::HeaderMap, + pairs: &[(String, String)], + body: Body, +) -> Response { + let data_dir = state.config.data_dir.clone(); + let target = match auth::authorize(state, caller, name, true).await { + Ok(target) => target, + Err(res) => return *res, + }; + if !blobs::session_belongs_to(&data_dir, id, name).await { + return oci_error( + StatusCode::NOT_FOUND, + "BLOB_UPLOAD_UNKNOWN", + "blob upload unknown to registry", + ); + } + match *method { + http::Method::GET => match blobs::session_size(&data_dir, id).await { + Ok(size) => { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::NO_CONTENT; + blobs::insert( + &mut res, + "location", + &format!("/v2/{name}/blobs/uploads/{id}"), + ); + blobs::insert(&mut res, "docker-upload-uuid", id); + blobs::insert(&mut res, "range", &blobs::range_of(size)); + res + } + Err(e) => auth::internal(e), + }, + http::Method::PATCH => { + if let Err(res) = + blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await + { + return *res; + } + match blobs::session_size(&data_dir, id).await { + Ok(size) => blobs::upload_progress(name, id, size), + Err(e) => auth::internal(e), + } + } + http::Method::PUT => { + let Some(digest) = query_value(pairs, "digest") else { + return oci_error( + StatusCode::BAD_REQUEST, + "DIGEST_INVALID", + "digest is required", + ); + }; + let hex = match blobs::digest_arg(&digest) { + Ok(hex) => hex.to_owned(), + Err(res) => return *res, + }; + if let Err(res) = + blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await + { + return *res; + } + finish_upload(state, &target, name, id, &hex).await + } + http::Method::DELETE => { + blobs::remove_session(&data_dir, id).await; + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::NO_CONTENT; + res + } + _ => unsupported(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_names_parse_up_to_the_keyword() { + assert_eq!( + parse_op(&["tahinli", "app", "manifests", "latest"]), + Some(Op::Manifest { + name: "tahinli/app".into(), + reference: "latest".into(), + }) + ); + assert_eq!( + parse_op(&["tahinli", "a", "b", "blobs", "uploads"]), + Some(Op::UploadStart { + name: "tahinli/a/b".into(), + }) + ); + assert_eq!( + parse_op(&["tahinli", "app", "tags", "list"]), + Some(Op::Tags { + name: "tahinli/app".into(), + }) + ); + } + + #[test] + fn a_keyword_inside_the_name_is_not_taken_for_one() { + assert_eq!( + parse_op(&["tahinli", "blobs", "x", "manifests", "v1"]), + Some(Op::Manifest { + name: "tahinli/blobs/x".into(), + reference: "v1".into(), + }) + ); + } + + #[test] + fn upload_and_blob_paths_are_told_apart() { + assert_eq!( + parse_op(&["tahinli", "app", "blobs", "uploads", "ID1"]), + Some(Op::Upload { + name: "tahinli/app".into(), + id: "ID1".into(), + }) + ); + assert!(matches!( + parse_op(&["tahinli", "app", "blobs", "sha256:abc"]), + Some(Op::Blob { .. }) + )); + assert_eq!(parse_op(&["tahinli"]), None); + } +} diff --git a/crates/forge-web/src/package_ops.rs b/crates/forge-web/src/package_ops.rs new file mode 100644 index 0000000..5928555 --- /dev/null +++ b/crates/forge-web/src/package_ops.rs @@ -0,0 +1,323 @@ +//! Package registry rules of the web layer: who may read or publish a package, publishing a +//! `.crate`, yanking a version, and the index and config files cargo reads. The protocol +//! rules (names, index lines, publish bodies) live in `forge_core::cargo`; the HTTP routes in +//! `api::packages` and the pages translate these results. Bytes go to the blob store under +//! `packages/`, and each change is announced on the owner's live signal. + +use forge_core::cargo; +use forge_core::model::User; +use forge_core::packages::{KIND_CARGO, KIND_OCI, NewPackageVersion, Package}; +use forge_core::store::orgs::OrgMemberRole; +use forge_core::{Error, Repo}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use crate::blobs::BlobRead; +use crate::state::AppState; + +/// Largest `.crate` accepted, in bytes. The limit crates.io uses. +pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024; +/// Largest publish body accepted: the crate plus its JSON metadata. +pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024; +/// Bytes handed to the blob writer at a time. +const PUSH_CHUNK: usize = 1024 * 1024; + +/// Why a registry request failed. The API maps each to a status and a cargo error body. +#[derive(Debug)] +pub enum PackageError { + Invalid(String), + NotFound, + Forbidden, + Conflict(String), + TooLarge, + Internal(String), +} + +impl From for PackageError { + fn from(e: Error) -> Self { + match e { + Error::InvalidName(msg) | Error::Invalid(msg) => Self::Invalid(msg), + Error::NotFound => Self::NotFound, + Error::Conflict(msg) => Self::Conflict(msg), + other => Self::Internal(other.to_string()), + } + } +} + +/// The user or org a registry path names. `None` when no such account exists. +pub async fn owner_named(state: &AppState, name: &str) -> Result, PackageError> { + Ok(state.store.user_by_username(name).await?) +} + +/// True when `actor` may read `package`. Public packages are readable by anyone. A private one +/// is readable by the instance admin, the owner and the owner's org members. +pub async fn may_read( + state: &AppState, + actor: Option<&User>, + owner: &User, + package: &Package, +) -> Result { + if !package.private { + return Ok(true); + } + let Some(actor) = actor else { + return Ok(false); + }; + if actor.is_admin || actor.id == owner.id { + return Ok(true); + } + Ok(owner.is_org() + && state + .store + .org_member_role(&owner.id, &actor.id) + .await? + .is_some()) +} + +/// True when `actor` may publish, yank or unyank in `owner`'s registry: the owner themselves, +/// an org owner, or the instance admin. +pub async fn may_publish( + state: &AppState, + actor: &User, + owner: &User, +) -> Result { + if actor.is_admin || actor.id == owner.id { + return Ok(true); + } + if !owner.is_org() { + return Ok(false); + } + let role = state.store.org_member_role(&owner.id, &actor.id).await?; + Ok(role == Some(OrgMemberRole::Owner)) +} + +/// The package `name` of `owner` as the actor may see it. A missing package and a private one +/// the actor may not read are the same `NotFound`. +pub async fn readable_package( + state: &AppState, + actor: Option<&User>, + owner: &User, + name: &str, +) -> Result { + let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; + let package = state + .store + .package_by_name(&owner.id, KIND_CARGO, &key) + .await? + .ok_or(PackageError::NotFound)?; + if !may_read(state, actor, owner, &package).await? { + return Err(PackageError::NotFound); + } + Ok(package) +} + +/// A container image of `owner` that the viewer may read. The name is the image path below the +/// owner, as the registry stores it. +pub async fn readable_oci_package( + state: &AppState, + actor: Option<&User>, + owner: &User, + name: &str, +) -> Result { + let package = state + .store + .package_by_name(&owner.id, KIND_OCI, name) + .await? + .ok_or(PackageError::NotFound)?; + if !may_read(state, actor, owner, &package).await? { + return Err(PackageError::NotFound); + } + Ok(package) +} + +/// The `config.json` of an owner's registry. `auth-required` is set when the owner has a private +/// package, since cargo then needs a token for every request to that registry. +pub async fn config_json(state: &AppState, owner: &User) -> Result { + let base = state.config.base_url.trim_end_matches('/'); + let auth_required = state.store.owner_has_private_packages(&owner.id).await?; + Ok(json!({ + "dl": format!("{base}/api/packages/{}/cargo/download/{{crate}}/{{version}}", owner.username), + "api": format!("{base}/api/packages/{}/cargo", owner.username), + "auth-required": auth_required, + })) +} + +/// The index file of a package: one JSON line per version, oldest first, each with the current +/// yank state. A package with no versions has no index. +pub async fn index_file(state: &AppState, package: &Package) -> Result { + let mut versions = state.store.package_versions(&package.id).await?; + versions.reverse(); + let mut out = String::new(); + for version in versions { + let mut line: Value = serde_json::from_str(&version.index_json) + .map_err(|e| PackageError::Internal(format!("stored index line: {e}")))?; + line["yanked"] = json!(version.yanked); + out.push_str(&line.to_string()); + out.push('\n'); + } + Ok(out) +} + +/// Publishes a `.crate` from a publish body. The version row is written first, so a repeated +/// version is a `Conflict` before any bytes are stored. A failed byte write removes the row. +pub async fn publish( + state: &AppState, + owner: &User, + actor: &User, + body: &[u8], +) -> Result<(), PackageError> { + if !may_publish(state, actor, owner).await? { + return Err(PackageError::Forbidden); + } + let parsed = cargo::parse_publish(body).map_err(|e| PackageError::Invalid(e.to_string()))?; + let meta = &parsed.metadata; + let name = cargo::meta_str(meta, "name") + .ok_or_else(|| PackageError::Invalid("metadata has no name".into()))?; + let vers = cargo::meta_str(meta, "vers") + .ok_or_else(|| PackageError::Invalid("metadata has no vers".into()))?; + let key = cargo::crate_name_key(name).map_err(|e| PackageError::Invalid(e.to_string()))?; + cargo::parse_version(vers).map_err(|e| PackageError::Invalid(e.to_string()))?; + let krate = parsed.crate_file; + if krate.len() as u64 > MAX_CRATE_BYTES { + return Err(PackageError::TooLarge); + } + + let checksum = hex::encode(Sha256::digest(krate)); + let index_line = cargo::index_line(meta, &checksum) + .map_err(|e| PackageError::Invalid(e.to_string()))? + .to_string(); + let readme = cargo::crate_readme(krate) + .or_else(|| cargo::meta_str(meta, "readme").map(str::to_owned)) + .filter(|text| !text.trim().is_empty()); + let description = cargo::meta_str(meta, "description") + .map(str::trim) + .filter(|text| !text.is_empty()); + + let package = state + .store + .ensure_package(&owner.id, KIND_CARGO, name, &key) + .await?; + link_repo(state, owner, &package, meta).await?; + + let version = state + .store + .publish_package_version(&NewPackageVersion { + package_id: &package.id, + version: vers, + checksum: &checksum, + size: krate.len() as u64, + index_json: &index_line, + description, + readme: readme.as_deref(), + publisher_id: &actor.id, + }) + .await + .map_err(|e| match e { + Error::Conflict(_) => { + PackageError::Conflict(format!("crate version `{name}@{vers}` is already uploaded")) + } + other => other.into(), + })?; + + if let Err(e) = store_bytes(state, &blob_key(&version.id), krate).await { + // Best effort: the row must not outlive its bytes. + let _ = state.store.delete_package_version(&package.id, vers).await; + return Err(PackageError::Internal(e.to_string())); + } + state.packages_live.bump(&owner.id); + Ok(()) +} + +/// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable, +/// marked as yanked, so existing lockfiles keep working. +pub async fn set_yanked( + state: &AppState, + owner: &User, + actor: &User, + name: &str, + version: &str, + yanked: bool, +) -> Result<(), PackageError> { + if !may_publish(state, actor, owner).await? { + return Err(PackageError::Forbidden); + } + let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; + let package = state + .store + .package_by_name(&owner.id, KIND_CARGO, &key) + .await? + .ok_or(PackageError::NotFound)?; + if !state + .store + .set_package_version_yanked(&package.id, version, yanked) + .await? + { + return Err(PackageError::NotFound); + } + state.packages_live.bump(&owner.id); + Ok(()) +} + +/// The `.crate` bytes of a version, for a download. Yanked versions still download. +pub async fn download( + state: &AppState, + actor: Option<&User>, + owner: &User, + name: &str, + version: &str, +) -> Result { + let package = readable_package(state, actor, owner, name).await?; + let found = state + .store + .package_version(&package.id, version) + .await? + .ok_or(PackageError::NotFound)?; + state + .blobs + .read(&blob_key(&found.id)) + .await? + .ok_or(PackageError::NotFound) +} + +/// The blob key of a version's `.crate` file. +pub fn blob_key(version_id: &str) -> String { + format!("packages/{version_id}") +} + +/// Points the package at the repo its `repository` field names, when that repo belongs to the +/// same owner. A repo of another owner is never linked, so nobody can claim it. +async fn link_repo( + state: &AppState, + owner: &User, + package: &Package, + meta: &Value, +) -> Result<(), PackageError> { + let linked: Option = match cargo::meta_str(meta, "repository") + .and_then(|url| cargo::repo_link(url, &state.config.base_url)) + { + Some((repo_owner, repo_name)) if repo_owner.eq_ignore_ascii_case(&owner.username) => state + .store + .repo_by_owner_and_name(&repo_owner, &repo_name) + .await? + .filter(|repo| repo.owner_id == owner.id), + _ => None, + }; + let repo_id = linked.as_ref().map(|repo| repo.id.as_str()); + if package.repo_id.as_deref() != repo_id { + state.store.set_package_repo(&package.id, repo_id).await?; + } + Ok(()) +} + +/// Streams `bytes` into the blob store under `key`, returning the sha256 the store computed. +async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result { + let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?; + for chunk in bytes.chunks(PUSH_CHUNK) { + if let Err(e) = writer.push(chunk).await { + writer.abort().await; + return Err(e); + } + } + let (_, sha) = writer.finish().await?; + Ok(sha) +} diff --git a/crates/forge-web/src/packages_live.rs b/crates/forge-web/src/packages_live.rs new file mode 100644 index 0000000..2d7208a --- /dev/null +++ b/crates/forge-web/src/packages_live.rs @@ -0,0 +1,80 @@ +//! Change signals for package registries. [`PackagesLive`] keeps one generation counter per owner. +//! A publish or a yank bumps the owner's counter, and every open page of that registry wakes and +//! refetches. The counter carries no data, and nothing polls. A signal with no receivers left is +//! removed, so the map holds only the owners somebody is watching. The hub is in-process only, +//! like [`NotifyHub`]. +//! +//! [`NotifyHub`]: crate::notify_hub::NotifyHub + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use tokio::sync::watch; + +/// The change counters of package registries, each keyed by its owner's id. +#[derive(Default)] +pub struct PackagesLive { + owners: Mutex>>, +} + +impl PackagesLive { + /// Subscribes to changes of `owner_id`'s registry. The receiver starts as seen, so a bump + /// after this call wakes it. Subscribe before the state you read, so a change in between is + /// not lost. + pub fn subscribe(&self, owner_id: &str) -> watch::Receiver { + self.owners() + .entry(owner_id.to_owned()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() + } + + /// Counts one change to `owner_id`'s registry. Without a subscriber there is no entry, so the + /// bump is a no-op. An entry whose last receiver is gone is removed here. + pub fn bump(&self, owner_id: &str) { + let mut owners = self.owners(); + let Some(tx) = owners.get(owner_id) else { + return; + }; + tx.send_modify(|generation| *generation = generation.wrapping_add(1)); + if tx.receiver_count() == 0 { + owners.remove(owner_id); + } + } + + fn owners(&self) -> MutexGuard<'_, HashMap>> { + self.owners.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[tokio::test] + async fn a_bump_wakes_only_the_subscribers_of_that_owner() { + let live = PackagesLive::default(); + let mut tahinli = live.subscribe("user-1"); + let mut other = live.subscribe("user-2"); + + live.bump("user-1"); + + tokio::time::timeout(Duration::from_secs(1), tahinli.changed()) + .await + .expect("woken") + .expect("open"); + assert!( + tokio::time::timeout(Duration::from_millis(50), other.changed()) + .await + .is_err() + ); + } + + #[test] + fn a_bump_without_subscribers_leaves_no_entry() { + let live = PackagesLive::default(); + live.bump("nobody"); + assert!(live.owners().is_empty()); + } +} diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 969d653..12c69aa 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -71,6 +71,8 @@ pub mod org_members; pub mod org_new; pub mod org_settings; pub mod org_teams; +pub mod packages; +pub mod packages_oci; pub mod passkeys; #[cfg(test)] mod passkeys_tests; diff --git a/crates/forge-web/src/pages/packages.rs b/crates/forge-web/src/pages/packages.rs new file mode 100644 index 0000000..db06c35 --- /dev/null +++ b/crates/forge-web/src/pages/packages.rs @@ -0,0 +1,460 @@ +//! Pages of the package registries: a package page at `/{owner}/-/packages/{name}` with its +//! install snippet, README and versions, and the owner's `changed` stream that both the package +//! page and the profile's Packages tab follow. The rows of the Packages tab are built here and +//! rendered by the profile page. + +use forge_core::User; +use forge_core::packages::{KIND_CARGO, KIND_OCI, Package}; +use futures_util::{Stream, stream}; +use serde::Deserialize; +use tokio::sync::watch; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::content::sse::Event; +use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param, query_params, route}; +use topcoat::view::{Unescaped, View, component, view}; + +use crate::auth::{current_user, require_csrf}; +use crate::i18n::packages::{self as pk, K}; +use crate::i18n::{self, Lang}; +use crate::oci::manifests; +use crate::package_ops::{self, PackageError}; +use crate::pages::ci_runs::{changed_event, events_response}; +use crate::pages::packages_oci::{self, oci_package_view}; +use crate::render::markdown::render_markdown; +use crate::state::AppState; +use crate::views::{enc, shell}; + +path_param!(owner); +path_param!(name); +path_param!(*pkg); + +/// One package on a list: what the Packages tab and the owner's lists show. +pub(crate) struct PackageRow { + pub name: String, + pub href: String, + pub latest: String, + pub versions: u64, + pub description: String, + pub private: bool, + /// True for a container image, which shows tags instead of versions. + pub container: bool, +} + +/// The package path of a package under its owner. +pub(crate) fn package_href(owner: &str, name: &str) -> String { + format!("/{}/-/packages/{}", enc(owner), enc(name)) +} + +/// The owner's live `changed` stream. Its path is the owner's profile path plus `/-/packages/events`. +pub(crate) fn events_href(owner: &str) -> String { + format!("/{}/-/packages/events", enc(owner)) +} + +/// The packages of `owner` that `viewer` may see, with a version, newest first by name. +/// Packages without a version are not listed. +pub(crate) async fn package_rows( + state: &AppState, + viewer: Option<&User>, + owner: &User, +) -> forge_core::Result> { + let mut summaries = state.store.list_packages(&owner.id, KIND_CARGO).await?; + summaries.extend(state.store.list_packages(&owner.id, KIND_OCI).await?); + summaries.sort_by(|a, b| a.package.name_key.cmp(&b.package.name_key)); + let mut rows = Vec::new(); + for summary in summaries { + if summary.version_count == 0 { + continue; + } + let readable = package_ops::may_read(state, viewer, owner, &summary.package) + .await + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?; + if !readable { + continue; + } + rows.push(PackageRow { + href: package_href(&owner.username, &summary.package.name), + name: summary.package.name, + latest: summary.latest_version.unwrap_or_default(), + versions: summary.version_count, + description: summary.latest_description.unwrap_or_default(), + private: summary.package.private, + container: summary.package.kind == KIND_OCI, + }); + } + Ok(rows) +} + +/// Query of the package page: `readme` (the default) or `versions`. +#[topcoat::router::query_params(error = bad_request)] +struct PackageQuery { + tab: Option, +} + +/// The package page: the head with the install snippet, then one tab of README or versions. +#[page("/{owner}/-/packages/{*pkg}")] +async fn package_page(cx: &Cx) -> Result { + let owner_name = path_param::(cx); + let pkg_name = path_param::(cx).collect::>().join("/"); + let pkg_name = pkg_name.as_str(); + let state = app_context::(cx); + let viewer = current_user(cx).await?; + let query = query_params::(cx)?; + let actor = viewer.as_ref().map(|(u, _)| u); + let lang = i18n::lang(cx, actor); + + let Some(owner) = state.store.user_by_username(owner_name).await? else { + return Err(not_found().into()); + }; + let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await { + Ok(package) => package, + Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await { + Ok(package) => package, + Err(_) => return Err(not_found().into()), + }, + }; + let csrf = viewer + .as_ref() + .map(|(_, s)| s.csrf_token.clone()) + .unwrap_or_default(); + let oci = if package.kind == KIND_OCI { + Some(packages_oci::model(state, actor, csrf, &owner, package.clone(), lang).await?) + } else { + None + }; + let versions = state.store.package_versions(&package.id).await?; + let latest = versions.iter().find(|v| !v.yanked).or(versions.first()); + let readme_html = latest + .and_then(|v| v.readme.as_deref()) + .filter(|text| !text.trim().is_empty()) + .map(|text| render_markdown(text, None)) + .unwrap_or_default(); + let description = latest + .and_then(|v| v.description.clone()) + .unwrap_or_default(); + // The linked repo is named only when it is public, so a private repo name never shows here. + let repo_link = match package.repo_id.as_deref() { + Some(id) => match state.store.repo_by_id(id).await? { + Some(repo) if repo.visibility == forge_core::Visibility::Public => { + match state.store.user_by_id(&repo.owner_id).await? { + Some(repo_owner) => Some(( + format!("/{}/{}", enc(&repo_owner.username), enc(&repo.name)), + format!("{}/{}", repo_owner.username, repo.name), + )), + None => None, + } + } + _ => None, + }, + None => None, + }; + let base = state.config.base_url.trim_end_matches('/').to_owned(); + let registry = format!("sparse+{base}/api/packages/{}/cargo/", owner.username); + let config_block = format!("[registries.{}]\nindex = \"{registry}\"", owner.username); + let add_cmd = format!("cargo add --registry {} {}", owner.username, package.name); + let publish_cmd = format!("cargo publish --registry {}", owner.username); + let login_cmd = format!("cargo login --registry {}", owner.username); + let versions_tab = query.tab.as_deref() == Some("versions"); + let version_rows: Vec<(String, String, bool, String)> = versions + .iter() + .map(|v| { + ( + v.version.clone(), + v.created_at.get(..10).unwrap_or(&v.created_at).to_owned(), + v.yanked, + v.checksum.clone(), + ) + }) + .collect(); + let readme_href = format!( + "{}?tab=readme", + package_href(&owner.username, &package.name) + ); + let versions_href = format!( + "{}?tab=versions", + package_href(&owner.username, &package.name) + ); + let events = events_href(&owner.username); + let latest_text = latest.map(|v| v.version.clone()).unwrap_or_default(); + let title = match &oci { + Some(page) => format!("{} {}", page.package.name, page.newest_tag), + None => format!("{} {}", package.name, latest_text), + }; + let view_model = PackagePage { + owner_name: owner.username.clone(), + package, + latest_text, + description, + repo_link, + readme_html, + versions_tab, + readme_href, + versions_href, + events, + config_block, + add_cmd, + publish_cmd, + login_cmd, + version_rows, + lang, + }; + Ok(view! { cx => + shell(title: title.as_str(), viewer: viewer.as_ref(), + if let Some(page) = oci { + oci_package_view(page: page) + } else { + package_view(page: view_model) + }) + }) +} + +/// The form of a tag delete: the csrf token, the package name and the tag. +#[derive(Deserialize)] +struct TagDeleteForm { + #[serde(default)] + csrf: String, + #[serde(default)] + package: String, + #[serde(default)] + tag: String, +} + +/// Deletes one tag of a container image and returns to the package page. Only the registry's +/// owner, an org owner, or the instance admin may do it. The page sends it from a confirm popover. +#[route(POST "/{owner}/-/packages/tags/delete")] +async fn tag_delete(cx: &Cx, Form(form): Form) -> Result { + let (viewer, _) = require_csrf(cx, &form.csrf).await?; + let owner_name = path_param::(cx); + let state = app_context::(cx); + let Some(owner) = state.store.user_by_username(owner_name).await? else { + return Err(not_found().into()); + }; + let allowed = package_ops::may_publish(state, &viewer, &owner) + .await + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?; + if !allowed { + return Err(forbidden().into()); + } + let Some(package) = state + .store + .package_by_name(&owner.id, KIND_OCI, &form.package) + .await? + else { + return Err(not_found().into()); + }; + manifests::remove_tag(state, &owner, &package, &form.tag).await?; + Ok(see_other(package_href(&owner.username, &package.name))) +} + +/// What the package page shows, prepared by the handler. +struct PackagePage { + owner_name: String, + package: Package, + latest_text: String, + description: String, + repo_link: Option<(String, String)>, + readme_html: String, + versions_tab: bool, + readme_href: String, + versions_href: String, + events: String, + config_block: String, + add_cmd: String, + publish_cmd: String, + login_cmd: String, + version_rows: Vec<(String, String, bool, String)>, + lang: Lang, +} + +/// The package page body. +#[component] +async fn package_view(page: PackagePage) -> Result { + let lang = page.lang; + let PackagePage { + owner_name, + package, + latest_text, + description, + repo_link, + readme_html, + versions_tab, + readme_href, + versions_href, + events, + config_block, + add_cmd, + publish_cmd, + login_cmd, + version_rows, + .. + } = page; + let has_readme = !readme_html.is_empty(); + let has_repo = repo_link.is_some(); + let (repo_href, repo_text) = repo_link.unwrap_or_default(); + let private = package.private; + let readme_on = !versions_tab; + let readme_class = if readme_on { "tab active" } else { "tab" }; + let versions_class = if versions_tab { "tab active" } else { "tab" }; + let has_versions = !version_rows.is_empty(); + let install = pk::t(lang, K::Install); + let copy_label = pk::t(lang, K::CopyCommand); + let readme_label = pk::t(lang, K::Readme); + let versions_label = pk::t(lang, K::PackageVersions); + let no_readme = pk::t(lang, K::NoReadme); + Ok(view! { +
+
+
+

(owner_name.as_str()) " / " (pk::t(lang, K::TabPackages))

+

(package.name.as_str()) " " (latest_text.as_str())

+ if !description.is_empty() { +

(description.as_str())

+ } + if private { + (pk::t(lang, K::PackagePrivate)) + } + if has_repo { +

(pk::t(lang, K::PackageRepoLink)) ": " (repo_text.as_str())

+ } +
+
+
+

(install)

+

(pk::t(lang, K::InstallHelp))

+

(pk::t(lang, K::InstallRegistryConfig))

+
+ (config_block.as_str()) + +
+

(pk::t(lang, K::InstallAdd))

+
+ (add_cmd.as_str()) + +
+

(pk::t(lang, K::InstallPublish))

+
+ (publish_cmd.as_str()) + +
+

(pk::t(lang, K::InstallLogin))

+
+ (login_cmd.as_str()) + +
+
+ + if versions_tab { + if has_versions { +
    + for (version, date, yanked, checksum) in version_rows.iter() { +
  • + (version.as_str()) + " " + (date.as_str()) + if *yanked { + " " + (pk::t(lang, K::VersionYanked)) + } +
    + (checksum.as_str()) +
  • + } +
+ } + } else { + if has_readme { +
(Unescaped::new_unchecked(readme_html))
+ } else { +

(no_readme)

+ } + } +
+ }) +} + +/// The owner's `changed` stream. A publish or a yank sends one `changed` event; nothing is sent +/// on connect, since the page was just rendered. +#[route(GET "/{owner}/-/packages/events")] +async fn packages_events(cx: &Cx) -> Result { + let owner_name = path_param::(cx); + let state = app_context::(cx); + let Some(owner) = state.store.user_by_username(owner_name).await? else { + return Err(not_found().into()); + }; + // Subscribed before the response is sent, so a change after this point is sent. + let wake = state.packages_live.subscribe(&owner.id); + events_response(cx, owner_changes(wake)) +} + +fn owner_changes(wake: watch::Receiver) -> impl Stream> + Send + 'static { + stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some((changed_event("list".to_owned()), wake)) + }) +} + +/// A package linked to a repo, as the repo's sidebar lists it. +pub struct PackageLink { + pub name: String, + pub href: String, + pub latest: String, +} + +/// The packages linked to `repo_id` that the viewer may see, with their newest version. A +/// package without versions is not listed. +pub async fn repo_package_links( + state: &AppState, + viewer: Option<&User>, + repo_id: &str, +) -> forge_core::Result> { + let mut links = Vec::new(); + for package in state.store.packages_for_repo(repo_id).await? { + let Some(owner) = state.store.user_by_id(&package.owner_id).await? else { + continue; + }; + let readable = match package_ops::may_read(state, viewer, &owner, &package).await { + Ok(readable) => readable, + Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg)), + Err(_) => false, + }; + if !readable { + continue; + } + let versions = state.store.package_versions(&package.id).await?; + let Some(latest) = versions.iter().find(|v| !v.yanked).or(versions.first()) else { + continue; + }; + links.push(PackageLink { + href: package_href(&owner.username, &package.name), + name: package.name, + latest: latest.version.clone(), + }); + } + Ok(links) +} + +/// The Packages card of a repo's sidebar: the packages linked to this repo. +#[component] +pub async fn repo_packages_card(links: Vec, lang: Lang) -> Result { + let heading = pk::t(lang, K::TabPackages); + Ok(view! { +
+

(heading)

+ +
+ }) +} diff --git a/crates/forge-web/src/pages/packages_oci.rs b/crates/forge-web/src/pages/packages_oci.rs new file mode 100644 index 0000000..8c07536 --- /dev/null +++ b/crates/forge-web/src/pages/packages_oci.rs @@ -0,0 +1,195 @@ +//! The package page of a container image: its pull command, its tags with digest, size and date, +//! and the owner's delete control for a tag. The page is the cargo package page's sibling; the +//! route and the shell are shared in [`super::packages`]. + +use forge_core::User; +use forge_core::packages::{OciTag, Package}; +use topcoat::Result; +use topcoat::view::{View, component, view}; + +use crate::i18n::Lang; +use crate::i18n::packages::{self as pk, K}; +use crate::package_ops; +use crate::state::AppState; +use crate::views::{enc, human_size}; + +/// What the container package page shows, prepared by the handler. +pub struct OciPage { + pub owner_name: String, + pub package: Package, + pub newest_tag: String, + pub host: String, + pub tags: Vec, + pub can_delete: bool, + pub csrf: String, + pub events: String, + pub lang: Lang, +} + +/// Builds the container page of `package` for `viewer`. The owner may delete tags. +pub async fn model( + state: &AppState, + viewer: Option<&User>, + csrf: String, + owner: &User, + package: Package, + lang: Lang, +) -> forge_core::Result { + let tags = state.store.oci_tags(&package.id).await?; + let can_delete = match viewer { + Some(user) => package_ops::may_publish(state, user, owner) + .await + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?, + None => false, + }; + let base = state.config.base_url.trim_end_matches('/'); + let host = base + .split_once("://") + .map_or(base, |(_, rest)| rest) + .to_owned(); + let newest_tag = tags.first().map(|t| t.tag.clone()).unwrap_or_default(); + Ok(OciPage { + owner_name: owner.username.clone(), + package, + newest_tag, + host, + tags, + can_delete, + csrf, + events: crate::pages::packages::events_href(&owner.username), + lang, + }) +} + +/// The shortened form of a digest for a table cell: the algorithm and the first twelve hex digits. +fn short_digest(digest: &str) -> String { + match digest.split_once(':') { + Some((alg, hex)) => format!("{alg}:{}", hex.get(..12).unwrap_or(hex)), + None => digest.to_owned(), + } +} + +/// The container package page body. +#[component] +pub async fn oci_package_view(page: OciPage) -> Result { + let lang = page.lang; + let OciPage { + owner_name, + package, + newest_tag, + host, + tags, + can_delete, + csrf, + events, + .. + } = page; + let image = format!("{host}/{owner_name}/{}", package.name); + let has_tags = !tags.is_empty(); + let pull = if newest_tag.is_empty() { + format!("docker pull {image}") + } else { + format!("docker pull {image}:{newest_tag}") + }; + let login = format!("docker login {host}"); + let push = format!("docker push {image}:"); + let copy_label = pk::t(lang, K::CopyCommand); + let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name)); + let private = package.private; + let tag_count = tags.len().to_string(); + let rows: Vec<(String, String, String, String, String)> = tags + .iter() + .map(|t| { + ( + t.tag.clone(), + short_digest(&t.digest), + t.digest.clone(), + human_size(lang, t.size), + t.created_at.get(..10).unwrap_or(&t.created_at).to_owned(), + ) + }) + .collect(); + Ok(view! { +
+
+
+

(owner_name.as_str()) " / " (pk::t(lang, K::ContainerKind))

+

(package.name.as_str()) " " (newest_tag.as_str())

+ if private { + (pk::t(lang, K::PackagePrivate)) + } +
+
+
+

(pk::t(lang, K::Install))

+

(pk::t(lang, K::ContainerInstallHelp))

+

(pk::t(lang, K::ContainerLogin))

+
+ (login.as_str()) + +
+ if has_tags { +

(pk::t(lang, K::ContainerPull))

+
+ (pull.as_str()) + +
+ } +

(pk::t(lang, K::ContainerPush))

+
+ (push.as_str()) + +
+
+
+

(pk::t(lang, K::ContainerTags)) " " (tag_count.as_str())

+ if has_tags { +
+ + + + + + + + if can_delete { + + } + + + + for (tag, short, full, size, created) in rows.iter() { + + + + + + if can_delete { + + } + + } + +
(pk::t(lang, K::ContainerTag))(pk::t(lang, K::ContainerDigest))(pk::t(lang, K::ContainerSize))(pk::t(lang, K::ContainerCreated))
(tag.as_str())(short.as_str())(size.as_str())(created.as_str()) +
+ (pk::t(lang, K::DeleteTag)) +
+

(pk::t(lang, K::DeleteTagMessage))

+
+ + + + + +
+
+
+
+
+ } else { +

(pk::t(lang, K::NoTags))

+ } +
+
+ }) +} diff --git a/crates/forge-web/src/pages/profile.rs b/crates/forge-web/src/pages/profile.rs index 1bcaa36..f06b6fc 100644 --- a/crates/forge-web/src/pages/profile.rs +++ b/crates/forge-web/src/pages/profile.rs @@ -22,9 +22,11 @@ use topcoat::view::{Unescaped, View, component, view}; use crate::auth::current_user; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as g, K}; +use crate::i18n::packages::{self as pk, K as PK}; use crate::i18n::{self, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::dashboard::badge_class; +use crate::pages::packages::{self as packages, PackageRow}; use crate::render::markdown::render_markdown; use crate::state::AppState; use crate::views::repo_list::{ @@ -217,13 +219,18 @@ async fn profile_page(cx: &Cx) -> Result { None }; + // The Packages tab lists the registry's packages the viewer may see. + let package_rows = packages::package_rows(state, actor, &user).await?; + let packages_on = tab == "packages"; + let title = user.username.clone(); Ok(view! { cx => shell(title: title.as_str(), viewer: viewer.as_ref(), profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time, org: org, lang: lang, tab: tab.to_owned(), q: q, sort: sort, repo_total: repo_total, star_total: star_total, cards: cards, from_pins: from_pins, - pins_edit_href: pins_edit_href, edit_profile: edit_profile, listing: listing)) + pins_edit_href: pins_edit_href, edit_profile: edit_profile, listing: listing, + packages_on: packages_on, package_rows: package_rows)) }) } @@ -323,6 +330,7 @@ fn tab_key(raw: Option<&str>) -> &'static str { match raw { Some("repositories") => "repositories", Some("stars") => "stars", + Some("packages") => "packages", _ => "overview", } } @@ -410,7 +418,13 @@ async fn profile_card( pins_edit_href: Option, edit_profile: bool, listing: Listing, + packages_on: bool, + package_rows: Vec, ) -> Result { + let package_count_text = package_rows.len().to_string(); + let packages_href = profile_href(&user.username, "packages", "", SORTS[0].0, 1); + let packages_events = packages::events_href(&user.username); + let has_packages = !package_rows.is_empty(); let src = avatar_url(&user.username, avatar.as_deref()); let has_about = !about_html.is_empty(); let is_org = user.is_org(); @@ -477,6 +491,9 @@ async fn profile_card( (g::t(lang, K::TabStars)) " " (star_count_text.as_str()) + + (pk::t(lang, PK::TabPackages)) " " (package_count_text.as_str()) + if overview_on {
@@ -542,6 +559,40 @@ async fn profile_card( pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang)
} + if packages_on { +
+
+

(pk::t(lang, PK::PackagesHeading))

+
+

(pk::t(lang, PK::PackagesHelp))

+ if has_packages { +
    + for row in package_rows.into_iter() { +
  • + (row.name.as_str()) + " " + if row.container { + (pk::t(lang, PK::ContainerKind)) + " " + } + (row.latest.as_str()) + " " + (row.versions.to_string()) " " (pk::t(lang, match (row.container, row.versions == 1) { (true, true) => PK::PackageTagCountOne, (true, false) => PK::PackageTagCount, (false, true) => PK::PackageVersionCountOne, (false, false) => PK::PackageVersionCount })) + if row.private { + " " + (pk::t(lang, PK::PackagePrivate)) + } + if !row.description.is_empty() { +

    (row.description.as_str())

    + } +
  • + } +
+ } else { +

(pk::t(lang, PK::NoPackages))

+ } +
+ } }) } diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index 02c3786..7c51cb2 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -25,6 +25,7 @@ use crate::pages::dashboard::badge_class; use crate::pages::finder::file_finder; use crate::pages::issue_parts::stamp_unix; use crate::pages::notifications::watch_form; +use crate::pages::packages::{self, repo_packages_card}; use crate::pages::refs::load_refs; use crate::pages::releases::latest_card; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; @@ -468,6 +469,8 @@ async fn repo_page(cx: &Cx) -> Result { header.live = live; let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; + let viewer_user = ctx.viewer.as_ref().map(|(user, _)| user); + let packages = packages::repo_package_links(state, viewer_user, &repo.id).await?; let now = now_unix(); Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), @@ -496,6 +499,9 @@ async fn repo_page(cx: &Cx) -> Result { }