An OCI container registry per user and org
Browse files at this commit136f946e656ed0bdf96f38a39bf762f3c1bbdcb9Parent: 05cd9ba- feat
- an OCI container registry per user and org
43 changed files +6509 -15
- Cargo.lock +2 -0
- crates/forge-core/Cargo.toml +2 -0
- crates/forge-core/migrations/0061_packages.sql +35 -0
- crates/forge-core/migrations/0062_oci.sql +47 -0
- crates/forge-core/migrations/0061_web_push.sql → crates/forge-core/migrations/0063_web_push.sql +0 -0
- crates/forge-core/migrations/0061_merge_queue.sql → crates/forge-core/migrations/0064_merge_queue.sql +0 -0
- crates/forge-core/src/cargo.rs +310 -0
- crates/forge-core/src/lib.rs +3 -0
- crates/forge-core/src/names.rs +1 -0
- crates/forge-core/src/oci.rs +296 -0
- crates/forge-core/src/packages.rs +89 -0
- crates/forge-core/src/store/migrate.rs +4 -2
- crates/forge-core/src/store/mod.rs +2 -0
- crates/forge-core/src/store/oci.rs +332 -0
- crates/forge-core/src/store/packages.rs +332 -0
- crates/forge-core/src/store/web_push.rs +1 -1
- crates/forge-web/src/api/mod.rs +24 -10
- crates/forge-web/src/api/packages.rs +367 -0
- crates/forge-web/src/blobs.rs +9 -0
- crates/forge-web/src/boot.rs +1 -0
- crates/forge-web/src/i18n/mod.rs +1 -0
- crates/forge-web/src/i18n/packages.rs +141 -0
- crates/forge-web/src/main.rs +3 -0
- crates/forge-web/src/oci/auth.rs +217 -0
- crates/forge-web/src/oci/blobs.rs +458 -0
- crates/forge-web/src/oci/gc.rs +38 -0
- crates/forge-web/src/oci/manifests.rs +365 -0
- crates/forge-web/src/oci/mod.rs +467 -0
- crates/forge-web/src/package_ops.rs +323 -0
- crates/forge-web/src/packages_live.rs +80 -0
- crates/forge-web/src/pages/mod.rs +2 -0
- crates/forge-web/src/pages/packages.rs +460 -0
- crates/forge-web/src/pages/packages_oci.rs +195 -0
- crates/forge-web/src/pages/profile.rs +52 -1
- crates/forge-web/src/pages/repo.rs +6 -0
- crates/forge-web/src/pages/settings_security.rs +1 -0
- crates/forge-web/src/pages/settings_tokens.rs +14 -1
- crates/forge-web/src/state.rs +1 -0
- crates/forge-web/src/test_support.rs +1 -0
- crates/forge-web/tests/oci_e2e.rs +972 -0
- crates/forge-web/tests/packages_e2e.rs +604 -0
- docs/packages.md +217 -0
- style/main.scss +34 -0
Cargo.lockmodified+2 -0
| @@ -2136,6 +2136,7 @@ dependencies = [ | |||
| 2136 | "argon2", | 2136 | "argon2", |
| 2137 | "base64 0.23.1", | 2137 | "base64 0.23.1", |
| 2138 | "chacha20poly1305", | 2138 | "chacha20poly1305", |
| 2139 | + "flate2", | ||
| 2139 | "forge-ci", | 2140 | "forge-ci", |
| 2140 | "hex", | 2141 | "hex", |
| 2141 | "hmac 0.13.0", | 2142 | "hmac 0.13.0", |
| @@ -2149,6 +2150,7 @@ dependencies = [ | |||
| 2149 | "sha1 0.11.0", | 2150 | "sha1 0.11.0", |
| 2150 | "sha2 0.11.1", | 2151 | "sha2 0.11.1", |
| 2151 | "subtle", | 2152 | "subtle", |
| 2153 | + "tar", | ||
| 2152 | "tempfile", | 2154 | "tempfile", |
| 2153 | "thiserror 2.0.21", | 2155 | "thiserror 2.0.21", |
| 2154 | "time", | 2156 | "time", |
crates/forge-core/Cargo.tomlmodified+2 -0
| @@ -32,6 +32,8 @@ tracing.workspace = true | |||
| 32 | serde_json.workspace = true | 32 | serde_json.workspace = true |
| 33 | semver = { workspace = true } | 33 | semver = { workspace = true } |
| 34 | zip = { workspace = true } | 34 | zip = { workspace = true } |
| 35 | +flate2.workspace = true | ||
| 36 | +tar.workspace = true | ||
| 35 | 37 | ||
| 36 | [dev-dependencies] | 38 | [dev-dependencies] |
| 37 | tempfile.workspace = true | 39 | tempfile.workspace = true |
crates/forge-core/migrations/0061_packages.sqladded+35 -0
| @@ -0,0 +1,35 @@ | |||
| 1 | +-- Package registries: the packages an owner (user or org) publishes, and their versions. `kind` | ||
| 2 | +-- names the registry format ('cargo' now; a container registry would add 'oci' rows beside them). | ||
| 3 | +-- `name_key` is the lowercase name that the index and the URLs use; `name` keeps the spelling of | ||
| 4 | +-- the first publish. The .crate bytes live in blob storage under `packages/<version id>`; a | ||
| 5 | +-- version row keeps the checksum, the index line and the README text. `repo_id` links a package | ||
| 6 | +-- to a repo on this forge, found from the crate's `repository` field. | ||
| 7 | + | ||
| 8 | +CREATE TABLE packages ( | ||
| 9 | + id TEXT PRIMARY KEY, | ||
| 10 | + owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, | ||
| 11 | + kind TEXT NOT NULL, | ||
| 12 | + name TEXT NOT NULL, | ||
| 13 | + name_key TEXT NOT NULL, | ||
| 14 | + repo_id TEXT REFERENCES repos(id) ON DELETE SET NULL, | ||
| 15 | + private INTEGER NOT NULL DEFAULT 0, | ||
| 16 | + created_at TEXT NOT NULL, | ||
| 17 | + updated_at TEXT NOT NULL, | ||
| 18 | + UNIQUE (owner_id, kind, name_key) | ||
| 19 | +); | ||
| 20 | +CREATE INDEX packages_repo ON packages(repo_id); | ||
| 21 | + | ||
| 22 | +CREATE TABLE package_versions ( | ||
| 23 | + id TEXT PRIMARY KEY, | ||
| 24 | + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, | ||
| 25 | + version TEXT NOT NULL, | ||
| 26 | + yanked INTEGER NOT NULL DEFAULT 0, | ||
| 27 | + checksum TEXT NOT NULL, | ||
| 28 | + size INTEGER NOT NULL, | ||
| 29 | + index_json TEXT NOT NULL, | ||
| 30 | + description TEXT, | ||
| 31 | + readme TEXT, | ||
| 32 | + publisher_id TEXT NOT NULL REFERENCES users(id), | ||
| 33 | + created_at TEXT NOT NULL, | ||
| 34 | + UNIQUE (package_id, version) | ||
| 35 | +); | ||
crates/forge-core/migrations/0062_oci.sqladded+47 -0
| @@ -0,0 +1,47 @@ | |||
| 1 | +-- Container registry (OCI Distribution). An image is a package of kind 'oci' whose name_key is | ||
| 2 | +-- the repository path below the owner (`app` for `tahinli/app`, `a/b` for `tahinli/a/b`). | ||
| 3 | +-- Blob bytes live in blob storage under `oci/<hex>`, shared by digest; the rows here say which | ||
| 4 | +-- package may use which digest. Manifests keep their exact bytes, so the digest stays valid. | ||
| 5 | + | ||
| 6 | +-- The blobs a package may read (layers, configs and uploads it has linked). Child manifests of an | ||
| 7 | +-- index are not blobs; they live in oci_manifests. `created_at` is when the package linked it. | ||
| 8 | +CREATE TABLE oci_blobs ( | ||
| 9 | + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, | ||
| 10 | + digest TEXT NOT NULL, | ||
| 11 | + size INTEGER NOT NULL, | ||
| 12 | + created_at TEXT NOT NULL, | ||
| 13 | + PRIMARY KEY (package_id, digest) | ||
| 14 | +); | ||
| 15 | +CREATE INDEX oci_blobs_digest ON oci_blobs(digest); | ||
| 16 | + | ||
| 17 | +-- Manifests by digest. `content` is the manifest JSON as pushed. `size` is the total of the | ||
| 18 | +-- image's config and layers (the manifest's own length for an index). | ||
| 19 | +CREATE TABLE oci_manifests ( | ||
| 20 | + id TEXT PRIMARY KEY, | ||
| 21 | + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, | ||
| 22 | + digest TEXT NOT NULL, | ||
| 23 | + media_type TEXT NOT NULL, | ||
| 24 | + content TEXT NOT NULL, | ||
| 25 | + size INTEGER NOT NULL, | ||
| 26 | + created_at TEXT NOT NULL, | ||
| 27 | + UNIQUE (package_id, digest) | ||
| 28 | +); | ||
| 29 | + | ||
| 30 | +-- Tags point at one manifest of their package. | ||
| 31 | +CREATE TABLE oci_tags ( | ||
| 32 | + package_id TEXT NOT NULL REFERENCES packages(id) ON DELETE CASCADE, | ||
| 33 | + tag TEXT NOT NULL, | ||
| 34 | + manifest_id TEXT NOT NULL REFERENCES oci_manifests(id) ON DELETE CASCADE, | ||
| 35 | + updated_at TEXT NOT NULL, | ||
| 36 | + PRIMARY KEY (package_id, tag) | ||
| 37 | +); | ||
| 38 | +CREATE INDEX oci_tags_manifest ON oci_tags(manifest_id); | ||
| 39 | + | ||
| 40 | +-- What each manifest refers to: config and layer digests (blobs), or child manifest digests of an | ||
| 41 | +-- index. The mark step of garbage collection reads these rows. | ||
| 42 | +CREATE TABLE oci_manifest_refs ( | ||
| 43 | + manifest_id TEXT NOT NULL REFERENCES oci_manifests(id) ON DELETE CASCADE, | ||
| 44 | + digest TEXT NOT NULL, | ||
| 45 | + PRIMARY KEY (manifest_id, digest) | ||
| 46 | +); | ||
| 47 | +CREATE INDEX oci_manifest_refs_digest ON oci_manifest_refs(digest); | ||
crates/forge-core/migrations/0061_web_push.sql → crates/forge-core/migrations/0063_web_push.sqlrenamed+0 -0
crates/forge-core/migrations/0061_merge_queue.sql → crates/forge-core/migrations/0064_merge_queue.sqlrenamed+0 -0
crates/forge-core/src/cargo.rsadded+310 -0
| @@ -0,0 +1,310 @@ | |||
| 1 | +//! Cargo registry rules, pure and without IO: crate and version names, the publish body, the | ||
| 2 | +//! index line written for each version, the index file path of a crate, and the README and | ||
| 3 | +//! repository link found in a `.crate` file. The wire formats follow the Cargo book's registry | ||
| 4 | +//! chapters: the publish body, the index format (version 2) and the sparse index layout. | ||
| 5 | + | ||
| 6 | +use std::io::Read; | ||
| 7 | + | ||
| 8 | +use flate2::read::GzDecoder; | ||
| 9 | +use serde_json::{Map, Value, json}; | ||
| 10 | + | ||
| 11 | +use crate::error::{Error, Result}; | ||
| 12 | + | ||
| 13 | +/// Longest crate name, in characters. | ||
| 14 | +pub const MAX_NAME_CHARS: usize = 64; | ||
| 15 | +/// Largest README read out of a `.crate` file, in bytes. | ||
| 16 | +pub const MAX_README_BYTES: u64 = 256 * 1024; | ||
| 17 | + | ||
| 18 | +/// Checks a crate name and returns its lowercase key. The key names the index file, so it is | ||
| 19 | +/// what routes and storage use; the name as published is kept for display and the index. | ||
| 20 | +pub fn crate_name_key(name: &str) -> Result<String> { | ||
| 21 | + let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()); | ||
| 22 | + let chars_ok = name | ||
| 23 | + .chars() | ||
| 24 | + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); | ||
| 25 | + if !starts_alpha || !chars_ok || name.len() > MAX_NAME_CHARS { | ||
| 26 | + return Err(Error::InvalidName(format!( | ||
| 27 | + "`{name}` is not a valid crate name: start with a letter, then letters, digits, `-` or `_`, at most {MAX_NAME_CHARS} characters" | ||
| 28 | + ))); | ||
| 29 | + } | ||
| 30 | + Ok(name.to_ascii_lowercase()) | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/// The sparse index path of a crate key, relative to the index URL (`1/a`, `2/ab`, `3/a/abc`, | ||
| 34 | +/// `ab/cd/abcdef`). The key is ASCII, checked by [`crate_name_key`]. | ||
| 35 | +pub fn index_path(key: &str) -> String { | ||
| 36 | + match key.len() { | ||
| 37 | + 1 => format!("1/{key}"), | ||
| 38 | + 2 => format!("2/{key}"), | ||
| 39 | + 3 => format!("3/{}/{key}", &key[..1]), | ||
| 40 | + _ => format!("{}/{}/{key}", &key[..2], &key[2..4]), | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Parses a version as semver. Cargo versions are semver, with build metadata kept as written. | ||
| 45 | +pub fn parse_version(version: &str) -> Result<semver::Version> { | ||
| 46 | + semver::Version::parse(version) | ||
| 47 | + .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}"))) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// A publish body split into its parts. The metadata is the JSON document, the crate the | ||
| 51 | +/// gzipped tarball whose sha256 the index records. | ||
| 52 | +pub struct Publish<'a> { | ||
| 53 | + pub metadata: Value, | ||
| 54 | + pub crate_file: &'a [u8], | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// Splits a publish body: a little-endian u32 length and the JSON metadata, then a little-endian | ||
| 58 | +/// u32 length and the `.crate` bytes. Both lengths must match the body exactly. | ||
| 59 | +pub fn parse_publish(body: &[u8]) -> Result<Publish<'_>> { | ||
| 60 | + let (json_len, rest) = take_len(body)?; | ||
| 61 | + if json_len > rest.len() { | ||
| 62 | + return Err(Error::Invalid( | ||
| 63 | + "publish body is shorter than its metadata length".into(), | ||
| 64 | + )); | ||
| 65 | + } | ||
| 66 | + let (json_bytes, rest) = rest.split_at(json_len); | ||
| 67 | + let metadata: Value = serde_json::from_slice(json_bytes) | ||
| 68 | + .map_err(|e| Error::Invalid(format!("publish metadata is not JSON: {e}")))?; | ||
| 69 | + if !metadata.is_object() { | ||
| 70 | + return Err(Error::Invalid( | ||
| 71 | + "publish metadata must be a JSON object".into(), | ||
| 72 | + )); | ||
| 73 | + } | ||
| 74 | + let (crate_len, rest) = take_len(rest)?; | ||
| 75 | + if crate_len != rest.len() { | ||
| 76 | + return Err(Error::Invalid( | ||
| 77 | + "crate length does not match the body".into(), | ||
| 78 | + )); | ||
| 79 | + } | ||
| 80 | + Ok(Publish { | ||
| 81 | + metadata, | ||
| 82 | + crate_file: rest, | ||
| 83 | + }) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> { | ||
| 87 | + let Some((head, rest)) = bytes.split_first_chunk::<4>().map(|(h, r)| (*h, r)) else { | ||
| 88 | + return Err(Error::Invalid("publish body is truncated".into())); | ||
| 89 | + }; | ||
| 90 | + let len = usize::try_from(u32::from_le_bytes(head)) | ||
| 91 | + .map_err(|_| Error::Invalid("length does not fit".into()))?; | ||
| 92 | + Ok((len, rest)) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Text field of the metadata, or `None` when absent or not a string. | ||
| 96 | +pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> { | ||
| 97 | + meta.get(key).and_then(Value::as_str) | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// The dependencies of an index line, from the publish metadata. A renamed dependency | ||
| 101 | +/// (`explicit_name_in_toml`) is listed under its local name, with the real crate in `package`. | ||
| 102 | +pub fn index_deps(meta: &Value) -> Vec<Value> { | ||
| 103 | + let deps = meta.get("deps").and_then(Value::as_array); | ||
| 104 | + deps.map_or_else(Vec::new, |list| { | ||
| 105 | + list.iter() | ||
| 106 | + .map(|dep| { | ||
| 107 | + let crate_name = meta_str(dep, "name").unwrap_or_default(); | ||
| 108 | + let renamed = meta_str(dep, "explicit_name_in_toml"); | ||
| 109 | + json!({ | ||
| 110 | + "name": renamed.unwrap_or(crate_name), | ||
| 111 | + "req": dep.get("version_req").cloned().unwrap_or(Value::Null), | ||
| 112 | + "features": dep.get("features").cloned().unwrap_or_else(|| json!([])), | ||
| 113 | + "optional": dep.get("optional").and_then(Value::as_bool).unwrap_or(false), | ||
| 114 | + "default_features": dep.get("default_features").and_then(Value::as_bool).unwrap_or(true), | ||
| 115 | + "target": dep.get("target").cloned().unwrap_or(Value::Null), | ||
| 116 | + "kind": dep.get("kind").and_then(Value::as_str).unwrap_or("normal"), | ||
| 117 | + "registry": dep.get("registry").cloned().unwrap_or(Value::Null), | ||
| 118 | + "package": renamed.map(|_| crate_name), | ||
| 119 | + }) | ||
| 120 | + }) | ||
| 121 | + .collect() | ||
| 122 | + }) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// The index line of one version (format version 2). Features that use the `dep:` or `?` | ||
| 126 | +/// syntax go to `features2`, as the format requires; the rest stay in `features`. | ||
| 127 | +pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> { | ||
| 128 | + let name = | ||
| 129 | + meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?; | ||
| 130 | + let vers = | ||
| 131 | + meta_str(meta, "vers").ok_or_else(|| Error::Invalid("metadata has no vers".into()))?; | ||
| 132 | + let mut features = Map::new(); | ||
| 133 | + let mut features2 = Map::new(); | ||
| 134 | + if let Some(declared) = meta.get("features").and_then(Value::as_object) { | ||
| 135 | + for (feature, members) in declared { | ||
| 136 | + let modern = members.as_array().is_some_and(|list| { | ||
| 137 | + list.iter() | ||
| 138 | + .filter_map(Value::as_str) | ||
| 139 | + .any(|m| m.starts_with("dep:") || m.contains('?')) | ||
| 140 | + }); | ||
| 141 | + if modern { | ||
| 142 | + features2.insert(feature.clone(), members.clone()); | ||
| 143 | + } else { | ||
| 144 | + features.insert(feature.clone(), members.clone()); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + let mut line = json!({ | ||
| 149 | + "name": name, | ||
| 150 | + "vers": vers, | ||
| 151 | + "deps": index_deps(meta), | ||
| 152 | + "cksum": checksum, | ||
| 153 | + "features": features, | ||
| 154 | + "yanked": false, | ||
| 155 | + "links": meta.get("links").cloned().unwrap_or(Value::Null), | ||
| 156 | + "v": 2, | ||
| 157 | + }); | ||
| 158 | + if !features2.is_empty() { | ||
| 159 | + line["features2"] = Value::Object(features2); | ||
| 160 | + } | ||
| 161 | + if let Some(rust_version) = meta_str(meta, "rust_version") { | ||
| 162 | + line["rust_version"] = json!(rust_version); | ||
| 163 | + } | ||
| 164 | + Ok(line) | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +/// The `(owner, repo)` a `repository` URL names on this forge, when it points at a repo under | ||
| 168 | +/// `base_url` (for example `https://git.tahinli.com/`). Any other URL links nothing. | ||
| 169 | +pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> { | ||
| 170 | + let base = base_url.trim_end_matches('/'); | ||
| 171 | + let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?; | ||
| 172 | + let rest = rest.trim_end_matches('/'); | ||
| 173 | + let rest = rest.strip_suffix(".git").unwrap_or(rest); | ||
| 174 | + let mut parts = rest.split('/'); | ||
| 175 | + let owner = parts.next().filter(|s| !s.is_empty())?; | ||
| 176 | + let repo = parts.next().filter(|s| !s.is_empty())?; | ||
| 177 | + if parts.next().is_some() { | ||
| 178 | + return None; | ||
| 179 | + } | ||
| 180 | + Some((owner.to_owned(), repo.to_owned())) | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// The README of a `.crate` file: the first `README*` file at the top of the package directory | ||
| 184 | +/// (`<name>-<version>/README.md`). Read at most [`MAX_README_BYTES`] bytes. Returns `None` when | ||
| 185 | +/// the archive is not a gzipped tarball or has no README. | ||
| 186 | +pub fn crate_readme(crate_file: &[u8]) -> Option<String> { | ||
| 187 | + let mut archive = tar::Archive::new(GzDecoder::new(crate_file)); | ||
| 188 | + let entries = archive.entries().ok()?; | ||
| 189 | + for entry in entries { | ||
| 190 | + let entry = entry.ok()?; | ||
| 191 | + let path = entry.path().ok()?.into_owned(); | ||
| 192 | + let mut parts = path.components(); | ||
| 193 | + parts.next()?; | ||
| 194 | + let file = parts.next()?; | ||
| 195 | + let is_top = parts.next().is_none(); | ||
| 196 | + let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase(); | ||
| 197 | + if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() { | ||
| 198 | + let mut bytes = Vec::new(); | ||
| 199 | + entry.take(MAX_README_BYTES).read_to_end(&mut bytes).ok()?; | ||
| 200 | + return Some(String::from_utf8_lossy(&bytes).into_owned()); | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + None | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +#[cfg(test)] | ||
| 207 | +mod tests { | ||
| 208 | + use super::*; | ||
| 209 | + | ||
| 210 | + #[test] | ||
| 211 | + fn names_follow_crate_rules_and_lowercase() { | ||
| 212 | + assert_eq!(crate_name_key("Serde_json").unwrap(), "serde_json"); | ||
| 213 | + assert!(crate_name_key("").is_err()); | ||
| 214 | + assert!(crate_name_key("1abc").is_err()); | ||
| 215 | + assert!(crate_name_key("a b").is_err()); | ||
| 216 | + assert!(crate_name_key("a.b").is_err()); | ||
| 217 | + assert!(crate_name_key(&"a".repeat(65)).is_err()); | ||
| 218 | + assert!(crate_name_key(&"a".repeat(64)).is_ok()); | ||
| 219 | + } | ||
| 220 | + | ||
| 221 | + #[test] | ||
| 222 | + fn index_paths_match_the_sparse_layout() { | ||
| 223 | + assert_eq!(index_path("a"), "1/a"); | ||
| 224 | + assert_eq!(index_path("ab"), "2/ab"); | ||
| 225 | + assert_eq!(index_path("abc"), "3/a/abc"); | ||
| 226 | + assert_eq!(index_path("serde"), "se/rd/serde"); | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + #[test] | ||
| 230 | + fn publish_body_round_trips_and_rejects_bad_lengths() { | ||
| 231 | + let meta = br#"{"name":"demo","vers":"0.1.0"}"#; | ||
| 232 | + let krate = b"gz-bytes"; | ||
| 233 | + let mut body = Vec::new(); | ||
| 234 | + body.extend_from_slice(&(meta.len() as u32).to_le_bytes()); | ||
| 235 | + body.extend_from_slice(meta); | ||
| 236 | + body.extend_from_slice(&(krate.len() as u32).to_le_bytes()); | ||
| 237 | + body.extend_from_slice(krate); | ||
| 238 | + let parsed = parse_publish(&body).unwrap(); | ||
| 239 | + assert_eq!(parsed.metadata["name"], "demo"); | ||
| 240 | + assert_eq!(parsed.crate_file, krate); | ||
| 241 | + | ||
| 242 | + let mut short = body.clone(); | ||
| 243 | + short.pop(); | ||
| 244 | + assert!(parse_publish(&short).is_err()); | ||
| 245 | + assert!(parse_publish(&body[..3]).is_err()); | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + #[test] | ||
| 249 | + fn index_line_renames_deps_and_splits_features() { | ||
| 250 | + let meta = json!({ | ||
| 251 | + "name": "demo", "vers": "0.2.0", "links": null, "rust_version": "1.80", | ||
| 252 | + "deps": [ | ||
| 253 | + {"name": "serde", "version_req": "^1", "features": ["derive"], "optional": false, | ||
| 254 | + "default_features": true, "target": null, "kind": "normal", "registry": null, | ||
| 255 | + "explicit_name_in_toml": null}, | ||
| 256 | + {"name": "tokio", "version_req": "1", "features": [], "optional": true, | ||
| 257 | + "default_features": false, "target": null, "kind": "dev", "registry": null, | ||
| 258 | + "explicit_name_in_toml": "rt"} | ||
| 259 | + ], | ||
| 260 | + "features": {"default": ["serde"], "net": ["dep:tokio"]} | ||
| 261 | + }); | ||
| 262 | + let line = index_line(&meta, "abc").unwrap(); | ||
| 263 | + assert_eq!(line["cksum"], "abc"); | ||
| 264 | + assert_eq!(line["yanked"], false); | ||
| 265 | + assert_eq!(line["v"], 2); | ||
| 266 | + assert_eq!(line["rust_version"], "1.80"); | ||
| 267 | + assert_eq!(line["deps"][1]["name"], "rt"); | ||
| 268 | + assert_eq!(line["deps"][1]["package"], "tokio"); | ||
| 269 | + assert_eq!(line["deps"][0]["package"], Value::Null); | ||
| 270 | + assert_eq!(line["features"]["default"], json!(["serde"])); | ||
| 271 | + assert_eq!(line["features2"]["net"], json!(["dep:tokio"])); | ||
| 272 | + } | ||
| 273 | + | ||
| 274 | + #[test] | ||
| 275 | + fn repository_links_only_forge_repos() { | ||
| 276 | + let base = "https://git.tahinli.com/"; | ||
| 277 | + assert_eq!( | ||
| 278 | + repo_link("https://git.tahinli.com/tahinli/forge.git", base), | ||
| 279 | + Some(("tahinli".into(), "forge".into())) | ||
| 280 | + ); | ||
| 281 | + assert_eq!(repo_link("https://github.com/tahinli/forge", base), None); | ||
| 282 | + assert_eq!(repo_link("https://git.tahinli.com/tahinli", base), None); | ||
| 283 | + assert_eq!(repo_link("https://git.tahinli.com/a/b/c", base), None); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + #[test] | ||
| 287 | + fn readme_is_read_from_the_package_directory() { | ||
| 288 | + let mut tar_bytes = Vec::new(); | ||
| 289 | + { | ||
| 290 | + let mut builder = tar::Builder::new(&mut tar_bytes); | ||
| 291 | + let body = b"# Demo\n\nHello."; | ||
| 292 | + let mut header = tar::Header::new_gnu(); | ||
| 293 | + header.set_size(body.len() as u64); | ||
| 294 | + header.set_mode(0o644); | ||
| 295 | + header.set_cksum(); | ||
| 296 | + builder | ||
| 297 | + .append_data(&mut header, "demo-0.1.0/README.md", &body[..]) | ||
| 298 | + .unwrap(); | ||
| 299 | + builder.finish().unwrap(); | ||
| 300 | + } | ||
| 301 | + let mut gz = Vec::new(); | ||
| 302 | + { | ||
| 303 | + let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast()); | ||
| 304 | + std::io::Write::write_all(&mut enc, &tar_bytes).unwrap(); | ||
| 305 | + enc.finish().unwrap(); | ||
| 306 | + } | ||
| 307 | + assert_eq!(crate_readme(&gz).as_deref(), Some("# Demo\n\nHello.")); | ||
| 308 | + assert_eq!(crate_readme(b"not gzip"), None); | ||
| 309 | + } | ||
| 310 | +} | ||
crates/forge-core/src/lib.rsmodified+3 -0
| @@ -5,6 +5,7 @@ pub mod alerts; | |||
| 5 | pub mod audit; | 5 | pub mod audit; |
| 6 | pub mod authz; | 6 | pub mod authz; |
| 7 | pub mod avatar; | 7 | pub mod avatar; |
| 8 | +pub mod cargo; | ||
| 8 | pub mod ci; | 9 | pub mod ci; |
| 9 | pub mod config; | 10 | pub mod config; |
| 10 | pub mod discussions; | 11 | pub mod discussions; |
| @@ -18,6 +19,8 @@ pub mod mirrors; | |||
| 18 | pub mod model; | 19 | pub mod model; |
| 19 | pub mod names; | 20 | pub mod names; |
| 20 | pub mod notifications; | 21 | pub mod notifications; |
| 22 | +pub mod oci; | ||
| 23 | +pub mod packages; | ||
| 21 | pub mod password; | 24 | pub mod password; |
| 22 | pub mod protection; | 25 | pub mod protection; |
| 23 | pub mod pulls; | 26 | pub mod pulls; |
crates/forge-core/src/names.rsmodified+1 -0
| @@ -7,6 +7,7 @@ use crate::error::{Error, Result}; | |||
| 7 | /// Names that may not be used as owners or repos (they collide with routes). | 7 | /// Names that may not be used as owners or repos (they collide with routes). |
| 8 | pub const RESERVED: &[&str] = &[ | 8 | pub const RESERVED: &[&str] = &[ |
| 9 | "api", | 9 | "api", |
| 10 | + "v2", | ||
| 10 | "admin", | 11 | "admin", |
| 11 | "auth", | 12 | "auth", |
| 12 | "assets", | 13 | "assets", |
crates/forge-core/src/oci.rsadded+296 -0
| @@ -0,0 +1,296 @@ | |||
| 1 | +//! Container registry rules shared by the web layer: repository names, digests, tags, the | ||
| 2 | +//! manifest media types, the reference scan of a manifest, and the short-lived bearer token that | ||
| 3 | +//! `docker login` and `podman` exchange for their credentials. | ||
| 4 | +//! | ||
| 5 | +//! Token format: `base64url("oci1|<user id or empty>|<expires>") + "." + base64url(hmac)`. The | ||
| 6 | +//! MAC covers the payload under its own domain tag, so an LFS token never verifies here. | ||
| 7 | + | ||
| 8 | +use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 9 | +use hmac::{Hmac, KeyInit, Mac}; | ||
| 10 | +use serde_json::Value; | ||
| 11 | +use sha2::Sha256; | ||
| 12 | +use subtle::ConstantTimeEq; | ||
| 13 | + | ||
| 14 | +type HmacSha256 = Hmac<Sha256>; | ||
| 15 | + | ||
| 16 | +/// The media types a manifest may be pushed as. | ||
| 17 | +pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ | ||
| 18 | + "application/vnd.oci.image.manifest.v1+json", | ||
| 19 | + "application/vnd.oci.image.index.v1+json", | ||
| 20 | + "application/vnd.docker.distribution.manifest.v2+json", | ||
| 21 | + "application/vnd.docker.distribution.manifest.list.v2+json", | ||
| 22 | +]; | ||
| 23 | + | ||
| 24 | +/// Longest repository name the spec allows. | ||
| 25 | +const MAX_REPO_NAME: usize = 255; | ||
| 26 | +/// Longest tag the spec allows. | ||
| 27 | +const MAX_TAG: usize = 128; | ||
| 28 | + | ||
| 29 | +/// True for one of [`MANIFEST_MEDIA_TYPES`]. | ||
| 30 | +pub fn is_manifest_media_type(media_type: &str) -> bool { | ||
| 31 | + MANIFEST_MEDIA_TYPES.contains(&media_type) | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// True for one path segment of a repository name: lowercase letters and digits, joined by a | ||
| 35 | +/// single `.` or `_`, or by runs of `-`, and starting and ending with a letter or digit. | ||
| 36 | +fn valid_segment(segment: &str) -> bool { | ||
| 37 | + let bytes = segment.as_bytes(); | ||
| 38 | + if bytes.is_empty() { | ||
| 39 | + return false; | ||
| 40 | + } | ||
| 41 | + let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); | ||
| 42 | + if !alnum(bytes[0]) || !alnum(bytes[bytes.len() - 1]) { | ||
| 43 | + return false; | ||
| 44 | + } | ||
| 45 | + let mut prev_sep = false; | ||
| 46 | + for &b in bytes { | ||
| 47 | + if alnum(b) { | ||
| 48 | + prev_sep = false; | ||
| 49 | + } else if matches!(b, b'.' | b'_' | b'-') { | ||
| 50 | + if prev_sep && b != b'-' { | ||
| 51 | + return false; | ||
| 52 | + } | ||
| 53 | + prev_sep = true; | ||
| 54 | + } else { | ||
| 55 | + return false; | ||
| 56 | + } | ||
| 57 | + } | ||
| 58 | + true | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// The owner and the image path of a repository name such as `tahinli/app` or `tahinli/a/b`. | ||
| 62 | +/// `None` when the name has no owner segment or no image segment, or a segment is malformed. | ||
| 63 | +pub fn split_repo_name(name: &str) -> Option<(&str, &str)> { | ||
| 64 | + if name.len() > MAX_REPO_NAME { | ||
| 65 | + return None; | ||
| 66 | + } | ||
| 67 | + let (owner, image) = name.split_once('/')?; | ||
| 68 | + if !image.split('/').all(valid_segment) || !valid_segment(owner) { | ||
| 69 | + return None; | ||
| 70 | + } | ||
| 71 | + Some((owner, image)) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// The lowercase `sha256:<hex>` digest, returned as its 64 hex characters. `None` for any other | ||
| 75 | +/// algorithm or a malformed value. | ||
| 76 | +pub fn parse_digest(digest: &str) -> Option<&str> { | ||
| 77 | + let hex = digest.strip_prefix("sha256:")?; | ||
| 78 | + let valid = hex.len() == 64 | ||
| 79 | + && hex | ||
| 80 | + .bytes() | ||
| 81 | + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); | ||
| 82 | + valid.then_some(hex) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// True for a tag: up to 128 characters from `[A-Za-z0-9_.-]`, not starting with `.` or `-`. | ||
| 86 | +pub fn valid_tag(tag: &str) -> bool { | ||
| 87 | + let bytes = tag.as_bytes(); | ||
| 88 | + !bytes.is_empty() | ||
| 89 | + && bytes.len() <= MAX_TAG | ||
| 90 | + && !matches!(bytes[0], b'.' | b'-') | ||
| 91 | + && bytes | ||
| 92 | + .iter() | ||
| 93 | + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// What a manifest refers to. | ||
| 97 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 98 | +pub struct ManifestRefs { | ||
| 99 | + /// `sha256:<hex>` digests of the config and layers, or of the child manifests of an index. | ||
| 100 | + pub digests: Vec<String>, | ||
| 101 | + /// Bytes of the image: its config and layers. For an index, the manifest's own length. | ||
| 102 | + pub total_size: u64, | ||
| 103 | + /// True for an index or manifest list, whose digests name manifests rather than blobs. | ||
| 104 | + pub is_index: bool, | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Reads the digests a manifest names. A manifest with a `manifests` array is an index. Any other | ||
| 108 | +/// manifest must name a `config` and may name layers. Every digest must be `sha256:<hex>`. | ||
| 109 | +pub fn scan_manifest(bytes: &[u8]) -> Result<ManifestRefs, String> { | ||
| 110 | + let value: Value = | ||
| 111 | + serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?; | ||
| 112 | + if !value.is_object() { | ||
| 113 | + return Err("manifest is not a JSON object".into()); | ||
| 114 | + } | ||
| 115 | + if let Some(children) = value.get("manifests").and_then(Value::as_array) { | ||
| 116 | + let digests = children | ||
| 117 | + .iter() | ||
| 118 | + .map(descriptor_digest) | ||
| 119 | + .collect::<Result<Vec<_>, _>>()?; | ||
| 120 | + return Ok(ManifestRefs { | ||
| 121 | + digests, | ||
| 122 | + total_size: bytes.len() as u64, | ||
| 123 | + is_index: true, | ||
| 124 | + }); | ||
| 125 | + } | ||
| 126 | + let config = value | ||
| 127 | + .get("config") | ||
| 128 | + .ok_or_else(|| "manifest has no config".to_owned())?; | ||
| 129 | + let mut digests = vec![descriptor_digest(config)?]; | ||
| 130 | + let mut total = descriptor_size(config); | ||
| 131 | + if let Some(layers) = value.get("layers") { | ||
| 132 | + let layers = layers | ||
| 133 | + .as_array() | ||
| 134 | + .ok_or_else(|| "manifest layers is not an array".to_owned())?; | ||
| 135 | + for layer in layers { | ||
| 136 | + digests.push(descriptor_digest(layer)?); | ||
| 137 | + total = total.saturating_add(descriptor_size(layer)); | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + Ok(ManifestRefs { | ||
| 141 | + digests, | ||
| 142 | + total_size: total, | ||
| 143 | + is_index: false, | ||
| 144 | + }) | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +fn descriptor_digest(descriptor: &Value) -> Result<String, String> { | ||
| 148 | + let digest = descriptor | ||
| 149 | + .get("digest") | ||
| 150 | + .and_then(Value::as_str) | ||
| 151 | + .ok_or_else(|| "a descriptor has no digest".to_owned())?; | ||
| 152 | + parse_digest(digest) | ||
| 153 | + .map(|hex| format!("sha256:{hex}")) | ||
| 154 | + .ok_or_else(|| format!("unsupported digest {digest}")) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +fn descriptor_size(descriptor: &Value) -> u64 { | ||
| 158 | + descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 { | ||
| 162 | + // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail. | ||
| 163 | + let mut mac = | ||
| 164 | + <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); | ||
| 165 | + mac.update(b"oci\0"); | ||
| 166 | + mac.update(payload); | ||
| 167 | + mac | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// Issues a bearer token for `subject` (a user id, or `None` for anonymous), valid until | ||
| 171 | +/// `expires_unix` seconds since the epoch. | ||
| 172 | +pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { | ||
| 173 | + let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); | ||
| 174 | + let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes(); | ||
| 175 | + format!( | ||
| 176 | + "{}.{}", | ||
| 177 | + BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), | ||
| 178 | + BASE64_URL_SAFE_NO_PAD.encode(tag) | ||
| 179 | + ) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Checks a bearer token at `now_unix`. Returns the subject it names (`None` for anonymous), or | ||
| 183 | +/// `None` when the token is malformed, forged, or expired. | ||
| 184 | +pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option<String>> { | ||
| 185 | + let (payload_b64, mac_b64) = token.split_once('.')?; | ||
| 186 | + let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?; | ||
| 187 | + let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?; | ||
| 188 | + let expected = mac_for(key, &payload).finalize().into_bytes(); | ||
| 189 | + if !bool::from(expected.as_slice().ct_eq(&tag)) { | ||
| 190 | + return None; | ||
| 191 | + } | ||
| 192 | + let payload = std::str::from_utf8(&payload).ok()?; | ||
| 193 | + let mut parts = payload.split('|'); | ||
| 194 | + if parts.next()? != "oci1" { | ||
| 195 | + return None; | ||
| 196 | + } | ||
| 197 | + let subject = parts.next()?; | ||
| 198 | + let expires: i64 = parts.next()?.parse().ok()?; | ||
| 199 | + if parts.next().is_some() || now_unix >= expires { | ||
| 200 | + return None; | ||
| 201 | + } | ||
| 202 | + Some((!subject.is_empty()).then(|| subject.to_owned())) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +#[cfg(test)] | ||
| 206 | +mod tests { | ||
| 207 | + use super::*; | ||
| 208 | + | ||
| 209 | + const KEY: [u8; 32] = [3; 32]; | ||
| 210 | + const NOW: i64 = 1_700_000_000; | ||
| 211 | + const HEX: &str = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393"; | ||
| 212 | + | ||
| 213 | + #[test] | ||
| 214 | + fn repo_names_need_an_owner_and_an_image() { | ||
| 215 | + assert_eq!(split_repo_name("tahinli/app"), Some(("tahinli", "app"))); | ||
| 216 | + assert_eq!(split_repo_name("tahinli/a/b"), Some(("tahinli", "a/b"))); | ||
| 217 | + assert_eq!(split_repo_name("tahinli"), None); | ||
| 218 | + assert_eq!(split_repo_name("Tahinli/app"), None); | ||
| 219 | + assert_eq!(split_repo_name("tahinli/app/"), None); | ||
| 220 | + assert_eq!(split_repo_name("tahinli//app"), None); | ||
| 221 | + assert_eq!(split_repo_name("tahinli/app__/x"), None); | ||
| 222 | + assert_eq!( | ||
| 223 | + split_repo_name("tahinli/my.app-v2_x"), | ||
| 224 | + Some(("tahinli", "my.app-v2_x")) | ||
| 225 | + ); | ||
| 226 | + assert_eq!(split_repo_name("tahinli/a..b"), None); | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + #[test] | ||
| 230 | + fn digests_must_be_lowercase_sha256_hex() { | ||
| 231 | + assert_eq!(parse_digest(&format!("sha256:{HEX}")), Some(HEX)); | ||
| 232 | + assert_eq!(parse_digest(HEX), None); | ||
| 233 | + assert_eq!(parse_digest(&format!("sha512:{HEX}")), None); | ||
| 234 | + assert_eq!( | ||
| 235 | + parse_digest(&format!("sha256:{}", HEX.to_uppercase())), | ||
| 236 | + None | ||
| 237 | + ); | ||
| 238 | + assert_eq!(parse_digest(&format!("sha256:{}", &HEX[..63])), None); | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + #[test] | ||
| 242 | + fn tags_follow_the_spec_charset() { | ||
| 243 | + assert!(valid_tag("latest")); | ||
| 244 | + assert!(valid_tag("v1.2.3-rc_1")); | ||
| 245 | + assert!(!valid_tag("")); | ||
| 246 | + assert!(!valid_tag(".hidden")); | ||
| 247 | + assert!(!valid_tag("a/b")); | ||
| 248 | + assert!(!valid_tag(&"a".repeat(129))); | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + #[test] | ||
| 252 | + fn an_image_manifest_names_its_config_and_layers() { | ||
| 253 | + let manifest = format!( | ||
| 254 | + r#"{{"schemaVersion":2,"config":{{"digest":"sha256:{HEX}","size":10}}, | ||
| 255 | + "layers":[{{"digest":"sha256:{HEX}","size":100}}]}}"# | ||
| 256 | + ); | ||
| 257 | + let refs = scan_manifest(manifest.as_bytes()).unwrap(); | ||
| 258 | + assert!(!refs.is_index); | ||
| 259 | + assert_eq!(refs.digests, vec![format!("sha256:{HEX}"); 2]); | ||
| 260 | + assert_eq!(refs.total_size, 110); | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + #[test] | ||
| 264 | + fn an_index_names_child_manifests() { | ||
| 265 | + let manifest = format!(r#"{{"manifests":[{{"digest":"sha256:{HEX}","size":5}}]}}"#); | ||
| 266 | + let refs = scan_manifest(manifest.as_bytes()).unwrap(); | ||
| 267 | + assert!(refs.is_index); | ||
| 268 | + assert_eq!(refs.digests, vec![format!("sha256:{HEX}")]); | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + #[test] | ||
| 272 | + fn bad_manifests_are_refused() { | ||
| 273 | + assert!(scan_manifest(b"not json").is_err()); | ||
| 274 | + assert!(scan_manifest(b"[]").is_err()); | ||
| 275 | + assert!(scan_manifest(b"{}").is_err()); | ||
| 276 | + assert!(scan_manifest(br#"{"config":{"digest":"md5:x"}}"#).is_err()); | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + #[test] | ||
| 280 | + fn a_token_round_trips_for_a_user_and_for_anonymous() { | ||
| 281 | + let token = issue_token(&KEY, Some("user-1"), NOW + 60); | ||
| 282 | + assert_eq!(verify_token(&KEY, &token, NOW), Some(Some("user-1".into()))); | ||
| 283 | + let anon = issue_token(&KEY, None, NOW + 60); | ||
| 284 | + assert_eq!(verify_token(&KEY, &anon, NOW), Some(None)); | ||
| 285 | + } | ||
| 286 | + | ||
| 287 | + #[test] | ||
| 288 | + fn a_token_is_refused_when_expired_forged_or_from_another_key() { | ||
| 289 | + let token = issue_token(&KEY, Some("user-1"), NOW + 60); | ||
| 290 | + assert_eq!(verify_token(&KEY, &token, NOW + 60), None); | ||
| 291 | + assert_eq!(verify_token(&[9; 32], &token, NOW), None); | ||
| 292 | + assert_eq!(verify_token(&KEY, "garbage", NOW), None); | ||
| 293 | + let forged = token.replacen(&BASE64_URL_SAFE_NO_PAD.encode("oci1|user-1|"), "x", 1); | ||
| 294 | + assert_eq!(verify_token(&KEY, &forged, NOW), None); | ||
| 295 | + } | ||
| 296 | +} | ||
crates/forge-core/src/packages.rsadded+89 -0
| @@ -0,0 +1,89 @@ | |||
| 1 | +//! Package registries. An owner (user or org) holds packages of one `kind`; each package has | ||
| 2 | +//! versions. The stored shape is in migrations/0061_packages.sql, the store functions in | ||
| 3 | +//! store/packages.rs. Bytes of a `.crate` live in blob storage under `packages/<version id>`; | ||
| 4 | +//! only metadata is stored here. Kinds are `cargo` and `oci` (container images). | ||
| 5 | + | ||
| 6 | +/// The Cargo registry kind. | ||
| 7 | +pub const KIND_CARGO: &str = "cargo"; | ||
| 8 | +/// The container registry kind. Its packages are images; their tags and manifests are in the | ||
| 9 | +/// `oci_*` tables (migrations/0062_oci.sql), not in `package_versions`. | ||
| 10 | +pub const KIND_OCI: &str = "oci"; | ||
| 11 | + | ||
| 12 | +/// A package. `name_key` is the lowercase name the index uses; `private` hides the package and | ||
| 13 | +/// its index from everyone but the owner's members. | ||
| 14 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 15 | +pub struct Package { | ||
| 16 | + pub id: String, | ||
| 17 | + pub owner_id: String, | ||
| 18 | + pub kind: String, | ||
| 19 | + pub name: String, | ||
| 20 | + pub name_key: String, | ||
| 21 | + pub repo_id: Option<String>, | ||
| 22 | + pub private: bool, | ||
| 23 | + pub created_at: String, | ||
| 24 | + pub updated_at: String, | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// One published version of a package. | ||
| 28 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 29 | +pub struct PackageVersion { | ||
| 30 | + pub id: String, | ||
| 31 | + pub package_id: String, | ||
| 32 | + pub version: String, | ||
| 33 | + pub yanked: bool, | ||
| 34 | + /// Lowercase hex sha256 of the `.crate` file. | ||
| 35 | + pub checksum: String, | ||
| 36 | + pub size: u64, | ||
| 37 | + /// The index line as published, with `yanked` false. Served with the current yank state. | ||
| 38 | + pub index_json: String, | ||
| 39 | + pub description: Option<String>, | ||
| 40 | + pub readme: Option<String>, | ||
| 41 | + pub publisher_id: String, | ||
| 42 | + pub created_at: String, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// A package with what its list shows: how many versions it has and the newest one. | ||
| 46 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 47 | +pub struct PackageSummary { | ||
| 48 | + pub package: Package, | ||
| 49 | + pub version_count: u64, | ||
| 50 | + pub latest_version: Option<String>, | ||
| 51 | + pub latest_description: Option<String>, | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Input for `Store::publish_package_version`. | ||
| 55 | +#[derive(Debug, Clone, Copy)] | ||
| 56 | +pub struct NewPackageVersion<'a> { | ||
| 57 | + pub package_id: &'a str, | ||
| 58 | + pub version: &'a str, | ||
| 59 | + pub checksum: &'a str, | ||
| 60 | + pub size: u64, | ||
| 61 | + pub index_json: &'a str, | ||
| 62 | + pub description: Option<&'a str>, | ||
| 63 | + pub readme: Option<&'a str>, | ||
| 64 | + pub publisher_id: &'a str, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// A container manifest as pushed. `content` is the exact JSON, so its digest still checks. | ||
| 68 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 69 | +pub struct OciManifest { | ||
| 70 | + pub id: String, | ||
| 71 | + pub package_id: String, | ||
| 72 | + pub digest: String, | ||
| 73 | + pub media_type: String, | ||
| 74 | + pub content: String, | ||
| 75 | + /// The image's config and layers in bytes, or the manifest's length for an index. | ||
| 76 | + pub size: u64, | ||
| 77 | + pub created_at: String, | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// One tag of a container image, with the manifest it points at. | ||
| 81 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 82 | +pub struct OciTag { | ||
| 83 | + pub tag: String, | ||
| 84 | + pub digest: String, | ||
| 85 | + pub media_type: String, | ||
| 86 | + pub size: u64, | ||
| 87 | + pub created_at: String, | ||
| 88 | + pub updated_at: String, | ||
| 89 | +} | ||
crates/forge-core/src/store/migrate.rsmodified+4 -2
| @@ -100,8 +100,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 100 | (58, include_str!("../../migrations/0058_passkeys.sql")), | 100 | (58, include_str!("../../migrations/0058_passkeys.sql")), |
| 101 | (59, include_str!("../../migrations/0059_admin_alerts.sql")), | 101 | (59, include_str!("../../migrations/0059_admin_alerts.sql")), |
| 102 | (60, include_str!("../../migrations/0060_runner_memory.sql")), | 102 | (60, include_str!("../../migrations/0060_runner_memory.sql")), |
| 103 | - (61, include_str!("../../migrations/0061_web_push.sql")), | 103 | + (61, include_str!("../../migrations/0061_packages.sql")), |
| 104 | - (61, include_str!("../../migrations/0061_merge_queue.sql")), | 104 | + (62, include_str!("../../migrations/0062_oci.sql")), |
| 105 | + (63, include_str!("../../migrations/0063_web_push.sql")), | ||
| 106 | + (64, include_str!("../../migrations/0064_merge_queue.sql")), | ||
| 105 | ]; | 107 | ]; |
| 106 | 108 | ||
| 107 | /// The highest migration version this binary knows about. | 109 | /// The highest migration version this binary knows about. |
crates/forge-core/src/store/mod.rsmodified+2 -0
| @@ -23,7 +23,9 @@ pub mod migrate; | |||
| 23 | pub mod mirrors; | 23 | pub mod mirrors; |
| 24 | pub mod notifications; | 24 | pub mod notifications; |
| 25 | pub mod notifications_extra; | 25 | pub mod notifications_extra; |
| 26 | +pub mod oci; | ||
| 26 | pub mod orgs; | 27 | pub mod orgs; |
| 28 | +pub mod packages; | ||
| 27 | pub mod passkeys; | 29 | pub mod passkeys; |
| 28 | pub mod pinned; | 30 | pub mod pinned; |
| 29 | pub mod profile_pins; | 31 | pub mod profile_pins; |
crates/forge-core/src/store/oci.rsadded+332 -0
| @@ -0,0 +1,332 @@ | |||
| 1 | +//! Container registry storage: the blobs a package may read, its manifests, the tags that name | ||
| 2 | +//! them, and the references each manifest makes. Blob bytes are not here; the web layer writes and | ||
| 3 | +//! deletes them under `oci/<hex>` in the blob store. | ||
| 4 | + | ||
| 5 | +use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id}; | ||
| 6 | +use crate::error::{Error, Result}; | ||
| 7 | +use crate::packages::{OciManifest, OciTag}; | ||
| 8 | +use crate::time::now_stamp; | ||
| 9 | + | ||
| 10 | +const MANIFEST_COLS: &str = "id, package_id, digest, media_type, content, size, created_at"; | ||
| 11 | + | ||
| 12 | +fn map_manifest(row: &turso::Row) -> Result<OciManifest> { | ||
| 13 | + Ok(OciManifest { | ||
| 14 | + id: col_text(row, 0)?, | ||
| 15 | + package_id: col_text(row, 1)?, | ||
| 16 | + digest: col_text(row, 2)?, | ||
| 17 | + media_type: col_text(row, 3)?, | ||
| 18 | + content: col_text(row, 4)?, | ||
| 19 | + size: to_u64(col_int(row, 5)?)?, | ||
| 20 | + created_at: col_text(row, 6)?, | ||
| 21 | + }) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +fn to_u64(value: i64) -> Result<u64> { | ||
| 25 | + u64::try_from(value).map_err(|_| Error::Database("negative size".into())) | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl Store { | ||
| 29 | + /// Records that `package_id` may read the blob `digest` of `size` bytes. Linking a digest the | ||
| 30 | + /// package already has changes nothing. | ||
| 31 | + pub async fn oci_link_blob(&self, package_id: &str, digest: &str, size: u64) -> Result<()> { | ||
| 32 | + let conn = self.inner.conn.lock().await; | ||
| 33 | + conn.execute( | ||
| 34 | + "INSERT OR IGNORE INTO oci_blobs (package_id, digest, size, created_at) \ | ||
| 35 | + VALUES (?1, ?2, ?3, ?4)", | ||
| 36 | + ( | ||
| 37 | + package_id.to_string(), | ||
| 38 | + digest.to_string(), | ||
| 39 | + i64::try_from(size).unwrap_or(i64::MAX), | ||
| 40 | + now_stamp(), | ||
| 41 | + ), | ||
| 42 | + ) | ||
| 43 | + .await | ||
| 44 | + .map_err(db_err)?; | ||
| 45 | + Ok(()) | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + /// The size of blob `digest` as `package_id` links it, or `None` when it does not. | ||
| 49 | + pub async fn oci_blob_size(&self, package_id: &str, digest: &str) -> Result<Option<u64>> { | ||
| 50 | + let conn = self.read_conn().await; | ||
| 51 | + let size = fetch_opt( | ||
| 52 | + &conn, | ||
| 53 | + "SELECT size FROM oci_blobs WHERE package_id = ?1 AND digest = ?2 LIMIT 1", | ||
| 54 | + (package_id.to_string(), digest.to_string()), | ||
| 55 | + |row| col_int(row, 0), | ||
| 56 | + ) | ||
| 57 | + .await?; | ||
| 58 | + size.map(to_u64).transpose() | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | + /// True when any package links `digest`. Its bytes are kept while this holds. | ||
| 62 | + pub async fn oci_digest_linked(&self, digest: &str) -> Result<bool> { | ||
| 63 | + let conn = self.read_conn().await; | ||
| 64 | + let count = fetch_opt( | ||
| 65 | + &conn, | ||
| 66 | + "SELECT COUNT(*) FROM oci_blobs WHERE digest = ?1", | ||
| 67 | + (digest.to_string(),), | ||
| 68 | + |row| col_int(row, 0), | ||
| 69 | + ) | ||
| 70 | + .await?; | ||
| 71 | + Ok(count.unwrap_or(0) > 0) | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + /// Stores a manifest of `package_id` under `digest`, with the digests it refers to. A manifest | ||
| 75 | + /// already stored under that digest is kept as it is. | ||
| 76 | + pub async fn oci_put_manifest( | ||
| 77 | + &self, | ||
| 78 | + package_id: &str, | ||
| 79 | + digest: &str, | ||
| 80 | + media_type: &str, | ||
| 81 | + content: &str, | ||
| 82 | + size: u64, | ||
| 83 | + refs: &[String], | ||
| 84 | + ) -> Result<OciManifest> { | ||
| 85 | + { | ||
| 86 | + let conn = self.inner.conn.lock().await; | ||
| 87 | + conn.execute( | ||
| 88 | + "INSERT OR IGNORE INTO oci_manifests (id, package_id, digest, media_type, content, \ | ||
| 89 | + size, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | ||
| 90 | + ( | ||
| 91 | + new_id(), | ||
| 92 | + package_id.to_string(), | ||
| 93 | + digest.to_string(), | ||
| 94 | + media_type.to_string(), | ||
| 95 | + content.to_string(), | ||
| 96 | + i64::try_from(size).unwrap_or(i64::MAX), | ||
| 97 | + now_stamp(), | ||
| 98 | + ), | ||
| 99 | + ) | ||
| 100 | + .await | ||
| 101 | + .map_err(db_err)?; | ||
| 102 | + } | ||
| 103 | + let manifest = self | ||
| 104 | + .oci_manifest(package_id, digest) | ||
| 105 | + .await? | ||
| 106 | + .ok_or_else(missing_row)?; | ||
| 107 | + let conn = self.inner.conn.lock().await; | ||
| 108 | + for dep in refs { | ||
| 109 | + conn.execute( | ||
| 110 | + "INSERT OR IGNORE INTO oci_manifest_refs (manifest_id, digest) VALUES (?1, ?2)", | ||
| 111 | + (manifest.id.clone(), dep.clone()), | ||
| 112 | + ) | ||
| 113 | + .await | ||
| 114 | + .map_err(db_err)?; | ||
| 115 | + } | ||
| 116 | + Ok(manifest) | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + /// The manifest of `package_id` stored under `digest`. | ||
| 120 | + pub async fn oci_manifest( | ||
| 121 | + &self, | ||
| 122 | + package_id: &str, | ||
| 123 | + digest: &str, | ||
| 124 | + ) -> Result<Option<OciManifest>> { | ||
| 125 | + let conn = self.read_conn().await; | ||
| 126 | + fetch_opt( | ||
| 127 | + &conn, | ||
| 128 | + &format!( | ||
| 129 | + "SELECT {MANIFEST_COLS} FROM oci_manifests WHERE package_id = ?1 AND digest = ?2 \ | ||
| 130 | + LIMIT 1" | ||
| 131 | + ), | ||
| 132 | + (package_id.to_string(), digest.to_string()), | ||
| 133 | + map_manifest, | ||
| 134 | + ) | ||
| 135 | + .await | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + /// The manifest the tag `tag` of `package_id` points at. | ||
| 139 | + pub async fn oci_tag_manifest( | ||
| 140 | + &self, | ||
| 141 | + package_id: &str, | ||
| 142 | + tag: &str, | ||
| 143 | + ) -> Result<Option<OciManifest>> { | ||
| 144 | + let conn = self.read_conn().await; | ||
| 145 | + fetch_opt( | ||
| 146 | + &conn, | ||
| 147 | + "SELECT m.id, m.package_id, m.digest, m.media_type, m.content, m.size, m.created_at \ | ||
| 148 | + FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ | ||
| 149 | + WHERE t.package_id = ?1 AND t.tag = ?2 LIMIT 1", | ||
| 150 | + (package_id.to_string(), tag.to_string()), | ||
| 151 | + map_manifest, | ||
| 152 | + ) | ||
| 153 | + .await | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target. | ||
| 157 | + pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> { | ||
| 158 | + let conn = self.inner.conn.lock().await; | ||
| 159 | + conn.execute( | ||
| 160 | + "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", | ||
| 161 | + (package_id.to_string(), tag.to_string()), | ||
| 162 | + ) | ||
| 163 | + .await | ||
| 164 | + .map_err(db_err)?; | ||
| 165 | + conn.execute( | ||
| 166 | + "INSERT INTO oci_tags (package_id, tag, manifest_id, updated_at) \ | ||
| 167 | + VALUES (?1, ?2, ?3, ?4)", | ||
| 168 | + ( | ||
| 169 | + package_id.to_string(), | ||
| 170 | + tag.to_string(), | ||
| 171 | + manifest_id.to_string(), | ||
| 172 | + now_stamp(), | ||
| 173 | + ), | ||
| 174 | + ) | ||
| 175 | + .await | ||
| 176 | + .map_err(db_err)?; | ||
| 177 | + Ok(()) | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + /// Removes `tag` from `package_id`. Returns the manifest id it pointed at, or `None` when the | ||
| 181 | + /// tag did not exist. | ||
| 182 | + pub async fn oci_delete_tag(&self, package_id: &str, tag: &str) -> Result<Option<String>> { | ||
| 183 | + let manifest_id = { | ||
| 184 | + let conn = self.read_conn().await; | ||
| 185 | + fetch_opt( | ||
| 186 | + &conn, | ||
| 187 | + "SELECT manifest_id FROM oci_tags WHERE package_id = ?1 AND tag = ?2 LIMIT 1", | ||
| 188 | + (package_id.to_string(), tag.to_string()), | ||
| 189 | + |row| col_text(row, 0), | ||
| 190 | + ) | ||
| 191 | + .await? | ||
| 192 | + }; | ||
| 193 | + let Some(manifest_id) = manifest_id else { | ||
| 194 | + return Ok(None); | ||
| 195 | + }; | ||
| 196 | + let conn = self.inner.conn.lock().await; | ||
| 197 | + conn.execute( | ||
| 198 | + "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", | ||
| 199 | + (package_id.to_string(), tag.to_string()), | ||
| 200 | + ) | ||
| 201 | + .await | ||
| 202 | + .map_err(db_err)?; | ||
| 203 | + Ok(Some(manifest_id)) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + /// How many tags point at a manifest. | ||
| 207 | + pub async fn oci_manifest_tag_count(&self, manifest_id: &str) -> Result<u64> { | ||
| 208 | + let conn = self.read_conn().await; | ||
| 209 | + let count = fetch_opt( | ||
| 210 | + &conn, | ||
| 211 | + "SELECT COUNT(*) FROM oci_tags WHERE manifest_id = ?1", | ||
| 212 | + (manifest_id.to_string(),), | ||
| 213 | + |row| col_int(row, 0), | ||
| 214 | + ) | ||
| 215 | + .await?; | ||
| 216 | + to_u64(count.unwrap_or(0)) | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + /// True when a manifest of `package_id` names `digest`: an index names its children, and a | ||
| 220 | + /// manifest names its blobs. | ||
| 221 | + pub async fn oci_digest_referenced(&self, package_id: &str, digest: &str) -> Result<bool> { | ||
| 222 | + let conn = self.read_conn().await; | ||
| 223 | + let count = fetch_opt( | ||
| 224 | + &conn, | ||
| 225 | + "SELECT COUNT(*) FROM oci_manifest_refs r JOIN oci_manifests m ON m.id = r.manifest_id \ | ||
| 226 | + WHERE m.package_id = ?1 AND r.digest = ?2", | ||
| 227 | + (package_id.to_string(), digest.to_string()), | ||
| 228 | + |row| col_int(row, 0), | ||
| 229 | + ) | ||
| 230 | + .await?; | ||
| 231 | + Ok(count.unwrap_or(0) > 0) | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + /// Removes a manifest by id. Its tags and references go with it. | ||
| 235 | + pub async fn oci_delete_manifest(&self, manifest_id: &str) -> Result<()> { | ||
| 236 | + let conn = self.inner.conn.lock().await; | ||
| 237 | + conn.execute( | ||
| 238 | + "DELETE FROM oci_manifests WHERE id = ?1", | ||
| 239 | + (manifest_id.to_string(),), | ||
| 240 | + ) | ||
| 241 | + .await | ||
| 242 | + .map_err(db_err)?; | ||
| 243 | + Ok(()) | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + /// Tag names of `package_id` after `last` (empty for the first page), in order, at most | ||
| 247 | + /// `limit` of them. | ||
| 248 | + pub async fn oci_tag_names( | ||
| 249 | + &self, | ||
| 250 | + package_id: &str, | ||
| 251 | + last: &str, | ||
| 252 | + limit: u64, | ||
| 253 | + ) -> Result<Vec<String>> { | ||
| 254 | + let conn = self.read_conn().await; | ||
| 255 | + fetch_all( | ||
| 256 | + &conn, | ||
| 257 | + "SELECT tag FROM oci_tags WHERE package_id = ?1 AND tag > ?2 ORDER BY tag LIMIT ?3", | ||
| 258 | + ( | ||
| 259 | + package_id.to_string(), | ||
| 260 | + last.to_string(), | ||
| 261 | + i64::try_from(limit).unwrap_or(i64::MAX), | ||
| 262 | + ), | ||
| 263 | + |row| col_text(row, 0), | ||
| 264 | + ) | ||
| 265 | + .await | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + /// Every tag of `package_id`, most recently updated first, with its manifest. | ||
| 269 | + pub async fn oci_tags(&self, package_id: &str) -> Result<Vec<OciTag>> { | ||
| 270 | + let conn = self.read_conn().await; | ||
| 271 | + fetch_all( | ||
| 272 | + &conn, | ||
| 273 | + "SELECT t.tag, m.digest, m.media_type, m.size, m.created_at, t.updated_at \ | ||
| 274 | + FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ | ||
| 275 | + WHERE t.package_id = ?1 ORDER BY t.updated_at DESC, t.tag", | ||
| 276 | + (package_id.to_string(),), | ||
| 277 | + |row| { | ||
| 278 | + Ok(OciTag { | ||
| 279 | + tag: col_text(row, 0)?, | ||
| 280 | + digest: col_text(row, 1)?, | ||
| 281 | + media_type: col_text(row, 2)?, | ||
| 282 | + size: to_u64(col_int(row, 3)?)?, | ||
| 283 | + created_at: col_text(row, 4)?, | ||
| 284 | + updated_at: col_text(row, 5)?, | ||
| 285 | + }) | ||
| 286 | + }, | ||
| 287 | + ) | ||
| 288 | + .await | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + /// The sweep of garbage collection for one package (mark and sweep). Drops every blob link of | ||
| 292 | + /// `package_id` that no manifest of the package refers to, and returns the digests dropped. | ||
| 293 | + /// The caller deletes the bytes of each digest that no package links any more. | ||
| 294 | + pub async fn oci_sweep_unreferenced(&self, package_id: &str) -> Result<Vec<String>> { | ||
| 295 | + let unreferenced = { | ||
| 296 | + let conn = self.read_conn().await; | ||
| 297 | + fetch_all( | ||
| 298 | + &conn, | ||
| 299 | + "SELECT digest FROM oci_blobs WHERE package_id = ?1 AND digest NOT IN \ | ||
| 300 | + (SELECT r.digest FROM oci_manifest_refs r JOIN oci_manifests m \ | ||
| 301 | + ON m.id = r.manifest_id WHERE m.package_id = ?1)", | ||
| 302 | + (package_id.to_string(),), | ||
| 303 | + |row| col_text(row, 0), | ||
| 304 | + ) | ||
| 305 | + .await? | ||
| 306 | + }; | ||
| 307 | + let conn = self.inner.conn.lock().await; | ||
| 308 | + for digest in &unreferenced { | ||
| 309 | + conn.execute( | ||
| 310 | + "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", | ||
| 311 | + (package_id.to_string(), digest.clone()), | ||
| 312 | + ) | ||
| 313 | + .await | ||
| 314 | + .map_err(db_err)?; | ||
| 315 | + } | ||
| 316 | + Ok(unreferenced) | ||
| 317 | + } | ||
| 318 | + | ||
| 319 | + /// Removes the link of `digest` from `package_id`. Returns true when there was one. | ||
| 320 | + pub async fn oci_unlink_blob(&self, package_id: &str, digest: &str) -> Result<bool> { | ||
| 321 | + let changed = { | ||
| 322 | + let conn = self.inner.conn.lock().await; | ||
| 323 | + conn.execute( | ||
| 324 | + "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", | ||
| 325 | + (package_id.to_string(), digest.to_string()), | ||
| 326 | + ) | ||
| 327 | + .await | ||
| 328 | + .map_err(db_err)? | ||
| 329 | + }; | ||
| 330 | + Ok(changed == 1) | ||
| 331 | + } | ||
| 332 | +} | ||
crates/forge-core/src/store/packages.rsadded+332 -0
| @@ -0,0 +1,332 @@ | |||
| 1 | +//! Package storage: packages, their versions and the link to a repo. Blob bytes are not here; | ||
| 2 | +//! the web layer writes and deletes them, under the ids this module returns. | ||
| 3 | + | ||
| 4 | +use turso::{Row, Value}; | ||
| 5 | + | ||
| 6 | +use super::{ | ||
| 7 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row, | ||
| 8 | + new_id, | ||
| 9 | +}; | ||
| 10 | +use crate::error::{Error, Result}; | ||
| 11 | +use crate::packages::{NewPackageVersion, Package, PackageSummary, PackageVersion}; | ||
| 12 | +use crate::time::now_stamp; | ||
| 13 | + | ||
| 14 | +const PACKAGE_COLS: &str = "p.id, p.owner_id, p.kind, p.name, p.name_key, p.repo_id, p.private, \ | ||
| 15 | + p.created_at, p.updated_at"; | ||
| 16 | + | ||
| 17 | +const VERSION_COLS: &str = "id, package_id, version, yanked, checksum, size, index_json, \ | ||
| 18 | + description, readme, publisher_id, created_at"; | ||
| 19 | + | ||
| 20 | +/// Newest first, by publish time. | ||
| 21 | +const VERSION_ORDER: &str = "created_at DESC, id DESC"; | ||
| 22 | + | ||
| 23 | +fn map_package(row: &Row) -> Result<Package> { | ||
| 24 | + Ok(Package { | ||
| 25 | + id: col_text(row, 0)?, | ||
| 26 | + owner_id: col_text(row, 1)?, | ||
| 27 | + kind: col_text(row, 2)?, | ||
| 28 | + name: col_text(row, 3)?, | ||
| 29 | + name_key: col_text(row, 4)?, | ||
| 30 | + repo_id: col_opt_text(row, 5)?, | ||
| 31 | + private: col_int(row, 6)? != 0, | ||
| 32 | + created_at: col_text(row, 7)?, | ||
| 33 | + updated_at: col_text(row, 8)?, | ||
| 34 | + }) | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +fn map_summary(row: &Row) -> Result<PackageSummary> { | ||
| 38 | + let count = col_int(row, 9)?; | ||
| 39 | + Ok(PackageSummary { | ||
| 40 | + package: map_package(row)?, | ||
| 41 | + version_count: u64::try_from(count) | ||
| 42 | + .map_err(|_| Error::Database("negative count".into()))?, | ||
| 43 | + latest_version: col_opt_text(row, 10)?, | ||
| 44 | + latest_description: col_opt_text(row, 11)?, | ||
| 45 | + }) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +fn map_version(row: &Row) -> Result<PackageVersion> { | ||
| 49 | + let size = col_int(row, 5)?; | ||
| 50 | + Ok(PackageVersion { | ||
| 51 | + id: col_text(row, 0)?, | ||
| 52 | + package_id: col_text(row, 1)?, | ||
| 53 | + version: col_text(row, 2)?, | ||
| 54 | + yanked: col_int(row, 3)? != 0, | ||
| 55 | + checksum: col_text(row, 4)?, | ||
| 56 | + size: u64::try_from(size).map_err(|_| Error::Database("negative size".into()))?, | ||
| 57 | + index_json: col_text(row, 6)?, | ||
| 58 | + description: col_opt_text(row, 7)?, | ||
| 59 | + readme: col_opt_text(row, 8)?, | ||
| 60 | + publisher_id: col_text(row, 9)?, | ||
| 61 | + created_at: col_text(row, 10)?, | ||
| 62 | + }) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl Store { | ||
| 66 | + /// The package `name_key` of `owner_id` in `kind`, created when it does not exist yet. The | ||
| 67 | + /// name as first published is kept. | ||
| 68 | + pub async fn ensure_package( | ||
| 69 | + &self, | ||
| 70 | + owner_id: &str, | ||
| 71 | + kind: &str, | ||
| 72 | + name: &str, | ||
| 73 | + name_key: &str, | ||
| 74 | + ) -> Result<Package> { | ||
| 75 | + { | ||
| 76 | + let conn = self.inner.conn.lock().await; | ||
| 77 | + conn.execute( | ||
| 78 | + "INSERT OR IGNORE INTO packages (id, owner_id, kind, name, name_key, private, \ | ||
| 79 | + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?6)", | ||
| 80 | + ( | ||
| 81 | + new_id(), | ||
| 82 | + owner_id.to_string(), | ||
| 83 | + kind.to_string(), | ||
| 84 | + name.to_string(), | ||
| 85 | + name_key.to_string(), | ||
| 86 | + now_stamp(), | ||
| 87 | + ), | ||
| 88 | + ) | ||
| 89 | + .await | ||
| 90 | + .map_err(db_err)?; | ||
| 91 | + } | ||
| 92 | + self.package_by_name(owner_id, kind, name_key) | ||
| 93 | + .await? | ||
| 94 | + .ok_or_else(missing_row) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// One package by id. | ||
| 98 | + pub async fn package(&self, id: &str) -> Result<Option<Package>> { | ||
| 99 | + let conn = self.read_conn().await; | ||
| 100 | + fetch_opt( | ||
| 101 | + &conn, | ||
| 102 | + &format!("SELECT {PACKAGE_COLS} FROM packages p WHERE p.id = ?1 LIMIT 1"), | ||
| 103 | + (id.to_string(),), | ||
| 104 | + map_package, | ||
| 105 | + ) | ||
| 106 | + .await | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// The package of `owner_id` called `name_key` in `kind`. | ||
| 110 | + pub async fn package_by_name( | ||
| 111 | + &self, | ||
| 112 | + owner_id: &str, | ||
| 113 | + kind: &str, | ||
| 114 | + name_key: &str, | ||
| 115 | + ) -> Result<Option<Package>> { | ||
| 116 | + let conn = self.read_conn().await; | ||
| 117 | + fetch_opt( | ||
| 118 | + &conn, | ||
| 119 | + &format!( | ||
| 120 | + "SELECT {PACKAGE_COLS} FROM packages p \ | ||
| 121 | + WHERE p.owner_id = ?1 AND p.kind = ?2 AND p.name_key = ?3 LIMIT 1" | ||
| 122 | + ), | ||
| 123 | + (owner_id.to_string(), kind.to_string(), name_key.to_string()), | ||
| 124 | + map_package, | ||
| 125 | + ) | ||
| 126 | + .await | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + /// Every package of an owner in `kind`, by name, with its version count and newest version. For | ||
| 130 | + /// an `oci` image the versions are its tags, newest first by update, and it has no description. | ||
| 131 | + pub async fn list_packages(&self, owner_id: &str, kind: &str) -> Result<Vec<PackageSummary>> { | ||
| 132 | + let conn = self.read_conn().await; | ||
| 133 | + fetch_all( | ||
| 134 | + &conn, | ||
| 135 | + &format!( | ||
| 136 | + "SELECT {PACKAGE_COLS}, \ | ||
| 137 | + CASE WHEN p.kind = 'oci' THEN \ | ||
| 138 | + (SELECT COUNT(*) FROM oci_tags t WHERE t.package_id = p.id) \ | ||
| 139 | + ELSE (SELECT COUNT(*) FROM package_versions v WHERE v.package_id = p.id) END, \ | ||
| 140 | + CASE WHEN p.kind = 'oci' THEN \ | ||
| 141 | + (SELECT t.tag FROM oci_tags t WHERE t.package_id = p.id \ | ||
| 142 | + ORDER BY t.updated_at DESC, t.tag LIMIT 1) \ | ||
| 143 | + ELSE (SELECT v.version FROM package_versions v WHERE v.package_id = p.id \ | ||
| 144 | + ORDER BY {VERSION_ORDER} LIMIT 1) END, \ | ||
| 145 | + CASE WHEN p.kind = 'oci' THEN NULL \ | ||
| 146 | + ELSE (SELECT v.description FROM package_versions v WHERE v.package_id = p.id \ | ||
| 147 | + ORDER BY {VERSION_ORDER} LIMIT 1) END \ | ||
| 148 | + FROM packages p WHERE p.owner_id = ?1 AND p.kind = ?2 ORDER BY p.name_key" | ||
| 149 | + ), | ||
| 150 | + (owner_id.to_string(), kind.to_string()), | ||
| 151 | + map_summary, | ||
| 152 | + ) | ||
| 153 | + .await | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + /// The packages linked to a repo, by name. | ||
| 157 | + pub async fn packages_for_repo(&self, repo_id: &str) -> Result<Vec<Package>> { | ||
| 158 | + let conn = self.read_conn().await; | ||
| 159 | + fetch_all( | ||
| 160 | + &conn, | ||
| 161 | + &format!( | ||
| 162 | + "SELECT {PACKAGE_COLS} FROM packages p WHERE p.repo_id = ?1 ORDER BY p.name_key" | ||
| 163 | + ), | ||
| 164 | + (repo_id.to_string(),), | ||
| 165 | + map_package, | ||
| 166 | + ) | ||
| 167 | + .await | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + /// True when the owner has at least one private package in any kind. A registry with one | ||
| 171 | + /// must ask every client for credentials. | ||
| 172 | + pub async fn owner_has_private_packages(&self, owner_id: &str) -> Result<bool> { | ||
| 173 | + let conn = self.read_conn().await; | ||
| 174 | + let count = fetch_opt( | ||
| 175 | + &conn, | ||
| 176 | + "SELECT COUNT(*) FROM packages WHERE owner_id = ?1 AND private = 1", | ||
| 177 | + (owner_id.to_string(),), | ||
| 178 | + |row| col_int(row, 0), | ||
| 179 | + ) | ||
| 180 | + .await?; | ||
| 181 | + Ok(count.unwrap_or(0) > 0) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// Links a package to a repo on this forge, or unlinks it with `None`. | ||
| 185 | + pub async fn set_package_repo(&self, package_id: &str, repo_id: Option<&str>) -> Result<()> { | ||
| 186 | + let conn = self.inner.conn.lock().await; | ||
| 187 | + conn.execute( | ||
| 188 | + "UPDATE packages SET repo_id = ?2, updated_at = ?3 WHERE id = ?1", | ||
| 189 | + ( | ||
| 190 | + package_id.to_string(), | ||
| 191 | + repo_id.map_or(Value::Null, |id| Value::Text(id.to_string())), | ||
| 192 | + now_stamp(), | ||
| 193 | + ), | ||
| 194 | + ) | ||
| 195 | + .await | ||
| 196 | + .map_err(db_err)?; | ||
| 197 | + Ok(()) | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + /// Sets whether a package is private. | ||
| 201 | + pub async fn set_package_private(&self, package_id: &str, private: bool) -> Result<()> { | ||
| 202 | + let conn = self.inner.conn.lock().await; | ||
| 203 | + conn.execute( | ||
| 204 | + "UPDATE packages SET private = ?2, updated_at = ?3 WHERE id = ?1", | ||
| 205 | + (package_id.to_string(), i64::from(private), now_stamp()), | ||
| 206 | + ) | ||
| 207 | + .await | ||
| 208 | + .map_err(db_err)?; | ||
| 209 | + Ok(()) | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + /// The versions of a package, newest first, yanked ones included. | ||
| 213 | + pub async fn package_versions(&self, package_id: &str) -> Result<Vec<PackageVersion>> { | ||
| 214 | + let conn = self.read_conn().await; | ||
| 215 | + fetch_all( | ||
| 216 | + &conn, | ||
| 217 | + &format!( | ||
| 218 | + "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 \ | ||
| 219 | + ORDER BY {VERSION_ORDER}" | ||
| 220 | + ), | ||
| 221 | + (package_id.to_string(),), | ||
| 222 | + map_version, | ||
| 223 | + ) | ||
| 224 | + .await | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + /// One version of a package. | ||
| 228 | + pub async fn package_version( | ||
| 229 | + &self, | ||
| 230 | + package_id: &str, | ||
| 231 | + version: &str, | ||
| 232 | + ) -> Result<Option<PackageVersion>> { | ||
| 233 | + let conn = self.read_conn().await; | ||
| 234 | + fetch_opt( | ||
| 235 | + &conn, | ||
| 236 | + &format!( | ||
| 237 | + "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 AND version = ?2 \ | ||
| 238 | + LIMIT 1" | ||
| 239 | + ), | ||
| 240 | + (package_id.to_string(), version.to_string()), | ||
| 241 | + map_version, | ||
| 242 | + ) | ||
| 243 | + .await | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + /// Adds a version row. A version that is already published is `Conflict`. The row is | ||
| 247 | + /// written before the bytes, so the caller removes it with [`Store::delete_package_version`] | ||
| 248 | + /// when the blob write fails. | ||
| 249 | + pub async fn publish_package_version( | ||
| 250 | + &self, | ||
| 251 | + new: &NewPackageVersion<'_>, | ||
| 252 | + ) -> Result<PackageVersion> { | ||
| 253 | + let now = now_stamp(); | ||
| 254 | + { | ||
| 255 | + let conn = self.inner.conn.lock().await; | ||
| 256 | + conn.execute( | ||
| 257 | + "INSERT INTO package_versions (id, package_id, version, yanked, checksum, size, \ | ||
| 258 | + index_json, description, readme, publisher_id, created_at) \ | ||
| 259 | + VALUES (?1, ?2, ?3, 0, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", | ||
| 260 | + ( | ||
| 261 | + new_id(), | ||
| 262 | + new.package_id.to_string(), | ||
| 263 | + new.version.to_string(), | ||
| 264 | + new.checksum.to_string(), | ||
| 265 | + i64::try_from(new.size).unwrap_or(i64::MAX), | ||
| 266 | + new.index_json.to_string(), | ||
| 267 | + new.description | ||
| 268 | + .map_or(Value::Null, |d| Value::Text(d.to_string())), | ||
| 269 | + new.readme | ||
| 270 | + .map_or(Value::Null, |r| Value::Text(r.to_string())), | ||
| 271 | + new.publisher_id.to_string(), | ||
| 272 | + now.clone(), | ||
| 273 | + ), | ||
| 274 | + ) | ||
| 275 | + .await | ||
| 276 | + .map_err(|e| insert_err(e, "this version is already published"))?; | ||
| 277 | + conn.execute( | ||
| 278 | + "UPDATE packages SET updated_at = ?2 WHERE id = ?1", | ||
| 279 | + (new.package_id.to_string(), now), | ||
| 280 | + ) | ||
| 281 | + .await | ||
| 282 | + .map_err(db_err)?; | ||
| 283 | + } | ||
| 284 | + self.package_version(new.package_id, new.version) | ||
| 285 | + .await? | ||
| 286 | + .ok_or_else(missing_row) | ||
| 287 | + } | ||
| 288 | + | ||
| 289 | + /// Removes a version row, for when its bytes could not be stored. | ||
| 290 | + pub async fn delete_package_version(&self, package_id: &str, version: &str) -> Result<()> { | ||
| 291 | + let conn = self.inner.conn.lock().await; | ||
| 292 | + conn.execute( | ||
| 293 | + "DELETE FROM package_versions WHERE package_id = ?1 AND version = ?2", | ||
| 294 | + (package_id.to_string(), version.to_string()), | ||
| 295 | + ) | ||
| 296 | + .await | ||
| 297 | + .map_err(db_err)?; | ||
| 298 | + Ok(()) | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + /// Sets the yank state of a version. Returns false when the version does not exist. | ||
| 302 | + pub async fn set_package_version_yanked( | ||
| 303 | + &self, | ||
| 304 | + package_id: &str, | ||
| 305 | + version: &str, | ||
| 306 | + yanked: bool, | ||
| 307 | + ) -> Result<bool> { | ||
| 308 | + let changed = { | ||
| 309 | + let conn = self.inner.conn.lock().await; | ||
| 310 | + conn.execute( | ||
| 311 | + "UPDATE package_versions SET yanked = ?3 WHERE package_id = ?1 AND version = ?2", | ||
| 312 | + ( | ||
| 313 | + package_id.to_string(), | ||
| 314 | + version.to_string(), | ||
| 315 | + i64::from(yanked), | ||
| 316 | + ), | ||
| 317 | + ) | ||
| 318 | + .await | ||
| 319 | + .map_err(db_err)? | ||
| 320 | + }; | ||
| 321 | + if changed == 1 { | ||
| 322 | + let conn = self.inner.conn.lock().await; | ||
| 323 | + conn.execute( | ||
| 324 | + "UPDATE packages SET updated_at = ?2 WHERE id = ?1", | ||
| 325 | + (package_id.to_string(), now_stamp()), | ||
| 326 | + ) | ||
| 327 | + .await | ||
| 328 | + .map_err(db_err)?; | ||
| 329 | + } | ||
| 330 | + Ok(changed == 1) | ||
| 331 | + } | ||
| 332 | +} | ||
crates/forge-core/src/store/web_push.rsmodified+1 -1
| @@ -1,4 +1,4 @@ | |||
| 1 | -//! Web Push (migration 0061): the instance's VAPID key pair and each user's push subscriptions. | 1 | +//! Web Push (migration 0063): the instance's VAPID key pair and each user's push subscriptions. |
| 2 | //! The store keeps the private key sealed; the web crate seals and opens it with the instance key. | 2 | //! The store keeps the private key sealed; the web crate seals and opens it with the instance key. |
| 3 | 3 | ||
| 4 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | 4 | use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; |
crates/forge-web/src/api/mod.rsmodified+24 -10
| @@ -8,6 +8,7 @@ | |||
| 8 | pub mod gitea; | 8 | pub mod gitea; |
| 9 | #[cfg(test)] | 9 | #[cfg(test)] |
| 10 | mod gitea_tests; | 10 | mod gitea_tests; |
| 11 | +pub mod packages; | ||
| 11 | pub mod releases; | 12 | pub mod releases; |
| 12 | pub mod statuses; | 13 | pub mod statuses; |
| 13 | 14 | ||
| @@ -101,6 +102,28 @@ pub async fn authenticate( | |||
| 101 | ip: IpAddr, | 102 | ip: IpAddr, |
| 102 | headers: &HeaderMap, | 103 | headers: &HeaderMap, |
| 103 | ) -> Result<Option<User>, Refusal> { | 104 | ) -> Result<Option<User>, Refusal> { |
| 105 | + let Some((user, token_id, scopes)) = authenticate_token(state, ip, headers).await? else { | ||
| 106 | + return Ok(None); | ||
| 107 | + }; | ||
| 108 | + if !scopes.iter().any(|scope| scope == REPO_SCOPE) { | ||
| 109 | + return Err(Box::new(error( | ||
| 110 | + StatusCode::FORBIDDEN, | ||
| 111 | + "the token lacks the repo scope", | ||
| 112 | + ))); | ||
| 113 | + } | ||
| 114 | + if let Err(e) = state.store.touch_token(&token_id).await { | ||
| 115 | + return Err(internal(e)); | ||
| 116 | + } | ||
| 117 | + Ok(Some(user)) | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// The user a token names, with the token's id and scopes. `None` when the request carries no | ||
| 121 | +/// Authorization header. The scope is not checked and the token is not touched: the caller does both. | ||
| 122 | +pub(crate) async fn authenticate_token( | ||
| 123 | + state: &AppState, | ||
| 124 | + ip: IpAddr, | ||
| 125 | + headers: &HeaderMap, | ||
| 126 | +) -> Result<Option<(User, String, Vec<String>)>, Refusal> { | ||
| 104 | if !headers.contains_key(AUTHORIZATION) { | 127 | if !headers.contains_key(AUTHORIZATION) { |
| 105 | return Ok(None); | 128 | return Ok(None); |
| 106 | } | 129 | } |
| @@ -137,16 +160,7 @@ pub async fn authenticate( | |||
| 137 | } | 160 | } |
| 138 | Err(e) => return Err(internal(e)), | 161 | Err(e) => return Err(internal(e)), |
| 139 | }; | 162 | }; |
| 140 | - if !access.scopes.iter().any(|scope| scope == REPO_SCOPE) { | 163 | + Ok(Some((user, access.id, access.scopes))) |
| 141 | - return Err(Box::new(error( | ||
| 142 | - StatusCode::FORBIDDEN, | ||
| 143 | - "the token lacks the repo scope", | ||
| 144 | - ))); | ||
| 145 | - } | ||
| 146 | - if let Err(e) = state.store.touch_token(&access.id).await { | ||
| 147 | - return Err(internal(e)); | ||
| 148 | - } | ||
| 149 | - Ok(Some(user)) | ||
| 150 | } | 164 | } |
| 151 | 165 | ||
| 152 | /// Maps a refused action. Anonymous callers always get 401, whether the repo is hidden, missing, | 166 | /// Maps a refused action. Anonymous callers always get 401, whether the repo is hidden, missing, |
crates/forge-web/src/api/packages.rsadded+367 -0
| @@ -0,0 +1,367 @@ | |||
| 1 | +//! The Cargo registry protocol under `/api/packages/{owner}/cargo/`: the sparse index and | ||
| 2 | +//! `config.json` that cargo reads, the `.crate` downloads, and the web API that `cargo publish`, | ||
| 3 | +//! `cargo yank` and `cargo owner --list` call. Documented for users in docs/packages.md. | ||
| 4 | +//! | ||
| 5 | +//! Cargo sends the bare token in `Authorization`, so a token with no scheme is accepted here | ||
| 6 | +//! and read as a Bearer token. Reads are public for public packages. Private packages, and any | ||
| 7 | +//! write, need a token with the `packages` scope. Errors use cargo's body, `{"errors":[{"detail":...}]}`. | ||
| 8 | + | ||
| 9 | +use forge_core::User; | ||
| 10 | +use futures_util::StreamExt; | ||
| 11 | +use http::HeaderMap; | ||
| 12 | +use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 13 | +use http_body::Frame; | ||
| 14 | +use http_body_util::StreamBody; | ||
| 15 | +use serde_json::{Value, json}; | ||
| 16 | +use topcoat::context::{Cx, app_context}; | ||
| 17 | +use topcoat::router::request::headers; | ||
| 18 | +use topcoat::router::response::Response; | ||
| 19 | +use topcoat::router::{Body, StatusCode, path_param, route}; | ||
| 20 | + | ||
| 21 | +use crate::api::{self, Refusal}; | ||
| 22 | +use crate::client_ip::client_ip; | ||
| 23 | +use crate::package_ops::{self, PackageError}; | ||
| 24 | +use crate::state::AppState; | ||
| 25 | + | ||
| 26 | +/// The scope a token needs for registry writes and private reads. | ||
| 27 | +pub const PACKAGES_SCOPE: &str = "packages"; | ||
| 28 | + | ||
| 29 | +path_param!(owner); | ||
| 30 | +path_param!(name); | ||
| 31 | +path_param!(version); | ||
| 32 | + | ||
| 33 | +/// The caller of a registry request. Reads with a token that lacks the scope are served as | ||
| 34 | +/// anonymous, so a token made for another purpose cannot break a public install. Writes refuse. | ||
| 35 | +async fn caller(cx: &Cx, scope_required: bool) -> Result<Option<User>, Refusal> { | ||
| 36 | + let state = app_context::<AppState>(cx); | ||
| 37 | + let normalized = bare_token_as_bearer(headers(cx)); | ||
| 38 | + let (user, token_id, scopes) = | ||
| 39 | + match api::authenticate_token(state, client_ip(cx), &normalized).await { | ||
| 40 | + Ok(Some(found)) => found, | ||
| 41 | + Ok(None) => return Ok(None), | ||
| 42 | + Err(refusal) => { | ||
| 43 | + return Err(Box::new(cargo_error( | ||
| 44 | + refusal.status(), | ||
| 45 | + "authentication required", | ||
| 46 | + ))); | ||
| 47 | + } | ||
| 48 | + }; | ||
| 49 | + if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) { | ||
| 50 | + return if scope_required { | ||
| 51 | + Err(Box::new(cargo_error( | ||
| 52 | + StatusCode::FORBIDDEN, | ||
| 53 | + "the token lacks the packages scope", | ||
| 54 | + ))) | ||
| 55 | + } else { | ||
| 56 | + Ok(None) | ||
| 57 | + }; | ||
| 58 | + } | ||
| 59 | + if let Err(e) = state.store.touch_token(&token_id).await { | ||
| 60 | + return Err(Box::new(failure(PackageError::Internal(e.to_string())))); | ||
| 61 | + } | ||
| 62 | + Ok(Some(user)) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// The headers with a bare token rewritten to `Bearer <token>`. Anything with a scheme is left | ||
| 66 | +/// as it was. | ||
| 67 | +fn bare_token_as_bearer(headers: &HeaderMap) -> HeaderMap { | ||
| 68 | + let mut out = headers.clone(); | ||
| 69 | + let bare = headers | ||
| 70 | + .get(AUTHORIZATION) | ||
| 71 | + .and_then(|value| value.to_str().ok()) | ||
| 72 | + .map(str::trim) | ||
| 73 | + .filter(|value| !value.is_empty() && !value.contains(' ')) | ||
| 74 | + .map(str::to_owned); | ||
| 75 | + if let Some(token) = bare | ||
| 76 | + && let Ok(value) = HeaderValue::from_str(&format!("Bearer {token}")) | ||
| 77 | + { | ||
| 78 | + out.insert(AUTHORIZATION, value); | ||
| 79 | + } | ||
| 80 | + out | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// A cargo-style error response. | ||
| 84 | +fn cargo_error(status: StatusCode, detail: &str) -> Response { | ||
| 85 | + api::json(status, &json!({ "errors": [{ "detail": detail }] })) | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Maps a registry failure to its status and cargo error body. | ||
| 89 | +fn failure(e: PackageError) -> Response { | ||
| 90 | + match e { | ||
| 91 | + PackageError::Invalid(msg) => cargo_error(StatusCode::BAD_REQUEST, &msg), | ||
| 92 | + PackageError::NotFound => cargo_error(StatusCode::NOT_FOUND, "not found"), | ||
| 93 | + PackageError::Forbidden => cargo_error( | ||
| 94 | + StatusCode::FORBIDDEN, | ||
| 95 | + "you do not have permission to publish to this registry", | ||
| 96 | + ), | ||
| 97 | + PackageError::Conflict(msg) => cargo_error(StatusCode::CONFLICT, &msg), | ||
| 98 | + PackageError::TooLarge => cargo_error( | ||
| 99 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 100 | + "the crate is larger than the registry accepts", | ||
| 101 | + ), | ||
| 102 | + PackageError::Internal(cause) => { | ||
| 103 | + tracing::error!(error = %cause, "package request failed"); | ||
| 104 | + cargo_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error") | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// A plain text response, used for index files. | ||
| 110 | +fn text(body: String) -> Response { | ||
| 111 | + let mut res = Response::new(Body::from(body)); | ||
| 112 | + *res.status_mut() = StatusCode::OK; | ||
| 113 | + res.headers_mut().insert( | ||
| 114 | + CONTENT_TYPE, | ||
| 115 | + HeaderValue::from_static("text/plain; charset=utf-8"), | ||
| 116 | + ); | ||
| 117 | + res | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Loads the registry owner named in the path, as the caller may see it. A missing owner is 404. | ||
| 121 | +async fn owner_of(cx: &Cx) -> Result<User, Refusal> { | ||
| 122 | + let state = app_context::<AppState>(cx); | ||
| 123 | + match package_ops::owner_named(state, path_param::<Owner>(cx)).await { | ||
| 124 | + Ok(Some(found)) => Ok(found), | ||
| 125 | + Ok(_) => Err(Box::new(failure(PackageError::NotFound))), | ||
| 126 | + Err(e) => Err(Box::new(failure(e))), | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +#[route(GET "/api/packages/{owner}/cargo/config.json")] | ||
| 131 | +async fn config(cx: &Cx) -> topcoat::Result<Response> { | ||
| 132 | + let state = app_context::<AppState>(cx); | ||
| 133 | + if let Err(res) = caller(cx, false).await { | ||
| 134 | + return Ok(*res); | ||
| 135 | + } | ||
| 136 | + let owner = match owner_of(cx).await { | ||
| 137 | + Ok(owner) => owner, | ||
| 138 | + Err(res) => return Ok(*res), | ||
| 139 | + }; | ||
| 140 | + match package_ops::config_json(state, &owner).await { | ||
| 141 | + Ok(value) => Ok(api::json(StatusCode::OK, &value)), | ||
| 142 | + Err(e) => Ok(failure(e)), | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// The index file of a one-letter crate. | ||
| 147 | +#[route(GET "/api/packages/{owner}/cargo/1/{name}")] | ||
| 148 | +async fn index_one(cx: &Cx) -> topcoat::Result<Response> { | ||
| 149 | + Ok(index_response(cx).await) | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/// The index file of a two-letter crate. | ||
| 153 | +#[route(GET "/api/packages/{owner}/cargo/2/{name}")] | ||
| 154 | +async fn index_two(cx: &Cx) -> topcoat::Result<Response> { | ||
| 155 | + Ok(index_response(cx).await) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// The index file of a crate with three or more letters. The prefix segments are derived from | ||
| 159 | +/// the name, so only the name is looked up. | ||
| 160 | +#[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")] | ||
| 161 | +async fn index_long(cx: &Cx) -> topcoat::Result<Response> { | ||
| 162 | + Ok(index_response(cx).await) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +async fn index_response(cx: &Cx) -> Response { | ||
| 166 | + let state = app_context::<AppState>(cx); | ||
| 167 | + let actor = match caller(cx, false).await { | ||
| 168 | + Ok(actor) => actor, | ||
| 169 | + Err(res) => return *res, | ||
| 170 | + }; | ||
| 171 | + let owner = match owner_of(cx).await { | ||
| 172 | + Ok(owner) => owner, | ||
| 173 | + Err(res) => return *res, | ||
| 174 | + }; | ||
| 175 | + let package = | ||
| 176 | + match package_ops::readable_package(state, actor.as_ref(), &owner, path_param::<Name>(cx)) | ||
| 177 | + .await | ||
| 178 | + { | ||
| 179 | + Ok(package) => package, | ||
| 180 | + Err(e) => return failure(e), | ||
| 181 | + }; | ||
| 182 | + match package_ops::index_file(state, &package).await { | ||
| 183 | + Ok(body) => text(body), | ||
| 184 | + Err(e) => failure(e), | ||
| 185 | + } | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +/// The `.crate` file of one version, streamed from the blob store. | ||
| 189 | +#[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")] | ||
| 190 | +async fn download(cx: &Cx) -> topcoat::Result<Response> { | ||
| 191 | + let state = app_context::<AppState>(cx); | ||
| 192 | + let actor = match caller(cx, false).await { | ||
| 193 | + Ok(actor) => actor, | ||
| 194 | + Err(res) => return Ok(*res), | ||
| 195 | + }; | ||
| 196 | + let owner = match owner_of(cx).await { | ||
| 197 | + Ok(owner) => owner, | ||
| 198 | + Err(res) => return Ok(*res), | ||
| 199 | + }; | ||
| 200 | + let read = match package_ops::download( | ||
| 201 | + state, | ||
| 202 | + actor.as_ref(), | ||
| 203 | + &owner, | ||
| 204 | + path_param::<Name>(cx), | ||
| 205 | + path_param::<Version>(cx), | ||
| 206 | + ) | ||
| 207 | + .await | ||
| 208 | + { | ||
| 209 | + Ok(read) => read, | ||
| 210 | + Err(e) => return Ok(failure(e)), | ||
| 211 | + }; | ||
| 212 | + let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); | ||
| 213 | + let mut res = Response::new(Body::new(StreamBody::new(chunks))); | ||
| 214 | + *res.status_mut() = StatusCode::OK; | ||
| 215 | + res.headers_mut().insert( | ||
| 216 | + CONTENT_TYPE, | ||
| 217 | + HeaderValue::from_static("application/octet-stream"), | ||
| 218 | + ); | ||
| 219 | + res.headers_mut() | ||
| 220 | + .insert(CONTENT_LENGTH, HeaderValue::from(read.size)); | ||
| 221 | + Ok(res) | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// `cargo publish`. The body is the publish format: a length-prefixed JSON document and a | ||
| 225 | +/// length-prefixed `.crate`. It is read whole, up to the publish limit. | ||
| 226 | +#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] | ||
| 227 | +async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 228 | + let state = app_context::<AppState>(cx); | ||
| 229 | + let actor = match caller(cx, true).await { | ||
| 230 | + Ok(Some(actor)) => actor, | ||
| 231 | + Ok(None) => { | ||
| 232 | + return Ok(cargo_error( | ||
| 233 | + StatusCode::UNAUTHORIZED, | ||
| 234 | + "authentication required", | ||
| 235 | + )); | ||
| 236 | + } | ||
| 237 | + Err(res) => return Ok(*res), | ||
| 238 | + }; | ||
| 239 | + let owner = match owner_of(cx).await { | ||
| 240 | + Ok(owner) => owner, | ||
| 241 | + Err(res) => return Ok(*res), | ||
| 242 | + }; | ||
| 243 | + let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await { | ||
| 244 | + Ok(bytes) => bytes, | ||
| 245 | + Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))), | ||
| 246 | + }; | ||
| 247 | + match package_ops::publish(state, &owner, &actor, &bytes).await { | ||
| 248 | + Ok(()) => Ok(api::json( | ||
| 249 | + StatusCode::OK, | ||
| 250 | + &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }), | ||
| 251 | + )), | ||
| 252 | + Err(e) => Ok(failure(e)), | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +fn read_failure(e: &impl std::fmt::Display) -> String { | ||
| 257 | + format!("the request body could not be read: {e}") | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +/// `cargo yank`: marks a version yanked. It stays in the index and downloadable. | ||
| 261 | +#[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")] | ||
| 262 | +async fn yank(cx: &Cx) -> topcoat::Result<Response> { | ||
| 263 | + set_yank(cx, true).await | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +/// `cargo yank --undo`. | ||
| 267 | +#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")] | ||
| 268 | +async fn unyank(cx: &Cx) -> topcoat::Result<Response> { | ||
| 269 | + set_yank(cx, false).await | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> { | ||
| 273 | + let state = app_context::<AppState>(cx); | ||
| 274 | + let actor = match caller(cx, true).await { | ||
| 275 | + Ok(Some(actor)) => actor, | ||
| 276 | + Ok(None) => { | ||
| 277 | + return Ok(cargo_error( | ||
| 278 | + StatusCode::UNAUTHORIZED, | ||
| 279 | + "authentication required", | ||
| 280 | + )); | ||
| 281 | + } | ||
| 282 | + Err(res) => return Ok(*res), | ||
| 283 | + }; | ||
| 284 | + let owner = match owner_of(cx).await { | ||
| 285 | + Ok(owner) => owner, | ||
| 286 | + Err(res) => return Ok(*res), | ||
| 287 | + }; | ||
| 288 | + match package_ops::set_yanked( | ||
| 289 | + state, | ||
| 290 | + &owner, | ||
| 291 | + &actor, | ||
| 292 | + path_param::<Name>(cx), | ||
| 293 | + path_param::<Version>(cx), | ||
| 294 | + yanked, | ||
| 295 | + ) | ||
| 296 | + .await | ||
| 297 | + { | ||
| 298 | + Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))), | ||
| 299 | + Err(e) => Ok(failure(e)), | ||
| 300 | + } | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +/// `cargo owner --list`: the people who may publish. For a user registry that is the user; for | ||
| 304 | +/// an org, its owners. Read-only: adding or removing owners is done in the forge. | ||
| 305 | +#[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")] | ||
| 306 | +async fn owners(cx: &Cx) -> topcoat::Result<Response> { | ||
| 307 | + let state = app_context::<AppState>(cx); | ||
| 308 | + let actor = match caller(cx, false).await { | ||
| 309 | + Ok(actor) => actor, | ||
| 310 | + Err(res) => return Ok(*res), | ||
| 311 | + }; | ||
| 312 | + let owner = match owner_of(cx).await { | ||
| 313 | + Ok(owner) => owner, | ||
| 314 | + Err(res) => return Ok(*res), | ||
| 315 | + }; | ||
| 316 | + if let Err(e) = | ||
| 317 | + package_ops::readable_package(state, actor.as_ref(), &owner, path_param::<Name>(cx)).await | ||
| 318 | + { | ||
| 319 | + return Ok(failure(e)); | ||
| 320 | + } | ||
| 321 | + let people: Vec<User> = if owner.is_org() { | ||
| 322 | + match state.store.org_members(&owner.id).await { | ||
| 323 | + Ok(members) => members | ||
| 324 | + .into_iter() | ||
| 325 | + .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner) | ||
| 326 | + .map(|(user, _)| user) | ||
| 327 | + .collect(), | ||
| 328 | + Err(e) => return Ok(failure(e.into())), | ||
| 329 | + } | ||
| 330 | + } else { | ||
| 331 | + vec![owner.clone()] | ||
| 332 | + }; | ||
| 333 | + let users: Vec<Value> = people | ||
| 334 | + .iter() | ||
| 335 | + .map(|user| { | ||
| 336 | + json!({ | ||
| 337 | + "id": user.id, | ||
| 338 | + "login": user.username, | ||
| 339 | + "name": user.display_name, | ||
| 340 | + "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username), | ||
| 341 | + }) | ||
| 342 | + }) | ||
| 343 | + .collect(); | ||
| 344 | + Ok(api::json(StatusCode::OK, &json!({ "users": users }))) | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +#[cfg(test)] | ||
| 348 | +mod tests { | ||
| 349 | + use http::HeaderValue; | ||
| 350 | + | ||
| 351 | + use super::*; | ||
| 352 | + | ||
| 353 | + #[test] | ||
| 354 | + fn a_bare_token_becomes_a_bearer_token() { | ||
| 355 | + let mut headers = HeaderMap::new(); | ||
| 356 | + headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc")); | ||
| 357 | + let rewritten = bare_token_as_bearer(&headers); | ||
| 358 | + assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc"); | ||
| 359 | + | ||
| 360 | + let mut bearer = HeaderMap::new(); | ||
| 361 | + bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc")); | ||
| 362 | + assert_eq!( | ||
| 363 | + bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(), | ||
| 364 | + "Bearer forge_abc" | ||
| 365 | + ); | ||
| 366 | + } | ||
| 367 | +} | ||
crates/forge-web/src/blobs.rsmodified+9 -0
| @@ -178,6 +178,15 @@ impl BlobStore { | |||
| 178 | } | 178 | } |
| 179 | } | 179 | } |
| 180 | 180 | ||
| 181 | + /// True when `key` holds a blob. Reads only the metadata, not the bytes. | ||
| 182 | + pub async fn exists(&self, key: &str) -> Result<bool> { | ||
| 183 | + match self.store.head(&ObjectPath::from(key)).await { | ||
| 184 | + Ok(_) => Ok(true), | ||
| 185 | + Err(object_store::Error::NotFound { .. }) => Ok(false), | ||
| 186 | + Err(e) => Err(storage_err(e)), | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + | ||
| 181 | /// Moves `from` to `to`, replacing `to`. Used to give a finished upload its final key. | 190 | /// Moves `from` to `to`, replacing `to`. Used to give a finished upload its final key. |
| 182 | pub async fn rename(&self, from: &str, to: &str) -> Result<()> { | 191 | pub async fn rename(&self, from: &str, to: &str) -> Result<()> { |
| 183 | self.store | 192 | self.store |
crates/forge-web/src/boot.rsmodified+1 -0
| @@ -136,6 +136,7 @@ pub async fn serve( | |||
| 136 | ci_live: Arc::new(crate::ci::CiLive::default()), | 136 | ci_live: Arc::new(crate::ci::CiLive::default()), |
| 137 | live: Arc::new(crate::live::LiveHub::default()), | 137 | live: Arc::new(crate::live::LiveHub::default()), |
| 138 | push_live: Arc::new(crate::web_push::PushLive::default()), | 138 | push_live: Arc::new(crate::web_push::PushLive::default()), |
| 139 | + packages_live: Arc::new(crate::packages_live::PackagesLive::default()), | ||
| 139 | }; | 140 | }; |
| 140 | if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { | 141 | if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { |
| 141 | tracing::error!(error = %e, "building the SSH allowed-signers file failed"); | 142 | tracing::error!(error = %e, "building the SSH allowed-signers file failed"); |
crates/forge-web/src/i18n/mod.rsmodified+1 -0
| @@ -32,6 +32,7 @@ pub mod merge_queue; | |||
| 32 | pub mod migrate; | 32 | pub mod migrate; |
| 33 | pub mod misc; | 33 | pub mod misc; |
| 34 | pub mod orgs; | 34 | pub mod orgs; |
| 35 | +pub mod packages; | ||
| 35 | pub mod pulls; | 36 | pub mod pulls; |
| 36 | pub mod pulls_review; | 37 | pub mod pulls_review; |
| 37 | pub mod push; | 38 | pub mod push; |
crates/forge-web/src/i18n/packages.rsadded+141 -0
| @@ -0,0 +1,141 @@ | |||
| 1 | +//! Strings for the package registry pages: the Packages tab, the package page, the install | ||
| 2 | +//! snippet and the token scope. One variant per phrase and an exhaustive `t` match. | ||
| 3 | + | ||
| 4 | +use super::Lang; | ||
| 5 | + | ||
| 6 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 7 | +pub enum K { | ||
| 8 | + TabPackages, | ||
| 9 | + PackagesHeading, | ||
| 10 | + PackagesHelp, | ||
| 11 | + NoPackages, | ||
| 12 | + PackageVersions, | ||
| 13 | + PackageVersionCount, | ||
| 14 | + PackageVersionCountOne, | ||
| 15 | + PackagePrivate, | ||
| 16 | + PackageRepoLink, | ||
| 17 | + VersionYanked, | ||
| 18 | + Install, | ||
| 19 | + InstallHelp, | ||
| 20 | + InstallRegistryConfig, | ||
| 21 | + InstallAdd, | ||
| 22 | + InstallPublish, | ||
| 23 | + InstallLogin, | ||
| 24 | + CopyCommand, | ||
| 25 | + Readme, | ||
| 26 | + NoReadme, | ||
| 27 | + ScopePackages, | ||
| 28 | + ScopePackagesHelp, | ||
| 29 | + Cancel, | ||
| 30 | + ContainerKind, | ||
| 31 | + ContainerInstallHelp, | ||
| 32 | + ContainerLogin, | ||
| 33 | + ContainerPull, | ||
| 34 | + ContainerPush, | ||
| 35 | + ContainerTags, | ||
| 36 | + ContainerTag, | ||
| 37 | + ContainerDigest, | ||
| 38 | + ContainerSize, | ||
| 39 | + ContainerCreated, | ||
| 40 | + DeleteTag, | ||
| 41 | + DeleteTagMessage, | ||
| 42 | + DeleteTagConfirm, | ||
| 43 | + NoTags, | ||
| 44 | + PackageTagCount, | ||
| 45 | + PackageTagCountOne, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 49 | + use K::*; | ||
| 50 | + use Lang::*; | ||
| 51 | + match (key, lang) { | ||
| 52 | + (Cancel, En) => "Cancel", | ||
| 53 | + (Cancel, Tr) => "Vazgeç", | ||
| 54 | + (ContainerKind, En) => "Container", | ||
| 55 | + (ContainerKind, Tr) => "Konteyner", | ||
| 56 | + (ContainerInstallHelp, En) => { | ||
| 57 | + "Log in with your username and a personal access token that has the packages scope." | ||
| 58 | + } | ||
| 59 | + (ContainerInstallHelp, Tr) => { | ||
| 60 | + "Kullanıcı adınız ve packages kapsamına sahip bir kişisel erişim belirteciyle giriş yapın." | ||
| 61 | + } | ||
| 62 | + (ContainerLogin, En) => "Log in", | ||
| 63 | + (ContainerLogin, Tr) => "Giriş yap", | ||
| 64 | + (ContainerPull, En) => "Pull the image", | ||
| 65 | + (ContainerPull, Tr) => "İmajı çek", | ||
| 66 | + (ContainerPush, En) => "Push a tag", | ||
| 67 | + (ContainerPush, Tr) => "Bir etiket gönder", | ||
| 68 | + (ContainerTags, En) => "Tags", | ||
| 69 | + (ContainerTags, Tr) => "Etiketler", | ||
| 70 | + (ContainerTag, En) => "Tag", | ||
| 71 | + (ContainerTag, Tr) => "Etiket", | ||
| 72 | + (ContainerDigest, En) => "Digest", | ||
| 73 | + (ContainerDigest, Tr) => "Özet", | ||
| 74 | + (ContainerSize, En) => "Size", | ||
| 75 | + (ContainerSize, Tr) => "Boyut", | ||
| 76 | + (ContainerCreated, En) => "Created", | ||
| 77 | + (ContainerCreated, Tr) => "Oluşturuldu", | ||
| 78 | + (DeleteTag, En) => "Delete", | ||
| 79 | + (DeleteTag, Tr) => "Sil", | ||
| 80 | + (DeleteTagMessage, En) => "Delete this tag? An image left with no tag is removed too.", | ||
| 81 | + (DeleteTagMessage, Tr) => "Bu etiket silinsin mi? Etiketsiz kalan imaj da kaldırılır.", | ||
| 82 | + (DeleteTagConfirm, En) => "Yes, delete", | ||
| 83 | + (DeleteTagConfirm, Tr) => "Evet, sil", | ||
| 84 | + (NoTags, En) => "No tags yet. Push an image to see it here.", | ||
| 85 | + (NoTags, Tr) => "Henüz etiket yok. Burada görmek için bir imaj gönderin.", | ||
| 86 | + (PackageTagCount, En) => "tags", | ||
| 87 | + (PackageTagCount, Tr) => "etiket", | ||
| 88 | + (PackageTagCountOne, En) => "tag", | ||
| 89 | + (PackageTagCountOne, Tr) => "etiket", | ||
| 90 | + (TabPackages, En) => "Packages", | ||
| 91 | + (TabPackages, Tr) => "Paketler", | ||
| 92 | + (PackagesHeading, En) => "Packages", | ||
| 93 | + (PackagesHeading, Tr) => "Paketler", | ||
| 94 | + (PackagesHelp, En) => "Packages this owner publishes: Cargo crates and container images.", | ||
| 95 | + (PackagesHelp, Tr) => { | ||
| 96 | + "Bu sahibin yayımladığı paketler: Cargo crate'leri ve konteyner imajları." | ||
| 97 | + } | ||
| 98 | + (NoPackages, En) => "No packages yet.", | ||
| 99 | + (NoPackages, Tr) => "Henüz paket yok.", | ||
| 100 | + (PackageVersions, En) => "Versions", | ||
| 101 | + (PackageVersions, Tr) => "Sürümler", | ||
| 102 | + (PackageVersionCount, En) => "versions", | ||
| 103 | + (PackageVersionCount, Tr) => "sürüm", | ||
| 104 | + (PackageVersionCountOne, En) => "version", | ||
| 105 | + (PackageVersionCountOne, Tr) => "sürüm", | ||
| 106 | + (PackagePrivate, En) => "Private", | ||
| 107 | + (PackagePrivate, Tr) => "Özel", | ||
| 108 | + (PackageRepoLink, En) => "Repository", | ||
| 109 | + (PackageRepoLink, Tr) => "Depo", | ||
| 110 | + (VersionYanked, En) => "yanked", | ||
| 111 | + (VersionYanked, Tr) => "geri çekildi", | ||
| 112 | + (Install, En) => "Install", | ||
| 113 | + (Install, Tr) => "Kurulum", | ||
| 114 | + (InstallHelp, En) => "Add this registry to your Cargo config, then add the crate.", | ||
| 115 | + (InstallHelp, Tr) => { | ||
| 116 | + "Bu kayıt defterini Cargo yapılandırmanıza ekleyin, sonra crate'i ekleyin." | ||
| 117 | + } | ||
| 118 | + (InstallRegistryConfig, En) => "Registry config", | ||
| 119 | + (InstallRegistryConfig, Tr) => "Kayıt defteri yapılandırması", | ||
| 120 | + (InstallAdd, En) => "Add the crate", | ||
| 121 | + (InstallAdd, Tr) => "Crate'i ekle", | ||
| 122 | + (InstallPublish, En) => "Publish", | ||
| 123 | + (InstallPublish, Tr) => "Yayımla", | ||
| 124 | + (InstallLogin, En) => "Log in with a token", | ||
| 125 | + (InstallLogin, Tr) => "Bir belirteçle giriş yapın", | ||
| 126 | + (CopyCommand, En) => "Copy", | ||
| 127 | + (CopyCommand, Tr) => "Kopyala", | ||
| 128 | + (Readme, En) => "README", | ||
| 129 | + (Readme, Tr) => "README", | ||
| 130 | + (NoReadme, En) => "This crate has no README.", | ||
| 131 | + (NoReadme, Tr) => "Bu crate'in README'si yok.", | ||
| 132 | + (ScopePackages, En) => "Packages", | ||
| 133 | + (ScopePackages, Tr) => "Paketler", | ||
| 134 | + (ScopePackagesHelp, En) => { | ||
| 135 | + "Read private packages, publish, yank and unyank crates in the owner's registry." | ||
| 136 | + } | ||
| 137 | + (ScopePackagesHelp, Tr) => { | ||
| 138 | + "Özel paketleri okuma, sahibin kayıt defterine crate yayımlama, geri çekme ve geri alma." | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | +} | ||
crates/forge-web/src/main.rsmodified+3 -0
| @@ -39,6 +39,9 @@ mod merge_queue; | |||
| 39 | mod mirrors; | 39 | mod mirrors; |
| 40 | mod notify; | 40 | mod notify; |
| 41 | mod notify_hub; | 41 | mod notify_hub; |
| 42 | +mod oci; | ||
| 43 | +mod package_ops; | ||
| 44 | +mod packages_live; | ||
| 42 | mod pages; | 45 | mod pages; |
| 43 | mod post_update; | 46 | mod post_update; |
| 44 | mod pulls_sync; | 47 | mod pulls_sync; |
crates/forge-web/src/oci/auth.rsadded+217 -0
| @@ -0,0 +1,217 @@ | |||
| 1 | +//! Who may use the container registry, and the challenge that asks a client for credentials. | ||
| 2 | +//! | ||
| 3 | +//! A request may carry no credentials (anonymous), a personal access token as HTTP Basic or as a | ||
| 4 | +//! Bearer token (the `packages` scope is needed for anything but public reads), or a short-lived | ||
| 5 | +//! bearer token that `GET /v2/token` issued. Permissions are checked on every request against the | ||
| 6 | +//! identity, so a bearer token only names who is calling and expires quickly. | ||
| 7 | + | ||
| 8 | +use forge_core::User; | ||
| 9 | +use forge_core::oci as rules; | ||
| 10 | +use forge_core::packages::{KIND_OCI, Package}; | ||
| 11 | +use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; | ||
| 12 | +use topcoat::context::{Cx, app_context}; | ||
| 13 | +use topcoat::router::StatusCode; | ||
| 14 | +use topcoat::router::request::headers; | ||
| 15 | +use topcoat::router::response::Response; | ||
| 16 | + | ||
| 17 | +use super::oci_error; | ||
| 18 | +use crate::api::{self, Refusal}; | ||
| 19 | +use crate::client_ip::client_ip; | ||
| 20 | +use crate::package_ops::{self, PackageError}; | ||
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +/// Lifetime of a bearer token from `GET /v2/token`, in seconds. | ||
| 24 | +pub const TOKEN_TTL_SECS: i64 = 300; | ||
| 25 | + | ||
| 26 | +/// The scope the challenge names for a repository. | ||
| 27 | +const ACTIONS: &str = "pull,push"; | ||
| 28 | + | ||
| 29 | +/// The caller of a registry request. `user` is `None` for anonymous callers. | ||
| 30 | +pub struct Caller { | ||
| 31 | + pub user: Option<User>, | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// The repository a request names, as its owner and package stand now. | ||
| 35 | +pub struct Target { | ||
| 36 | + pub owner: User, | ||
| 37 | + pub image: String, | ||
| 38 | + pub package: Option<Package>, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// Resolves the caller from the `Authorization` header. A bearer token this forge issued is | ||
| 42 | +/// verified here; anything else goes to the personal access token check the API uses. A bad | ||
| 43 | +/// credential is a 401 with the challenge, so the client can ask again. | ||
| 44 | +pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> { | ||
| 45 | + let state = app_context::<AppState>(cx); | ||
| 46 | + let headers = headers(cx); | ||
| 47 | + let Some(value) = headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()) else { | ||
| 48 | + return Ok(Caller { user: None }); | ||
| 49 | + }; | ||
| 50 | + if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) | ||
| 51 | + && !bearer.starts_with("forge_") | ||
| 52 | + { | ||
| 53 | + let now = unix_now(); | ||
| 54 | + return match rules::verify_token(&state.key, bearer, now) { | ||
| 55 | + Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { | ||
| 56 | + Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), | ||
| 57 | + Ok(_) => Err(Box::new(challenge(state, None))), | ||
| 58 | + Err(e) => Err(Box::new(internal(e))), | ||
| 59 | + }, | ||
| 60 | + Some(None) => Ok(Caller { user: None }), | ||
| 61 | + None => Err(Box::new(challenge(state, None))), | ||
| 62 | + }; | ||
| 63 | + } | ||
| 64 | + match api::authenticate_token(state, client_ip(cx), headers).await { | ||
| 65 | + Ok(Some((user, token_id, scopes))) => { | ||
| 66 | + if !scopes | ||
| 67 | + .iter() | ||
| 68 | + .any(|s| s == crate::api::packages::PACKAGES_SCOPE) | ||
| 69 | + { | ||
| 70 | + return Ok(Caller { user: None }); | ||
| 71 | + } | ||
| 72 | + if let Err(e) = state.store.touch_token(&token_id).await { | ||
| 73 | + return Err(Box::new(internal(e))); | ||
| 74 | + } | ||
| 75 | + Ok(Caller { user: Some(user) }) | ||
| 76 | + } | ||
| 77 | + Ok(None) => Ok(Caller { user: None }), | ||
| 78 | + Err(_) => Err(Box::new(challenge(state, None))), | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Resolves the repository `name` for `caller`. A write needs the owner, an org owner, or the | ||
| 83 | +/// instance admin, and a signed-in caller. A read of a missing or private image is refused | ||
| 84 | +/// without saying which: anonymous callers get the challenge, signed-in ones 404 or 403. | ||
| 85 | +pub async fn authorize( | ||
| 86 | + state: &AppState, | ||
| 87 | + caller: &Caller, | ||
| 88 | + name: &str, | ||
| 89 | + write: bool, | ||
| 90 | +) -> Result<Target, Refusal> { | ||
| 91 | + let Some((owner_name, image)) = rules::split_repo_name(name) else { | ||
| 92 | + return Err(Box::new(oci_error( | ||
| 93 | + StatusCode::BAD_REQUEST, | ||
| 94 | + "NAME_INVALID", | ||
| 95 | + "invalid repository name", | ||
| 96 | + ))); | ||
| 97 | + }; | ||
| 98 | + let anonymous = caller.user.is_none(); | ||
| 99 | + if write && anonymous { | ||
| 100 | + return Err(Box::new(challenge(state, Some(name)))); | ||
| 101 | + } | ||
| 102 | + let owner = state | ||
| 103 | + .store | ||
| 104 | + .user_by_username(owner_name) | ||
| 105 | + .await | ||
| 106 | + .map_err(internal)?; | ||
| 107 | + let Some(owner) = owner else { | ||
| 108 | + return Err(Box::new(if anonymous { | ||
| 109 | + challenge(state, Some(name)) | ||
| 110 | + } else { | ||
| 111 | + oci_error( | ||
| 112 | + StatusCode::NOT_FOUND, | ||
| 113 | + "NAME_UNKNOWN", | ||
| 114 | + "repository name not known to registry", | ||
| 115 | + ) | ||
| 116 | + })); | ||
| 117 | + }; | ||
| 118 | + let package = state | ||
| 119 | + .store | ||
| 120 | + .package_by_name(&owner.id, KIND_OCI, image) | ||
| 121 | + .await | ||
| 122 | + .map_err(internal)?; | ||
| 123 | + let target = Target { | ||
| 124 | + owner: owner.clone(), | ||
| 125 | + image: image.to_owned(), | ||
| 126 | + package: package.clone(), | ||
| 127 | + }; | ||
| 128 | + if write { | ||
| 129 | + let user = caller.user.as_ref().expect("checked above"); | ||
| 130 | + if !package_ops::may_publish(state, user, &owner) | ||
| 131 | + .await | ||
| 132 | + .map_err(package_failure)? | ||
| 133 | + { | ||
| 134 | + return Err(Box::new(denied())); | ||
| 135 | + } | ||
| 136 | + return Ok(target); | ||
| 137 | + } | ||
| 138 | + match package { | ||
| 139 | + Some(package) => { | ||
| 140 | + let readable = package_ops::may_read(state, caller.user.as_ref(), &owner, &package) | ||
| 141 | + .await | ||
| 142 | + .map_err(package_failure)?; | ||
| 143 | + if readable { | ||
| 144 | + Ok(target) | ||
| 145 | + } else if anonymous { | ||
| 146 | + Err(Box::new(challenge(state, Some(name)))) | ||
| 147 | + } else { | ||
| 148 | + Err(Box::new(denied())) | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | + None if anonymous => Err(Box::new(challenge(state, Some(name)))), | ||
| 152 | + None => Err(Box::new(oci_error( | ||
| 153 | + StatusCode::NOT_FOUND, | ||
| 154 | + "NAME_UNKNOWN", | ||
| 155 | + "repository name not known to registry", | ||
| 156 | + ))), | ||
| 157 | + } | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when | ||
| 161 | +/// the request names one. | ||
| 162 | +pub fn challenge(state: &AppState, name: Option<&str>) -> Response { | ||
| 163 | + let base = state.config.base_url.trim_end_matches('/'); | ||
| 164 | + let host = base.split_once("://").map_or(base, |(_, rest)| rest); | ||
| 165 | + let mut value = format!("Bearer realm=\"{base}/v2/token\",service=\"{host}\""); | ||
| 166 | + if let Some(name) = name { | ||
| 167 | + value.push_str(&format!(",scope=\"repository:{name}:{ACTIONS}\"")); | ||
| 168 | + } | ||
| 169 | + let mut res = oci_error( | ||
| 170 | + StatusCode::UNAUTHORIZED, | ||
| 171 | + "UNAUTHORIZED", | ||
| 172 | + "authentication required", | ||
| 173 | + ); | ||
| 174 | + if let Ok(header) = HeaderValue::from_str(&value) { | ||
| 175 | + res.headers_mut().insert(WWW_AUTHENTICATE, header); | ||
| 176 | + } | ||
| 177 | + res | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// The 403 for a signed-in caller who may not do the thing. | ||
| 181 | +pub fn denied() -> Response { | ||
| 182 | + oci_error( | ||
| 183 | + StatusCode::FORBIDDEN, | ||
| 184 | + "DENIED", | ||
| 185 | + "requested access to the resource is denied", | ||
| 186 | + ) | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// Logs an internal failure and answers 500 in the registry's error body. | ||
| 190 | +pub fn internal(error: impl std::fmt::Display) -> Response { | ||
| 191 | + tracing::error!(error = %error, "oci request failed"); | ||
| 192 | + oci_error( | ||
| 193 | + StatusCode::INTERNAL_SERVER_ERROR, | ||
| 194 | + "UNKNOWN", | ||
| 195 | + "internal server error", | ||
| 196 | + ) | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// Maps a package permission failure to a refusal. | ||
| 200 | +pub fn package_failure(error: PackageError) -> Refusal { | ||
| 201 | + match error { | ||
| 202 | + PackageError::Internal(cause) => Box::new(internal(cause)), | ||
| 203 | + _ => Box::new(denied()), | ||
| 204 | + } | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +/// Logs an internal failure and boxes the 500 as a refusal. | ||
| 208 | +pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal { | ||
| 209 | + Box::new(internal(error)) | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +/// The current time in seconds since the epoch. | ||
| 213 | +pub fn unix_now() -> i64 { | ||
| 214 | + std::time::SystemTime::now() | ||
| 215 | + .duration_since(std::time::UNIX_EPOCH) | ||
| 216 | + .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) | ||
| 217 | +} | ||
crates/forge-web/src/oci/blobs.rsadded+458 -0
| @@ -0,0 +1,458 @@ | |||
| 1 | +//! Blobs of the container registry: upload sessions, the digest check, the blob store writes, and | ||
| 2 | +//! the blob reads. | ||
| 3 | +//! | ||
| 4 | +//! An upload session is a temp file under `<data_dir>/oci/uploads`, named by a ULID, with a | ||
| 5 | +//! sidecar `<id>.repo` that names the repository it belongs to. Chunks are appended to it. When | ||
| 6 | +//! the client finishes, the file's sha256 must match the digest it names; then the bytes move into | ||
| 7 | +//! the blob store under `oci/<hex>`, shared by every package that links the digest. A session that | ||
| 8 | +//! is never finished is removed once it is a day old; the check runs when a new session starts, so | ||
| 9 | +//! no timer is needed. | ||
| 10 | + | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | +use std::time::{Duration, SystemTime}; | ||
| 13 | + | ||
| 14 | +use forge_core::oci as rules; | ||
| 15 | +use forge_core::packages::{KIND_OCI, Package}; | ||
| 16 | +use futures_util::StreamExt; | ||
| 17 | +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 18 | +use http_body::Frame; | ||
| 19 | +use http_body_util::StreamBody; | ||
| 20 | +use sha2::{Digest, Sha256}; | ||
| 21 | +use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
| 22 | +use topcoat::router::response::Response; | ||
| 23 | +use topcoat::router::{Body, StatusCode}; | ||
| 24 | + | ||
| 25 | +use super::auth::{self, Caller, Target, internal, internal_refusal}; | ||
| 26 | +use super::{gc, oci_error}; | ||
| 27 | +use crate::api::Refusal; | ||
| 28 | +use crate::state::AppState; | ||
| 29 | + | ||
| 30 | +/// Largest blob accepted, in bytes. | ||
| 31 | +pub const MAX_BLOB_BYTES: u64 = 10 * 1024 * 1024 * 1024; | ||
| 32 | +/// Bytes read from a temp file at a time. | ||
| 33 | +const CHUNK: usize = 1024 * 1024; | ||
| 34 | +/// How long an unfinished upload is kept. | ||
| 35 | +const SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 36 | + | ||
| 37 | +/// The directory of upload sessions: `<data_dir>/oci/uploads`. | ||
| 38 | +pub fn uploads_dir(data_dir: &Path) -> PathBuf { | ||
| 39 | + data_dir.join("oci").join("uploads") | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// The blob store key of a digest's bytes. | ||
| 43 | +pub fn blob_key(hex: &str) -> String { | ||
| 44 | + format!("oci/{hex}") | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a | ||
| 48 | +/// session, so no id can name a path outside the uploads directory. | ||
| 49 | +pub fn valid_session_id(id: &str) -> bool { | ||
| 50 | + id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +fn session_path(dir: &Path, id: &str) -> PathBuf { | ||
| 54 | + dir.join(id) | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +fn sidecar_path(dir: &Path, id: &str) -> PathBuf { | ||
| 58 | + dir.join(format!("{id}.repo")) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Starts a session for `name`, after removing sessions that were left unfinished for a day. | ||
| 62 | +pub async fn new_session(data_dir: &Path, name: &str) -> std::io::Result<String> { | ||
| 63 | + let dir = uploads_dir(data_dir); | ||
| 64 | + tokio::fs::create_dir_all(&dir).await?; | ||
| 65 | + remove_stale(&dir).await; | ||
| 66 | + let id = ulid::Ulid::generate().to_string(); | ||
| 67 | + tokio::fs::File::create_new(session_path(&dir, &id)).await?; | ||
| 68 | + tokio::fs::write(sidecar_path(&dir, &id), name).await?; | ||
| 69 | + Ok(id) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// Removes every session whose file has not changed for [`SESSION_TTL`]. Failures are ignored: a | ||
| 73 | +/// session that cannot be removed now is tried again at the next start. | ||
| 74 | +async fn remove_stale(dir: &Path) { | ||
| 75 | + let Ok(mut entries) = tokio::fs::read_dir(dir).await else { | ||
| 76 | + return; | ||
| 77 | + }; | ||
| 78 | + let now = SystemTime::now(); | ||
| 79 | + while let Ok(Some(entry)) = entries.next_entry().await { | ||
| 80 | + let path = entry.path(); | ||
| 81 | + if path.extension().is_some_and(|ext| ext == "repo") { | ||
| 82 | + continue; | ||
| 83 | + } | ||
| 84 | + let Ok(meta) = entry.metadata().await else { | ||
| 85 | + continue; | ||
| 86 | + }; | ||
| 87 | + let age = meta | ||
| 88 | + .modified() | ||
| 89 | + .ok() | ||
| 90 | + .and_then(|at| now.duration_since(at).ok()); | ||
| 91 | + if age.is_some_and(|age| age > SESSION_TTL) { | ||
| 92 | + if let Some(id) = path.file_name().and_then(|n| n.to_str()) { | ||
| 93 | + let _ = tokio::fs::remove_file(sidecar_path(dir, id)).await; | ||
| 94 | + } | ||
| 95 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 96 | + } | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// True when session `id` exists and belongs to repository `name`. | ||
| 101 | +pub async fn session_belongs_to(data_dir: &Path, id: &str, name: &str) -> bool { | ||
| 102 | + if !valid_session_id(id) { | ||
| 103 | + return false; | ||
| 104 | + } | ||
| 105 | + let dir = uploads_dir(data_dir); | ||
| 106 | + match tokio::fs::read_to_string(sidecar_path(&dir, id)).await { | ||
| 107 | + Ok(owner) => owner == name && tokio::fs::metadata(session_path(&dir, id)).await.is_ok(), | ||
| 108 | + Err(_) => false, | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// Removes a session's files, once it is finished or cancelled. | ||
| 113 | +pub async fn remove_session(data_dir: &Path, id: &str) { | ||
| 114 | + let dir = uploads_dir(data_dir); | ||
| 115 | + let _ = tokio::fs::remove_file(sidecar_path(&dir, id)).await; | ||
| 116 | + let _ = tokio::fs::remove_file(session_path(&dir, id)).await; | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// The size of a session file so far. | ||
| 120 | +pub async fn session_size(data_dir: &Path, id: &str) -> std::io::Result<u64> { | ||
| 121 | + let meta = tokio::fs::metadata(session_path(&uploads_dir(data_dir), id)).await?; | ||
| 122 | + Ok(meta.len()) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Appends the request body to a session. `expected_start` is the offset a `Content-Range` names, | ||
| 126 | +/// when the client sent one; a mismatch is refused without writing. Returns the new size. | ||
| 127 | +pub async fn append( | ||
| 128 | + data_dir: &Path, | ||
| 129 | + id: &str, | ||
| 130 | + body: Body, | ||
| 131 | + expected_start: Option<u64>, | ||
| 132 | +) -> Result<u64, Box<Response>> { | ||
| 133 | + let path = session_path(&uploads_dir(data_dir), id); | ||
| 134 | + let mut file = tokio::fs::OpenOptions::new() | ||
| 135 | + .append(true) | ||
| 136 | + .open(&path) | ||
| 137 | + .await | ||
| 138 | + .map_err(|e| Box::new(internal(e)))?; | ||
| 139 | + let size = file | ||
| 140 | + .metadata() | ||
| 141 | + .await | ||
| 142 | + .map_err(|e| Box::new(internal(e)))? | ||
| 143 | + .len(); | ||
| 144 | + if expected_start.is_some_and(|start| start != size) { | ||
| 145 | + return Err(Box::new(range_not_satisfiable(size))); | ||
| 146 | + } | ||
| 147 | + let mut written = size; | ||
| 148 | + let mut stream = std::pin::pin!(body.into_data_stream()); | ||
| 149 | + while let Some(chunk) = stream.next().await { | ||
| 150 | + let Ok(chunk) = chunk else { | ||
| 151 | + return Err(Box::new(oci_error( | ||
| 152 | + StatusCode::BAD_REQUEST, | ||
| 153 | + "BLOB_UPLOAD_INVALID", | ||
| 154 | + "the request body could not be read", | ||
| 155 | + ))); | ||
| 156 | + }; | ||
| 157 | + written = written.saturating_add(chunk.len() as u64); | ||
| 158 | + if written > MAX_BLOB_BYTES { | ||
| 159 | + return Err(Box::new(oci_error( | ||
| 160 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 161 | + "SIZE_INVALID", | ||
| 162 | + "the blob is larger than the registry accepts", | ||
| 163 | + ))); | ||
| 164 | + } | ||
| 165 | + file.write_all(&chunk) | ||
| 166 | + .await | ||
| 167 | + .map_err(|e| Box::new(internal(e)))?; | ||
| 168 | + } | ||
| 169 | + file.flush().await.map_err(|e| Box::new(internal(e)))?; | ||
| 170 | + Ok(written) | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// The sha256 of a file, hex. | ||
| 174 | +pub async fn file_sha256(path: &Path) -> std::io::Result<String> { | ||
| 175 | + let mut file = tokio::fs::File::open(path).await?; | ||
| 176 | + let mut hasher = Sha256::new(); | ||
| 177 | + let mut buf = vec![0u8; CHUNK]; | ||
| 178 | + loop { | ||
| 179 | + let read = file.read(&mut buf).await?; | ||
| 180 | + if read == 0 { | ||
| 181 | + break; | ||
| 182 | + } | ||
| 183 | + hasher.update(&buf[..read]); | ||
| 184 | + } | ||
| 185 | + Ok(hex::encode(hasher.finalize())) | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +/// Links `digest` to `package` once its bytes are in the blob store. Holds the garbage collection | ||
| 189 | +/// lock, so a sweep cannot remove bytes between the check and the link. | ||
| 190 | +pub async fn link( | ||
| 191 | + state: &AppState, | ||
| 192 | + package: &Package, | ||
| 193 | + hex: &str, | ||
| 194 | + size: u64, | ||
| 195 | + source: Option<&Path>, | ||
| 196 | +) -> Result<(), Refusal> { | ||
| 197 | + let _gc = gc::lock().await; | ||
| 198 | + let key = blob_key(hex); | ||
| 199 | + let exists = state.blobs.exists(&key).await.map_err(internal_refusal)?; | ||
| 200 | + if !exists { | ||
| 201 | + let Some(source) = source else { | ||
| 202 | + return Err(Box::new(oci_error( | ||
| 203 | + StatusCode::NOT_FOUND, | ||
| 204 | + "BLOB_UNKNOWN", | ||
| 205 | + "blob unknown to registry", | ||
| 206 | + ))); | ||
| 207 | + }; | ||
| 208 | + copy_into_store(state, &key, source).await?; | ||
| 209 | + } | ||
| 210 | + state | ||
| 211 | + .store | ||
| 212 | + .oci_link_blob(&package.id, &format!("sha256:{hex}"), size) | ||
| 213 | + .await | ||
| 214 | + .map_err(internal_refusal) | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +async fn copy_into_store(state: &AppState, key: &str, source: &Path) -> Result<(), Refusal> { | ||
| 218 | + let mut file = tokio::fs::File::open(source) | ||
| 219 | + .await | ||
| 220 | + .map_err(internal_refusal)?; | ||
| 221 | + let mut writer = state | ||
| 222 | + .blobs | ||
| 223 | + .begin(key, MAX_BLOB_BYTES) | ||
| 224 | + .await | ||
| 225 | + .map_err(internal_refusal)?; | ||
| 226 | + let mut buf = vec![0u8; CHUNK]; | ||
| 227 | + loop { | ||
| 228 | + let read = match file.read(&mut buf).await { | ||
| 229 | + Ok(read) => read, | ||
| 230 | + Err(e) => { | ||
| 231 | + writer.abort().await; | ||
| 232 | + return Err(internal_refusal(e)); | ||
| 233 | + } | ||
| 234 | + }; | ||
| 235 | + if read == 0 { | ||
| 236 | + break; | ||
| 237 | + } | ||
| 238 | + if let Err(e) = writer.push(&buf[..read]).await { | ||
| 239 | + writer.abort().await; | ||
| 240 | + return Err(internal_refusal(e)); | ||
| 241 | + } | ||
| 242 | + } | ||
| 243 | + writer.finish().await.map_err(internal_refusal)?; | ||
| 244 | + Ok(()) | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +/// The response that closes an upload with its blob's location. | ||
| 248 | +pub fn created(name: &str, hex: &str) -> Response { | ||
| 249 | + let digest = format!("sha256:{hex}"); | ||
| 250 | + let mut res = Response::new(Body::empty()); | ||
| 251 | + *res.status_mut() = StatusCode::CREATED; | ||
| 252 | + insert(&mut res, "location", &format!("/v2/{name}/blobs/{digest}")); | ||
| 253 | + insert(&mut res, "docker-content-digest", &digest); | ||
| 254 | + res | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// A 202 for an upload still open, with the bytes received so far. | ||
| 258 | +pub fn upload_progress(name: &str, id: &str, size: u64) -> Response { | ||
| 259 | + let mut res = Response::new(Body::empty()); | ||
| 260 | + *res.status_mut() = StatusCode::ACCEPTED; | ||
| 261 | + insert( | ||
| 262 | + &mut res, | ||
| 263 | + "location", | ||
| 264 | + &format!("/v2/{name}/blobs/uploads/{id}"), | ||
| 265 | + ); | ||
| 266 | + insert(&mut res, "docker-upload-uuid", id); | ||
| 267 | + insert(&mut res, "range", &range_of(size)); | ||
| 268 | + res | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/// The `Range` a registry answers with: the bytes received, `0-n`, or `0-0` when none. | ||
| 272 | +pub fn range_of(size: u64) -> String { | ||
| 273 | + format!("0-{}", size.saturating_sub(1)) | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +fn range_not_satisfiable(size: u64) -> Response { | ||
| 277 | + let mut res = oci_error( | ||
| 278 | + StatusCode::RANGE_NOT_SATISFIABLE, | ||
| 279 | + "BLOB_UPLOAD_INVALID", | ||
| 280 | + "the chunk does not start where the upload ends", | ||
| 281 | + ); | ||
| 282 | + insert(&mut res, "range", &range_of(size)); | ||
| 283 | + res | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// Sets a header from a string value. A value that is not a valid header is left out. | ||
| 287 | +pub fn insert(res: &mut Response, name: &'static str, value: &str) { | ||
| 288 | + if let Ok(value) = HeaderValue::from_str(value) { | ||
| 289 | + res.headers_mut() | ||
| 290 | + .insert(http::HeaderName::from_static(name), value); | ||
| 291 | + } | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +/// A blob GET or HEAD. The blob must be linked to the package the caller may read. | ||
| 295 | +pub async fn get_blob( | ||
| 296 | + state: &AppState, | ||
| 297 | + caller: &Caller, | ||
| 298 | + name: &str, | ||
| 299 | + digest: &str, | ||
| 300 | + head: bool, | ||
| 301 | +) -> Response { | ||
| 302 | + let target = match auth::authorize(state, caller, name, false).await { | ||
| 303 | + Ok(target) => target, | ||
| 304 | + Err(res) => return *res, | ||
| 305 | + }; | ||
| 306 | + let Some(hex) = rules::parse_digest(digest) else { | ||
| 307 | + return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); | ||
| 308 | + }; | ||
| 309 | + let Some(package) = target.package.as_ref() else { | ||
| 310 | + return unknown_blob(); | ||
| 311 | + }; | ||
| 312 | + let size = match state.store.oci_blob_size(&package.id, digest).await { | ||
| 313 | + Ok(Some(size)) => size, | ||
| 314 | + Ok(None) => return unknown_blob(), | ||
| 315 | + Err(e) => return internal(e), | ||
| 316 | + }; | ||
| 317 | + let mut res = Response::new(Body::empty()); | ||
| 318 | + *res.status_mut() = StatusCode::OK; | ||
| 319 | + insert(&mut res, "docker-content-digest", digest); | ||
| 320 | + res.headers_mut().insert( | ||
| 321 | + CONTENT_TYPE, | ||
| 322 | + HeaderValue::from_static("application/octet-stream"), | ||
| 323 | + ); | ||
| 324 | + res.headers_mut() | ||
| 325 | + .insert(CONTENT_LENGTH, HeaderValue::from(size)); | ||
| 326 | + if head { | ||
| 327 | + return res; | ||
| 328 | + } | ||
| 329 | + match state.blobs.read(&blob_key(hex)).await { | ||
| 330 | + Ok(Some(read)) => { | ||
| 331 | + let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); | ||
| 332 | + *res.body_mut() = Body::new(StreamBody::new(chunks)); | ||
| 333 | + res | ||
| 334 | + } | ||
| 335 | + // Linked but missing from the store: the store is damaged, not the request. | ||
| 336 | + Ok(None) => internal("a linked blob is missing from the blob store"), | ||
| 337 | + Err(e) => internal(e), | ||
| 338 | + } | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +fn unknown_blob() -> Response { | ||
| 342 | + oci_error( | ||
| 343 | + StatusCode::NOT_FOUND, | ||
| 344 | + "BLOB_UNKNOWN", | ||
| 345 | + "blob unknown to registry", | ||
| 346 | + ) | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +/// Unlinks a blob from the repository. A blob a manifest of the repo still names is kept, so no | ||
| 350 | +/// image breaks; the caller deletes the manifest first. Bytes no package links are removed. | ||
| 351 | +pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Response { | ||
| 352 | + let Some(hex) = rules::parse_digest(digest) else { | ||
| 353 | + return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); | ||
| 354 | + }; | ||
| 355 | + let Some(package) = target.package.as_ref() else { | ||
| 356 | + return unknown_blob(); | ||
| 357 | + }; | ||
| 358 | + match state.store.oci_blob_size(&package.id, digest).await { | ||
| 359 | + Ok(Some(_)) => {} | ||
| 360 | + Ok(None) => return unknown_blob(), | ||
| 361 | + Err(e) => return internal(e), | ||
| 362 | + } | ||
| 363 | + match state.store.oci_digest_referenced(&package.id, digest).await { | ||
| 364 | + Ok(true) => { | ||
| 365 | + return oci_error( | ||
| 366 | + StatusCode::BAD_REQUEST, | ||
| 367 | + "UNSUPPORTED", | ||
| 368 | + "a manifest still uses this blob; delete the manifest first", | ||
| 369 | + ); | ||
| 370 | + } | ||
| 371 | + Ok(false) => {} | ||
| 372 | + Err(e) => return internal(e), | ||
| 373 | + } | ||
| 374 | + let _gc = gc::lock().await; | ||
| 375 | + if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await { | ||
| 376 | + return internal(e); | ||
| 377 | + } | ||
| 378 | + match state.store.oci_digest_linked(digest).await { | ||
| 379 | + Ok(false) => { | ||
| 380 | + if let Err(e) = state.blobs.delete(&blob_key(hex)).await { | ||
| 381 | + return internal(e); | ||
| 382 | + } | ||
| 383 | + } | ||
| 384 | + Ok(true) => {} | ||
| 385 | + Err(e) => return internal(e), | ||
| 386 | + } | ||
| 387 | + let mut res = Response::new(Body::empty()); | ||
| 388 | + *res.status_mut() = StatusCode::ACCEPTED; | ||
| 389 | + res | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +/// The package a write goes to, created on first use. | ||
| 393 | +pub async fn write_package(state: &AppState, target: &Target) -> Result<Package, Refusal> { | ||
| 394 | + if let Some(package) = target.package.as_ref() { | ||
| 395 | + return Ok(package.clone()); | ||
| 396 | + } | ||
| 397 | + state | ||
| 398 | + .store | ||
| 399 | + .ensure_package(&target.owner.id, KIND_OCI, &target.image, &target.image) | ||
| 400 | + .await | ||
| 401 | + .map_err(internal_refusal) | ||
| 402 | +} | ||
| 403 | + | ||
| 404 | +/// Mounts `digest` from repository `from` into the target when the caller may read `from` and | ||
| 405 | +/// the blob is there. Returns false when the mount is not possible, so the caller starts an upload. | ||
| 406 | +pub async fn try_mount( | ||
| 407 | + state: &AppState, | ||
| 408 | + caller: &Caller, | ||
| 409 | + target: &Target, | ||
| 410 | + digest: &str, | ||
| 411 | + from: &str, | ||
| 412 | +) -> Result<bool, Refusal> { | ||
| 413 | + let Some(hex) = rules::parse_digest(digest) else { | ||
| 414 | + return Ok(false); | ||
| 415 | + }; | ||
| 416 | + let Ok(source) = auth::authorize(state, caller, from, false).await else { | ||
| 417 | + return Ok(false); | ||
| 418 | + }; | ||
| 419 | + let Some(source_package) = source.package.as_ref() else { | ||
| 420 | + return Ok(false); | ||
| 421 | + }; | ||
| 422 | + let Some(size) = state | ||
| 423 | + .store | ||
| 424 | + .oci_blob_size(&source_package.id, digest) | ||
| 425 | + .await | ||
| 426 | + .map_err(internal_refusal)? | ||
| 427 | + else { | ||
| 428 | + return Ok(false); | ||
| 429 | + }; | ||
| 430 | + if !state | ||
| 431 | + .blobs | ||
| 432 | + .exists(&blob_key(hex)) | ||
| 433 | + .await | ||
| 434 | + .map_err(internal_refusal)? | ||
| 435 | + { | ||
| 436 | + return Ok(false); | ||
| 437 | + } | ||
| 438 | + let package = write_package(state, target).await?; | ||
| 439 | + link(state, &package, hex, size, None).await?; | ||
| 440 | + Ok(true) | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +/// Reads the digest a request names, or the 400 when it is malformed. | ||
| 444 | +pub fn digest_arg(digest: &str) -> Result<&str, Box<Response>> { | ||
| 445 | + rules::parse_digest(digest).ok_or_else(|| { | ||
| 446 | + Box::new(oci_error( | ||
| 447 | + StatusCode::BAD_REQUEST, | ||
| 448 | + "DIGEST_INVALID", | ||
| 449 | + "invalid digest", | ||
| 450 | + )) | ||
| 451 | + }) | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +/// The offset a `Content-Range` header starts at, when the client sent one. | ||
| 455 | +pub fn content_range_start(headers: &http::HeaderMap) -> Option<u64> { | ||
| 456 | + let value = headers.get("content-range")?.to_str().ok()?; | ||
| 457 | + value.split('-').next()?.trim().parse().ok() | ||
| 458 | +} | ||
crates/forge-web/src/oci/gc.rsadded+38 -0
| @@ -0,0 +1,38 @@ | |||
| 1 | +//! Garbage collection of the container registry: a mark and sweep that runs after a manifest or a | ||
| 2 | +//! tag is deleted, never on a timer. | ||
| 3 | +//! | ||
| 4 | +//! Mark: the digests a package's manifests refer to. Sweep: the blob links of that package that no | ||
| 5 | +//! manifest refers to are dropped. Then each dropped digest whose bytes no package links any more | ||
| 6 | +//! is deleted from the blob store. A blob pushed but not yet named by a manifest is swept too, so a | ||
| 7 | +//! push that races a delete fails at its manifest with `MANIFEST_BLOB_UNKNOWN` and can be retried. | ||
| 8 | +//! | ||
| 9 | +//! One process-wide lock serializes the sweep with the links and the manifest writes that depend | ||
| 10 | +//! on the blobs they check, so a sweep never removes bytes between a check and the link after it. | ||
| 11 | + | ||
| 12 | +use tokio::sync::{Mutex, MutexGuard}; | ||
| 13 | + | ||
| 14 | +use super::blobs::blob_key; | ||
| 15 | +use crate::state::AppState; | ||
| 16 | + | ||
| 17 | +static LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 18 | + | ||
| 19 | +/// Takes the registry's garbage collection lock. | ||
| 20 | +pub async fn lock() -> MutexGuard<'static, ()> { | ||
| 21 | + LOCK.lock().await | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// Drops the blob links of `package_id` that no manifest names, and deletes the bytes of the | ||
| 25 | +/// digests that no package links any more. Returns how many digests were dropped. | ||
| 26 | +pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> { | ||
| 27 | + let _guard = lock().await; | ||
| 28 | + let dropped = state.store.oci_sweep_unreferenced(package_id).await?; | ||
| 29 | + for digest in &dropped { | ||
| 30 | + if state.store.oci_digest_linked(digest).await? { | ||
| 31 | + continue; | ||
| 32 | + } | ||
| 33 | + if let Some(hex) = digest.strip_prefix("sha256:") { | ||
| 34 | + state.blobs.delete(&blob_key(hex)).await?; | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + Ok(dropped.len()) | ||
| 38 | +} | ||
crates/forge-web/src/oci/manifests.rsadded+365 -0
| @@ -0,0 +1,365 @@ | |||
| 1 | +//! Manifests and tags of the container registry: push, pull, delete and the tag list. A manifest | ||
| 2 | +//! is stored as its exact bytes under its digest; a tag names one manifest of its package. | ||
| 3 | + | ||
| 4 | +use forge_core::User; | ||
| 5 | +use forge_core::oci as rules; | ||
| 6 | +use forge_core::packages::Package; | ||
| 7 | +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 8 | +use serde_json::json; | ||
| 9 | +use sha2::{Digest, Sha256}; | ||
| 10 | +use topcoat::router::response::Response; | ||
| 11 | +use topcoat::router::{Body, StatusCode, to_bytes}; | ||
| 12 | + | ||
| 13 | +use super::auth::{self, Caller, internal}; | ||
| 14 | +use super::blobs::{insert, write_package}; | ||
| 15 | +use super::{gc, oci_error}; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +/// Largest manifest accepted, in bytes. | ||
| 19 | +pub const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; | ||
| 20 | + | ||
| 21 | +/// What a manifest reference names: a digest, or a tag. | ||
| 22 | +pub enum Reference<'a> { | ||
| 23 | + Digest(&'a str), | ||
| 24 | + Tag(&'a str), | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// Reads a reference from a path segment. A reference with a colon is a digest, anything else a | ||
| 28 | +/// tag. The error is the response to send. | ||
| 29 | +pub fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> { | ||
| 30 | + if reference.contains(':') { | ||
| 31 | + if rules::parse_digest(reference).is_some() { | ||
| 32 | + Ok(Reference::Digest(reference)) | ||
| 33 | + } else { | ||
| 34 | + Err(Box::new(oci_error( | ||
| 35 | + StatusCode::BAD_REQUEST, | ||
| 36 | + "DIGEST_INVALID", | ||
| 37 | + "invalid digest", | ||
| 38 | + ))) | ||
| 39 | + } | ||
| 40 | + } else if rules::valid_tag(reference) { | ||
| 41 | + Ok(Reference::Tag(reference)) | ||
| 42 | + } else { | ||
| 43 | + Err(Box::new(oci_error( | ||
| 44 | + StatusCode::BAD_REQUEST, | ||
| 45 | + "TAG_INVALID", | ||
| 46 | + "invalid tag", | ||
| 47 | + ))) | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +fn sha256_of(bytes: &[u8]) -> String { | ||
| 52 | + format!("sha256:{}", hex::encode(Sha256::digest(bytes))) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +fn manifest_unknown() -> Response { | ||
| 56 | + oci_error( | ||
| 57 | + StatusCode::NOT_FOUND, | ||
| 58 | + "MANIFEST_UNKNOWN", | ||
| 59 | + "manifest unknown to registry", | ||
| 60 | + ) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +fn name_unknown() -> Response { | ||
| 64 | + oci_error( | ||
| 65 | + StatusCode::NOT_FOUND, | ||
| 66 | + "NAME_UNKNOWN", | ||
| 67 | + "repository name not known to registry", | ||
| 68 | + ) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// `PUT /v2/{name}/manifests/{reference}`. The referenced blobs must already be in the package, so | ||
| 72 | +/// a manifest never names bytes the registry lacks. The digest of the bytes is the manifest's id. | ||
| 73 | +pub async fn put_manifest( | ||
| 74 | + state: &AppState, | ||
| 75 | + caller: &Caller, | ||
| 76 | + name: &str, | ||
| 77 | + reference: &str, | ||
| 78 | + content_type: Option<&str>, | ||
| 79 | + body: Body, | ||
| 80 | +) -> Response { | ||
| 81 | + let target = match auth::authorize(state, caller, name, true).await { | ||
| 82 | + Ok(target) => target, | ||
| 83 | + Err(res) => return *res, | ||
| 84 | + }; | ||
| 85 | + let reference = match parse_reference(reference) { | ||
| 86 | + Ok(reference) => reference, | ||
| 87 | + Err(res) => return *res, | ||
| 88 | + }; | ||
| 89 | + let media_type = content_type | ||
| 90 | + .and_then(|value| value.split(';').next()) | ||
| 91 | + .map(str::trim) | ||
| 92 | + .unwrap_or_default() | ||
| 93 | + .to_owned(); | ||
| 94 | + if !rules::is_manifest_media_type(&media_type) { | ||
| 95 | + return oci_error( | ||
| 96 | + StatusCode::BAD_REQUEST, | ||
| 97 | + "MANIFEST_INVALID", | ||
| 98 | + "unsupported manifest media type", | ||
| 99 | + ); | ||
| 100 | + } | ||
| 101 | + let bytes = match to_bytes(body, MAX_MANIFEST_BYTES).await { | ||
| 102 | + Ok(bytes) => bytes, | ||
| 103 | + Err(_) => { | ||
| 104 | + return oci_error( | ||
| 105 | + StatusCode::PAYLOAD_TOO_LARGE, | ||
| 106 | + "SIZE_INVALID", | ||
| 107 | + "the manifest is larger than the registry accepts", | ||
| 108 | + ); | ||
| 109 | + } | ||
| 110 | + }; | ||
| 111 | + let digest = sha256_of(&bytes); | ||
| 112 | + if let Reference::Digest(wanted) = reference | ||
| 113 | + && wanted != digest | ||
| 114 | + { | ||
| 115 | + return oci_error( | ||
| 116 | + StatusCode::BAD_REQUEST, | ||
| 117 | + "DIGEST_INVALID", | ||
| 118 | + "the manifest does not match its digest", | ||
| 119 | + ); | ||
| 120 | + } | ||
| 121 | + let Ok(content) = String::from_utf8(bytes.to_vec()) else { | ||
| 122 | + return oci_error( | ||
| 123 | + StatusCode::BAD_REQUEST, | ||
| 124 | + "MANIFEST_INVALID", | ||
| 125 | + "manifest is not UTF-8", | ||
| 126 | + ); | ||
| 127 | + }; | ||
| 128 | + let refs = match rules::scan_manifest(&bytes) { | ||
| 129 | + Ok(refs) => refs, | ||
| 130 | + Err(message) => { | ||
| 131 | + return oci_error(StatusCode::BAD_REQUEST, "MANIFEST_INVALID", &message); | ||
| 132 | + } | ||
| 133 | + }; | ||
| 134 | + | ||
| 135 | + let _gc = gc::lock().await; | ||
| 136 | + let package = match write_package(state, &target).await { | ||
| 137 | + Ok(package) => package, | ||
| 138 | + Err(res) => return *res, | ||
| 139 | + }; | ||
| 140 | + for dep in &refs.digests { | ||
| 141 | + let present = if refs.is_index { | ||
| 142 | + state | ||
| 143 | + .store | ||
| 144 | + .oci_manifest(&package.id, dep) | ||
| 145 | + .await | ||
| 146 | + .map(|m| m.is_some()) | ||
| 147 | + } else { | ||
| 148 | + state | ||
| 149 | + .store | ||
| 150 | + .oci_blob_size(&package.id, dep) | ||
| 151 | + .await | ||
| 152 | + .map(|size| size.is_some()) | ||
| 153 | + }; | ||
| 154 | + match present { | ||
| 155 | + Ok(true) => {} | ||
| 156 | + Ok(false) => { | ||
| 157 | + return oci_error( | ||
| 158 | + StatusCode::BAD_REQUEST, | ||
| 159 | + "MANIFEST_BLOB_UNKNOWN", | ||
| 160 | + &format!("blob unknown to registry: {dep}"), | ||
| 161 | + ); | ||
| 162 | + } | ||
| 163 | + Err(e) => return internal(e), | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + let stored = match state | ||
| 167 | + .store | ||
| 168 | + .oci_put_manifest( | ||
| 169 | + &package.id, | ||
| 170 | + &digest, | ||
| 171 | + &media_type, | ||
| 172 | + &content, | ||
| 173 | + refs.total_size, | ||
| 174 | + &refs.digests, | ||
| 175 | + ) | ||
| 176 | + .await | ||
| 177 | + { | ||
| 178 | + Ok(stored) => stored, | ||
| 179 | + Err(e) => return internal(e), | ||
| 180 | + }; | ||
| 181 | + if let Reference::Tag(tag) = reference | ||
| 182 | + && let Err(e) = state.store.oci_set_tag(&package.id, tag, &stored.id).await | ||
| 183 | + { | ||
| 184 | + return internal(e); | ||
| 185 | + } | ||
| 186 | + state.packages_live.bump(&target.owner.id); | ||
| 187 | + let mut res = Response::new(Body::empty()); | ||
| 188 | + *res.status_mut() = StatusCode::CREATED; | ||
| 189 | + insert( | ||
| 190 | + &mut res, | ||
| 191 | + "location", | ||
| 192 | + &format!("/v2/{name}/manifests/{digest}"), | ||
| 193 | + ); | ||
| 194 | + insert(&mut res, "docker-content-digest", &digest); | ||
| 195 | + res | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +/// `GET` and `HEAD` of a manifest, by tag or digest. | ||
| 199 | +pub async fn get_manifest( | ||
| 200 | + state: &AppState, | ||
| 201 | + caller: &Caller, | ||
| 202 | + name: &str, | ||
| 203 | + reference: &str, | ||
| 204 | + head: bool, | ||
| 205 | +) -> Response { | ||
| 206 | + let target = match auth::authorize(state, caller, name, false).await { | ||
| 207 | + Ok(target) => target, | ||
| 208 | + Err(res) => return *res, | ||
| 209 | + }; | ||
| 210 | + let reference = match parse_reference(reference) { | ||
| 211 | + Ok(reference) => reference, | ||
| 212 | + Err(res) => return *res, | ||
| 213 | + }; | ||
| 214 | + let Some(package) = target.package.as_ref() else { | ||
| 215 | + return name_unknown(); | ||
| 216 | + }; | ||
| 217 | + let found = match reference { | ||
| 218 | + Reference::Digest(digest) => state.store.oci_manifest(&package.id, digest).await, | ||
| 219 | + Reference::Tag(tag) => state.store.oci_tag_manifest(&package.id, tag).await, | ||
| 220 | + }; | ||
| 221 | + let manifest = match found { | ||
| 222 | + Ok(Some(manifest)) => manifest, | ||
| 223 | + Ok(None) => return manifest_unknown(), | ||
| 224 | + Err(e) => return internal(e), | ||
| 225 | + }; | ||
| 226 | + let mut res = Response::new(if head { | ||
| 227 | + Body::empty() | ||
| 228 | + } else { | ||
| 229 | + Body::from(manifest.content.clone()) | ||
| 230 | + }); | ||
| 231 | + *res.status_mut() = StatusCode::OK; | ||
| 232 | + if let Ok(value) = HeaderValue::from_str(&manifest.media_type) { | ||
| 233 | + res.headers_mut().insert(CONTENT_TYPE, value); | ||
| 234 | + } | ||
| 235 | + insert(&mut res, "docker-content-digest", &manifest.digest); | ||
| 236 | + res.headers_mut() | ||
| 237 | + .insert(CONTENT_LENGTH, HeaderValue::from(manifest.content.len())); | ||
| 238 | + res | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +/// `DELETE` of a manifest by digest, which removes it and every tag on it, or by tag, which | ||
| 242 | +/// removes the tag. A manifest left with no tag and no index naming it is removed as well. | ||
| 243 | +pub async fn delete_manifest( | ||
| 244 | + state: &AppState, | ||
| 245 | + caller: &Caller, | ||
| 246 | + name: &str, | ||
| 247 | + reference: &str, | ||
| 248 | +) -> Response { | ||
| 249 | + let target = match auth::authorize(state, caller, name, true).await { | ||
| 250 | + Ok(target) => target, | ||
| 251 | + Err(res) => return *res, | ||
| 252 | + }; | ||
| 253 | + let reference = match parse_reference(reference) { | ||
| 254 | + Ok(reference) => reference, | ||
| 255 | + Err(res) => return *res, | ||
| 256 | + }; | ||
| 257 | + let Some(package) = target.package.as_ref() else { | ||
| 258 | + return name_unknown(); | ||
| 259 | + }; | ||
| 260 | + match reference { | ||
| 261 | + Reference::Digest(digest) => { | ||
| 262 | + let manifest = match state.store.oci_manifest(&package.id, digest).await { | ||
| 263 | + Ok(Some(manifest)) => manifest, | ||
| 264 | + Ok(None) => return manifest_unknown(), | ||
| 265 | + Err(e) => return internal(e), | ||
| 266 | + }; | ||
| 267 | + { | ||
| 268 | + let _gc = gc::lock().await; | ||
| 269 | + if let Err(e) = state.store.oci_delete_manifest(&manifest.id).await { | ||
| 270 | + return internal(e); | ||
| 271 | + } | ||
| 272 | + } | ||
| 273 | + if let Err(e) = gc::sweep(state, &package.id).await { | ||
| 274 | + return internal(e); | ||
| 275 | + } | ||
| 276 | + } | ||
| 277 | + Reference::Tag(tag) => match remove_tag(state, &target.owner, package, tag).await { | ||
| 278 | + Ok(true) => {} | ||
| 279 | + Ok(false) => return manifest_unknown(), | ||
| 280 | + Err(e) => return internal(e), | ||
| 281 | + }, | ||
| 282 | + } | ||
| 283 | + state.packages_live.bump(&target.owner.id); | ||
| 284 | + let mut res = Response::new(Body::empty()); | ||
| 285 | + *res.status_mut() = StatusCode::ACCEPTED; | ||
| 286 | + res | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// Removes `tag` from the package. A manifest left with no tag, and not named by an index, goes | ||
| 290 | +/// too, and the sweep follows. Returns false when the tag does not exist. | ||
| 291 | +pub async fn remove_tag( | ||
| 292 | + state: &AppState, | ||
| 293 | + owner: &User, | ||
| 294 | + package: &Package, | ||
| 295 | + tag: &str, | ||
| 296 | +) -> forge_core::Result<bool> { | ||
| 297 | + let Some(manifest) = state.store.oci_tag_manifest(&package.id, tag).await? else { | ||
| 298 | + return Ok(false); | ||
| 299 | + }; | ||
| 300 | + { | ||
| 301 | + let _gc = gc::lock().await; | ||
| 302 | + state.store.oci_delete_tag(&package.id, tag).await?; | ||
| 303 | + let tags_left = state.store.oci_manifest_tag_count(&manifest.id).await?; | ||
| 304 | + let named = state | ||
| 305 | + .store | ||
| 306 | + .oci_digest_referenced(&package.id, &manifest.digest) | ||
| 307 | + .await?; | ||
| 308 | + if tags_left == 0 && !named { | ||
| 309 | + state.store.oci_delete_manifest(&manifest.id).await?; | ||
| 310 | + } | ||
| 311 | + } | ||
| 312 | + gc::sweep(state, &package.id).await?; | ||
| 313 | + state.packages_live.bump(&owner.id); | ||
| 314 | + Ok(true) | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +/// `GET /v2/{name}/tags/list`, with `n` and `last` for pages. A page that is not the last names | ||
| 318 | +/// the next page in a `Link` header. | ||
| 319 | +pub async fn list_tags( | ||
| 320 | + state: &AppState, | ||
| 321 | + caller: &Caller, | ||
| 322 | + name: &str, | ||
| 323 | + n: Option<u64>, | ||
| 324 | + last: Option<&str>, | ||
| 325 | +) -> Response { | ||
| 326 | + let target = match auth::authorize(state, caller, name, false).await { | ||
| 327 | + Ok(target) => target, | ||
| 328 | + Err(res) => return *res, | ||
| 329 | + }; | ||
| 330 | + let Some(package) = target.package.as_ref() else { | ||
| 331 | + return name_unknown(); | ||
| 332 | + }; | ||
| 333 | + let last = last.unwrap_or(""); | ||
| 334 | + let wanted = n.map(|n| n.saturating_add(1)); | ||
| 335 | + let names = match state | ||
| 336 | + .store | ||
| 337 | + .oci_tag_names(&package.id, last, wanted.unwrap_or(u64::MAX)) | ||
| 338 | + .await | ||
| 339 | + { | ||
| 340 | + Ok(names) => names, | ||
| 341 | + Err(e) => return internal(e), | ||
| 342 | + }; | ||
| 343 | + let mut names = names; | ||
| 344 | + let mut link = None; | ||
| 345 | + if let Some(n) = n { | ||
| 346 | + let n = usize::try_from(n).unwrap_or(usize::MAX); | ||
| 347 | + if names.len() > n { | ||
| 348 | + names.truncate(n); | ||
| 349 | + if let Some(last_kept) = names.last() { | ||
| 350 | + link = Some(format!( | ||
| 351 | + "</v2/{name}/tags/list?n={n}&last={last_kept}>; rel=\"next\"" | ||
| 352 | + )); | ||
| 353 | + } | ||
| 354 | + } | ||
| 355 | + } | ||
| 356 | + let body = json!({ "name": name, "tags": names }); | ||
| 357 | + let mut res = Response::new(Body::from(body.to_string())); | ||
| 358 | + *res.status_mut() = StatusCode::OK; | ||
| 359 | + res.headers_mut() | ||
| 360 | + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 361 | + if let Some(link) = link { | ||
| 362 | + insert(&mut res, "link", &link); | ||
| 363 | + } | ||
| 364 | + res | ||
| 365 | +} | ||
crates/forge-web/src/oci/mod.rsadded+467 -0
| @@ -0,0 +1,467 @@ | |||
| 1 | +//! The container registry: images pushed and pulled with `docker` or `podman`, speaking the OCI | ||
| 2 | +//! Distribution spec v1.1 under `/v2/`. | ||
| 3 | +//! | ||
| 4 | +//! An image is a package of kind `oci` owned by a user or an org; its name is `{owner}/{image}`, | ||
| 5 | +//! and the image may have nested segments (`{owner}/{a}/{b}`). Blobs are content-addressed bytes | ||
| 6 | +//! in the blob store, shared by digest ([`blobs`]). Manifests and tags live in the database | ||
| 7 | +//! ([`manifests`]). Unreferenced blobs are removed by a mark and sweep after deletes ([`gc`]). | ||
| 8 | +//! Credentials come through `GET /v2/token` ([`auth`]); the Packages tab and the package page show | ||
| 9 | +//! the images ([`crate::pages::packages`]). | ||
| 10 | +//! | ||
| 11 | +//! The `/v2/` path must reach the forge unchanged, with a large body limit and no request | ||
| 12 | +//! buffering, since layers are big. docs/packages.md says how a proxy is set up. | ||
| 13 | + | ||
| 14 | +pub mod auth; | ||
| 15 | +pub mod blobs; | ||
| 16 | +pub mod gc; | ||
| 17 | +pub mod manifests; | ||
| 18 | + | ||
| 19 | +use forge_core::oci as rules; | ||
| 20 | +use http::header::{CONTENT_TYPE, HeaderValue}; | ||
| 21 | +use serde_json::{Value, json}; | ||
| 22 | +use topcoat::context::{Cx, app_context}; | ||
| 23 | +use topcoat::router::request::{headers, method, uri}; | ||
| 24 | +use topcoat::router::response::Response; | ||
| 25 | +use topcoat::router::{Body, StatusCode, path_param, route}; | ||
| 26 | + | ||
| 27 | +use crate::state::AppState; | ||
| 28 | +use auth::{Caller, unix_now}; | ||
| 29 | + | ||
| 30 | +path_param!(*rest); | ||
| 31 | + | ||
| 32 | +/// The API version header every `/v2/` answer carries. | ||
| 33 | +const API_VERSION: &str = "docker-distribution-api-version"; | ||
| 34 | + | ||
| 35 | +/// One OCI error response: `{"errors":[{"code","message","detail"}]}`. | ||
| 36 | +pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response { | ||
| 37 | + let body = json!({ "errors": [{ "code": code, "message": message, "detail": Value::Null }] }); | ||
| 38 | + json_response(status, &body) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +fn json_response(status: StatusCode, value: &Value) -> Response { | ||
| 42 | + let mut res = Response::new(Body::from(value.to_string())); | ||
| 43 | + *res.status_mut() = status; | ||
| 44 | + res.headers_mut() | ||
| 45 | + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 46 | + res.headers_mut() | ||
| 47 | + .insert(API_VERSION, HeaderValue::from_static("registry/2.0")); | ||
| 48 | + res | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// What a `/v2/` path names. | ||
| 52 | +#[derive(Debug, PartialEq, Eq)] | ||
| 53 | +enum Op { | ||
| 54 | + Tags { name: String }, | ||
| 55 | + Manifest { name: String, reference: String }, | ||
| 56 | + UploadStart { name: String }, | ||
| 57 | + Upload { name: String, id: String }, | ||
| 58 | + Blob { name: String, digest: String }, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Reads the operation of a path below `/v2/`. The repository name is every segment before the | ||
| 62 | +/// keyword `tags`, `manifests` or `blobs` that begins a valid operation, so nested names work. | ||
| 63 | +fn parse_op(segments: &[&str]) -> Option<Op> { | ||
| 64 | + for (i, keyword) in segments.iter().enumerate().skip(1) { | ||
| 65 | + let name = segments[..i].join("/"); | ||
| 66 | + let rest = &segments[i + 1..]; | ||
| 67 | + let op = match *keyword { | ||
| 68 | + "tags" if rest == ["list"] => Op::Tags { name }, | ||
| 69 | + "manifests" if rest.len() == 1 => Op::Manifest { | ||
| 70 | + name, | ||
| 71 | + reference: rest[0].to_owned(), | ||
| 72 | + }, | ||
| 73 | + "blobs" if rest == ["uploads"] => Op::UploadStart { name }, | ||
| 74 | + "blobs" if rest.len() == 2 && rest[0] == "uploads" => Op::Upload { | ||
| 75 | + name, | ||
| 76 | + id: rest[1].to_owned(), | ||
| 77 | + }, | ||
| 78 | + "blobs" if rest.len() == 1 => Op::Blob { | ||
| 79 | + name, | ||
| 80 | + digest: rest[0].to_owned(), | ||
| 81 | + }, | ||
| 82 | + _ => continue, | ||
| 83 | + }; | ||
| 84 | + return Some(op); | ||
| 85 | + } | ||
| 86 | + None | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// The query string as pairs, decoded. | ||
| 90 | +fn query_pairs(cx: &Cx) -> Vec<(String, String)> { | ||
| 91 | + uri(cx) | ||
| 92 | + .query() | ||
| 93 | + .map(|q| { | ||
| 94 | + form_urlencoded::parse(q.as_bytes()) | ||
| 95 | + .map(|(k, v)| (k.into_owned(), v.into_owned())) | ||
| 96 | + .collect() | ||
| 97 | + }) | ||
| 98 | + .unwrap_or_default() | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +fn query_value(pairs: &[(String, String)], key: &str) -> Option<String> { | ||
| 102 | + pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// `GET /v2/`: the probe. A caller with valid credentials gets 200; anyone else the challenge. | ||
| 106 | +#[route(GET "/v2/")] | ||
| 107 | +async fn root(cx: &Cx) -> topcoat::Result<Response> { | ||
| 108 | + let state = app_context::<AppState>(cx); | ||
| 109 | + Ok(match auth::caller(cx).await { | ||
| 110 | + Ok(Caller { user: Some(_) }) => json_response(StatusCode::OK, &json!({})), | ||
| 111 | + Ok(_) => auth::challenge(state, None), | ||
| 112 | + Err(res) => *res, | ||
| 113 | + }) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// `GET /v2/token`: exchanges Basic credentials (a personal access token as the password) for a | ||
| 117 | +/// short-lived bearer token. Anonymous callers get an anonymous token, which reads public images. | ||
| 118 | +#[route(GET "/v2/token")] | ||
| 119 | +async fn token(cx: &Cx) -> topcoat::Result<Response> { | ||
| 120 | + let state = app_context::<AppState>(cx); | ||
| 121 | + let caller = match auth::caller(cx).await { | ||
| 122 | + Ok(caller) => caller, | ||
| 123 | + Err(res) => return Ok(*res), | ||
| 124 | + }; | ||
| 125 | + let subject = caller.user.as_ref().map(|user| user.id.as_str()); | ||
| 126 | + let now = unix_now(); | ||
| 127 | + let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS); | ||
| 128 | + // Clients parse `issued_at` as an RFC 3339 time, so a number is refused. | ||
| 129 | + let issued_at = time::OffsetDateTime::now_utc() | ||
| 130 | + .format(&time::format_description::well_known::Rfc3339) | ||
| 131 | + .unwrap_or_default(); | ||
| 132 | + Ok(json_response( | ||
| 133 | + StatusCode::OK, | ||
| 134 | + &json!({ | ||
| 135 | + "token": token, | ||
| 136 | + "access_token": token, | ||
| 137 | + "expires_in": auth::TOKEN_TTL_SECS, | ||
| 138 | + "issued_at": issued_at, | ||
| 139 | + }), | ||
| 140 | + )) | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +#[route(GET "/v2/{*rest}")] | ||
| 144 | +async fn get_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 145 | + Ok(dispatch(cx, body).await) | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +#[route(POST "/v2/{*rest}")] | ||
| 149 | +async fn post_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 150 | + Ok(dispatch(cx, body).await) | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +#[route(PUT "/v2/{*rest}")] | ||
| 154 | +async fn put_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 155 | + Ok(dispatch(cx, body).await) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +#[route(PATCH "/v2/{*rest}")] | ||
| 159 | +async fn patch_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 160 | + Ok(dispatch(cx, body).await) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +#[route(DELETE "/v2/{*rest}")] | ||
| 164 | +async fn delete_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 165 | + Ok(dispatch(cx, body).await) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// Routes a request below `/v2/` to its operation. The caller is resolved first, so every answer | ||
| 169 | +/// about a repository comes from the same identity. | ||
| 170 | +async fn dispatch(cx: &Cx, body: Body) -> Response { | ||
| 171 | + let state = app_context::<AppState>(cx); | ||
| 172 | + let segments: Vec<String> = path_param::<Rest>(cx).map(str::to_owned).collect(); | ||
| 173 | + let mut parts: Vec<&str> = segments.iter().map(String::as_str).collect(); | ||
| 174 | + while parts.last() == Some(&"") { | ||
| 175 | + parts.pop(); | ||
| 176 | + } | ||
| 177 | + let caller = match auth::caller(cx).await { | ||
| 178 | + Ok(caller) => caller, | ||
| 179 | + Err(res) => return *res, | ||
| 180 | + }; | ||
| 181 | + let method = method(cx).clone(); | ||
| 182 | + let read = method == http::Method::GET || method == http::Method::HEAD; | ||
| 183 | + let head = method == http::Method::HEAD; | ||
| 184 | + let pairs = query_pairs(cx); | ||
| 185 | + let headers = headers(cx).clone(); | ||
| 186 | + let Some(op) = parse_op(&parts) else { | ||
| 187 | + return oci_error(StatusCode::NOT_FOUND, "NAME_UNKNOWN", "not found"); | ||
| 188 | + }; | ||
| 189 | + match op { | ||
| 190 | + Op::Tags { name } if read => { | ||
| 191 | + let n = query_value(&pairs, "n").and_then(|v| v.parse::<u64>().ok()); | ||
| 192 | + let last = query_value(&pairs, "last"); | ||
| 193 | + manifests::list_tags(state, &caller, &name, n, last.as_deref()).await | ||
| 194 | + } | ||
| 195 | + Op::Manifest { name, reference } => match method { | ||
| 196 | + http::Method::GET | http::Method::HEAD => { | ||
| 197 | + manifests::get_manifest(state, &caller, &name, &reference, head).await | ||
| 198 | + } | ||
| 199 | + http::Method::PUT => { | ||
| 200 | + let content_type = headers | ||
| 201 | + .get(CONTENT_TYPE) | ||
| 202 | + .and_then(|v| v.to_str().ok()) | ||
| 203 | + .map(str::to_owned); | ||
| 204 | + manifests::put_manifest( | ||
| 205 | + state, | ||
| 206 | + &caller, | ||
| 207 | + &name, | ||
| 208 | + &reference, | ||
| 209 | + content_type.as_deref(), | ||
| 210 | + body, | ||
| 211 | + ) | ||
| 212 | + .await | ||
| 213 | + } | ||
| 214 | + http::Method::DELETE => { | ||
| 215 | + manifests::delete_manifest(state, &caller, &name, &reference).await | ||
| 216 | + } | ||
| 217 | + _ => unsupported(), | ||
| 218 | + }, | ||
| 219 | + Op::Blob { name, digest } => match method { | ||
| 220 | + http::Method::GET | http::Method::HEAD => { | ||
| 221 | + blobs::get_blob(state, &caller, &name, &digest, head).await | ||
| 222 | + } | ||
| 223 | + http::Method::DELETE => match auth::authorize(state, &caller, &name, true).await { | ||
| 224 | + Ok(target) => blobs::delete_blob(state, &target, &digest).await, | ||
| 225 | + Err(res) => *res, | ||
| 226 | + }, | ||
| 227 | + _ => unsupported(), | ||
| 228 | + }, | ||
| 229 | + Op::UploadStart { name } if method == http::Method::POST => { | ||
| 230 | + start_upload(state, &caller, &name, &pairs, body).await | ||
| 231 | + } | ||
| 232 | + Op::Upload { name, id } => { | ||
| 233 | + upload_step(state, &caller, &name, &id, &method, &headers, &pairs, body).await | ||
| 234 | + } | ||
| 235 | + _ => unsupported(), | ||
| 236 | + } | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +fn unsupported() -> Response { | ||
| 240 | + oci_error( | ||
| 241 | + StatusCode::METHOD_NOT_ALLOWED, | ||
| 242 | + "UNSUPPORTED", | ||
| 243 | + "the operation is unsupported", | ||
| 244 | + ) | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +/// `POST /v2/{name}/blobs/uploads/`: a cross-repo mount when `mount` and `from` are given and | ||
| 248 | +/// possible, a monolithic upload when `digest` is given with the body, and otherwise a new session. | ||
| 249 | +async fn start_upload( | ||
| 250 | + state: &AppState, | ||
| 251 | + caller: &Caller, | ||
| 252 | + name: &str, | ||
| 253 | + pairs: &[(String, String)], | ||
| 254 | + body: Body, | ||
| 255 | +) -> Response { | ||
| 256 | + let target = match auth::authorize(state, caller, name, true).await { | ||
| 257 | + Ok(target) => target, | ||
| 258 | + Err(res) => return *res, | ||
| 259 | + }; | ||
| 260 | + if let (Some(mount), Some(from)) = (query_value(pairs, "mount"), query_value(pairs, "from")) { | ||
| 261 | + match blobs::try_mount(state, caller, &target, &mount, &from).await { | ||
| 262 | + Ok(true) => { | ||
| 263 | + let hex = rules::parse_digest(&mount).unwrap_or_default(); | ||
| 264 | + state.packages_live.bump(&target.owner.id); | ||
| 265 | + return blobs::created(name, hex); | ||
| 266 | + } | ||
| 267 | + Ok(false) => {} | ||
| 268 | + Err(res) => return *res, | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | + let data_dir = state.config.data_dir.clone(); | ||
| 272 | + let id = match blobs::new_session(&data_dir, name).await { | ||
| 273 | + Ok(id) => id, | ||
| 274 | + Err(e) => return auth::internal(e), | ||
| 275 | + }; | ||
| 276 | + let Some(digest) = query_value(pairs, "digest") else { | ||
| 277 | + return blobs::upload_progress(name, &id, 0); | ||
| 278 | + }; | ||
| 279 | + let hex = match blobs::digest_arg(&digest) { | ||
| 280 | + Ok(hex) => hex.to_owned(), | ||
| 281 | + Err(res) => { | ||
| 282 | + blobs::remove_session(&data_dir, &id).await; | ||
| 283 | + return *res; | ||
| 284 | + } | ||
| 285 | + }; | ||
| 286 | + if let Err(res) = blobs::append(&data_dir, &id, body, None).await { | ||
| 287 | + blobs::remove_session(&data_dir, &id).await; | ||
| 288 | + return *res; | ||
| 289 | + } | ||
| 290 | + finish_upload(state, &target, name, &id, &hex).await | ||
| 291 | +} | ||
| 292 | + | ||
| 293 | +/// Checks the session and the digest of a finished upload, links the blob to the package and | ||
| 294 | +/// removes the session. A digest that does not match refuses the upload and removes it. | ||
| 295 | +async fn finish_upload( | ||
| 296 | + state: &AppState, | ||
| 297 | + target: &auth::Target, | ||
| 298 | + name: &str, | ||
| 299 | + id: &str, | ||
| 300 | + hex: &str, | ||
| 301 | +) -> Response { | ||
| 302 | + let data_dir = state.config.data_dir.clone(); | ||
| 303 | + let path = blobs::uploads_dir(&data_dir).join(id); | ||
| 304 | + let actual = match blobs::file_sha256(&path).await { | ||
| 305 | + Ok(actual) => actual, | ||
| 306 | + Err(e) => return auth::internal(e), | ||
| 307 | + }; | ||
| 308 | + if actual != hex { | ||
| 309 | + blobs::remove_session(&data_dir, id).await; | ||
| 310 | + return oci_error( | ||
| 311 | + StatusCode::BAD_REQUEST, | ||
| 312 | + "DIGEST_INVALID", | ||
| 313 | + "the content does not match the digest", | ||
| 314 | + ); | ||
| 315 | + } | ||
| 316 | + let size = match tokio::fs::metadata(&path).await { | ||
| 317 | + Ok(meta) => meta.len(), | ||
| 318 | + Err(e) => return auth::internal(e), | ||
| 319 | + }; | ||
| 320 | + let package = match blobs::write_package(state, target).await { | ||
| 321 | + Ok(package) => package, | ||
| 322 | + Err(res) => return *res, | ||
| 323 | + }; | ||
| 324 | + if let Err(res) = blobs::link(state, &package, hex, size, Some(&path)).await { | ||
| 325 | + blobs::remove_session(&data_dir, id).await; | ||
| 326 | + return *res; | ||
| 327 | + } | ||
| 328 | + blobs::remove_session(&data_dir, id).await; | ||
| 329 | + state.packages_live.bump(&target.owner.id); | ||
| 330 | + blobs::created(name, hex) | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +/// The steps of an open upload: `GET` its status, `PATCH` a chunk, `PUT` the last chunk with the | ||
| 334 | +/// digest, and `DELETE` it. | ||
| 335 | +#[allow(clippy::too_many_arguments)] | ||
| 336 | +async fn upload_step( | ||
| 337 | + state: &AppState, | ||
| 338 | + caller: &Caller, | ||
| 339 | + name: &str, | ||
| 340 | + id: &str, | ||
| 341 | + method: &http::Method, | ||
| 342 | + headers: &http::HeaderMap, | ||
| 343 | + pairs: &[(String, String)], | ||
| 344 | + body: Body, | ||
| 345 | +) -> Response { | ||
| 346 | + let data_dir = state.config.data_dir.clone(); | ||
| 347 | + let target = match auth::authorize(state, caller, name, true).await { | ||
| 348 | + Ok(target) => target, | ||
| 349 | + Err(res) => return *res, | ||
| 350 | + }; | ||
| 351 | + if !blobs::session_belongs_to(&data_dir, id, name).await { | ||
| 352 | + return oci_error( | ||
| 353 | + StatusCode::NOT_FOUND, | ||
| 354 | + "BLOB_UPLOAD_UNKNOWN", | ||
| 355 | + "blob upload unknown to registry", | ||
| 356 | + ); | ||
| 357 | + } | ||
| 358 | + match *method { | ||
| 359 | + http::Method::GET => match blobs::session_size(&data_dir, id).await { | ||
| 360 | + Ok(size) => { | ||
| 361 | + let mut res = Response::new(Body::empty()); | ||
| 362 | + *res.status_mut() = StatusCode::NO_CONTENT; | ||
| 363 | + blobs::insert( | ||
| 364 | + &mut res, | ||
| 365 | + "location", | ||
| 366 | + &format!("/v2/{name}/blobs/uploads/{id}"), | ||
| 367 | + ); | ||
| 368 | + blobs::insert(&mut res, "docker-upload-uuid", id); | ||
| 369 | + blobs::insert(&mut res, "range", &blobs::range_of(size)); | ||
| 370 | + res | ||
| 371 | + } | ||
| 372 | + Err(e) => auth::internal(e), | ||
| 373 | + }, | ||
| 374 | + http::Method::PATCH => { | ||
| 375 | + if let Err(res) = | ||
| 376 | + blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await | ||
| 377 | + { | ||
| 378 | + return *res; | ||
| 379 | + } | ||
| 380 | + match blobs::session_size(&data_dir, id).await { | ||
| 381 | + Ok(size) => blobs::upload_progress(name, id, size), | ||
| 382 | + Err(e) => auth::internal(e), | ||
| 383 | + } | ||
| 384 | + } | ||
| 385 | + http::Method::PUT => { | ||
| 386 | + let Some(digest) = query_value(pairs, "digest") else { | ||
| 387 | + return oci_error( | ||
| 388 | + StatusCode::BAD_REQUEST, | ||
| 389 | + "DIGEST_INVALID", | ||
| 390 | + "digest is required", | ||
| 391 | + ); | ||
| 392 | + }; | ||
| 393 | + let hex = match blobs::digest_arg(&digest) { | ||
| 394 | + Ok(hex) => hex.to_owned(), | ||
| 395 | + Err(res) => return *res, | ||
| 396 | + }; | ||
| 397 | + if let Err(res) = | ||
| 398 | + blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await | ||
| 399 | + { | ||
| 400 | + return *res; | ||
| 401 | + } | ||
| 402 | + finish_upload(state, &target, name, id, &hex).await | ||
| 403 | + } | ||
| 404 | + http::Method::DELETE => { | ||
| 405 | + blobs::remove_session(&data_dir, id).await; | ||
| 406 | + let mut res = Response::new(Body::empty()); | ||
| 407 | + *res.status_mut() = StatusCode::NO_CONTENT; | ||
| 408 | + res | ||
| 409 | + } | ||
| 410 | + _ => unsupported(), | ||
| 411 | + } | ||
| 412 | +} | ||
| 413 | + | ||
| 414 | +#[cfg(test)] | ||
| 415 | +mod tests { | ||
| 416 | + use super::*; | ||
| 417 | + | ||
| 418 | + #[test] | ||
| 419 | + fn nested_names_parse_up_to_the_keyword() { | ||
| 420 | + assert_eq!( | ||
| 421 | + parse_op(&["tahinli", "app", "manifests", "latest"]), | ||
| 422 | + Some(Op::Manifest { | ||
| 423 | + name: "tahinli/app".into(), | ||
| 424 | + reference: "latest".into(), | ||
| 425 | + }) | ||
| 426 | + ); | ||
| 427 | + assert_eq!( | ||
| 428 | + parse_op(&["tahinli", "a", "b", "blobs", "uploads"]), | ||
| 429 | + Some(Op::UploadStart { | ||
| 430 | + name: "tahinli/a/b".into(), | ||
| 431 | + }) | ||
| 432 | + ); | ||
| 433 | + assert_eq!( | ||
| 434 | + parse_op(&["tahinli", "app", "tags", "list"]), | ||
| 435 | + Some(Op::Tags { | ||
| 436 | + name: "tahinli/app".into(), | ||
| 437 | + }) | ||
| 438 | + ); | ||
| 439 | + } | ||
| 440 | + | ||
| 441 | + #[test] | ||
| 442 | + fn a_keyword_inside_the_name_is_not_taken_for_one() { | ||
| 443 | + assert_eq!( | ||
| 444 | + parse_op(&["tahinli", "blobs", "x", "manifests", "v1"]), | ||
| 445 | + Some(Op::Manifest { | ||
| 446 | + name: "tahinli/blobs/x".into(), | ||
| 447 | + reference: "v1".into(), | ||
| 448 | + }) | ||
| 449 | + ); | ||
| 450 | + } | ||
| 451 | + | ||
| 452 | + #[test] | ||
| 453 | + fn upload_and_blob_paths_are_told_apart() { | ||
| 454 | + assert_eq!( | ||
| 455 | + parse_op(&["tahinli", "app", "blobs", "uploads", "ID1"]), | ||
| 456 | + Some(Op::Upload { | ||
| 457 | + name: "tahinli/app".into(), | ||
| 458 | + id: "ID1".into(), | ||
| 459 | + }) | ||
| 460 | + ); | ||
| 461 | + assert!(matches!( | ||
| 462 | + parse_op(&["tahinli", "app", "blobs", "sha256:abc"]), | ||
| 463 | + Some(Op::Blob { .. }) | ||
| 464 | + )); | ||
| 465 | + assert_eq!(parse_op(&["tahinli"]), None); | ||
| 466 | + } | ||
| 467 | +} | ||
crates/forge-web/src/package_ops.rsadded+323 -0
| @@ -0,0 +1,323 @@ | |||
| 1 | +//! Package registry rules of the web layer: who may read or publish a package, publishing a | ||
| 2 | +//! `.crate`, yanking a version, and the index and config files cargo reads. The protocol | ||
| 3 | +//! rules (names, index lines, publish bodies) live in `forge_core::cargo`; the HTTP routes in | ||
| 4 | +//! `api::packages` and the pages translate these results. Bytes go to the blob store under | ||
| 5 | +//! `packages/<version id>`, and each change is announced on the owner's live signal. | ||
| 6 | + | ||
| 7 | +use forge_core::cargo; | ||
| 8 | +use forge_core::model::User; | ||
| 9 | +use forge_core::packages::{KIND_CARGO, KIND_OCI, NewPackageVersion, Package}; | ||
| 10 | +use forge_core::store::orgs::OrgMemberRole; | ||
| 11 | +use forge_core::{Error, Repo}; | ||
| 12 | +use serde_json::{Value, json}; | ||
| 13 | +use sha2::{Digest, Sha256}; | ||
| 14 | + | ||
| 15 | +use crate::blobs::BlobRead; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +/// Largest `.crate` accepted, in bytes. The limit crates.io uses. | ||
| 19 | +pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024; | ||
| 20 | +/// Largest publish body accepted: the crate plus its JSON metadata. | ||
| 21 | +pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024; | ||
| 22 | +/// Bytes handed to the blob writer at a time. | ||
| 23 | +const PUSH_CHUNK: usize = 1024 * 1024; | ||
| 24 | + | ||
| 25 | +/// Why a registry request failed. The API maps each to a status and a cargo error body. | ||
| 26 | +#[derive(Debug)] | ||
| 27 | +pub enum PackageError { | ||
| 28 | + Invalid(String), | ||
| 29 | + NotFound, | ||
| 30 | + Forbidden, | ||
| 31 | + Conflict(String), | ||
| 32 | + TooLarge, | ||
| 33 | + Internal(String), | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +impl From<Error> for PackageError { | ||
| 37 | + fn from(e: Error) -> Self { | ||
| 38 | + match e { | ||
| 39 | + Error::InvalidName(msg) | Error::Invalid(msg) => Self::Invalid(msg), | ||
| 40 | + Error::NotFound => Self::NotFound, | ||
| 41 | + Error::Conflict(msg) => Self::Conflict(msg), | ||
| 42 | + other => Self::Internal(other.to_string()), | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The user or org a registry path names. `None` when no such account exists. | ||
| 48 | +pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> { | ||
| 49 | + Ok(state.store.user_by_username(name).await?) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// True when `actor` may read `package`. Public packages are readable by anyone. A private one | ||
| 53 | +/// is readable by the instance admin, the owner and the owner's org members. | ||
| 54 | +pub async fn may_read( | ||
| 55 | + state: &AppState, | ||
| 56 | + actor: Option<&User>, | ||
| 57 | + owner: &User, | ||
| 58 | + package: &Package, | ||
| 59 | +) -> Result<bool, PackageError> { | ||
| 60 | + if !package.private { | ||
| 61 | + return Ok(true); | ||
| 62 | + } | ||
| 63 | + let Some(actor) = actor else { | ||
| 64 | + return Ok(false); | ||
| 65 | + }; | ||
| 66 | + if actor.is_admin || actor.id == owner.id { | ||
| 67 | + return Ok(true); | ||
| 68 | + } | ||
| 69 | + Ok(owner.is_org() | ||
| 70 | + && state | ||
| 71 | + .store | ||
| 72 | + .org_member_role(&owner.id, &actor.id) | ||
| 73 | + .await? | ||
| 74 | + .is_some()) | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// True when `actor` may publish, yank or unyank in `owner`'s registry: the owner themselves, | ||
| 78 | +/// an org owner, or the instance admin. | ||
| 79 | +pub async fn may_publish( | ||
| 80 | + state: &AppState, | ||
| 81 | + actor: &User, | ||
| 82 | + owner: &User, | ||
| 83 | +) -> Result<bool, PackageError> { | ||
| 84 | + if actor.is_admin || actor.id == owner.id { | ||
| 85 | + return Ok(true); | ||
| 86 | + } | ||
| 87 | + if !owner.is_org() { | ||
| 88 | + return Ok(false); | ||
| 89 | + } | ||
| 90 | + let role = state.store.org_member_role(&owner.id, &actor.id).await?; | ||
| 91 | + Ok(role == Some(OrgMemberRole::Owner)) | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// The package `name` of `owner` as the actor may see it. A missing package and a private one | ||
| 95 | +/// the actor may not read are the same `NotFound`. | ||
| 96 | +pub async fn readable_package( | ||
| 97 | + state: &AppState, | ||
| 98 | + actor: Option<&User>, | ||
| 99 | + owner: &User, | ||
| 100 | + name: &str, | ||
| 101 | +) -> Result<Package, PackageError> { | ||
| 102 | + let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; | ||
| 103 | + let package = state | ||
| 104 | + .store | ||
| 105 | + .package_by_name(&owner.id, KIND_CARGO, &key) | ||
| 106 | + .await? | ||
| 107 | + .ok_or(PackageError::NotFound)?; | ||
| 108 | + if !may_read(state, actor, owner, &package).await? { | ||
| 109 | + return Err(PackageError::NotFound); | ||
| 110 | + } | ||
| 111 | + Ok(package) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// A container image of `owner` that the viewer may read. The name is the image path below the | ||
| 115 | +/// owner, as the registry stores it. | ||
| 116 | +pub async fn readable_oci_package( | ||
| 117 | + state: &AppState, | ||
| 118 | + actor: Option<&User>, | ||
| 119 | + owner: &User, | ||
| 120 | + name: &str, | ||
| 121 | +) -> Result<Package, PackageError> { | ||
| 122 | + let package = state | ||
| 123 | + .store | ||
| 124 | + .package_by_name(&owner.id, KIND_OCI, name) | ||
| 125 | + .await? | ||
| 126 | + .ok_or(PackageError::NotFound)?; | ||
| 127 | + if !may_read(state, actor, owner, &package).await? { | ||
| 128 | + return Err(PackageError::NotFound); | ||
| 129 | + } | ||
| 130 | + Ok(package) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// The `config.json` of an owner's registry. `auth-required` is set when the owner has a private | ||
| 134 | +/// package, since cargo then needs a token for every request to that registry. | ||
| 135 | +pub async fn config_json(state: &AppState, owner: &User) -> Result<Value, PackageError> { | ||
| 136 | + let base = state.config.base_url.trim_end_matches('/'); | ||
| 137 | + let auth_required = state.store.owner_has_private_packages(&owner.id).await?; | ||
| 138 | + Ok(json!({ | ||
| 139 | + "dl": format!("{base}/api/packages/{}/cargo/download/{{crate}}/{{version}}", owner.username), | ||
| 140 | + "api": format!("{base}/api/packages/{}/cargo", owner.username), | ||
| 141 | + "auth-required": auth_required, | ||
| 142 | + })) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// The index file of a package: one JSON line per version, oldest first, each with the current | ||
| 146 | +/// yank state. A package with no versions has no index. | ||
| 147 | +pub async fn index_file(state: &AppState, package: &Package) -> Result<String, PackageError> { | ||
| 148 | + let mut versions = state.store.package_versions(&package.id).await?; | ||
| 149 | + versions.reverse(); | ||
| 150 | + let mut out = String::new(); | ||
| 151 | + for version in versions { | ||
| 152 | + let mut line: Value = serde_json::from_str(&version.index_json) | ||
| 153 | + .map_err(|e| PackageError::Internal(format!("stored index line: {e}")))?; | ||
| 154 | + line["yanked"] = json!(version.yanked); | ||
| 155 | + out.push_str(&line.to_string()); | ||
| 156 | + out.push('\n'); | ||
| 157 | + } | ||
| 158 | + Ok(out) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +/// Publishes a `.crate` from a publish body. The version row is written first, so a repeated | ||
| 162 | +/// version is a `Conflict` before any bytes are stored. A failed byte write removes the row. | ||
| 163 | +pub async fn publish( | ||
| 164 | + state: &AppState, | ||
| 165 | + owner: &User, | ||
| 166 | + actor: &User, | ||
| 167 | + body: &[u8], | ||
| 168 | +) -> Result<(), PackageError> { | ||
| 169 | + if !may_publish(state, actor, owner).await? { | ||
| 170 | + return Err(PackageError::Forbidden); | ||
| 171 | + } | ||
| 172 | + let parsed = cargo::parse_publish(body).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 173 | + let meta = &parsed.metadata; | ||
| 174 | + let name = cargo::meta_str(meta, "name") | ||
| 175 | + .ok_or_else(|| PackageError::Invalid("metadata has no name".into()))?; | ||
| 176 | + let vers = cargo::meta_str(meta, "vers") | ||
| 177 | + .ok_or_else(|| PackageError::Invalid("metadata has no vers".into()))?; | ||
| 178 | + let key = cargo::crate_name_key(name).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 179 | + cargo::parse_version(vers).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 180 | + let krate = parsed.crate_file; | ||
| 181 | + if krate.len() as u64 > MAX_CRATE_BYTES { | ||
| 182 | + return Err(PackageError::TooLarge); | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + let checksum = hex::encode(Sha256::digest(krate)); | ||
| 186 | + let index_line = cargo::index_line(meta, &checksum) | ||
| 187 | + .map_err(|e| PackageError::Invalid(e.to_string()))? | ||
| 188 | + .to_string(); | ||
| 189 | + let readme = cargo::crate_readme(krate) | ||
| 190 | + .or_else(|| cargo::meta_str(meta, "readme").map(str::to_owned)) | ||
| 191 | + .filter(|text| !text.trim().is_empty()); | ||
| 192 | + let description = cargo::meta_str(meta, "description") | ||
| 193 | + .map(str::trim) | ||
| 194 | + .filter(|text| !text.is_empty()); | ||
| 195 | + | ||
| 196 | + let package = state | ||
| 197 | + .store | ||
| 198 | + .ensure_package(&owner.id, KIND_CARGO, name, &key) | ||
| 199 | + .await?; | ||
| 200 | + link_repo(state, owner, &package, meta).await?; | ||
| 201 | + | ||
| 202 | + let version = state | ||
| 203 | + .store | ||
| 204 | + .publish_package_version(&NewPackageVersion { | ||
| 205 | + package_id: &package.id, | ||
| 206 | + version: vers, | ||
| 207 | + checksum: &checksum, | ||
| 208 | + size: krate.len() as u64, | ||
| 209 | + index_json: &index_line, | ||
| 210 | + description, | ||
| 211 | + readme: readme.as_deref(), | ||
| 212 | + publisher_id: &actor.id, | ||
| 213 | + }) | ||
| 214 | + .await | ||
| 215 | + .map_err(|e| match e { | ||
| 216 | + Error::Conflict(_) => { | ||
| 217 | + PackageError::Conflict(format!("crate version `{name}@{vers}` is already uploaded")) | ||
| 218 | + } | ||
| 219 | + other => other.into(), | ||
| 220 | + })?; | ||
| 221 | + | ||
| 222 | + if let Err(e) = store_bytes(state, &blob_key(&version.id), krate).await { | ||
| 223 | + // Best effort: the row must not outlive its bytes. | ||
| 224 | + let _ = state.store.delete_package_version(&package.id, vers).await; | ||
| 225 | + return Err(PackageError::Internal(e.to_string())); | ||
| 226 | + } | ||
| 227 | + state.packages_live.bump(&owner.id); | ||
| 228 | + Ok(()) | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +/// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable, | ||
| 232 | +/// marked as yanked, so existing lockfiles keep working. | ||
| 233 | +pub async fn set_yanked( | ||
| 234 | + state: &AppState, | ||
| 235 | + owner: &User, | ||
| 236 | + actor: &User, | ||
| 237 | + name: &str, | ||
| 238 | + version: &str, | ||
| 239 | + yanked: bool, | ||
| 240 | +) -> Result<(), PackageError> { | ||
| 241 | + if !may_publish(state, actor, owner).await? { | ||
| 242 | + return Err(PackageError::Forbidden); | ||
| 243 | + } | ||
| 244 | + let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; | ||
| 245 | + let package = state | ||
| 246 | + .store | ||
| 247 | + .package_by_name(&owner.id, KIND_CARGO, &key) | ||
| 248 | + .await? | ||
| 249 | + .ok_or(PackageError::NotFound)?; | ||
| 250 | + if !state | ||
| 251 | + .store | ||
| 252 | + .set_package_version_yanked(&package.id, version, yanked) | ||
| 253 | + .await? | ||
| 254 | + { | ||
| 255 | + return Err(PackageError::NotFound); | ||
| 256 | + } | ||
| 257 | + state.packages_live.bump(&owner.id); | ||
| 258 | + Ok(()) | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +/// The `.crate` bytes of a version, for a download. Yanked versions still download. | ||
| 262 | +pub async fn download( | ||
| 263 | + state: &AppState, | ||
| 264 | + actor: Option<&User>, | ||
| 265 | + owner: &User, | ||
| 266 | + name: &str, | ||
| 267 | + version: &str, | ||
| 268 | +) -> Result<BlobRead, PackageError> { | ||
| 269 | + let package = readable_package(state, actor, owner, name).await?; | ||
| 270 | + let found = state | ||
| 271 | + .store | ||
| 272 | + .package_version(&package.id, version) | ||
| 273 | + .await? | ||
| 274 | + .ok_or(PackageError::NotFound)?; | ||
| 275 | + state | ||
| 276 | + .blobs | ||
| 277 | + .read(&blob_key(&found.id)) | ||
| 278 | + .await? | ||
| 279 | + .ok_or(PackageError::NotFound) | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +/// The blob key of a version's `.crate` file. | ||
| 283 | +pub fn blob_key(version_id: &str) -> String { | ||
| 284 | + format!("packages/{version_id}") | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +/// Points the package at the repo its `repository` field names, when that repo belongs to the | ||
| 288 | +/// same owner. A repo of another owner is never linked, so nobody can claim it. | ||
| 289 | +async fn link_repo( | ||
| 290 | + state: &AppState, | ||
| 291 | + owner: &User, | ||
| 292 | + package: &Package, | ||
| 293 | + meta: &Value, | ||
| 294 | +) -> Result<(), PackageError> { | ||
| 295 | + let linked: Option<Repo> = match cargo::meta_str(meta, "repository") | ||
| 296 | + .and_then(|url| cargo::repo_link(url, &state.config.base_url)) | ||
| 297 | + { | ||
| 298 | + Some((repo_owner, repo_name)) if repo_owner.eq_ignore_ascii_case(&owner.username) => state | ||
| 299 | + .store | ||
| 300 | + .repo_by_owner_and_name(&repo_owner, &repo_name) | ||
| 301 | + .await? | ||
| 302 | + .filter(|repo| repo.owner_id == owner.id), | ||
| 303 | + _ => None, | ||
| 304 | + }; | ||
| 305 | + let repo_id = linked.as_ref().map(|repo| repo.id.as_str()); | ||
| 306 | + if package.repo_id.as_deref() != repo_id { | ||
| 307 | + state.store.set_package_repo(&package.id, repo_id).await?; | ||
| 308 | + } | ||
| 309 | + Ok(()) | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +/// Streams `bytes` into the blob store under `key`, returning the sha256 the store computed. | ||
| 313 | +async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<String> { | ||
| 314 | + let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?; | ||
| 315 | + for chunk in bytes.chunks(PUSH_CHUNK) { | ||
| 316 | + if let Err(e) = writer.push(chunk).await { | ||
| 317 | + writer.abort().await; | ||
| 318 | + return Err(e); | ||
| 319 | + } | ||
| 320 | + } | ||
| 321 | + let (_, sha) = writer.finish().await?; | ||
| 322 | + Ok(sha) | ||
| 323 | +} | ||
crates/forge-web/src/packages_live.rsadded+80 -0
| @@ -0,0 +1,80 @@ | |||
| 1 | +//! Change signals for package registries. [`PackagesLive`] keeps one generation counter per owner. | ||
| 2 | +//! A publish or a yank bumps the owner's counter, and every open page of that registry wakes and | ||
| 3 | +//! refetches. The counter carries no data, and nothing polls. A signal with no receivers left is | ||
| 4 | +//! removed, so the map holds only the owners somebody is watching. The hub is in-process only, | ||
| 5 | +//! like [`NotifyHub`]. | ||
| 6 | +//! | ||
| 7 | +//! [`NotifyHub`]: crate::notify_hub::NotifyHub | ||
| 8 | + | ||
| 9 | +use std::collections::HashMap; | ||
| 10 | +use std::sync::{Mutex, MutexGuard, PoisonError}; | ||
| 11 | + | ||
| 12 | +use tokio::sync::watch; | ||
| 13 | + | ||
| 14 | +/// The change counters of package registries, each keyed by its owner's id. | ||
| 15 | +#[derive(Default)] | ||
| 16 | +pub struct PackagesLive { | ||
| 17 | + owners: Mutex<HashMap<String, watch::Sender<u64>>>, | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +impl PackagesLive { | ||
| 21 | + /// Subscribes to changes of `owner_id`'s registry. The receiver starts as seen, so a bump | ||
| 22 | + /// after this call wakes it. Subscribe before the state you read, so a change in between is | ||
| 23 | + /// not lost. | ||
| 24 | + pub fn subscribe(&self, owner_id: &str) -> watch::Receiver<u64> { | ||
| 25 | + self.owners() | ||
| 26 | + .entry(owner_id.to_owned()) | ||
| 27 | + .or_insert_with(|| watch::channel(0).0) | ||
| 28 | + .subscribe() | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + /// Counts one change to `owner_id`'s registry. Without a subscriber there is no entry, so the | ||
| 32 | + /// bump is a no-op. An entry whose last receiver is gone is removed here. | ||
| 33 | + pub fn bump(&self, owner_id: &str) { | ||
| 34 | + let mut owners = self.owners(); | ||
| 35 | + let Some(tx) = owners.get(owner_id) else { | ||
| 36 | + return; | ||
| 37 | + }; | ||
| 38 | + tx.send_modify(|generation| *generation = generation.wrapping_add(1)); | ||
| 39 | + if tx.receiver_count() == 0 { | ||
| 40 | + owners.remove(owner_id); | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + fn owners(&self) -> MutexGuard<'_, HashMap<String, watch::Sender<u64>>> { | ||
| 45 | + self.owners.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[cfg(test)] | ||
| 50 | +mod tests { | ||
| 51 | + use std::time::Duration; | ||
| 52 | + | ||
| 53 | + use super::*; | ||
| 54 | + | ||
| 55 | + #[tokio::test] | ||
| 56 | + async fn a_bump_wakes_only_the_subscribers_of_that_owner() { | ||
| 57 | + let live = PackagesLive::default(); | ||
| 58 | + let mut tahinli = live.subscribe("user-1"); | ||
| 59 | + let mut other = live.subscribe("user-2"); | ||
| 60 | + | ||
| 61 | + live.bump("user-1"); | ||
| 62 | + | ||
| 63 | + tokio::time::timeout(Duration::from_secs(1), tahinli.changed()) | ||
| 64 | + .await | ||
| 65 | + .expect("woken") | ||
| 66 | + .expect("open"); | ||
| 67 | + assert!( | ||
| 68 | + tokio::time::timeout(Duration::from_millis(50), other.changed()) | ||
| 69 | + .await | ||
| 70 | + .is_err() | ||
| 71 | + ); | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + #[test] | ||
| 75 | + fn a_bump_without_subscribers_leaves_no_entry() { | ||
| 76 | + let live = PackagesLive::default(); | ||
| 77 | + live.bump("nobody"); | ||
| 78 | + assert!(live.owners().is_empty()); | ||
| 79 | + } | ||
| 80 | +} | ||
crates/forge-web/src/pages/mod.rsmodified+2 -0
| @@ -71,6 +71,8 @@ pub mod org_members; | |||
| 71 | pub mod org_new; | 71 | pub mod org_new; |
| 72 | pub mod org_settings; | 72 | pub mod org_settings; |
| 73 | pub mod org_teams; | 73 | pub mod org_teams; |
| 74 | +pub mod packages; | ||
| 75 | +pub mod packages_oci; | ||
| 74 | pub mod passkeys; | 76 | pub mod passkeys; |
| 75 | #[cfg(test)] | 77 | #[cfg(test)] |
| 76 | mod passkeys_tests; | 78 | mod passkeys_tests; |
crates/forge-web/src/pages/packages.rsadded+460 -0
| @@ -0,0 +1,460 @@ | |||
| 1 | +//! Pages of the package registries: a package page at `/{owner}/-/packages/{name}` with its | ||
| 2 | +//! install snippet, README and versions, and the owner's `changed` stream that both the package | ||
| 3 | +//! page and the profile's Packages tab follow. The rows of the Packages tab are built here and | ||
| 4 | +//! rendered by the profile page. | ||
| 5 | + | ||
| 6 | +use forge_core::User; | ||
| 7 | +use forge_core::packages::{KIND_CARGO, KIND_OCI, Package}; | ||
| 8 | +use futures_util::{Stream, stream}; | ||
| 9 | +use serde::Deserialize; | ||
| 10 | +use tokio::sync::watch; | ||
| 11 | +use topcoat::Result; | ||
| 12 | +use topcoat::context::{Cx, app_context}; | ||
| 13 | +use topcoat::router::content::Form; | ||
| 14 | +use topcoat::router::content::sse::Event; | ||
| 15 | +use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; | ||
| 16 | +use topcoat::router::response::Response; | ||
| 17 | +use topcoat::router::{page, path_param, query_params, route}; | ||
| 18 | +use topcoat::view::{Unescaped, View, component, view}; | ||
| 19 | + | ||
| 20 | +use crate::auth::{current_user, require_csrf}; | ||
| 21 | +use crate::i18n::packages::{self as pk, K}; | ||
| 22 | +use crate::i18n::{self, Lang}; | ||
| 23 | +use crate::oci::manifests; | ||
| 24 | +use crate::package_ops::{self, PackageError}; | ||
| 25 | +use crate::pages::ci_runs::{changed_event, events_response}; | ||
| 26 | +use crate::pages::packages_oci::{self, oci_package_view}; | ||
| 27 | +use crate::render::markdown::render_markdown; | ||
| 28 | +use crate::state::AppState; | ||
| 29 | +use crate::views::{enc, shell}; | ||
| 30 | + | ||
| 31 | +path_param!(owner); | ||
| 32 | +path_param!(name); | ||
| 33 | +path_param!(*pkg); | ||
| 34 | + | ||
| 35 | +/// One package on a list: what the Packages tab and the owner's lists show. | ||
| 36 | +pub(crate) struct PackageRow { | ||
| 37 | + pub name: String, | ||
| 38 | + pub href: String, | ||
| 39 | + pub latest: String, | ||
| 40 | + pub versions: u64, | ||
| 41 | + pub description: String, | ||
| 42 | + pub private: bool, | ||
| 43 | + /// True for a container image, which shows tags instead of versions. | ||
| 44 | + pub container: bool, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// The package path of a package under its owner. | ||
| 48 | +pub(crate) fn package_href(owner: &str, name: &str) -> String { | ||
| 49 | + format!("/{}/-/packages/{}", enc(owner), enc(name)) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// The owner's live `changed` stream. Its path is the owner's profile path plus `/-/packages/events`. | ||
| 53 | +pub(crate) fn events_href(owner: &str) -> String { | ||
| 54 | + format!("/{}/-/packages/events", enc(owner)) | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// The packages of `owner` that `viewer` may see, with a version, newest first by name. | ||
| 58 | +/// Packages without a version are not listed. | ||
| 59 | +pub(crate) async fn package_rows( | ||
| 60 | + state: &AppState, | ||
| 61 | + viewer: Option<&User>, | ||
| 62 | + owner: &User, | ||
| 63 | +) -> forge_core::Result<Vec<PackageRow>> { | ||
| 64 | + let mut summaries = state.store.list_packages(&owner.id, KIND_CARGO).await?; | ||
| 65 | + summaries.extend(state.store.list_packages(&owner.id, KIND_OCI).await?); | ||
| 66 | + summaries.sort_by(|a, b| a.package.name_key.cmp(&b.package.name_key)); | ||
| 67 | + let mut rows = Vec::new(); | ||
| 68 | + for summary in summaries { | ||
| 69 | + if summary.version_count == 0 { | ||
| 70 | + continue; | ||
| 71 | + } | ||
| 72 | + let readable = package_ops::may_read(state, viewer, owner, &summary.package) | ||
| 73 | + .await | ||
| 74 | + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?; | ||
| 75 | + if !readable { | ||
| 76 | + continue; | ||
| 77 | + } | ||
| 78 | + rows.push(PackageRow { | ||
| 79 | + href: package_href(&owner.username, &summary.package.name), | ||
| 80 | + name: summary.package.name, | ||
| 81 | + latest: summary.latest_version.unwrap_or_default(), | ||
| 82 | + versions: summary.version_count, | ||
| 83 | + description: summary.latest_description.unwrap_or_default(), | ||
| 84 | + private: summary.package.private, | ||
| 85 | + container: summary.package.kind == KIND_OCI, | ||
| 86 | + }); | ||
| 87 | + } | ||
| 88 | + Ok(rows) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Query of the package page: `readme` (the default) or `versions`. | ||
| 92 | +#[topcoat::router::query_params(error = bad_request)] | ||
| 93 | +struct PackageQuery { | ||
| 94 | + tab: Option<String>, | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// The package page: the head with the install snippet, then one tab of README or versions. | ||
| 98 | +#[page("/{owner}/-/packages/{*pkg}")] | ||
| 99 | +async fn package_page(cx: &Cx) -> Result<impl View> { | ||
| 100 | + let owner_name = path_param::<Owner>(cx); | ||
| 101 | + let pkg_name = path_param::<Pkg>(cx).collect::<Vec<_>>().join("/"); | ||
| 102 | + let pkg_name = pkg_name.as_str(); | ||
| 103 | + let state = app_context::<AppState>(cx); | ||
| 104 | + let viewer = current_user(cx).await?; | ||
| 105 | + let query = query_params::<PackageQuery>(cx)?; | ||
| 106 | + let actor = viewer.as_ref().map(|(u, _)| u); | ||
| 107 | + let lang = i18n::lang(cx, actor); | ||
| 108 | + | ||
| 109 | + let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 110 | + return Err(not_found().into()); | ||
| 111 | + }; | ||
| 112 | + let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await { | ||
| 113 | + Ok(package) => package, | ||
| 114 | + Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await { | ||
| 115 | + Ok(package) => package, | ||
| 116 | + Err(_) => return Err(not_found().into()), | ||
| 117 | + }, | ||
| 118 | + }; | ||
| 119 | + let csrf = viewer | ||
| 120 | + .as_ref() | ||
| 121 | + .map(|(_, s)| s.csrf_token.clone()) | ||
| 122 | + .unwrap_or_default(); | ||
| 123 | + let oci = if package.kind == KIND_OCI { | ||
| 124 | + Some(packages_oci::model(state, actor, csrf, &owner, package.clone(), lang).await?) | ||
| 125 | + } else { | ||
| 126 | + None | ||
| 127 | + }; | ||
| 128 | + let versions = state.store.package_versions(&package.id).await?; | ||
| 129 | + let latest = versions.iter().find(|v| !v.yanked).or(versions.first()); | ||
| 130 | + let readme_html = latest | ||
| 131 | + .and_then(|v| v.readme.as_deref()) | ||
| 132 | + .filter(|text| !text.trim().is_empty()) | ||
| 133 | + .map(|text| render_markdown(text, None)) | ||
| 134 | + .unwrap_or_default(); | ||
| 135 | + let description = latest | ||
| 136 | + .and_then(|v| v.description.clone()) | ||
| 137 | + .unwrap_or_default(); | ||
| 138 | + // The linked repo is named only when it is public, so a private repo name never shows here. | ||
| 139 | + let repo_link = match package.repo_id.as_deref() { | ||
| 140 | + Some(id) => match state.store.repo_by_id(id).await? { | ||
| 141 | + Some(repo) if repo.visibility == forge_core::Visibility::Public => { | ||
| 142 | + match state.store.user_by_id(&repo.owner_id).await? { | ||
| 143 | + Some(repo_owner) => Some(( | ||
| 144 | + format!("/{}/{}", enc(&repo_owner.username), enc(&repo.name)), | ||
| 145 | + format!("{}/{}", repo_owner.username, repo.name), | ||
| 146 | + )), | ||
| 147 | + None => None, | ||
| 148 | + } | ||
| 149 | + } | ||
| 150 | + _ => None, | ||
| 151 | + }, | ||
| 152 | + None => None, | ||
| 153 | + }; | ||
| 154 | + let base = state.config.base_url.trim_end_matches('/').to_owned(); | ||
| 155 | + let registry = format!("sparse+{base}/api/packages/{}/cargo/", owner.username); | ||
| 156 | + let config_block = format!("[registries.{}]\nindex = \"{registry}\"", owner.username); | ||
| 157 | + let add_cmd = format!("cargo add --registry {} {}", owner.username, package.name); | ||
| 158 | + let publish_cmd = format!("cargo publish --registry {}", owner.username); | ||
| 159 | + let login_cmd = format!("cargo login --registry {}", owner.username); | ||
| 160 | + let versions_tab = query.tab.as_deref() == Some("versions"); | ||
| 161 | + let version_rows: Vec<(String, String, bool, String)> = versions | ||
| 162 | + .iter() | ||
| 163 | + .map(|v| { | ||
| 164 | + ( | ||
| 165 | + v.version.clone(), | ||
| 166 | + v.created_at.get(..10).unwrap_or(&v.created_at).to_owned(), | ||
| 167 | + v.yanked, | ||
| 168 | + v.checksum.clone(), | ||
| 169 | + ) | ||
| 170 | + }) | ||
| 171 | + .collect(); | ||
| 172 | + let readme_href = format!( | ||
| 173 | + "{}?tab=readme", | ||
| 174 | + package_href(&owner.username, &package.name) | ||
| 175 | + ); | ||
| 176 | + let versions_href = format!( | ||
| 177 | + "{}?tab=versions", | ||
| 178 | + package_href(&owner.username, &package.name) | ||
| 179 | + ); | ||
| 180 | + let events = events_href(&owner.username); | ||
| 181 | + let latest_text = latest.map(|v| v.version.clone()).unwrap_or_default(); | ||
| 182 | + let title = match &oci { | ||
| 183 | + Some(page) => format!("{} {}", page.package.name, page.newest_tag), | ||
| 184 | + None => format!("{} {}", package.name, latest_text), | ||
| 185 | + }; | ||
| 186 | + let view_model = PackagePage { | ||
| 187 | + owner_name: owner.username.clone(), | ||
| 188 | + package, | ||
| 189 | + latest_text, | ||
| 190 | + description, | ||
| 191 | + repo_link, | ||
| 192 | + readme_html, | ||
| 193 | + versions_tab, | ||
| 194 | + readme_href, | ||
| 195 | + versions_href, | ||
| 196 | + events, | ||
| 197 | + config_block, | ||
| 198 | + add_cmd, | ||
| 199 | + publish_cmd, | ||
| 200 | + login_cmd, | ||
| 201 | + version_rows, | ||
| 202 | + lang, | ||
| 203 | + }; | ||
| 204 | + Ok(view! { cx => | ||
| 205 | + shell(title: title.as_str(), viewer: viewer.as_ref(), | ||
| 206 | + if let Some(page) = oci { | ||
| 207 | + oci_package_view(page: page) | ||
| 208 | + } else { | ||
| 209 | + package_view(page: view_model) | ||
| 210 | + }) | ||
| 211 | + }) | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// The form of a tag delete: the csrf token, the package name and the tag. | ||
| 215 | +#[derive(Deserialize)] | ||
| 216 | +struct TagDeleteForm { | ||
| 217 | + #[serde(default)] | ||
| 218 | + csrf: String, | ||
| 219 | + #[serde(default)] | ||
| 220 | + package: String, | ||
| 221 | + #[serde(default)] | ||
| 222 | + tag: String, | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +/// Deletes one tag of a container image and returns to the package page. Only the registry's | ||
| 226 | +/// owner, an org owner, or the instance admin may do it. The page sends it from a confirm popover. | ||
| 227 | +#[route(POST "/{owner}/-/packages/tags/delete")] | ||
| 228 | +async fn tag_delete(cx: &Cx, Form(form): Form<TagDeleteForm>) -> Result<SeeOther> { | ||
| 229 | + let (viewer, _) = require_csrf(cx, &form.csrf).await?; | ||
| 230 | + let owner_name = path_param::<Owner>(cx); | ||
| 231 | + let state = app_context::<AppState>(cx); | ||
| 232 | + let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 233 | + return Err(not_found().into()); | ||
| 234 | + }; | ||
| 235 | + let allowed = package_ops::may_publish(state, &viewer, &owner) | ||
| 236 | + .await | ||
| 237 | + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?; | ||
| 238 | + if !allowed { | ||
| 239 | + return Err(forbidden().into()); | ||
| 240 | + } | ||
| 241 | + let Some(package) = state | ||
| 242 | + .store | ||
| 243 | + .package_by_name(&owner.id, KIND_OCI, &form.package) | ||
| 244 | + .await? | ||
| 245 | + else { | ||
| 246 | + return Err(not_found().into()); | ||
| 247 | + }; | ||
| 248 | + manifests::remove_tag(state, &owner, &package, &form.tag).await?; | ||
| 249 | + Ok(see_other(package_href(&owner.username, &package.name))) | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +/// What the package page shows, prepared by the handler. | ||
| 253 | +struct PackagePage { | ||
| 254 | + owner_name: String, | ||
| 255 | + package: Package, | ||
| 256 | + latest_text: String, | ||
| 257 | + description: String, | ||
| 258 | + repo_link: Option<(String, String)>, | ||
| 259 | + readme_html: String, | ||
| 260 | + versions_tab: bool, | ||
| 261 | + readme_href: String, | ||
| 262 | + versions_href: String, | ||
| 263 | + events: String, | ||
| 264 | + config_block: String, | ||
| 265 | + add_cmd: String, | ||
| 266 | + publish_cmd: String, | ||
| 267 | + login_cmd: String, | ||
| 268 | + version_rows: Vec<(String, String, bool, String)>, | ||
| 269 | + lang: Lang, | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// The package page body. | ||
| 273 | +#[component] | ||
| 274 | +async fn package_view(page: PackagePage) -> Result<impl View> { | ||
| 275 | + let lang = page.lang; | ||
| 276 | + let PackagePage { | ||
| 277 | + owner_name, | ||
| 278 | + package, | ||
| 279 | + latest_text, | ||
| 280 | + description, | ||
| 281 | + repo_link, | ||
| 282 | + readme_html, | ||
| 283 | + versions_tab, | ||
| 284 | + readme_href, | ||
| 285 | + versions_href, | ||
| 286 | + events, | ||
| 287 | + config_block, | ||
| 288 | + add_cmd, | ||
| 289 | + publish_cmd, | ||
| 290 | + login_cmd, | ||
| 291 | + version_rows, | ||
| 292 | + .. | ||
| 293 | + } = page; | ||
| 294 | + let has_readme = !readme_html.is_empty(); | ||
| 295 | + let has_repo = repo_link.is_some(); | ||
| 296 | + let (repo_href, repo_text) = repo_link.unwrap_or_default(); | ||
| 297 | + let private = package.private; | ||
| 298 | + let readme_on = !versions_tab; | ||
| 299 | + let readme_class = if readme_on { "tab active" } else { "tab" }; | ||
| 300 | + let versions_class = if versions_tab { "tab active" } else { "tab" }; | ||
| 301 | + let has_versions = !version_rows.is_empty(); | ||
| 302 | + let install = pk::t(lang, K::Install); | ||
| 303 | + let copy_label = pk::t(lang, K::CopyCommand); | ||
| 304 | + let readme_label = pk::t(lang, K::Readme); | ||
| 305 | + let versions_label = pk::t(lang, K::PackageVersions); | ||
| 306 | + let no_readme = pk::t(lang, K::NoReadme); | ||
| 307 | + Ok(view! { | ||
| 308 | + <article class="package-page" data-live=(events.as_str())> | ||
| 309 | + <header class="package-head"> | ||
| 310 | + <div> | ||
| 311 | + <p class="muted small">(owner_name.as_str()) " / " (pk::t(lang, K::TabPackages))</p> | ||
| 312 | + <h1>(package.name.as_str()) " " <span class="muted">(latest_text.as_str())</span></h1> | ||
| 313 | + if !description.is_empty() { | ||
| 314 | + <p class="muted">(description.as_str())</p> | ||
| 315 | + } | ||
| 316 | + if private { | ||
| 317 | + <span class="badge">(pk::t(lang, K::PackagePrivate))</span> | ||
| 318 | + } | ||
| 319 | + if has_repo { | ||
| 320 | + <p class="small">(pk::t(lang, K::PackageRepoLink)) ": " <a href=(repo_href.as_str())>(repo_text.as_str())</a></p> | ||
| 321 | + } | ||
| 322 | + </div> | ||
| 323 | + </header> | ||
| 324 | + <section class="package-install"> | ||
| 325 | + <h2>(install)</h2> | ||
| 326 | + <p class="muted small">(pk::t(lang, K::InstallHelp))</p> | ||
| 327 | + <p class="small">(pk::t(lang, K::InstallRegistryConfig))</p> | ||
| 328 | + <div class="copy-box"> | ||
| 329 | + <code id="pkg-config">(config_block.as_str())</code> | ||
| 330 | + <button type="button" data-copy="pkg-config">(copy_label)</button> | ||
| 331 | + </div> | ||
| 332 | + <p class="small">(pk::t(lang, K::InstallAdd))</p> | ||
| 333 | + <div class="copy-box"> | ||
| 334 | + <code id="pkg-add">(add_cmd.as_str())</code> | ||
| 335 | + <button type="button" data-copy="pkg-add">(copy_label)</button> | ||
| 336 | + </div> | ||
| 337 | + <p class="small">(pk::t(lang, K::InstallPublish))</p> | ||
| 338 | + <div class="copy-box"> | ||
| 339 | + <code id="pkg-publish">(publish_cmd.as_str())</code> | ||
| 340 | + <button type="button" data-copy="pkg-publish">(copy_label)</button> | ||
| 341 | + </div> | ||
| 342 | + <p class="small">(pk::t(lang, K::InstallLogin))</p> | ||
| 343 | + <div class="copy-box"> | ||
| 344 | + <code id="pkg-login">(login_cmd.as_str())</code> | ||
| 345 | + <button type="button" data-copy="pkg-login">(copy_label)</button> | ||
| 346 | + </div> | ||
| 347 | + </section> | ||
| 348 | + <nav class="profile-tabs" aria-label=(package.name.as_str())> | ||
| 349 | + <a class=(readme_class) href=(readme_href.as_str())>(readme_label)</a> | ||
| 350 | + <a class=(versions_class) href=(versions_href.as_str())>(versions_label)</a> | ||
| 351 | + </nav> | ||
| 352 | + if versions_tab { | ||
| 353 | + if has_versions { | ||
| 354 | + <ul class="item-list package-versions"> | ||
| 355 | + for (version, date, yanked, checksum) in version_rows.iter() { | ||
| 356 | + <li> | ||
| 357 | + <span class="repo-name">(version.as_str())</span> | ||
| 358 | + " " | ||
| 359 | + <span class="muted small">(date.as_str())</span> | ||
| 360 | + if *yanked { | ||
| 361 | + " " | ||
| 362 | + <span class="badge">(pk::t(lang, K::VersionYanked))</span> | ||
| 363 | + } | ||
| 364 | + <br> | ||
| 365 | + <code class="small">(checksum.as_str())</code> | ||
| 366 | + </li> | ||
| 367 | + } | ||
| 368 | + </ul> | ||
| 369 | + } | ||
| 370 | + } else { | ||
| 371 | + if has_readme { | ||
| 372 | + <section class="markdown-body package-readme">(Unescaped::new_unchecked(readme_html))</section> | ||
| 373 | + } else { | ||
| 374 | + <p class="muted">(no_readme)</p> | ||
| 375 | + } | ||
| 376 | + } | ||
| 377 | + </article> | ||
| 378 | + }) | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +/// The owner's `changed` stream. A publish or a yank sends one `changed` event; nothing is sent | ||
| 382 | +/// on connect, since the page was just rendered. | ||
| 383 | +#[route(GET "/{owner}/-/packages/events")] | ||
| 384 | +async fn packages_events(cx: &Cx) -> Result<Response> { | ||
| 385 | + let owner_name = path_param::<Owner>(cx); | ||
| 386 | + let state = app_context::<AppState>(cx); | ||
| 387 | + let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 388 | + return Err(not_found().into()); | ||
| 389 | + }; | ||
| 390 | + // Subscribed before the response is sent, so a change after this point is sent. | ||
| 391 | + let wake = state.packages_live.subscribe(&owner.id); | ||
| 392 | + events_response(cx, owner_changes(wake)) | ||
| 393 | +} | ||
| 394 | + | ||
| 395 | +fn owner_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static { | ||
| 396 | + stream::unfold(wake, |mut wake| async move { | ||
| 397 | + wake.changed().await.ok()?; | ||
| 398 | + Some((changed_event("list".to_owned()), wake)) | ||
| 399 | + }) | ||
| 400 | +} | ||
| 401 | + | ||
| 402 | +/// A package linked to a repo, as the repo's sidebar lists it. | ||
| 403 | +pub struct PackageLink { | ||
| 404 | + pub name: String, | ||
| 405 | + pub href: String, | ||
| 406 | + pub latest: String, | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +/// The packages linked to `repo_id` that the viewer may see, with their newest version. A | ||
| 410 | +/// package without versions is not listed. | ||
| 411 | +pub async fn repo_package_links( | ||
| 412 | + state: &AppState, | ||
| 413 | + viewer: Option<&User>, | ||
| 414 | + repo_id: &str, | ||
| 415 | +) -> forge_core::Result<Vec<PackageLink>> { | ||
| 416 | + let mut links = Vec::new(); | ||
| 417 | + for package in state.store.packages_for_repo(repo_id).await? { | ||
| 418 | + let Some(owner) = state.store.user_by_id(&package.owner_id).await? else { | ||
| 419 | + continue; | ||
| 420 | + }; | ||
| 421 | + let readable = match package_ops::may_read(state, viewer, &owner, &package).await { | ||
| 422 | + Ok(readable) => readable, | ||
| 423 | + Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg)), | ||
| 424 | + Err(_) => false, | ||
| 425 | + }; | ||
| 426 | + if !readable { | ||
| 427 | + continue; | ||
| 428 | + } | ||
| 429 | + let versions = state.store.package_versions(&package.id).await?; | ||
| 430 | + let Some(latest) = versions.iter().find(|v| !v.yanked).or(versions.first()) else { | ||
| 431 | + continue; | ||
| 432 | + }; | ||
| 433 | + links.push(PackageLink { | ||
| 434 | + href: package_href(&owner.username, &package.name), | ||
| 435 | + name: package.name, | ||
| 436 | + latest: latest.version.clone(), | ||
| 437 | + }); | ||
| 438 | + } | ||
| 439 | + Ok(links) | ||
| 440 | +} | ||
| 441 | + | ||
| 442 | +/// The Packages card of a repo's sidebar: the packages linked to this repo. | ||
| 443 | +#[component] | ||
| 444 | +pub async fn repo_packages_card(links: Vec<PackageLink>, lang: Lang) -> Result<impl View> { | ||
| 445 | + let heading = pk::t(lang, K::TabPackages); | ||
| 446 | + Ok(view! { | ||
| 447 | + <section class="card repo-packages"> | ||
| 448 | + <h3>(heading)</h3> | ||
| 449 | + <ul class="item-list"> | ||
| 450 | + for link in links.into_iter() { | ||
| 451 | + <li> | ||
| 452 | + <a href=(link.href.as_str())>(link.name.as_str())</a> | ||
| 453 | + " " | ||
| 454 | + <span class="muted small">(link.latest.as_str())</span> | ||
| 455 | + </li> | ||
| 456 | + } | ||
| 457 | + </ul> | ||
| 458 | + </section> | ||
| 459 | + }) | ||
| 460 | +} | ||
crates/forge-web/src/pages/packages_oci.rsadded+195 -0
| @@ -0,0 +1,195 @@ | |||
| 1 | +//! The package page of a container image: its pull command, its tags with digest, size and date, | ||
| 2 | +//! and the owner's delete control for a tag. The page is the cargo package page's sibling; the | ||
| 3 | +//! route and the shell are shared in [`super::packages`]. | ||
| 4 | + | ||
| 5 | +use forge_core::User; | ||
| 6 | +use forge_core::packages::{OciTag, Package}; | ||
| 7 | +use topcoat::Result; | ||
| 8 | +use topcoat::view::{View, component, view}; | ||
| 9 | + | ||
| 10 | +use crate::i18n::Lang; | ||
| 11 | +use crate::i18n::packages::{self as pk, K}; | ||
| 12 | +use crate::package_ops; | ||
| 13 | +use crate::state::AppState; | ||
| 14 | +use crate::views::{enc, human_size}; | ||
| 15 | + | ||
| 16 | +/// What the container package page shows, prepared by the handler. | ||
| 17 | +pub struct OciPage { | ||
| 18 | + pub owner_name: String, | ||
| 19 | + pub package: Package, | ||
| 20 | + pub newest_tag: String, | ||
| 21 | + pub host: String, | ||
| 22 | + pub tags: Vec<OciTag>, | ||
| 23 | + pub can_delete: bool, | ||
| 24 | + pub csrf: String, | ||
| 25 | + pub events: String, | ||
| 26 | + pub lang: Lang, | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Builds the container page of `package` for `viewer`. The owner may delete tags. | ||
| 30 | +pub async fn model( | ||
| 31 | + state: &AppState, | ||
| 32 | + viewer: Option<&User>, | ||
| 33 | + csrf: String, | ||
| 34 | + owner: &User, | ||
| 35 | + package: Package, | ||
| 36 | + lang: Lang, | ||
| 37 | +) -> forge_core::Result<OciPage> { | ||
| 38 | + let tags = state.store.oci_tags(&package.id).await?; | ||
| 39 | + let can_delete = match viewer { | ||
| 40 | + Some(user) => package_ops::may_publish(state, user, owner) | ||
| 41 | + .await | ||
| 42 | + .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?, | ||
| 43 | + None => false, | ||
| 44 | + }; | ||
| 45 | + let base = state.config.base_url.trim_end_matches('/'); | ||
| 46 | + let host = base | ||
| 47 | + .split_once("://") | ||
| 48 | + .map_or(base, |(_, rest)| rest) | ||
| 49 | + .to_owned(); | ||
| 50 | + let newest_tag = tags.first().map(|t| t.tag.clone()).unwrap_or_default(); | ||
| 51 | + Ok(OciPage { | ||
| 52 | + owner_name: owner.username.clone(), | ||
| 53 | + package, | ||
| 54 | + newest_tag, | ||
| 55 | + host, | ||
| 56 | + tags, | ||
| 57 | + can_delete, | ||
| 58 | + csrf, | ||
| 59 | + events: crate::pages::packages::events_href(&owner.username), | ||
| 60 | + lang, | ||
| 61 | + }) | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The shortened form of a digest for a table cell: the algorithm and the first twelve hex digits. | ||
| 65 | +fn short_digest(digest: &str) -> String { | ||
| 66 | + match digest.split_once(':') { | ||
| 67 | + Some((alg, hex)) => format!("{alg}:{}", hex.get(..12).unwrap_or(hex)), | ||
| 68 | + None => digest.to_owned(), | ||
| 69 | + } | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// The container package page body. | ||
| 73 | +#[component] | ||
| 74 | +pub async fn oci_package_view(page: OciPage) -> Result<impl View> { | ||
| 75 | + let lang = page.lang; | ||
| 76 | + let OciPage { | ||
| 77 | + owner_name, | ||
| 78 | + package, | ||
| 79 | + newest_tag, | ||
| 80 | + host, | ||
| 81 | + tags, | ||
| 82 | + can_delete, | ||
| 83 | + csrf, | ||
| 84 | + events, | ||
| 85 | + .. | ||
| 86 | + } = page; | ||
| 87 | + let image = format!("{host}/{owner_name}/{}", package.name); | ||
| 88 | + let has_tags = !tags.is_empty(); | ||
| 89 | + let pull = if newest_tag.is_empty() { | ||
| 90 | + format!("docker pull {image}") | ||
| 91 | + } else { | ||
| 92 | + format!("docker pull {image}:{newest_tag}") | ||
| 93 | + }; | ||
| 94 | + let login = format!("docker login {host}"); | ||
| 95 | + let push = format!("docker push {image}:<tag>"); | ||
| 96 | + let copy_label = pk::t(lang, K::CopyCommand); | ||
| 97 | + let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name)); | ||
| 98 | + let private = package.private; | ||
| 99 | + let tag_count = tags.len().to_string(); | ||
| 100 | + let rows: Vec<(String, String, String, String, String)> = tags | ||
| 101 | + .iter() | ||
| 102 | + .map(|t| { | ||
| 103 | + ( | ||
| 104 | + t.tag.clone(), | ||
| 105 | + short_digest(&t.digest), | ||
| 106 | + t.digest.clone(), | ||
| 107 | + human_size(lang, t.size), | ||
| 108 | + t.created_at.get(..10).unwrap_or(&t.created_at).to_owned(), | ||
| 109 | + ) | ||
| 110 | + }) | ||
| 111 | + .collect(); | ||
| 112 | + Ok(view! { | ||
| 113 | + <article class="package-page" data-live=(events.as_str())> | ||
| 114 | + <header class="package-head"> | ||
| 115 | + <div> | ||
| 116 | + <p class="muted small">(owner_name.as_str()) " / " (pk::t(lang, K::ContainerKind))</p> | ||
| 117 | + <h1>(package.name.as_str()) " " <span class="muted">(newest_tag.as_str())</span></h1> | ||
| 118 | + if private { | ||
| 119 | + <span class="badge">(pk::t(lang, K::PackagePrivate))</span> | ||
| 120 | + } | ||
| 121 | + </div> | ||
| 122 | + </header> | ||
| 123 | + <section class="package-install"> | ||
| 124 | + <h2>(pk::t(lang, K::Install))</h2> | ||
| 125 | + <p class="muted small">(pk::t(lang, K::ContainerInstallHelp))</p> | ||
| 126 | + <p class="small">(pk::t(lang, K::ContainerLogin))</p> | ||
| 127 | + <div class="copy-box"> | ||
| 128 | + <code id="oci-login">(login.as_str())</code> | ||
| 129 | + <button type="button" data-copy="oci-login">(copy_label)</button> | ||
| 130 | + </div> | ||
| 131 | + if has_tags { | ||
| 132 | + <p class="small">(pk::t(lang, K::ContainerPull))</p> | ||
| 133 | + <div class="copy-box"> | ||
| 134 | + <code id="oci-pull">(pull.as_str())</code> | ||
| 135 | + <button type="button" data-copy="oci-pull">(copy_label)</button> | ||
| 136 | + </div> | ||
| 137 | + } | ||
| 138 | + <p class="small">(pk::t(lang, K::ContainerPush))</p> | ||
| 139 | + <div class="copy-box"> | ||
| 140 | + <code id="oci-push">(push.as_str())</code> | ||
| 141 | + <button type="button" data-copy="oci-push">(copy_label)</button> | ||
| 142 | + </div> | ||
| 143 | + </section> | ||
| 144 | + <section class="package-tags"> | ||
| 145 | + <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2> | ||
| 146 | + if has_tags { | ||
| 147 | + <div class="table-wrap"> | ||
| 148 | + <table class="table container-tags"> | ||
| 149 | + <thead> | ||
| 150 | + <tr> | ||
| 151 | + <th>(pk::t(lang, K::ContainerTag))</th> | ||
| 152 | + <th>(pk::t(lang, K::ContainerDigest))</th> | ||
| 153 | + <th>(pk::t(lang, K::ContainerSize))</th> | ||
| 154 | + <th>(pk::t(lang, K::ContainerCreated))</th> | ||
| 155 | + if can_delete { | ||
| 156 | + <th></th> | ||
| 157 | + } | ||
| 158 | + </tr> | ||
| 159 | + </thead> | ||
| 160 | + <tbody> | ||
| 161 | + for (tag, short, full, size, created) in rows.iter() { | ||
| 162 | + <tr> | ||
| 163 | + <td><code>(tag.as_str())</code></td> | ||
| 164 | + <td><code class="small" title=(full.as_str())>(short.as_str())</code></td> | ||
| 165 | + <td class="muted small">(size.as_str())</td> | ||
| 166 | + <td class="muted small">(created.as_str())</td> | ||
| 167 | + if can_delete { | ||
| 168 | + <td> | ||
| 169 | + <details class="confirm-inline"> | ||
| 170 | + <summary class="button danger">(pk::t(lang, K::DeleteTag))</summary> | ||
| 171 | + <div class="confirm-pop"> | ||
| 172 | + <p>(pk::t(lang, K::DeleteTagMessage))</p> | ||
| 173 | + <form method="post" action=(delete_action.as_str())> | ||
| 174 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 175 | + <input type="hidden" name="package" value=(package.name.as_str())> | ||
| 176 | + <input type="hidden" name="tag" value=(tag.as_str())> | ||
| 177 | + <button type="submit" class="danger">(pk::t(lang, K::DeleteTagConfirm))</button> | ||
| 178 | + <button type="button" data-close-details="">(pk::t(lang, K::Cancel))</button> | ||
| 179 | + </form> | ||
| 180 | + </div> | ||
| 181 | + </details> | ||
| 182 | + </td> | ||
| 183 | + } | ||
| 184 | + </tr> | ||
| 185 | + } | ||
| 186 | + </tbody> | ||
| 187 | + </table> | ||
| 188 | + </div> | ||
| 189 | + } else { | ||
| 190 | + <p class="muted">(pk::t(lang, K::NoTags))</p> | ||
| 191 | + } | ||
| 192 | + </section> | ||
| 193 | + </article> | ||
| 194 | + }) | ||
| 195 | +} | ||
crates/forge-web/src/pages/profile.rsmodified+52 -1
| @@ -22,9 +22,11 @@ use topcoat::view::{Unescaped, View, component, view}; | |||
| 22 | use crate::auth::current_user; | 22 | use crate::auth::current_user; |
| 23 | use crate::i18n::misc::{self as mi, K as MK}; | 23 | use crate::i18n::misc::{self as mi, K as MK}; |
| 24 | use crate::i18n::orgs::{self as g, K}; | 24 | use crate::i18n::orgs::{self as g, K}; |
| 25 | +use crate::i18n::packages::{self as pk, K as PK}; | ||
| 25 | use crate::i18n::{self, Lang}; | 26 | use crate::i18n::{self, Lang}; |
| 26 | use crate::live::{Topic, stream_changes}; | 27 | use crate::live::{Topic, stream_changes}; |
| 27 | use crate::pages::dashboard::badge_class; | 28 | use crate::pages::dashboard::badge_class; |
| 29 | +use crate::pages::packages::{self as packages, PackageRow}; | ||
| 28 | use crate::render::markdown::render_markdown; | 30 | use crate::render::markdown::render_markdown; |
| 29 | use crate::state::AppState; | 31 | use crate::state::AppState; |
| 30 | use crate::views::repo_list::{ | 32 | use crate::views::repo_list::{ |
| @@ -217,13 +219,18 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | |||
| 217 | None | 219 | None |
| 218 | }; | 220 | }; |
| 219 | 221 | ||
| 222 | + // The Packages tab lists the registry's packages the viewer may see. | ||
| 223 | + let package_rows = packages::package_rows(state, actor, &user).await?; | ||
| 224 | + let packages_on = tab == "packages"; | ||
| 225 | + | ||
| 220 | let title = user.username.clone(); | 226 | let title = user.username.clone(); |
| 221 | Ok(view! { cx => | 227 | Ok(view! { cx => |
| 222 | shell(title: title.as_str(), viewer: viewer.as_ref(), | 228 | shell(title: title.as_str(), viewer: viewer.as_ref(), |
| 223 | profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time, | 229 | profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time, |
| 224 | org: org, lang: lang, tab: tab.to_owned(), q: q, sort: sort, repo_total: repo_total, | 230 | org: org, lang: lang, tab: tab.to_owned(), q: q, sort: sort, repo_total: repo_total, |
| 225 | star_total: star_total, cards: cards, from_pins: from_pins, | 231 | star_total: star_total, cards: cards, from_pins: from_pins, |
| 226 | - pins_edit_href: pins_edit_href, edit_profile: edit_profile, listing: listing)) | 232 | + pins_edit_href: pins_edit_href, edit_profile: edit_profile, listing: listing, |
| 233 | + packages_on: packages_on, package_rows: package_rows)) | ||
| 227 | }) | 234 | }) |
| 228 | } | 235 | } |
| 229 | 236 | ||
| @@ -323,6 +330,7 @@ fn tab_key(raw: Option<&str>) -> &'static str { | |||
| 323 | match raw { | 330 | match raw { |
| 324 | Some("repositories") => "repositories", | 331 | Some("repositories") => "repositories", |
| 325 | Some("stars") => "stars", | 332 | Some("stars") => "stars", |
| 333 | + Some("packages") => "packages", | ||
| 326 | _ => "overview", | 334 | _ => "overview", |
| 327 | } | 335 | } |
| 328 | } | 336 | } |
| @@ -410,7 +418,13 @@ async fn profile_card( | |||
| 410 | pins_edit_href: Option<String>, | 418 | pins_edit_href: Option<String>, |
| 411 | edit_profile: bool, | 419 | edit_profile: bool, |
| 412 | listing: Listing, | 420 | listing: Listing, |
| 421 | + packages_on: bool, | ||
| 422 | + package_rows: Vec<PackageRow>, | ||
| 413 | ) -> Result<impl View> { | 423 | ) -> Result<impl View> { |
| 424 | + let package_count_text = package_rows.len().to_string(); | ||
| 425 | + let packages_href = profile_href(&user.username, "packages", "", SORTS[0].0, 1); | ||
| 426 | + let packages_events = packages::events_href(&user.username); | ||
| 427 | + let has_packages = !package_rows.is_empty(); | ||
| 414 | let src = avatar_url(&user.username, avatar.as_deref()); | 428 | let src = avatar_url(&user.username, avatar.as_deref()); |
| 415 | let has_about = !about_html.is_empty(); | 429 | let has_about = !about_html.is_empty(); |
| 416 | let is_org = user.is_org(); | 430 | let is_org = user.is_org(); |
| @@ -477,6 +491,9 @@ async fn profile_card( | |||
| 477 | <a class=(tab_class(stars_on)) href=(stars_href.as_str())> | 491 | <a class=(tab_class(stars_on)) href=(stars_href.as_str())> |
| 478 | (g::t(lang, K::TabStars)) " " <span class="tab-count">(star_count_text.as_str())</span> | 492 | (g::t(lang, K::TabStars)) " " <span class="tab-count">(star_count_text.as_str())</span> |
| 479 | </a> | 493 | </a> |
| 494 | + <a class=(tab_class(packages_on)) href=(packages_href.as_str())> | ||
| 495 | + (pk::t(lang, PK::TabPackages)) " " <span class="tab-count">(package_count_text.as_str())</span> | ||
| 496 | + </a> | ||
| 480 | </nav> | 497 | </nav> |
| 481 | if overview_on { | 498 | if overview_on { |
| 482 | <section class="profile-pinned"> | 499 | <section class="profile-pinned"> |
| @@ -542,6 +559,40 @@ async fn profile_card( | |||
| 542 | pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) | 559 | pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) |
| 543 | </section> | 560 | </section> |
| 544 | } | 561 | } |
| 562 | + if packages_on { | ||
| 563 | + <section class="package-listing" data-live=(packages_events.as_str())> | ||
| 564 | + <div class="profile-section-head"> | ||
| 565 | + <h2>(pk::t(lang, PK::PackagesHeading))</h2> | ||
| 566 | + </div> | ||
| 567 | + <p class="muted small">(pk::t(lang, PK::PackagesHelp))</p> | ||
| 568 | + if has_packages { | ||
| 569 | + <ul class="item-list"> | ||
| 570 | + for row in package_rows.into_iter() { | ||
| 571 | + <li> | ||
| 572 | + <a class="repo-name" href=(row.href.as_str())>(row.name.as_str())</a> | ||
| 573 | + " " | ||
| 574 | + if row.container { | ||
| 575 | + <span class="badge">(pk::t(lang, PK::ContainerKind))</span> | ||
| 576 | + " " | ||
| 577 | + } | ||
| 578 | + <span class="muted small">(row.latest.as_str())</span> | ||
| 579 | + " " | ||
| 580 | + <span class="muted small">(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 }))</span> | ||
| 581 | + if row.private { | ||
| 582 | + " " | ||
| 583 | + <span class="badge">(pk::t(lang, PK::PackagePrivate))</span> | ||
| 584 | + } | ||
| 585 | + if !row.description.is_empty() { | ||
| 586 | + <p class="muted small">(row.description.as_str())</p> | ||
| 587 | + } | ||
| 588 | + </li> | ||
| 589 | + } | ||
| 590 | + </ul> | ||
| 591 | + } else { | ||
| 592 | + <p class="muted">(pk::t(lang, PK::NoPackages))</p> | ||
| 593 | + } | ||
| 594 | + </section> | ||
| 595 | + } | ||
| 545 | </article> | 596 | </article> |
| 546 | }) | 597 | }) |
| 547 | } | 598 | } |
crates/forge-web/src/pages/repo.rsmodified+6 -0
| @@ -25,6 +25,7 @@ use crate::pages::dashboard::badge_class; | |||
| 25 | use crate::pages::finder::file_finder; | 25 | use crate::pages::finder::file_finder; |
| 26 | use crate::pages::issue_parts::stamp_unix; | 26 | use crate::pages::issue_parts::stamp_unix; |
| 27 | use crate::pages::notifications::watch_form; | 27 | use crate::pages::notifications::watch_form; |
| 28 | +use crate::pages::packages::{self, repo_packages_card}; | ||
| 28 | use crate::pages::refs::load_refs; | 29 | use crate::pages::refs::load_refs; |
| 29 | use crate::pages::releases::latest_card; | 30 | use crate::pages::releases::latest_card; |
| 30 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 31 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| @@ -468,6 +469,8 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | |||
| 468 | header.live = live; | 469 | header.live = live; |
| 469 | let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; | 470 | let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; |
| 470 | let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; | 471 | let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; |
| 472 | + let viewer_user = ctx.viewer.as_ref().map(|(user, _)| user); | ||
| 473 | + let packages = packages::repo_package_links(state, viewer_user, &repo.id).await?; | ||
| 471 | let now = now_unix(); | 474 | let now = now_unix(); |
| 472 | Ok(view! { | 475 | Ok(view! { |
| 473 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | 476 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| @@ -496,6 +499,9 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | |||
| 496 | } | 499 | } |
| 497 | </div> | 500 | </div> |
| 498 | <aside class="repo-meta" aria-label=(g::t(lang, K::BranchesTitle))> | 501 | <aside class="repo-meta" aria-label=(g::t(lang, K::BranchesTitle))> |
| 502 | + if !packages.is_empty() { | ||
| 503 | + repo_packages_card(links: packages, lang: lang) | ||
| 504 | + } | ||
| 499 | <section> | 505 | <section> |
| 500 | <h2>(g::t(lang, K::BranchesTitle))</h2> | 506 | <h2>(g::t(lang, K::BranchesTitle))</h2> |
| 501 | <ul class="branch-list"> | 507 | <ul class="branch-list"> |
crates/forge-web/src/pages/settings_security.rsmodified+1 -0
| @@ -1102,6 +1102,7 @@ mod tests { | |||
| 1102 | ci_live: Arc::new(crate::ci::CiLive::default()), | 1102 | ci_live: Arc::new(crate::ci::CiLive::default()), |
| 1103 | live: Arc::new(crate::live::LiveHub::default()), | 1103 | live: Arc::new(crate::live::LiveHub::default()), |
| 1104 | push_live: Arc::new(crate::web_push::PushLive::default()), | 1104 | push_live: Arc::new(crate::web_push::PushLive::default()), |
| 1105 | + packages_live: Arc::new(crate::packages_live::PackagesLive::default()), | ||
| 1105 | }; | 1106 | }; |
| 1106 | let hash = hash_password_async(PASSWORD.into()).await.unwrap(); | 1107 | let hash = hash_password_async(PASSWORD.into()).await.unwrap(); |
| 1107 | let user = store | 1108 | let user = store |
crates/forge-web/src/pages/settings_tokens.rsmodified+14 -1
| @@ -16,8 +16,10 @@ use topcoat::router::response::response_headers; | |||
| 16 | use topcoat::router::{page, route}; | 16 | use topcoat::router::{page, route}; |
| 17 | use topcoat::view::{View, component, view}; | 17 | use topcoat::view::{View, component, view}; |
| 18 | 18 | ||
| 19 | +use crate::api::packages::PACKAGES_SCOPE; | ||
| 19 | use crate::audit::{self, Actor, Target}; | 20 | use crate::audit::{self, Actor, Target}; |
| 20 | use crate::auth::{require_csrf, require_user}; | 21 | use crate::auth::{require_csrf, require_user}; |
| 22 | +use crate::i18n::packages::{self as pk, K as PK}; | ||
| 21 | use crate::i18n::{self, Key, Lang, t, token_meta, token_name_length}; | 23 | use crate::i18n::{self, Key, Lang, t, token_meta, token_name_length}; |
| 22 | use crate::state::AppState; | 24 | use crate::state::AppState; |
| 23 | use crate::views::{alert, shell}; | 25 | use crate::views::{alert, shell}; |
| @@ -34,6 +36,9 @@ struct CreateTokenForm { | |||
| 34 | name: String, | 36 | name: String, |
| 35 | #[serde(default)] | 37 | #[serde(default)] |
| 36 | expires: String, | 38 | expires: String, |
| 39 | + /// The packages checkbox: any value means the token also gets the `packages` scope. | ||
| 40 | + #[serde(default)] | ||
| 41 | + packages: String, | ||
| 37 | } | 42 | } |
| 38 | 43 | ||
| 39 | #[derive(Deserialize)] | 44 | #[derive(Deserialize)] |
| @@ -116,6 +121,11 @@ async fn tokens_view( | |||
| 116 | <option value="never">(t(lang, Key::ExpiresNever))</option> | 121 | <option value="never">(t(lang, Key::ExpiresNever))</option> |
| 117 | </select> | 122 | </select> |
| 118 | </label> | 123 | </label> |
| 124 | + <label class="checkbox"> | ||
| 125 | + <input type="checkbox" name="packages" value="on"> | ||
| 126 | + <span>(pk::t(lang, PK::ScopePackages))</span> | ||
| 127 | + </label> | ||
| 128 | + <p class="muted small">(pk::t(lang, PK::ScopePackagesHelp))</p> | ||
| 119 | <p class="muted small">(t(lang, Key::ScopeNote))</p> | 129 | <p class="muted small">(t(lang, Key::ScopeNote))</p> |
| 120 | <button type="submit" class="primary">(t(lang, Key::CreateToken))</button> | 130 | <button type="submit" class="primary">(t(lang, Key::CreateToken))</button> |
| 121 | </form> | 131 | </form> |
| @@ -151,7 +161,10 @@ async fn tokens_create(cx: &Cx, Form(form): Form<CreateTokenForm>) -> Result<imp | |||
| 151 | let token = generate_token(); | 161 | let token = generate_token(); |
| 152 | let expires_at = expiry_days(&form.expires) | 162 | let expires_at = expiry_days(&form.expires) |
| 153 | .map(|days| stamp_after(Duration::from_secs(days * 24 * 60 * 60))); | 163 | .map(|days| stamp_after(Duration::from_secs(days * 24 * 60 * 60))); |
| 154 | - let scopes: Vec<String> = SCOPES.iter().map(|s| (*s).to_owned()).collect(); | 164 | + let mut scopes: Vec<String> = SCOPES.iter().map(|s| (*s).to_owned()).collect(); |
| 165 | + if !form.packages.is_empty() { | ||
| 166 | + scopes.push(PACKAGES_SCOPE.to_owned()); | ||
| 167 | + } | ||
| 155 | let row = store | 168 | let row = store |
| 156 | .create_token( | 169 | .create_token( |
| 157 | &viewer.0.id, | 170 | &viewer.0.id, |
crates/forge-web/src/state.rsmodified+1 -0
| @@ -53,6 +53,7 @@ pub struct AppState { | |||
| 53 | pub live: Arc<crate::live::LiveHub>, | 53 | pub live: Arc<crate::live::LiveHub>, |
| 54 | /// Device changes per user. The settings pages showing a user's push devices listen to it. | 54 | /// Device changes per user. The settings pages showing a user's push devices listen to it. |
| 55 | pub push_live: Arc<crate::web_push::PushLive>, | 55 | pub push_live: Arc<crate::web_push::PushLive>, |
| 56 | + pub packages_live: Arc<crate::packages_live::PackagesLive>, | ||
| 56 | } | 57 | } |
| 57 | 58 | ||
| 58 | /// A settings handle over `config` with no stored overrides and no file keys. For tests. | 59 | /// A settings handle over `config` with no stored overrides and no file keys. For tests. |
crates/forge-web/src/test_support.rsmodified+1 -0
| @@ -88,6 +88,7 @@ pub async fn test_state(dir: &Path) -> AppState { | |||
| 88 | ci_live: Arc::new(crate::ci::CiLive::default()), | 88 | ci_live: Arc::new(crate::ci::CiLive::default()), |
| 89 | live: Arc::new(crate::live::LiveHub::default()), | 89 | live: Arc::new(crate::live::LiveHub::default()), |
| 90 | push_live: Arc::new(crate::web_push::PushLive::default()), | 90 | push_live: Arc::new(crate::web_push::PushLive::default()), |
| 91 | + packages_live: Arc::new(crate::packages_live::PackagesLive::default()), | ||
| 91 | } | 92 | } |
| 92 | } | 93 | } |
| 93 | 94 | ||
crates/forge-web/tests/oci_e2e.rsadded+972 -0
| @@ -0,0 +1,972 @@ | |||
| 1 | +//! Black-box tests for the container registry. They start the real `forge` binary and drive the | ||
| 2 | +//! OCI Distribution API over HTTP the way a container client does: the auth probe, the token | ||
| 3 | +//! exchange, monolithic and chunked blob uploads, manifests by tag and digest, the tag list, mounts, | ||
| 4 | +//! deletes and the garbage collection they trigger. Private images and the packages scope are set | ||
| 5 | +//! up through the store before the server starts, since the web has no way to make one private. | ||
| 6 | +//! The last test drives podman when it is installed; it is ignored by default. | ||
| 7 | + | ||
| 8 | +mod common; | ||
| 9 | +use common::{BIN, Server, describe, launch, pick_ports, tool_on_path, write_config}; | ||
| 10 | +use std::path::Path; | ||
| 11 | +use std::process::Command; | ||
| 12 | +use std::time::Duration; | ||
| 13 | + | ||
| 14 | +use forge_core::packages::KIND_OCI; | ||
| 15 | +use forge_core::token::{generate_token, hash_token}; | ||
| 16 | +use forge_core::{Store, User}; | ||
| 17 | +use sha2::{Digest, Sha256}; | ||
| 18 | + | ||
| 19 | +const PW: &str = "tahinli-password-123"; | ||
| 20 | +const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json"; | ||
| 21 | + | ||
| 22 | +struct Resp { | ||
| 23 | + status: u16, | ||
| 24 | + headers: Vec<(String, String)>, | ||
| 25 | + body: Vec<u8>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl Resp { | ||
| 29 | + fn header(&self, name: &str) -> Option<&str> { | ||
| 30 | + self.headers | ||
| 31 | + .iter() | ||
| 32 | + .find(|(k, _)| k.eq_ignore_ascii_case(name)) | ||
| 33 | + .map(|(_, v)| v.as_str()) | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + fn text(&self) -> String { | ||
| 37 | + String::from_utf8_lossy(&self.body).into_owned() | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + fn json(&self) -> serde_json::Value { | ||
| 41 | + serde_json::from_slice(&self.body).expect("json body") | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + /// The `code` of the first OCI error, for asserting error codes. | ||
| 45 | + fn error_code(&self) -> String { | ||
| 46 | + self.json()["errors"][0]["code"] | ||
| 47 | + .as_str() | ||
| 48 | + .unwrap_or_default() | ||
| 49 | + .to_owned() | ||
| 50 | + } | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +struct Http { | ||
| 54 | + client: reqwest::Client, | ||
| 55 | + base: String, | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +impl Http { | ||
| 59 | + fn new(port: u16) -> Self { | ||
| 60 | + let client = reqwest::Client::builder() | ||
| 61 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 62 | + .timeout(Duration::from_secs(60)) | ||
| 63 | + .build() | ||
| 64 | + .expect("http client"); | ||
| 65 | + Self { | ||
| 66 | + client, | ||
| 67 | + base: format!("http://127.0.0.1:{port}"), | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + /// Sends one request. `auth` is the whole Authorization value, when there is one. | ||
| 72 | + async fn send( | ||
| 73 | + &self, | ||
| 74 | + method: reqwest::Method, | ||
| 75 | + path: &str, | ||
| 76 | + auth: Option<&str>, | ||
| 77 | + headers: &[(&str, &str)], | ||
| 78 | + body: Option<Vec<u8>>, | ||
| 79 | + ) -> Resp { | ||
| 80 | + let url = if path.starts_with("http") { | ||
| 81 | + path.to_owned() | ||
| 82 | + } else { | ||
| 83 | + format!("{}{path}", self.base) | ||
| 84 | + }; | ||
| 85 | + let mut req = self.client.request(method, url); | ||
| 86 | + if let Some(value) = auth { | ||
| 87 | + req = req.header("Authorization", value); | ||
| 88 | + } | ||
| 89 | + for (name, value) in headers { | ||
| 90 | + req = req.header(*name, *value); | ||
| 91 | + } | ||
| 92 | + if let Some(bytes) = body { | ||
| 93 | + req = req.body(bytes); | ||
| 94 | + } | ||
| 95 | + let res = req.send().await.expect("http request"); | ||
| 96 | + let status = res.status().as_u16(); | ||
| 97 | + let headers = res | ||
| 98 | + .headers() | ||
| 99 | + .iter() | ||
| 100 | + .map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap_or("").to_owned())) | ||
| 101 | + .collect(); | ||
| 102 | + let body = res.bytes().await.expect("read body").to_vec(); | ||
| 103 | + Resp { | ||
| 104 | + status, | ||
| 105 | + headers, | ||
| 106 | + body, | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + async fn get(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 111 | + self.send(reqwest::Method::GET, path, auth, &[], None).await | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + async fn post(&self, path: &str, auth: Option<&str>, body: Option<Vec<u8>>) -> Resp { | ||
| 115 | + self.send(reqwest::Method::POST, path, auth, &[], body) | ||
| 116 | + .await | ||
| 117 | + } | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. | ||
| 121 | +fn admin(config: &Path, args: &[&str]) { | ||
| 122 | + let out = Command::new(BIN) | ||
| 123 | + .arg("--config") | ||
| 124 | + .arg(config) | ||
| 125 | + .arg("admin") | ||
| 126 | + .args(args) | ||
| 127 | + .env("FORGE_PASSWORD", PW) | ||
| 128 | + .output() | ||
| 129 | + .expect("run admin command"); | ||
| 130 | + assert!( | ||
| 131 | + out.status.success(), | ||
| 132 | + "admin {args:?} failed:\n{}", | ||
| 133 | + describe(&out) | ||
| 134 | + ); | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// A running server. The temp dir lives as long as the test. | ||
| 138 | +struct Env { | ||
| 139 | + _root: tempfile::TempDir, | ||
| 140 | + _server: Server, | ||
| 141 | + http: Http, | ||
| 142 | + port: u16, | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// Creates the users `tahinli` and `bob`, runs `seed` on the store, then starts the server. | ||
| 146 | +async fn start<F, Fut>(seed: F) -> Env | ||
| 147 | +where | ||
| 148 | + F: FnOnce(Store) -> Fut, | ||
| 149 | + Fut: std::future::Future<Output = ()>, | ||
| 150 | +{ | ||
| 151 | + let root = tempfile::Builder::new() | ||
| 152 | + .prefix("foci") | ||
| 153 | + .tempdir_in("/tmp") | ||
| 154 | + .expect("temp dir"); | ||
| 155 | + let dir = root.path().to_path_buf(); | ||
| 156 | + let ports = pick_ports(); | ||
| 157 | + let config = write_config(&dir, ports); | ||
| 158 | + admin(&config, &["create-user", "tahinli"]); | ||
| 159 | + admin(&config, &["create-user", "bob"]); | ||
| 160 | + let store = Store::open(&dir.join("forge.db")) | ||
| 161 | + .await | ||
| 162 | + .expect("open store"); | ||
| 163 | + seed(store).await; | ||
| 164 | + let (server, ports) = launch(&dir, ports).await; | ||
| 165 | + Env { | ||
| 166 | + _root: root, | ||
| 167 | + _server: server, | ||
| 168 | + http: Http::new(ports.http), | ||
| 169 | + port: ports.http, | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Stores a token for `user` with the given scopes. `token` is the plaintext a client will send. | ||
| 174 | +async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) { | ||
| 175 | + let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); | ||
| 176 | + store | ||
| 177 | + .create_token(&user.id, "ci", &hash_token(token), &scopes, None) | ||
| 178 | + .await | ||
| 179 | + .expect("create token"); | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +async fn user(store: &Store, name: &str) -> User { | ||
| 183 | + store | ||
| 184 | + .user_by_username(name) | ||
| 185 | + .await | ||
| 186 | + .expect("lookup user") | ||
| 187 | + .expect("user exists") | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +fn sha256_digest(bytes: &[u8]) -> String { | ||
| 191 | + format!("sha256:{}", hex::encode(Sha256::digest(bytes))) | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// The bearer header a client gets from the token endpoint with Basic `tahinli:<token>`. | ||
| 195 | +async fn bearer_for(http: &Http, token: &str) -> String { | ||
| 196 | + let res = http | ||
| 197 | + .send( | ||
| 198 | + reqwest::Method::GET, | ||
| 199 | + "/v2/token?service=127.0.0.1&scope=repository:tahinli/app:pull,push", | ||
| 200 | + Some(&basic("tahinli", token)), | ||
| 201 | + &[], | ||
| 202 | + None, | ||
| 203 | + ) | ||
| 204 | + .await; | ||
| 205 | + assert_eq!(res.status, 200, "{}", res.text()); | ||
| 206 | + let token = res.json()["token"].as_str().expect("token").to_owned(); | ||
| 207 | + format!("Bearer {token}") | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +fn basic(user: &str, password: &str) -> String { | ||
| 211 | + let encoded = { | ||
| 212 | + use base64::Engine as _; | ||
| 213 | + base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}")) | ||
| 214 | + }; | ||
| 215 | + format!("Basic {encoded}") | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// Pushes a blob in one request with its digest. | ||
| 219 | +async fn push_blob(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp { | ||
| 220 | + let digest = sha256_digest(bytes); | ||
| 221 | + http.post( | ||
| 222 | + &format!("/v2/{repo}/blobs/uploads/?digest={digest}"), | ||
| 223 | + Some(auth), | ||
| 224 | + Some(bytes.to_vec()), | ||
| 225 | + ) | ||
| 226 | + .await | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/// Pushes a blob in three chunks, then closes the upload with its digest. | ||
| 230 | +async fn push_blob_chunked(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp { | ||
| 231 | + let start = http | ||
| 232 | + .post(&format!("/v2/{repo}/blobs/uploads/"), Some(auth), None) | ||
| 233 | + .await; | ||
| 234 | + assert_eq!(start.status, 202, "{}", start.text()); | ||
| 235 | + let location = start.header("location").expect("location").to_owned(); | ||
| 236 | + let third = bytes.len() / 3; | ||
| 237 | + let mut offset = 0; | ||
| 238 | + for chunk in [ | ||
| 239 | + &bytes[..third], | ||
| 240 | + &bytes[third..2 * third], | ||
| 241 | + &bytes[2 * third..], | ||
| 242 | + ] { | ||
| 243 | + let range = format!("{offset}-{}", offset + chunk.len() - 1); | ||
| 244 | + let res = http | ||
| 245 | + .send( | ||
| 246 | + reqwest::Method::PATCH, | ||
| 247 | + &location, | ||
| 248 | + Some(auth), | ||
| 249 | + &[ | ||
| 250 | + ("Content-Range", &range), | ||
| 251 | + ("Content-Type", "application/octet-stream"), | ||
| 252 | + ], | ||
| 253 | + Some(chunk.to_vec()), | ||
| 254 | + ) | ||
| 255 | + .await; | ||
| 256 | + assert_eq!(res.status, 202, "{}", res.text()); | ||
| 257 | + offset += chunk.len(); | ||
| 258 | + } | ||
| 259 | + let digest = sha256_digest(bytes); | ||
| 260 | + http.send( | ||
| 261 | + reqwest::Method::PUT, | ||
| 262 | + &format!("{location}?digest={digest}"), | ||
| 263 | + Some(auth), | ||
| 264 | + &[], | ||
| 265 | + Some(Vec::new()), | ||
| 266 | + ) | ||
| 267 | + .await | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// An image manifest naming `config` and `layers`, as the JSON a client pushes. | ||
| 271 | +fn manifest(config: &[u8], layers: &[&[u8]]) -> Vec<u8> { | ||
| 272 | + serde_json::to_vec(&serde_json::json!({ | ||
| 273 | + "schemaVersion": 2, | ||
| 274 | + "mediaType": MANIFEST_TYPE, | ||
| 275 | + "config": { | ||
| 276 | + "mediaType": "application/vnd.oci.image.config.v1+json", | ||
| 277 | + "digest": sha256_digest(config), | ||
| 278 | + "size": config.len(), | ||
| 279 | + }, | ||
| 280 | + "layers": layers.iter().map(|layer| serde_json::json!({ | ||
| 281 | + "mediaType": "application/vnd.oci.image.layer.v1.tar", | ||
| 282 | + "digest": sha256_digest(layer), | ||
| 283 | + "size": layer.len(), | ||
| 284 | + })).collect::<Vec<_>>(), | ||
| 285 | + })) | ||
| 286 | + .expect("manifest json") | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +async fn put_manifest(http: &Http, repo: &str, reference: &str, auth: &str, body: &[u8]) -> Resp { | ||
| 290 | + http.send( | ||
| 291 | + reqwest::Method::PUT, | ||
| 292 | + &format!("/v2/{repo}/manifests/{reference}"), | ||
| 293 | + Some(auth), | ||
| 294 | + &[("Content-Type", MANIFEST_TYPE)], | ||
| 295 | + Some(body.to_vec()), | ||
| 296 | + ) | ||
| 297 | + .await | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +#[tokio::test] | ||
| 301 | +async fn probe_challenges_and_the_token_endpoint_issues_a_bearer_token() { | ||
| 302 | + let token = generate_token(); | ||
| 303 | + let seeded = token.clone(); | ||
| 304 | + let env = start(move |store| async move { | ||
| 305 | + let tahinli = user(&store, "tahinli").await; | ||
| 306 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 307 | + }) | ||
| 308 | + .await; | ||
| 309 | + let port = env.port; | ||
| 310 | + | ||
| 311 | + let probe = env.http.get("/v2/", None).await; | ||
| 312 | + assert_eq!(probe.status, 401, "{}", probe.text()); | ||
| 313 | + let challenge = probe.header("www-authenticate").expect("challenge"); | ||
| 314 | + assert!( | ||
| 315 | + challenge.starts_with(&format!( | ||
| 316 | + "Bearer realm=\"http://127.0.0.1:{port}/v2/token\"" | ||
| 317 | + )), | ||
| 318 | + "{challenge}" | ||
| 319 | + ); | ||
| 320 | + assert!( | ||
| 321 | + challenge.contains(&format!("service=\"127.0.0.1:{port}\"")), | ||
| 322 | + "{challenge}" | ||
| 323 | + ); | ||
| 324 | + | ||
| 325 | + let auth = bearer_for(&env.http, &token).await; | ||
| 326 | + assert_eq!(env.http.get("/v2/", Some(&auth)).await.status, 200); | ||
| 327 | + | ||
| 328 | + let bad = env | ||
| 329 | + .http | ||
| 330 | + .get("/v2/", Some(&basic("tahinli", "forge_wrong"))) | ||
| 331 | + .await; | ||
| 332 | + assert_eq!(bad.status, 401, "{}", bad.text()); | ||
| 333 | + assert_eq!(bad.error_code(), "UNAUTHORIZED"); | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +#[tokio::test] | ||
| 337 | +async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { | ||
| 338 | + let token = generate_token(); | ||
| 339 | + let seeded = token.clone(); | ||
| 340 | + let env = start(move |store| async move { | ||
| 341 | + let tahinli = user(&store, "tahinli").await; | ||
| 342 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 343 | + }) | ||
| 344 | + .await; | ||
| 345 | + let http = &env.http; | ||
| 346 | + let auth = bearer_for(http, &token).await; | ||
| 347 | + | ||
| 348 | + let config = br#"{"architecture":"amd64","os":"linux"}"#.to_vec(); | ||
| 349 | + let layer_one = b"the first layer, pushed in one request".to_vec(); | ||
| 350 | + let layer_two: Vec<u8> = (0..3000u32).map(|i| (i % 251) as u8).collect(); | ||
| 351 | + | ||
| 352 | + let res = push_blob(http, "tahinli/app", &auth, &config).await; | ||
| 353 | + assert_eq!(res.status, 201, "{}", res.text()); | ||
| 354 | + assert_eq!( | ||
| 355 | + res.header("docker-content-digest"), | ||
| 356 | + Some(sha256_digest(&config).as_str()) | ||
| 357 | + ); | ||
| 358 | + assert_eq!( | ||
| 359 | + push_blob(http, "tahinli/app", &auth, &layer_one) | ||
| 360 | + .await | ||
| 361 | + .status, | ||
| 362 | + 201 | ||
| 363 | + ); | ||
| 364 | + let res = push_blob_chunked(http, "tahinli/app", &auth, &layer_two).await; | ||
| 365 | + assert_eq!(res.status, 201, "{}", res.text()); | ||
| 366 | + assert_eq!( | ||
| 367 | + res.header("location"), | ||
| 368 | + Some(format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)).as_str()) | ||
| 369 | + ); | ||
| 370 | + | ||
| 371 | + let head = http | ||
| 372 | + .send( | ||
| 373 | + reqwest::Method::HEAD, | ||
| 374 | + &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)), | ||
| 375 | + Some(&auth), | ||
| 376 | + &[], | ||
| 377 | + None, | ||
| 378 | + ) | ||
| 379 | + .await; | ||
| 380 | + assert_eq!(head.status, 200); | ||
| 381 | + assert_eq!(head.header("content-length"), Some("3000")); | ||
| 382 | + let blob = http | ||
| 383 | + .get( | ||
| 384 | + &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&layer_two)), | ||
| 385 | + Some(&auth), | ||
| 386 | + ) | ||
| 387 | + .await; | ||
| 388 | + assert_eq!(blob.status, 200); | ||
| 389 | + assert_eq!(blob.body, layer_two); | ||
| 390 | + | ||
| 391 | + let image = manifest(&config, &[&layer_one, &layer_two]); | ||
| 392 | + let res = put_manifest(http, "tahinli/app", "v1", &auth, &image).await; | ||
| 393 | + assert_eq!(res.status, 201, "{}", res.text()); | ||
| 394 | + let digest = sha256_digest(&image); | ||
| 395 | + assert_eq!(res.header("docker-content-digest"), Some(digest.as_str())); | ||
| 396 | + | ||
| 397 | + let by_tag = http.get("/v2/tahinli/app/manifests/v1", Some(&auth)).await; | ||
| 398 | + assert_eq!(by_tag.status, 200, "{}", by_tag.text()); | ||
| 399 | + assert_eq!(by_tag.body, image); | ||
| 400 | + assert_eq!(by_tag.header("content-type"), Some(MANIFEST_TYPE)); | ||
| 401 | + let by_digest = http | ||
| 402 | + .get(&format!("/v2/tahinli/app/manifests/{digest}"), Some(&auth)) | ||
| 403 | + .await; | ||
| 404 | + assert_eq!(by_digest.status, 200); | ||
| 405 | + assert_eq!(by_digest.body, image); | ||
| 406 | + let head = http | ||
| 407 | + .send( | ||
| 408 | + reqwest::Method::HEAD, | ||
| 409 | + "/v2/tahinli/app/manifests/v1", | ||
| 410 | + Some(&auth), | ||
| 411 | + &[], | ||
| 412 | + None, | ||
| 413 | + ) | ||
| 414 | + .await; | ||
| 415 | + assert_eq!(head.status, 200); | ||
| 416 | + assert!(head.body.is_empty()); | ||
| 417 | + | ||
| 418 | + let missing = http.get("/v2/tahinli/app/manifests/v9", Some(&auth)).await; | ||
| 419 | + assert_eq!(missing.status, 404); | ||
| 420 | + assert_eq!(missing.error_code(), "MANIFEST_UNKNOWN"); | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +#[tokio::test] | ||
| 424 | +async fn the_tag_list_pages_with_n_and_last() { | ||
| 425 | + let token = generate_token(); | ||
| 426 | + let seeded = token.clone(); | ||
| 427 | + let env = start(move |store| async move { | ||
| 428 | + let tahinli = user(&store, "tahinli").await; | ||
| 429 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 430 | + }) | ||
| 431 | + .await; | ||
| 432 | + let http = &env.http; | ||
| 433 | + let auth = bearer_for(http, &token).await; | ||
| 434 | + let config = b"{}".to_vec(); | ||
| 435 | + assert_eq!( | ||
| 436 | + push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 437 | + 201 | ||
| 438 | + ); | ||
| 439 | + let image = manifest(&config, &[]); | ||
| 440 | + for tag in ["v1", "v2", "v3"] { | ||
| 441 | + assert_eq!( | ||
| 442 | + put_manifest(http, "tahinli/app", tag, &auth, &image) | ||
| 443 | + .await | ||
| 444 | + .status, | ||
| 445 | + 201 | ||
| 446 | + ); | ||
| 447 | + } | ||
| 448 | + | ||
| 449 | + let first = http.get("/v2/tahinli/app/tags/list?n=2", Some(&auth)).await; | ||
| 450 | + assert_eq!(first.status, 200); | ||
| 451 | + assert_eq!(first.json()["tags"], serde_json::json!(["v1", "v2"])); | ||
| 452 | + let link = first.header("link").expect("next page link"); | ||
| 453 | + assert!( | ||
| 454 | + link.contains("last=v2") && link.contains("rel=\"next\""), | ||
| 455 | + "{link}" | ||
| 456 | + ); | ||
| 457 | + | ||
| 458 | + let second = http | ||
| 459 | + .get("/v2/tahinli/app/tags/list?n=2&last=v2", Some(&auth)) | ||
| 460 | + .await; | ||
| 461 | + assert_eq!(second.json()["tags"], serde_json::json!(["v3"])); | ||
| 462 | + assert!(second.header("link").is_none()); | ||
| 463 | + | ||
| 464 | + let all = http.get("/v2/tahinli/app/tags/list", Some(&auth)).await; | ||
| 465 | + assert_eq!(all.json()["name"], "tahinli/app"); | ||
| 466 | + assert_eq!(all.json()["tags"], serde_json::json!(["v1", "v2", "v3"])); | ||
| 467 | +} | ||
| 468 | + | ||
| 469 | +#[tokio::test] | ||
| 470 | +async fn bad_digests_and_missing_blobs_are_refused_with_oci_codes() { | ||
| 471 | + let token = generate_token(); | ||
| 472 | + let seeded = token.clone(); | ||
| 473 | + let env = start(move |store| async move { | ||
| 474 | + let tahinli = user(&store, "tahinli").await; | ||
| 475 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 476 | + }) | ||
| 477 | + .await; | ||
| 478 | + let http = &env.http; | ||
| 479 | + let auth = bearer_for(http, &token).await; | ||
| 480 | + let config = b"{}".to_vec(); | ||
| 481 | + | ||
| 482 | + let wrong = format!( | ||
| 483 | + "/v2/tahinli/app/blobs/uploads/?digest={}", | ||
| 484 | + sha256_digest(b"other") | ||
| 485 | + ); | ||
| 486 | + let res = http.post(&wrong, Some(&auth), Some(config.clone())).await; | ||
| 487 | + assert_eq!(res.status, 400, "{}", res.text()); | ||
| 488 | + assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 489 | + | ||
| 490 | + let image = manifest(&config, &[]); | ||
| 491 | + let res = put_manifest(http, "tahinli/app", "v1", &auth, &image).await; | ||
| 492 | + assert_eq!(res.status, 400); | ||
| 493 | + assert_eq!(res.error_code(), "MANIFEST_BLOB_UNKNOWN"); | ||
| 494 | + | ||
| 495 | + assert_eq!( | ||
| 496 | + push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 497 | + 201 | ||
| 498 | + ); | ||
| 499 | + let res = put_manifest( | ||
| 500 | + http, | ||
| 501 | + "tahinli/app", | ||
| 502 | + &sha256_digest(b"not this"), | ||
| 503 | + &auth, | ||
| 504 | + &image, | ||
| 505 | + ) | ||
| 506 | + .await; | ||
| 507 | + assert_eq!(res.status, 400); | ||
| 508 | + assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 509 | + | ||
| 510 | + let res = http.get("/v2/tahinli/nope/manifests/v1", Some(&auth)).await; | ||
| 511 | + assert_eq!(res.status, 404); | ||
| 512 | + assert_eq!(res.error_code(), "NAME_UNKNOWN"); | ||
| 513 | + | ||
| 514 | + let res = http.get("/v2/Tahinli/App/tags/list", Some(&auth)).await; | ||
| 515 | + assert_eq!(res.status, 400); | ||
| 516 | + assert_eq!(res.error_code(), "NAME_INVALID"); | ||
| 517 | + | ||
| 518 | + let res = http | ||
| 519 | + .get( | ||
| 520 | + &format!("/v2/tahinli/app/blobs/{}", sha256_digest(b"absent")), | ||
| 521 | + Some(&auth), | ||
| 522 | + ) | ||
| 523 | + .await; | ||
| 524 | + assert_eq!(res.status, 404); | ||
| 525 | + assert_eq!(res.error_code(), "BLOB_UNKNOWN"); | ||
| 526 | +} | ||
| 527 | + | ||
| 528 | +#[tokio::test] | ||
| 529 | +async fn an_aborted_chunked_upload_is_gone_after_a_bad_digest() { | ||
| 530 | + let token = generate_token(); | ||
| 531 | + let seeded = token.clone(); | ||
| 532 | + let env = start(move |store| async move { | ||
| 533 | + let tahinli = user(&store, "tahinli").await; | ||
| 534 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 535 | + }) | ||
| 536 | + .await; | ||
| 537 | + let http = &env.http; | ||
| 538 | + let auth = bearer_for(http, &token).await; | ||
| 539 | + | ||
| 540 | + let start = http | ||
| 541 | + .post("/v2/tahinli/app/blobs/uploads/", Some(&auth), None) | ||
| 542 | + .await; | ||
| 543 | + assert_eq!(start.status, 202); | ||
| 544 | + let location = start.header("location").expect("location").to_owned(); | ||
| 545 | + let patched = http | ||
| 546 | + .send( | ||
| 547 | + reqwest::Method::PATCH, | ||
| 548 | + &location, | ||
| 549 | + Some(&auth), | ||
| 550 | + &[], | ||
| 551 | + Some(b"some bytes".to_vec()), | ||
| 552 | + ) | ||
| 553 | + .await; | ||
| 554 | + assert_eq!(patched.status, 202); | ||
| 555 | + assert_eq!(patched.header("range"), Some("0-9")); | ||
| 556 | + | ||
| 557 | + let res = http | ||
| 558 | + .send( | ||
| 559 | + reqwest::Method::PUT, | ||
| 560 | + &format!("{location}?digest={}", sha256_digest(b"different")), | ||
| 561 | + Some(&auth), | ||
| 562 | + &[], | ||
| 563 | + Some(Vec::new()), | ||
| 564 | + ) | ||
| 565 | + .await; | ||
| 566 | + assert_eq!(res.status, 400); | ||
| 567 | + assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 568 | + | ||
| 569 | + let status = http | ||
| 570 | + .send(reqwest::Method::GET, &location, Some(&auth), &[], None) | ||
| 571 | + .await; | ||
| 572 | + assert_eq!(status.status, 404, "{}", status.text()); | ||
| 573 | + assert_eq!(status.error_code(), "BLOB_UPLOAD_UNKNOWN"); | ||
| 574 | +} | ||
| 575 | + | ||
| 576 | +#[tokio::test] | ||
| 577 | +async fn a_public_image_pulls_anonymously_and_a_private_one_does_not() { | ||
| 578 | + let token = generate_token(); | ||
| 579 | + let seeded = token.clone(); | ||
| 580 | + let env = start(move |store| async move { | ||
| 581 | + let tahinli = user(&store, "tahinli").await; | ||
| 582 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 583 | + let secret = store | ||
| 584 | + .ensure_package(&tahinli.id, KIND_OCI, "secret", "secret") | ||
| 585 | + .await | ||
| 586 | + .expect("package"); | ||
| 587 | + store | ||
| 588 | + .set_package_private(&secret.id, true) | ||
| 589 | + .await | ||
| 590 | + .expect("make private"); | ||
| 591 | + }) | ||
| 592 | + .await; | ||
| 593 | + let http = &env.http; | ||
| 594 | + let auth = bearer_for(http, &token).await; | ||
| 595 | + let config = b"{}".to_vec(); | ||
| 596 | + assert_eq!( | ||
| 597 | + push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 598 | + 201 | ||
| 599 | + ); | ||
| 600 | + let image = manifest(&config, &[]); | ||
| 601 | + assert_eq!( | ||
| 602 | + put_manifest(http, "tahinli/app", "v1", &auth, &image) | ||
| 603 | + .await | ||
| 604 | + .status, | ||
| 605 | + 201 | ||
| 606 | + ); | ||
| 607 | + assert_eq!( | ||
| 608 | + push_blob(http, "tahinli/secret", &auth, &config) | ||
| 609 | + .await | ||
| 610 | + .status, | ||
| 611 | + 201 | ||
| 612 | + ); | ||
| 613 | + assert_eq!( | ||
| 614 | + put_manifest(http, "tahinli/secret", "v1", &auth, &image) | ||
| 615 | + .await | ||
| 616 | + .status, | ||
| 617 | + 201 | ||
| 618 | + ); | ||
| 619 | + | ||
| 620 | + let anon = http.get("/v2/tahinli/app/manifests/v1", None).await; | ||
| 621 | + assert_eq!(anon.status, 200, "{}", anon.text()); | ||
| 622 | + assert_eq!(anon.body, image); | ||
| 623 | + let anon_blob = http | ||
| 624 | + .get( | ||
| 625 | + &format!("/v2/tahinli/app/blobs/{}", sha256_digest(&config)), | ||
| 626 | + None, | ||
| 627 | + ) | ||
| 628 | + .await; | ||
| 629 | + assert_eq!(anon_blob.status, 200); | ||
| 630 | + | ||
| 631 | + let hidden = http.get("/v2/tahinli/secret/manifests/v1", None).await; | ||
| 632 | + assert_eq!(hidden.status, 401); | ||
| 633 | + assert!(hidden.header("www-authenticate").is_some()); | ||
| 634 | + assert_eq!(hidden.error_code(), "UNAUTHORIZED"); | ||
| 635 | + let owner = http | ||
| 636 | + .get("/v2/tahinli/secret/manifests/v1", Some(&auth)) | ||
| 637 | + .await; | ||
| 638 | + assert_eq!(owner.status, 200); | ||
| 639 | + | ||
| 640 | + let missing = http.get("/v2/tahinli/nothing/manifests/v1", None).await; | ||
| 641 | + assert_eq!( | ||
| 642 | + missing.status, 401, | ||
| 643 | + "anonymous callers learn nothing about missing images" | ||
| 644 | + ); | ||
| 645 | +} | ||
| 646 | + | ||
| 647 | +#[tokio::test] | ||
| 648 | +async fn writes_need_the_packages_scope_and_the_owner() { | ||
| 649 | + let token = generate_token(); | ||
| 650 | + let bob_token = generate_token(); | ||
| 651 | + let no_scope = generate_token(); | ||
| 652 | + let (seeded, seeded_bob, seeded_none) = (token.clone(), bob_token.clone(), no_scope.clone()); | ||
| 653 | + let env = start(move |store| async move { | ||
| 654 | + let tahinli = user(&store, "tahinli").await; | ||
| 655 | + let bob = user(&store, "bob").await; | ||
| 656 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 657 | + grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 658 | + grant(&store, &tahinli, &["repo"], &seeded_none).await; | ||
| 659 | + }) | ||
| 660 | + .await; | ||
| 661 | + let http = &env.http; | ||
| 662 | + | ||
| 663 | + let anon = http | ||
| 664 | + .post("/v2/tahinli/app/blobs/uploads/", None, None) | ||
| 665 | + .await; | ||
| 666 | + assert_eq!(anon.status, 401); | ||
| 667 | + assert!(anon.header("www-authenticate").is_some()); | ||
| 668 | + | ||
| 669 | + let without = bearer_for_scope_less(http, &no_scope).await; | ||
| 670 | + let res = http | ||
| 671 | + .post("/v2/tahinli/app/blobs/uploads/", Some(&without), None) | ||
| 672 | + .await; | ||
| 673 | + assert_eq!( | ||
| 674 | + res.status, 401, | ||
| 675 | + "a token without the packages scope cannot push" | ||
| 676 | + ); | ||
| 677 | + | ||
| 678 | + let bob_auth = bearer_for_as(http, "bob", &bob_token).await; | ||
| 679 | + let res = http | ||
| 680 | + .post("/v2/tahinli/app/blobs/uploads/", Some(&bob_auth), None) | ||
| 681 | + .await; | ||
| 682 | + assert_eq!(res.status, 403); | ||
| 683 | + assert_eq!(res.error_code(), "DENIED"); | ||
| 684 | + | ||
| 685 | + let owner_auth = bearer_for(http, &token).await; | ||
| 686 | + let res = http | ||
| 687 | + .post("/v2/tahinli/app/blobs/uploads/", Some(&owner_auth), None) | ||
| 688 | + .await; | ||
| 689 | + assert_eq!(res.status, 202); | ||
| 690 | +} | ||
| 691 | + | ||
| 692 | +/// A bearer header for `token` with no scope, read through the token endpoint as Basic. | ||
| 693 | +async fn bearer_for_scope_less(http: &Http, token: &str) -> String { | ||
| 694 | + bearer_for(http, token).await | ||
| 695 | +} | ||
| 696 | + | ||
| 697 | +/// A bearer header for `token` owned by `who`, read through the token endpoint as Basic. | ||
| 698 | +async fn bearer_for_as(http: &Http, who: &str, token: &str) -> String { | ||
| 699 | + let res = http | ||
| 700 | + .send( | ||
| 701 | + reqwest::Method::GET, | ||
| 702 | + "/v2/token", | ||
| 703 | + Some(&basic(who, token)), | ||
| 704 | + &[], | ||
| 705 | + None, | ||
| 706 | + ) | ||
| 707 | + .await; | ||
| 708 | + assert_eq!(res.status, 200, "{}", res.text()); | ||
| 709 | + format!("Bearer {}", res.json()["token"].as_str().expect("token")) | ||
| 710 | +} | ||
| 711 | + | ||
| 712 | +#[tokio::test] | ||
| 713 | +async fn mount_copies_a_blob_across_repositories() { | ||
| 714 | + let token = generate_token(); | ||
| 715 | + let seeded = token.clone(); | ||
| 716 | + let env = start(move |store| async move { | ||
| 717 | + let tahinli = user(&store, "tahinli").await; | ||
| 718 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 719 | + }) | ||
| 720 | + .await; | ||
| 721 | + let http = &env.http; | ||
| 722 | + let auth = bearer_for(http, &token).await; | ||
| 723 | + let layer = b"shared layer bytes".to_vec(); | ||
| 724 | + assert_eq!( | ||
| 725 | + push_blob(http, "tahinli/app", &auth, &layer).await.status, | ||
| 726 | + 201 | ||
| 727 | + ); | ||
| 728 | + | ||
| 729 | + let digest = sha256_digest(&layer); | ||
| 730 | + let mounted = http | ||
| 731 | + .post( | ||
| 732 | + &format!("/v2/tahinli/other/blobs/uploads/?mount={digest}&from=tahinli/app"), | ||
| 733 | + Some(&auth), | ||
| 734 | + None, | ||
| 735 | + ) | ||
| 736 | + .await; | ||
| 737 | + assert_eq!(mounted.status, 201, "{}", mounted.text()); | ||
| 738 | + let read = http | ||
| 739 | + .get(&format!("/v2/tahinli/other/blobs/{digest}"), Some(&auth)) | ||
| 740 | + .await; | ||
| 741 | + assert_eq!(read.body, layer); | ||
| 742 | + | ||
| 743 | + let not_there = http | ||
| 744 | + .post( | ||
| 745 | + &format!( | ||
| 746 | + "/v2/tahinli/other/blobs/uploads/?mount={}&from=tahinli/app", | ||
| 747 | + sha256_digest(b"x") | ||
| 748 | + ), | ||
| 749 | + Some(&auth), | ||
| 750 | + None, | ||
| 751 | + ) | ||
| 752 | + .await; | ||
| 753 | + assert_eq!( | ||
| 754 | + not_there.status, 202, | ||
| 755 | + "a mount that is not possible opens an upload instead" | ||
| 756 | + ); | ||
| 757 | +} | ||
| 758 | + | ||
| 759 | +#[tokio::test] | ||
| 760 | +async fn deleting_tags_and_manifests_sweeps_the_blobs_nothing_uses() { | ||
| 761 | + let token = generate_token(); | ||
| 762 | + let seeded = token.clone(); | ||
| 763 | + let env = start(move |store| async move { | ||
| 764 | + let tahinli = user(&store, "tahinli").await; | ||
| 765 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 766 | + }) | ||
| 767 | + .await; | ||
| 768 | + let http = &env.http; | ||
| 769 | + let auth = bearer_for(http, &token).await; | ||
| 770 | + let config = b"{\"shared\":true}".to_vec(); | ||
| 771 | + let layer_a = b"only in v1".to_vec(); | ||
| 772 | + let layer_b = b"only in v2".to_vec(); | ||
| 773 | + for blob in [&config, &layer_a, &layer_b] { | ||
| 774 | + assert_eq!( | ||
| 775 | + push_blob(http, "tahinli/app", &auth, blob).await.status, | ||
| 776 | + 201 | ||
| 777 | + ); | ||
| 778 | + } | ||
| 779 | + let v1 = manifest(&config, &[&layer_a]); | ||
| 780 | + let v2 = manifest(&config, &[&layer_b]); | ||
| 781 | + assert_eq!( | ||
| 782 | + put_manifest(http, "tahinli/app", "v1", &auth, &v1) | ||
| 783 | + .await | ||
| 784 | + .status, | ||
| 785 | + 201 | ||
| 786 | + ); | ||
| 787 | + assert_eq!( | ||
| 788 | + put_manifest(http, "tahinli/app", "v2", &auth, &v2) | ||
| 789 | + .await | ||
| 790 | + .status, | ||
| 791 | + 201 | ||
| 792 | + ); | ||
| 793 | + | ||
| 794 | + let blob_url = |bytes: &[u8]| format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)); | ||
| 795 | + let res = http | ||
| 796 | + .send( | ||
| 797 | + reqwest::Method::DELETE, | ||
| 798 | + "/v2/tahinli/app/manifests/v2", | ||
| 799 | + Some(&auth), | ||
| 800 | + &[], | ||
| 801 | + None, | ||
| 802 | + ) | ||
| 803 | + .await; | ||
| 804 | + assert_eq!(res.status, 202, "{}", res.text()); | ||
| 805 | + assert_eq!( | ||
| 806 | + http.get("/v2/tahinli/app/manifests/v2", Some(&auth)) | ||
| 807 | + .await | ||
| 808 | + .status, | ||
| 809 | + 404 | ||
| 810 | + ); | ||
| 811 | + assert_eq!(http.get(&blob_url(&layer_b), Some(&auth)).await.status, 404); | ||
| 812 | + assert_eq!(http.get(&blob_url(&layer_a), Some(&auth)).await.status, 200); | ||
| 813 | + assert_eq!(http.get(&blob_url(&config), Some(&auth)).await.status, 200); | ||
| 814 | + | ||
| 815 | + let v1_digest = sha256_digest(&v1); | ||
| 816 | + let res = http | ||
| 817 | + .send( | ||
| 818 | + reqwest::Method::DELETE, | ||
| 819 | + &format!("/v2/tahinli/app/manifests/{v1_digest}"), | ||
| 820 | + Some(&auth), | ||
| 821 | + &[], | ||
| 822 | + None, | ||
| 823 | + ) | ||
| 824 | + .await; | ||
| 825 | + assert_eq!(res.status, 202); | ||
| 826 | + assert_eq!(http.get(&blob_url(&layer_a), Some(&auth)).await.status, 404); | ||
| 827 | + assert_eq!(http.get(&blob_url(&config), Some(&auth)).await.status, 404); | ||
| 828 | + let tags = http.get("/v2/tahinli/app/tags/list", Some(&auth)).await; | ||
| 829 | + assert_eq!(tags.json()["tags"], serde_json::json!([])); | ||
| 830 | +} | ||
| 831 | + | ||
| 832 | +#[tokio::test] | ||
| 833 | +async fn a_blob_a_manifest_uses_cannot_be_deleted_and_an_unused_one_can() { | ||
| 834 | + let token = generate_token(); | ||
| 835 | + let seeded = token.clone(); | ||
| 836 | + let env = start(move |store| async move { | ||
| 837 | + let tahinli = user(&store, "tahinli").await; | ||
| 838 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 839 | + }) | ||
| 840 | + .await; | ||
| 841 | + let http = &env.http; | ||
| 842 | + let auth = bearer_for(http, &token).await; | ||
| 843 | + let config = b"{}".to_vec(); | ||
| 844 | + let layer = b"kept by the manifest".to_vec(); | ||
| 845 | + let spare = b"never used".to_vec(); | ||
| 846 | + assert_eq!( | ||
| 847 | + push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 848 | + 201 | ||
| 849 | + ); | ||
| 850 | + assert_eq!( | ||
| 851 | + push_blob(http, "tahinli/app", &auth, &layer).await.status, | ||
| 852 | + 201 | ||
| 853 | + ); | ||
| 854 | + assert_eq!( | ||
| 855 | + push_blob(http, "tahinli/app", &auth, &spare).await.status, | ||
| 856 | + 201 | ||
| 857 | + ); | ||
| 858 | + assert_eq!( | ||
| 859 | + put_manifest( | ||
| 860 | + http, | ||
| 861 | + "tahinli/app", | ||
| 862 | + "v1", | ||
| 863 | + &auth, | ||
| 864 | + &manifest(&config, &[&layer]) | ||
| 865 | + ) | ||
| 866 | + .await | ||
| 867 | + .status, | ||
| 868 | + 201 | ||
| 869 | + ); | ||
| 870 | + | ||
| 871 | + let delete = |bytes: &[u8]| format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)); | ||
| 872 | + let refused = http | ||
| 873 | + .send( | ||
| 874 | + reqwest::Method::DELETE, | ||
| 875 | + &delete(&layer), | ||
| 876 | + Some(&auth), | ||
| 877 | + &[], | ||
| 878 | + None, | ||
| 879 | + ) | ||
| 880 | + .await; | ||
| 881 | + assert_eq!(refused.status, 400); | ||
| 882 | + assert_eq!(refused.error_code(), "UNSUPPORTED"); | ||
| 883 | + | ||
| 884 | + let gone = http | ||
| 885 | + .send( | ||
| 886 | + reqwest::Method::DELETE, | ||
| 887 | + &delete(&spare), | ||
| 888 | + Some(&auth), | ||
| 889 | + &[], | ||
| 890 | + None, | ||
| 891 | + ) | ||
| 892 | + .await; | ||
| 893 | + assert_eq!(gone.status, 202); | ||
| 894 | + assert_eq!(http.get(&delete(&spare), Some(&auth)).await.status, 404); | ||
| 895 | +} | ||
| 896 | + | ||
| 897 | +#[tokio::test] | ||
| 898 | +#[ignore = "runs podman; run with --ignored"] | ||
| 899 | +async fn podman_logs_in_pushes_and_pulls_an_image() { | ||
| 900 | + if !tool_on_path("podman") { | ||
| 901 | + eprintln!("podman is not installed; skipping"); | ||
| 902 | + return; | ||
| 903 | + } | ||
| 904 | + let token = generate_token(); | ||
| 905 | + let seeded = token.clone(); | ||
| 906 | + let env = start(move |store| async move { | ||
| 907 | + let tahinli = user(&store, "tahinli").await; | ||
| 908 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 909 | + }) | ||
| 910 | + .await; | ||
| 911 | + let host = format!("127.0.0.1:{}", env.port); | ||
| 912 | + let work = tempfile::tempdir().expect("work dir"); | ||
| 913 | + let dir = work.path(); | ||
| 914 | + let auth_file = dir.join("auth.json"); | ||
| 915 | + std::fs::write(dir.join("hello.txt"), "hello from the forge\n").expect("file"); | ||
| 916 | + std::fs::write( | ||
| 917 | + dir.join("Containerfile"), | ||
| 918 | + "FROM scratch\nCOPY hello.txt /hello.txt\n", | ||
| 919 | + ) | ||
| 920 | + .expect("containerfile"); | ||
| 921 | + let root = dir.join("store"); | ||
| 922 | + let run = dir.join("run"); | ||
| 923 | + let auth_path = auth_file.to_str().expect("utf8").to_owned(); | ||
| 924 | + let root_arg = root.to_str().expect("utf8").to_owned(); | ||
| 925 | + let run_arg = run.to_str().expect("utf8").to_owned(); | ||
| 926 | + let podman = |args: &[&str]| -> String { | ||
| 927 | + let out = Command::new("podman") | ||
| 928 | + .args(["--root", &root_arg, "--runroot", &run_arg]) | ||
| 929 | + .args(args) | ||
| 930 | + .env("REGISTRY_AUTH_FILE", &auth_path) | ||
| 931 | + .current_dir(dir) | ||
| 932 | + .output() | ||
| 933 | + .expect("run podman"); | ||
| 934 | + assert!( | ||
| 935 | + out.status.success(), | ||
| 936 | + "podman {args:?} failed:\n{}", | ||
| 937 | + describe(&out) | ||
| 938 | + ); | ||
| 939 | + format!( | ||
| 940 | + "{}{}", | ||
| 941 | + String::from_utf8_lossy(&out.stdout), | ||
| 942 | + String::from_utf8_lossy(&out.stderr) | ||
| 943 | + ) | ||
| 944 | + }; | ||
| 945 | + | ||
| 946 | + podman(&[ | ||
| 947 | + "build", | ||
| 948 | + "-f", | ||
| 949 | + "Containerfile", | ||
| 950 | + "-t", | ||
| 951 | + "localhost/tiny:v1", | ||
| 952 | + ".", | ||
| 953 | + ]); | ||
| 954 | + podman(&[ | ||
| 955 | + "login", | ||
| 956 | + "--tls-verify=false", | ||
| 957 | + "-u", | ||
| 958 | + "tahinli", | ||
| 959 | + "-p", | ||
| 960 | + &token, | ||
| 961 | + &host, | ||
| 962 | + ]); | ||
| 963 | + let target = format!("{host}/tahinli/tiny:v1"); | ||
| 964 | + podman(&["push", "--tls-verify=false", "localhost/tiny:v1", &target]); | ||
| 965 | + podman(&["rmi", "localhost/tiny:v1"]); | ||
| 966 | + podman(&["pull", "--tls-verify=false", &target]); | ||
| 967 | + let listed = podman(&["images", "--format", "{{.Repository}}:{{.Tag}}"]); | ||
| 968 | + assert!( | ||
| 969 | + listed.contains(&format!("{host}/tahinli/tiny:v1")), | ||
| 970 | + "{listed}" | ||
| 971 | + ); | ||
| 972 | +} | ||
crates/forge-web/tests/packages_e2e.rsadded+604 -0
| @@ -0,0 +1,604 @@ | |||
| 1 | +//! Black-box tests for the Cargo package registry. They start the real `forge` binary and drive | ||
| 2 | +//! the protocol over HTTP the way cargo does: config.json, the sparse index, the publish body, the | ||
| 3 | +//! download, yank and unyank, plus the scope, ownership and private-package rules. Tokens and a | ||
| 4 | +//! private package are seeded through the store before the server starts, since the web API has | ||
| 5 | +//! no way to make a package private. | ||
| 6 | + | ||
| 7 | +mod common; | ||
| 8 | +use common::{BIN, Server, describe, launch, pick_ports, write_config}; | ||
| 9 | +use std::io::Write; | ||
| 10 | +use std::path::Path; | ||
| 11 | +use std::process::Command; | ||
| 12 | +use std::time::Duration; | ||
| 13 | + | ||
| 14 | +use forge_core::packages::{KIND_CARGO, NewPackageVersion}; | ||
| 15 | +use forge_core::token::{generate_token, hash_token}; | ||
| 16 | +use forge_core::{Store, User}; | ||
| 17 | +use sha2::{Digest, Sha256}; | ||
| 18 | + | ||
| 19 | +const PW: &str = "tahinli-password-123"; | ||
| 20 | + | ||
| 21 | +/// The index file of `demo-crate`, which is ten letters: `de/mo/demo-crate`. | ||
| 22 | +const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate"; | ||
| 23 | +const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new"; | ||
| 24 | + | ||
| 25 | +struct Resp { | ||
| 26 | + status: u16, | ||
| 27 | + body: Vec<u8>, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl Resp { | ||
| 31 | + fn text(&self) -> String { | ||
| 32 | + String::from_utf8_lossy(&self.body).into_owned() | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + fn json(&self) -> serde_json::Value { | ||
| 36 | + serde_json::from_slice(&self.body).expect("json body") | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +struct Http { | ||
| 41 | + client: reqwest::Client, | ||
| 42 | + base: String, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +impl Http { | ||
| 46 | + fn new(port: u16) -> Self { | ||
| 47 | + let client = reqwest::Client::builder() | ||
| 48 | + .redirect(reqwest::redirect::Policy::none()) | ||
| 49 | + .timeout(Duration::from_secs(60)) | ||
| 50 | + .build() | ||
| 51 | + .expect("http client"); | ||
| 52 | + Self { | ||
| 53 | + client, | ||
| 54 | + base: format!("http://127.0.0.1:{port}"), | ||
| 55 | + } | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + async fn call( | ||
| 59 | + &self, | ||
| 60 | + method: reqwest::Method, | ||
| 61 | + path: &str, | ||
| 62 | + auth: Option<&str>, | ||
| 63 | + body: Option<Vec<u8>>, | ||
| 64 | + ) -> Resp { | ||
| 65 | + let mut req = self.client.request(method, format!("{}{path}", self.base)); | ||
| 66 | + if let Some(token) = auth { | ||
| 67 | + req = req.header("Authorization", token); | ||
| 68 | + } | ||
| 69 | + if let Some(bytes) = body { | ||
| 70 | + req = req.body(bytes); | ||
| 71 | + } | ||
| 72 | + let res = req.send().await.expect("http request"); | ||
| 73 | + let status = res.status().as_u16(); | ||
| 74 | + let body = res.bytes().await.expect("read body").to_vec(); | ||
| 75 | + Resp { status, body } | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + async fn get(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 79 | + self.call(reqwest::Method::GET, path, auth, None).await | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + async fn put(&self, path: &str, auth: Option<&str>, body: Vec<u8>) -> Resp { | ||
| 83 | + self.call(reqwest::Method::PUT, path, auth, Some(body)) | ||
| 84 | + .await | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + async fn delete(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 88 | + self.call(reqwest::Method::DELETE, path, auth, None).await | ||
| 89 | + } | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded. | ||
| 93 | +fn admin(config: &Path, args: &[&str]) { | ||
| 94 | + let out = Command::new(BIN) | ||
| 95 | + .arg("--config") | ||
| 96 | + .arg(config) | ||
| 97 | + .arg("admin") | ||
| 98 | + .args(args) | ||
| 99 | + .env("FORGE_PASSWORD", PW) | ||
| 100 | + .output() | ||
| 101 | + .expect("run admin command"); | ||
| 102 | + assert!( | ||
| 103 | + out.status.success(), | ||
| 104 | + "admin {args:?} failed:\n{}", | ||
| 105 | + describe(&out) | ||
| 106 | + ); | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// A running server. The temp dir lives as long as the test. | ||
| 110 | +struct Env { | ||
| 111 | + _root: tempfile::TempDir, | ||
| 112 | + _server: Server, | ||
| 113 | + http: Http, | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// Creates the users `tahinli` and `bob`, runs `seed` on the store, then starts the server. | ||
| 117 | +async fn start<F, Fut>(seed: F) -> Env | ||
| 118 | +where | ||
| 119 | + F: FnOnce(Store) -> Fut, | ||
| 120 | + Fut: std::future::Future<Output = ()>, | ||
| 121 | +{ | ||
| 122 | + let root = tempfile::Builder::new() | ||
| 123 | + .prefix("fpk") | ||
| 124 | + .tempdir_in("/tmp") | ||
| 125 | + .expect("temp dir"); | ||
| 126 | + let dir = root.path().to_path_buf(); | ||
| 127 | + let ports = pick_ports(); | ||
| 128 | + let config = write_config(&dir, ports); | ||
| 129 | + admin(&config, &["create-user", "tahinli"]); | ||
| 130 | + admin(&config, &["create-user", "bob"]); | ||
| 131 | + let store = Store::open(&dir.join("forge.db")) | ||
| 132 | + .await | ||
| 133 | + .expect("open store"); | ||
| 134 | + seed(store).await; | ||
| 135 | + let (server, ports) = launch(&dir, ports).await; | ||
| 136 | + Env { | ||
| 137 | + _root: root, | ||
| 138 | + _server: server, | ||
| 139 | + http: Http::new(ports.http), | ||
| 140 | + } | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +/// Stores a token for `user` with the given scopes. `token` is the plaintext cargo will send. | ||
| 144 | +async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) { | ||
| 145 | + let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); | ||
| 146 | + store | ||
| 147 | + .create_token(&user.id, "ci", &hash_token(token), &scopes, None) | ||
| 148 | + .await | ||
| 149 | + .expect("create token"); | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +async fn user(store: &Store, name: &str) -> User { | ||
| 153 | + store | ||
| 154 | + .user_by_username(name) | ||
| 155 | + .await | ||
| 156 | + .expect("lookup user") | ||
| 157 | + .expect("user exists") | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// A `.crate` file: a gzipped tarball with one package directory holding Cargo.toml and README.md. | ||
| 161 | +fn crate_file(name: &str, version: &str, readme: &str) -> Vec<u8> { | ||
| 162 | + let mut tar_bytes = Vec::new(); | ||
| 163 | + { | ||
| 164 | + let mut builder = tar::Builder::new(&mut tar_bytes); | ||
| 165 | + for (path, body) in [ | ||
| 166 | + ( | ||
| 167 | + format!("{name}-{version}/Cargo.toml"), | ||
| 168 | + format!("[package]\nname = \"{name}\"\n"), | ||
| 169 | + ), | ||
| 170 | + (format!("{name}-{version}/README.md"), readme.to_owned()), | ||
| 171 | + ] { | ||
| 172 | + let mut header = tar::Header::new_gnu(); | ||
| 173 | + header.set_size(body.len() as u64); | ||
| 174 | + header.set_mode(0o644); | ||
| 175 | + header.set_cksum(); | ||
| 176 | + builder | ||
| 177 | + .append_data(&mut header, path, body.as_bytes()) | ||
| 178 | + .expect("append"); | ||
| 179 | + } | ||
| 180 | + builder.finish().expect("finish tar"); | ||
| 181 | + } | ||
| 182 | + let mut gz = Vec::new(); | ||
| 183 | + { | ||
| 184 | + let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast()); | ||
| 185 | + enc.write_all(&tar_bytes).expect("gzip"); | ||
| 186 | + enc.finish().expect("finish gzip"); | ||
| 187 | + } | ||
| 188 | + gz | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +/// The publish body cargo sends: a length-prefixed JSON document, then a length-prefixed crate. | ||
| 192 | +fn publish_body(meta: &serde_json::Value, krate: &[u8]) -> Vec<u8> { | ||
| 193 | + let json = serde_json::to_vec(meta).expect("metadata json"); | ||
| 194 | + let mut body = Vec::new(); | ||
| 195 | + body.extend_from_slice(&(json.len() as u32).to_le_bytes()); | ||
| 196 | + body.extend_from_slice(&json); | ||
| 197 | + body.extend_from_slice(&(krate.len() as u32).to_le_bytes()); | ||
| 198 | + body.extend_from_slice(krate); | ||
| 199 | + body | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +fn metadata(name: &str, version: &str) -> serde_json::Value { | ||
| 203 | + serde_json::json!({ | ||
| 204 | + "name": name, | ||
| 205 | + "vers": version, | ||
| 206 | + "deps": [{ | ||
| 207 | + "name": "serde", | ||
| 208 | + "version_req": "^1", | ||
| 209 | + "features": ["derive"], | ||
| 210 | + "optional": false, | ||
| 211 | + "default_features": true, | ||
| 212 | + "target": null, | ||
| 213 | + "kind": "normal", | ||
| 214 | + "registry": null, | ||
| 215 | + "explicit_name_in_toml": null | ||
| 216 | + }], | ||
| 217 | + "features": { "default": ["serde"] }, | ||
| 218 | + "authors": [], | ||
| 219 | + "description": "A demo crate", | ||
| 220 | + "license": "MIT", | ||
| 221 | + "readme": "# Demo\n\nFrom the metadata.", | ||
| 222 | + "keywords": [], | ||
| 223 | + "categories": [], | ||
| 224 | + "badges": {}, | ||
| 225 | + "links": null | ||
| 226 | + }) | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +fn sha256_hex(bytes: &[u8]) -> String { | ||
| 230 | + hex::encode(Sha256::digest(bytes)) | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +fn index_line(resp: &Resp) -> serde_json::Value { | ||
| 234 | + let text = resp.text(); | ||
| 235 | + serde_json::from_str(text.trim()).expect("one index line") | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +#[tokio::test] | ||
| 239 | +async fn config_json_points_at_the_owner_registry() { | ||
| 240 | + let env = start(|_| async {}).await; | ||
| 241 | + let res = env | ||
| 242 | + .http | ||
| 243 | + .get("/api/packages/tahinli/cargo/config.json", None) | ||
| 244 | + .await; | ||
| 245 | + assert_eq!(res.status, 200, "{}", res.text()); | ||
| 246 | + let json = res.json(); | ||
| 247 | + let dl = json["dl"].as_str().expect("dl"); | ||
| 248 | + let api = json["api"].as_str().expect("api"); | ||
| 249 | + assert!( | ||
| 250 | + dl.ends_with("/api/packages/tahinli/cargo/download/{crate}/{version}"), | ||
| 251 | + "{dl}" | ||
| 252 | + ); | ||
| 253 | + assert!(api.ends_with("/api/packages/tahinli/cargo"), "{api}"); | ||
| 254 | + assert_eq!(json["auth-required"], false); | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +#[tokio::test] | ||
| 258 | +async fn publish_index_download_and_checksum_round_trip() { | ||
| 259 | + let token = generate_token(); | ||
| 260 | + let seeded = token.clone(); | ||
| 261 | + let env = start(move |store| async move { | ||
| 262 | + let tahinli = user(&store, "tahinli").await; | ||
| 263 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 264 | + }) | ||
| 265 | + .await; | ||
| 266 | + let krate = crate_file("demo-crate", "0.1.0", "# Demo\n\nHello from the README."); | ||
| 267 | + let body = publish_body(&metadata("demo-crate", "0.1.0"), &krate); | ||
| 268 | + | ||
| 269 | + let res = env.http.put(PUBLISH, Some(&token), body.clone()).await; | ||
| 270 | + assert_eq!(res.status, 200, "{}", res.text()); | ||
| 271 | + assert!(res.json()["warnings"].is_object()); | ||
| 272 | + | ||
| 273 | + let index = env.http.get(DEMO_INDEX, None).await; | ||
| 274 | + assert_eq!(index.status, 200, "{}", index.text()); | ||
| 275 | + let line = index_line(&index); | ||
| 276 | + assert_eq!(line["name"], "demo-crate"); | ||
| 277 | + assert_eq!(line["vers"], "0.1.0"); | ||
| 278 | + assert_eq!(line["v"], 2); | ||
| 279 | + assert_eq!(line["yanked"], false); | ||
| 280 | + assert_eq!(line["deps"][0]["name"], "serde"); | ||
| 281 | + assert_eq!(line["features"]["default"], serde_json::json!(["serde"])); | ||
| 282 | + let cksum = line["cksum"].as_str().expect("cksum").to_owned(); | ||
| 283 | + assert_eq!(cksum, sha256_hex(&krate)); | ||
| 284 | + | ||
| 285 | + let download = env | ||
| 286 | + .http | ||
| 287 | + .get( | ||
| 288 | + "/api/packages/tahinli/cargo/download/demo-crate/0.1.0", | ||
| 289 | + None, | ||
| 290 | + ) | ||
| 291 | + .await; | ||
| 292 | + assert_eq!(download.status, 200); | ||
| 293 | + assert_eq!( | ||
| 294 | + sha256_hex(&download.body), | ||
| 295 | + cksum, | ||
| 296 | + "downloaded bytes match the index checksum" | ||
| 297 | + ); | ||
| 298 | + assert_eq!(download.body, krate); | ||
| 299 | + | ||
| 300 | + let duplicate = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 301 | + assert_eq!(duplicate.status, 409, "{}", duplicate.text()); | ||
| 302 | + let detail = duplicate.json()["errors"][0]["detail"] | ||
| 303 | + .as_str() | ||
| 304 | + .unwrap_or_default() | ||
| 305 | + .to_owned(); | ||
| 306 | + assert!(detail.contains("already uploaded"), "{detail}"); | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +#[tokio::test] | ||
| 310 | +async fn publish_needs_a_packages_token_with_write_access() { | ||
| 311 | + let repo_only = generate_token(); | ||
| 312 | + let bob_token = generate_token(); | ||
| 313 | + let (seeded_repo_only, seeded_bob) = (repo_only.clone(), bob_token.clone()); | ||
| 314 | + let env = start(move |store| async move { | ||
| 315 | + let tahinli = user(&store, "tahinli").await; | ||
| 316 | + let bob = user(&store, "bob").await; | ||
| 317 | + grant(&store, &tahinli, &["repo"], &seeded_repo_only).await; | ||
| 318 | + grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 319 | + }) | ||
| 320 | + .await; | ||
| 321 | + let body = publish_body( | ||
| 322 | + &metadata("demo-crate", "0.1.0"), | ||
| 323 | + &crate_file("demo-crate", "0.1.0", "x"), | ||
| 324 | + ); | ||
| 325 | + | ||
| 326 | + let anonymous = env.http.put(PUBLISH, None, body.clone()).await; | ||
| 327 | + assert_eq!(anonymous.status, 401, "{}", anonymous.text()); | ||
| 328 | + | ||
| 329 | + let no_scope = env.http.put(PUBLISH, Some(&repo_only), body.clone()).await; | ||
| 330 | + assert_eq!(no_scope.status, 403, "{}", no_scope.text()); | ||
| 331 | + assert!( | ||
| 332 | + no_scope.json()["errors"][0]["detail"] | ||
| 333 | + .as_str() | ||
| 334 | + .unwrap_or_default() | ||
| 335 | + .contains("packages scope") | ||
| 336 | + ); | ||
| 337 | + | ||
| 338 | + let stranger = env.http.put(PUBLISH, Some(&bob_token), body).await; | ||
| 339 | + assert_eq!(stranger.status, 403, "{}", stranger.text()); | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +#[tokio::test] | ||
| 343 | +async fn invalid_names_and_versions_are_400_with_cargo_errors() { | ||
| 344 | + let token = generate_token(); | ||
| 345 | + let seeded = token.clone(); | ||
| 346 | + let env = start(move |store| async move { | ||
| 347 | + let tahinli = user(&store, "tahinli").await; | ||
| 348 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 349 | + }) | ||
| 350 | + .await; | ||
| 351 | + let bad_name = publish_body( | ||
| 352 | + &metadata("1bad name", "0.1.0"), | ||
| 353 | + &crate_file("1bad", "0.1.0", "x"), | ||
| 354 | + ); | ||
| 355 | + let res = env.http.put(PUBLISH, Some(&token), bad_name).await; | ||
| 356 | + assert_eq!(res.status, 400, "{}", res.text()); | ||
| 357 | + assert!(res.json()["errors"][0]["detail"].is_string()); | ||
| 358 | + | ||
| 359 | + let bad_version = publish_body( | ||
| 360 | + &metadata("demo-crate", "one"), | ||
| 361 | + &crate_file("demo-crate", "0.1.0", "x"), | ||
| 362 | + ); | ||
| 363 | + let res = env.http.put(PUBLISH, Some(&token), bad_version).await; | ||
| 364 | + assert_eq!(res.status, 400, "{}", res.text()); | ||
| 365 | + | ||
| 366 | + let garbage = env | ||
| 367 | + .http | ||
| 368 | + .put(PUBLISH, Some(&token), b"not a publish body".to_vec()) | ||
| 369 | + .await; | ||
| 370 | + assert_eq!(garbage.status, 400, "{}", garbage.text()); | ||
| 371 | +} | ||
| 372 | + | ||
| 373 | +#[tokio::test] | ||
| 374 | +async fn yank_marks_the_version_and_unyank_restores_it() { | ||
| 375 | + let token = generate_token(); | ||
| 376 | + let seeded = token.clone(); | ||
| 377 | + let env = start(move |store| async move { | ||
| 378 | + let tahinli = user(&store, "tahinli").await; | ||
| 379 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 380 | + }) | ||
| 381 | + .await; | ||
| 382 | + let body = publish_body( | ||
| 383 | + &metadata("demo-crate", "0.1.0"), | ||
| 384 | + &crate_file("demo-crate", "0.1.0", "x"), | ||
| 385 | + ); | ||
| 386 | + let publish = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 387 | + assert_eq!(publish.status, 200, "{}", publish.text()); | ||
| 388 | + | ||
| 389 | + let yank = "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/0.1.0/yank"; | ||
| 390 | + let yanked = env.http.delete(yank, Some(&token)).await; | ||
| 391 | + assert_eq!(yanked.status, 200, "{}", yanked.text()); | ||
| 392 | + assert_eq!( | ||
| 393 | + index_line(&env.http.get(DEMO_INDEX, None).await)["yanked"], | ||
| 394 | + true | ||
| 395 | + ); | ||
| 396 | + let download = env | ||
| 397 | + .http | ||
| 398 | + .get( | ||
| 399 | + "/api/packages/tahinli/cargo/download/demo-crate/0.1.0", | ||
| 400 | + None, | ||
| 401 | + ) | ||
| 402 | + .await; | ||
| 403 | + assert_eq!(download.status, 200, "a yanked version still downloads"); | ||
| 404 | + | ||
| 405 | + let unyank = "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/0.1.0/unyank"; | ||
| 406 | + let restored = env.http.put(unyank, Some(&token), Vec::new()).await; | ||
| 407 | + assert_eq!(restored.status, 200, "{}", restored.text()); | ||
| 408 | + assert_eq!( | ||
| 409 | + index_line(&env.http.get(DEMO_INDEX, None).await)["yanked"], | ||
| 410 | + false | ||
| 411 | + ); | ||
| 412 | + | ||
| 413 | + let missing = env | ||
| 414 | + .http | ||
| 415 | + .delete( | ||
| 416 | + "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/9.9.9/yank", | ||
| 417 | + Some(&token), | ||
| 418 | + ) | ||
| 419 | + .await; | ||
| 420 | + assert_eq!(missing.status, 404); | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +#[tokio::test] | ||
| 424 | +async fn private_packages_need_a_token_and_the_owner_to_read() { | ||
| 425 | + let owner_token = generate_token(); | ||
| 426 | + let bob_token = generate_token(); | ||
| 427 | + let (seeded_owner, seeded_bob) = (owner_token.clone(), bob_token.clone()); | ||
| 428 | + let env = start(move |store| async move { | ||
| 429 | + let tahinli = user(&store, "tahinli").await; | ||
| 430 | + let bob = user(&store, "bob").await; | ||
| 431 | + grant(&store, &tahinli, &["packages"], &seeded_owner).await; | ||
| 432 | + grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 433 | + let package = store | ||
| 434 | + .ensure_package(&tahinli.id, KIND_CARGO, "Secret-Crate", "secret-crate") | ||
| 435 | + .await | ||
| 436 | + .expect("package"); | ||
| 437 | + store | ||
| 438 | + .set_package_private(&package.id, true) | ||
| 439 | + .await | ||
| 440 | + .expect("private"); | ||
| 441 | + store | ||
| 442 | + .publish_package_version(&NewPackageVersion { | ||
| 443 | + package_id: &package.id, | ||
| 444 | + version: "0.1.0", | ||
| 445 | + checksum: "00", | ||
| 446 | + size: 0, | ||
| 447 | + index_json: r#"{"name":"Secret-Crate","vers":"0.1.0","deps":[],"cksum":"00","features":{},"yanked":false,"links":null,"v":2}"#, | ||
| 448 | + description: Some("Hidden"), | ||
| 449 | + readme: None, | ||
| 450 | + publisher_id: &tahinli.id, | ||
| 451 | + }) | ||
| 452 | + .await | ||
| 453 | + .expect("version"); | ||
| 454 | + }) | ||
| 455 | + .await; | ||
| 456 | + let index = "/api/packages/tahinli/cargo/se/cr/secret-crate"; | ||
| 457 | + | ||
| 458 | + assert_eq!(env.http.get(index, None).await.status, 404, "anonymous"); | ||
| 459 | + assert_eq!( | ||
| 460 | + env.http.get(index, Some(&bob_token)).await.status, | ||
| 461 | + 404, | ||
| 462 | + "another user" | ||
| 463 | + ); | ||
| 464 | + assert_eq!( | ||
| 465 | + env.http.get(index, Some(&owner_token)).await.status, | ||
| 466 | + 200, | ||
| 467 | + "the owner" | ||
| 468 | + ); | ||
| 469 | + | ||
| 470 | + let config = env | ||
| 471 | + .http | ||
| 472 | + .get("/api/packages/tahinli/cargo/config.json", None) | ||
| 473 | + .await; | ||
| 474 | + assert_eq!( | ||
| 475 | + config.json()["auth-required"], | ||
| 476 | + true, | ||
| 477 | + "a private package needs auth" | ||
| 478 | + ); | ||
| 479 | + | ||
| 480 | + let profile = env.http.get("/tahinli?tab=packages", None).await; | ||
| 481 | + assert_eq!(profile.status, 200); | ||
| 482 | + assert!( | ||
| 483 | + !profile.text().contains("secret-crate"), | ||
| 484 | + "private packages stay off the public tab" | ||
| 485 | + ); | ||
| 486 | + let page = env.http.get("/tahinli/-/packages/secret-crate", None).await; | ||
| 487 | + assert_eq!( | ||
| 488 | + page.status, 404, | ||
| 489 | + "the private package page is hidden from anonymous readers" | ||
| 490 | + ); | ||
| 491 | +} | ||
| 492 | + | ||
| 493 | +#[tokio::test] | ||
| 494 | +async fn profile_tab_and_package_page_show_the_published_crate() { | ||
| 495 | + let token = generate_token(); | ||
| 496 | + let seeded = token.clone(); | ||
| 497 | + let env = start(move |store| async move { | ||
| 498 | + let tahinli = user(&store, "tahinli").await; | ||
| 499 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 500 | + }) | ||
| 501 | + .await; | ||
| 502 | + let body = publish_body( | ||
| 503 | + &metadata("demo-crate", "0.1.0"), | ||
| 504 | + &crate_file("demo-crate", "0.1.0", "# Demo\n\nHello."), | ||
| 505 | + ); | ||
| 506 | + let publish = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 507 | + assert_eq!(publish.status, 200, "{}", publish.text()); | ||
| 508 | + | ||
| 509 | + let tab = env.http.get("/tahinli?tab=packages", None).await; | ||
| 510 | + assert_eq!(tab.status, 200); | ||
| 511 | + assert!( | ||
| 512 | + tab.text().contains("demo-crate"), | ||
| 513 | + "the Packages tab lists the crate" | ||
| 514 | + ); | ||
| 515 | + | ||
| 516 | + let page = env.http.get("/tahinli/-/packages/demo-crate", None).await; | ||
| 517 | + assert_eq!(page.status, 200); | ||
| 518 | + let html = page.text(); | ||
| 519 | + assert!( | ||
| 520 | + html.contains("cargo add --registry tahinli demo-crate"), | ||
| 521 | + "install snippet" | ||
| 522 | + ); | ||
| 523 | + assert!( | ||
| 524 | + html.contains("sparse+http://127.0.0.1:"), | ||
| 525 | + "registry index in the config block" | ||
| 526 | + ); | ||
| 527 | + assert!(html.contains("data-copy=\"pkg-config\""), "copy button"); | ||
| 528 | + assert!(html.contains("Hello."), "README rendered"); | ||
| 529 | + assert!(html.contains("data-live="), "the page follows live changes"); | ||
| 530 | +} | ||
| 531 | + | ||
| 532 | +/// Drives the real `cargo` binary: publishes a crate with `cargo publish`, then resolves it | ||
| 533 | +/// from a consumer project with `cargo fetch`. Ignored by default because it runs cargo. | ||
| 534 | +#[tokio::test] | ||
| 535 | +#[ignore = "runs the real cargo binary; run with --ignored"] | ||
| 536 | +async fn real_cargo_publishes_and_fetches_from_the_registry() { | ||
| 537 | + let token = generate_token(); | ||
| 538 | + let seeded = token.clone(); | ||
| 539 | + let env = start(move |store| async move { | ||
| 540 | + let tahinli = user(&store, "tahinli").await; | ||
| 541 | + grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 542 | + }) | ||
| 543 | + .await; | ||
| 544 | + let index = format!("sparse+{}/api/packages/tahinli/cargo/", env.http.base); | ||
| 545 | + let work = tempfile::tempdir().expect("work dir"); | ||
| 546 | + let cargo_home = work.path().join("home"); | ||
| 547 | + let cargo_home = cargo_home.to_str().expect("utf8 path").to_owned(); | ||
| 548 | + let envs = [ | ||
| 549 | + ("CARGO_HOME", cargo_home.as_str()), | ||
| 550 | + ("CARGO_REGISTRIES_LOCAL_INDEX", index.as_str()), | ||
| 551 | + ("CARGO_REGISTRIES_LOCAL_TOKEN", token.as_str()), | ||
| 552 | + ]; | ||
| 553 | + | ||
| 554 | + let krate = work.path().join("real-demo"); | ||
| 555 | + std::fs::create_dir_all(krate.join("src")).expect("crate dir"); | ||
| 556 | + std::fs::write( | ||
| 557 | + krate.join("Cargo.toml"), | ||
| 558 | + "[package]\nname = \"real-demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\ | ||
| 559 | + description = \"Real cargo smoke test\"\nlicense = \"MIT\"\n", | ||
| 560 | + ) | ||
| 561 | + .expect("manifest"); | ||
| 562 | + std::fs::write(krate.join("src/lib.rs"), "pub fn hi() -> u8 { 7 }\n").expect("lib"); | ||
| 563 | + std::fs::write(krate.join("README.md"), "# real-demo\n").expect("readme"); | ||
| 564 | + run_cargo( | ||
| 565 | + &krate, | ||
| 566 | + &[ | ||
| 567 | + "publish", | ||
| 568 | + "--registry", | ||
| 569 | + "local", | ||
| 570 | + "--no-verify", | ||
| 571 | + "--allow-dirty", | ||
| 572 | + ], | ||
| 573 | + &envs, | ||
| 574 | + ); | ||
| 575 | + | ||
| 576 | + let consumer = work.path().join("consumer"); | ||
| 577 | + std::fs::create_dir_all(consumer.join("src")).expect("consumer dir"); | ||
| 578 | + std::fs::write( | ||
| 579 | + consumer.join("Cargo.toml"), | ||
| 580 | + "[package]\nname = \"consumer\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\ | ||
| 581 | + [dependencies]\nreal-demo = { version = \"0.1.0\", registry = \"local\" }\n", | ||
| 582 | + ) | ||
| 583 | + .expect("consumer manifest"); | ||
| 584 | + std::fs::write(consumer.join("src/main.rs"), "fn main() {}\n").expect("main"); | ||
| 585 | + let fetched = run_cargo(&consumer, &["fetch"], &envs); | ||
| 586 | + assert!(fetched.contains("real-demo v0.1.0"), "{fetched}"); | ||
| 587 | +} | ||
| 588 | + | ||
| 589 | +/// Runs cargo with `envs` in `dir`, panics with its output on failure, and returns the output. | ||
| 590 | +fn run_cargo(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> String { | ||
| 591 | + let out = Command::new("cargo") | ||
| 592 | + .args(args) | ||
| 593 | + .current_dir(dir) | ||
| 594 | + .envs(envs.iter().copied()) | ||
| 595 | + .output() | ||
| 596 | + .expect("run cargo"); | ||
| 597 | + let text = format!( | ||
| 598 | + "{}{}", | ||
| 599 | + String::from_utf8_lossy(&out.stdout), | ||
| 600 | + String::from_utf8_lossy(&out.stderr) | ||
| 601 | + ); | ||
| 602 | + assert!(out.status.success(), "cargo {args:?} failed:\n{text}"); | ||
| 603 | + text | ||
| 604 | +} | ||
docs/packages.mdadded+217 -0
| @@ -0,0 +1,217 @@ | |||
| 1 | +# Package registries | ||
| 2 | + | ||
| 3 | +Every user and organization has a package registry on this forge. It speaks the Cargo registry | ||
| 4 | +protocol (the sparse index), so `cargo` can publish to it, install from it and yank versions, and | ||
| 5 | +the OCI container protocol, so `docker` can push and pull images (see | ||
| 6 | +[Container images](#container-images)). Packages show on the owner's profile under the **Packages** tab, and on the | ||
| 7 | +package page with its README, versions and an install snippet. | ||
| 8 | + | ||
| 9 | +The registry of an owner is named after the owner. Below, `tahinli` is the owner and | ||
| 10 | +`git.tahinli.com` is the forge. | ||
| 11 | + | ||
| 12 | +## Use a registry in Cargo | ||
| 13 | + | ||
| 14 | +Add the registry to `~/.cargo/config.toml` (or to a project's `.cargo/config.toml`): | ||
| 15 | + | ||
| 16 | +```toml | ||
| 17 | +[registries.tahinli] | ||
| 18 | +index = "sparse+https://git.tahinli.com/api/packages/tahinli/cargo/" | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +Then add a crate from it: | ||
| 22 | + | ||
| 23 | +```sh | ||
| 24 | +cargo add --registry tahinli my-crate | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +Or refer to it in `Cargo.toml`: | ||
| 28 | + | ||
| 29 | +```toml | ||
| 30 | +[dependencies] | ||
| 31 | +my-crate = { version = "0.1", registry = "tahinli" } | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +Packages marked private need a token for every request to that registry, so Cargo asks for | ||
| 35 | +credentials when it reads the index (see below). | ||
| 36 | + | ||
| 37 | +## Tokens | ||
| 38 | + | ||
| 39 | +Create a personal access token under **Settings, Tokens** and tick **Packages**. A token with | ||
| 40 | +the `packages` scope can read private packages in the registries of the owners it may act for, | ||
| 41 | +publish, yank and unyank. A token without it is treated as anonymous for public reads and is | ||
| 42 | +refused for writes. | ||
| 43 | + | ||
| 44 | +Log in once on your machine: | ||
| 45 | + | ||
| 46 | +```sh | ||
| 47 | +cargo login --registry tahinli | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +Cargo asks for the token and stores it in `~/.cargo/credentials.toml`. Cargo sends the bare | ||
| 51 | +token in the `Authorization` header, which is what this forge expects. | ||
| 52 | + | ||
| 53 | +## Publish | ||
| 54 | + | ||
| 55 | +Set the registry in the crate's `Cargo.toml` so that `cargo publish` does not go to crates.io: | ||
| 56 | + | ||
| 57 | +```toml | ||
| 58 | +[package] | ||
| 59 | +name = "my-crate" | ||
| 60 | +version = "0.1.0" | ||
| 61 | +repository = "https://git.tahinli.com/tahinli/my-crate" # links the package to this repo | ||
| 62 | +publish = ["tahinli"] | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +Then publish: | ||
| 66 | + | ||
| 67 | +```sh | ||
| 68 | +cargo publish --registry tahinli | ||
| 69 | +``` | ||
| 70 | + | ||
| 71 | +Rules: | ||
| 72 | + | ||
| 73 | +- The crate name starts with a letter and holds letters, digits, `-` and `_`, at most 64 characters. | ||
| 74 | + Names are case-insensitive in the registry: `My_Crate` and `my_crate` are the same package. | ||
| 75 | +- The version must be valid semver, and it can be published only once. A second publish of the | ||
| 76 | + same version fails with `409 Conflict` and the message `crate version ... is already uploaded`. | ||
| 77 | +- A `.crate` file is at most 10 MiB. | ||
| 78 | +- Only the owner, the instance admin, or an owner of an organization may publish. Members of an | ||
| 79 | + organization without the owner role may read but not publish. | ||
| 80 | +- The package links to a repository when its `repository` URL points to a repo of the same owner | ||
| 81 | + on this forge. The package then shows on that repo's page. Links to other owners' repos are | ||
| 82 | + ignored. | ||
| 83 | +- The README is read from the `.crate` (`README*` at the top of the package directory), or from | ||
| 84 | + the `readme` field of the publish metadata when the file is missing. | ||
| 85 | + | ||
| 86 | +## Yank | ||
| 87 | + | ||
| 88 | +```sh | ||
| 89 | +cargo yank --registry tahinli --version 0.1.0 my-crate | ||
| 90 | +cargo yank --registry tahinli --version 0.1.0 --undo my-crate | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +A yanked version stays in the index and can still be downloaded, so existing `Cargo.lock` files | ||
| 94 | +keep working. Cargo stops choosing it for new builds. | ||
| 95 | + | ||
| 96 | +## Continuous integration | ||
| 97 | + | ||
| 98 | +Create a token with the `packages` scope and store it as a secret of the CI system, for | ||
| 99 | +example `FORGE_PACKAGES_TOKEN`. Then pass it to Cargo through an environment variable, which | ||
| 100 | +Cargo reads for a registry named `tahinli`: | ||
| 101 | + | ||
| 102 | +```yaml | ||
| 103 | +env: | ||
| 104 | + CARGO_REGISTRIES_TAHINLI_INDEX: sparse+https://git.tahinli.com/api/packages/tahinli/cargo/ | ||
| 105 | + CARGO_REGISTRIES_TAHINLI_TOKEN: ${{ secrets.FORGE_PACKAGES_TOKEN }} | ||
| 106 | +steps: | ||
| 107 | + - run: cargo publish --registry tahinli | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +Keep the token out of the repository. Use a dedicated token for CI, and revoke it when the job | ||
| 111 | +is no longer needed. | ||
| 112 | + | ||
| 113 | +## Private packages | ||
| 114 | + | ||
| 115 | +A package is public unless it is marked private. Public packages install without a token. | ||
| 116 | +When an owner has any private package, the registry's `config.json` sets `auth-required`, and | ||
| 117 | +Cargo then sends the token for every request to that registry, so a token is needed for public | ||
| 118 | +packages too. | ||
| 119 | + | ||
| 120 | +## Container images | ||
| 121 | + | ||
| 122 | +Every owner also has a container registry. It speaks the OCI Distribution protocol (v1.1) under | ||
| 123 | +`/v2/`, so `docker`, `podman` and other OCI clients push and pull images with no extra setup. | ||
| 124 | +Container images show in the owner's **Packages** tab with a `container` badge, next to the | ||
| 125 | +Cargo crates. | ||
| 126 | + | ||
| 127 | +### Log in, push and pull | ||
| 128 | + | ||
| 129 | +Log in with your username and a personal access token that has the **packages** scope: | ||
| 130 | + | ||
| 131 | +```sh | ||
| 132 | +docker login git.tahinli.com | ||
| 133 | +``` | ||
| 134 | + | ||
| 135 | +Tag an image with the owner and a name below the owner, then push it: | ||
| 136 | + | ||
| 137 | +```sh | ||
| 138 | +docker tag myapp:latest git.tahinli.com/tahinli/myapp:1.0.0 | ||
| 139 | +docker push git.tahinli.com/tahinli/myapp:1.0.0 | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +A name may have several parts, such as `tahinli/tools/cli`. Pull a public image with no login: | ||
| 143 | + | ||
| 144 | +```sh | ||
| 145 | +docker pull git.tahinli.com/tahinli/myapp:1.0.0 | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +Pulls of a public image need no token. A private image needs a token with the packages scope, and | ||
| 149 | +a pull of a private image without one is answered with `401` and a `WWW-Authenticate` challenge. | ||
| 150 | +Pushing needs write access to the owner: the owner, or a member of the organization with write | ||
| 151 | +access. The web page of an image shows the pull command, the tags with their digest, size and | ||
| 152 | +date, and the delete control for tags. | ||
| 153 | + | ||
| 154 | +### Token endpoint | ||
| 155 | + | ||
| 156 | +Clients that use the Bearer challenge get their token from `/v2/token`. The request uses HTTP | ||
| 157 | +Basic with the username and the token. The response is `{"token": ..., "access_token": ..., | ||
| 158 | +"expires_in": 300, ...}`, and the token is good for five minutes. Basic auth also works on each | ||
| 159 | +`/v2/` request directly, so simple clients need no token step. | ||
| 160 | + | ||
| 161 | +### Deleting | ||
| 162 | + | ||
| 163 | +Deleting a tag, with the owner's delete control or `DELETE /v2/{name}/manifests/{tag}`, removes | ||
| 164 | +the tag. A manifest that no tag names any more, and that no index names, is removed as well. | ||
| 165 | +Deleting by digest removes the manifest and all its tags. Blobs that no image uses are then | ||
| 166 | +swept from the store. The sweep runs on the request that deleted something, under a lock, so the | ||
| 167 | +registry has no background timer. A push that is still in flight when a sweep runs can lose its | ||
| 168 | +blobs; the client then gets `MANIFEST_BLOB_UNKNOWN` and pushes again. | ||
| 169 | + | ||
| 170 | +### Proxy in front of the forge | ||
| 171 | + | ||
| 172 | +Blobs are large, so the reverse proxy in front of the forge must accept request bodies of | ||
| 173 | +gigabytes and must not buffer request bodies. Route `/v2/` to the forge with a large body size | ||
| 174 | +limit and with request buffering turned off. A proxy that buffers streams every layer to disk | ||
| 175 | +before forwarding, and a small limit rejects the first layer. | ||
| 176 | + | ||
| 177 | +### Limits and storage | ||
| 178 | + | ||
| 179 | +Blobs are stored once per digest under the blob store (`oci/<hex>`), however many images use | ||
| 180 | +them. Upload sessions are temporary files under the data directory and are removed when the | ||
| 181 | +upload completes. A session left behind by a crash is removed by the next upload, once it is | ||
| 182 | +older than a day. Manifests and tags are in the database. A manifest is at most 4 MiB, and a | ||
| 183 | +blob at most 10 GiB. | ||
| 184 | + | ||
| 185 | +Not supported yet: the referrers API (`/v2/{name}/referrers/{digest}`). Blobs can be mounted from | ||
| 186 | +one image into another, so a shared base layer is uploaded once. | ||
| 187 | + | ||
| 188 | +## What is not supported yet | ||
| 189 | + | ||
| 190 | +- `cargo search` and the search endpoint. | ||
| 191 | +- Adding or removing owners with `cargo owner`. The owners list (`cargo owner --list`) works and | ||
| 192 | + shows the owner, or the owners of an organization. | ||
| 193 | +- Managing package visibility from the web page. | ||
| 194 | + | ||
| 195 | +## Storage | ||
| 196 | + | ||
| 197 | +Each `.crate` file is stored with the other release and artifact blobs (see `[storage]` in | ||
| 198 | +[backup.md](backup.md)), under `packages/<version id>`. The metadata, the index lines, the | ||
| 199 | +checksums and the READMEs are in the database, so the index is served without reading any file. | ||
| 200 | +Container images are rows of the same packages table with the kind `oci`. Their tags, manifests | ||
| 201 | +and blob links are in their own tables, and their blob bytes are stored under `oci/<hex>`. | ||
| 202 | + | ||
| 203 | +## Protocol endpoints | ||
| 204 | + | ||
| 205 | +All paths are under `/api/packages/{owner}/cargo/`: | ||
| 206 | + | ||
| 207 | +| Method | Path | Purpose | | ||
| 208 | +| --- | --- | --- | | ||
| 209 | +| GET | `config.json` | Registry config: `dl`, `api` and `auth-required`. | | ||
| 210 | +| GET | `1/{name}`, `2/{name}`, `{ab}/{cd}/{name}` | Sparse index file of a crate. | | ||
| 211 | +| GET | `download/{name}/{version}` | The `.crate` file. | | ||
| 212 | +| PUT | `api/v1/crates/new` | Publish. The body is the length-prefixed JSON metadata and `.crate`. | | ||
| 213 | +| DELETE | `api/v1/crates/{name}/{version}/yank` | Yank a version. | | ||
| 214 | +| PUT | `api/v1/crates/{name}/{version}/unyank` | Unyank a version. | | ||
| 215 | +| GET | `api/v1/crates/{name}/owners` | The people who may publish. | | ||
| 216 | + | ||
| 217 | +Errors use the body Cargo expects: `{"errors":[{"detail":"..."}]}`. | ||
style/main.scssmodified+34 -0
| @@ -6753,3 +6753,37 @@ button.ci-job-last { | |||
| 6753 | min-width: 5rem; | 6753 | min-width: 5rem; |
| 6754 | } | 6754 | } |
| 6755 | } | 6755 | } |
| 6756 | + | ||
| 6757 | +// The container package page: a header, the install commands, then the tag table. | ||
| 6758 | +.package-page { | ||
| 6759 | + max-width: 960px; | ||
| 6760 | + | ||
| 6761 | + .package-head h1 { | ||
| 6762 | + margin: 0 0 8px; | ||
| 6763 | + overflow-wrap: anywhere; | ||
| 6764 | + } | ||
| 6765 | + | ||
| 6766 | + .package-install h2, | ||
| 6767 | + .package-tags h2 { | ||
| 6768 | + margin: 28px 0 8px; | ||
| 6769 | + } | ||
| 6770 | + | ||
| 6771 | + .container-tags code { | ||
| 6772 | + overflow-wrap: anywhere; | ||
| 6773 | + } | ||
| 6774 | + | ||
| 6775 | + .container-tags td, | ||
| 6776 | + .container-tags th { | ||
| 6777 | + vertical-align: middle; | ||
| 6778 | + } | ||
| 6779 | +} | ||
| 6780 | + | ||
| 6781 | +// On a phone the digest and date columns give way, so the tag and its delete control stay in view. | ||
| 6782 | +@media (max-width: 600px) { | ||
| 6783 | + .package-page .container-tags th:nth-child(2), | ||
| 6784 | + .package-page .container-tags td:nth-child(2), | ||
| 6785 | + .package-page .container-tags th:nth-child(4), | ||
| 6786 | + .package-page .container-tags td:nth-child(4) { | ||
| 6787 | + display: none; | ||
| 6788 | + } | ||
| 6789 | +} | ||