🔥 remove: package registries (Cargo sparse index and OCI container registry, package pages, Packages tab, packages token scope)
Browse files at this commitb32181a0647a664fb7d33d7dd8e282ba6d9d6a61Parent: a953f4758 changed files +34 -5877
- Cargo.lock +0 -8
- Cargo.toml +1 -2
- crates/forge-core/Cargo.toml +0 -3
- crates/forge-core/src/cargo.rs +0 -287
- crates/forge-core/src/lib.rs +0 -3
- crates/forge-core/src/names.rs +0 -1
- crates/forge-core/src/oci.rs +0 -258
- crates/forge-core/src/packages.rs +0 -71
- crates/forge-core/src/store/mod.rs +0 -2
- crates/forge-core/src/store/oci.rs +0 -307
- crates/forge-core/src/store/packages.rs +0 -310
- crates/forge-core/src/store/user_delete.rs +0 -1
- crates/forge-core/tests/integration/store_basic.rs +0 -35
- crates/forge-e2e/Cargo.toml +0 -5
- crates/forge-e2e/tests/e2e/main.rs +0 -2
- crates/forge-e2e/tests/e2e/oci_e2e.rs +0 -882
- crates/forge-e2e/tests/e2e/packages_e2e.rs +0 -567
- crates/forge-web-account/src/pages/audit_log.rs +1 -1
- crates/forge-web-account/src/pages/org_ctx.rs +2 -8
- crates/forge-web-account/src/pages/org_members.rs +4 -5
- crates/forge-web-account/src/pages/org_settings.rs +4 -5
- crates/forge-web-account/src/pages/org_teams.rs +6 -9
- crates/forge-web-account/src/pages/profile.rs +0 -41
- crates/forge-web-account/src/pages/settings_security.rs +1 -2
- crates/forge-web-account/src/pages/settings_tokens.rs +2 -13
- crates/forge-web-app/src/api/mod.rs +0 -1
- crates/forge-web-app/src/api/packages.rs +0 -318
- crates/forge-web-app/src/lib.rs +0 -3
- crates/forge-web-app/src/oci/auth.rs +0 -184
- crates/forge-web-app/src/oci/blobs.rs +0 -412
- crates/forge-web-app/src/oci/gc.rs +0 -53
- crates/forge-web-app/src/oci/manifests.rs +0 -346
- crates/forge-web-app/src/oci/mod.rs +0 -445
- crates/forge-web-app/src/package_ops.rs +0 -328
- crates/forge-web-app/src/packages_live.rs +0 -68
- crates/forge-web-app/src/prune.rs +0 -3
- crates/forge-web-app/src/state.rs +0 -1
- crates/forge-web-app/src/test_support/mod.rs +0 -1
- crates/forge-web-app/src/views/mod.rs +0 -2
- crates/forge-web-base/src/i18n/audit_names.rs +0 -4
- crates/forge-web-base/src/i18n/mod.rs +0 -1
- crates/forge-web-base/src/i18n/packages.rs +0 -33
- crates/forge-web-base/src/i18n/releases_ci.rs +1 -0
- crates/forge-web-pages/src/lib.rs +2 -2
- crates/forge-web-pages/src/pages/code_live.rs +4 -14
- crates/forge-web-pages/src/pages/mod.rs +0 -2
- crates/forge-web-pages/src/pages/packages.rs +0 -431
- crates/forge-web-pages/src/pages/packages_oci.rs +0 -146
- crates/forge-web-pages/src/pages/repo.rs +1 -4
- crates/forge-web-pages/src/pages/repo_side.rs +0 -5
- crates/forge-web-pages/src/pages/tree.rs +1 -1
- crates/forge-web-repo/src/pages/blob.rs +1 -1
- crates/forge-web/src/boot.rs +0 -1
- crates/forge-web/src/routes.snap +0 -19
- docs/architecture.md +1 -1
- docs/packages.md +0 -217
- style/_repo.scss +1 -1
- style/main.scss +1 -1
Cargo.lockmodified+0 -8
| @@ -1988,7 +1988,6 @@ dependencies = [ | |||
| 1988 | "argon2 0.6.0", | 1988 | "argon2 0.6.0", |
| 1989 | "base64 0.23.1", | 1989 | "base64 0.23.1", |
| 1990 | "chacha20poly1305", | 1990 | "chacha20poly1305", |
| 1991 | - "flate2", | ||
| 1992 | "forge-ci", | 1991 | "forge-ci", |
| 1993 | "hex", | 1992 | "hex", |
| 1994 | "hmac 0.13.0", | 1993 | "hmac 0.13.0", |
| @@ -1996,13 +1995,11 @@ dependencies = [ | |||
| 1996 | "ipnet", | 1995 | "ipnet", |
| 1997 | "jiff 1.0.3", | 1996 | "jiff 1.0.3", |
| 1998 | "rand 0.10.4", | 1997 | "rand 0.10.4", |
| 1999 | - "semver", | ||
| 2000 | "serde", | 1998 | "serde", |
| 2001 | "serde_json", | 1999 | "serde_json", |
| 2002 | "sha1 0.11.0", | 2000 | "sha1 0.11.0", |
| 2003 | "sha2 0.11.1", | 2001 | "sha2 0.11.1", |
| 2004 | "subtle", | 2002 | "subtle", |
| 2005 | - "tar", | ||
| 2006 | "tempfile", | 2003 | "tempfile", |
| 2007 | "thiserror 2.0.21", | 2004 | "thiserror 2.0.21", |
| 2008 | "time", | 2005 | "time", |
| @@ -2018,18 +2015,13 @@ dependencies = [ | |||
| 2018 | name = "forge-e2e" | 2015 | name = "forge-e2e" |
| 2019 | version = "0.1.0" | 2016 | version = "0.1.0" |
| 2020 | dependencies = [ | 2017 | dependencies = [ |
| 2021 | - "base64 0.23.1", | ||
| 2022 | - "flate2", | ||
| 2023 | "forge-ci", | 2018 | "forge-ci", |
| 2024 | "forge-core", | 2019 | "forge-core", |
| 2025 | "forge-git", | 2020 | "forge-git", |
| 2026 | "forge-runner", | 2021 | "forge-runner", |
| 2027 | - "hex", | ||
| 2028 | "reqwest", | 2022 | "reqwest", |
| 2029 | "scraper", | 2023 | "scraper", |
| 2030 | "serde_json", | 2024 | "serde_json", |
| 2031 | - "sha2 0.11.1", | ||
| 2032 | - "tar", | ||
| 2033 | "tempfile", | 2025 | "tempfile", |
| 2034 | "tokio", | 2026 | "tokio", |
| 2035 | "tokio-util", | 2027 | "tokio-util", |
Cargo.tomlmodified+1 -2
| @@ -123,8 +123,7 @@ reqwest = { version = "0.13.5", default-features = false, features = ["rustls", | |||
| 123 | scraper = "0.29.0" | 123 | scraper = "0.29.0" |
| 124 | similar = "3.2.1" | 124 | similar = "3.2.1" |
| 125 | 125 | ||
| 126 | -# semver (forge-core) and zip (CI archives) | 126 | +# zip (CI archives) |
| 127 | -semver = "1.0.28" | ||
| 128 | zip = { version = "9.8.2", default-features = false, features = ["deflate"] } | 127 | zip = { version = "9.8.2", default-features = false, features = ["deflate"] } |
| 129 | 128 | ||
| 130 | [profile.dev] | 129 | [profile.dev] |
crates/forge-core/Cargo.tomlmodified+0 -3
| @@ -30,9 +30,6 @@ turso.workspace = true | |||
| 30 | tokio = { workspace = true, features = ["sync"] } | 30 | tokio = { workspace = true, features = ["sync"] } |
| 31 | tracing.workspace = true | 31 | tracing.workspace = true |
| 32 | serde_json.workspace = true | 32 | serde_json.workspace = true |
| 33 | -semver = { workspace = true } | ||
| 34 | -flate2.workspace = true | ||
| 35 | -tar.workspace = true | ||
| 36 | 33 | ||
| 37 | [dev-dependencies] | 34 | [dev-dependencies] |
| 38 | tempfile.workspace = true | 35 | tempfile.workspace = true |
crates/forge-core/src/cargo.rsdeleted+0 -287
| @@ -1,287 +0,0 @@ | |||
| 1 | -use std::io::Read; | ||
| 2 | - | ||
| 3 | -use flate2::read::GzDecoder; | ||
| 4 | -use serde_json::{Map, Value, json}; | ||
| 5 | - | ||
| 6 | -use crate::error::{Error, Result}; | ||
| 7 | - | ||
| 8 | -pub const MAX_NAME_CHARS: usize = 64; | ||
| 9 | -pub const MAX_README_BYTES: u64 = 256 * 1024; | ||
| 10 | - | ||
| 11 | -pub fn crate_name_key(name: &str) -> Result<String> { | ||
| 12 | - let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()); | ||
| 13 | - let chars_ok = name | ||
| 14 | - .chars() | ||
| 15 | - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); | ||
| 16 | - if !starts_alpha || !chars_ok || name.len() > MAX_NAME_CHARS { | ||
| 17 | - return Err(Error::InvalidName(format!( | ||
| 18 | - "`{name}` is not a valid crate name: start with a letter, then letters, digits, `-` or `_`, at most {MAX_NAME_CHARS} characters" | ||
| 19 | - ))); | ||
| 20 | - } | ||
| 21 | - Ok(name.to_ascii_lowercase()) | ||
| 22 | -} | ||
| 23 | - | ||
| 24 | -pub fn index_path(key: &str) -> String { | ||
| 25 | - match key.len() { | ||
| 26 | - 1 => format!("1/{key}"), | ||
| 27 | - 2 => format!("2/{key}"), | ||
| 28 | - 3 => format!("3/{}/{key}", &key[..1]), | ||
| 29 | - _ => format!("{}/{}/{key}", &key[..2], &key[2..4]), | ||
| 30 | - } | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -pub fn parse_version(version: &str) -> Result<semver::Version> { | ||
| 34 | - semver::Version::parse(version) | ||
| 35 | - .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}"))) | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -pub struct Publish<'a> { | ||
| 39 | - pub metadata: Value, | ||
| 40 | - pub crate_file: &'a [u8], | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -pub fn parse_publish(body: &[u8]) -> Result<Publish<'_>> { | ||
| 44 | - let (json_len, rest) = take_len(body)?; | ||
| 45 | - if json_len > rest.len() { | ||
| 46 | - return Err(Error::Invalid( | ||
| 47 | - "publish body is shorter than its metadata length".into(), | ||
| 48 | - )); | ||
| 49 | - } | ||
| 50 | - let (json_bytes, rest) = rest.split_at(json_len); | ||
| 51 | - let metadata: Value = serde_json::from_slice(json_bytes) | ||
| 52 | - .map_err(|e| Error::Invalid(format!("publish metadata is not JSON: {e}")))?; | ||
| 53 | - if !metadata.is_object() { | ||
| 54 | - return Err(Error::Invalid( | ||
| 55 | - "publish metadata must be a JSON object".into(), | ||
| 56 | - )); | ||
| 57 | - } | ||
| 58 | - let (crate_len, rest) = take_len(rest)?; | ||
| 59 | - if crate_len != rest.len() { | ||
| 60 | - return Err(Error::Invalid( | ||
| 61 | - "crate length does not match the body".into(), | ||
| 62 | - )); | ||
| 63 | - } | ||
| 64 | - Ok(Publish { | ||
| 65 | - metadata, | ||
| 66 | - crate_file: rest, | ||
| 67 | - }) | ||
| 68 | -} | ||
| 69 | - | ||
| 70 | -fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> { | ||
| 71 | - let Some((head, rest)) = bytes.split_first_chunk::<4>().map(|(h, r)| (*h, r)) else { | ||
| 72 | - return Err(Error::Invalid("publish body is truncated".into())); | ||
| 73 | - }; | ||
| 74 | - let len = usize::try_from(u32::from_le_bytes(head)) | ||
| 75 | - .map_err(|_| Error::Invalid("length does not fit".into()))?; | ||
| 76 | - Ok((len, rest)) | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> { | ||
| 80 | - meta.get(key).and_then(Value::as_str) | ||
| 81 | -} | ||
| 82 | - | ||
| 83 | -pub fn index_deps(meta: &Value) -> Vec<Value> { | ||
| 84 | - let deps = meta.get("deps").and_then(Value::as_array); | ||
| 85 | - deps.map_or_else(Vec::new, |list| { | ||
| 86 | - list.iter() | ||
| 87 | - .map(|dep| { | ||
| 88 | - let crate_name = meta_str(dep, "name").unwrap_or_default(); | ||
| 89 | - let renamed = meta_str(dep, "explicit_name_in_toml"); | ||
| 90 | - json!({ | ||
| 91 | - "name": renamed.unwrap_or(crate_name), | ||
| 92 | - "req": dep.get("version_req").cloned().unwrap_or(Value::Null), | ||
| 93 | - "features": dep.get("features").cloned().unwrap_or_else(|| json!([])), | ||
| 94 | - "optional": dep.get("optional").and_then(Value::as_bool).unwrap_or(false), | ||
| 95 | - "default_features": dep.get("default_features").and_then(Value::as_bool).unwrap_or(true), | ||
| 96 | - "target": dep.get("target").cloned().unwrap_or(Value::Null), | ||
| 97 | - "kind": dep.get("kind").and_then(Value::as_str).unwrap_or("normal"), | ||
| 98 | - "registry": dep.get("registry").cloned().unwrap_or(Value::Null), | ||
| 99 | - "package": renamed.map(|_| crate_name), | ||
| 100 | - }) | ||
| 101 | - }) | ||
| 102 | - .collect() | ||
| 103 | - }) | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> { | ||
| 107 | - let name = | ||
| 108 | - meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?; | ||
| 109 | - let vers = | ||
| 110 | - meta_str(meta, "vers").ok_or_else(|| Error::Invalid("metadata has no vers".into()))?; | ||
| 111 | - let mut features = Map::new(); | ||
| 112 | - let mut features2 = Map::new(); | ||
| 113 | - if let Some(declared) = meta.get("features").and_then(Value::as_object) { | ||
| 114 | - for (feature, members) in declared { | ||
| 115 | - let modern = members.as_array().is_some_and(|list| { | ||
| 116 | - list.iter() | ||
| 117 | - .filter_map(Value::as_str) | ||
| 118 | - .any(|m| m.starts_with("dep:") || m.contains('?')) | ||
| 119 | - }); | ||
| 120 | - if modern { | ||
| 121 | - features2.insert(feature.clone(), members.clone()); | ||
| 122 | - } else { | ||
| 123 | - features.insert(feature.clone(), members.clone()); | ||
| 124 | - } | ||
| 125 | - } | ||
| 126 | - } | ||
| 127 | - let mut line = json!({ | ||
| 128 | - "name": name, | ||
| 129 | - "vers": vers, | ||
| 130 | - "deps": index_deps(meta), | ||
| 131 | - "cksum": checksum, | ||
| 132 | - "features": features, | ||
| 133 | - "yanked": false, | ||
| 134 | - "links": meta.get("links").cloned().unwrap_or(Value::Null), | ||
| 135 | - "v": 2, | ||
| 136 | - }); | ||
| 137 | - if !features2.is_empty() { | ||
| 138 | - line["features2"] = Value::Object(features2); | ||
| 139 | - } | ||
| 140 | - if let Some(rust_version) = meta_str(meta, "rust_version") { | ||
| 141 | - line["rust_version"] = json!(rust_version); | ||
| 142 | - } | ||
| 143 | - Ok(line) | ||
| 144 | -} | ||
| 145 | - | ||
| 146 | -pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> { | ||
| 147 | - let base = base_url.trim_end_matches('/'); | ||
| 148 | - let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?; | ||
| 149 | - let rest = rest.trim_end_matches('/'); | ||
| 150 | - let rest = rest.strip_suffix(".git").unwrap_or(rest); | ||
| 151 | - let mut parts = rest.split('/'); | ||
| 152 | - let owner = parts.next().filter(|s| !s.is_empty())?; | ||
| 153 | - let repo = parts.next().filter(|s| !s.is_empty())?; | ||
| 154 | - if parts.next().is_some() { | ||
| 155 | - return None; | ||
| 156 | - } | ||
| 157 | - Some((owner.to_owned(), repo.to_owned())) | ||
| 158 | -} | ||
| 159 | - | ||
| 160 | -pub fn crate_readme(crate_file: &[u8]) -> Option<String> { | ||
| 161 | - const MAX_INFLATED_SCAN_BYTES: u64 = 256 * 1024 * 1024; | ||
| 162 | - let inflated = GzDecoder::new(crate_file).take(MAX_INFLATED_SCAN_BYTES); | ||
| 163 | - let mut archive = tar::Archive::new(inflated); | ||
| 164 | - let entries = archive.entries().ok()?; | ||
| 165 | - for entry in entries { | ||
| 166 | - let entry = entry.ok()?; | ||
| 167 | - let path = entry.path().ok()?.into_owned(); | ||
| 168 | - let mut parts = path.components(); | ||
| 169 | - let (Some(_), Some(file)) = (parts.next(), parts.next()) else { | ||
| 170 | - continue; | ||
| 171 | - }; | ||
| 172 | - let is_top = parts.next().is_none(); | ||
| 173 | - let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase(); | ||
| 174 | - if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() { | ||
| 175 | - let mut bytes = Vec::new(); | ||
| 176 | - entry.take(MAX_README_BYTES).read_to_end(&mut bytes).ok()?; | ||
| 177 | - return Some(String::from_utf8_lossy(&bytes).into_owned()); | ||
| 178 | - } | ||
| 179 | - } | ||
| 180 | - None | ||
| 181 | -} | ||
| 182 | - | ||
| 183 | -#[cfg(test)] | ||
| 184 | -mod tests { | ||
| 185 | - use super::*; | ||
| 186 | - | ||
| 187 | - #[test] | ||
| 188 | - fn names_follow_crate_rules_and_lowercase() { | ||
| 189 | - assert_eq!(crate_name_key("Serde_json").unwrap(), "serde_json"); | ||
| 190 | - assert!(crate_name_key("").is_err()); | ||
| 191 | - assert!(crate_name_key("1abc").is_err()); | ||
| 192 | - assert!(crate_name_key("a b").is_err()); | ||
| 193 | - assert!(crate_name_key("a.b").is_err()); | ||
| 194 | - assert!(crate_name_key(&"a".repeat(65)).is_err()); | ||
| 195 | - assert!(crate_name_key(&"a".repeat(64)).is_ok()); | ||
| 196 | - } | ||
| 197 | - | ||
| 198 | - #[test] | ||
| 199 | - fn index_paths_match_the_sparse_layout() { | ||
| 200 | - assert_eq!(index_path("a"), "1/a"); | ||
| 201 | - assert_eq!(index_path("ab"), "2/ab"); | ||
| 202 | - assert_eq!(index_path("abc"), "3/a/abc"); | ||
| 203 | - assert_eq!(index_path("serde"), "se/rd/serde"); | ||
| 204 | - } | ||
| 205 | - | ||
| 206 | - #[test] | ||
| 207 | - fn publish_body_round_trips_and_rejects_bad_lengths() { | ||
| 208 | - let meta = br#"{"name":"demo","vers":"0.1.0"}"#; | ||
| 209 | - let krate = b"gz-bytes"; | ||
| 210 | - let mut body = Vec::new(); | ||
| 211 | - body.extend_from_slice(&(meta.len() as u32).to_le_bytes()); | ||
| 212 | - body.extend_from_slice(meta); | ||
| 213 | - body.extend_from_slice(&(krate.len() as u32).to_le_bytes()); | ||
| 214 | - body.extend_from_slice(krate); | ||
| 215 | - let parsed = parse_publish(&body).unwrap(); | ||
| 216 | - assert_eq!(parsed.metadata["name"], "demo"); | ||
| 217 | - assert_eq!(parsed.crate_file, krate); | ||
| 218 | - | ||
| 219 | - let mut short = body.clone(); | ||
| 220 | - short.pop(); | ||
| 221 | - assert!(parse_publish(&short).is_err()); | ||
| 222 | - assert!(parse_publish(&body[..3]).is_err()); | ||
| 223 | - } | ||
| 224 | - | ||
| 225 | - #[test] | ||
| 226 | - fn index_line_renames_deps_and_splits_features() { | ||
| 227 | - let meta = json!({ | ||
| 228 | - "name": "demo", "vers": "0.2.0", "links": null, "rust_version": "1.80", | ||
| 229 | - "deps": [ | ||
| 230 | - {"name": "serde", "version_req": "^1", "features": ["derive"], "optional": false, | ||
| 231 | - "default_features": true, "target": null, "kind": "normal", "registry": null, | ||
| 232 | - "explicit_name_in_toml": null}, | ||
| 233 | - {"name": "tokio", "version_req": "1", "features": [], "optional": true, | ||
| 234 | - "default_features": false, "target": null, "kind": "dev", "registry": null, | ||
| 235 | - "explicit_name_in_toml": "rt"} | ||
| 236 | - ], | ||
| 237 | - "features": {"default": ["serde"], "net": ["dep:tokio"]} | ||
| 238 | - }); | ||
| 239 | - let line = index_line(&meta, "abc").unwrap(); | ||
| 240 | - assert_eq!(line["cksum"], "abc"); | ||
| 241 | - assert_eq!(line["yanked"], false); | ||
| 242 | - assert_eq!(line["v"], 2); | ||
| 243 | - assert_eq!(line["rust_version"], "1.80"); | ||
| 244 | - assert_eq!(line["deps"][1]["name"], "rt"); | ||
| 245 | - assert_eq!(line["deps"][1]["package"], "tokio"); | ||
| 246 | - assert_eq!(line["deps"][0]["package"], Value::Null); | ||
| 247 | - assert_eq!(line["features"]["default"], json!(["serde"])); | ||
| 248 | - assert_eq!(line["features2"]["net"], json!(["dep:tokio"])); | ||
| 249 | - } | ||
| 250 | - | ||
| 251 | - #[test] | ||
| 252 | - fn repository_links_only_forge_repos() { | ||
| 253 | - let base = "https://git.tahinli.com/"; | ||
| 254 | - assert_eq!( | ||
| 255 | - repo_link("https://git.tahinli.com/tahinli/forge.git", base), | ||
| 256 | - Some(("tahinli".into(), "forge".into())) | ||
| 257 | - ); | ||
| 258 | - assert_eq!(repo_link("https://github.com/tahinli/forge", base), None); | ||
| 259 | - assert_eq!(repo_link("https://git.tahinli.com/tahinli", base), None); | ||
| 260 | - assert_eq!(repo_link("https://git.tahinli.com/a/b/c", base), None); | ||
| 261 | - } | ||
| 262 | - | ||
| 263 | - #[test] | ||
| 264 | - fn readme_is_read_from_the_package_directory() { | ||
| 265 | - let mut tar_bytes = Vec::new(); | ||
| 266 | - { | ||
| 267 | - let mut builder = tar::Builder::new(&mut tar_bytes); | ||
| 268 | - let body = b"# Demo\n\nHello."; | ||
| 269 | - let mut header = tar::Header::new_gnu(); | ||
| 270 | - header.set_size(body.len() as u64); | ||
| 271 | - header.set_mode(0o644); | ||
| 272 | - header.set_cksum(); | ||
| 273 | - builder | ||
| 274 | - .append_data(&mut header, "demo-0.1.0/README.md", &body[..]) | ||
| 275 | - .unwrap(); | ||
| 276 | - builder.finish().unwrap(); | ||
| 277 | - } | ||
| 278 | - let mut gz = Vec::new(); | ||
| 279 | - { | ||
| 280 | - let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast()); | ||
| 281 | - std::io::Write::write_all(&mut enc, &tar_bytes).unwrap(); | ||
| 282 | - enc.finish().unwrap(); | ||
| 283 | - } | ||
| 284 | - assert_eq!(crate_readme(&gz).as_deref(), Some("# Demo\n\nHello.")); | ||
| 285 | - assert_eq!(crate_readme(b"not gzip"), None); | ||
| 286 | - } | ||
| 287 | -} | ||
crates/forge-core/src/lib.rsmodified+0 -3
| @@ -28,7 +28,6 @@ pub mod alerts; | |||
| 28 | pub mod audit; | 28 | pub mod audit; |
| 29 | pub mod authz; | 29 | pub mod authz; |
| 30 | pub mod avatar; | 30 | pub mod avatar; |
| 31 | -pub mod cargo; | ||
| 32 | pub mod ci; | 31 | pub mod ci; |
| 33 | pub mod config; | 32 | pub mod config; |
| 34 | pub mod discussions; | 33 | pub mod discussions; |
| @@ -42,8 +41,6 @@ pub mod mirrors; | |||
| 42 | pub mod model; | 41 | pub mod model; |
| 43 | pub mod names; | 42 | pub mod names; |
| 44 | pub mod notifications; | 43 | pub mod notifications; |
| 45 | -pub mod oci; | ||
| 46 | -pub mod packages; | ||
| 47 | pub mod password; | 44 | pub mod password; |
| 48 | pub mod protection; | 45 | pub mod protection; |
| 49 | pub mod pulls; | 46 | pub mod pulls; |
crates/forge-core/src/names.rsmodified+0 -1
| @@ -4,7 +4,6 @@ use crate::error::{Error, Result}; | |||
| 4 | 4 | ||
| 5 | pub const RESERVED: &[&str] = &[ | 5 | pub const RESERVED: &[&str] = &[ |
| 6 | "api", | 6 | "api", |
| 7 | - "v2", | ||
| 8 | "admin", | 7 | "admin", |
| 9 | "auth", | 8 | "auth", |
| 10 | "assets", | 9 | "assets", |
crates/forge-core/src/oci.rsdeleted+0 -258
| @@ -1,258 +0,0 @@ | |||
| 1 | -use crate::signed_token; | ||
| 2 | -use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; | ||
| 3 | -use serde_json::Value; | ||
| 4 | - | ||
| 5 | -pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [ | ||
| 6 | - "application/vnd.oci.image.manifest.v1+json", | ||
| 7 | - "application/vnd.oci.image.index.v1+json", | ||
| 8 | - "application/vnd.docker.distribution.manifest.v2+json", | ||
| 9 | - "application/vnd.docker.distribution.manifest.list.v2+json", | ||
| 10 | -]; | ||
| 11 | - | ||
| 12 | -const MAX_REPO_NAME: usize = 255; | ||
| 13 | -const MAX_TAG: usize = 128; | ||
| 14 | - | ||
| 15 | -pub fn is_manifest_media_type(media_type: &str) -> bool { | ||
| 16 | - MANIFEST_MEDIA_TYPES.contains(&media_type) | ||
| 17 | -} | ||
| 18 | - | ||
| 19 | -fn valid_segment(segment: &str) -> bool { | ||
| 20 | - let bytes = segment.as_bytes(); | ||
| 21 | - if bytes.is_empty() { | ||
| 22 | - return false; | ||
| 23 | - } | ||
| 24 | - let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); | ||
| 25 | - if !alnum(bytes[0]) || !alnum(bytes[bytes.len() - 1]) { | ||
| 26 | - return false; | ||
| 27 | - } | ||
| 28 | - let mut prev_sep = false; | ||
| 29 | - for &b in bytes { | ||
| 30 | - if alnum(b) { | ||
| 31 | - prev_sep = false; | ||
| 32 | - } else if matches!(b, b'.' | b'_' | b'-') { | ||
| 33 | - if prev_sep && b != b'-' { | ||
| 34 | - return false; | ||
| 35 | - } | ||
| 36 | - prev_sep = true; | ||
| 37 | - } else { | ||
| 38 | - return false; | ||
| 39 | - } | ||
| 40 | - } | ||
| 41 | - true | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -pub fn split_repo_name(name: &str) -> Option<(&str, &str)> { | ||
| 45 | - if name.len() > MAX_REPO_NAME { | ||
| 46 | - return None; | ||
| 47 | - } | ||
| 48 | - let (owner, image) = name.split_once('/')?; | ||
| 49 | - if !image.split('/').all(valid_segment) || !valid_segment(owner) { | ||
| 50 | - return None; | ||
| 51 | - } | ||
| 52 | - Some((owner, image)) | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -pub fn parse_digest(digest: &str) -> Option<&str> { | ||
| 56 | - let hex = digest.strip_prefix("sha256:")?; | ||
| 57 | - let valid = hex.len() == 64 | ||
| 58 | - && hex | ||
| 59 | - .bytes() | ||
| 60 | - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); | ||
| 61 | - valid.then_some(hex) | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -pub fn valid_tag(tag: &str) -> bool { | ||
| 65 | - let bytes = tag.as_bytes(); | ||
| 66 | - !bytes.is_empty() | ||
| 67 | - && bytes.len() <= MAX_TAG | ||
| 68 | - && !matches!(bytes[0], b'.' | b'-') | ||
| 69 | - && bytes | ||
| 70 | - .iter() | ||
| 71 | - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) | ||
| 72 | -} | ||
| 73 | - | ||
| 74 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 75 | -pub struct ManifestRefs { | ||
| 76 | - pub digests: Vec<String>, | ||
| 77 | - pub total_size: u64, | ||
| 78 | - pub is_index: bool, | ||
| 79 | -} | ||
| 80 | - | ||
| 81 | -pub fn scan_manifest(bytes: &[u8]) -> Result<ManifestRefs, String> { | ||
| 82 | - let value: Value = | ||
| 83 | - serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?; | ||
| 84 | - if !value.is_object() { | ||
| 85 | - return Err("manifest is not a JSON object".into()); | ||
| 86 | - } | ||
| 87 | - if let Some(children) = value.get("manifests").and_then(Value::as_array) { | ||
| 88 | - let digests = children | ||
| 89 | - .iter() | ||
| 90 | - .map(descriptor_digest) | ||
| 91 | - .collect::<Result<Vec<_>, _>>()?; | ||
| 92 | - return Ok(ManifestRefs { | ||
| 93 | - digests, | ||
| 94 | - total_size: bytes.len() as u64, | ||
| 95 | - is_index: true, | ||
| 96 | - }); | ||
| 97 | - } | ||
| 98 | - let config = value | ||
| 99 | - .get("config") | ||
| 100 | - .ok_or_else(|| "manifest has no config".to_owned())?; | ||
| 101 | - let mut digests = vec![descriptor_digest(config)?]; | ||
| 102 | - let mut total = descriptor_size(config); | ||
| 103 | - if let Some(layers) = value.get("layers") { | ||
| 104 | - let layers = layers | ||
| 105 | - .as_array() | ||
| 106 | - .ok_or_else(|| "manifest layers is not an array".to_owned())?; | ||
| 107 | - for layer in layers { | ||
| 108 | - digests.push(descriptor_digest(layer)?); | ||
| 109 | - total = total.saturating_add(descriptor_size(layer)); | ||
| 110 | - } | ||
| 111 | - } | ||
| 112 | - Ok(ManifestRefs { | ||
| 113 | - digests, | ||
| 114 | - total_size: total, | ||
| 115 | - is_index: false, | ||
| 116 | - }) | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | -fn descriptor_digest(descriptor: &Value) -> Result<String, String> { | ||
| 120 | - let digest = descriptor | ||
| 121 | - .get("digest") | ||
| 122 | - .and_then(Value::as_str) | ||
| 123 | - .ok_or_else(|| "a descriptor has no digest".to_owned())?; | ||
| 124 | - parse_digest(digest) | ||
| 125 | - .map(|hex| format!("sha256:{hex}")) | ||
| 126 | - .ok_or_else(|| format!("unsupported digest {digest}")) | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -fn descriptor_size(descriptor: &Value) -> u64 { | ||
| 130 | - descriptor.get("size").and_then(Value::as_u64).unwrap_or(0) | ||
| 131 | -} | ||
| 132 | - | ||
| 133 | -fn framing(payload: &[u8]) -> [&[u8]; 2] { | ||
| 134 | - [b"oci\0", payload] | ||
| 135 | -} | ||
| 136 | - | ||
| 137 | -pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String { | ||
| 138 | - let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or("")); | ||
| 139 | - let tag = signed_token::mac(key, &framing(payload.as_bytes())); | ||
| 140 | - format!( | ||
| 141 | - "{}.{}", | ||
| 142 | - BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()), | ||
| 143 | - BASE64_URL_SAFE_NO_PAD.encode(tag) | ||
| 144 | - ) | ||
| 145 | -} | ||
| 146 | - | ||
| 147 | -pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option<String>> { | ||
| 148 | - let (payload_b64, mac_b64) = token.split_once('.')?; | ||
| 149 | - let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?; | ||
| 150 | - let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?; | ||
| 151 | - if !signed_token::verify(key, &framing(&payload), &tag) { | ||
| 152 | - return None; | ||
| 153 | - } | ||
| 154 | - let payload = std::str::from_utf8(&payload).ok()?; | ||
| 155 | - let mut parts = payload.split('|'); | ||
| 156 | - if parts.next()? != "oci1" { | ||
| 157 | - return None; | ||
| 158 | - } | ||
| 159 | - let subject = parts.next()?; | ||
| 160 | - let expires = signed_token::parse_expiry(parts.next()?)?; | ||
| 161 | - if parts.next().is_some() || now_unix >= expires { | ||
| 162 | - return None; | ||
| 163 | - } | ||
| 164 | - Some((!subject.is_empty()).then(|| subject.to_owned())) | ||
| 165 | -} | ||
| 166 | - | ||
| 167 | -#[cfg(test)] | ||
| 168 | -mod tests { | ||
| 169 | - use super::*; | ||
| 170 | - | ||
| 171 | - const KEY: [u8; 32] = [3; 32]; | ||
| 172 | - const NOW: i64 = 1_700_000_000; | ||
| 173 | - const HEX: &str = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393"; | ||
| 174 | - | ||
| 175 | - #[test] | ||
| 176 | - fn repo_names_need_an_owner_and_an_image() { | ||
| 177 | - assert_eq!(split_repo_name("tahinli/app"), Some(("tahinli", "app"))); | ||
| 178 | - assert_eq!(split_repo_name("tahinli/a/b"), Some(("tahinli", "a/b"))); | ||
| 179 | - assert_eq!(split_repo_name("tahinli"), None); | ||
| 180 | - assert_eq!(split_repo_name("Tahinli/app"), None); | ||
| 181 | - assert_eq!(split_repo_name("tahinli/app/"), None); | ||
| 182 | - assert_eq!(split_repo_name("tahinli//app"), None); | ||
| 183 | - assert_eq!(split_repo_name("tahinli/app__/x"), None); | ||
| 184 | - assert_eq!( | ||
| 185 | - split_repo_name("tahinli/my.app-v2_x"), | ||
| 186 | - Some(("tahinli", "my.app-v2_x")) | ||
| 187 | - ); | ||
| 188 | - assert_eq!(split_repo_name("tahinli/a..b"), None); | ||
| 189 | - } | ||
| 190 | - | ||
| 191 | - #[test] | ||
| 192 | - fn digests_must_be_lowercase_sha256_hex() { | ||
| 193 | - assert_eq!(parse_digest(&format!("sha256:{HEX}")), Some(HEX)); | ||
| 194 | - assert_eq!(parse_digest(HEX), None); | ||
| 195 | - assert_eq!(parse_digest(&format!("sha512:{HEX}")), None); | ||
| 196 | - assert_eq!( | ||
| 197 | - parse_digest(&format!("sha256:{}", HEX.to_uppercase())), | ||
| 198 | - None | ||
| 199 | - ); | ||
| 200 | - assert_eq!(parse_digest(&format!("sha256:{}", &HEX[..63])), None); | ||
| 201 | - } | ||
| 202 | - | ||
| 203 | - #[test] | ||
| 204 | - fn tags_follow_the_spec_charset() { | ||
| 205 | - assert!(valid_tag("latest")); | ||
| 206 | - assert!(valid_tag("v1.2.3-rc_1")); | ||
| 207 | - assert!(!valid_tag("")); | ||
| 208 | - assert!(!valid_tag(".hidden")); | ||
| 209 | - assert!(!valid_tag("a/b")); | ||
| 210 | - assert!(!valid_tag(&"a".repeat(129))); | ||
| 211 | - } | ||
| 212 | - | ||
| 213 | - #[test] | ||
| 214 | - fn an_image_manifest_names_its_config_and_layers() { | ||
| 215 | - let manifest = format!( | ||
| 216 | - r#"{{"schemaVersion":2,"config":{{"digest":"sha256:{HEX}","size":10}}, | ||
| 217 | - "layers":[{{"digest":"sha256:{HEX}","size":100}}]}}"# | ||
| 218 | - ); | ||
| 219 | - let refs = scan_manifest(manifest.as_bytes()).unwrap(); | ||
| 220 | - assert!(!refs.is_index); | ||
| 221 | - assert_eq!(refs.digests, vec![format!("sha256:{HEX}"); 2]); | ||
| 222 | - assert_eq!(refs.total_size, 110); | ||
| 223 | - } | ||
| 224 | - | ||
| 225 | - #[test] | ||
| 226 | - fn an_index_names_child_manifests() { | ||
| 227 | - let manifest = format!(r#"{{"manifests":[{{"digest":"sha256:{HEX}","size":5}}]}}"#); | ||
| 228 | - let refs = scan_manifest(manifest.as_bytes()).unwrap(); | ||
| 229 | - assert!(refs.is_index); | ||
| 230 | - assert_eq!(refs.digests, vec![format!("sha256:{HEX}")]); | ||
| 231 | - } | ||
| 232 | - | ||
| 233 | - #[test] | ||
| 234 | - fn bad_manifests_are_refused() { | ||
| 235 | - assert!(scan_manifest(b"not json").is_err()); | ||
| 236 | - assert!(scan_manifest(b"[]").is_err()); | ||
| 237 | - assert!(scan_manifest(b"{}").is_err()); | ||
| 238 | - assert!(scan_manifest(br#"{"config":{"digest":"md5:x"}}"#).is_err()); | ||
| 239 | - } | ||
| 240 | - | ||
| 241 | - #[test] | ||
| 242 | - fn a_token_round_trips_for_a_user_and_for_anonymous() { | ||
| 243 | - let token = issue_token(&KEY, Some("user-1"), NOW + 60); | ||
| 244 | - assert_eq!(verify_token(&KEY, &token, NOW), Some(Some("user-1".into()))); | ||
| 245 | - let anon = issue_token(&KEY, None, NOW + 60); | ||
| 246 | - assert_eq!(verify_token(&KEY, &anon, NOW), Some(None)); | ||
| 247 | - } | ||
| 248 | - | ||
| 249 | - #[test] | ||
| 250 | - fn a_token_is_refused_when_expired_forged_or_from_another_key() { | ||
| 251 | - let token = issue_token(&KEY, Some("user-1"), NOW + 60); | ||
| 252 | - assert_eq!(verify_token(&KEY, &token, NOW + 60), None); | ||
| 253 | - assert_eq!(verify_token(&[9; 32], &token, NOW), None); | ||
| 254 | - assert_eq!(verify_token(&KEY, "garbage", NOW), None); | ||
| 255 | - let forged = token.replacen(&BASE64_URL_SAFE_NO_PAD.encode("oci1|user-1|"), "x", 1); | ||
| 256 | - assert_eq!(verify_token(&KEY, &forged, NOW), None); | ||
| 257 | - } | ||
| 258 | -} | ||
crates/forge-core/src/packages.rsdeleted+0 -71
| @@ -1,71 +0,0 @@ | |||
| 1 | -pub const KIND_CARGO: &str = "cargo"; | ||
| 2 | -pub const KIND_OCI: &str = "oci"; | ||
| 3 | - | ||
| 4 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 5 | -pub struct Package { | ||
| 6 | - pub id: String, | ||
| 7 | - pub owner_id: String, | ||
| 8 | - pub kind: String, | ||
| 9 | - pub name: String, | ||
| 10 | - pub name_key: String, | ||
| 11 | - pub repo_id: Option<String>, | ||
| 12 | - pub private: bool, | ||
| 13 | - pub created_at: String, | ||
| 14 | - pub updated_at: String, | ||
| 15 | -} | ||
| 16 | - | ||
| 17 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 18 | -pub struct PackageVersion { | ||
| 19 | - pub id: String, | ||
| 20 | - pub package_id: String, | ||
| 21 | - pub version: String, | ||
| 22 | - pub yanked: bool, | ||
| 23 | - pub checksum: String, | ||
| 24 | - pub size: u64, | ||
| 25 | - pub index_json: String, | ||
| 26 | - pub description: Option<String>, | ||
| 27 | - pub readme: Option<String>, | ||
| 28 | - pub publisher_id: String, | ||
| 29 | - pub created_at: String, | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 33 | -pub struct PackageSummary { | ||
| 34 | - pub package: Package, | ||
| 35 | - pub version_count: u64, | ||
| 36 | - pub latest_version: Option<String>, | ||
| 37 | - pub latest_description: Option<String>, | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -#[derive(Debug, Clone, Copy)] | ||
| 41 | -pub struct NewPackageVersion<'a> { | ||
| 42 | - pub package_id: &'a str, | ||
| 43 | - pub version: &'a str, | ||
| 44 | - pub checksum: &'a str, | ||
| 45 | - pub size: u64, | ||
| 46 | - pub index_json: &'a str, | ||
| 47 | - pub description: Option<&'a str>, | ||
| 48 | - pub readme: Option<&'a str>, | ||
| 49 | - pub publisher_id: &'a str, | ||
| 50 | -} | ||
| 51 | - | ||
| 52 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 53 | -pub struct OciManifest { | ||
| 54 | - pub id: String, | ||
| 55 | - pub package_id: String, | ||
| 56 | - pub digest: String, | ||
| 57 | - pub media_type: String, | ||
| 58 | - pub content: String, | ||
| 59 | - pub size: u64, | ||
| 60 | - pub created_at: String, | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 64 | -pub struct OciTag { | ||
| 65 | - pub tag: String, | ||
| 66 | - pub digest: String, | ||
| 67 | - pub media_type: String, | ||
| 68 | - pub size: u64, | ||
| 69 | - pub created_at: String, | ||
| 70 | - pub updated_at: String, | ||
| 71 | -} | ||
crates/forge-core/src/store/mod.rsmodified+0 -2
| @@ -21,9 +21,7 @@ pub mod mirrors; | |||
| 21 | pub mod needs; | 21 | pub mod needs; |
| 22 | pub mod notifications; | 22 | pub mod notifications; |
| 23 | pub mod notifications_extra; | 23 | pub mod notifications_extra; |
| 24 | -pub mod oci; | ||
| 25 | pub mod orgs; | 24 | pub mod orgs; |
| 26 | -pub mod packages; | ||
| 27 | pub mod passkeys; | 25 | pub mod passkeys; |
| 28 | pub mod pinned; | 26 | pub mod pinned; |
| 29 | pub mod profile_pins; | 27 | pub mod profile_pins; |
crates/forge-core/src/store/oci.rsdeleted+0 -307
| @@ -1,307 +0,0 @@ | |||
| 1 | -use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id}; | ||
| 2 | -use crate::error::{Error, Result}; | ||
| 3 | -use crate::packages::{OciManifest, OciTag}; | ||
| 4 | -use crate::time::now_stamp; | ||
| 5 | - | ||
| 6 | -const MANIFEST_COLS: &str = "id, package_id, digest, media_type, content, size, created_at"; | ||
| 7 | - | ||
| 8 | -fn map_manifest(row: &turso::Row) -> Result<OciManifest> { | ||
| 9 | - Ok(OciManifest { | ||
| 10 | - id: col_text(row, 0)?, | ||
| 11 | - package_id: col_text(row, 1)?, | ||
| 12 | - digest: col_text(row, 2)?, | ||
| 13 | - media_type: col_text(row, 3)?, | ||
| 14 | - content: col_text(row, 4)?, | ||
| 15 | - size: to_u64(col_int(row, 5)?)?, | ||
| 16 | - created_at: col_text(row, 6)?, | ||
| 17 | - }) | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -fn to_u64(value: i64) -> Result<u64> { | ||
| 21 | - u64::try_from(value).map_err(|_| Error::Database("negative size".into())) | ||
| 22 | -} | ||
| 23 | - | ||
| 24 | -impl Store { | ||
| 25 | - pub async fn oci_link_blob(&self, package_id: &str, digest: &str, size: u64) -> Result<()> { | ||
| 26 | - let conn = self.inner.conn.lock().await; | ||
| 27 | - conn.execute( | ||
| 28 | - "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \ | ||
| 29 | - ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \ | ||
| 30 | - created_at = excluded.created_at", | ||
| 31 | - ( | ||
| 32 | - package_id.to_string(), | ||
| 33 | - digest.to_string(), | ||
| 34 | - i64::try_from(size).unwrap_or(i64::MAX), | ||
| 35 | - now_stamp(), | ||
| 36 | - ), | ||
| 37 | - ) | ||
| 38 | - .await | ||
| 39 | - .map_err(db_err)?; | ||
| 40 | - Ok(()) | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - pub async fn oci_blob_size(&self, package_id: &str, digest: &str) -> Result<Option<u64>> { | ||
| 44 | - let conn = self.read_conn().await; | ||
| 45 | - let size = fetch_opt( | ||
| 46 | - &conn, | ||
| 47 | - "SELECT size FROM oci_blobs WHERE package_id = ?1 AND digest = ?2 LIMIT 1", | ||
| 48 | - (package_id.to_string(), digest.to_string()), | ||
| 49 | - |row| col_int(row, 0), | ||
| 50 | - ) | ||
| 51 | - .await?; | ||
| 52 | - size.map(to_u64).transpose() | ||
| 53 | - } | ||
| 54 | - | ||
| 55 | - pub async fn oci_digest_linked(&self, digest: &str) -> Result<bool> { | ||
| 56 | - let conn = self.read_conn().await; | ||
| 57 | - let count = fetch_opt( | ||
| 58 | - &conn, | ||
| 59 | - "SELECT COUNT(*) FROM oci_blobs WHERE digest = ?1", | ||
| 60 | - (digest.to_string(),), | ||
| 61 | - |row| col_int(row, 0), | ||
| 62 | - ) | ||
| 63 | - .await?; | ||
| 64 | - Ok(count.unwrap_or(0) > 0) | ||
| 65 | - } | ||
| 66 | - | ||
| 67 | - pub async fn oci_put_manifest( | ||
| 68 | - &self, | ||
| 69 | - package_id: &str, | ||
| 70 | - digest: &str, | ||
| 71 | - media_type: &str, | ||
| 72 | - content: &str, | ||
| 73 | - size: u64, | ||
| 74 | - refs: &[String], | ||
| 75 | - ) -> Result<OciManifest> { | ||
| 76 | - { | ||
| 77 | - let conn = self.inner.conn.lock().await; | ||
| 78 | - conn.execute( | ||
| 79 | - "INSERT OR IGNORE INTO oci_manifests (id, package_id, digest, media_type, content, \ | ||
| 80 | - size, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | ||
| 81 | - ( | ||
| 82 | - new_id(), | ||
| 83 | - package_id.to_string(), | ||
| 84 | - digest.to_string(), | ||
| 85 | - media_type.to_string(), | ||
| 86 | - content.to_string(), | ||
| 87 | - i64::try_from(size).unwrap_or(i64::MAX), | ||
| 88 | - now_stamp(), | ||
| 89 | - ), | ||
| 90 | - ) | ||
| 91 | - .await | ||
| 92 | - .map_err(db_err)?; | ||
| 93 | - } | ||
| 94 | - let manifest = self | ||
| 95 | - .oci_manifest(package_id, digest) | ||
| 96 | - .await? | ||
| 97 | - .ok_or_else(missing_row)?; | ||
| 98 | - let conn = self.inner.conn.lock().await; | ||
| 99 | - for dep in refs { | ||
| 100 | - conn.execute( | ||
| 101 | - "INSERT OR IGNORE INTO oci_manifest_refs (manifest_id, digest) VALUES (?1, ?2)", | ||
| 102 | - (manifest.id.clone(), dep.clone()), | ||
| 103 | - ) | ||
| 104 | - .await | ||
| 105 | - .map_err(db_err)?; | ||
| 106 | - } | ||
| 107 | - Ok(manifest) | ||
| 108 | - } | ||
| 109 | - | ||
| 110 | - pub async fn oci_manifest( | ||
| 111 | - &self, | ||
| 112 | - package_id: &str, | ||
| 113 | - digest: &str, | ||
| 114 | - ) -> Result<Option<OciManifest>> { | ||
| 115 | - let conn = self.read_conn().await; | ||
| 116 | - fetch_opt( | ||
| 117 | - &conn, | ||
| 118 | - &format!( | ||
| 119 | - "SELECT {MANIFEST_COLS} FROM oci_manifests WHERE package_id = ?1 AND digest = ?2 \ | ||
| 120 | - LIMIT 1" | ||
| 121 | - ), | ||
| 122 | - (package_id.to_string(), digest.to_string()), | ||
| 123 | - map_manifest, | ||
| 124 | - ) | ||
| 125 | - .await | ||
| 126 | - } | ||
| 127 | - | ||
| 128 | - pub async fn oci_tag_manifest( | ||
| 129 | - &self, | ||
| 130 | - package_id: &str, | ||
| 131 | - tag: &str, | ||
| 132 | - ) -> Result<Option<OciManifest>> { | ||
| 133 | - let conn = self.read_conn().await; | ||
| 134 | - fetch_opt( | ||
| 135 | - &conn, | ||
| 136 | - "SELECT m.id, m.package_id, m.digest, m.media_type, m.content, m.size, m.created_at \ | ||
| 137 | - FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ | ||
| 138 | - WHERE t.package_id = ?1 AND t.tag = ?2 LIMIT 1", | ||
| 139 | - (package_id.to_string(), tag.to_string()), | ||
| 140 | - map_manifest, | ||
| 141 | - ) | ||
| 142 | - .await | ||
| 143 | - } | ||
| 144 | - | ||
| 145 | - pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> { | ||
| 146 | - let conn = self.inner.conn.lock().await; | ||
| 147 | - conn.execute( | ||
| 148 | - "INSERT INTO oci_tags (package_id, tag, manifest_id, updated_at) \ | ||
| 149 | - VALUES (?1, ?2, ?3, ?4) ON CONFLICT(package_id, tag) DO UPDATE SET \ | ||
| 150 | - manifest_id = excluded.manifest_id, updated_at = excluded.updated_at", | ||
| 151 | - ( | ||
| 152 | - package_id.to_string(), | ||
| 153 | - tag.to_string(), | ||
| 154 | - manifest_id.to_string(), | ||
| 155 | - now_stamp(), | ||
| 156 | - ), | ||
| 157 | - ) | ||
| 158 | - .await | ||
| 159 | - .map_err(db_err)?; | ||
| 160 | - Ok(()) | ||
| 161 | - } | ||
| 162 | - | ||
| 163 | - pub async fn oci_delete_tag(&self, package_id: &str, tag: &str) -> Result<Option<String>> { | ||
| 164 | - let manifest_id = { | ||
| 165 | - let conn = self.read_conn().await; | ||
| 166 | - fetch_opt( | ||
| 167 | - &conn, | ||
| 168 | - "SELECT manifest_id FROM oci_tags WHERE package_id = ?1 AND tag = ?2 LIMIT 1", | ||
| 169 | - (package_id.to_string(), tag.to_string()), | ||
| 170 | - |row| col_text(row, 0), | ||
| 171 | - ) | ||
| 172 | - .await? | ||
| 173 | - }; | ||
| 174 | - let Some(manifest_id) = manifest_id else { | ||
| 175 | - return Ok(None); | ||
| 176 | - }; | ||
| 177 | - let conn = self.inner.conn.lock().await; | ||
| 178 | - conn.execute( | ||
| 179 | - "DELETE FROM oci_tags WHERE package_id = ?1 AND tag = ?2", | ||
| 180 | - (package_id.to_string(), tag.to_string()), | ||
| 181 | - ) | ||
| 182 | - .await | ||
| 183 | - .map_err(db_err)?; | ||
| 184 | - Ok(Some(manifest_id)) | ||
| 185 | - } | ||
| 186 | - | ||
| 187 | - pub async fn oci_manifest_tag_count(&self, manifest_id: &str) -> Result<u64> { | ||
| 188 | - let conn = self.read_conn().await; | ||
| 189 | - let count = fetch_opt( | ||
| 190 | - &conn, | ||
| 191 | - "SELECT COUNT(*) FROM oci_tags WHERE manifest_id = ?1", | ||
| 192 | - (manifest_id.to_string(),), | ||
| 193 | - |row| col_int(row, 0), | ||
| 194 | - ) | ||
| 195 | - .await?; | ||
| 196 | - to_u64(count.unwrap_or(0)) | ||
| 197 | - } | ||
| 198 | - | ||
| 199 | - pub async fn oci_digest_referenced(&self, package_id: &str, digest: &str) -> Result<bool> { | ||
| 200 | - let conn = self.read_conn().await; | ||
| 201 | - let count = fetch_opt( | ||
| 202 | - &conn, | ||
| 203 | - "SELECT COUNT(*) FROM oci_manifest_refs r JOIN oci_manifests m ON m.id = r.manifest_id \ | ||
| 204 | - WHERE m.package_id = ?1 AND r.digest = ?2", | ||
| 205 | - (package_id.to_string(), digest.to_string()), | ||
| 206 | - |row| col_int(row, 0), | ||
| 207 | - ) | ||
| 208 | - .await?; | ||
| 209 | - Ok(count.unwrap_or(0) > 0) | ||
| 210 | - } | ||
| 211 | - | ||
| 212 | - pub async fn oci_delete_manifest(&self, manifest_id: &str) -> Result<()> { | ||
| 213 | - let conn = self.inner.conn.lock().await; | ||
| 214 | - conn.execute( | ||
| 215 | - "DELETE FROM oci_manifests WHERE id = ?1", | ||
| 216 | - (manifest_id.to_string(),), | ||
| 217 | - ) | ||
| 218 | - .await | ||
| 219 | - .map_err(db_err)?; | ||
| 220 | - Ok(()) | ||
| 221 | - } | ||
| 222 | - | ||
| 223 | - pub async fn oci_tag_names( | ||
| 224 | - &self, | ||
| 225 | - package_id: &str, | ||
| 226 | - last: &str, | ||
| 227 | - limit: u64, | ||
| 228 | - ) -> Result<Vec<String>> { | ||
| 229 | - let conn = self.read_conn().await; | ||
| 230 | - fetch_all( | ||
| 231 | - &conn, | ||
| 232 | - "SELECT tag FROM oci_tags WHERE package_id = ?1 AND tag > ?2 ORDER BY tag LIMIT ?3", | ||
| 233 | - ( | ||
| 234 | - package_id.to_string(), | ||
| 235 | - last.to_string(), | ||
| 236 | - i64::try_from(limit).unwrap_or(i64::MAX), | ||
| 237 | - ), | ||
| 238 | - |row| col_text(row, 0), | ||
| 239 | - ) | ||
| 240 | - .await | ||
| 241 | - } | ||
| 242 | - | ||
| 243 | - pub async fn oci_tags(&self, package_id: &str) -> Result<Vec<OciTag>> { | ||
| 244 | - let conn = self.read_conn().await; | ||
| 245 | - fetch_all( | ||
| 246 | - &conn, | ||
| 247 | - "SELECT t.tag, m.digest, m.media_type, m.size, m.created_at, t.updated_at \ | ||
| 248 | - FROM oci_tags t JOIN oci_manifests m ON m.id = t.manifest_id \ | ||
| 249 | - WHERE t.package_id = ?1 ORDER BY t.updated_at DESC, t.tag", | ||
| 250 | - (package_id.to_string(),), | ||
| 251 | - |row| { | ||
| 252 | - Ok(OciTag { | ||
| 253 | - tag: col_text(row, 0)?, | ||
| 254 | - digest: col_text(row, 1)?, | ||
| 255 | - media_type: col_text(row, 2)?, | ||
| 256 | - size: to_u64(col_int(row, 3)?)?, | ||
| 257 | - created_at: col_text(row, 4)?, | ||
| 258 | - updated_at: col_text(row, 5)?, | ||
| 259 | - }) | ||
| 260 | - }, | ||
| 261 | - ) | ||
| 262 | - .await | ||
| 263 | - } | ||
| 264 | - | ||
| 265 | - pub async fn oci_sweep_unreferenced( | ||
| 266 | - &self, | ||
| 267 | - package_id: &str, | ||
| 268 | - linked_before: &str, | ||
| 269 | - ) -> Result<Vec<String>> { | ||
| 270 | - let unreferenced = { | ||
| 271 | - let conn = self.read_conn().await; | ||
| 272 | - fetch_all( | ||
| 273 | - &conn, | ||
| 274 | - "SELECT digest FROM oci_blobs WHERE package_id = ?1 AND created_at < ?2 \ | ||
| 275 | - AND digest NOT IN \ | ||
| 276 | - (SELECT r.digest FROM oci_manifest_refs r JOIN oci_manifests m \ | ||
| 277 | - ON m.id = r.manifest_id WHERE m.package_id = ?1)", | ||
| 278 | - (package_id.to_string(), linked_before.to_string()), | ||
| 279 | - |row| col_text(row, 0), | ||
| 280 | - ) | ||
| 281 | - .await? | ||
| 282 | - }; | ||
| 283 | - let conn = self.inner.conn.lock().await; | ||
| 284 | - for digest in &unreferenced { | ||
| 285 | - conn.execute( | ||
| 286 | - "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", | ||
| 287 | - (package_id.to_string(), digest.clone()), | ||
| 288 | - ) | ||
| 289 | - .await | ||
| 290 | - .map_err(db_err)?; | ||
| 291 | - } | ||
| 292 | - Ok(unreferenced) | ||
| 293 | - } | ||
| 294 | - | ||
| 295 | - pub async fn oci_unlink_blob(&self, package_id: &str, digest: &str) -> Result<bool> { | ||
| 296 | - let changed = { | ||
| 297 | - let conn = self.inner.conn.lock().await; | ||
| 298 | - conn.execute( | ||
| 299 | - "DELETE FROM oci_blobs WHERE package_id = ?1 AND digest = ?2", | ||
| 300 | - (package_id.to_string(), digest.to_string()), | ||
| 301 | - ) | ||
| 302 | - .await | ||
| 303 | - .map_err(db_err)? | ||
| 304 | - }; | ||
| 305 | - Ok(changed == 1) | ||
| 306 | - } | ||
| 307 | -} | ||
crates/forge-core/src/store/packages.rsdeleted+0 -310
| @@ -1,310 +0,0 @@ | |||
| 1 | -use turso::{Row, Value}; | ||
| 2 | - | ||
| 3 | -use super::{ | ||
| 4 | - Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, missing_row, | ||
| 5 | - new_id, | ||
| 6 | -}; | ||
| 7 | -use crate::error::{Error, Result}; | ||
| 8 | -use crate::packages::{NewPackageVersion, Package, PackageSummary, PackageVersion}; | ||
| 9 | -use crate::time::now_stamp; | ||
| 10 | - | ||
| 11 | -const PACKAGE_COLS: &str = "p.id, p.owner_id, p.kind, p.name, p.name_key, p.repo_id, p.private, \ | ||
| 12 | - p.created_at, p.updated_at"; | ||
| 13 | - | ||
| 14 | -const VERSION_COLS: &str = "id, package_id, version, yanked, checksum, size, index_json, \ | ||
| 15 | - description, readme, publisher_id, created_at"; | ||
| 16 | - | ||
| 17 | -const VERSION_ORDER: &str = "created_at DESC, id DESC"; | ||
| 18 | - | ||
| 19 | -fn map_package(row: &Row) -> Result<Package> { | ||
| 20 | - Ok(Package { | ||
| 21 | - id: col_text(row, 0)?, | ||
| 22 | - owner_id: col_text(row, 1)?, | ||
| 23 | - kind: col_text(row, 2)?, | ||
| 24 | - name: col_text(row, 3)?, | ||
| 25 | - name_key: col_text(row, 4)?, | ||
| 26 | - repo_id: col_opt_text(row, 5)?, | ||
| 27 | - private: col_int(row, 6)? != 0, | ||
| 28 | - created_at: col_text(row, 7)?, | ||
| 29 | - updated_at: col_text(row, 8)?, | ||
| 30 | - }) | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -fn map_summary(row: &Row) -> Result<PackageSummary> { | ||
| 34 | - let count = col_int(row, 9)?; | ||
| 35 | - Ok(PackageSummary { | ||
| 36 | - package: map_package(row)?, | ||
| 37 | - version_count: u64::try_from(count) | ||
| 38 | - .map_err(|_| Error::Database("negative count".into()))?, | ||
| 39 | - latest_version: col_opt_text(row, 10)?, | ||
| 40 | - latest_description: col_opt_text(row, 11)?, | ||
| 41 | - }) | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -fn map_version(row: &Row) -> Result<PackageVersion> { | ||
| 45 | - let size = col_int(row, 5)?; | ||
| 46 | - Ok(PackageVersion { | ||
| 47 | - id: col_text(row, 0)?, | ||
| 48 | - package_id: col_text(row, 1)?, | ||
| 49 | - version: col_text(row, 2)?, | ||
| 50 | - yanked: col_int(row, 3)? != 0, | ||
| 51 | - checksum: col_text(row, 4)?, | ||
| 52 | - size: u64::try_from(size).map_err(|_| Error::Database("negative size".into()))?, | ||
| 53 | - index_json: col_text(row, 6)?, | ||
| 54 | - description: col_opt_text(row, 7)?, | ||
| 55 | - readme: col_opt_text(row, 8)?, | ||
| 56 | - publisher_id: col_text(row, 9)?, | ||
| 57 | - created_at: col_text(row, 10)?, | ||
| 58 | - }) | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -impl Store { | ||
| 62 | - pub async fn ensure_package( | ||
| 63 | - &self, | ||
| 64 | - owner_id: &str, | ||
| 65 | - kind: &str, | ||
| 66 | - name: &str, | ||
| 67 | - name_key: &str, | ||
| 68 | - ) -> Result<Package> { | ||
| 69 | - { | ||
| 70 | - let conn = self.inner.conn.lock().await; | ||
| 71 | - conn.execute( | ||
| 72 | - "INSERT OR IGNORE INTO packages (id, owner_id, kind, name, name_key, private, \ | ||
| 73 | - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?6)", | ||
| 74 | - ( | ||
| 75 | - new_id(), | ||
| 76 | - owner_id.to_string(), | ||
| 77 | - kind.to_string(), | ||
| 78 | - name.to_string(), | ||
| 79 | - name_key.to_string(), | ||
| 80 | - now_stamp(), | ||
| 81 | - ), | ||
| 82 | - ) | ||
| 83 | - .await | ||
| 84 | - .map_err(db_err)?; | ||
| 85 | - } | ||
| 86 | - self.package_by_name(owner_id, kind, name_key) | ||
| 87 | - .await? | ||
| 88 | - .ok_or_else(missing_row) | ||
| 89 | - } | ||
| 90 | - | ||
| 91 | - pub async fn package(&self, id: &str) -> Result<Option<Package>> { | ||
| 92 | - let conn = self.read_conn().await; | ||
| 93 | - fetch_opt( | ||
| 94 | - &conn, | ||
| 95 | - &format!("SELECT {PACKAGE_COLS} FROM packages p WHERE p.id = ?1 LIMIT 1"), | ||
| 96 | - (id.to_string(),), | ||
| 97 | - map_package, | ||
| 98 | - ) | ||
| 99 | - .await | ||
| 100 | - } | ||
| 101 | - | ||
| 102 | - pub async fn package_by_name( | ||
| 103 | - &self, | ||
| 104 | - owner_id: &str, | ||
| 105 | - kind: &str, | ||
| 106 | - name_key: &str, | ||
| 107 | - ) -> Result<Option<Package>> { | ||
| 108 | - let conn = self.read_conn().await; | ||
| 109 | - fetch_opt( | ||
| 110 | - &conn, | ||
| 111 | - &format!( | ||
| 112 | - "SELECT {PACKAGE_COLS} FROM packages p \ | ||
| 113 | - WHERE p.owner_id = ?1 AND p.kind = ?2 AND p.name_key = ?3 LIMIT 1" | ||
| 114 | - ), | ||
| 115 | - (owner_id.to_string(), kind.to_string(), name_key.to_string()), | ||
| 116 | - map_package, | ||
| 117 | - ) | ||
| 118 | - .await | ||
| 119 | - } | ||
| 120 | - | ||
| 121 | - pub async fn list_packages(&self, owner_id: &str, kind: &str) -> Result<Vec<PackageSummary>> { | ||
| 122 | - let conn = self.read_conn().await; | ||
| 123 | - fetch_all( | ||
| 124 | - &conn, | ||
| 125 | - &format!( | ||
| 126 | - "SELECT {PACKAGE_COLS}, \ | ||
| 127 | - CASE WHEN p.kind = 'oci' THEN \ | ||
| 128 | - (SELECT COUNT(*) FROM oci_tags t WHERE t.package_id = p.id) \ | ||
| 129 | - ELSE (SELECT COUNT(*) FROM package_versions v WHERE v.package_id = p.id) END, \ | ||
| 130 | - CASE WHEN p.kind = 'oci' THEN \ | ||
| 131 | - (SELECT t.tag FROM oci_tags t WHERE t.package_id = p.id \ | ||
| 132 | - ORDER BY t.updated_at DESC, t.tag LIMIT 1) \ | ||
| 133 | - ELSE (SELECT v.version FROM package_versions v WHERE v.package_id = p.id \ | ||
| 134 | - ORDER BY {VERSION_ORDER} LIMIT 1) END, \ | ||
| 135 | - CASE WHEN p.kind = 'oci' THEN NULL \ | ||
| 136 | - ELSE (SELECT v.description FROM package_versions v WHERE v.package_id = p.id \ | ||
| 137 | - ORDER BY {VERSION_ORDER} LIMIT 1) END \ | ||
| 138 | - FROM packages p WHERE p.owner_id = ?1 AND p.kind = ?2 ORDER BY p.name_key" | ||
| 139 | - ), | ||
| 140 | - (owner_id.to_string(), kind.to_string()), | ||
| 141 | - map_summary, | ||
| 142 | - ) | ||
| 143 | - .await | ||
| 144 | - } | ||
| 145 | - | ||
| 146 | - pub async fn packages_for_repo(&self, repo_id: &str) -> Result<Vec<Package>> { | ||
| 147 | - let conn = self.read_conn().await; | ||
| 148 | - fetch_all( | ||
| 149 | - &conn, | ||
| 150 | - &format!( | ||
| 151 | - "SELECT {PACKAGE_COLS} FROM packages p WHERE p.repo_id = ?1 ORDER BY p.name_key" | ||
| 152 | - ), | ||
| 153 | - (repo_id.to_string(),), | ||
| 154 | - map_package, | ||
| 155 | - ) | ||
| 156 | - .await | ||
| 157 | - } | ||
| 158 | - | ||
| 159 | - pub async fn owner_has_private_packages(&self, owner_id: &str) -> Result<bool> { | ||
| 160 | - let conn = self.read_conn().await; | ||
| 161 | - let count = fetch_opt( | ||
| 162 | - &conn, | ||
| 163 | - "SELECT COUNT(*) FROM packages WHERE owner_id = ?1 AND private = 1", | ||
| 164 | - (owner_id.to_string(),), | ||
| 165 | - |row| col_int(row, 0), | ||
| 166 | - ) | ||
| 167 | - .await?; | ||
| 168 | - Ok(count.unwrap_or(0) > 0) | ||
| 169 | - } | ||
| 170 | - | ||
| 171 | - pub async fn set_package_repo(&self, package_id: &str, repo_id: Option<&str>) -> Result<()> { | ||
| 172 | - let conn = self.inner.conn.lock().await; | ||
| 173 | - conn.execute( | ||
| 174 | - "UPDATE packages SET repo_id = ?2, updated_at = ?3 WHERE id = ?1", | ||
| 175 | - ( | ||
| 176 | - package_id.to_string(), | ||
| 177 | - repo_id.map_or(Value::Null, |id| Value::Text(id.to_string())), | ||
| 178 | - now_stamp(), | ||
| 179 | - ), | ||
| 180 | - ) | ||
| 181 | - .await | ||
| 182 | - .map_err(db_err)?; | ||
| 183 | - Ok(()) | ||
| 184 | - } | ||
| 185 | - | ||
| 186 | - pub async fn set_package_private(&self, package_id: &str, private: bool) -> Result<()> { | ||
| 187 | - let conn = self.inner.conn.lock().await; | ||
| 188 | - conn.execute( | ||
| 189 | - "UPDATE packages SET private = ?2, updated_at = ?3 WHERE id = ?1", | ||
| 190 | - (package_id.to_string(), i64::from(private), now_stamp()), | ||
| 191 | - ) | ||
| 192 | - .await | ||
| 193 | - .map_err(db_err)?; | ||
| 194 | - Ok(()) | ||
| 195 | - } | ||
| 196 | - | ||
| 197 | - pub async fn package_versions(&self, package_id: &str) -> Result<Vec<PackageVersion>> { | ||
| 198 | - let conn = self.read_conn().await; | ||
| 199 | - fetch_all( | ||
| 200 | - &conn, | ||
| 201 | - &format!( | ||
| 202 | - "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 \ | ||
| 203 | - ORDER BY {VERSION_ORDER}" | ||
| 204 | - ), | ||
| 205 | - (package_id.to_string(),), | ||
| 206 | - map_version, | ||
| 207 | - ) | ||
| 208 | - .await | ||
| 209 | - } | ||
| 210 | - | ||
| 211 | - pub async fn package_version( | ||
| 212 | - &self, | ||
| 213 | - package_id: &str, | ||
| 214 | - version: &str, | ||
| 215 | - ) -> Result<Option<PackageVersion>> { | ||
| 216 | - let conn = self.read_conn().await; | ||
| 217 | - fetch_opt( | ||
| 218 | - &conn, | ||
| 219 | - &format!( | ||
| 220 | - "SELECT {VERSION_COLS} FROM package_versions WHERE package_id = ?1 AND version = ?2 \ | ||
| 221 | - LIMIT 1" | ||
| 222 | - ), | ||
| 223 | - (package_id.to_string(), version.to_string()), | ||
| 224 | - map_version, | ||
| 225 | - ) | ||
| 226 | - .await | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - pub async fn publish_package_version( | ||
| 230 | - &self, | ||
| 231 | - new: &NewPackageVersion<'_>, | ||
| 232 | - ) -> Result<PackageVersion> { | ||
| 233 | - let now = now_stamp(); | ||
| 234 | - { | ||
| 235 | - let conn = self.inner.conn.lock().await; | ||
| 236 | - conn.execute( | ||
| 237 | - "INSERT INTO package_versions (id, package_id, version, yanked, checksum, size, \ | ||
| 238 | - index_json, description, readme, publisher_id, created_at) \ | ||
| 239 | - VALUES (?1, ?2, ?3, 0, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", | ||
| 240 | - ( | ||
| 241 | - new_id(), | ||
| 242 | - new.package_id.to_string(), | ||
| 243 | - new.version.to_string(), | ||
| 244 | - new.checksum.to_string(), | ||
| 245 | - i64::try_from(new.size).unwrap_or(i64::MAX), | ||
| 246 | - new.index_json.to_string(), | ||
| 247 | - new.description | ||
| 248 | - .map_or(Value::Null, |d| Value::Text(d.to_string())), | ||
| 249 | - new.readme | ||
| 250 | - .map_or(Value::Null, |r| Value::Text(r.to_string())), | ||
| 251 | - new.publisher_id.to_string(), | ||
| 252 | - now.clone(), | ||
| 253 | - ), | ||
| 254 | - ) | ||
| 255 | - .await | ||
| 256 | - .map_err(|e| insert_err(e, "this version is already published"))?; | ||
| 257 | - conn.execute( | ||
| 258 | - "UPDATE packages SET updated_at = ?2 WHERE id = ?1", | ||
| 259 | - (new.package_id.to_string(), now), | ||
| 260 | - ) | ||
| 261 | - .await | ||
| 262 | - .map_err(db_err)?; | ||
| 263 | - } | ||
| 264 | - self.package_version(new.package_id, new.version) | ||
| 265 | - .await? | ||
| 266 | - .ok_or_else(missing_row) | ||
| 267 | - } | ||
| 268 | - | ||
| 269 | - pub async fn delete_package_version(&self, package_id: &str, version: &str) -> Result<()> { | ||
| 270 | - let conn = self.inner.conn.lock().await; | ||
| 271 | - conn.execute( | ||
| 272 | - "DELETE FROM package_versions WHERE package_id = ?1 AND version = ?2", | ||
| 273 | - (package_id.to_string(), version.to_string()), | ||
| 274 | - ) | ||
| 275 | - .await | ||
| 276 | - .map_err(db_err)?; | ||
| 277 | - Ok(()) | ||
| 278 | - } | ||
| 279 | - | ||
| 280 | - pub async fn set_package_version_yanked( | ||
| 281 | - &self, | ||
| 282 | - package_id: &str, | ||
| 283 | - version: &str, | ||
| 284 | - yanked: bool, | ||
| 285 | - ) -> Result<bool> { | ||
| 286 | - let changed = { | ||
| 287 | - let conn = self.inner.conn.lock().await; | ||
| 288 | - conn.execute( | ||
| 289 | - "UPDATE package_versions SET yanked = ?3 WHERE package_id = ?1 AND version = ?2", | ||
| 290 | - ( | ||
| 291 | - package_id.to_string(), | ||
| 292 | - version.to_string(), | ||
| 293 | - i64::from(yanked), | ||
| 294 | - ), | ||
| 295 | - ) | ||
| 296 | - .await | ||
| 297 | - .map_err(db_err)? | ||
| 298 | - }; | ||
| 299 | - if changed == 1 { | ||
| 300 | - let conn = self.inner.conn.lock().await; | ||
| 301 | - conn.execute( | ||
| 302 | - "UPDATE packages SET updated_at = ?2 WHERE id = ?1", | ||
| 303 | - (package_id.to_string(), now_stamp()), | ||
| 304 | - ) | ||
| 305 | - .await | ||
| 306 | - .map_err(db_err)?; | ||
| 307 | - } | ||
| 308 | - Ok(changed == 1) | ||
| 309 | - } | ||
| 310 | -} | ||
crates/forge-core/src/store/user_delete.rsmodified+0 -1
| @@ -70,7 +70,6 @@ const REASSIGNED: &[(&str, &str, &str, &str)] = &[ | |||
| 70 | "", | 70 | "", |
| 71 | ), | 71 | ), |
| 72 | ("merge queue entries", "merge_queue", "enqueued_by", ""), | 72 | ("merge queue entries", "merge_queue", "enqueued_by", ""), |
| 73 | - ("package versions", "package_versions", "publisher_id", ""), | ||
| 74 | ( | 73 | ( |
| 75 | "notification actors", | 74 | "notification actors", |
| 76 | "notifications", | 75 | "notifications", |
crates/forge-core/tests/integration/store_basic.rsmodified+0 -35
| @@ -540,38 +540,3 @@ async fn set_username_display_changes_only_capitalization() { | |||
| 540 | let still = store.user_by_id(&user.id).await.unwrap().expect("found"); | 540 | let still = store.user_by_id(&user.id).await.unwrap().expect("found"); |
| 541 | assert_eq!(still.username, "Tahinli"); | 541 | assert_eq!(still.username, "Tahinli"); |
| 542 | } | 542 | } |
| 543 | - | ||
| 544 | -#[tokio::test] | ||
| 545 | -async fn oci_sweep_keeps_a_blob_linked_within_the_grace_period() { | ||
| 546 | - let dir = tempfile::tempdir().expect("temp dir"); | ||
| 547 | - let store = open_store(&db_path(&dir)).await; | ||
| 548 | - let user = store | ||
| 549 | - .create_user("tahinli", None, "h", false) | ||
| 550 | - .await | ||
| 551 | - .expect("user"); | ||
| 552 | - let package = store | ||
| 553 | - .ensure_package(&user.id, "oci", "app", "app") | ||
| 554 | - .await | ||
| 555 | - .expect("package"); | ||
| 556 | - let digest = format!("sha256:{}", "a".repeat(64)); | ||
| 557 | - store | ||
| 558 | - .oci_link_blob(&package.id, &digest, 10) | ||
| 559 | - .await | ||
| 560 | - .expect("link"); | ||
| 561 | - | ||
| 562 | - let grace_cutoff = forge_core::time::stamp_ago(Duration::from_secs(3600)); | ||
| 563 | - let kept = store | ||
| 564 | - .oci_sweep_unreferenced(&package.id, &grace_cutoff) | ||
| 565 | - .await | ||
| 566 | - .expect("sweep"); | ||
| 567 | - assert!(kept.is_empty(), "a recent link is kept"); | ||
| 568 | - assert!(store.oci_digest_linked(&digest).await.expect("linked")); | ||
| 569 | - | ||
| 570 | - let later_cutoff = stamp_after(Duration::from_secs(3600)); | ||
| 571 | - let dropped = store | ||
| 572 | - .oci_sweep_unreferenced(&package.id, &later_cutoff) | ||
| 573 | - .await | ||
| 574 | - .expect("sweep"); | ||
| 575 | - assert_eq!(dropped, vec![digest.clone()]); | ||
| 576 | - assert!(!store.oci_digest_linked(&digest).await.expect("linked")); | ||
| 577 | -} | ||
crates/forge-e2e/Cargo.tomlmodified+0 -5
| @@ -19,11 +19,6 @@ tokio.workspace = true | |||
| 19 | tokio-util = { workspace = true, features = ["io"] } | 19 | tokio-util = { workspace = true, features = ["io"] } |
| 20 | reqwest.workspace = true | 20 | reqwest.workspace = true |
| 21 | serde_json.workspace = true | 21 | serde_json.workspace = true |
| 22 | -base64.workspace = true | ||
| 23 | -sha2.workspace = true | ||
| 24 | -hex.workspace = true | ||
| 25 | -flate2.workspace = true | ||
| 26 | -tar.workspace = true | ||
| 27 | zip = { workspace = true } | 22 | zip = { workspace = true } |
| 28 | tempfile.workspace = true | 23 | tempfile.workspace = true |
| 29 | scraper = { workspace = true } | 24 | scraper = { workspace = true } |
crates/forge-e2e/tests/e2e/main.rsmodified+0 -2
| @@ -12,11 +12,9 @@ mod issue_close_e2e; | |||
| 12 | mod lfs_e2e; | 12 | mod lfs_e2e; |
| 13 | mod merge_queue_e2e; | 13 | mod merge_queue_e2e; |
| 14 | mod mirrors_e2e; | 14 | mod mirrors_e2e; |
| 15 | -mod oci_e2e; | ||
| 16 | mod orgs_core_e2e; | 15 | mod orgs_core_e2e; |
| 17 | mod orgs_live_e2e; | 16 | mod orgs_live_e2e; |
| 18 | mod orgs_ui_e2e; | 17 | mod orgs_ui_e2e; |
| 19 | -mod packages_e2e; | ||
| 20 | mod pulls_e2e; | 18 | mod pulls_e2e; |
| 21 | mod repo_collaborators_e2e; | 19 | mod repo_collaborators_e2e; |
| 22 | mod repo_rename_e2e; | 20 | mod repo_rename_e2e; |
crates/forge-e2e/tests/e2e/oci_e2e.rsdeleted+0 -882
| @@ -1,882 +0,0 @@ | |||
| 1 | -use crate::common::{Server, describe, launch, provision, tool_on_path}; | ||
| 2 | -use std::process::Command; | ||
| 3 | -use std::time::Duration; | ||
| 4 | - | ||
| 5 | -use forge_core::packages::KIND_OCI; | ||
| 6 | -use forge_core::token::{generate_token, hash_token}; | ||
| 7 | -use forge_core::{Store, User}; | ||
| 8 | -use sha2::{Digest, Sha256}; | ||
| 9 | - | ||
| 10 | -const MANIFEST_TYPE: &str = "application/vnd.oci.image.manifest.v1+json"; | ||
| 11 | - | ||
| 12 | -struct Resp { | ||
| 13 | - status: u16, | ||
| 14 | - headers: Vec<(String, String)>, | ||
| 15 | - body: Vec<u8>, | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -impl Resp { | ||
| 19 | - fn header(&self, name: &str) -> Option<&str> { | ||
| 20 | - self.headers | ||
| 21 | - .iter() | ||
| 22 | - .find(|(k, _)| k.eq_ignore_ascii_case(name)) | ||
| 23 | - .map(|(_, v)| v.as_str()) | ||
| 24 | - } | ||
| 25 | - | ||
| 26 | - fn text(&self) -> String { | ||
| 27 | - String::from_utf8_lossy(&self.body).into_owned() | ||
| 28 | - } | ||
| 29 | - | ||
| 30 | - fn json(&self) -> serde_json::Value { | ||
| 31 | - serde_json::from_slice(&self.body).expect("json body") | ||
| 32 | - } | ||
| 33 | - | ||
| 34 | - fn error_code(&self) -> String { | ||
| 35 | - self.json()["errors"][0]["code"] | ||
| 36 | - .as_str() | ||
| 37 | - .unwrap_or_default() | ||
| 38 | - .to_owned() | ||
| 39 | - } | ||
| 40 | -} | ||
| 41 | - | ||
| 42 | -struct Http { | ||
| 43 | - client: reqwest::Client, | ||
| 44 | - base: String, | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -impl Http { | ||
| 48 | - fn new(port: u16) -> Self { | ||
| 49 | - let client = reqwest::Client::builder() | ||
| 50 | - .redirect(reqwest::redirect::Policy::none()) | ||
| 51 | - .timeout(Duration::from_secs(60)) | ||
| 52 | - .build() | ||
| 53 | - .expect("http client"); | ||
| 54 | - Self { | ||
| 55 | - client, | ||
| 56 | - base: format!("http://127.0.0.1:{port}"), | ||
| 57 | - } | ||
| 58 | - } | ||
| 59 | - | ||
| 60 | - async fn send( | ||
| 61 | - &self, | ||
| 62 | - method: reqwest::Method, | ||
| 63 | - path: &str, | ||
| 64 | - auth: Option<&str>, | ||
| 65 | - headers: &[(&str, &str)], | ||
| 66 | - body: Option<Vec<u8>>, | ||
| 67 | - ) -> Resp { | ||
| 68 | - let url = if path.starts_with("http") { | ||
| 69 | - path.to_owned() | ||
| 70 | - } else { | ||
| 71 | - format!("{}{path}", self.base) | ||
| 72 | - }; | ||
| 73 | - let mut req = self.client.request(method, url); | ||
| 74 | - if let Some(value) = auth { | ||
| 75 | - req = req.header("Authorization", value); | ||
| 76 | - } | ||
| 77 | - for (name, value) in headers { | ||
| 78 | - req = req.header(*name, *value); | ||
| 79 | - } | ||
| 80 | - if let Some(bytes) = body { | ||
| 81 | - req = req.body(bytes); | ||
| 82 | - } | ||
| 83 | - let res = req.send().await.expect("http request"); | ||
| 84 | - let status = res.status().as_u16(); | ||
| 85 | - let headers = res | ||
| 86 | - .headers() | ||
| 87 | - .iter() | ||
| 88 | - .map(|(k, v)| (k.as_str().to_owned(), v.to_str().unwrap_or("").to_owned())) | ||
| 89 | - .collect(); | ||
| 90 | - let body = res.bytes().await.expect("read body").to_vec(); | ||
| 91 | - Resp { | ||
| 92 | - status, | ||
| 93 | - headers, | ||
| 94 | - body, | ||
| 95 | - } | ||
| 96 | - } | ||
| 97 | - | ||
| 98 | - async fn get(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 99 | - self.send(reqwest::Method::GET, path, auth, &[], None).await | ||
| 100 | - } | ||
| 101 | - | ||
| 102 | - async fn post(&self, path: &str, auth: Option<&str>, body: Option<Vec<u8>>) -> Resp { | ||
| 103 | - self.send(reqwest::Method::POST, path, auth, &[], body) | ||
| 104 | - .await | ||
| 105 | - } | ||
| 106 | -} | ||
| 107 | - | ||
| 108 | -struct Env { | ||
| 109 | - _root: tempfile::TempDir, | ||
| 110 | - _server: Server, | ||
| 111 | - http: Http, | ||
| 112 | - port: u16, | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | -async fn start<F, Fut>(seed: F) -> Env | ||
| 116 | -where | ||
| 117 | - F: FnOnce(Store) -> Fut, | ||
| 118 | - Fut: std::future::Future<Output = ()>, | ||
| 119 | -{ | ||
| 120 | - let root = crate::common::temp_dir("foci"); | ||
| 121 | - let dir = root.path().to_path_buf(); | ||
| 122 | - let (_, ports) = provision( | ||
| 123 | - &dir, | ||
| 124 | - "", | ||
| 125 | - &[&["create-user", "tahinli"], &["create-user", "bob"]], | ||
| 126 | - ); | ||
| 127 | - let store = Store::open(&dir.join("forge.db")) | ||
| 128 | - .await | ||
| 129 | - .expect("open store"); | ||
| 130 | - seed(store).await; | ||
| 131 | - let (server, ports) = launch(&dir, ports).await; | ||
| 132 | - Env { | ||
| 133 | - _root: root, | ||
| 134 | - _server: server, | ||
| 135 | - http: Http::new(ports.http), | ||
| 136 | - port: ports.http, | ||
| 137 | - } | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | -async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) { | ||
| 141 | - let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); | ||
| 142 | - store | ||
| 143 | - .create_token(&user.id, "ci", &hash_token(token), &scopes, None) | ||
| 144 | - .await | ||
| 145 | - .expect("create token"); | ||
| 146 | -} | ||
| 147 | - | ||
| 148 | -async fn user(store: &Store, name: &str) -> User { | ||
| 149 | - store | ||
| 150 | - .user_by_username(name) | ||
| 151 | - .await | ||
| 152 | - .expect("lookup user") | ||
| 153 | - .expect("user exists") | ||
| 154 | -} | ||
| 155 | - | ||
| 156 | -async fn start_with_packages_token() -> (Env, String) { | ||
| 157 | - let token = generate_token(); | ||
| 158 | - let seeded = token.clone(); | ||
| 159 | - let env = start(move |store| async move { | ||
| 160 | - let tahinli = user(&store, "tahinli").await; | ||
| 161 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 162 | - }) | ||
| 163 | - .await; | ||
| 164 | - (env, token) | ||
| 165 | -} | ||
| 166 | - | ||
| 167 | -fn sha256_digest(bytes: &[u8]) -> String { | ||
| 168 | - format!("sha256:{}", hex::encode(Sha256::digest(bytes))) | ||
| 169 | -} | ||
| 170 | - | ||
| 171 | -fn blob_path(bytes: &[u8]) -> String { | ||
| 172 | - format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes)) | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | -async fn bearer_for(http: &Http, token: &str) -> String { | ||
| 176 | - let res = http | ||
| 177 | - .send( | ||
| 178 | - reqwest::Method::GET, | ||
| 179 | - "/v2/token?service=127.0.0.1&scope=repository:tahinli/app:pull,push", | ||
| 180 | - Some(&basic("tahinli", token)), | ||
| 181 | - &[], | ||
| 182 | - None, | ||
| 183 | - ) | ||
| 184 | - .await; | ||
| 185 | - assert_eq!(res.status, 200, "{}", res.text()); | ||
| 186 | - let token = res.json()["token"].as_str().expect("token").to_owned(); | ||
| 187 | - format!("Bearer {token}") | ||
| 188 | -} | ||
| 189 | - | ||
| 190 | -fn basic(user: &str, password: &str) -> String { | ||
| 191 | - let encoded = { | ||
| 192 | - use base64::Engine as _; | ||
| 193 | - base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}")) | ||
| 194 | - }; | ||
| 195 | - format!("Basic {encoded}") | ||
| 196 | -} | ||
| 197 | - | ||
| 198 | -async fn push_blob(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp { | ||
| 199 | - let digest = sha256_digest(bytes); | ||
| 200 | - http.post( | ||
| 201 | - &format!("/v2/{repo}/blobs/uploads/?digest={digest}"), | ||
| 202 | - Some(auth), | ||
| 203 | - Some(bytes.to_vec()), | ||
| 204 | - ) | ||
| 205 | - .await | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -async fn push_blob_chunked(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp { | ||
| 209 | - let start = http | ||
| 210 | - .post(&format!("/v2/{repo}/blobs/uploads/"), Some(auth), None) | ||
| 211 | - .await; | ||
| 212 | - assert_eq!(start.status, 202, "{}", start.text()); | ||
| 213 | - let location = start.header("location").expect("location").to_owned(); | ||
| 214 | - let third = bytes.len() / 3; | ||
| 215 | - let mut offset = 0; | ||
| 216 | - for chunk in [ | ||
| 217 | - &bytes[..third], | ||
| 218 | - &bytes[third..2 * third], | ||
| 219 | - &bytes[2 * third..], | ||
| 220 | - ] { | ||
| 221 | - let range = format!("{offset}-{}", offset + chunk.len() - 1); | ||
| 222 | - let res = http | ||
| 223 | - .send( | ||
| 224 | - reqwest::Method::PATCH, | ||
| 225 | - &location, | ||
| 226 | - Some(auth), | ||
| 227 | - &[ | ||
| 228 | - ("Content-Range", &range), | ||
| 229 | - ("Content-Type", "application/octet-stream"), | ||
| 230 | - ], | ||
| 231 | - Some(chunk.to_vec()), | ||
| 232 | - ) | ||
| 233 | - .await; | ||
| 234 | - assert_eq!(res.status, 202, "{}", res.text()); | ||
| 235 | - offset += chunk.len(); | ||
| 236 | - } | ||
| 237 | - let digest = sha256_digest(bytes); | ||
| 238 | - http.send( | ||
| 239 | - reqwest::Method::PUT, | ||
| 240 | - &format!("{location}?digest={digest}"), | ||
| 241 | - Some(auth), | ||
| 242 | - &[], | ||
| 243 | - Some(Vec::new()), | ||
| 244 | - ) | ||
| 245 | - .await | ||
| 246 | -} | ||
| 247 | - | ||
| 248 | -fn manifest(config: &[u8], layers: &[&[u8]]) -> Vec<u8> { | ||
| 249 | - serde_json::to_vec(&serde_json::json!({ | ||
| 250 | - "schemaVersion": 2, | ||
| 251 | - "mediaType": MANIFEST_TYPE, | ||
| 252 | - "config": { | ||
| 253 | - "mediaType": "application/vnd.oci.image.config.v1+json", | ||
| 254 | - "digest": sha256_digest(config), | ||
| 255 | - "size": config.len(), | ||
| 256 | - }, | ||
| 257 | - "layers": layers.iter().map(|layer| serde_json::json!({ | ||
| 258 | - "mediaType": "application/vnd.oci.image.layer.v1.tar", | ||
| 259 | - "digest": sha256_digest(layer), | ||
| 260 | - "size": layer.len(), | ||
| 261 | - })).collect::<Vec<_>>(), | ||
| 262 | - })) | ||
| 263 | - .expect("manifest json") | ||
| 264 | -} | ||
| 265 | - | ||
| 266 | -async fn put_manifest(http: &Http, repo: &str, reference: &str, auth: &str, body: &[u8]) -> Resp { | ||
| 267 | - http.send( | ||
| 268 | - reqwest::Method::PUT, | ||
| 269 | - &format!("/v2/{repo}/manifests/{reference}"), | ||
| 270 | - Some(auth), | ||
| 271 | - &[("Content-Type", MANIFEST_TYPE)], | ||
| 272 | - Some(body.to_vec()), | ||
| 273 | - ) | ||
| 274 | - .await | ||
| 275 | -} | ||
| 276 | - | ||
| 277 | -#[tokio::test] | ||
| 278 | -async fn probe_challenges_and_the_token_endpoint_issues_a_bearer_token() { | ||
| 279 | - let (env, token) = start_with_packages_token().await; | ||
| 280 | - let port = env.port; | ||
| 281 | - | ||
| 282 | - let probe = env.http.get("/v2/", None).await; | ||
| 283 | - assert_eq!(probe.status, 401, "{}", probe.text()); | ||
| 284 | - let challenge = probe.header("www-authenticate").expect("challenge"); | ||
| 285 | - assert!( | ||
| 286 | - challenge.starts_with(&format!( | ||
| 287 | - "Bearer realm=\"http://127.0.0.1:{port}/v2/token\"" | ||
| 288 | - )), | ||
| 289 | - "{challenge}" | ||
| 290 | - ); | ||
| 291 | - assert!( | ||
| 292 | - challenge.contains(&format!("service=\"127.0.0.1:{port}\"")), | ||
| 293 | - "{challenge}" | ||
| 294 | - ); | ||
| 295 | - | ||
| 296 | - let auth = bearer_for(&env.http, &token).await; | ||
| 297 | - assert_eq!(env.http.get("/v2/", Some(&auth)).await.status, 200); | ||
| 298 | - | ||
| 299 | - let bad = env | ||
| 300 | - .http | ||
| 301 | - .get("/v2/", Some(&basic("tahinli", "forge_wrong"))) | ||
| 302 | - .await; | ||
| 303 | - assert_eq!(bad.status, 401, "{}", bad.text()); | ||
| 304 | - assert_eq!(bad.error_code(), "UNAUTHORIZED"); | ||
| 305 | -} | ||
| 306 | - | ||
| 307 | -#[tokio::test] | ||
| 308 | -async fn push_by_monolithic_and_chunked_upload_then_pull_by_tag_and_digest() { | ||
| 309 | - let (env, token) = start_with_packages_token().await; | ||
| 310 | - let http = &env.http; | ||
| 311 | - let auth = bearer_for(http, &token).await; | ||
| 312 | - | ||
| 313 | - let config = br#"{"architecture":"amd64","os":"linux"}"#.to_vec(); | ||
| 314 | - let layer_one = b"the first layer, pushed in one request".to_vec(); | ||
| 315 | - let layer_two: Vec<u8> = (0..3000u32).map(|i| (i % 251) as u8).collect(); | ||
| 316 | - | ||
| 317 | - let res = push_blob(http, "tahinli/app", &auth, &config).await; | ||
| 318 | - assert_eq!(res.status, 201, "{}", res.text()); | ||
| 319 | - assert_eq!( | ||
| 320 | - res.header("docker-content-digest"), | ||
| 321 | - Some(sha256_digest(&config).as_str()) | ||
| 322 | - ); | ||
| 323 | - assert_eq!( | ||
| 324 | - push_blob(http, "tahinli/app", &auth, &layer_one) | ||
| 325 | - .await | ||
| 326 | - .status, | ||
| 327 | - 201 | ||
| 328 | - ); | ||
| 329 | - let res = push_blob_chunked(http, "tahinli/app", &auth, &layer_two).await; | ||
| 330 | - assert_eq!(res.status, 201, "{}", res.text()); | ||
| 331 | - assert_eq!(res.header("location"), Some(blob_path(&layer_two).as_str())); | ||
| 332 | - | ||
| 333 | - let head = http | ||
| 334 | - .send( | ||
| 335 | - reqwest::Method::HEAD, | ||
| 336 | - &blob_path(&layer_two), | ||
| 337 | - Some(&auth), | ||
| 338 | - &[], | ||
| 339 | - None, | ||
| 340 | - ) | ||
| 341 | - .await; | ||
| 342 | - assert_eq!(head.status, 200); | ||
| 343 | - assert_eq!(head.header("content-length"), Some("3000")); | ||
| 344 | - let blob = http.get(&blob_path(&layer_two), Some(&auth)).await; | ||
| 345 | - assert_eq!(blob.status, 200); | ||
| 346 | - assert_eq!(blob.body, layer_two); | ||
| 347 | - | ||
| 348 | - let image = manifest(&config, &[&layer_one, &layer_two]); | ||
| 349 | - let res = put_manifest(http, "tahinli/app", "v1", &auth, &image).await; | ||
| 350 | - assert_eq!(res.status, 201, "{}", res.text()); | ||
| 351 | - let digest = sha256_digest(&image); | ||
| 352 | - assert_eq!(res.header("docker-content-digest"), Some(digest.as_str())); | ||
| 353 | - | ||
| 354 | - let by_tag = http.get("/v2/tahinli/app/manifests/v1", Some(&auth)).await; | ||
| 355 | - assert_eq!(by_tag.status, 200, "{}", by_tag.text()); | ||
| 356 | - assert_eq!(by_tag.body, image); | ||
| 357 | - assert_eq!(by_tag.header("content-type"), Some(MANIFEST_TYPE)); | ||
| 358 | - let by_digest = http | ||
| 359 | - .get(&format!("/v2/tahinli/app/manifests/{digest}"), Some(&auth)) | ||
| 360 | - .await; | ||
| 361 | - assert_eq!(by_digest.status, 200); | ||
| 362 | - assert_eq!(by_digest.body, image); | ||
| 363 | - let head = http | ||
| 364 | - .send( | ||
| 365 | - reqwest::Method::HEAD, | ||
| 366 | - "/v2/tahinli/app/manifests/v1", | ||
| 367 | - Some(&auth), | ||
| 368 | - &[], | ||
| 369 | - None, | ||
| 370 | - ) | ||
| 371 | - .await; | ||
| 372 | - assert_eq!(head.status, 200); | ||
| 373 | - assert!(head.body.is_empty()); | ||
| 374 | - | ||
| 375 | - let missing = http.get("/v2/tahinli/app/manifests/v9", Some(&auth)).await; | ||
| 376 | - assert_eq!(missing.status, 404); | ||
| 377 | - assert_eq!(missing.error_code(), "MANIFEST_UNKNOWN"); | ||
| 378 | -} | ||
| 379 | - | ||
| 380 | -#[tokio::test] | ||
| 381 | -async fn the_tag_list_pages_with_n_and_last() { | ||
| 382 | - let (env, token) = start_with_packages_token().await; | ||
| 383 | - let http = &env.http; | ||
| 384 | - let auth = bearer_for(http, &token).await; | ||
| 385 | - let config = b"{}".to_vec(); | ||
| 386 | - assert_eq!( | ||
| 387 | - push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 388 | - 201 | ||
| 389 | - ); | ||
| 390 | - let image = manifest(&config, &[]); | ||
| 391 | - for tag in ["v1", "v2", "v3"] { | ||
| 392 | - assert_eq!( | ||
| 393 | - put_manifest(http, "tahinli/app", tag, &auth, &image) | ||
| 394 | - .await | ||
| 395 | - .status, | ||
| 396 | - 201 | ||
| 397 | - ); | ||
| 398 | - } | ||
| 399 | - | ||
| 400 | - let first = http.get("/v2/tahinli/app/tags/list?n=2", Some(&auth)).await; | ||
| 401 | - assert_eq!(first.status, 200); | ||
| 402 | - assert_eq!(first.json()["tags"], serde_json::json!(["v1", "v2"])); | ||
| 403 | - let link = first.header("link").expect("next page link"); | ||
| 404 | - assert!( | ||
| 405 | - link.contains("last=v2") && link.contains("rel=\"next\""), | ||
| 406 | - "{link}" | ||
| 407 | - ); | ||
| 408 | - | ||
| 409 | - let second = http | ||
| 410 | - .get("/v2/tahinli/app/tags/list?n=2&last=v2", Some(&auth)) | ||
| 411 | - .await; | ||
| 412 | - assert_eq!(second.json()["tags"], serde_json::json!(["v3"])); | ||
| 413 | - assert!(second.header("link").is_none()); | ||
| 414 | - | ||
| 415 | - let all = http.get("/v2/tahinli/app/tags/list", Some(&auth)).await; | ||
| 416 | - assert_eq!(all.json()["name"], "tahinli/app"); | ||
| 417 | - assert_eq!(all.json()["tags"], serde_json::json!(["v1", "v2", "v3"])); | ||
| 418 | -} | ||
| 419 | - | ||
| 420 | -#[tokio::test] | ||
| 421 | -async fn bad_digests_and_missing_blobs_are_refused_with_oci_codes() { | ||
| 422 | - let (env, token) = start_with_packages_token().await; | ||
| 423 | - let http = &env.http; | ||
| 424 | - let auth = bearer_for(http, &token).await; | ||
| 425 | - let config = b"{}".to_vec(); | ||
| 426 | - | ||
| 427 | - let wrong = format!( | ||
| 428 | - "/v2/tahinli/app/blobs/uploads/?digest={}", | ||
| 429 | - sha256_digest(b"other") | ||
| 430 | - ); | ||
| 431 | - let res = http.post(&wrong, Some(&auth), Some(config.clone())).await; | ||
| 432 | - assert_eq!(res.status, 400, "{}", res.text()); | ||
| 433 | - assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 434 | - | ||
| 435 | - let image = manifest(&config, &[]); | ||
| 436 | - let res = put_manifest(http, "tahinli/app", "v1", &auth, &image).await; | ||
| 437 | - assert_eq!(res.status, 400); | ||
| 438 | - assert_eq!(res.error_code(), "MANIFEST_BLOB_UNKNOWN"); | ||
| 439 | - | ||
| 440 | - assert_eq!( | ||
| 441 | - push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 442 | - 201 | ||
| 443 | - ); | ||
| 444 | - let res = put_manifest( | ||
| 445 | - http, | ||
| 446 | - "tahinli/app", | ||
| 447 | - &sha256_digest(b"not this"), | ||
| 448 | - &auth, | ||
| 449 | - &image, | ||
| 450 | - ) | ||
| 451 | - .await; | ||
| 452 | - assert_eq!(res.status, 400); | ||
| 453 | - assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 454 | - | ||
| 455 | - let res = http.get("/v2/tahinli/nope/manifests/v1", Some(&auth)).await; | ||
| 456 | - assert_eq!(res.status, 404); | ||
| 457 | - assert_eq!(res.error_code(), "NAME_UNKNOWN"); | ||
| 458 | - | ||
| 459 | - let res = http.get("/v2/Tahinli/App/tags/list", Some(&auth)).await; | ||
| 460 | - assert_eq!(res.status, 400); | ||
| 461 | - assert_eq!(res.error_code(), "NAME_INVALID"); | ||
| 462 | - | ||
| 463 | - let res = http.get(&blob_path(b"absent"), Some(&auth)).await; | ||
| 464 | - assert_eq!(res.status, 404); | ||
| 465 | - assert_eq!(res.error_code(), "BLOB_UNKNOWN"); | ||
| 466 | -} | ||
| 467 | - | ||
| 468 | -#[tokio::test] | ||
| 469 | -async fn an_aborted_chunked_upload_is_gone_after_a_bad_digest() { | ||
| 470 | - let (env, token) = start_with_packages_token().await; | ||
| 471 | - let http = &env.http; | ||
| 472 | - let auth = bearer_for(http, &token).await; | ||
| 473 | - | ||
| 474 | - let start = http | ||
| 475 | - .post("/v2/tahinli/app/blobs/uploads/", Some(&auth), None) | ||
| 476 | - .await; | ||
| 477 | - assert_eq!(start.status, 202); | ||
| 478 | - let location = start.header("location").expect("location").to_owned(); | ||
| 479 | - let patched = http | ||
| 480 | - .send( | ||
| 481 | - reqwest::Method::PATCH, | ||
| 482 | - &location, | ||
| 483 | - Some(&auth), | ||
| 484 | - &[], | ||
| 485 | - Some(b"some bytes".to_vec()), | ||
| 486 | - ) | ||
| 487 | - .await; | ||
| 488 | - assert_eq!(patched.status, 202); | ||
| 489 | - assert_eq!(patched.header("range"), Some("0-9")); | ||
| 490 | - | ||
| 491 | - let res = http | ||
| 492 | - .send( | ||
| 493 | - reqwest::Method::PUT, | ||
| 494 | - &format!("{location}?digest={}", sha256_digest(b"different")), | ||
| 495 | - Some(&auth), | ||
| 496 | - &[], | ||
| 497 | - Some(Vec::new()), | ||
| 498 | - ) | ||
| 499 | - .await; | ||
| 500 | - assert_eq!(res.status, 400); | ||
| 501 | - assert_eq!(res.error_code(), "DIGEST_INVALID"); | ||
| 502 | - | ||
| 503 | - let status = http | ||
| 504 | - .send(reqwest::Method::GET, &location, Some(&auth), &[], None) | ||
| 505 | - .await; | ||
| 506 | - assert_eq!(status.status, 404, "{}", status.text()); | ||
| 507 | - assert_eq!(status.error_code(), "BLOB_UPLOAD_UNKNOWN"); | ||
| 508 | -} | ||
| 509 | - | ||
| 510 | -#[tokio::test] | ||
| 511 | -async fn a_public_image_pulls_anonymously_and_a_private_one_does_not() { | ||
| 512 | - let token = generate_token(); | ||
| 513 | - let seeded = token.clone(); | ||
| 514 | - let env = start(move |store| async move { | ||
| 515 | - let tahinli = user(&store, "tahinli").await; | ||
| 516 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 517 | - let secret = store | ||
| 518 | - .ensure_package(&tahinli.id, KIND_OCI, "secret", "secret") | ||
| 519 | - .await | ||
| 520 | - .expect("package"); | ||
| 521 | - store | ||
| 522 | - .set_package_private(&secret.id, true) | ||
| 523 | - .await | ||
| 524 | - .expect("make private"); | ||
| 525 | - }) | ||
| 526 | - .await; | ||
| 527 | - let http = &env.http; | ||
| 528 | - let auth = bearer_for(http, &token).await; | ||
| 529 | - let config = b"{}".to_vec(); | ||
| 530 | - assert_eq!( | ||
| 531 | - push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 532 | - 201 | ||
| 533 | - ); | ||
| 534 | - let image = manifest(&config, &[]); | ||
| 535 | - assert_eq!( | ||
| 536 | - put_manifest(http, "tahinli/app", "v1", &auth, &image) | ||
| 537 | - .await | ||
| 538 | - .status, | ||
| 539 | - 201 | ||
| 540 | - ); | ||
| 541 | - assert_eq!( | ||
| 542 | - push_blob(http, "tahinli/secret", &auth, &config) | ||
| 543 | - .await | ||
| 544 | - .status, | ||
| 545 | - 201 | ||
| 546 | - ); | ||
| 547 | - assert_eq!( | ||
| 548 | - put_manifest(http, "tahinli/secret", "v1", &auth, &image) | ||
| 549 | - .await | ||
| 550 | - .status, | ||
| 551 | - 201 | ||
| 552 | - ); | ||
| 553 | - | ||
| 554 | - let anon = http.get("/v2/tahinli/app/manifests/v1", None).await; | ||
| 555 | - assert_eq!(anon.status, 200, "{}", anon.text()); | ||
| 556 | - assert_eq!(anon.body, image); | ||
| 557 | - let anon_blob = http.get(&blob_path(&config), None).await; | ||
| 558 | - assert_eq!(anon_blob.status, 200); | ||
| 559 | - | ||
| 560 | - let hidden = http.get("/v2/tahinli/secret/manifests/v1", None).await; | ||
| 561 | - assert_eq!(hidden.status, 401); | ||
| 562 | - assert!(hidden.header("www-authenticate").is_some()); | ||
| 563 | - assert_eq!(hidden.error_code(), "UNAUTHORIZED"); | ||
| 564 | - let owner = http | ||
| 565 | - .get("/v2/tahinli/secret/manifests/v1", Some(&auth)) | ||
| 566 | - .await; | ||
| 567 | - assert_eq!(owner.status, 200); | ||
| 568 | - | ||
| 569 | - let missing = http.get("/v2/tahinli/nothing/manifests/v1", None).await; | ||
| 570 | - assert_eq!( | ||
| 571 | - missing.status, 401, | ||
| 572 | - "anonymous callers learn nothing about missing images" | ||
| 573 | - ); | ||
| 574 | -} | ||
| 575 | - | ||
| 576 | -#[tokio::test] | ||
| 577 | -async fn writes_need_the_packages_scope_and_the_owner() { | ||
| 578 | - let token = generate_token(); | ||
| 579 | - let bob_token = generate_token(); | ||
| 580 | - let no_scope = generate_token(); | ||
| 581 | - let (seeded, seeded_bob, seeded_none) = (token.clone(), bob_token.clone(), no_scope.clone()); | ||
| 582 | - let env = start(move |store| async move { | ||
| 583 | - let tahinli = user(&store, "tahinli").await; | ||
| 584 | - let bob = user(&store, "bob").await; | ||
| 585 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 586 | - grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 587 | - grant(&store, &tahinli, &["repo"], &seeded_none).await; | ||
| 588 | - }) | ||
| 589 | - .await; | ||
| 590 | - let http = &env.http; | ||
| 591 | - | ||
| 592 | - let anon = http | ||
| 593 | - .post("/v2/tahinli/app/blobs/uploads/", None, None) | ||
| 594 | - .await; | ||
| 595 | - assert_eq!(anon.status, 401); | ||
| 596 | - assert!(anon.header("www-authenticate").is_some()); | ||
| 597 | - | ||
| 598 | - let without = bearer_for_scope_less(http, &no_scope).await; | ||
| 599 | - let res = http | ||
| 600 | - .post("/v2/tahinli/app/blobs/uploads/", Some(&without), None) | ||
| 601 | - .await; | ||
| 602 | - assert_eq!( | ||
| 603 | - res.status, 401, | ||
| 604 | - "a token without the packages scope cannot push" | ||
| 605 | - ); | ||
| 606 | - | ||
| 607 | - let bob_auth = bearer_for_as(http, "bob", &bob_token).await; | ||
| 608 | - let res = http | ||
| 609 | - .post("/v2/tahinli/app/blobs/uploads/", Some(&bob_auth), None) | ||
| 610 | - .await; | ||
| 611 | - assert_eq!(res.status, 403); | ||
| 612 | - assert_eq!(res.error_code(), "DENIED"); | ||
| 613 | - | ||
| 614 | - let owner_auth = bearer_for(http, &token).await; | ||
| 615 | - let res = http | ||
| 616 | - .post("/v2/tahinli/app/blobs/uploads/", Some(&owner_auth), None) | ||
| 617 | - .await; | ||
| 618 | - assert_eq!(res.status, 202); | ||
| 619 | -} | ||
| 620 | - | ||
| 621 | -async fn bearer_for_scope_less(http: &Http, token: &str) -> String { | ||
| 622 | - bearer_for(http, token).await | ||
| 623 | -} | ||
| 624 | - | ||
| 625 | -async fn bearer_for_as(http: &Http, who: &str, token: &str) -> String { | ||
| 626 | - let res = http | ||
| 627 | - .send( | ||
| 628 | - reqwest::Method::GET, | ||
| 629 | - "/v2/token", | ||
| 630 | - Some(&basic(who, token)), | ||
| 631 | - &[], | ||
| 632 | - None, | ||
| 633 | - ) | ||
| 634 | - .await; | ||
| 635 | - assert_eq!(res.status, 200, "{}", res.text()); | ||
| 636 | - format!("Bearer {}", res.json()["token"].as_str().expect("token")) | ||
| 637 | -} | ||
| 638 | - | ||
| 639 | -#[tokio::test] | ||
| 640 | -async fn mount_copies_a_blob_across_repositories() { | ||
| 641 | - let (env, token) = start_with_packages_token().await; | ||
| 642 | - let http = &env.http; | ||
| 643 | - let auth = bearer_for(http, &token).await; | ||
| 644 | - let layer = b"shared layer bytes".to_vec(); | ||
| 645 | - assert_eq!( | ||
| 646 | - push_blob(http, "tahinli/app", &auth, &layer).await.status, | ||
| 647 | - 201 | ||
| 648 | - ); | ||
| 649 | - | ||
| 650 | - let digest = sha256_digest(&layer); | ||
| 651 | - let mounted = http | ||
| 652 | - .post( | ||
| 653 | - &format!("/v2/tahinli/other/blobs/uploads/?mount={digest}&from=tahinli/app"), | ||
| 654 | - Some(&auth), | ||
| 655 | - None, | ||
| 656 | - ) | ||
| 657 | - .await; | ||
| 658 | - assert_eq!(mounted.status, 201, "{}", mounted.text()); | ||
| 659 | - let read = http | ||
| 660 | - .get(&format!("/v2/tahinli/other/blobs/{digest}"), Some(&auth)) | ||
| 661 | - .await; | ||
| 662 | - assert_eq!(read.body, layer); | ||
| 663 | - | ||
| 664 | - let not_there = http | ||
| 665 | - .post( | ||
| 666 | - &format!( | ||
| 667 | - "/v2/tahinli/other/blobs/uploads/?mount={}&from=tahinli/app", | ||
| 668 | - sha256_digest(b"x") | ||
| 669 | - ), | ||
| 670 | - Some(&auth), | ||
| 671 | - None, | ||
| 672 | - ) | ||
| 673 | - .await; | ||
| 674 | - assert_eq!( | ||
| 675 | - not_there.status, 202, | ||
| 676 | - "a mount that is not possible opens an upload instead" | ||
| 677 | - ); | ||
| 678 | -} | ||
| 679 | - | ||
| 680 | -#[tokio::test] | ||
| 681 | -async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() { | ||
| 682 | - let (env, token) = start_with_packages_token().await; | ||
| 683 | - let http = &env.http; | ||
| 684 | - let auth = bearer_for(http, &token).await; | ||
| 685 | - let config = b"{\"shared\":true}".to_vec(); | ||
| 686 | - let layer_a = b"only in v1".to_vec(); | ||
| 687 | - let layer_b = b"only in v2".to_vec(); | ||
| 688 | - for blob in [&config, &layer_a, &layer_b] { | ||
| 689 | - assert_eq!( | ||
| 690 | - push_blob(http, "tahinli/app", &auth, blob).await.status, | ||
| 691 | - 201 | ||
| 692 | - ); | ||
| 693 | - } | ||
| 694 | - let v1 = manifest(&config, &[&layer_a]); | ||
| 695 | - let v2 = manifest(&config, &[&layer_b]); | ||
| 696 | - assert_eq!( | ||
| 697 | - put_manifest(http, "tahinli/app", "v1", &auth, &v1) | ||
| 698 | - .await | ||
| 699 | - .status, | ||
| 700 | - 201 | ||
| 701 | - ); | ||
| 702 | - assert_eq!( | ||
| 703 | - put_manifest(http, "tahinli/app", "v2", &auth, &v2) | ||
| 704 | - .await | ||
| 705 | - .status, | ||
| 706 | - 201 | ||
| 707 | - ); | ||
| 708 | - | ||
| 709 | - let res = http | ||
| 710 | - .send( | ||
| 711 | - reqwest::Method::DELETE, | ||
| 712 | - "/v2/tahinli/app/manifests/v2", | ||
| 713 | - Some(&auth), | ||
| 714 | - &[], | ||
| 715 | - None, | ||
| 716 | - ) | ||
| 717 | - .await; | ||
| 718 | - assert_eq!(res.status, 202, "{}", res.text()); | ||
| 719 | - assert_eq!( | ||
| 720 | - http.get("/v2/tahinli/app/manifests/v2", Some(&auth)) | ||
| 721 | - .await | ||
| 722 | - .status, | ||
| 723 | - 404 | ||
| 724 | - ); | ||
| 725 | - assert_eq!( | ||
| 726 | - http.get(&blob_path(&layer_b), Some(&auth)).await.status, | ||
| 727 | - 200 | ||
| 728 | - ); | ||
| 729 | - assert_eq!( | ||
| 730 | - http.get(&blob_path(&layer_a), Some(&auth)).await.status, | ||
| 731 | - 200 | ||
| 732 | - ); | ||
| 733 | - assert_eq!(http.get(&blob_path(&config), Some(&auth)).await.status, 200); | ||
| 734 | - | ||
| 735 | - let v1_digest = sha256_digest(&v1); | ||
| 736 | - let res = http | ||
| 737 | - .send( | ||
| 738 | - reqwest::Method::DELETE, | ||
| 739 | - &format!("/v2/tahinli/app/manifests/{v1_digest}"), | ||
| 740 | - Some(&auth), | ||
| 741 | - &[], | ||
| 742 | - None, | ||
| 743 | - ) | ||
| 744 | - .await; | ||
| 745 | - assert_eq!(res.status, 202); | ||
| 746 | - assert_eq!( | ||
| 747 | - http.get(&blob_path(&layer_a), Some(&auth)).await.status, | ||
| 748 | - 200 | ||
| 749 | - ); | ||
| 750 | - assert_eq!(http.get(&blob_path(&config), Some(&auth)).await.status, 200); | ||
| 751 | - let tags = http.get("/v2/tahinli/app/tags/list", Some(&auth)).await; | ||
| 752 | - assert_eq!(tags.json()["tags"], serde_json::json!([])); | ||
| 753 | -} | ||
| 754 | - | ||
| 755 | -#[tokio::test] | ||
| 756 | -async fn a_blob_a_manifest_uses_cannot_be_deleted_and_an_unused_one_can() { | ||
| 757 | - let (env, token) = start_with_packages_token().await; | ||
| 758 | - let http = &env.http; | ||
| 759 | - let auth = bearer_for(http, &token).await; | ||
| 760 | - let config = b"{}".to_vec(); | ||
| 761 | - let layer = b"kept by the manifest".to_vec(); | ||
| 762 | - let spare = b"never used".to_vec(); | ||
| 763 | - assert_eq!( | ||
| 764 | - push_blob(http, "tahinli/app", &auth, &config).await.status, | ||
| 765 | - 201 | ||
| 766 | - ); | ||
| 767 | - assert_eq!( | ||
| 768 | - push_blob(http, "tahinli/app", &auth, &layer).await.status, | ||
| 769 | - 201 | ||
| 770 | - ); | ||
| 771 | - assert_eq!( | ||
| 772 | - push_blob(http, "tahinli/app", &auth, &spare).await.status, | ||
| 773 | - 201 | ||
| 774 | - ); | ||
| 775 | - assert_eq!( | ||
| 776 | - put_manifest( | ||
| 777 | - http, | ||
| 778 | - "tahinli/app", | ||
| 779 | - "v1", | ||
| 780 | - &auth, | ||
| 781 | - &manifest(&config, &[&layer]) | ||
| 782 | - ) | ||
| 783 | - .await | ||
| 784 | - .status, | ||
| 785 | - 201 | ||
| 786 | - ); | ||
| 787 | - | ||
| 788 | - let refused = http | ||
| 789 | - .send( | ||
| 790 | - reqwest::Method::DELETE, | ||
| 791 | - &blob_path(&layer), | ||
| 792 | - Some(&auth), | ||
| 793 | - &[], | ||
| 794 | - None, | ||
| 795 | - ) | ||
| 796 | - .await; | ||
| 797 | - assert_eq!(refused.status, 400); | ||
| 798 | - assert_eq!(refused.error_code(), "UNSUPPORTED"); | ||
| 799 | - | ||
| 800 | - let gone = http | ||
| 801 | - .send( | ||
| 802 | - reqwest::Method::DELETE, | ||
| 803 | - &blob_path(&spare), | ||
| 804 | - Some(&auth), | ||
| 805 | - &[], | ||
| 806 | - None, | ||
| 807 | - ) | ||
| 808 | - .await; | ||
| 809 | - assert_eq!(gone.status, 202); | ||
| 810 | - assert_eq!(http.get(&blob_path(&spare), Some(&auth)).await.status, 404); | ||
| 811 | -} | ||
| 812 | - | ||
| 813 | -#[tokio::test] | ||
| 814 | -#[ignore = "runs podman; run with --ignored"] | ||
| 815 | -async fn podman_logs_in_pushes_and_pulls_an_image() { | ||
| 816 | - if !tool_on_path("podman") { | ||
| 817 | - eprintln!("podman is not installed; skipping"); | ||
| 818 | - return; | ||
| 819 | - } | ||
| 820 | - let (env, token) = start_with_packages_token().await; | ||
| 821 | - let host = format!("127.0.0.1:{}", env.port); | ||
| 822 | - let work = tempfile::tempdir().expect("work dir"); | ||
| 823 | - let dir = work.path(); | ||
| 824 | - let auth_file = dir.join("auth.json"); | ||
| 825 | - std::fs::write(dir.join("hello.txt"), "hello from the forge\n").expect("file"); | ||
| 826 | - std::fs::write( | ||
| 827 | - dir.join("Containerfile"), | ||
| 828 | - "FROM scratch\nCOPY hello.txt /hello.txt\n", | ||
| 829 | - ) | ||
| 830 | - .expect("containerfile"); | ||
| 831 | - let root = dir.join("store"); | ||
| 832 | - let run = dir.join("run"); | ||
| 833 | - let auth_path = auth_file.to_str().expect("utf8").to_owned(); | ||
| 834 | - let root_arg = root.to_str().expect("utf8").to_owned(); | ||
| 835 | - let run_arg = run.to_str().expect("utf8").to_owned(); | ||
| 836 | - let podman = |args: &[&str]| -> String { | ||
| 837 | - let out = Command::new("podman") | ||
| 838 | - .args(["--root", &root_arg, "--runroot", &run_arg]) | ||
| 839 | - .args(args) | ||
| 840 | - .env("REGISTRY_AUTH_FILE", &auth_path) | ||
| 841 | - .current_dir(dir) | ||
| 842 | - .output() | ||
| 843 | - .expect("run podman"); | ||
| 844 | - assert!( | ||
| 845 | - out.status.success(), | ||
| 846 | - "podman {args:?} failed:\n{}", | ||
| 847 | - describe(&out) | ||
| 848 | - ); | ||
| 849 | - format!( | ||
| 850 | - "{}{}", | ||
| 851 | - String::from_utf8_lossy(&out.stdout), | ||
| 852 | - String::from_utf8_lossy(&out.stderr) | ||
| 853 | - ) | ||
| 854 | - }; | ||
| 855 | - | ||
| 856 | - podman(&[ | ||
| 857 | - "build", | ||
| 858 | - "-f", | ||
| 859 | - "Containerfile", | ||
| 860 | - "-t", | ||
| 861 | - "localhost/tiny:v1", | ||
| 862 | - ".", | ||
| 863 | - ]); | ||
| 864 | - podman(&[ | ||
| 865 | - "login", | ||
| 866 | - "--tls-verify=false", | ||
| 867 | - "-u", | ||
| 868 | - "tahinli", | ||
| 869 | - "-p", | ||
| 870 | - &token, | ||
| 871 | - &host, | ||
| 872 | - ]); | ||
| 873 | - let target = format!("{host}/tahinli/tiny:v1"); | ||
| 874 | - podman(&["push", "--tls-verify=false", "localhost/tiny:v1", &target]); | ||
| 875 | - podman(&["rmi", "localhost/tiny:v1"]); | ||
| 876 | - podman(&["pull", "--tls-verify=false", &target]); | ||
| 877 | - let listed = podman(&["images", "--format", "{{.Repository}}:{{.Tag}}"]); | ||
| 878 | - assert!( | ||
| 879 | - listed.contains(&format!("{host}/tahinli/tiny:v1")), | ||
| 880 | - "{listed}" | ||
| 881 | - ); | ||
| 882 | -} | ||
crates/forge-e2e/tests/e2e/packages_e2e.rsdeleted+0 -567
| @@ -1,567 +0,0 @@ | |||
| 1 | -use crate::common::{Server, launch, provision}; | ||
| 2 | -use std::io::Write; | ||
| 3 | -use std::path::Path; | ||
| 4 | -use std::process::Command; | ||
| 5 | -use std::time::Duration; | ||
| 6 | - | ||
| 7 | -use forge_core::packages::{KIND_CARGO, NewPackageVersion}; | ||
| 8 | -use forge_core::token::{generate_token, hash_token}; | ||
| 9 | -use forge_core::{Store, User}; | ||
| 10 | -use sha2::{Digest, Sha256}; | ||
| 11 | - | ||
| 12 | -const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate"; | ||
| 13 | -const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new"; | ||
| 14 | - | ||
| 15 | -struct Resp { | ||
| 16 | - status: u16, | ||
| 17 | - body: Vec<u8>, | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -impl Resp { | ||
| 21 | - fn text(&self) -> String { | ||
| 22 | - String::from_utf8_lossy(&self.body).into_owned() | ||
| 23 | - } | ||
| 24 | - | ||
| 25 | - fn json(&self) -> serde_json::Value { | ||
| 26 | - serde_json::from_slice(&self.body).expect("json body") | ||
| 27 | - } | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -struct Http { | ||
| 31 | - client: reqwest::Client, | ||
| 32 | - base: String, | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -impl Http { | ||
| 36 | - fn new(port: u16) -> Self { | ||
| 37 | - let client = reqwest::Client::builder() | ||
| 38 | - .redirect(reqwest::redirect::Policy::none()) | ||
| 39 | - .timeout(Duration::from_secs(60)) | ||
| 40 | - .build() | ||
| 41 | - .expect("http client"); | ||
| 42 | - Self { | ||
| 43 | - client, | ||
| 44 | - base: format!("http://127.0.0.1:{port}"), | ||
| 45 | - } | ||
| 46 | - } | ||
| 47 | - | ||
| 48 | - async fn call( | ||
| 49 | - &self, | ||
| 50 | - method: reqwest::Method, | ||
| 51 | - path: &str, | ||
| 52 | - auth: Option<&str>, | ||
| 53 | - body: Option<Vec<u8>>, | ||
| 54 | - ) -> Resp { | ||
| 55 | - let mut req = self.client.request(method, format!("{}{path}", self.base)); | ||
| 56 | - if let Some(token) = auth { | ||
| 57 | - req = req.header("Authorization", token); | ||
| 58 | - } | ||
| 59 | - if let Some(bytes) = body { | ||
| 60 | - req = req.body(bytes); | ||
| 61 | - } | ||
| 62 | - let res = req.send().await.expect("http request"); | ||
| 63 | - let status = res.status().as_u16(); | ||
| 64 | - let body = res.bytes().await.expect("read body").to_vec(); | ||
| 65 | - Resp { status, body } | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - async fn get(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 69 | - self.call(reqwest::Method::GET, path, auth, None).await | ||
| 70 | - } | ||
| 71 | - | ||
| 72 | - async fn put(&self, path: &str, auth: Option<&str>, body: Vec<u8>) -> Resp { | ||
| 73 | - self.call(reqwest::Method::PUT, path, auth, Some(body)) | ||
| 74 | - .await | ||
| 75 | - } | ||
| 76 | - | ||
| 77 | - async fn delete(&self, path: &str, auth: Option<&str>) -> Resp { | ||
| 78 | - self.call(reqwest::Method::DELETE, path, auth, None).await | ||
| 79 | - } | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | -struct Env { | ||
| 83 | - _root: tempfile::TempDir, | ||
| 84 | - _server: Server, | ||
| 85 | - http: Http, | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -async fn start<F, Fut>(seed: F) -> Env | ||
| 89 | -where | ||
| 90 | - F: FnOnce(Store) -> Fut, | ||
| 91 | - Fut: std::future::Future<Output = ()>, | ||
| 92 | -{ | ||
| 93 | - let root = crate::common::temp_dir("fpk"); | ||
| 94 | - let dir = root.path().to_path_buf(); | ||
| 95 | - let (_, ports) = provision( | ||
| 96 | - &dir, | ||
| 97 | - "", | ||
| 98 | - &[&["create-user", "tahinli"], &["create-user", "bob"]], | ||
| 99 | - ); | ||
| 100 | - let store = Store::open(&dir.join("forge.db")) | ||
| 101 | - .await | ||
| 102 | - .expect("open store"); | ||
| 103 | - seed(store).await; | ||
| 104 | - let (server, ports) = launch(&dir, ports).await; | ||
| 105 | - Env { | ||
| 106 | - _root: root, | ||
| 107 | - _server: server, | ||
| 108 | - http: Http::new(ports.http), | ||
| 109 | - } | ||
| 110 | -} | ||
| 111 | - | ||
| 112 | -async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) { | ||
| 113 | - let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect(); | ||
| 114 | - store | ||
| 115 | - .create_token(&user.id, "ci", &hash_token(token), &scopes, None) | ||
| 116 | - .await | ||
| 117 | - .expect("create token"); | ||
| 118 | -} | ||
| 119 | - | ||
| 120 | -async fn user(store: &Store, name: &str) -> User { | ||
| 121 | - store | ||
| 122 | - .user_by_username(name) | ||
| 123 | - .await | ||
| 124 | - .expect("lookup user") | ||
| 125 | - .expect("user exists") | ||
| 126 | -} | ||
| 127 | - | ||
| 128 | -fn crate_file(name: &str, version: &str, readme: &str) -> Vec<u8> { | ||
| 129 | - let mut tar_bytes = Vec::new(); | ||
| 130 | - { | ||
| 131 | - let mut builder = tar::Builder::new(&mut tar_bytes); | ||
| 132 | - for (path, body) in [ | ||
| 133 | - ( | ||
| 134 | - format!("{name}-{version}/Cargo.toml"), | ||
| 135 | - format!("[package]\nname = \"{name}\"\n"), | ||
| 136 | - ), | ||
| 137 | - (format!("{name}-{version}/README.md"), readme.to_owned()), | ||
| 138 | - ] { | ||
| 139 | - let mut header = tar::Header::new_gnu(); | ||
| 140 | - header.set_size(body.len() as u64); | ||
| 141 | - header.set_mode(0o644); | ||
| 142 | - header.set_cksum(); | ||
| 143 | - builder | ||
| 144 | - .append_data(&mut header, path, body.as_bytes()) | ||
| 145 | - .expect("append"); | ||
| 146 | - } | ||
| 147 | - builder.finish().expect("finish tar"); | ||
| 148 | - } | ||
| 149 | - let mut gz = Vec::new(); | ||
| 150 | - { | ||
| 151 | - let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast()); | ||
| 152 | - enc.write_all(&tar_bytes).expect("gzip"); | ||
| 153 | - enc.finish().expect("finish gzip"); | ||
| 154 | - } | ||
| 155 | - gz | ||
| 156 | -} | ||
| 157 | - | ||
| 158 | -fn publish_body(meta: &serde_json::Value, krate: &[u8]) -> Vec<u8> { | ||
| 159 | - let json = serde_json::to_vec(meta).expect("metadata json"); | ||
| 160 | - let mut body = Vec::new(); | ||
| 161 | - body.extend_from_slice(&(json.len() as u32).to_le_bytes()); | ||
| 162 | - body.extend_from_slice(&json); | ||
| 163 | - body.extend_from_slice(&(krate.len() as u32).to_le_bytes()); | ||
| 164 | - body.extend_from_slice(krate); | ||
| 165 | - body | ||
| 166 | -} | ||
| 167 | - | ||
| 168 | -fn metadata(name: &str, version: &str) -> serde_json::Value { | ||
| 169 | - serde_json::json!({ | ||
| 170 | - "name": name, | ||
| 171 | - "vers": version, | ||
| 172 | - "deps": [{ | ||
| 173 | - "name": "serde", | ||
| 174 | - "version_req": "^1", | ||
| 175 | - "features": ["derive"], | ||
| 176 | - "optional": false, | ||
| 177 | - "default_features": true, | ||
| 178 | - "target": null, | ||
| 179 | - "kind": "normal", | ||
| 180 | - "registry": null, | ||
| 181 | - "explicit_name_in_toml": null | ||
| 182 | - }], | ||
| 183 | - "features": { "default": ["serde"] }, | ||
| 184 | - "authors": [], | ||
| 185 | - "description": "A demo crate", | ||
| 186 | - "license": "MIT", | ||
| 187 | - "readme": "# Demo\n\nFrom the metadata.", | ||
| 188 | - "keywords": [], | ||
| 189 | - "categories": [], | ||
| 190 | - "badges": {}, | ||
| 191 | - "links": null | ||
| 192 | - }) | ||
| 193 | -} | ||
| 194 | - | ||
| 195 | -fn sha256_hex(bytes: &[u8]) -> String { | ||
| 196 | - hex::encode(Sha256::digest(bytes)) | ||
| 197 | -} | ||
| 198 | - | ||
| 199 | -fn index_line(resp: &Resp) -> serde_json::Value { | ||
| 200 | - let text = resp.text(); | ||
| 201 | - serde_json::from_str(text.trim()).expect("one index line") | ||
| 202 | -} | ||
| 203 | - | ||
| 204 | -#[tokio::test] | ||
| 205 | -async fn config_json_points_at_the_owner_registry() { | ||
| 206 | - let env = start(|_| async {}).await; | ||
| 207 | - let res = env | ||
| 208 | - .http | ||
| 209 | - .get("/api/packages/tahinli/cargo/config.json", None) | ||
| 210 | - .await; | ||
| 211 | - assert_eq!(res.status, 200, "{}", res.text()); | ||
| 212 | - let json = res.json(); | ||
| 213 | - let dl = json["dl"].as_str().expect("dl"); | ||
| 214 | - let api = json["api"].as_str().expect("api"); | ||
| 215 | - assert!( | ||
| 216 | - dl.ends_with("/api/packages/tahinli/cargo/download/{crate}/{version}"), | ||
| 217 | - "{dl}" | ||
| 218 | - ); | ||
| 219 | - assert!(api.ends_with("/api/packages/tahinli/cargo"), "{api}"); | ||
| 220 | - assert_eq!(json["auth-required"], false); | ||
| 221 | -} | ||
| 222 | - | ||
| 223 | -#[tokio::test] | ||
| 224 | -async fn publish_index_download_and_checksum_round_trip() { | ||
| 225 | - let token = generate_token(); | ||
| 226 | - let seeded = token.clone(); | ||
| 227 | - let env = start(move |store| async move { | ||
| 228 | - let tahinli = user(&store, "tahinli").await; | ||
| 229 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 230 | - }) | ||
| 231 | - .await; | ||
| 232 | - let krate = crate_file("demo-crate", "0.1.0", "# Demo\n\nHello from the README."); | ||
| 233 | - let body = publish_body(&metadata("demo-crate", "0.1.0"), &krate); | ||
| 234 | - | ||
| 235 | - let res = env.http.put(PUBLISH, Some(&token), body.clone()).await; | ||
| 236 | - assert_eq!(res.status, 200, "{}", res.text()); | ||
| 237 | - assert!(res.json()["warnings"].is_object()); | ||
| 238 | - | ||
| 239 | - let index = env.http.get(DEMO_INDEX, None).await; | ||
| 240 | - assert_eq!(index.status, 200, "{}", index.text()); | ||
| 241 | - let line = index_line(&index); | ||
| 242 | - assert_eq!(line["name"], "demo-crate"); | ||
| 243 | - assert_eq!(line["vers"], "0.1.0"); | ||
| 244 | - assert_eq!(line["v"], 2); | ||
| 245 | - assert_eq!(line["yanked"], false); | ||
| 246 | - assert_eq!(line["deps"][0]["name"], "serde"); | ||
| 247 | - assert_eq!(line["features"]["default"], serde_json::json!(["serde"])); | ||
| 248 | - let cksum = line["cksum"].as_str().expect("cksum").to_owned(); | ||
| 249 | - assert_eq!(cksum, sha256_hex(&krate)); | ||
| 250 | - | ||
| 251 | - let download = env | ||
| 252 | - .http | ||
| 253 | - .get( | ||
| 254 | - "/api/packages/tahinli/cargo/download/demo-crate/0.1.0", | ||
| 255 | - None, | ||
| 256 | - ) | ||
| 257 | - .await; | ||
| 258 | - assert_eq!(download.status, 200); | ||
| 259 | - assert_eq!( | ||
| 260 | - sha256_hex(&download.body), | ||
| 261 | - cksum, | ||
| 262 | - "downloaded bytes match the index checksum" | ||
| 263 | - ); | ||
| 264 | - assert_eq!(download.body, krate); | ||
| 265 | - | ||
| 266 | - let duplicate = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 267 | - assert_eq!(duplicate.status, 409, "{}", duplicate.text()); | ||
| 268 | - let detail = duplicate.json()["errors"][0]["detail"] | ||
| 269 | - .as_str() | ||
| 270 | - .unwrap_or_default() | ||
| 271 | - .to_owned(); | ||
| 272 | - assert!(detail.contains("already uploaded"), "{detail}"); | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -#[tokio::test] | ||
| 276 | -async fn publish_needs_a_packages_token_with_write_access() { | ||
| 277 | - let repo_only = generate_token(); | ||
| 278 | - let bob_token = generate_token(); | ||
| 279 | - let (seeded_repo_only, seeded_bob) = (repo_only.clone(), bob_token.clone()); | ||
| 280 | - let env = start(move |store| async move { | ||
| 281 | - let tahinli = user(&store, "tahinli").await; | ||
| 282 | - let bob = user(&store, "bob").await; | ||
| 283 | - grant(&store, &tahinli, &["repo"], &seeded_repo_only).await; | ||
| 284 | - grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 285 | - }) | ||
| 286 | - .await; | ||
| 287 | - let body = publish_body( | ||
| 288 | - &metadata("demo-crate", "0.1.0"), | ||
| 289 | - &crate_file("demo-crate", "0.1.0", "x"), | ||
| 290 | - ); | ||
| 291 | - | ||
| 292 | - let anonymous = env.http.put(PUBLISH, None, body.clone()).await; | ||
| 293 | - assert_eq!(anonymous.status, 401, "{}", anonymous.text()); | ||
| 294 | - | ||
| 295 | - let no_scope = env.http.put(PUBLISH, Some(&repo_only), body.clone()).await; | ||
| 296 | - assert_eq!(no_scope.status, 403, "{}", no_scope.text()); | ||
| 297 | - assert!( | ||
| 298 | - no_scope.json()["errors"][0]["detail"] | ||
| 299 | - .as_str() | ||
| 300 | - .unwrap_or_default() | ||
| 301 | - .contains("packages scope") | ||
| 302 | - ); | ||
| 303 | - | ||
| 304 | - let stranger = env.http.put(PUBLISH, Some(&bob_token), body).await; | ||
| 305 | - assert_eq!(stranger.status, 403, "{}", stranger.text()); | ||
| 306 | -} | ||
| 307 | - | ||
| 308 | -#[tokio::test] | ||
| 309 | -async fn invalid_names_and_versions_are_400_with_cargo_errors() { | ||
| 310 | - let token = generate_token(); | ||
| 311 | - let seeded = token.clone(); | ||
| 312 | - let env = start(move |store| async move { | ||
| 313 | - let tahinli = user(&store, "tahinli").await; | ||
| 314 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 315 | - }) | ||
| 316 | - .await; | ||
| 317 | - let bad_name = publish_body( | ||
| 318 | - &metadata("1bad name", "0.1.0"), | ||
| 319 | - &crate_file("1bad", "0.1.0", "x"), | ||
| 320 | - ); | ||
| 321 | - let res = env.http.put(PUBLISH, Some(&token), bad_name).await; | ||
| 322 | - assert_eq!(res.status, 400, "{}", res.text()); | ||
| 323 | - assert!(res.json()["errors"][0]["detail"].is_string()); | ||
| 324 | - | ||
| 325 | - let bad_version = publish_body( | ||
| 326 | - &metadata("demo-crate", "one"), | ||
| 327 | - &crate_file("demo-crate", "0.1.0", "x"), | ||
| 328 | - ); | ||
| 329 | - let res = env.http.put(PUBLISH, Some(&token), bad_version).await; | ||
| 330 | - assert_eq!(res.status, 400, "{}", res.text()); | ||
| 331 | - | ||
| 332 | - let garbage = env | ||
| 333 | - .http | ||
| 334 | - .put(PUBLISH, Some(&token), b"not a publish body".to_vec()) | ||
| 335 | - .await; | ||
| 336 | - assert_eq!(garbage.status, 400, "{}", garbage.text()); | ||
| 337 | -} | ||
| 338 | - | ||
| 339 | -#[tokio::test] | ||
| 340 | -async fn yank_marks_the_version_and_unyank_restores_it() { | ||
| 341 | - let token = generate_token(); | ||
| 342 | - let seeded = token.clone(); | ||
| 343 | - let env = start(move |store| async move { | ||
| 344 | - let tahinli = user(&store, "tahinli").await; | ||
| 345 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 346 | - }) | ||
| 347 | - .await; | ||
| 348 | - let body = publish_body( | ||
| 349 | - &metadata("demo-crate", "0.1.0"), | ||
| 350 | - &crate_file("demo-crate", "0.1.0", "x"), | ||
| 351 | - ); | ||
| 352 | - let publish = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 353 | - assert_eq!(publish.status, 200, "{}", publish.text()); | ||
| 354 | - | ||
| 355 | - let yank = "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/0.1.0/yank"; | ||
| 356 | - let yanked = env.http.delete(yank, Some(&token)).await; | ||
| 357 | - assert_eq!(yanked.status, 200, "{}", yanked.text()); | ||
| 358 | - assert_eq!( | ||
| 359 | - index_line(&env.http.get(DEMO_INDEX, None).await)["yanked"], | ||
| 360 | - true | ||
| 361 | - ); | ||
| 362 | - let download = env | ||
| 363 | - .http | ||
| 364 | - .get( | ||
| 365 | - "/api/packages/tahinli/cargo/download/demo-crate/0.1.0", | ||
| 366 | - None, | ||
| 367 | - ) | ||
| 368 | - .await; | ||
| 369 | - assert_eq!(download.status, 200, "a yanked version still downloads"); | ||
| 370 | - | ||
| 371 | - let unyank = "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/0.1.0/unyank"; | ||
| 372 | - let restored = env.http.put(unyank, Some(&token), Vec::new()).await; | ||
| 373 | - assert_eq!(restored.status, 200, "{}", restored.text()); | ||
| 374 | - assert_eq!( | ||
| 375 | - index_line(&env.http.get(DEMO_INDEX, None).await)["yanked"], | ||
| 376 | - false | ||
| 377 | - ); | ||
| 378 | - | ||
| 379 | - let missing = env | ||
| 380 | - .http | ||
| 381 | - .delete( | ||
| 382 | - "/api/packages/tahinli/cargo/api/v1/crates/demo-crate/9.9.9/yank", | ||
| 383 | - Some(&token), | ||
| 384 | - ) | ||
| 385 | - .await; | ||
| 386 | - assert_eq!(missing.status, 404); | ||
| 387 | -} | ||
| 388 | - | ||
| 389 | -#[tokio::test] | ||
| 390 | -async fn private_packages_need_a_token_and_the_owner_to_read() { | ||
| 391 | - let owner_token = generate_token(); | ||
| 392 | - let bob_token = generate_token(); | ||
| 393 | - let (seeded_owner, seeded_bob) = (owner_token.clone(), bob_token.clone()); | ||
| 394 | - let env = start(move |store| async move { | ||
| 395 | - let tahinli = user(&store, "tahinli").await; | ||
| 396 | - let bob = user(&store, "bob").await; | ||
| 397 | - grant(&store, &tahinli, &["packages"], &seeded_owner).await; | ||
| 398 | - grant(&store, &bob, &["packages"], &seeded_bob).await; | ||
| 399 | - let package = store | ||
| 400 | - .ensure_package(&tahinli.id, KIND_CARGO, "Secret-Crate", "secret-crate") | ||
| 401 | - .await | ||
| 402 | - .expect("package"); | ||
| 403 | - store | ||
| 404 | - .set_package_private(&package.id, true) | ||
| 405 | - .await | ||
| 406 | - .expect("private"); | ||
| 407 | - store | ||
| 408 | - .publish_package_version(&NewPackageVersion { | ||
| 409 | - package_id: &package.id, | ||
| 410 | - version: "0.1.0", | ||
| 411 | - checksum: "00", | ||
| 412 | - size: 0, | ||
| 413 | - index_json: r#"{"name":"Secret-Crate","vers":"0.1.0","deps":[],"cksum":"00","features":{},"yanked":false,"links":null,"v":2}"#, | ||
| 414 | - description: Some("Hidden"), | ||
| 415 | - readme: None, | ||
| 416 | - publisher_id: &tahinli.id, | ||
| 417 | - }) | ||
| 418 | - .await | ||
| 419 | - .expect("version"); | ||
| 420 | - }) | ||
| 421 | - .await; | ||
| 422 | - let index = "/api/packages/tahinli/cargo/se/cr/secret-crate"; | ||
| 423 | - | ||
| 424 | - assert_eq!(env.http.get(index, None).await.status, 404, "anonymous"); | ||
| 425 | - assert_eq!( | ||
| 426 | - env.http.get(index, Some(&bob_token)).await.status, | ||
| 427 | - 404, | ||
| 428 | - "another user" | ||
| 429 | - ); | ||
| 430 | - assert_eq!( | ||
| 431 | - env.http.get(index, Some(&owner_token)).await.status, | ||
| 432 | - 200, | ||
| 433 | - "the owner" | ||
| 434 | - ); | ||
| 435 | - | ||
| 436 | - let config = env | ||
| 437 | - .http | ||
| 438 | - .get("/api/packages/tahinli/cargo/config.json", None) | ||
| 439 | - .await; | ||
| 440 | - assert_eq!( | ||
| 441 | - config.json()["auth-required"], | ||
| 442 | - true, | ||
| 443 | - "a private package needs auth" | ||
| 444 | - ); | ||
| 445 | - | ||
| 446 | - let profile = env.http.get("/tahinli?tab=packages", None).await; | ||
| 447 | - assert_eq!(profile.status, 200); | ||
| 448 | - assert!( | ||
| 449 | - !profile.text().contains("secret-crate"), | ||
| 450 | - "private packages stay off the public tab" | ||
| 451 | - ); | ||
| 452 | - let page = env.http.get("/tahinli/-/packages/secret-crate", None).await; | ||
| 453 | - assert_eq!( | ||
| 454 | - page.status, 404, | ||
| 455 | - "the private package page is hidden from anonymous readers" | ||
| 456 | - ); | ||
| 457 | -} | ||
| 458 | - | ||
| 459 | -#[tokio::test] | ||
| 460 | -async fn profile_tab_and_package_page_show_the_published_crate() { | ||
| 461 | - let token = generate_token(); | ||
| 462 | - let seeded = token.clone(); | ||
| 463 | - let env = start(move |store| async move { | ||
| 464 | - let tahinli = user(&store, "tahinli").await; | ||
| 465 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 466 | - }) | ||
| 467 | - .await; | ||
| 468 | - let body = publish_body( | ||
| 469 | - &metadata("demo-crate", "0.1.0"), | ||
| 470 | - &crate_file("demo-crate", "0.1.0", "# Demo\n\nHello."), | ||
| 471 | - ); | ||
| 472 | - let publish = env.http.put(PUBLISH, Some(&token), body).await; | ||
| 473 | - assert_eq!(publish.status, 200, "{}", publish.text()); | ||
| 474 | - | ||
| 475 | - let tab = env.http.get("/tahinli?tab=packages", None).await; | ||
| 476 | - assert_eq!(tab.status, 200); | ||
| 477 | - assert!( | ||
| 478 | - tab.text().contains("demo-crate"), | ||
| 479 | - "the Packages tab lists the crate" | ||
| 480 | - ); | ||
| 481 | - | ||
| 482 | - let page = env.http.get("/tahinli/-/packages/demo-crate", None).await; | ||
| 483 | - assert_eq!(page.status, 200); | ||
| 484 | - let html = page.text(); | ||
| 485 | - assert!( | ||
| 486 | - html.contains("cargo add --registry tahinli demo-crate"), | ||
| 487 | - "install snippet" | ||
| 488 | - ); | ||
| 489 | - assert!( | ||
| 490 | - html.contains("sparse+http://127.0.0.1:"), | ||
| 491 | - "registry index in the config block" | ||
| 492 | - ); | ||
| 493 | - assert!(html.contains("data-copy=\"pkg-config\""), "copy button"); | ||
| 494 | - assert!(html.contains("Hello."), "README rendered"); | ||
| 495 | - assert!(html.contains("data-live="), "the page follows live changes"); | ||
| 496 | -} | ||
| 497 | - | ||
| 498 | -#[tokio::test] | ||
| 499 | -#[ignore = "runs the real cargo binary; run with --ignored"] | ||
| 500 | -async fn real_cargo_publishes_and_fetches_from_the_registry() { | ||
| 501 | - let token = generate_token(); | ||
| 502 | - let seeded = token.clone(); | ||
| 503 | - let env = start(move |store| async move { | ||
| 504 | - let tahinli = user(&store, "tahinli").await; | ||
| 505 | - grant(&store, &tahinli, &["packages"], &seeded).await; | ||
| 506 | - }) | ||
| 507 | - .await; | ||
| 508 | - let index = format!("sparse+{}/api/packages/tahinli/cargo/", env.http.base); | ||
| 509 | - let work = tempfile::tempdir().expect("work dir"); | ||
| 510 | - let cargo_home = work.path().join("home"); | ||
| 511 | - let cargo_home = cargo_home.to_str().expect("utf8 path").to_owned(); | ||
| 512 | - let envs = [ | ||
| 513 | - ("CARGO_HOME", cargo_home.as_str()), | ||
| 514 | - ("CARGO_REGISTRIES_LOCAL_INDEX", index.as_str()), | ||
| 515 | - ("CARGO_REGISTRIES_LOCAL_TOKEN", token.as_str()), | ||
| 516 | - ]; | ||
| 517 | - | ||
| 518 | - let krate = work.path().join("real-demo"); | ||
| 519 | - std::fs::create_dir_all(krate.join("src")).expect("crate dir"); | ||
| 520 | - std::fs::write( | ||
| 521 | - krate.join("Cargo.toml"), | ||
| 522 | - "[package]\nname = \"real-demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\ | ||
| 523 | - description = \"Real cargo smoke test\"\nlicense = \"MIT\"\n", | ||
| 524 | - ) | ||
| 525 | - .expect("manifest"); | ||
| 526 | - std::fs::write(krate.join("src/lib.rs"), "pub fn hi() -> u8 { 7 }\n").expect("lib"); | ||
| 527 | - std::fs::write(krate.join("README.md"), "# real-demo\n").expect("readme"); | ||
| 528 | - run_cargo( | ||
| 529 | - &krate, | ||
| 530 | - &[ | ||
| 531 | - "publish", | ||
| 532 | - "--registry", | ||
| 533 | - "local", | ||
| 534 | - "--no-verify", | ||
| 535 | - "--allow-dirty", | ||
| 536 | - ], | ||
| 537 | - &envs, | ||
| 538 | - ); | ||
| 539 | - | ||
| 540 | - let consumer = work.path().join("consumer"); | ||
| 541 | - std::fs::create_dir_all(consumer.join("src")).expect("consumer dir"); | ||
| 542 | - std::fs::write( | ||
| 543 | - consumer.join("Cargo.toml"), | ||
| 544 | - "[package]\nname = \"consumer\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\ | ||
| 545 | - [dependencies]\nreal-demo = { version = \"0.1.0\", registry = \"local\" }\n", | ||
| 546 | - ) | ||
| 547 | - .expect("consumer manifest"); | ||
| 548 | - std::fs::write(consumer.join("src/main.rs"), "fn main() {}\n").expect("main"); | ||
| 549 | - let fetched = run_cargo(&consumer, &["fetch"], &envs); | ||
| 550 | - assert!(fetched.contains("real-demo v0.1.0"), "{fetched}"); | ||
| 551 | -} | ||
| 552 | - | ||
| 553 | -fn run_cargo(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> String { | ||
| 554 | - let out = Command::new("cargo") | ||
| 555 | - .args(args) | ||
| 556 | - .current_dir(dir) | ||
| 557 | - .envs(envs.iter().copied()) | ||
| 558 | - .output() | ||
| 559 | - .expect("run cargo"); | ||
| 560 | - let text = format!( | ||
| 561 | - "{}{}", | ||
| 562 | - String::from_utf8_lossy(&out.stdout), | ||
| 563 | - String::from_utf8_lossy(&out.stderr) | ||
| 564 | - ); | ||
| 565 | - assert!(out.status.success(), "cargo {args:?} failed:\n{text}"); | ||
| 566 | - text | ||
| 567 | -} | ||
crates/forge-web-account/src/pages/audit_log.rsmodified+1 -1
| @@ -178,7 +178,7 @@ fn action_words(action: &str) -> String { | |||
| 178 | .split('_') | 178 | .split('_') |
| 179 | .enumerate() | 179 | .enumerate() |
| 180 | .map(|(i, word)| match word { | 180 | .map(|(i, word)| match word { |
| 181 | - "ci" | "ui" | "ip" | "ssh" | "gpg" | "oci" | "totp" | "2fa" | "api" | "pat" => { | 181 | + "ci" | "ui" | "ip" | "ssh" | "gpg" | "totp" | "2fa" | "api" | "pat" => { |
| 182 | word.to_uppercase() | 182 | word.to_uppercase() |
| 183 | } | 183 | } |
| 184 | _ if i == 0 => { | 184 | _ if i == 0 => { |
crates/forge-web-account/src/pages/org_ctx.rsmodified+2 -8
| @@ -9,7 +9,6 @@ use topcoat::view::{View, component, view}; | |||
| 9 | use crate::auth::{check_csrf, require_user}; | 9 | use crate::auth::{check_csrf, require_user}; |
| 10 | use crate::i18n::Lang; | 10 | use crate::i18n::Lang; |
| 11 | use crate::i18n::orgs::{self as g, K}; | 11 | use crate::i18n::orgs::{self as g, K}; |
| 12 | -use crate::pages::packages; | ||
| 13 | use crate::state::AppState; | 12 | use crate::state::AppState; |
| 14 | use crate::views::{notice_line, profile_items, query_value}; | 13 | use crate::views::{notice_line, profile_items, query_value}; |
| 15 | 14 | ||
| @@ -145,15 +144,12 @@ pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { | |||
| 145 | .map(|(_, key, is_error)| (g::t(lang, *key), *is_error)) | 144 | .map(|(_, key, is_error)| (g::t(lang, *key), *is_error)) |
| 146 | } | 145 | } |
| 147 | 146 | ||
| 148 | -pub async fn org_tab_counts(state: &AppState, org: &User, viewer: &User) -> Result<(u64, usize)> { | 147 | +pub async fn org_repo_count(state: &AppState, org: &User, viewer: &User) -> Result<u64> { |
| 149 | let repos = state | 148 | let repos = state |
| 150 | .store | 149 | .store |
| 151 | .count_visible_repos(RepoScope::OwnedBy(&org.id), Some(viewer)) | 150 | .count_visible_repos(RepoScope::OwnedBy(&org.id), Some(viewer)) |
| 152 | .await?; | 151 | .await?; |
| 153 | - let packages = packages::package_rows(state, Some(viewer), org) | 152 | + Ok(repos) |
| 154 | - .await? | ||
| 155 | - .len(); | ||
| 156 | - Ok((repos, packages)) | ||
| 157 | } | 153 | } |
| 158 | 154 | ||
| 159 | #[component] | 155 | #[component] |
| @@ -164,7 +160,6 @@ pub async fn org_tabs( | |||
| 164 | current: String, | 160 | current: String, |
| 165 | owner: bool, | 161 | owner: bool, |
| 166 | repo_count: u64, | 162 | repo_count: u64, |
| 167 | - package_count: usize, | ||
| 168 | ) -> Result<impl View> { | 163 | ) -> Result<impl View> { |
| 169 | let mut tabs: Vec<(String, String, bool, Option<String>)> = | 164 | let mut tabs: Vec<(String, String, bool, Option<String>)> = |
| 170 | profile_items(lang, &name, true, false, true) | 165 | profile_items(lang, &name, true, false, true) |
| @@ -172,7 +167,6 @@ pub async fn org_tabs( | |||
| 172 | .map(|item| { | 167 | .map(|item| { |
| 173 | let count = match item.key { | 168 | let count = match item.key { |
| 174 | "repositories" => Some(repo_count.to_string()), | 169 | "repositories" => Some(repo_count.to_string()), |
| 175 | - "packages" => Some(package_count.to_string()), | ||
| 176 | _ => None, | 170 | _ => None, |
| 177 | }; | 171 | }; |
| 178 | (item.href, item.label.to_owned(), item.key == current, count) | 172 | (item.href, item.label.to_owned(), item.key == current, count) |
crates/forge-web-account/src/pages/org_members.rsmodified+4 -5
| @@ -12,7 +12,7 @@ use crate::audit::{self, Actor, Target}; | |||
| 12 | use crate::i18n::orgs::{self as g, K}; | 12 | use crate::i18n::orgs::{self as g, K}; |
| 13 | use crate::i18n::{self, Lang}; | 13 | use crate::i18n::{self, Lang}; |
| 14 | use crate::pages::org_ctx::{ | 14 | use crate::pages::org_ctx::{ |
| 15 | - load_org, notice_href, org_notice, org_tab_counts, org_tabs, require_form_csrf, require_member, | 15 | + load_org, notice_href, org_notice, org_repo_count, org_tabs, require_form_csrf, require_member, |
| 16 | require_owner, take_notice, | 16 | require_owner, take_notice, |
| 17 | }; | 17 | }; |
| 18 | use crate::state::AppState; | 18 | use crate::state::AppState; |
| @@ -62,7 +62,6 @@ async fn members_body( | |||
| 62 | lang: Lang, | 62 | lang: Lang, |
| 63 | live: String, | 63 | live: String, |
| 64 | repo_count: u64, | 64 | repo_count: u64, |
| 65 | - package_count: usize, | ||
| 66 | ) -> Result<impl View> { | 65 | ) -> Result<impl View> { |
| 67 | let sub = if description.is_empty() { | 66 | let sub = if description.is_empty() { |
| 68 | Vec::new() | 67 | Vec::new() |
| @@ -95,7 +94,7 @@ async fn members_body( | |||
| 95 | }; | 94 | }; |
| 96 | Ok(view! { | 95 | Ok(view! { |
| 97 | head(title: name.as_str(), sub: sub, live: Some(live.as_str())) | 96 | head(title: name.as_str(), sub: sub, live: Some(live.as_str())) |
| 98 | - org_tabs(lang: lang, name: name.clone(), current: "members".to_owned(), owner: owner, repo_count: repo_count, package_count: package_count) | 97 | + org_tabs(lang: lang, name: name.clone(), current: "members".to_owned(), owner: owner, repo_count: repo_count) |
| 99 | org_notice(notice: notice) | 98 | org_notice(notice: notice) |
| 100 | <div class="sheet"> | 99 | <div class="sheet"> |
| 101 | people_list(list: list) | 100 | people_list(list: list) |
| @@ -143,12 +142,12 @@ async fn org_members_page(cx: &Cx) -> Result<impl View> { | |||
| 143 | let base = ctx.href(""); | 142 | let base = ctx.href(""); |
| 144 | let csrf = ctx.viewer.1.csrf_token.clone(); | 143 | let csrf = ctx.viewer.1.csrf_token.clone(); |
| 145 | let live = ctx.href("/members/events"); | 144 | let live = ctx.href("/members/events"); |
| 146 | - let (repo_count, package_count) = org_tab_counts(state, &ctx.org, &ctx.viewer.0).await?; | 145 | + let repo_count = org_repo_count(state, &ctx.org, &ctx.viewer.0).await?; |
| 147 | Ok(view! { | 146 | Ok(view! { |
| 148 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), | 147 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), |
| 149 | members_body(name: name, description: description, base: base, owner: owner, | 148 | members_body(name: name, description: description, base: base, owner: owner, |
| 150 | rows: rows, csrf: csrf, notice: notice, lang: lang, live: live, | 149 | rows: rows, csrf: csrf, notice: notice, lang: lang, live: live, |
| 151 | - repo_count: repo_count, package_count: package_count)) | 150 | + repo_count: repo_count)) |
| 152 | }) | 151 | }) |
| 153 | } | 152 | } |
| 154 | 153 | ||
crates/forge-web-account/src/pages/org_settings.rsmodified+4 -5
| @@ -15,7 +15,7 @@ use crate::i18n::orgs::{self as g, K}; | |||
| 15 | use crate::i18n::{self, Key, Lang, t}; | 15 | use crate::i18n::{self, Key, Lang, t}; |
| 16 | use crate::live::Topic; | 16 | use crate::live::Topic; |
| 17 | use crate::pages::org_ctx::{ | 17 | use crate::pages::org_ctx::{ |
| 18 | - DEFAULT_ROLES, MAX_DESCRIPTION_CHARS, load_org, notice_href, org_notice, org_tab_counts, | 18 | + DEFAULT_ROLES, MAX_DESCRIPTION_CHARS, load_org, notice_href, org_notice, org_repo_count, |
| 19 | org_tabs, require_form_csrf, require_owner, take_notice, | 19 | org_tabs, require_form_csrf, require_owner, take_notice, |
| 20 | }; | 20 | }; |
| 21 | use crate::pages::settings_profile::store_avatar; | 21 | use crate::pages::settings_profile::store_avatar; |
| @@ -63,7 +63,6 @@ async fn settings_body( | |||
| 63 | lang: Lang, | 63 | lang: Lang, |
| 64 | live: String, | 64 | live: String, |
| 65 | repo_count: u64, | 65 | repo_count: u64, |
| 66 | - package_count: usize, | ||
| 67 | ) -> Result<impl View> { | 66 | ) -> Result<impl View> { |
| 68 | let save_action = format!("{base}/settings"); | 67 | let save_action = format!("{base}/settings"); |
| 69 | let avatar_action = format!("{base}/settings/avatar"); | 68 | let avatar_action = format!("{base}/settings/avatar"); |
| @@ -72,7 +71,7 @@ async fn settings_body( | |||
| 72 | let confirm_label = g::type_to_confirm(lang, &name); | 71 | let confirm_label = g::type_to_confirm(lang, &name); |
| 73 | Ok(view! { | 72 | Ok(view! { |
| 74 | head(title: name.as_str(), live: Some(live.as_str())) | 73 | head(title: name.as_str(), live: Some(live.as_str())) |
| 75 | - org_tabs(lang: lang, name: name.clone(), current: "settings".to_owned(), owner: true, repo_count: repo_count, package_count: package_count) | 74 | + org_tabs(lang: lang, name: name.clone(), current: "settings".to_owned(), owner: true, repo_count: repo_count) |
| 76 | org_notice(notice: notice) | 75 | org_notice(notice: notice) |
| 77 | <div class="sheet"> | 76 | <div class="sheet"> |
| 78 | <form id="org-settings-form" method="post" action=(save_action.as_str())> | 77 | <form id="org-settings-form" method="post" action=(save_action.as_str())> |
| @@ -169,13 +168,13 @@ async fn org_settings_page(cx: &Cx) -> Result<impl View> { | |||
| 169 | let base = ctx.href(""); | 168 | let base = ctx.href(""); |
| 170 | let csrf = ctx.viewer.1.csrf_token.clone(); | 169 | let csrf = ctx.viewer.1.csrf_token.clone(); |
| 171 | let live = ctx.href("/settings/events"); | 170 | let live = ctx.href("/settings/events"); |
| 172 | - let (repo_count, package_count) = org_tab_counts(state, &ctx.org, &ctx.viewer.0).await?; | 171 | + let repo_count = org_repo_count(state, &ctx.org, &ctx.viewer.0).await?; |
| 173 | Ok(view! { | 172 | Ok(view! { |
| 174 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), | 173 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), |
| 175 | settings_body(name: name, display_name: display_name, description: description, | 174 | settings_body(name: name, display_name: display_name, description: description, |
| 176 | has_avatar: has_avatar, avatar_src: avatar_src, base: base, csrf: csrf, | 175 | has_avatar: has_avatar, avatar_src: avatar_src, base: base, csrf: csrf, |
| 177 | default_role: default_role, members_can_create: members_can_create, notice: notice, lang: lang, live: live, | 176 | default_role: default_role, members_can_create: members_can_create, notice: notice, lang: lang, live: live, |
| 178 | - repo_count: repo_count, package_count: package_count)) | 177 | + repo_count: repo_count)) |
| 179 | }) | 178 | }) |
| 180 | } | 179 | } |
| 181 | 180 | ||
crates/forge-web-account/src/pages/org_teams.rsmodified+6 -9
| @@ -13,7 +13,7 @@ use crate::auth::CsrfForm; | |||
| 13 | use crate::i18n::orgs::{self as g, K}; | 13 | use crate::i18n::orgs::{self as g, K}; |
| 14 | use crate::i18n::{self, Lang}; | 14 | use crate::i18n::{self, Lang}; |
| 15 | use crate::pages::org_ctx::{ | 15 | use crate::pages::org_ctx::{ |
| 16 | - OrgCtx, TEAM_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs, | 16 | + OrgCtx, TEAM_ROLES, load_org, notice_href, org_notice, org_repo_count, org_tabs, |
| 17 | require_form_csrf, require_member, require_owner, take_notice, | 17 | require_form_csrf, require_member, require_owner, take_notice, |
| 18 | }; | 18 | }; |
| 19 | use crate::state::AppState; | 19 | use crate::state::AppState; |
| @@ -103,7 +103,6 @@ struct TeamPage { | |||
| 103 | repos: Vec<TeamRepoRow>, | 103 | repos: Vec<TeamRepoRow>, |
| 104 | choices: Vec<RepoChoice>, | 104 | choices: Vec<RepoChoice>, |
| 105 | repo_count: u64, | 105 | repo_count: u64, |
| 106 | - package_count: usize, | ||
| 107 | } | 106 | } |
| 108 | 107 | ||
| 109 | fn parse_team_role(word: &str) -> Option<Role> { | 108 | fn parse_team_role(word: &str) -> Option<Role> { |
| @@ -167,7 +166,6 @@ async fn teams_body( | |||
| 167 | lang: Lang, | 166 | lang: Lang, |
| 168 | live: String, | 167 | live: String, |
| 169 | repo_count: u64, | 168 | repo_count: u64, |
| 170 | - package_count: usize, | ||
| 171 | ) -> Result<impl View> { | 169 | ) -> Result<impl View> { |
| 172 | let create_action = format!("{base}/teams/new"); | 170 | let create_action = format!("{base}/teams/new"); |
| 173 | let sub = if description.is_empty() { | 171 | let sub = if description.is_empty() { |
| @@ -177,7 +175,7 @@ async fn teams_body( | |||
| 177 | }; | 175 | }; |
| 178 | Ok(view! { | 176 | Ok(view! { |
| 179 | head(title: name.as_str(), sub: sub, live: Some(live.as_str())) | 177 | head(title: name.as_str(), sub: sub, live: Some(live.as_str())) |
| 180 | - org_tabs(lang: lang, name: name.clone(), current: "teams".to_owned(), owner: owner, repo_count: repo_count, package_count: package_count) | 178 | + org_tabs(lang: lang, name: name.clone(), current: "teams".to_owned(), owner: owner, repo_count: repo_count) |
| 181 | org_notice(notice: notice) | 179 | org_notice(notice: notice) |
| 182 | <div class="sheet"> | 180 | <div class="sheet"> |
| 183 | <div class="sheet-tools"> | 181 | <div class="sheet-tools"> |
| @@ -254,12 +252,12 @@ async fn org_teams_page(cx: &Cx) -> Result<impl View> { | |||
| 254 | let base = ctx.href(""); | 252 | let base = ctx.href(""); |
| 255 | let csrf = ctx.viewer.1.csrf_token.clone(); | 253 | let csrf = ctx.viewer.1.csrf_token.clone(); |
| 256 | let live = ctx.href("/teams/events"); | 254 | let live = ctx.href("/teams/events"); |
| 257 | - let (repo_count, package_count) = org_tab_counts(state, &ctx.org, &ctx.viewer.0).await?; | 255 | + let repo_count = org_repo_count(state, &ctx.org, &ctx.viewer.0).await?; |
| 258 | Ok(view! { | 256 | Ok(view! { |
| 259 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), | 257 | shell(title: title.as_str(), viewer: Some(&ctx.viewer), |
| 260 | teams_body(name: name, description: description, base: base, owner: owner, | 258 | teams_body(name: name, description: description, base: base, owner: owner, |
| 261 | csrf: csrf, rows: rows, notice: notice, lang: lang, live: live, | 259 | csrf: csrf, rows: rows, notice: notice, lang: lang, live: live, |
| 262 | - repo_count: repo_count, package_count: package_count)) | 260 | + repo_count: repo_count)) |
| 263 | }) | 261 | }) |
| 264 | } | 262 | } |
| 265 | 263 | ||
| @@ -291,7 +289,7 @@ async fn team_body( | |||
| 291 | } | 289 | } |
| 292 | Ok(view! { | 290 | Ok(view! { |
| 293 | head(title: data.team_name.as_str(), sub: sub, live: Some(data.live.as_str())) | 291 | head(title: data.team_name.as_str(), sub: sub, live: Some(data.live.as_str())) |
| 294 | - org_tabs(lang: lang, name: data.org_name.clone(), current: "teams".to_owned(), owner: owner, repo_count: data.repo_count, package_count: data.package_count) | 292 | + org_tabs(lang: lang, name: data.org_name.clone(), current: "teams".to_owned(), owner: owner, repo_count: data.repo_count) |
| 295 | org_notice(notice: notice) | 293 | org_notice(notice: notice) |
| 296 | <div class="sheet"> | 294 | <div class="sheet"> |
| 297 | <section class="sec"> | 295 | <section class="sec"> |
| @@ -447,10 +445,9 @@ async fn org_team_page(cx: &Cx) -> Result<impl View> { | |||
| 447 | }) | 445 | }) |
| 448 | .collect(); | 446 | .collect(); |
| 449 | let title = format!("{} \u{b7} {}", ctx.org.username, team.name); | 447 | let title = format!("{} \u{b7} {}", ctx.org.username, team.name); |
| 450 | - let (repo_count, package_count) = org_tab_counts(state, &ctx.org, &ctx.viewer.0).await?; | 448 | + let repo_count = org_repo_count(state, &ctx.org, &ctx.viewer.0).await?; |
| 451 | let data = TeamPage { | 449 | let data = TeamPage { |
| 452 | repo_count, | 450 | repo_count, |
| 453 | - package_count, | ||
| 454 | org_name: ctx.org.username.clone(), | 451 | org_name: ctx.org.username.clone(), |
| 455 | base: ctx.href(&format!("/teams/{}", team.id)), | 452 | base: ctx.href(&format!("/teams/{}", team.id)), |
| 456 | live: ctx.href(&format!("/teams/{}/events", team.id)), | 453 | live: ctx.href(&format!("/teams/{}/events", team.id)), |
crates/forge-web-account/src/pages/profile.rsmodified+0 -41
| @@ -16,11 +16,9 @@ use crate::auth::current_user; | |||
| 16 | use crate::i18n::community::{self as cm, K as CK}; | 16 | use crate::i18n::community::{self as cm, K as CK}; |
| 17 | use crate::i18n::misc::{self as mi, K as MK}; | 17 | use crate::i18n::misc::{self as mi, K as MK}; |
| 18 | use crate::i18n::orgs::{self as g, K}; | 18 | use crate::i18n::orgs::{self as g, K}; |
| 19 | -use crate::i18n::packages::{self as pk, K as PK}; | ||
| 20 | use crate::i18n::{self, Lang}; | 19 | use crate::i18n::{self, Lang}; |
| 21 | use crate::live::{Topic, stream_changes}; | 20 | use crate::live::{Topic, stream_changes}; |
| 22 | use crate::pages::org_new::may_create_org; | 21 | use crate::pages::org_new::may_create_org; |
| 23 | -use crate::pages::packages::{self as packages, PackageRow}; | ||
| 24 | use crate::pages::profile_calendar::{calendar_since, load_calendar}; | 22 | use crate::pages::profile_calendar::{calendar_since, load_calendar}; |
| 25 | use crate::pages::profile_pins::{PinOption, pin_options, pins_menu}; | 23 | use crate::pages::profile_pins::{PinOption, pin_options, pins_menu}; |
| 26 | use crate::pages::repo_settings::{notice_banner_for, take_notice}; | 24 | use crate::pages::repo_settings::{notice_banner_for, take_notice}; |
| @@ -75,7 +73,6 @@ pub enum Tab { | |||
| 75 | Repositories, | 73 | Repositories, |
| 76 | Snippets, | 74 | Snippets, |
| 77 | Stars, | 75 | Stars, |
| 78 | - Packages, | ||
| 79 | Organizations, | 76 | Organizations, |
| 80 | } | 77 | } |
| 81 | 78 | ||
| @@ -85,7 +82,6 @@ impl Tab { | |||
| 85 | Some("repositories") => Self::Repositories, | 82 | Some("repositories") => Self::Repositories, |
| 86 | Some("snippets") => Self::Snippets, | 83 | Some("snippets") => Self::Snippets, |
| 87 | Some("stars") => Self::Stars, | 84 | Some("stars") => Self::Stars, |
| 88 | - Some("packages") => Self::Packages, | ||
| 89 | Some("organizations") => Self::Organizations, | 85 | Some("organizations") => Self::Organizations, |
| 90 | _ => Self::Overview, | 86 | _ => Self::Overview, |
| 91 | } | 87 | } |
| @@ -97,7 +93,6 @@ impl Tab { | |||
| 97 | Self::Repositories => "repositories", | 93 | Self::Repositories => "repositories", |
| 98 | Self::Snippets => "snippets", | 94 | Self::Snippets => "snippets", |
| 99 | Self::Stars => "stars", | 95 | Self::Stars => "stars", |
| 100 | - Self::Packages => "packages", | ||
| 101 | Self::Organizations => "organizations", | 96 | Self::Organizations => "organizations", |
| 102 | } | 97 | } |
| 103 | } | 98 | } |
| @@ -358,9 +353,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | |||
| 358 | None | 353 | None |
| 359 | }; | 354 | }; |
| 360 | 355 | ||
| 361 | - let package_rows = packages::package_rows(state, actor, &user).await?; | ||
| 362 | - let packages_on = tab == Tab::Packages; | ||
| 363 | - | ||
| 364 | let notice = take_notice(cx); | 356 | let notice = take_notice(cx); |
| 365 | let title = user.username.clone(); | 357 | let title = user.username.clone(); |
| 366 | Ok(view! { | 358 | Ok(view! { |
| @@ -370,7 +362,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | |||
| 370 | org: org, lang: lang, tab: tab, finder: finder, sort: sort, repo_total: repo_total, | 362 | org: org, lang: lang, tab: tab, finder: finder, sort: sort, repo_total: repo_total, |
| 371 | star_total: star_total, cards: cards, from_pins: from_pins, | 363 | star_total: star_total, cards: cards, from_pins: from_pins, |
| 372 | pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing, | 364 | pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing, |
| 373 | - packages_on: packages_on, package_rows: package_rows, | ||
| 374 | org_member: org_member, org_owner: org_owner, org_can_create: org_can_create, | 365 | org_member: org_member, org_owner: org_owner, org_can_create: org_can_create, |
| 375 | heat: heat, snippets: snippets, snippet_total: snippet_total, | 366 | heat: heat, snippets: snippets, snippet_total: snippet_total, |
| 376 | snippet_paging: (snippet_page, snippet_pages, snippet_pager), orgs: orgs, org_create_allowed: org_create_allowed, | 367 | snippet_paging: (snippet_page, snippet_pages, snippet_pager), orgs: orgs, org_create_allowed: org_create_allowed, |
| @@ -573,8 +564,6 @@ async fn profile_card( | |||
| 573 | pins_error: bool, | 564 | pins_error: bool, |
| 574 | edit_profile: bool, | 565 | edit_profile: bool, |
| 575 | listing: Listing, | 566 | listing: Listing, |
| 576 | - packages_on: bool, | ||
| 577 | - package_rows: Vec<PackageRow>, | ||
| 578 | org_member: bool, | 567 | org_member: bool, |
| 579 | org_owner: bool, | 568 | org_owner: bool, |
| 580 | org_can_create: bool, | 569 | org_can_create: bool, |
| @@ -591,8 +580,6 @@ async fn profile_card( | |||
| 591 | let snippets_on = tab == Tab::Snippets; | 580 | let snippets_on = tab == Tab::Snippets; |
| 592 | let orgs_on = tab == Tab::Organizations; | 581 | let orgs_on = tab == Tab::Organizations; |
| 593 | let has_orgs = !orgs.is_empty(); | 582 | let has_orgs = !orgs.is_empty(); |
| 594 | - let packages_events = packages::events_href(&user.username); | ||
| 595 | - let has_packages = !package_rows.is_empty(); | ||
| 596 | let src = avatar_url(&user.username, avatar.as_deref()); | 583 | let src = avatar_url(&user.username, avatar.as_deref()); |
| 597 | let has_about = !about_html.is_empty(); | 584 | let has_about = !about_html.is_empty(); |
| 598 | let is_org = user.is_org(); | 585 | let is_org = user.is_org(); |
| @@ -608,7 +595,6 @@ async fn profile_card( | |||
| 608 | ("repositories", repo_total.to_string()), | 595 | ("repositories", repo_total.to_string()), |
| 609 | ("snippets", snippet_total.to_string()), | 596 | ("snippets", snippet_total.to_string()), |
| 610 | ("stars", star_total.to_string()), | 597 | ("stars", star_total.to_string()), |
| 611 | - ("packages", package_rows.len().to_string()), | ||
| 612 | ]; | 598 | ]; |
| 613 | let base = format!("/{}", enc(&user.username)); | 599 | let base = format!("/{}", enc(&user.username)); |
| 614 | let overview_on = tab == Tab::Overview; | 600 | let overview_on = tab == Tab::Overview; |
| @@ -763,31 +749,6 @@ async fn profile_card( | |||
| 763 | pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) | 749 | pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) |
| 764 | </section> | 750 | </section> |
| 765 | } | 751 | } |
| 766 | - if packages_on { | ||
| 767 | - <section class="sec package-listing" data-live=(packages_events.as_str())> | ||
| 768 | - <h2>(pk::t(lang, PK::PackagesHeading))</h2> | ||
| 769 | - if has_packages { | ||
| 770 | - for row in package_rows.into_iter() { | ||
| 771 | - <div class="line" data-kb-row=""> | ||
| 772 | - <a class="name" href=(row.href.as_str())>(row.name.as_str())</a> | ||
| 773 | - if row.container { | ||
| 774 | - <span class="badge">(pk::t(lang, PK::ContainerKind))</span> | ||
| 775 | - } | ||
| 776 | - <span class="val">(row.latest.as_str())</span> | ||
| 777 | - <span class="val">(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> | ||
| 778 | - if row.private { | ||
| 779 | - <span class="badge">(pk::t(lang, PK::PackagePrivate))</span> | ||
| 780 | - } | ||
| 781 | - if !row.description.is_empty() { | ||
| 782 | - <span class="val">(row.description.as_str())</span> | ||
| 783 | - } | ||
| 784 | - </div> | ||
| 785 | - } | ||
| 786 | - } else { | ||
| 787 | - <p class="state">(pk::t(lang, PK::NoPackages))</p> | ||
| 788 | - } | ||
| 789 | - </section> | ||
| 790 | - } | ||
| 791 | if snippets_on { | 752 | if snippets_on { |
| 792 | <section class="sec snippet-listing"> | 753 | <section class="sec snippet-listing"> |
| 793 | <h2>(cm::t(lang, CK::Snippets))</h2> | 754 | <h2>(cm::t(lang, CK::Snippets))</h2> |
| @@ -848,12 +809,10 @@ pub async fn own_profile_tabs( | |||
| 848 | .list_owner_snippets(&user.id, Some(user.id.as_str())) | 809 | .list_owner_snippets(&user.id, Some(user.id.as_str())) |
| 849 | .await? | 810 | .await? |
| 850 | .len(); | 811 | .len(); |
| 851 | - let packages = packages::package_rows(state, actor, &user).await?.len(); | ||
| 852 | counts = vec![ | 812 | counts = vec![ |
| 853 | ("repositories", repos.to_string()), | 813 | ("repositories", repos.to_string()), |
| 854 | ("snippets", snippets.to_string()), | 814 | ("snippets", snippets.to_string()), |
| 855 | ("stars", stars.to_string()), | 815 | ("stars", stars.to_string()), |
| 856 | - ("packages", packages.to_string()), | ||
| 857 | ]; | 816 | ]; |
| 858 | } | 817 | } |
| 859 | Ok(view! { | 818 | Ok(view! { |
crates/forge-web-account/src/pages/settings_security.rsmodified+1 -2
| @@ -18,7 +18,6 @@ use crate::auth::{ | |||
| 18 | CsrfForm, hash_password_async, logout, require_csrf, require_user, two_factor_enabled, | 18 | CsrfForm, hash_password_async, logout, require_csrf, require_user, two_factor_enabled, |
| 19 | verify_password_async, verify_second_factor, | 19 | verify_password_async, verify_second_factor, |
| 20 | }; | 20 | }; |
| 21 | -use crate::i18n::packages::{self as pk, K as PK}; | ||
| 22 | use crate::i18n::releases_ci::{self as rc, K as RC}; | 21 | use crate::i18n::releases_ci::{self as rc, K as RC}; |
| 23 | use crate::i18n::s; | 22 | use crate::i18n::s; |
| 24 | use crate::i18n::{self, Key, Lang, t}; | 23 | use crate::i18n::{self, Key, Lang, t}; |
| @@ -359,7 +358,7 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | |||
| 359 | } | 358 | } |
| 360 | </ul> | 359 | </ul> |
| 361 | <div class="acts"> | 360 | <div class="acts"> |
| 362 | - <button type="button" class="act" data-copy="recovery-codes" data-lines="" data-copied=(rc::t(lang, RC::CopyDone)) data-failed=(rc::t(lang, RC::CopyFailed))>(pk::t(lang, PK::CopyCommand))</button> | 361 | + <button type="button" class="act" data-copy="recovery-codes" data-lines="" data-copied=(rc::t(lang, RC::CopyDone)) data-failed=(rc::t(lang, RC::CopyFailed))>(rc::t(lang, RC::CopyCommand))</button> |
| 363 | </div> | 362 | </div> |
| 364 | </div> | 363 | </div> |
| 365 | } | 364 | } |
crates/forge-web-account/src/pages/settings_tokens.rsmodified+2 -13
| @@ -14,10 +14,8 @@ use topcoat::router::response::response_headers; | |||
| 14 | use topcoat::router::{page, route}; | 14 | use topcoat::router::{page, route}; |
| 15 | use topcoat::view::{View, component, view}; | 15 | use topcoat::view::{View, component, view}; |
| 16 | 16 | ||
| 17 | -use crate::api::packages::PACKAGES_SCOPE; | ||
| 18 | use crate::audit::{self, Actor, Target}; | 17 | use crate::audit::{self, Actor, Target}; |
| 19 | use crate::auth::require_csrf; | 18 | use crate::auth::require_csrf; |
| 20 | -use crate::i18n::packages::{self as pk, K as PK}; | ||
| 21 | use crate::i18n::releases_ci::{self as rc, K as RC}; | 19 | use crate::i18n::releases_ci::{self as rc, K as RC}; |
| 22 | use crate::i18n::s; | 20 | use crate::i18n::s; |
| 23 | use crate::i18n::{self, Key, Lang, t, token_name_length}; | 21 | use crate::i18n::{self, Key, Lang, t, token_name_length}; |
| @@ -37,8 +35,6 @@ struct CreateTokenForm { | |||
| 37 | name: String, | 35 | name: String, |
| 38 | #[serde(default)] | 36 | #[serde(default)] |
| 39 | expires: String, | 37 | expires: String, |
| 40 | - #[serde(default)] | ||
| 41 | - packages: String, | ||
| 42 | } | 38 | } |
| 43 | 39 | ||
| 44 | #[derive(Deserialize)] | 40 | #[derive(Deserialize)] |
| @@ -76,7 +72,7 @@ pub(crate) async fn tokens_section( | |||
| 76 | <p class="hint">(t(lang, Key::CopyNow))</p> | 72 | <p class="hint">(t(lang, Key::CopyNow))</p> |
| 77 | <div class="copy-box"> | 73 | <div class="copy-box"> |
| 78 | <pre class="code"><code id="new-token">(token)</code></pre> | 74 | <pre class="code"><code id="new-token">(token)</code></pre> |
| 79 | - <button type="button" class="small" data-copy="new-token" data-copied=(rc::t(lang, RC::CopyDone)) data-failed=(rc::t(lang, RC::CopyFailed))>(pk::t(lang, PK::CopyCommand))</button> | 75 | + <button type="button" class="small" data-copy="new-token" data-copied=(rc::t(lang, RC::CopyDone)) data-failed=(rc::t(lang, RC::CopyFailed))>(rc::t(lang, RC::CopyCommand))</button> |
| 80 | </div> | 76 | </div> |
| 81 | </div> | 77 | </div> |
| 82 | } | 78 | } |
| @@ -100,10 +96,6 @@ pub(crate) async fn tokens_section( | |||
| 100 | <option value="never">(t(lang, Key::ExpiresNever))</option> | 96 | <option value="never">(t(lang, Key::ExpiresNever))</option> |
| 101 | </select> | 97 | </select> |
| 102 | </div> | 98 | </div> |
| 103 | - <label class="switch"> | ||
| 104 | - <input type="checkbox" name="packages" value="on"> | ||
| 105 | - <span>(pk::t(lang, PK::ScopePackages))</span> | ||
| 106 | - </label> | ||
| 107 | <div class="acts asks"> | 99 | <div class="acts asks"> |
| 108 | <button type="submit" class="primary">(t(lang, Key::CreateToken))</button> | 100 | <button type="submit" class="primary">(t(lang, Key::CreateToken))</button> |
| 109 | <a class="act" href="/settings/tokens">(s(lang, "Keep it", "Vazgeç"))</a> | 101 | <a class="act" href="/settings/tokens">(s(lang, "Keep it", "Vazgeç"))</a> |
| @@ -143,10 +135,7 @@ async fn tokens_create(cx: &Cx, Form(form): Form<CreateTokenForm>) -> Result<imp | |||
| 143 | let token = generate_token(); | 135 | let token = generate_token(); |
| 144 | let expires_at = expiry_days(&form.expires) | 136 | let expires_at = expiry_days(&form.expires) |
| 145 | .map(|days| stamp_after(Duration::from_secs(days * 24 * 60 * 60))); | 137 | .map(|days| stamp_after(Duration::from_secs(days * 24 * 60 * 60))); |
| 146 | - let mut scopes: Vec<String> = SCOPES.iter().map(|s| (*s).to_owned()).collect(); | 138 | + let scopes: Vec<String> = SCOPES.iter().map(|s| (*s).to_owned()).collect(); |
| 147 | - if !form.packages.is_empty() { | ||
| 148 | - scopes.push(PACKAGES_SCOPE.to_owned()); | ||
| 149 | - } | ||
| 150 | let created = store | 139 | let created = store |
| 151 | .create_token( | 140 | .create_token( |
| 152 | &viewer.0.id, | 141 | &viewer.0.id, |
crates/forge-web-app/src/api/mod.rsmodified+0 -1
| @@ -1,6 +1,5 @@ | |||
| 1 | pub mod ci; | 1 | pub mod ci; |
| 2 | pub mod gitea; | 2 | pub mod gitea; |
| 3 | -pub mod packages; | ||
| 4 | pub mod releases; | 3 | pub mod releases; |
| 5 | pub mod statuses; | 4 | pub mod statuses; |
| 6 | pub mod tags; | 5 | pub mod tags; |
crates/forge-web-app/src/api/packages.rsdeleted+0 -318
| @@ -1,318 +0,0 @@ | |||
| 1 | -use forge_core::User; | ||
| 2 | -use futures_util::StreamExt; | ||
| 3 | -use http::HeaderMap; | ||
| 4 | -use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 5 | -use http_body::Frame; | ||
| 6 | -use http_body_util::StreamBody; | ||
| 7 | -use serde_json::{Value, json}; | ||
| 8 | -use topcoat::context::{Cx, context}; | ||
| 9 | -use topcoat::router::request::headers; | ||
| 10 | -use topcoat::router::response::Response; | ||
| 11 | -use topcoat::router::{Body, StatusCode, path_param, route}; | ||
| 12 | - | ||
| 13 | -use crate::api::{self, Refusal}; | ||
| 14 | -use crate::client_ip::client_ip; | ||
| 15 | -use crate::package_ops::{self, PackageError}; | ||
| 16 | -use crate::state::AppState; | ||
| 17 | - | ||
| 18 | -pub const PACKAGES_SCOPE: &str = "packages"; | ||
| 19 | - | ||
| 20 | -path_param!(owner); | ||
| 21 | -path_param!(name); | ||
| 22 | -path_param!(version); | ||
| 23 | - | ||
| 24 | -async fn caller(cx: &Cx, scope_required: bool) -> Result<Option<User>, Refusal> { | ||
| 25 | - let state = context::<AppState>(cx); | ||
| 26 | - let normalized = bare_token_as_bearer(headers(cx)); | ||
| 27 | - let (user, token_id, scopes) = | ||
| 28 | - match api::authenticate_token(state, client_ip(cx), &normalized).await { | ||
| 29 | - Ok(Some(found)) => found, | ||
| 30 | - Ok(None) => return Ok(None), | ||
| 31 | - Err(refusal) => { | ||
| 32 | - return Err(Box::new(cargo_error( | ||
| 33 | - refusal.status(), | ||
| 34 | - "authentication required", | ||
| 35 | - ))); | ||
| 36 | - } | ||
| 37 | - }; | ||
| 38 | - if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) { | ||
| 39 | - return if scope_required { | ||
| 40 | - Err(Box::new(cargo_error( | ||
| 41 | - StatusCode::FORBIDDEN, | ||
| 42 | - "the token lacks the packages scope", | ||
| 43 | - ))) | ||
| 44 | - } else { | ||
| 45 | - Ok(None) | ||
| 46 | - }; | ||
| 47 | - } | ||
| 48 | - if let Err(e) = state.store.touch_token(&token_id).await { | ||
| 49 | - return Err(Box::new(failure(PackageError::Internal(e.to_string())))); | ||
| 50 | - } | ||
| 51 | - crate::live::bump_account(state, &user.id); | ||
| 52 | - Ok(Some(user)) | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -fn bare_token_as_bearer(headers: &HeaderMap) -> HeaderMap { | ||
| 56 | - let mut out = headers.clone(); | ||
| 57 | - let bare = headers | ||
| 58 | - .get(AUTHORIZATION) | ||
| 59 | - .and_then(|value| value.to_str().ok()) | ||
| 60 | - .map(str::trim) | ||
| 61 | - .filter(|value| !value.is_empty() && !value.contains(' ')) | ||
| 62 | - .map(str::to_owned); | ||
| 63 | - if let Some(token) = bare | ||
| 64 | - && let Ok(value) = HeaderValue::from_str(&format!("Bearer {token}")) | ||
| 65 | - { | ||
| 66 | - out.insert(AUTHORIZATION, value); | ||
| 67 | - } | ||
| 68 | - out | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -fn cargo_error(status: StatusCode, detail: &str) -> Response { | ||
| 72 | - api::json(status, &json!({ "errors": [{ "detail": detail }] })) | ||
| 73 | -} | ||
| 74 | - | ||
| 75 | -fn failure(e: PackageError) -> Response { | ||
| 76 | - match e { | ||
| 77 | - PackageError::Invalid(msg) => cargo_error(StatusCode::BAD_REQUEST, &msg), | ||
| 78 | - PackageError::NotFound => cargo_error(StatusCode::NOT_FOUND, "not found"), | ||
| 79 | - PackageError::Forbidden => cargo_error( | ||
| 80 | - StatusCode::FORBIDDEN, | ||
| 81 | - "you do not have permission to publish to this registry", | ||
| 82 | - ), | ||
| 83 | - PackageError::Conflict(msg) => cargo_error(StatusCode::CONFLICT, &msg), | ||
| 84 | - PackageError::TooLarge => cargo_error( | ||
| 85 | - StatusCode::PAYLOAD_TOO_LARGE, | ||
| 86 | - "the crate is larger than the registry accepts", | ||
| 87 | - ), | ||
| 88 | - PackageError::Internal(cause) => { | ||
| 89 | - tracing::error!(error = %cause, "package request failed"); | ||
| 90 | - cargo_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error") | ||
| 91 | - } | ||
| 92 | - } | ||
| 93 | -} | ||
| 94 | - | ||
| 95 | -fn text(body: String) -> Response { | ||
| 96 | - let mut res = Response::new(Body::from(body)); | ||
| 97 | - *res.status_mut() = StatusCode::OK; | ||
| 98 | - res.headers_mut().insert( | ||
| 99 | - CONTENT_TYPE, | ||
| 100 | - HeaderValue::from_static("text/plain; charset=utf-8"), | ||
| 101 | - ); | ||
| 102 | - res | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -async fn owner_of(cx: &Cx) -> Result<User, Refusal> { | ||
| 106 | - let state = context::<AppState>(cx); | ||
| 107 | - match package_ops::owner_named(state, owner(cx)).await { | ||
| 108 | - Ok(Some(found)) => Ok(found), | ||
| 109 | - Ok(_) => Err(Box::new(failure(PackageError::NotFound))), | ||
| 110 | - Err(e) => Err(Box::new(failure(e))), | ||
| 111 | - } | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -async fn writer(cx: &Cx) -> Result<User, Refusal> { | ||
| 115 | - match caller(cx, true).await? { | ||
| 116 | - Some(user) => Ok(user), | ||
| 117 | - None => Err(Box::new(cargo_error( | ||
| 118 | - StatusCode::UNAUTHORIZED, | ||
| 119 | - "authentication required", | ||
| 120 | - ))), | ||
| 121 | - } | ||
| 122 | -} | ||
| 123 | - | ||
| 124 | -#[route(GET "/api/packages/{owner}/cargo/config.json")] | ||
| 125 | -async fn config(cx: &Cx) -> topcoat::Result<Response> { | ||
| 126 | - let state = context::<AppState>(cx); | ||
| 127 | - if let Err(res) = caller(cx, false).await { | ||
| 128 | - return Ok(*res); | ||
| 129 | - } | ||
| 130 | - let owner = match owner_of(cx).await { | ||
| 131 | - Ok(owner) => owner, | ||
| 132 | - Err(res) => return Ok(*res), | ||
| 133 | - }; | ||
| 134 | - match package_ops::config_json(state, &owner).await { | ||
| 135 | - Ok(value) => Ok(api::json(StatusCode::OK, &value)), | ||
| 136 | - Err(e) => Ok(failure(e)), | ||
| 137 | - } | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | -#[route(GET "/api/packages/{owner}/cargo/1/{name}")] | ||
| 141 | -async fn index_one(cx: &Cx) -> topcoat::Result<Response> { | ||
| 142 | - Ok(index_response(cx).await) | ||
| 143 | -} | ||
| 144 | - | ||
| 145 | -#[route(GET "/api/packages/{owner}/cargo/2/{name}")] | ||
| 146 | -async fn index_two(cx: &Cx) -> topcoat::Result<Response> { | ||
| 147 | - Ok(index_response(cx).await) | ||
| 148 | -} | ||
| 149 | - | ||
| 150 | -#[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")] | ||
| 151 | -async fn index_long(cx: &Cx) -> topcoat::Result<Response> { | ||
| 152 | - Ok(index_response(cx).await) | ||
| 153 | -} | ||
| 154 | - | ||
| 155 | -async fn index_response(cx: &Cx) -> Response { | ||
| 156 | - let state = context::<AppState>(cx); | ||
| 157 | - let actor = match caller(cx, false).await { | ||
| 158 | - Ok(actor) => actor, | ||
| 159 | - Err(res) => return *res, | ||
| 160 | - }; | ||
| 161 | - let owner = match owner_of(cx).await { | ||
| 162 | - Ok(owner) => owner, | ||
| 163 | - Err(res) => return *res, | ||
| 164 | - }; | ||
| 165 | - let package = match package_ops::readable_package(state, actor.as_ref(), &owner, name(cx)).await | ||
| 166 | - { | ||
| 167 | - Ok(package) => package, | ||
| 168 | - Err(e) => return failure(e), | ||
| 169 | - }; | ||
| 170 | - match package_ops::index_file(state, &package).await { | ||
| 171 | - Ok(body) => text(body), | ||
| 172 | - Err(e) => failure(e), | ||
| 173 | - } | ||
| 174 | -} | ||
| 175 | - | ||
| 176 | -#[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")] | ||
| 177 | -async fn download(cx: &Cx) -> topcoat::Result<Response> { | ||
| 178 | - let state = context::<AppState>(cx); | ||
| 179 | - let actor = match caller(cx, false).await { | ||
| 180 | - Ok(actor) => actor, | ||
| 181 | - Err(res) => return Ok(*res), | ||
| 182 | - }; | ||
| 183 | - let owner = match owner_of(cx).await { | ||
| 184 | - Ok(owner) => owner, | ||
| 185 | - Err(res) => return Ok(*res), | ||
| 186 | - }; | ||
| 187 | - let read = | ||
| 188 | - match package_ops::download(state, actor.as_ref(), &owner, name(cx), version(cx)).await { | ||
| 189 | - Ok(read) => read, | ||
| 190 | - Err(e) => return Ok(failure(e)), | ||
| 191 | - }; | ||
| 192 | - let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); | ||
| 193 | - let mut res = Response::new(Body::new(StreamBody::new(chunks))); | ||
| 194 | - *res.status_mut() = StatusCode::OK; | ||
| 195 | - res.headers_mut().insert( | ||
| 196 | - CONTENT_TYPE, | ||
| 197 | - HeaderValue::from_static("application/octet-stream"), | ||
| 198 | - ); | ||
| 199 | - res.headers_mut() | ||
| 200 | - .insert(CONTENT_LENGTH, HeaderValue::from(read.size)); | ||
| 201 | - Ok(res) | ||
| 202 | -} | ||
| 203 | - | ||
| 204 | -#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] | ||
| 205 | -async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 206 | - let state = context::<AppState>(cx); | ||
| 207 | - let actor = match writer(cx).await { | ||
| 208 | - Ok(actor) => actor, | ||
| 209 | - Err(res) => return Ok(*res), | ||
| 210 | - }; | ||
| 211 | - let owner = match owner_of(cx).await { | ||
| 212 | - Ok(owner) => owner, | ||
| 213 | - Err(res) => return Ok(*res), | ||
| 214 | - }; | ||
| 215 | - let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await { | ||
| 216 | - Ok(bytes) => bytes, | ||
| 217 | - Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))), | ||
| 218 | - }; | ||
| 219 | - match package_ops::publish(state, &owner, &actor, &bytes).await { | ||
| 220 | - Ok(()) => Ok(api::json( | ||
| 221 | - StatusCode::OK, | ||
| 222 | - &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }), | ||
| 223 | - )), | ||
| 224 | - Err(e) => Ok(failure(e)), | ||
| 225 | - } | ||
| 226 | -} | ||
| 227 | - | ||
| 228 | -fn read_failure(e: &impl std::fmt::Display) -> String { | ||
| 229 | - format!("the request body could not be read: {e}") | ||
| 230 | -} | ||
| 231 | - | ||
| 232 | -#[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")] | ||
| 233 | -async fn yank(cx: &Cx) -> topcoat::Result<Response> { | ||
| 234 | - set_yank(cx, true).await | ||
| 235 | -} | ||
| 236 | - | ||
| 237 | -#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")] | ||
| 238 | -async fn unyank(cx: &Cx) -> topcoat::Result<Response> { | ||
| 239 | - set_yank(cx, false).await | ||
| 240 | -} | ||
| 241 | - | ||
| 242 | -async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> { | ||
| 243 | - let state = context::<AppState>(cx); | ||
| 244 | - let actor = match writer(cx).await { | ||
| 245 | - Ok(actor) => actor, | ||
| 246 | - Err(res) => return Ok(*res), | ||
| 247 | - }; | ||
| 248 | - let owner = match owner_of(cx).await { | ||
| 249 | - Ok(owner) => owner, | ||
| 250 | - Err(res) => return Ok(*res), | ||
| 251 | - }; | ||
| 252 | - match package_ops::set_yanked(state, &owner, &actor, name(cx), version(cx), yanked).await { | ||
| 253 | - Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))), | ||
| 254 | - Err(e) => Ok(failure(e)), | ||
| 255 | - } | ||
| 256 | -} | ||
| 257 | - | ||
| 258 | -#[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")] | ||
| 259 | -async fn owners(cx: &Cx) -> topcoat::Result<Response> { | ||
| 260 | - let state = context::<AppState>(cx); | ||
| 261 | - let actor = match caller(cx, false).await { | ||
| 262 | - Ok(actor) => actor, | ||
| 263 | - Err(res) => return Ok(*res), | ||
| 264 | - }; | ||
| 265 | - let owner = match owner_of(cx).await { | ||
| 266 | - Ok(owner) => owner, | ||
| 267 | - Err(res) => return Ok(*res), | ||
| 268 | - }; | ||
| 269 | - if let Err(e) = package_ops::readable_package(state, actor.as_ref(), &owner, name(cx)).await { | ||
| 270 | - return Ok(failure(e)); | ||
| 271 | - } | ||
| 272 | - let people: Vec<User> = if owner.is_org() { | ||
| 273 | - match state.store.org_members(&owner.id).await { | ||
| 274 | - Ok(members) => members | ||
| 275 | - .into_iter() | ||
| 276 | - .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner) | ||
| 277 | - .map(|(user, _)| user) | ||
| 278 | - .collect(), | ||
| 279 | - Err(e) => return Ok(failure(e.into())), | ||
| 280 | - } | ||
| 281 | - } else { | ||
| 282 | - vec![owner.clone()] | ||
| 283 | - }; | ||
| 284 | - let users: Vec<Value> = people | ||
| 285 | - .iter() | ||
| 286 | - .map(|user| { | ||
| 287 | - json!({ | ||
| 288 | - "id": user.id, | ||
| 289 | - "login": user.username, | ||
| 290 | - "name": user.display_name, | ||
| 291 | - "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username), | ||
| 292 | - }) | ||
| 293 | - }) | ||
| 294 | - .collect(); | ||
| 295 | - Ok(api::json(StatusCode::OK, &json!({ "users": users }))) | ||
| 296 | -} | ||
| 297 | - | ||
| 298 | -#[cfg(test)] | ||
| 299 | -mod tests { | ||
| 300 | - use http::HeaderValue; | ||
| 301 | - | ||
| 302 | - use super::*; | ||
| 303 | - | ||
| 304 | - #[test] | ||
| 305 | - fn a_bare_token_becomes_a_bearer_token() { | ||
| 306 | - let mut headers = HeaderMap::new(); | ||
| 307 | - headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc")); | ||
| 308 | - let rewritten = bare_token_as_bearer(&headers); | ||
| 309 | - assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc"); | ||
| 310 | - | ||
| 311 | - let mut bearer = HeaderMap::new(); | ||
| 312 | - bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc")); | ||
| 313 | - assert_eq!( | ||
| 314 | - bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(), | ||
| 315 | - "Bearer forge_abc" | ||
| 316 | - ); | ||
| 317 | - } | ||
| 318 | -} | ||
crates/forge-web-app/src/lib.rsmodified+0 -3
| @@ -31,9 +31,6 @@ pub mod merge_queue; | |||
| 31 | pub mod mirrors; | 31 | pub mod mirrors; |
| 32 | pub mod notify; | 32 | pub mod notify; |
| 33 | pub mod notify_hub; | 33 | pub mod notify_hub; |
| 34 | -pub mod oci; | ||
| 35 | -pub mod package_ops; | ||
| 36 | -pub mod packages_live; | ||
| 37 | pub mod post_update; | 34 | pub mod post_update; |
| 38 | pub mod prune; | 35 | pub mod prune; |
| 39 | pub mod pulls_sync; | 36 | pub mod pulls_sync; |
crates/forge-web-app/src/oci/auth.rsdeleted+0 -184
| @@ -1,184 +0,0 @@ | |||
| 1 | -use forge_core::User; | ||
| 2 | -use forge_core::oci as rules; | ||
| 3 | -use forge_core::packages::{KIND_OCI, Package}; | ||
| 4 | -use forge_core::time::now_unix; | ||
| 5 | -use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE}; | ||
| 6 | -use topcoat::context::{Cx, context}; | ||
| 7 | -use topcoat::router::StatusCode; | ||
| 8 | -use topcoat::router::request::headers; | ||
| 9 | -use topcoat::router::response::Response; | ||
| 10 | - | ||
| 11 | -use super::{name_unknown, oci_error}; | ||
| 12 | -use crate::api::{self, Refusal}; | ||
| 13 | -use crate::client_ip::client_ip; | ||
| 14 | -use crate::package_ops::{self, PackageError}; | ||
| 15 | -use crate::state::AppState; | ||
| 16 | - | ||
| 17 | -pub const TOKEN_TTL_SECS: i64 = 300; | ||
| 18 | - | ||
| 19 | -const ACTIONS: &str = "pull,push"; | ||
| 20 | - | ||
| 21 | -pub struct Caller { | ||
| 22 | - pub user: Option<User>, | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -pub struct Target { | ||
| 26 | - pub owner: User, | ||
| 27 | - pub image: String, | ||
| 28 | - pub package: Option<Package>, | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> { | ||
| 32 | - let state = context::<AppState>(cx); | ||
| 33 | - let headers = headers(cx); | ||
| 34 | - let Some(value) = headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()) else { | ||
| 35 | - return Ok(Caller { user: None }); | ||
| 36 | - }; | ||
| 37 | - if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim) | ||
| 38 | - && !bearer.starts_with("forge_") | ||
| 39 | - { | ||
| 40 | - let now = now_unix(); | ||
| 41 | - return match rules::verify_token(&state.key, bearer, now) { | ||
| 42 | - Some(Some(user_id)) => match state.store.user_by_id(&user_id).await { | ||
| 43 | - Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }), | ||
| 44 | - Ok(_) => Err(Box::new(challenge(state, None))), | ||
| 45 | - Err(e) => Err(Box::new(internal(e))), | ||
| 46 | - }, | ||
| 47 | - Some(None) => Ok(Caller { user: None }), | ||
| 48 | - None => Err(Box::new(challenge(state, None))), | ||
| 49 | - }; | ||
| 50 | - } | ||
| 51 | - match api::authenticate_token(state, client_ip(cx), headers).await { | ||
| 52 | - Ok(Some((user, token_id, scopes))) => { | ||
| 53 | - if !scopes | ||
| 54 | - .iter() | ||
| 55 | - .any(|s| s == crate::api::packages::PACKAGES_SCOPE) | ||
| 56 | - { | ||
| 57 | - return Ok(Caller { user: None }); | ||
| 58 | - } | ||
| 59 | - if let Err(e) = state.store.touch_token(&token_id).await { | ||
| 60 | - return Err(Box::new(internal(e))); | ||
| 61 | - } | ||
| 62 | - Ok(Caller { user: Some(user) }) | ||
| 63 | - } | ||
| 64 | - Ok(None) => Ok(Caller { user: None }), | ||
| 65 | - Err(_) => Err(Box::new(challenge(state, None))), | ||
| 66 | - } | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -pub async fn authorize( | ||
| 70 | - state: &AppState, | ||
| 71 | - caller: &Caller, | ||
| 72 | - name: &str, | ||
| 73 | - write: bool, | ||
| 74 | -) -> Result<Target, Refusal> { | ||
| 75 | - let Some((owner_name, image)) = rules::split_repo_name(name) else { | ||
| 76 | - return Err(Box::new(oci_error( | ||
| 77 | - StatusCode::BAD_REQUEST, | ||
| 78 | - "NAME_INVALID", | ||
| 79 | - "invalid repository name", | ||
| 80 | - ))); | ||
| 81 | - }; | ||
| 82 | - let anonymous = caller.user.is_none(); | ||
| 83 | - if write && anonymous { | ||
| 84 | - return Err(Box::new(challenge(state, Some(name)))); | ||
| 85 | - } | ||
| 86 | - let owner = state | ||
| 87 | - .store | ||
| 88 | - .user_by_username(owner_name) | ||
| 89 | - .await | ||
| 90 | - .map_err(internal)?; | ||
| 91 | - let Some(owner) = owner else { | ||
| 92 | - return Err(Box::new(if anonymous { | ||
| 93 | - challenge(state, Some(name)) | ||
| 94 | - } else { | ||
| 95 | - oci_error( | ||
| 96 | - StatusCode::NOT_FOUND, | ||
| 97 | - "NAME_UNKNOWN", | ||
| 98 | - "repository name not known to registry", | ||
| 99 | - ) | ||
| 100 | - })); | ||
| 101 | - }; | ||
| 102 | - let package = state | ||
| 103 | - .store | ||
| 104 | - .package_by_name(&owner.id, KIND_OCI, image) | ||
| 105 | - .await | ||
| 106 | - .map_err(internal)?; | ||
| 107 | - let target = Target { | ||
| 108 | - owner: owner.clone(), | ||
| 109 | - image: image.to_owned(), | ||
| 110 | - package: package.clone(), | ||
| 111 | - }; | ||
| 112 | - if write { | ||
| 113 | - let user = caller.user.as_ref().expect("checked above"); | ||
| 114 | - if !package_ops::may_publish(state, user, &owner) | ||
| 115 | - .await | ||
| 116 | - .map_err(package_failure)? | ||
| 117 | - { | ||
| 118 | - return Err(Box::new(denied())); | ||
| 119 | - } | ||
| 120 | - return Ok(target); | ||
| 121 | - } | ||
| 122 | - match package { | ||
| 123 | - Some(package) => { | ||
| 124 | - let readable = package_ops::may_read(state, caller.user.as_ref(), &owner, &package) | ||
| 125 | - .await | ||
| 126 | - .map_err(package_failure)?; | ||
| 127 | - if readable { | ||
| 128 | - Ok(target) | ||
| 129 | - } else if anonymous { | ||
| 130 | - Err(Box::new(challenge(state, Some(name)))) | ||
| 131 | - } else { | ||
| 132 | - Err(Box::new(name_unknown())) | ||
| 133 | - } | ||
| 134 | - } | ||
| 135 | - None if anonymous => Err(Box::new(challenge(state, Some(name)))), | ||
| 136 | - None => Err(Box::new(name_unknown())), | ||
| 137 | - } | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | -pub fn challenge(state: &AppState, name: Option<&str>) -> Response { | ||
| 141 | - let base = state.config.base_url.trim_end_matches('/'); | ||
| 142 | - let host = base.split_once("://").map_or(base, |(_, rest)| rest); | ||
| 143 | - let mut value = format!("Bearer realm=\"{base}/v2/token\",service=\"{host}\""); | ||
| 144 | - if let Some(name) = name { | ||
| 145 | - value.push_str(&format!(",scope=\"repository:{name}:{ACTIONS}\"")); | ||
| 146 | - } | ||
| 147 | - let mut res = oci_error( | ||
| 148 | - StatusCode::UNAUTHORIZED, | ||
| 149 | - "UNAUTHORIZED", | ||
| 150 | - "authentication required", | ||
| 151 | - ); | ||
| 152 | - if let Ok(header) = HeaderValue::from_str(&value) { | ||
| 153 | - res.headers_mut().insert(WWW_AUTHENTICATE, header); | ||
| 154 | - } | ||
| 155 | - res | ||
| 156 | -} | ||
| 157 | - | ||
| 158 | -pub fn denied() -> Response { | ||
| 159 | - oci_error( | ||
| 160 | - StatusCode::FORBIDDEN, | ||
| 161 | - "DENIED", | ||
| 162 | - "requested access to the resource is denied", | ||
| 163 | - ) | ||
| 164 | -} | ||
| 165 | - | ||
| 166 | -pub fn internal(error: impl std::fmt::Display) -> Response { | ||
| 167 | - tracing::error!(error = %error, "oci request failed"); | ||
| 168 | - oci_error( | ||
| 169 | - StatusCode::INTERNAL_SERVER_ERROR, | ||
| 170 | - "UNKNOWN", | ||
| 171 | - "internal server error", | ||
| 172 | - ) | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | -pub fn package_failure(error: PackageError) -> Refusal { | ||
| 176 | - match error { | ||
| 177 | - PackageError::Internal(cause) => Box::new(internal(cause)), | ||
| 178 | - _ => Box::new(denied()), | ||
| 179 | - } | ||
| 180 | -} | ||
| 181 | - | ||
| 182 | -pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal { | ||
| 183 | - Box::new(internal(error)) | ||
| 184 | -} | ||
crates/forge-web-app/src/oci/blobs.rsdeleted+0 -412
| @@ -1,412 +0,0 @@ | |||
| 1 | -use std::path::{Path, PathBuf}; | ||
| 2 | -use std::time::{Duration, SystemTime}; | ||
| 3 | - | ||
| 4 | -use forge_core::oci as rules; | ||
| 5 | -use forge_core::packages::{KIND_OCI, Package}; | ||
| 6 | -use forge_core::token::sha256_reader; | ||
| 7 | -use futures_util::StreamExt; | ||
| 8 | -use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 9 | -use http_body::Frame; | ||
| 10 | -use http_body_util::StreamBody; | ||
| 11 | -use tokio::io::{AsyncReadExt, AsyncWriteExt}; | ||
| 12 | -use topcoat::router::response::Response; | ||
| 13 | -use topcoat::router::{Body, StatusCode}; | ||
| 14 | - | ||
| 15 | -use super::auth::{self, Caller, Target, internal, internal_refusal}; | ||
| 16 | -use super::{gc, oci_error}; | ||
| 17 | -use crate::api::Refusal; | ||
| 18 | -use crate::state::AppState; | ||
| 19 | - | ||
| 20 | -pub const MAX_BLOB_BYTES: u64 = 10 * 1024 * 1024 * 1024; | ||
| 21 | -const CHUNK: usize = 1024 * 1024; | ||
| 22 | -const SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 23 | - | ||
| 24 | -pub fn uploads_dir(data_dir: &Path) -> PathBuf { | ||
| 25 | - data_dir.join("oci").join("uploads") | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -pub fn blob_key(hex: &str) -> String { | ||
| 29 | - format!("oci/{hex}") | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -fn valid_session_id(id: &str) -> bool { | ||
| 33 | - id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric()) | ||
| 34 | -} | ||
| 35 | - | ||
| 36 | -fn session_path(dir: &Path, id: &str) -> PathBuf { | ||
| 37 | - dir.join(id) | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -fn sidecar_path(dir: &Path, id: &str) -> PathBuf { | ||
| 41 | - dir.join(format!("{id}.repo")) | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -pub async fn new_session(data_dir: &Path, name: &str) -> std::io::Result<String> { | ||
| 45 | - let dir = uploads_dir(data_dir); | ||
| 46 | - tokio::fs::create_dir_all(&dir).await?; | ||
| 47 | - remove_stale(&dir).await; | ||
| 48 | - let id = ulid::Ulid::generate().to_string(); | ||
| 49 | - tokio::fs::File::create_new(session_path(&dir, &id)).await?; | ||
| 50 | - tokio::fs::write(sidecar_path(&dir, &id), name).await?; | ||
| 51 | - Ok(id) | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | -async fn remove_stale(dir: &Path) { | ||
| 55 | - let Ok(mut entries) = tokio::fs::read_dir(dir).await else { | ||
| 56 | - return; | ||
| 57 | - }; | ||
| 58 | - let now = SystemTime::now(); | ||
| 59 | - while let Ok(Some(entry)) = entries.next_entry().await { | ||
| 60 | - let path = entry.path(); | ||
| 61 | - if path.extension().is_some_and(|ext| ext == "repo") { | ||
| 62 | - continue; | ||
| 63 | - } | ||
| 64 | - let Ok(meta) = entry.metadata().await else { | ||
| 65 | - continue; | ||
| 66 | - }; | ||
| 67 | - let age = meta | ||
| 68 | - .modified() | ||
| 69 | - .ok() | ||
| 70 | - .and_then(|at| now.duration_since(at).ok()); | ||
| 71 | - if age.is_some_and(|age| age > SESSION_TTL) { | ||
| 72 | - if let Some(id) = path.file_name().and_then(|n| n.to_str()) { | ||
| 73 | - let _ = tokio::fs::remove_file(sidecar_path(dir, id)).await; | ||
| 74 | - } | ||
| 75 | - let _ = tokio::fs::remove_file(&path).await; | ||
| 76 | - } | ||
| 77 | - } | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -pub async fn session_belongs_to(data_dir: &Path, id: &str, name: &str) -> bool { | ||
| 81 | - if !valid_session_id(id) { | ||
| 82 | - return false; | ||
| 83 | - } | ||
| 84 | - let dir = uploads_dir(data_dir); | ||
| 85 | - match tokio::fs::read_to_string(sidecar_path(&dir, id)).await { | ||
| 86 | - Ok(owner) => owner == name && tokio::fs::metadata(session_path(&dir, id)).await.is_ok(), | ||
| 87 | - Err(_) => false, | ||
| 88 | - } | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -pub async fn remove_session(data_dir: &Path, id: &str) { | ||
| 92 | - let dir = uploads_dir(data_dir); | ||
| 93 | - let _ = tokio::fs::remove_file(sidecar_path(&dir, id)).await; | ||
| 94 | - let _ = tokio::fs::remove_file(session_path(&dir, id)).await; | ||
| 95 | -} | ||
| 96 | - | ||
| 97 | -pub async fn session_size(data_dir: &Path, id: &str) -> std::io::Result<u64> { | ||
| 98 | - let meta = tokio::fs::metadata(session_path(&uploads_dir(data_dir), id)).await?; | ||
| 99 | - Ok(meta.len()) | ||
| 100 | -} | ||
| 101 | - | ||
| 102 | -pub async fn append( | ||
| 103 | - data_dir: &Path, | ||
| 104 | - id: &str, | ||
| 105 | - body: Body, | ||
| 106 | - expected_start: Option<u64>, | ||
| 107 | -) -> Result<u64, Box<Response>> { | ||
| 108 | - let path = session_path(&uploads_dir(data_dir), id); | ||
| 109 | - let mut file = tokio::fs::OpenOptions::new() | ||
| 110 | - .append(true) | ||
| 111 | - .open(&path) | ||
| 112 | - .await | ||
| 113 | - .map_err(|e| Box::new(internal(e)))?; | ||
| 114 | - let size = file | ||
| 115 | - .metadata() | ||
| 116 | - .await | ||
| 117 | - .map_err(|e| Box::new(internal(e)))? | ||
| 118 | - .len(); | ||
| 119 | - if expected_start.is_some_and(|start| start != size) { | ||
| 120 | - return Err(Box::new(range_not_satisfiable(size))); | ||
| 121 | - } | ||
| 122 | - let mut written = size; | ||
| 123 | - let mut stream = std::pin::pin!(body.into_data_stream()); | ||
| 124 | - while let Some(chunk) = stream.next().await { | ||
| 125 | - let Ok(chunk) = chunk else { | ||
| 126 | - return Err(Box::new(oci_error( | ||
| 127 | - StatusCode::BAD_REQUEST, | ||
| 128 | - "BLOB_UPLOAD_INVALID", | ||
| 129 | - "the request body could not be read", | ||
| 130 | - ))); | ||
| 131 | - }; | ||
| 132 | - written = written.saturating_add(chunk.len() as u64); | ||
| 133 | - if written > MAX_BLOB_BYTES { | ||
| 134 | - return Err(Box::new(oci_error( | ||
| 135 | - StatusCode::PAYLOAD_TOO_LARGE, | ||
| 136 | - "SIZE_INVALID", | ||
| 137 | - "the blob is larger than the registry accepts", | ||
| 138 | - ))); | ||
| 139 | - } | ||
| 140 | - file.write_all(&chunk) | ||
| 141 | - .await | ||
| 142 | - .map_err(|e| Box::new(internal(e)))?; | ||
| 143 | - } | ||
| 144 | - file.flush().await.map_err(|e| Box::new(internal(e)))?; | ||
| 145 | - Ok(written) | ||
| 146 | -} | ||
| 147 | - | ||
| 148 | -pub async fn file_sha256(path: &Path) -> std::io::Result<String> { | ||
| 149 | - let path = path.to_owned(); | ||
| 150 | - tokio::task::spawn_blocking(move || { | ||
| 151 | - sha256_reader(std::fs::File::open(path)?).map(|(_, hex)| hex) | ||
| 152 | - }) | ||
| 153 | - .await | ||
| 154 | - .map_err(std::io::Error::other)? | ||
| 155 | -} | ||
| 156 | - | ||
| 157 | -pub async fn link( | ||
| 158 | - state: &AppState, | ||
| 159 | - package: &Package, | ||
| 160 | - hex: &str, | ||
| 161 | - size: u64, | ||
| 162 | - source: Option<&Path>, | ||
| 163 | -) -> Result<(), Refusal> { | ||
| 164 | - let _gc = gc::lock().await; | ||
| 165 | - let key = blob_key(hex); | ||
| 166 | - let exists = state.blobs.exists(&key).await.map_err(internal_refusal)?; | ||
| 167 | - if !exists { | ||
| 168 | - let Some(source) = source else { | ||
| 169 | - return Err(Box::new(oci_error( | ||
| 170 | - StatusCode::NOT_FOUND, | ||
| 171 | - "BLOB_UNKNOWN", | ||
| 172 | - "blob unknown to registry", | ||
| 173 | - ))); | ||
| 174 | - }; | ||
| 175 | - copy_into_store(state, &key, source).await?; | ||
| 176 | - } | ||
| 177 | - state | ||
| 178 | - .store | ||
| 179 | - .oci_link_blob(&package.id, &format!("sha256:{hex}"), size) | ||
| 180 | - .await | ||
| 181 | - .map_err(internal_refusal) | ||
| 182 | -} | ||
| 183 | - | ||
| 184 | -async fn copy_into_store(state: &AppState, key: &str, source: &Path) -> Result<(), Refusal> { | ||
| 185 | - let mut file = tokio::fs::File::open(source) | ||
| 186 | - .await | ||
| 187 | - .map_err(internal_refusal)?; | ||
| 188 | - let mut writer = state | ||
| 189 | - .blobs | ||
| 190 | - .begin(key, MAX_BLOB_BYTES) | ||
| 191 | - .await | ||
| 192 | - .map_err(internal_refusal)?; | ||
| 193 | - let mut buf = vec![0u8; CHUNK]; | ||
| 194 | - loop { | ||
| 195 | - let read = match file.read(&mut buf).await { | ||
| 196 | - Ok(read) => read, | ||
| 197 | - Err(e) => { | ||
| 198 | - writer.abort().await; | ||
| 199 | - return Err(internal_refusal(e)); | ||
| 200 | - } | ||
| 201 | - }; | ||
| 202 | - if read == 0 { | ||
| 203 | - break; | ||
| 204 | - } | ||
| 205 | - if let Err(e) = writer.push(&buf[..read]).await { | ||
| 206 | - writer.abort().await; | ||
| 207 | - return Err(internal_refusal(e)); | ||
| 208 | - } | ||
| 209 | - } | ||
| 210 | - writer.finish().await.map_err(internal_refusal)?; | ||
| 211 | - Ok(()) | ||
| 212 | -} | ||
| 213 | - | ||
| 214 | -pub fn created(name: &str, hex: &str) -> Response { | ||
| 215 | - let digest = format!("sha256:{hex}"); | ||
| 216 | - let mut res = Response::new(Body::empty()); | ||
| 217 | - *res.status_mut() = StatusCode::CREATED; | ||
| 218 | - insert(&mut res, "location", &format!("/v2/{name}/blobs/{digest}")); | ||
| 219 | - insert(&mut res, "docker-content-digest", &digest); | ||
| 220 | - res | ||
| 221 | -} | ||
| 222 | - | ||
| 223 | -pub fn upload_progress(name: &str, id: &str, size: u64) -> Response { | ||
| 224 | - let mut res = Response::new(Body::empty()); | ||
| 225 | - *res.status_mut() = StatusCode::ACCEPTED; | ||
| 226 | - insert( | ||
| 227 | - &mut res, | ||
| 228 | - "location", | ||
| 229 | - &format!("/v2/{name}/blobs/uploads/{id}"), | ||
| 230 | - ); | ||
| 231 | - insert(&mut res, "docker-upload-uuid", id); | ||
| 232 | - insert(&mut res, "range", &range_of(size)); | ||
| 233 | - res | ||
| 234 | -} | ||
| 235 | - | ||
| 236 | -pub fn range_of(size: u64) -> String { | ||
| 237 | - format!("0-{}", size.saturating_sub(1)) | ||
| 238 | -} | ||
| 239 | - | ||
| 240 | -fn range_not_satisfiable(size: u64) -> Response { | ||
| 241 | - let mut res = oci_error( | ||
| 242 | - StatusCode::RANGE_NOT_SATISFIABLE, | ||
| 243 | - "BLOB_UPLOAD_INVALID", | ||
| 244 | - "the chunk does not start where the upload ends", | ||
| 245 | - ); | ||
| 246 | - insert(&mut res, "range", &range_of(size)); | ||
| 247 | - res | ||
| 248 | -} | ||
| 249 | - | ||
| 250 | -pub fn insert(res: &mut Response, name: &'static str, value: &str) { | ||
| 251 | - if let Ok(value) = HeaderValue::from_str(value) { | ||
| 252 | - res.headers_mut() | ||
| 253 | - .insert(http::HeaderName::from_static(name), value); | ||
| 254 | - } | ||
| 255 | -} | ||
| 256 | - | ||
| 257 | -pub async fn get_blob( | ||
| 258 | - state: &AppState, | ||
| 259 | - caller: &Caller, | ||
| 260 | - name: &str, | ||
| 261 | - digest: &str, | ||
| 262 | - head: bool, | ||
| 263 | -) -> Response { | ||
| 264 | - let target = match auth::authorize(state, caller, name, false).await { | ||
| 265 | - Ok(target) => target, | ||
| 266 | - Err(res) => return *res, | ||
| 267 | - }; | ||
| 268 | - let Some(hex) = rules::parse_digest(digest) else { | ||
| 269 | - return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); | ||
| 270 | - }; | ||
| 271 | - let Some(package) = target.package.as_ref() else { | ||
| 272 | - return unknown_blob(); | ||
| 273 | - }; | ||
| 274 | - let size = match state.store.oci_blob_size(&package.id, digest).await { | ||
| 275 | - Ok(Some(size)) => size, | ||
| 276 | - Ok(None) => return unknown_blob(), | ||
| 277 | - Err(e) => return internal(e), | ||
| 278 | - }; | ||
| 279 | - let mut res = Response::new(Body::empty()); | ||
| 280 | - *res.status_mut() = StatusCode::OK; | ||
| 281 | - insert(&mut res, "docker-content-digest", digest); | ||
| 282 | - res.headers_mut().insert( | ||
| 283 | - CONTENT_TYPE, | ||
| 284 | - HeaderValue::from_static("application/octet-stream"), | ||
| 285 | - ); | ||
| 286 | - res.headers_mut() | ||
| 287 | - .insert(CONTENT_LENGTH, HeaderValue::from(size)); | ||
| 288 | - if head { | ||
| 289 | - return res; | ||
| 290 | - } | ||
| 291 | - match state.blobs.read(&blob_key(hex)).await { | ||
| 292 | - Ok(Some(read)) => { | ||
| 293 | - let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); | ||
| 294 | - *res.body_mut() = Body::new(StreamBody::new(chunks)); | ||
| 295 | - res | ||
| 296 | - } | ||
| 297 | - Ok(None) => internal("a linked blob is missing from the blob store"), | ||
| 298 | - Err(e) => internal(e), | ||
| 299 | - } | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -fn unknown_blob() -> Response { | ||
| 303 | - oci_error( | ||
| 304 | - StatusCode::NOT_FOUND, | ||
| 305 | - "BLOB_UNKNOWN", | ||
| 306 | - "blob unknown to registry", | ||
| 307 | - ) | ||
| 308 | -} | ||
| 309 | - | ||
| 310 | -pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Response { | ||
| 311 | - let Some(hex) = rules::parse_digest(digest) else { | ||
| 312 | - return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest"); | ||
| 313 | - }; | ||
| 314 | - let Some(package) = target.package.as_ref() else { | ||
| 315 | - return unknown_blob(); | ||
| 316 | - }; | ||
| 317 | - let _gc = gc::lock().await; | ||
| 318 | - match state.store.oci_blob_size(&package.id, digest).await { | ||
| 319 | - Ok(Some(_)) => {} | ||
| 320 | - Ok(None) => return unknown_blob(), | ||
| 321 | - Err(e) => return internal(e), | ||
| 322 | - } | ||
| 323 | - match state.store.oci_digest_referenced(&package.id, digest).await { | ||
| 324 | - Ok(true) => { | ||
| 325 | - return oci_error( | ||
| 326 | - StatusCode::BAD_REQUEST, | ||
| 327 | - "UNSUPPORTED", | ||
| 328 | - "a manifest still uses this blob; delete the manifest first", | ||
| 329 | - ); | ||
| 330 | - } | ||
| 331 | - Ok(false) => {} | ||
| 332 | - Err(e) => return internal(e), | ||
| 333 | - } | ||
| 334 | - if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await { | ||
| 335 | - return internal(e); | ||
| 336 | - } | ||
| 337 | - match state.store.oci_digest_linked(digest).await { | ||
| 338 | - Ok(false) => { | ||
| 339 | - if let Err(e) = state.blobs.delete(&blob_key(hex)).await { | ||
| 340 | - return internal(e); | ||
| 341 | - } | ||
| 342 | - } | ||
| 343 | - Ok(true) => {} | ||
| 344 | - Err(e) => return internal(e), | ||
| 345 | - } | ||
| 346 | - let mut res = Response::new(Body::empty()); | ||
| 347 | - *res.status_mut() = StatusCode::ACCEPTED; | ||
| 348 | - res | ||
| 349 | -} | ||
| 350 | - | ||
| 351 | -pub async fn write_package(state: &AppState, target: &Target) -> Result<Package, Refusal> { | ||
| 352 | - if let Some(package) = target.package.as_ref() { | ||
| 353 | - return Ok(package.clone()); | ||
| 354 | - } | ||
| 355 | - state | ||
| 356 | - .store | ||
| 357 | - .ensure_package(&target.owner.id, KIND_OCI, &target.image, &target.image) | ||
| 358 | - .await | ||
| 359 | - .map_err(internal_refusal) | ||
| 360 | -} | ||
| 361 | - | ||
| 362 | -pub async fn try_mount( | ||
| 363 | - state: &AppState, | ||
| 364 | - caller: &Caller, | ||
| 365 | - target: &Target, | ||
| 366 | - digest: &str, | ||
| 367 | - from: &str, | ||
| 368 | -) -> Result<bool, Refusal> { | ||
| 369 | - let Some(hex) = rules::parse_digest(digest) else { | ||
| 370 | - return Ok(false); | ||
| 371 | - }; | ||
| 372 | - let Ok(source) = auth::authorize(state, caller, from, false).await else { | ||
| 373 | - return Ok(false); | ||
| 374 | - }; | ||
| 375 | - let Some(source_package) = source.package.as_ref() else { | ||
| 376 | - return Ok(false); | ||
| 377 | - }; | ||
| 378 | - let Some(size) = state | ||
| 379 | - .store | ||
| 380 | - .oci_blob_size(&source_package.id, digest) | ||
| 381 | - .await | ||
| 382 | - .map_err(internal_refusal)? | ||
| 383 | - else { | ||
| 384 | - return Ok(false); | ||
| 385 | - }; | ||
| 386 | - if !state | ||
| 387 | - .blobs | ||
| 388 | - .exists(&blob_key(hex)) | ||
| 389 | - .await | ||
| 390 | - .map_err(internal_refusal)? | ||
| 391 | - { | ||
| 392 | - return Ok(false); | ||
| 393 | - } | ||
| 394 | - let package = write_package(state, target).await?; | ||
| 395 | - link(state, &package, hex, size, None).await?; | ||
| 396 | - Ok(true) | ||
| 397 | -} | ||
| 398 | - | ||
| 399 | -pub fn digest_arg(digest: &str) -> Result<&str, Box<Response>> { | ||
| 400 | - rules::parse_digest(digest).ok_or_else(|| { | ||
| 401 | - Box::new(oci_error( | ||
| 402 | - StatusCode::BAD_REQUEST, | ||
| 403 | - "DIGEST_INVALID", | ||
| 404 | - "invalid digest", | ||
| 405 | - )) | ||
| 406 | - }) | ||
| 407 | -} | ||
| 408 | - | ||
| 409 | -pub fn content_range_start(headers: &http::HeaderMap) -> Option<u64> { | ||
| 410 | - let value = headers.get("content-range")?.to_str().ok()?; | ||
| 411 | - value.split('-').next()?.trim().parse().ok() | ||
| 412 | -} | ||
crates/forge-web-app/src/oci/gc.rsdeleted+0 -53
| @@ -1,53 +0,0 @@ | |||
| 1 | -use std::time::{Duration, SystemTime}; | ||
| 2 | - | ||
| 3 | -use tokio::sync::{Mutex, MutexGuard}; | ||
| 4 | - | ||
| 5 | -use super::blobs::blob_key; | ||
| 6 | -use crate::state::AppState; | ||
| 7 | - | ||
| 8 | -static LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 9 | - | ||
| 10 | -pub const GRACE: Duration = Duration::from_secs(60 * 60); | ||
| 11 | - | ||
| 12 | -pub async fn lock() -> MutexGuard<'static, ()> { | ||
| 13 | - LOCK.lock().await | ||
| 14 | -} | ||
| 15 | - | ||
| 16 | -pub async fn sweep_orphans(state: &AppState) -> forge_core::Result<usize> { | ||
| 17 | - let cutoff = SystemTime::now() - GRACE; | ||
| 18 | - let mut removed = 0; | ||
| 19 | - for key in state.blobs.keys_older_than("oci/", cutoff).await? { | ||
| 20 | - let Some(hex) = key.strip_prefix("oci/") else { | ||
| 21 | - continue; | ||
| 22 | - }; | ||
| 23 | - let _guard = lock().await; | ||
| 24 | - if state | ||
| 25 | - .store | ||
| 26 | - .oci_digest_linked(&format!("sha256:{hex}")) | ||
| 27 | - .await? | ||
| 28 | - { | ||
| 29 | - continue; | ||
| 30 | - } | ||
| 31 | - state.blobs.delete(&key).await?; | ||
| 32 | - removed += 1; | ||
| 33 | - } | ||
| 34 | - Ok(removed) | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | -pub async fn sweep(state: &AppState, package_id: &str) -> forge_core::Result<usize> { | ||
| 38 | - let _guard = lock().await; | ||
| 39 | - let linked_before = forge_core::time::stamp_ago(GRACE); | ||
| 40 | - let dropped = state | ||
| 41 | - .store | ||
| 42 | - .oci_sweep_unreferenced(package_id, &linked_before) | ||
| 43 | - .await?; | ||
| 44 | - for digest in &dropped { | ||
| 45 | - if state.store.oci_digest_linked(digest).await? { | ||
| 46 | - continue; | ||
| 47 | - } | ||
| 48 | - if let Some(hex) = digest.strip_prefix("sha256:") { | ||
| 49 | - state.blobs.delete(&blob_key(hex)).await?; | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - Ok(dropped.len()) | ||
| 53 | -} | ||
crates/forge-web-app/src/oci/manifests.rsdeleted+0 -346
| @@ -1,346 +0,0 @@ | |||
| 1 | -use forge_core::User; | ||
| 2 | -use forge_core::oci as rules; | ||
| 3 | -use forge_core::packages::Package; | ||
| 4 | -use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; | ||
| 5 | -use serde_json::json; | ||
| 6 | -use sha2::{Digest, Sha256}; | ||
| 7 | -use topcoat::router::response::Response; | ||
| 8 | -use topcoat::router::{Body, StatusCode, to_bytes}; | ||
| 9 | - | ||
| 10 | -use super::auth::{self, Caller, internal}; | ||
| 11 | -use super::blobs::{insert, write_package}; | ||
| 12 | -use super::{gc, name_unknown, oci_error}; | ||
| 13 | -use crate::package_ops::bump_linked_repo; | ||
| 14 | -use crate::state::AppState; | ||
| 15 | - | ||
| 16 | -const MAX_MANIFEST_BYTES: usize = 4 * 1024 * 1024; | ||
| 17 | - | ||
| 18 | -enum Reference<'a> { | ||
| 19 | - Digest(&'a str), | ||
| 20 | - Tag(&'a str), | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -fn parse_reference(reference: &str) -> Result<Reference<'_>, Box<Response>> { | ||
| 24 | - if reference.contains(':') { | ||
| 25 | - if rules::parse_digest(reference).is_some() { | ||
| 26 | - Ok(Reference::Digest(reference)) | ||
| 27 | - } else { | ||
| 28 | - Err(Box::new(oci_error( | ||
| 29 | - StatusCode::BAD_REQUEST, | ||
| 30 | - "DIGEST_INVALID", | ||
| 31 | - "invalid digest", | ||
| 32 | - ))) | ||
| 33 | - } | ||
| 34 | - } else if rules::valid_tag(reference) { | ||
| 35 | - Ok(Reference::Tag(reference)) | ||
| 36 | - } else { | ||
| 37 | - Err(Box::new(oci_error( | ||
| 38 | - StatusCode::BAD_REQUEST, | ||
| 39 | - "TAG_INVALID", | ||
| 40 | - "invalid tag", | ||
| 41 | - ))) | ||
| 42 | - } | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -fn sha256_of(bytes: &[u8]) -> String { | ||
| 46 | - format!("sha256:{}", hex::encode(Sha256::digest(bytes))) | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -fn manifest_unknown() -> Response { | ||
| 50 | - oci_error( | ||
| 51 | - StatusCode::NOT_FOUND, | ||
| 52 | - "MANIFEST_UNKNOWN", | ||
| 53 | - "manifest unknown to registry", | ||
| 54 | - ) | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -pub async fn put_manifest( | ||
| 58 | - state: &AppState, | ||
| 59 | - caller: &Caller, | ||
| 60 | - name: &str, | ||
| 61 | - reference: &str, | ||
| 62 | - content_type: Option<&str>, | ||
| 63 | - body: Body, | ||
| 64 | -) -> Response { | ||
| 65 | - let target = match auth::authorize(state, caller, name, true).await { | ||
| 66 | - Ok(target) => target, | ||
| 67 | - Err(res) => return *res, | ||
| 68 | - }; | ||
| 69 | - let reference = match parse_reference(reference) { | ||
| 70 | - Ok(reference) => reference, | ||
| 71 | - Err(res) => return *res, | ||
| 72 | - }; | ||
| 73 | - let media_type = content_type | ||
| 74 | - .and_then(|value| value.split(';').next()) | ||
| 75 | - .map(str::trim) | ||
| 76 | - .unwrap_or_default() | ||
| 77 | - .to_owned(); | ||
| 78 | - if !rules::is_manifest_media_type(&media_type) { | ||
| 79 | - return oci_error( | ||
| 80 | - StatusCode::BAD_REQUEST, | ||
| 81 | - "MANIFEST_INVALID", | ||
| 82 | - "unsupported manifest media type", | ||
| 83 | - ); | ||
| 84 | - } | ||
| 85 | - let bytes = match to_bytes(body, MAX_MANIFEST_BYTES).await { | ||
| 86 | - Ok(bytes) => bytes, | ||
| 87 | - Err(_) => { | ||
| 88 | - return oci_error( | ||
| 89 | - StatusCode::PAYLOAD_TOO_LARGE, | ||
| 90 | - "SIZE_INVALID", | ||
| 91 | - "the manifest is larger than the registry accepts", | ||
| 92 | - ); | ||
| 93 | - } | ||
| 94 | - }; | ||
| 95 | - let digest = sha256_of(&bytes); | ||
| 96 | - if let Reference::Digest(wanted) = reference | ||
| 97 | - && wanted != digest | ||
| 98 | - { | ||
| 99 | - return oci_error( | ||
| 100 | - StatusCode::BAD_REQUEST, | ||
| 101 | - "DIGEST_INVALID", | ||
| 102 | - "the manifest does not match its digest", | ||
| 103 | - ); | ||
| 104 | - } | ||
| 105 | - let Ok(content) = String::from_utf8(bytes.to_vec()) else { | ||
| 106 | - return oci_error( | ||
| 107 | - StatusCode::BAD_REQUEST, | ||
| 108 | - "MANIFEST_INVALID", | ||
| 109 | - "manifest is not UTF-8", | ||
| 110 | - ); | ||
| 111 | - }; | ||
| 112 | - let refs = match rules::scan_manifest(&bytes) { | ||
| 113 | - Ok(refs) => refs, | ||
| 114 | - Err(message) => { | ||
| 115 | - return oci_error(StatusCode::BAD_REQUEST, "MANIFEST_INVALID", &message); | ||
| 116 | - } | ||
| 117 | - }; | ||
| 118 | - | ||
| 119 | - let _gc = gc::lock().await; | ||
| 120 | - let package = match write_package(state, &target).await { | ||
| 121 | - Ok(package) => package, | ||
| 122 | - Err(res) => return *res, | ||
| 123 | - }; | ||
| 124 | - for dep in &refs.digests { | ||
| 125 | - let present = if refs.is_index { | ||
| 126 | - state | ||
| 127 | - .store | ||
| 128 | - .oci_manifest(&package.id, dep) | ||
| 129 | - .await | ||
| 130 | - .map(|m| m.is_some()) | ||
| 131 | - } else { | ||
| 132 | - state | ||
| 133 | - .store | ||
| 134 | - .oci_blob_size(&package.id, dep) | ||
| 135 | - .await | ||
| 136 | - .map(|size| size.is_some()) | ||
| 137 | - }; | ||
| 138 | - match present { | ||
| 139 | - Ok(true) => {} | ||
| 140 | - Ok(false) => { | ||
| 141 | - return oci_error( | ||
| 142 | - StatusCode::BAD_REQUEST, | ||
| 143 | - "MANIFEST_BLOB_UNKNOWN", | ||
| 144 | - &format!("blob unknown to registry: {dep}"), | ||
| 145 | - ); | ||
| 146 | - } | ||
| 147 | - Err(e) => return internal(e), | ||
| 148 | - } | ||
| 149 | - } | ||
| 150 | - let stored = match state | ||
| 151 | - .store | ||
| 152 | - .oci_put_manifest( | ||
| 153 | - &package.id, | ||
| 154 | - &digest, | ||
| 155 | - &media_type, | ||
| 156 | - &content, | ||
| 157 | - refs.total_size, | ||
| 158 | - &refs.digests, | ||
| 159 | - ) | ||
| 160 | - .await | ||
| 161 | - { | ||
| 162 | - Ok(stored) => stored, | ||
| 163 | - Err(e) => return internal(e), | ||
| 164 | - }; | ||
| 165 | - if let Reference::Tag(tag) = reference | ||
| 166 | - && let Err(e) = state.store.oci_set_tag(&package.id, tag, &stored.id).await | ||
| 167 | - { | ||
| 168 | - return internal(e); | ||
| 169 | - } | ||
| 170 | - state.packages_live.bump(&target.owner.id); | ||
| 171 | - bump_linked_repo(state, &package.id).await; | ||
| 172 | - let mut res = Response::new(Body::empty()); | ||
| 173 | - *res.status_mut() = StatusCode::CREATED; | ||
| 174 | - insert( | ||
| 175 | - &mut res, | ||
| 176 | - "location", | ||
| 177 | - &format!("/v2/{name}/manifests/{digest}"), | ||
| 178 | - ); | ||
| 179 | - insert(&mut res, "docker-content-digest", &digest); | ||
| 180 | - res | ||
| 181 | -} | ||
| 182 | - | ||
| 183 | -pub async fn get_manifest( | ||
| 184 | - state: &AppState, | ||
| 185 | - caller: &Caller, | ||
| 186 | - name: &str, | ||
| 187 | - reference: &str, | ||
| 188 | - head: bool, | ||
| 189 | -) -> Response { | ||
| 190 | - let target = match auth::authorize(state, caller, name, false).await { | ||
| 191 | - Ok(target) => target, | ||
| 192 | - Err(res) => return *res, | ||
| 193 | - }; | ||
| 194 | - let reference = match parse_reference(reference) { | ||
| 195 | - Ok(reference) => reference, | ||
| 196 | - Err(res) => return *res, | ||
| 197 | - }; | ||
| 198 | - let Some(package) = target.package.as_ref() else { | ||
| 199 | - return name_unknown(); | ||
| 200 | - }; | ||
| 201 | - let found = match reference { | ||
| 202 | - Reference::Digest(digest) => state.store.oci_manifest(&package.id, digest).await, | ||
| 203 | - Reference::Tag(tag) => state.store.oci_tag_manifest(&package.id, tag).await, | ||
| 204 | - }; | ||
| 205 | - let manifest = match found { | ||
| 206 | - Ok(Some(manifest)) => manifest, | ||
| 207 | - Ok(None) => return manifest_unknown(), | ||
| 208 | - Err(e) => return internal(e), | ||
| 209 | - }; | ||
| 210 | - let len = manifest.content.len(); | ||
| 211 | - let mut res = Response::new(if head { | ||
| 212 | - Body::empty() | ||
| 213 | - } else { | ||
| 214 | - Body::from(manifest.content) | ||
| 215 | - }); | ||
| 216 | - *res.status_mut() = StatusCode::OK; | ||
| 217 | - if let Ok(value) = HeaderValue::from_str(&manifest.media_type) { | ||
| 218 | - res.headers_mut().insert(CONTENT_TYPE, value); | ||
| 219 | - } | ||
| 220 | - insert(&mut res, "docker-content-digest", &manifest.digest); | ||
| 221 | - res.headers_mut() | ||
| 222 | - .insert(CONTENT_LENGTH, HeaderValue::from(len)); | ||
| 223 | - res | ||
| 224 | -} | ||
| 225 | - | ||
| 226 | -pub async fn delete_manifest( | ||
| 227 | - state: &AppState, | ||
| 228 | - caller: &Caller, | ||
| 229 | - name: &str, | ||
| 230 | - reference: &str, | ||
| 231 | -) -> Response { | ||
| 232 | - let target = match auth::authorize(state, caller, name, true).await { | ||
| 233 | - Ok(target) => target, | ||
| 234 | - Err(res) => return *res, | ||
| 235 | - }; | ||
| 236 | - let reference = match parse_reference(reference) { | ||
| 237 | - Ok(reference) => reference, | ||
| 238 | - Err(res) => return *res, | ||
| 239 | - }; | ||
| 240 | - let Some(package) = target.package.as_ref() else { | ||
| 241 | - return name_unknown(); | ||
| 242 | - }; | ||
| 243 | - match reference { | ||
| 244 | - Reference::Digest(digest) => { | ||
| 245 | - let manifest = match state.store.oci_manifest(&package.id, digest).await { | ||
| 246 | - Ok(Some(manifest)) => manifest, | ||
| 247 | - Ok(None) => return manifest_unknown(), | ||
| 248 | - Err(e) => return internal(e), | ||
| 249 | - }; | ||
| 250 | - { | ||
| 251 | - let _gc = gc::lock().await; | ||
| 252 | - if let Err(e) = state.store.oci_delete_manifest(&manifest.id).await { | ||
| 253 | - return internal(e); | ||
| 254 | - } | ||
| 255 | - } | ||
| 256 | - if let Err(e) = gc::sweep(state, &package.id).await { | ||
| 257 | - return internal(e); | ||
| 258 | - } | ||
| 259 | - } | ||
| 260 | - Reference::Tag(tag) => match remove_tag(state, &target.owner, package, tag).await { | ||
| 261 | - Ok(true) => {} | ||
| 262 | - Ok(false) => return manifest_unknown(), | ||
| 263 | - Err(e) => return internal(e), | ||
| 264 | - }, | ||
| 265 | - } | ||
| 266 | - state.packages_live.bump(&target.owner.id); | ||
| 267 | - bump_linked_repo(state, &package.id).await; | ||
| 268 | - let mut res = Response::new(Body::empty()); | ||
| 269 | - *res.status_mut() = StatusCode::ACCEPTED; | ||
| 270 | - res | ||
| 271 | -} | ||
| 272 | - | ||
| 273 | -pub async fn remove_tag( | ||
| 274 | - state: &AppState, | ||
| 275 | - owner: &User, | ||
| 276 | - package: &Package, | ||
| 277 | - tag: &str, | ||
| 278 | -) -> forge_core::Result<bool> { | ||
| 279 | - let Some(manifest) = state.store.oci_tag_manifest(&package.id, tag).await? else { | ||
| 280 | - return Ok(false); | ||
| 281 | - }; | ||
| 282 | - { | ||
| 283 | - let _gc = gc::lock().await; | ||
| 284 | - state.store.oci_delete_tag(&package.id, tag).await?; | ||
| 285 | - let tags_left = state.store.oci_manifest_tag_count(&manifest.id).await?; | ||
| 286 | - let named = state | ||
| 287 | - .store | ||
| 288 | - .oci_digest_referenced(&package.id, &manifest.digest) | ||
| 289 | - .await?; | ||
| 290 | - if tags_left == 0 && !named { | ||
| 291 | - state.store.oci_delete_manifest(&manifest.id).await?; | ||
| 292 | - } | ||
| 293 | - } | ||
| 294 | - gc::sweep(state, &package.id).await?; | ||
| 295 | - state.packages_live.bump(&owner.id); | ||
| 296 | - bump_linked_repo(state, &package.id).await; | ||
| 297 | - Ok(true) | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | -pub async fn list_tags( | ||
| 301 | - state: &AppState, | ||
| 302 | - caller: &Caller, | ||
| 303 | - name: &str, | ||
| 304 | - n: Option<u64>, | ||
| 305 | - last: Option<&str>, | ||
| 306 | -) -> Response { | ||
| 307 | - let target = match auth::authorize(state, caller, name, false).await { | ||
| 308 | - Ok(target) => target, | ||
| 309 | - Err(res) => return *res, | ||
| 310 | - }; | ||
| 311 | - let Some(package) = target.package.as_ref() else { | ||
| 312 | - return name_unknown(); | ||
| 313 | - }; | ||
| 314 | - let last = last.unwrap_or(""); | ||
| 315 | - let wanted = n.map(|n| n.saturating_add(1)); | ||
| 316 | - let names = match state | ||
| 317 | - .store | ||
| 318 | - .oci_tag_names(&package.id, last, wanted.unwrap_or(u64::MAX)) | ||
| 319 | - .await | ||
| 320 | - { | ||
| 321 | - Ok(names) => names, | ||
| 322 | - Err(e) => return internal(e), | ||
| 323 | - }; | ||
| 324 | - let mut names = names; | ||
| 325 | - let mut link = None; | ||
| 326 | - if let Some(n) = n { | ||
| 327 | - let n = usize::try_from(n).unwrap_or(usize::MAX); | ||
| 328 | - if names.len() > n { | ||
| 329 | - names.truncate(n); | ||
| 330 | - if let Some(last_kept) = names.last() { | ||
| 331 | - link = Some(format!( | ||
| 332 | - "</v2/{name}/tags/list?n={n}&last={last_kept}>; rel=\"next\"" | ||
| 333 | - )); | ||
| 334 | - } | ||
| 335 | - } | ||
| 336 | - } | ||
| 337 | - let body = json!({ "name": name, "tags": names }); | ||
| 338 | - let mut res = Response::new(Body::from(body.to_string())); | ||
| 339 | - *res.status_mut() = StatusCode::OK; | ||
| 340 | - res.headers_mut() | ||
| 341 | - .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 342 | - if let Some(link) = link { | ||
| 343 | - insert(&mut res, "link", &link); | ||
| 344 | - } | ||
| 345 | - res | ||
| 346 | -} | ||
crates/forge-web-app/src/oci/mod.rsdeleted+0 -445
| @@ -1,445 +0,0 @@ | |||
| 1 | -pub mod auth; | ||
| 2 | -pub mod blobs; | ||
| 3 | -pub mod gc; | ||
| 4 | -pub mod manifests; | ||
| 5 | - | ||
| 6 | -use forge_core::oci as rules; | ||
| 7 | -use http::header::{CONTENT_TYPE, HeaderValue}; | ||
| 8 | -use serde_json::{Value, json}; | ||
| 9 | -use topcoat::context::{Cx, context}; | ||
| 10 | -use topcoat::router::request::{headers, method, uri}; | ||
| 11 | -use topcoat::router::response::Response; | ||
| 12 | -use topcoat::router::{Body, StatusCode, path_param, route}; | ||
| 13 | - | ||
| 14 | -use crate::state::AppState; | ||
| 15 | -use auth::Caller; | ||
| 16 | -use forge_core::time::now_unix; | ||
| 17 | - | ||
| 18 | -path_param!(*rest); | ||
| 19 | - | ||
| 20 | -const API_VERSION: &str = "docker-distribution-api-version"; | ||
| 21 | - | ||
| 22 | -pub fn oci_error(status: StatusCode, code: &str, message: &str) -> Response { | ||
| 23 | - let body = json!({ "errors": [{ "code": code, "message": message, "detail": Value::Null }] }); | ||
| 24 | - json_response(status, &body) | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -fn name_unknown() -> Response { | ||
| 28 | - oci_error( | ||
| 29 | - StatusCode::NOT_FOUND, | ||
| 30 | - "NAME_UNKNOWN", | ||
| 31 | - "repository name not known to registry", | ||
| 32 | - ) | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -fn json_response(status: StatusCode, value: &Value) -> Response { | ||
| 36 | - let mut res = Response::new(Body::from(value.to_string())); | ||
| 37 | - *res.status_mut() = status; | ||
| 38 | - res.headers_mut() | ||
| 39 | - .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 40 | - res.headers_mut() | ||
| 41 | - .insert(API_VERSION, HeaderValue::from_static("registry/2.0")); | ||
| 42 | - res | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -#[derive(Debug, PartialEq, Eq)] | ||
| 46 | -enum Op { | ||
| 47 | - Tags { name: String }, | ||
| 48 | - Manifest { name: String, reference: String }, | ||
| 49 | - UploadStart { name: String }, | ||
| 50 | - Upload { name: String, id: String }, | ||
| 51 | - Blob { name: String, digest: String }, | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | -fn parse_op(segments: &[&str]) -> Option<Op> { | ||
| 55 | - for (i, keyword) in segments.iter().enumerate().skip(1) { | ||
| 56 | - let name = segments[..i].join("/"); | ||
| 57 | - let rest = &segments[i + 1..]; | ||
| 58 | - let op = match *keyword { | ||
| 59 | - "tags" if rest == ["list"] => Op::Tags { name }, | ||
| 60 | - "manifests" if rest.len() == 1 => Op::Manifest { | ||
| 61 | - name, | ||
| 62 | - reference: rest[0].to_owned(), | ||
| 63 | - }, | ||
| 64 | - "blobs" if rest == ["uploads"] => Op::UploadStart { name }, | ||
| 65 | - "blobs" if rest.len() == 2 && rest[0] == "uploads" => Op::Upload { | ||
| 66 | - name, | ||
| 67 | - id: rest[1].to_owned(), | ||
| 68 | - }, | ||
| 69 | - "blobs" if rest.len() == 1 => Op::Blob { | ||
| 70 | - name, | ||
| 71 | - digest: rest[0].to_owned(), | ||
| 72 | - }, | ||
| 73 | - _ => continue, | ||
| 74 | - }; | ||
| 75 | - return Some(op); | ||
| 76 | - } | ||
| 77 | - None | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -fn query_pairs(cx: &Cx) -> Vec<(String, String)> { | ||
| 81 | - uri(cx) | ||
| 82 | - .query() | ||
| 83 | - .map(|q| { | ||
| 84 | - form_urlencoded::parse(q.as_bytes()) | ||
| 85 | - .map(|(k, v)| (k.into_owned(), v.into_owned())) | ||
| 86 | - .collect() | ||
| 87 | - }) | ||
| 88 | - .unwrap_or_default() | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -fn query_value(pairs: &[(String, String)], key: &str) -> Option<String> { | ||
| 92 | - pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()) | ||
| 93 | -} | ||
| 94 | - | ||
| 95 | -#[route(GET "/v2/")] | ||
| 96 | -async fn root(cx: &Cx) -> topcoat::Result<Response> { | ||
| 97 | - let state = context::<AppState>(cx); | ||
| 98 | - Ok(match auth::caller(cx).await { | ||
| 99 | - Ok(Caller { user: Some(_) }) => json_response(StatusCode::OK, &json!({})), | ||
| 100 | - Ok(_) => auth::challenge(state, None), | ||
| 101 | - Err(res) => *res, | ||
| 102 | - }) | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -#[route(GET "/v2/token")] | ||
| 106 | -async fn token(cx: &Cx) -> topcoat::Result<Response> { | ||
| 107 | - let state = context::<AppState>(cx); | ||
| 108 | - let caller = match auth::caller(cx).await { | ||
| 109 | - Ok(caller) => caller, | ||
| 110 | - Err(res) => return Ok(*res), | ||
| 111 | - }; | ||
| 112 | - let subject = caller.user.as_ref().map(|user| user.id.as_str()); | ||
| 113 | - let now = now_unix(); | ||
| 114 | - let token = forge_core::oci::issue_token(&state.key, subject, now + auth::TOKEN_TTL_SECS); | ||
| 115 | - let issued_at = time::OffsetDateTime::now_utc() | ||
| 116 | - .format(&time::format_description::well_known::Rfc3339) | ||
| 117 | - .unwrap_or_default(); | ||
| 118 | - Ok(json_response( | ||
| 119 | - StatusCode::OK, | ||
| 120 | - &json!({ | ||
| 121 | - "token": token, | ||
| 122 | - "access_token": token, | ||
| 123 | - "expires_in": auth::TOKEN_TTL_SECS, | ||
| 124 | - "issued_at": issued_at, | ||
| 125 | - }), | ||
| 126 | - )) | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -#[route(GET "/v2/{*rest}")] | ||
| 130 | -async fn get_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 131 | - Ok(dispatch(cx, body).await) | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -#[route(POST "/v2/{*rest}")] | ||
| 135 | -async fn post_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 136 | - Ok(dispatch(cx, body).await) | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | -#[route(PUT "/v2/{*rest}")] | ||
| 140 | -async fn put_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 141 | - Ok(dispatch(cx, body).await) | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -#[route(PATCH "/v2/{*rest}")] | ||
| 145 | -async fn patch_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 146 | - Ok(dispatch(cx, body).await) | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -#[route(DELETE "/v2/{*rest}")] | ||
| 150 | -async fn delete_v2(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 151 | - Ok(dispatch(cx, body).await) | ||
| 152 | -} | ||
| 153 | - | ||
| 154 | -async fn dispatch(cx: &Cx, body: Body) -> Response { | ||
| 155 | - let state = context::<AppState>(cx); | ||
| 156 | - let segments: Vec<String> = rest(cx).map(str::to_owned).collect(); | ||
| 157 | - let mut parts: Vec<&str> = segments.iter().map(String::as_str).collect(); | ||
| 158 | - while parts.last() == Some(&"") { | ||
| 159 | - parts.pop(); | ||
| 160 | - } | ||
| 161 | - let caller = match auth::caller(cx).await { | ||
| 162 | - Ok(caller) => caller, | ||
| 163 | - Err(res) => return *res, | ||
| 164 | - }; | ||
| 165 | - let method = method(cx).clone(); | ||
| 166 | - let read = method == http::Method::GET || method == http::Method::HEAD; | ||
| 167 | - let head = method == http::Method::HEAD; | ||
| 168 | - let pairs = query_pairs(cx); | ||
| 169 | - let headers = headers(cx).clone(); | ||
| 170 | - let Some(op) = parse_op(&parts) else { | ||
| 171 | - return oci_error(StatusCode::NOT_FOUND, "NAME_UNKNOWN", "not found"); | ||
| 172 | - }; | ||
| 173 | - match op { | ||
| 174 | - Op::Tags { name } if read => { | ||
| 175 | - let n = query_value(&pairs, "n").and_then(|v| v.parse::<u64>().ok()); | ||
| 176 | - let last = query_value(&pairs, "last"); | ||
| 177 | - manifests::list_tags(state, &caller, &name, n, last.as_deref()).await | ||
| 178 | - } | ||
| 179 | - Op::Manifest { name, reference } => match method { | ||
| 180 | - http::Method::GET | http::Method::HEAD => { | ||
| 181 | - manifests::get_manifest(state, &caller, &name, &reference, head).await | ||
| 182 | - } | ||
| 183 | - http::Method::PUT => { | ||
| 184 | - let content_type = headers | ||
| 185 | - .get(CONTENT_TYPE) | ||
| 186 | - .and_then(|v| v.to_str().ok()) | ||
| 187 | - .map(str::to_owned); | ||
| 188 | - manifests::put_manifest( | ||
| 189 | - state, | ||
| 190 | - &caller, | ||
| 191 | - &name, | ||
| 192 | - &reference, | ||
| 193 | - content_type.as_deref(), | ||
| 194 | - body, | ||
| 195 | - ) | ||
| 196 | - .await | ||
| 197 | - } | ||
| 198 | - http::Method::DELETE => { | ||
| 199 | - manifests::delete_manifest(state, &caller, &name, &reference).await | ||
| 200 | - } | ||
| 201 | - _ => unsupported(), | ||
| 202 | - }, | ||
| 203 | - Op::Blob { name, digest } => match method { | ||
| 204 | - http::Method::GET | http::Method::HEAD => { | ||
| 205 | - blobs::get_blob(state, &caller, &name, &digest, head).await | ||
| 206 | - } | ||
| 207 | - http::Method::DELETE => match auth::authorize(state, &caller, &name, true).await { | ||
| 208 | - Ok(target) => blobs::delete_blob(state, &target, &digest).await, | ||
| 209 | - Err(res) => *res, | ||
| 210 | - }, | ||
| 211 | - _ => unsupported(), | ||
| 212 | - }, | ||
| 213 | - Op::UploadStart { name } if method == http::Method::POST => { | ||
| 214 | - start_upload(state, &caller, &name, &pairs, body).await | ||
| 215 | - } | ||
| 216 | - Op::Upload { name, id } => { | ||
| 217 | - upload_step(state, &caller, &name, &id, &method, &headers, &pairs, body).await | ||
| 218 | - } | ||
| 219 | - _ => unsupported(), | ||
| 220 | - } | ||
| 221 | -} | ||
| 222 | - | ||
| 223 | -fn unsupported() -> Response { | ||
| 224 | - oci_error( | ||
| 225 | - StatusCode::METHOD_NOT_ALLOWED, | ||
| 226 | - "UNSUPPORTED", | ||
| 227 | - "the operation is unsupported", | ||
| 228 | - ) | ||
| 229 | -} | ||
| 230 | - | ||
| 231 | -async fn start_upload( | ||
| 232 | - state: &AppState, | ||
| 233 | - caller: &Caller, | ||
| 234 | - name: &str, | ||
| 235 | - pairs: &[(String, String)], | ||
| 236 | - body: Body, | ||
| 237 | -) -> Response { | ||
| 238 | - let target = match auth::authorize(state, caller, name, true).await { | ||
| 239 | - Ok(target) => target, | ||
| 240 | - Err(res) => return *res, | ||
| 241 | - }; | ||
| 242 | - if let (Some(mount), Some(from)) = (query_value(pairs, "mount"), query_value(pairs, "from")) { | ||
| 243 | - match blobs::try_mount(state, caller, &target, &mount, &from).await { | ||
| 244 | - Ok(true) => { | ||
| 245 | - let hex = rules::parse_digest(&mount).unwrap_or_default(); | ||
| 246 | - state.packages_live.bump(&target.owner.id); | ||
| 247 | - return blobs::created(name, hex); | ||
| 248 | - } | ||
| 249 | - Ok(false) => {} | ||
| 250 | - Err(res) => return *res, | ||
| 251 | - } | ||
| 252 | - } | ||
| 253 | - let data_dir = state.config.data_dir.clone(); | ||
| 254 | - let id = match blobs::new_session(&data_dir, name).await { | ||
| 255 | - Ok(id) => id, | ||
| 256 | - Err(e) => return auth::internal(e), | ||
| 257 | - }; | ||
| 258 | - let Some(digest) = query_value(pairs, "digest") else { | ||
| 259 | - return blobs::upload_progress(name, &id, 0); | ||
| 260 | - }; | ||
| 261 | - let hex = match blobs::digest_arg(&digest) { | ||
| 262 | - Ok(hex) => hex.to_owned(), | ||
| 263 | - Err(res) => { | ||
| 264 | - blobs::remove_session(&data_dir, &id).await; | ||
| 265 | - return *res; | ||
| 266 | - } | ||
| 267 | - }; | ||
| 268 | - if let Err(res) = blobs::append(&data_dir, &id, body, None).await { | ||
| 269 | - blobs::remove_session(&data_dir, &id).await; | ||
| 270 | - return *res; | ||
| 271 | - } | ||
| 272 | - finish_upload(state, &target, name, &id, &hex).await | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -async fn finish_upload( | ||
| 276 | - state: &AppState, | ||
| 277 | - target: &auth::Target, | ||
| 278 | - name: &str, | ||
| 279 | - id: &str, | ||
| 280 | - hex: &str, | ||
| 281 | -) -> Response { | ||
| 282 | - let data_dir = state.config.data_dir.clone(); | ||
| 283 | - let path = blobs::uploads_dir(&data_dir).join(id); | ||
| 284 | - let actual = match blobs::file_sha256(&path).await { | ||
| 285 | - Ok(actual) => actual, | ||
| 286 | - Err(e) => return auth::internal(e), | ||
| 287 | - }; | ||
| 288 | - if actual != hex { | ||
| 289 | - blobs::remove_session(&data_dir, id).await; | ||
| 290 | - return oci_error( | ||
| 291 | - StatusCode::BAD_REQUEST, | ||
| 292 | - "DIGEST_INVALID", | ||
| 293 | - "the content does not match the digest", | ||
| 294 | - ); | ||
| 295 | - } | ||
| 296 | - let size = match tokio::fs::metadata(&path).await { | ||
| 297 | - Ok(meta) => meta.len(), | ||
| 298 | - Err(e) => return auth::internal(e), | ||
| 299 | - }; | ||
| 300 | - let package = match blobs::write_package(state, target).await { | ||
| 301 | - Ok(package) => package, | ||
| 302 | - Err(res) => return *res, | ||
| 303 | - }; | ||
| 304 | - if let Err(res) = blobs::link(state, &package, hex, size, Some(&path)).await { | ||
| 305 | - blobs::remove_session(&data_dir, id).await; | ||
| 306 | - return *res; | ||
| 307 | - } | ||
| 308 | - blobs::remove_session(&data_dir, id).await; | ||
| 309 | - state.packages_live.bump(&target.owner.id); | ||
| 310 | - blobs::created(name, hex) | ||
| 311 | -} | ||
| 312 | - | ||
| 313 | -#[allow(clippy::too_many_arguments)] | ||
| 314 | -async fn upload_step( | ||
| 315 | - state: &AppState, | ||
| 316 | - caller: &Caller, | ||
| 317 | - name: &str, | ||
| 318 | - id: &str, | ||
| 319 | - method: &http::Method, | ||
| 320 | - headers: &http::HeaderMap, | ||
| 321 | - pairs: &[(String, String)], | ||
| 322 | - body: Body, | ||
| 323 | -) -> Response { | ||
| 324 | - let data_dir = state.config.data_dir.clone(); | ||
| 325 | - let target = match auth::authorize(state, caller, name, true).await { | ||
| 326 | - Ok(target) => target, | ||
| 327 | - Err(res) => return *res, | ||
| 328 | - }; | ||
| 329 | - if !blobs::session_belongs_to(&data_dir, id, name).await { | ||
| 330 | - return oci_error( | ||
| 331 | - StatusCode::NOT_FOUND, | ||
| 332 | - "BLOB_UPLOAD_UNKNOWN", | ||
| 333 | - "blob upload unknown to registry", | ||
| 334 | - ); | ||
| 335 | - } | ||
| 336 | - match *method { | ||
| 337 | - http::Method::GET => match blobs::session_size(&data_dir, id).await { | ||
| 338 | - Ok(size) => { | ||
| 339 | - let mut res = Response::new(Body::empty()); | ||
| 340 | - *res.status_mut() = StatusCode::NO_CONTENT; | ||
| 341 | - blobs::insert( | ||
| 342 | - &mut res, | ||
| 343 | - "location", | ||
| 344 | - &format!("/v2/{name}/blobs/uploads/{id}"), | ||
| 345 | - ); | ||
| 346 | - blobs::insert(&mut res, "docker-upload-uuid", id); | ||
| 347 | - blobs::insert(&mut res, "range", &blobs::range_of(size)); | ||
| 348 | - res | ||
| 349 | - } | ||
| 350 | - Err(e) => auth::internal(e), | ||
| 351 | - }, | ||
| 352 | - http::Method::PATCH => { | ||
| 353 | - if let Err(res) = | ||
| 354 | - blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await | ||
| 355 | - { | ||
| 356 | - return *res; | ||
| 357 | - } | ||
| 358 | - match blobs::session_size(&data_dir, id).await { | ||
| 359 | - Ok(size) => blobs::upload_progress(name, id, size), | ||
| 360 | - Err(e) => auth::internal(e), | ||
| 361 | - } | ||
| 362 | - } | ||
| 363 | - http::Method::PUT => { | ||
| 364 | - let Some(digest) = query_value(pairs, "digest") else { | ||
| 365 | - return oci_error( | ||
| 366 | - StatusCode::BAD_REQUEST, | ||
| 367 | - "DIGEST_INVALID", | ||
| 368 | - "digest is required", | ||
| 369 | - ); | ||
| 370 | - }; | ||
| 371 | - let hex = match blobs::digest_arg(&digest) { | ||
| 372 | - Ok(hex) => hex.to_owned(), | ||
| 373 | - Err(res) => return *res, | ||
| 374 | - }; | ||
| 375 | - if let Err(res) = | ||
| 376 | - blobs::append(&data_dir, id, body, blobs::content_range_start(headers)).await | ||
| 377 | - { | ||
| 378 | - return *res; | ||
| 379 | - } | ||
| 380 | - finish_upload(state, &target, name, id, &hex).await | ||
| 381 | - } | ||
| 382 | - http::Method::DELETE => { | ||
| 383 | - blobs::remove_session(&data_dir, id).await; | ||
| 384 | - let mut res = Response::new(Body::empty()); | ||
| 385 | - *res.status_mut() = StatusCode::NO_CONTENT; | ||
| 386 | - res | ||
| 387 | - } | ||
| 388 | - _ => unsupported(), | ||
| 389 | - } | ||
| 390 | -} | ||
| 391 | - | ||
| 392 | -#[cfg(test)] | ||
| 393 | -mod tests { | ||
| 394 | - use super::*; | ||
| 395 | - | ||
| 396 | - #[test] | ||
| 397 | - fn nested_names_parse_up_to_the_keyword() { | ||
| 398 | - assert_eq!( | ||
| 399 | - parse_op(&["tahinli", "app", "manifests", "latest"]), | ||
| 400 | - Some(Op::Manifest { | ||
| 401 | - name: "tahinli/app".into(), | ||
| 402 | - reference: "latest".into(), | ||
| 403 | - }) | ||
| 404 | - ); | ||
| 405 | - assert_eq!( | ||
| 406 | - parse_op(&["tahinli", "a", "b", "blobs", "uploads"]), | ||
| 407 | - Some(Op::UploadStart { | ||
| 408 | - name: "tahinli/a/b".into(), | ||
| 409 | - }) | ||
| 410 | - ); | ||
| 411 | - assert_eq!( | ||
| 412 | - parse_op(&["tahinli", "app", "tags", "list"]), | ||
| 413 | - Some(Op::Tags { | ||
| 414 | - name: "tahinli/app".into(), | ||
| 415 | - }) | ||
| 416 | - ); | ||
| 417 | - } | ||
| 418 | - | ||
| 419 | - #[test] | ||
| 420 | - fn a_keyword_inside_the_name_is_not_taken_for_one() { | ||
| 421 | - assert_eq!( | ||
| 422 | - parse_op(&["tahinli", "blobs", "x", "manifests", "v1"]), | ||
| 423 | - Some(Op::Manifest { | ||
| 424 | - name: "tahinli/blobs/x".into(), | ||
| 425 | - reference: "v1".into(), | ||
| 426 | - }) | ||
| 427 | - ); | ||
| 428 | - } | ||
| 429 | - | ||
| 430 | - #[test] | ||
| 431 | - fn upload_and_blob_paths_are_told_apart() { | ||
| 432 | - assert_eq!( | ||
| 433 | - parse_op(&["tahinli", "app", "blobs", "uploads", "ID1"]), | ||
| 434 | - Some(Op::Upload { | ||
| 435 | - name: "tahinli/app".into(), | ||
| 436 | - id: "ID1".into(), | ||
| 437 | - }) | ||
| 438 | - ); | ||
| 439 | - assert!(matches!( | ||
| 440 | - parse_op(&["tahinli", "app", "blobs", "sha256:abc"]), | ||
| 441 | - Some(Op::Blob { .. }) | ||
| 442 | - )); | ||
| 443 | - assert_eq!(parse_op(&["tahinli"]), None); | ||
| 444 | - } | ||
| 445 | -} | ||
crates/forge-web-app/src/package_ops.rsdeleted+0 -328
| @@ -1,328 +0,0 @@ | |||
| 1 | -use forge_core::authz::{Action, authorize}; | ||
| 2 | -use forge_core::cargo; | ||
| 3 | -use forge_core::model::User; | ||
| 4 | -use forge_core::packages::{KIND_CARGO, KIND_OCI, NewPackageVersion, Package}; | ||
| 5 | -use forge_core::store::orgs::OrgMemberRole; | ||
| 6 | -use forge_core::{Error, Repo}; | ||
| 7 | -use serde_json::{Value, json}; | ||
| 8 | -use sha2::{Digest, Sha256}; | ||
| 9 | - | ||
| 10 | -use crate::blobs::BlobRead; | ||
| 11 | -use crate::state::AppState; | ||
| 12 | - | ||
| 13 | -pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024; | ||
| 14 | -pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024; | ||
| 15 | - | ||
| 16 | -#[derive(Debug)] | ||
| 17 | -pub enum PackageError { | ||
| 18 | - Invalid(String), | ||
| 19 | - NotFound, | ||
| 20 | - Forbidden, | ||
| 21 | - Conflict(String), | ||
| 22 | - TooLarge, | ||
| 23 | - Internal(String), | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -impl From<Error> for PackageError { | ||
| 27 | - fn from(e: Error) -> Self { | ||
| 28 | - match e { | ||
| 29 | - Error::InvalidName(msg) | Error::Invalid(msg) => Self::Invalid(msg), | ||
| 30 | - Error::NotFound => Self::NotFound, | ||
| 31 | - Error::Conflict(msg) => Self::Conflict(msg), | ||
| 32 | - other => Self::Internal(other.to_string()), | ||
| 33 | - } | ||
| 34 | - } | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | -impl From<PackageError> for Error { | ||
| 38 | - fn from(e: PackageError) -> Self { | ||
| 39 | - Self::Database(format!("{e:?}")) | ||
| 40 | - } | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> { | ||
| 44 | - Ok(state.store.user_by_username(name).await?) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -async fn linked_repo_readable( | ||
| 48 | - state: &AppState, | ||
| 49 | - actor: Option<&User>, | ||
| 50 | - repo_id: &str, | ||
| 51 | -) -> Result<bool, PackageError> { | ||
| 52 | - let Some(repo) = state.store.repo_by_id(repo_id).await? else { | ||
| 53 | - return Ok(false); | ||
| 54 | - }; | ||
| 55 | - let (role, org_role) = match actor { | ||
| 56 | - Some(user) => ( | ||
| 57 | - state.store.collaborator_role(&repo.id, &user.id).await?, | ||
| 58 | - state | ||
| 59 | - .store | ||
| 60 | - .org_repo_role(&repo.owner_id, &user.id, &repo.id) | ||
| 61 | - .await?, | ||
| 62 | - ), | ||
| 63 | - None => (None, None), | ||
| 64 | - }; | ||
| 65 | - Ok(authorize(actor, &repo, role, org_role, Action::Read).is_ok()) | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -pub async fn may_read( | ||
| 69 | - state: &AppState, | ||
| 70 | - actor: Option<&User>, | ||
| 71 | - owner: &User, | ||
| 72 | - package: &Package, | ||
| 73 | -) -> Result<bool, PackageError> { | ||
| 74 | - if !package.private { | ||
| 75 | - return match &package.repo_id { | ||
| 76 | - Some(repo_id) => linked_repo_readable(state, actor, repo_id).await, | ||
| 77 | - None => Ok(true), | ||
| 78 | - }; | ||
| 79 | - } | ||
| 80 | - let Some(actor) = actor else { | ||
| 81 | - return Ok(false); | ||
| 82 | - }; | ||
| 83 | - if actor.is_admin || actor.id == owner.id { | ||
| 84 | - return Ok(true); | ||
| 85 | - } | ||
| 86 | - Ok(owner.is_org() | ||
| 87 | - && state | ||
| 88 | - .store | ||
| 89 | - .org_member_role(&owner.id, &actor.id) | ||
| 90 | - .await? | ||
| 91 | - .is_some()) | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -pub async fn may_publish( | ||
| 95 | - state: &AppState, | ||
| 96 | - actor: &User, | ||
| 97 | - owner: &User, | ||
| 98 | -) -> Result<bool, PackageError> { | ||
| 99 | - if actor.is_admin || actor.id == owner.id { | ||
| 100 | - return Ok(true); | ||
| 101 | - } | ||
| 102 | - if !owner.is_org() { | ||
| 103 | - return Ok(false); | ||
| 104 | - } | ||
| 105 | - let role = state.store.org_member_role(&owner.id, &actor.id).await?; | ||
| 106 | - Ok(role == Some(OrgMemberRole::Owner)) | ||
| 107 | -} | ||
| 108 | - | ||
| 109 | -pub async fn readable_package( | ||
| 110 | - state: &AppState, | ||
| 111 | - actor: Option<&User>, | ||
| 112 | - owner: &User, | ||
| 113 | - name: &str, | ||
| 114 | -) -> Result<Package, PackageError> { | ||
| 115 | - let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; | ||
| 116 | - let package = state | ||
| 117 | - .store | ||
| 118 | - .package_by_name(&owner.id, KIND_CARGO, &key) | ||
| 119 | - .await? | ||
| 120 | - .ok_or(PackageError::NotFound)?; | ||
| 121 | - if !may_read(state, actor, owner, &package).await? { | ||
| 122 | - return Err(PackageError::NotFound); | ||
| 123 | - } | ||
| 124 | - Ok(package) | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -pub async fn readable_oci_package( | ||
| 128 | - state: &AppState, | ||
| 129 | - actor: Option<&User>, | ||
| 130 | - owner: &User, | ||
| 131 | - name: &str, | ||
| 132 | -) -> Result<Package, PackageError> { | ||
| 133 | - let package = state | ||
| 134 | - .store | ||
| 135 | - .package_by_name(&owner.id, KIND_OCI, name) | ||
| 136 | - .await? | ||
| 137 | - .ok_or(PackageError::NotFound)?; | ||
| 138 | - if !may_read(state, actor, owner, &package).await? { | ||
| 139 | - return Err(PackageError::NotFound); | ||
| 140 | - } | ||
| 141 | - Ok(package) | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -pub async fn config_json(state: &AppState, owner: &User) -> Result<Value, PackageError> { | ||
| 145 | - let base = state.config.base_url.trim_end_matches('/'); | ||
| 146 | - let auth_required = state.store.owner_has_private_packages(&owner.id).await?; | ||
| 147 | - Ok(json!({ | ||
| 148 | - "dl": format!("{base}/api/packages/{}/cargo/download/{{crate}}/{{version}}", owner.username), | ||
| 149 | - "api": format!("{base}/api/packages/{}/cargo", owner.username), | ||
| 150 | - "auth-required": auth_required, | ||
| 151 | - })) | ||
| 152 | -} | ||
| 153 | - | ||
| 154 | -pub async fn index_file(state: &AppState, package: &Package) -> Result<String, PackageError> { | ||
| 155 | - let mut versions = state.store.package_versions(&package.id).await?; | ||
| 156 | - versions.reverse(); | ||
| 157 | - let mut out = String::new(); | ||
| 158 | - for version in versions { | ||
| 159 | - let mut line: Value = serde_json::from_str(&version.index_json) | ||
| 160 | - .map_err(|e| PackageError::Internal(format!("stored index line: {e}")))?; | ||
| 161 | - line["yanked"] = json!(version.yanked); | ||
| 162 | - out.push_str(&line.to_string()); | ||
| 163 | - out.push('\n'); | ||
| 164 | - } | ||
| 165 | - Ok(out) | ||
| 166 | -} | ||
| 167 | - | ||
| 168 | -pub async fn publish( | ||
| 169 | - state: &AppState, | ||
| 170 | - owner: &User, | ||
| 171 | - actor: &User, | ||
| 172 | - body: &[u8], | ||
| 173 | -) -> Result<(), PackageError> { | ||
| 174 | - if !may_publish(state, actor, owner).await? { | ||
| 175 | - return Err(PackageError::Forbidden); | ||
| 176 | - } | ||
| 177 | - let parsed = cargo::parse_publish(body).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 178 | - let meta = &parsed.metadata; | ||
| 179 | - let name = cargo::meta_str(meta, "name") | ||
| 180 | - .ok_or_else(|| PackageError::Invalid("metadata has no name".into()))?; | ||
| 181 | - let vers = cargo::meta_str(meta, "vers") | ||
| 182 | - .ok_or_else(|| PackageError::Invalid("metadata has no vers".into()))?; | ||
| 183 | - let key = cargo::crate_name_key(name).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 184 | - cargo::parse_version(vers).map_err(|e| PackageError::Invalid(e.to_string()))?; | ||
| 185 | - let krate = parsed.crate_file; | ||
| 186 | - if krate.len() as u64 > MAX_CRATE_BYTES { | ||
| 187 | - return Err(PackageError::TooLarge); | ||
| 188 | - } | ||
| 189 | - | ||
| 190 | - let checksum = hex::encode(Sha256::digest(krate)); | ||
| 191 | - let index_line = cargo::index_line(meta, &checksum) | ||
| 192 | - .map_err(|e| PackageError::Invalid(e.to_string()))? | ||
| 193 | - .to_string(); | ||
| 194 | - let readme = cargo::crate_readme(krate) | ||
| 195 | - .or_else(|| cargo::meta_str(meta, "readme").map(str::to_owned)) | ||
| 196 | - .filter(|text| !text.trim().is_empty()); | ||
| 197 | - let description = cargo::meta_str(meta, "description") | ||
| 198 | - .map(str::trim) | ||
| 199 | - .filter(|text| !text.is_empty()); | ||
| 200 | - | ||
| 201 | - let package = state | ||
| 202 | - .store | ||
| 203 | - .ensure_package(&owner.id, KIND_CARGO, name, &key) | ||
| 204 | - .await?; | ||
| 205 | - link_repo(state, owner, &package, meta).await?; | ||
| 206 | - | ||
| 207 | - let version = state | ||
| 208 | - .store | ||
| 209 | - .publish_package_version(&NewPackageVersion { | ||
| 210 | - package_id: &package.id, | ||
| 211 | - version: vers, | ||
| 212 | - checksum: &checksum, | ||
| 213 | - size: krate.len() as u64, | ||
| 214 | - index_json: &index_line, | ||
| 215 | - description, | ||
| 216 | - readme: readme.as_deref(), | ||
| 217 | - publisher_id: &actor.id, | ||
| 218 | - }) | ||
| 219 | - .await | ||
| 220 | - .map_err(|e| match e { | ||
| 221 | - Error::Conflict(_) => { | ||
| 222 | - PackageError::Conflict(format!("crate version `{name}@{vers}` is already uploaded")) | ||
| 223 | - } | ||
| 224 | - other => other.into(), | ||
| 225 | - })?; | ||
| 226 | - | ||
| 227 | - if let Err(e) = store_bytes(state, &blob_key(&version.id), krate).await { | ||
| 228 | - let _ = state.store.delete_package_version(&package.id, vers).await; | ||
| 229 | - return Err(PackageError::Internal(e.to_string())); | ||
| 230 | - } | ||
| 231 | - state.packages_live.bump(&owner.id); | ||
| 232 | - bump_linked_repo(state, &package.id).await; | ||
| 233 | - Ok(()) | ||
| 234 | -} | ||
| 235 | - | ||
| 236 | -pub async fn bump_linked_repo(state: &AppState, package_id: &str) { | ||
| 237 | - if let Ok(Some(package)) = state.store.package(package_id).await | ||
| 238 | - && let Some(repo_id) = package.repo_id | ||
| 239 | - { | ||
| 240 | - state.live.bump(&crate::live::Topic::Repo(repo_id)); | ||
| 241 | - } | ||
| 242 | -} | ||
| 243 | - | ||
| 244 | -pub async fn set_yanked( | ||
| 245 | - state: &AppState, | ||
| 246 | - owner: &User, | ||
| 247 | - actor: &User, | ||
| 248 | - name: &str, | ||
| 249 | - version: &str, | ||
| 250 | - yanked: bool, | ||
| 251 | -) -> Result<(), PackageError> { | ||
| 252 | - if !may_publish(state, actor, owner).await? { | ||
| 253 | - return Err(PackageError::Forbidden); | ||
| 254 | - } | ||
| 255 | - let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?; | ||
| 256 | - let package = state | ||
| 257 | - .store | ||
| 258 | - .package_by_name(&owner.id, KIND_CARGO, &key) | ||
| 259 | - .await? | ||
| 260 | - .ok_or(PackageError::NotFound)?; | ||
| 261 | - if !state | ||
| 262 | - .store | ||
| 263 | - .set_package_version_yanked(&package.id, version, yanked) | ||
| 264 | - .await? | ||
| 265 | - { | ||
| 266 | - return Err(PackageError::NotFound); | ||
| 267 | - } | ||
| 268 | - state.packages_live.bump(&owner.id); | ||
| 269 | - bump_linked_repo(state, &package.id).await; | ||
| 270 | - Ok(()) | ||
| 271 | -} | ||
| 272 | - | ||
| 273 | -pub async fn download( | ||
| 274 | - state: &AppState, | ||
| 275 | - actor: Option<&User>, | ||
| 276 | - owner: &User, | ||
| 277 | - name: &str, | ||
| 278 | - version: &str, | ||
| 279 | -) -> Result<BlobRead, PackageError> { | ||
| 280 | - let package = readable_package(state, actor, owner, name).await?; | ||
| 281 | - let found = state | ||
| 282 | - .store | ||
| 283 | - .package_version(&package.id, version) | ||
| 284 | - .await? | ||
| 285 | - .ok_or(PackageError::NotFound)?; | ||
| 286 | - state | ||
| 287 | - .blobs | ||
| 288 | - .read(&blob_key(&found.id)) | ||
| 289 | - .await? | ||
| 290 | - .ok_or(PackageError::NotFound) | ||
| 291 | -} | ||
| 292 | - | ||
| 293 | -fn blob_key(version_id: &str) -> String { | ||
| 294 | - format!("packages/{version_id}") | ||
| 295 | -} | ||
| 296 | - | ||
| 297 | -async fn link_repo( | ||
| 298 | - state: &AppState, | ||
| 299 | - owner: &User, | ||
| 300 | - package: &Package, | ||
| 301 | - meta: &Value, | ||
| 302 | -) -> Result<(), PackageError> { | ||
| 303 | - let linked: Option<Repo> = match cargo::meta_str(meta, "repository") | ||
| 304 | - .and_then(|url| cargo::repo_link(url, &state.config.base_url)) | ||
| 305 | - { | ||
| 306 | - Some((repo_owner, repo_name)) if repo_owner.eq_ignore_ascii_case(&owner.username) => state | ||
| 307 | - .store | ||
| 308 | - .repo_by_owner_and_name(&repo_owner, &repo_name) | ||
| 309 | - .await? | ||
| 310 | - .filter(|repo| repo.owner_id == owner.id), | ||
| 311 | - _ => None, | ||
| 312 | - }; | ||
| 313 | - let repo_id = linked.as_ref().map(|repo| repo.id.as_str()); | ||
| 314 | - if package.repo_id.as_deref() != repo_id { | ||
| 315 | - state.store.set_package_repo(&package.id, repo_id).await?; | ||
| 316 | - } | ||
| 317 | - Ok(()) | ||
| 318 | -} | ||
| 319 | - | ||
| 320 | -async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<()> { | ||
| 321 | - let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?; | ||
| 322 | - if let Err(e) = writer.push(bytes).await { | ||
| 323 | - writer.abort().await; | ||
| 324 | - return Err(e); | ||
| 325 | - } | ||
| 326 | - writer.finish().await?; | ||
| 327 | - Ok(()) | ||
| 328 | -} | ||
crates/forge-web-app/src/packages_live.rsdeleted+0 -68
| @@ -1,68 +0,0 @@ | |||
| 1 | -use std::collections::HashMap; | ||
| 2 | -use std::sync::{Mutex, MutexGuard, PoisonError}; | ||
| 3 | - | ||
| 4 | -use tokio::sync::watch; | ||
| 5 | - | ||
| 6 | -#[derive(Default)] | ||
| 7 | -pub struct PackagesLive { | ||
| 8 | - owners: Mutex<HashMap<String, watch::Sender<u64>>>, | ||
| 9 | -} | ||
| 10 | - | ||
| 11 | -impl PackagesLive { | ||
| 12 | - pub fn subscribe(&self, owner_id: &str) -> watch::Receiver<u64> { | ||
| 13 | - let mut owners = self.owners(); | ||
| 14 | - owners.retain(|_, tx| tx.receiver_count() > 0); | ||
| 15 | - owners | ||
| 16 | - .entry(owner_id.to_owned()) | ||
| 17 | - .or_insert_with(|| watch::channel(0).0) | ||
| 18 | - .subscribe() | ||
| 19 | - } | ||
| 20 | - | ||
| 21 | - pub fn bump(&self, owner_id: &str) { | ||
| 22 | - let mut owners = self.owners(); | ||
| 23 | - let Some(tx) = owners.get(owner_id) else { | ||
| 24 | - return; | ||
| 25 | - }; | ||
| 26 | - tx.send_modify(|generation| *generation = generation.wrapping_add(1)); | ||
| 27 | - if tx.receiver_count() == 0 { | ||
| 28 | - owners.remove(owner_id); | ||
| 29 | - } | ||
| 30 | - } | ||
| 31 | - | ||
| 32 | - fn owners(&self) -> MutexGuard<'_, HashMap<String, watch::Sender<u64>>> { | ||
| 33 | - self.owners.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 34 | - } | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | -#[cfg(test)] | ||
| 38 | -mod tests { | ||
| 39 | - use std::time::Duration; | ||
| 40 | - | ||
| 41 | - use super::*; | ||
| 42 | - | ||
| 43 | - #[tokio::test] | ||
| 44 | - async fn a_bump_wakes_only_the_subscribers_of_that_owner() { | ||
| 45 | - let live = PackagesLive::default(); | ||
| 46 | - let mut tahinli = live.subscribe("user-1"); | ||
| 47 | - let mut other = live.subscribe("user-2"); | ||
| 48 | - | ||
| 49 | - live.bump("user-1"); | ||
| 50 | - | ||
| 51 | - tokio::time::timeout(Duration::from_secs(1), tahinli.changed()) | ||
| 52 | - .await | ||
| 53 | - .expect("woken") | ||
| 54 | - .expect("open"); | ||
| 55 | - assert!( | ||
| 56 | - tokio::time::timeout(Duration::from_millis(50), other.changed()) | ||
| 57 | - .await | ||
| 58 | - .is_err() | ||
| 59 | - ); | ||
| 60 | - } | ||
| 61 | - | ||
| 62 | - #[test] | ||
| 63 | - fn a_bump_without_subscribers_leaves_no_entry() { | ||
| 64 | - let live = PackagesLive::default(); | ||
| 65 | - live.bump("nobody"); | ||
| 66 | - assert!(live.owners().is_empty()); | ||
| 67 | - } | ||
| 68 | -} | ||
crates/forge-web-app/src/prune.rsmodified+0 -3
| @@ -45,9 +45,6 @@ async fn sweep(state: &AppState) { | |||
| 45 | Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"), | 45 | Err(e) => tracing::error!(error = %e, repo_id = %id, "prune failed"), |
| 46 | } | 46 | } |
| 47 | } | 47 | } |
| 48 | - if let Err(e) = crate::oci::gc::sweep_orphans(state).await { | ||
| 49 | - tracing::error!(error = %e, "prune: oci orphan sweep failed"); | ||
| 50 | - } | ||
| 51 | } | 48 | } |
| 52 | 49 | ||
| 53 | async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) { | 50 | async fn blank_unreachable_messages(state: &AppState, repo_id: &str, dir: &Path) { |
crates/forge-web-app/src/state.rsmodified+0 -1
| @@ -31,7 +31,6 @@ pub struct AppState { | |||
| 31 | pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>, | 31 | pub runner_logs: Arc<crate::ci::runner_log::RunnerLogs>, |
| 32 | pub runner_metrics: Arc<crate::ci::runner_metrics::RunnerMetrics>, | 32 | pub runner_metrics: Arc<crate::ci::runner_metrics::RunnerMetrics>, |
| 33 | pub live: Arc<crate::live::LiveHub>, | 33 | pub live: Arc<crate::live::LiveHub>, |
| 34 | - pub packages_live: Arc<crate::packages_live::PackagesLive>, | ||
| 35 | } | 34 | } |
| 36 | 35 | ||
| 37 | #[cfg(any(test, feature = "test-support"))] | 36 | #[cfg(any(test, feature = "test-support"))] |
crates/forge-web-app/src/test_support/mod.rsmodified+0 -1
| @@ -86,7 +86,6 @@ pub async fn test_state(dir: &Path) -> AppState { | |||
| 86 | runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()), | 86 | runner_logs: Arc::new(crate::ci::runner_log::RunnerLogs::default()), |
| 87 | runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()), | 87 | runner_metrics: Arc::new(crate::ci::runner_metrics::RunnerMetrics::default()), |
| 88 | live: Arc::new(crate::live::LiveHub::default()), | 88 | live: Arc::new(crate::live::LiveHub::default()), |
| 89 | - packages_live: Arc::new(crate::packages_live::PackagesLive::default()), | ||
| 90 | } | 89 | } |
| 91 | } | 90 | } |
| 92 | 91 | ||
crates/forge-web-app/src/views/mod.rsmodified+0 -2
| @@ -41,7 +41,6 @@ use crate::i18n::link::{self as lk, K as LinkKey}; | |||
| 41 | use crate::i18n::migrate::{self as mg, K as MGK}; | 41 | use crate::i18n::migrate::{self as mg, K as MGK}; |
| 42 | use crate::i18n::misc::{self as mi, K as MK}; | 42 | use crate::i18n::misc::{self as mi, K as MK}; |
| 43 | use crate::i18n::orgs::{self as o, K as OK}; | 43 | use crate::i18n::orgs::{self as o, K as OK}; |
| 44 | -use crate::i18n::packages::{self as pk, K as PK}; | ||
| 45 | use crate::i18n::s; | 44 | use crate::i18n::s; |
| 46 | use crate::i18n::{self, Key, Lang, t}; | 45 | use crate::i18n::{self, Key, Lang, t}; |
| 47 | use crate::render::highlight::highlight_css; | 46 | use crate::render::highlight::highlight_css; |
| @@ -849,7 +848,6 @@ pub fn profile_items( | |||
| 849 | items.push(tab("snippets", cm::t(lang, CK::Snippets))); | 848 | items.push(tab("snippets", cm::t(lang, CK::Snippets))); |
| 850 | items.push(tab("stars", o::t(lang, OK::TabStars))); | 849 | items.push(tab("stars", o::t(lang, OK::TabStars))); |
| 851 | } | 850 | } |
| 852 | - items.push(tab("packages", pk::t(lang, PK::TabPackages))); | ||
| 853 | if own_profile { | 851 | if own_profile { |
| 854 | items.push(tab("organizations", o::t(lang, OK::Organizations))); | 852 | items.push(tab("organizations", o::t(lang, OK::Organizations))); |
| 855 | } | 853 | } |
crates/forge-web-base/src/i18n/audit_names.rsmodified+0 -4
| @@ -356,8 +356,6 @@ pub fn detail_key_name(lang: Lang, key: &str) -> Option<&'static str> { | |||
| 356 | ("fork_of", Lang::Tr) => Some("çatal kaynağı"), | 356 | ("fork_of", Lang::Tr) => Some("çatal kaynağı"), |
| 357 | ("enabled", Lang::En) => Some("enabled"), | 357 | ("enabled", Lang::En) => Some("enabled"), |
| 358 | ("enabled", Lang::Tr) => Some("açık"), | 358 | ("enabled", Lang::Tr) => Some("açık"), |
| 359 | - ("ecosystem", Lang::En) => Some("ecosystem"), | ||
| 360 | - ("ecosystem", Lang::Tr) => Some("ekosistem"), | ||
| 361 | ("default_repo_role", Lang::En) => Some("default repository role"), | 359 | ("default_repo_role", Lang::En) => Some("default repository role"), |
| 362 | ("default_repo_role", Lang::Tr) => Some("varsayılan depo rolü"), | 360 | ("default_repo_role", Lang::Tr) => Some("varsayılan depo rolü"), |
| 363 | ("commit", Lang::En) => Some("commit"), | 361 | ("commit", Lang::En) => Some("commit"), |
| @@ -376,8 +374,6 @@ pub fn detail_key_name(lang: Lang, key: &str) -> Option<&'static str> { | |||
| 376 | ("secret_cleared", Lang::Tr) => Some("gizli değer temizlendi"), | 374 | ("secret_cleared", Lang::Tr) => Some("gizli değer temizlendi"), |
| 377 | ("password_changed", Lang::En) => Some("password changed"), | 375 | ("password_changed", Lang::En) => Some("password changed"), |
| 378 | ("password_changed", Lang::Tr) => Some("parola değiştirildi"), | 376 | ("password_changed", Lang::Tr) => Some("parola değiştirildi"), |
| 379 | - ("package", Lang::En) => Some("package"), | ||
| 380 | - ("package", Lang::Tr) => Some("paket"), | ||
| 381 | ("user_ids", Lang::En) => Some("users"), | 377 | ("user_ids", Lang::En) => Some("users"), |
| 382 | ("user_ids", Lang::Tr) => Some("kullanıcılar"), | 378 | ("user_ids", Lang::Tr) => Some("kullanıcılar"), |
| 383 | ("base_light", Lang::En) => Some("light base"), | 379 | ("base_light", Lang::En) => Some("light base"), |
crates/forge-web-base/src/i18n/mod.rsmodified+0 -1
| @@ -44,7 +44,6 @@ pub mod migrate; | |||
| 44 | pub mod misc; | 44 | pub mod misc; |
| 45 | pub mod needs; | 45 | pub mod needs; |
| 46 | pub mod orgs; | 46 | pub mod orgs; |
| 47 | -pub mod packages; | ||
| 48 | pub mod pulls; | 47 | pub mod pulls; |
| 49 | pub mod pulls_review; | 48 | pub mod pulls_review; |
| 50 | pub mod releases_ci; | 49 | pub mod releases_ci; |
crates/forge-web-base/src/i18n/packages.rsdeleted+0 -33
| @@ -1,33 +0,0 @@ | |||
| 1 | -use super::Lang; | ||
| 2 | - | ||
| 3 | -strings! { | ||
| 4 | - K; | ||
| 5 | - ContainerKind => "Container", "Konteyner"; | ||
| 6 | - ContainerLogin => "Log in", "Giriş yap"; | ||
| 7 | - ContainerPull => "Pull the image", "İmajı çek"; | ||
| 8 | - ContainerPush => "Push a tag", "Bir etiket gönder"; | ||
| 9 | - ContainerTags => "Tags", "Etiketler"; | ||
| 10 | - DeleteTag => "Delete", "Sil"; | ||
| 11 | - NoTags => "No tags yet. Push an image to see it here.", "Henüz etiket yok. Burada görmek için bir imaj gönderin."; | ||
| 12 | - NoVersions => "No versions published yet.", "Henüz sürüm yayımlanmadı."; | ||
| 13 | - PackageTagCount => "tags", "etiket"; | ||
| 14 | - PackageTagCountOne => "tag", "etiket"; | ||
| 15 | - TabPackages => "Packages", "Paketler"; | ||
| 16 | - PackagesHeading => "Packages", "Paketler"; | ||
| 17 | - NoPackages => "No packages yet.", "Henüz paket yok."; | ||
| 18 | - PackageVersions => "Versions", "Sürümler"; | ||
| 19 | - PackageVersionCount => "versions", "sürüm"; | ||
| 20 | - PackageVersionCountOne => "version", "sürüm"; | ||
| 21 | - PackagePrivate => "Private", "Özel"; | ||
| 22 | - PackageRepoLink => "Repository", "Depo"; | ||
| 23 | - VersionYanked => "yanked", "geri çekildi"; | ||
| 24 | - Install => "Install", "Kurulum"; | ||
| 25 | - InstallRegistryConfig => "Registry config", "Kayıt defteri yapılandırması"; | ||
| 26 | - InstallAdd => "Add the crate", "Crate'i ekle"; | ||
| 27 | - InstallPublish => "Publish", "Yayımla"; | ||
| 28 | - InstallLogin => "Log in with a token", "Bir belirteçle giriş yapın"; | ||
| 29 | - CopyCommand => "Copy", "Kopyala"; | ||
| 30 | - Readme => "README", "README"; | ||
| 31 | - NoReadme => "This crate has no README.", "Bu crate'in README'si yok."; | ||
| 32 | - ScopePackages => "Packages", "Paketler"; | ||
| 33 | -} | ||
crates/forge-web-base/src/i18n/releases_ci.rsmodified+1 -0
| @@ -44,6 +44,7 @@ strings! { | |||
| 44 | Exit => "exit", "çıkış"; | 44 | Exit => "exit", "çıkış"; |
| 45 | Log => "Log", "Günlük"; | 45 | Log => "Log", "Günlük"; |
| 46 | FullLog => "Full log", "Tam günlük"; | 46 | FullLog => "Full log", "Tam günlük"; |
| 47 | + CopyCommand => "Copy", "Kopyala"; | ||
| 47 | CopyDone => "Copied", "Kopyalandı"; | 48 | CopyDone => "Copied", "Kopyalandı"; |
| 48 | CopyFailed => "Copy failed", "Kopyalanamadı"; | 49 | CopyFailed => "Copy failed", "Kopyalanamadı"; |
| 49 | FailOpenLog => "Open in full log", "Tam günlükte aç"; | 50 | FailOpenLog => "Open in full log", "Tam günlükte aç"; |
crates/forge-web-pages/src/lib.rsmodified+2 -2
| @@ -4,8 +4,8 @@ | |||
| 4 | pub(crate) use forge_web_app::test_support; | 4 | pub(crate) use forge_web_app::test_support; |
| 5 | pub(crate) use forge_web_app::{ | 5 | pub(crate) use forge_web_app::{ |
| 6 | api, audit, auth, automerge, blobs, ci, client_ip, i18n, internal, layers, live, merge, | 6 | api, audit, auth, automerge, blobs, ci, client_ip, i18n, internal, layers, live, merge, |
| 7 | - merge_queue, notify, notify_hub, oci, package_ops, post_update, raw, release_ops, render, | 7 | + merge_queue, notify, notify_hub, post_update, raw, release_ops, render, replication, |
| 8 | - replication, repo_stats, state, templates, views, webhooks, | 8 | + repo_stats, state, templates, views, webhooks, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | pub mod pages; | 11 | pub mod pages; |
crates/forge-web-pages/src/pages/code_live.rsmodified+4 -14
| @@ -1,6 +1,6 @@ | |||
| 1 | use std::path::PathBuf; | 1 | use std::path::PathBuf; |
| 2 | 2 | ||
| 3 | -use forge_core::{Repo as RepoRecord, User, Visibility}; | 3 | +use forge_core::{Repo as RepoRecord, Visibility}; |
| 4 | use forge_git::browse::{RefInfo, RefKind}; | 4 | use forge_git::browse::{RefInfo, RefKind}; |
| 5 | use topcoat::Result; | 5 | use topcoat::Result; |
| 6 | use topcoat::context::{Cx, context}; | 6 | use topcoat::context::{Cx, context}; |
| @@ -9,7 +9,6 @@ use topcoat::router::{path_param, query_params, route}; | |||
| 9 | 9 | ||
| 10 | use crate::auth::percent_encode; | 10 | use crate::auth::percent_encode; |
| 11 | use crate::live::{Topic, stream_changes_with}; | 11 | use crate::live::{Topic, stream_changes_with}; |
| 12 | -use crate::pages::packages::repo_package_links; | ||
| 13 | use crate::pages::refs::load_refs; | 12 | use crate::pages::refs::load_refs; |
| 14 | use crate::pages::repo_ctx::{fork_count, load_repo}; | 13 | use crate::pages::repo_ctx::{fork_count, load_repo}; |
| 15 | use crate::pages::repo_side::runs_fingerprint; | 14 | use crate::pages::repo_side::runs_fingerprint; |
| @@ -103,11 +102,7 @@ fn header_text(repo: &RepoRecord, counts: [u64; 5], rest: &str) -> String { | |||
| 103 | ) | 102 | ) |
| 104 | } | 103 | } |
| 105 | 104 | ||
| 106 | -async fn home_fingerprint( | 105 | +async fn home_fingerprint(state: &AppState, repo_id: &str) -> Result<String> { |
| 107 | - state: &AppState, | ||
| 108 | - repo_id: &str, | ||
| 109 | - viewer: Option<&User>, | ||
| 110 | -) -> Result<String> { | ||
| 111 | let mut release_text = String::new(); | 106 | let mut release_text = String::new(); |
| 112 | if let Some(release) = state.store.latest_release(repo_id).await? { | 107 | if let Some(release) = state.store.latest_release(repo_id).await? { |
| 113 | let assets = state.store.list_release_assets(&release.id).await?; | 108 | let assets = state.store.list_release_assets(&release.id).await?; |
| @@ -124,12 +119,7 @@ async fn home_fingerprint( | |||
| 124 | names.join(" ") | 119 | names.join(" ") |
| 125 | ); | 120 | ); |
| 126 | } | 121 | } |
| 127 | - let packages = repo_package_links(state, viewer, repo_id).await?; | 122 | + Ok(release_text) |
| 128 | - let package_text: Vec<String> = packages | ||
| 129 | - .iter() | ||
| 130 | - .map(|link| format!("{} {}", link.name, link.latest)) | ||
| 131 | - .collect(); | ||
| 132 | - Ok(format!("{release_text}\n{}", package_text.join("\n"))) | ||
| 133 | } | 123 | } |
| 134 | 124 | ||
| 135 | #[route(GET "/{owner}/{repo}/events")] | 125 | #[route(GET "/{owner}/{repo}/events")] |
| @@ -174,7 +164,7 @@ async fn repo_events(cx: &Cx) -> Result<Response> { | |||
| 174 | out = format!("{out}\n{refs}"); | 164 | out = format!("{out}\n{refs}"); |
| 175 | } | 165 | } |
| 176 | if home { | 166 | if home { |
| 177 | - let extra = home_fingerprint(&state, &repo_id, viewer.as_ref()).await?; | 167 | + let extra = home_fingerprint(&state, &repo_id).await?; |
| 178 | let runs = runs_fingerprint(&state, &repo_id).await?; | 168 | let runs = runs_fingerprint(&state, &repo_id).await?; |
| 179 | out = format!("{out}\n{extra}\n{runs}"); | 169 | out = format!("{out}\n{extra}\n{runs}"); |
| 180 | } | 170 | } |
crates/forge-web-pages/src/pages/mod.rsmodified+0 -2
| @@ -18,8 +18,6 @@ pub mod issue_parts; | |||
| 18 | pub mod issues_list; | 18 | pub mod issues_list; |
| 19 | pub mod issues_live; | 19 | pub mod issues_live; |
| 20 | pub mod notifications; | 20 | pub mod notifications; |
| 21 | -pub mod packages; | ||
| 22 | -pub mod packages_oci; | ||
| 23 | pub mod pull_live; | 21 | pub mod pull_live; |
| 24 | pub mod pull_reviews; | 22 | pub mod pull_reviews; |
| 25 | pub mod ref_live; | 23 | pub mod ref_live; |
crates/forge-web-pages/src/pages/packages.rsdeleted+0 -431
| @@ -1,431 +0,0 @@ | |||
| 1 | -use forge_core::User; | ||
| 2 | -use forge_core::packages::{KIND_CARGO, KIND_OCI, Package, PackageVersion}; | ||
| 3 | -use futures_util::{Stream, stream}; | ||
| 4 | -use serde::Deserialize; | ||
| 5 | -use tokio::sync::watch; | ||
| 6 | -use topcoat::Result; | ||
| 7 | -use topcoat::context::{Cx, context}; | ||
| 8 | -use topcoat::router::content::Form; | ||
| 9 | -use topcoat::router::content::sse::Event; | ||
| 10 | -use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; | ||
| 11 | -use topcoat::router::response::Response; | ||
| 12 | -use topcoat::router::{page, path_param, query_params, route}; | ||
| 13 | -use topcoat::view::{Unescaped, View, component, view}; | ||
| 14 | - | ||
| 15 | -use crate::auth::{current_user, require_csrf}; | ||
| 16 | -use crate::i18n::packages::{self as pk, K}; | ||
| 17 | -use crate::i18n::{self, Lang}; | ||
| 18 | -use crate::live::{changed_event, events_response}; | ||
| 19 | -use crate::oci::manifests; | ||
| 20 | -use crate::package_ops::{self, PackageError}; | ||
| 21 | -use crate::pages::packages_oci::{self, oci_package_view}; | ||
| 22 | -use crate::render::markdown::render_markdown; | ||
| 23 | -use crate::state::AppState; | ||
| 24 | -use crate::views::parts::{SubPart, head}; | ||
| 25 | -use crate::views::{empty_state, enc, rel_time, shell}; | ||
| 26 | - | ||
| 27 | -path_param!(owner); | ||
| 28 | -path_param!(name); | ||
| 29 | -path_param!(*pkg); | ||
| 30 | - | ||
| 31 | -pub struct PackageRow { | ||
| 32 | - pub name: String, | ||
| 33 | - pub href: String, | ||
| 34 | - pub latest: String, | ||
| 35 | - pub versions: u64, | ||
| 36 | - pub description: String, | ||
| 37 | - pub private: bool, | ||
| 38 | - pub container: bool, | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | -pub fn package_href(owner: &str, name: &str) -> String { | ||
| 42 | - format!("/{}/-/packages/{}", enc(owner), enc(name)) | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -pub fn events_href(owner: &str) -> String { | ||
| 46 | - format!("/{}/-/packages/events", enc(owner)) | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -pub async fn package_rows( | ||
| 50 | - state: &AppState, | ||
| 51 | - viewer: Option<&User>, | ||
| 52 | - owner: &User, | ||
| 53 | -) -> forge_core::Result<Vec<PackageRow>> { | ||
| 54 | - let mut summaries = state.store.list_packages(&owner.id, KIND_CARGO).await?; | ||
| 55 | - summaries.extend(state.store.list_packages(&owner.id, KIND_OCI).await?); | ||
| 56 | - summaries.sort_by(|a, b| a.package.name_key.cmp(&b.package.name_key)); | ||
| 57 | - let mut rows = Vec::new(); | ||
| 58 | - for summary in summaries { | ||
| 59 | - if summary.version_count == 0 { | ||
| 60 | - continue; | ||
| 61 | - } | ||
| 62 | - let readable = package_ops::may_read(state, viewer, owner, &summary.package).await?; | ||
| 63 | - if !readable { | ||
| 64 | - continue; | ||
| 65 | - } | ||
| 66 | - rows.push(PackageRow { | ||
| 67 | - href: package_href(&owner.username, &summary.package.name), | ||
| 68 | - name: summary.package.name, | ||
| 69 | - latest: summary.latest_version.unwrap_or_default(), | ||
| 70 | - versions: summary.version_count, | ||
| 71 | - description: summary.latest_description.unwrap_or_default(), | ||
| 72 | - private: summary.package.private, | ||
| 73 | - container: summary.package.kind == KIND_OCI, | ||
| 74 | - }); | ||
| 75 | - } | ||
| 76 | - Ok(rows) | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -#[topcoat::router::query_params(error = bad_request)] | ||
| 80 | -struct PackageQuery { | ||
| 81 | - tab: Option<String>, | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -#[page("/{owner}/-/packages/{*pkg}")] | ||
| 85 | -async fn package_page(cx: &Cx) -> Result<impl View> { | ||
| 86 | - let owner_name = owner(cx); | ||
| 87 | - let pkg_name = pkg(cx).collect::<Vec<_>>().join("/"); | ||
| 88 | - let pkg_name = pkg_name.as_str(); | ||
| 89 | - let state = context::<AppState>(cx); | ||
| 90 | - let viewer = current_user(cx).await?; | ||
| 91 | - let query = query_params::<PackageQuery>(cx)?; | ||
| 92 | - let actor = viewer.as_ref().map(|(u, _)| u); | ||
| 93 | - let lang = i18n::lang(cx, actor); | ||
| 94 | - | ||
| 95 | - let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 96 | - return Err(not_found().into()); | ||
| 97 | - }; | ||
| 98 | - let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await { | ||
| 99 | - Ok(package) => package, | ||
| 100 | - Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg).into()), | ||
| 101 | - Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await { | ||
| 102 | - Ok(package) => package, | ||
| 103 | - Err(PackageError::Internal(msg)) => { | ||
| 104 | - return Err(forge_core::Error::Database(msg).into()); | ||
| 105 | - } | ||
| 106 | - Err(_) => return Err(not_found().into()), | ||
| 107 | - }, | ||
| 108 | - }; | ||
| 109 | - let csrf = viewer | ||
| 110 | - .as_ref() | ||
| 111 | - .map(|(_, s)| s.csrf_token.clone()) | ||
| 112 | - .unwrap_or_default(); | ||
| 113 | - let oci = if package.kind == KIND_OCI { | ||
| 114 | - Some(packages_oci::model(state, actor, csrf, &owner, package.clone(), lang).await?) | ||
| 115 | - } else { | ||
| 116 | - None | ||
| 117 | - }; | ||
| 118 | - let versions = state.store.package_versions(&package.id).await?; | ||
| 119 | - let latest = versions.iter().find(|v| !v.yanked).or(versions.first()); | ||
| 120 | - let readme_html = latest | ||
| 121 | - .and_then(|v| v.readme.as_deref()) | ||
| 122 | - .filter(|text| !text.trim().is_empty()) | ||
| 123 | - .map(|text| render_markdown(text, None)) | ||
| 124 | - .unwrap_or_default(); | ||
| 125 | - let description = latest | ||
| 126 | - .and_then(|v| v.description.clone()) | ||
| 127 | - .unwrap_or_default(); | ||
| 128 | - let repo_link = match package.repo_id.as_deref() { | ||
| 129 | - Some(id) => match state.store.repo_by_id(id).await? { | ||
| 130 | - Some(repo) if repo.visibility == forge_core::Visibility::Public => { | ||
| 131 | - match state.store.user_by_id(&repo.owner_id).await? { | ||
| 132 | - Some(repo_owner) => Some(( | ||
| 133 | - format!("/{}/{}", enc(&repo_owner.username), enc(&repo.name)), | ||
| 134 | - format!("{}/{}", repo_owner.username, repo.name), | ||
| 135 | - )), | ||
| 136 | - None => None, | ||
| 137 | - } | ||
| 138 | - } | ||
| 139 | - _ => None, | ||
| 140 | - }, | ||
| 141 | - None => None, | ||
| 142 | - }; | ||
| 143 | - let base = state.config.base_url.trim_end_matches('/').to_owned(); | ||
| 144 | - let registry = format!("sparse+{base}/api/packages/{}/cargo/", owner.username); | ||
| 145 | - let config_block = format!("[registries.{}]\nindex = \"{registry}\"", owner.username); | ||
| 146 | - let add_cmd = format!("cargo add --registry {} {}", owner.username, package.name); | ||
| 147 | - let publish_cmd = format!("cargo publish --registry {}", owner.username); | ||
| 148 | - let login_cmd = format!("cargo login --registry {}", owner.username); | ||
| 149 | - let versions_tab = query.tab.as_deref() == Some("versions"); | ||
| 150 | - let readme_href = format!( | ||
| 151 | - "{}?tab=readme", | ||
| 152 | - package_href(&owner.username, &package.name) | ||
| 153 | - ); | ||
| 154 | - let versions_href = format!( | ||
| 155 | - "{}?tab=versions", | ||
| 156 | - package_href(&owner.username, &package.name) | ||
| 157 | - ); | ||
| 158 | - let events = events_href(&owner.username); | ||
| 159 | - let latest_text = latest.map(|v| v.version.clone()).unwrap_or_default(); | ||
| 160 | - let title = match &oci { | ||
| 161 | - Some(page) => format!("{} {}", page.package.name, page.newest_tag), | ||
| 162 | - None => format!("{} {}", package.name, latest_text), | ||
| 163 | - }; | ||
| 164 | - let view_model = PackagePage { | ||
| 165 | - owner_name: owner.username.clone(), | ||
| 166 | - package, | ||
| 167 | - latest_text, | ||
| 168 | - description, | ||
| 169 | - repo_link, | ||
| 170 | - readme_html, | ||
| 171 | - versions_tab, | ||
| 172 | - readme_href, | ||
| 173 | - versions_href, | ||
| 174 | - events, | ||
| 175 | - config_block, | ||
| 176 | - add_cmd, | ||
| 177 | - publish_cmd, | ||
| 178 | - login_cmd, | ||
| 179 | - versions, | ||
| 180 | - lang, | ||
| 181 | - }; | ||
| 182 | - Ok(view! { | ||
| 183 | - shell(title: title.as_str(), viewer: viewer.as_ref(), | ||
| 184 | - if let Some(page) = oci { | ||
| 185 | - oci_package_view(page: page) | ||
| 186 | - } else { | ||
| 187 | - package_view(page: view_model) | ||
| 188 | - }) | ||
| 189 | - }) | ||
| 190 | -} | ||
| 191 | - | ||
| 192 | -#[derive(Deserialize)] | ||
| 193 | -struct TagDeleteForm { | ||
| 194 | - #[serde(default)] | ||
| 195 | - csrf: String, | ||
| 196 | - #[serde(default)] | ||
| 197 | - package: String, | ||
| 198 | - #[serde(default)] | ||
| 199 | - tag: String, | ||
| 200 | -} | ||
| 201 | - | ||
| 202 | -#[route(POST "/{owner}/-/packages/tags/delete")] | ||
| 203 | -async fn tag_delete(cx: &Cx, Form(form): Form<TagDeleteForm>) -> Result<SeeOther> { | ||
| 204 | - let (viewer, _) = require_csrf(cx, &form.csrf).await?; | ||
| 205 | - let owner_name = owner(cx); | ||
| 206 | - let state = context::<AppState>(cx); | ||
| 207 | - let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 208 | - return Err(not_found().into()); | ||
| 209 | - }; | ||
| 210 | - let allowed = package_ops::may_publish(state, &viewer, &owner) | ||
| 211 | - .await | ||
| 212 | - .map_err(forge_core::Error::from)?; | ||
| 213 | - if !allowed { | ||
| 214 | - return Err(forbidden().into()); | ||
| 215 | - } | ||
| 216 | - let Some(package) = state | ||
| 217 | - .store | ||
| 218 | - .package_by_name(&owner.id, KIND_OCI, &form.package) | ||
| 219 | - .await? | ||
| 220 | - else { | ||
| 221 | - return Err(not_found().into()); | ||
| 222 | - }; | ||
| 223 | - manifests::remove_tag(state, &owner, &package, &form.tag).await?; | ||
| 224 | - Ok(see_other(package_href(&owner.username, &package.name))) | ||
| 225 | -} | ||
| 226 | - | ||
| 227 | -struct PackagePage { | ||
| 228 | - owner_name: String, | ||
| 229 | - package: Package, | ||
| 230 | - latest_text: String, | ||
| 231 | - description: String, | ||
| 232 | - repo_link: Option<(String, String)>, | ||
| 233 | - readme_html: String, | ||
| 234 | - versions_tab: bool, | ||
| 235 | - readme_href: String, | ||
| 236 | - versions_href: String, | ||
| 237 | - events: String, | ||
| 238 | - config_block: String, | ||
| 239 | - add_cmd: String, | ||
| 240 | - publish_cmd: String, | ||
| 241 | - login_cmd: String, | ||
| 242 | - versions: Vec<PackageVersion>, | ||
| 243 | - lang: Lang, | ||
| 244 | -} | ||
| 245 | - | ||
| 246 | -#[component] | ||
| 247 | -async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> { | ||
| 248 | - let lang = page.lang; | ||
| 249 | - let PackagePage { | ||
| 250 | - owner_name, | ||
| 251 | - package, | ||
| 252 | - latest_text, | ||
| 253 | - description, | ||
| 254 | - repo_link, | ||
| 255 | - readme_html, | ||
| 256 | - versions_tab, | ||
| 257 | - readme_href, | ||
| 258 | - versions_href, | ||
| 259 | - events, | ||
| 260 | - config_block, | ||
| 261 | - add_cmd, | ||
| 262 | - publish_cmd, | ||
| 263 | - login_cmd, | ||
| 264 | - versions, | ||
| 265 | - .. | ||
| 266 | - } = page; | ||
| 267 | - let has_readme = !readme_html.is_empty(); | ||
| 268 | - let has_repo = repo_link.is_some(); | ||
| 269 | - let (repo_href, repo_text) = repo_link.unwrap_or_default(); | ||
| 270 | - let private = package.private; | ||
| 271 | - let readme_on = !versions_tab; | ||
| 272 | - let readme_current: Option<&str> = readme_on.then_some("page"); | ||
| 273 | - let versions_current: Option<&str> = versions_tab.then_some("page"); | ||
| 274 | - let has_versions = !versions.is_empty(); | ||
| 275 | - let install = pk::t(lang, K::Install); | ||
| 276 | - let install_cmds = [ | ||
| 277 | - ( | ||
| 278 | - pk::t(lang, K::InstallRegistryConfig), | ||
| 279 | - "pkg-config", | ||
| 280 | - config_block, | ||
| 281 | - ), | ||
| 282 | - (pk::t(lang, K::InstallAdd), "pkg-add", add_cmd), | ||
| 283 | - (pk::t(lang, K::InstallPublish), "pkg-publish", publish_cmd), | ||
| 284 | - (pk::t(lang, K::InstallLogin), "pkg-login", login_cmd), | ||
| 285 | - ]; | ||
| 286 | - let copy_label = pk::t(lang, K::CopyCommand); | ||
| 287 | - let readme_label = pk::t(lang, K::Readme); | ||
| 288 | - let versions_label = pk::t(lang, K::PackageVersions); | ||
| 289 | - let no_readme = pk::t(lang, K::NoReadme); | ||
| 290 | - let mut sub = vec![ | ||
| 291 | - SubPart::text(owner_name.as_str()), | ||
| 292 | - SubPart::text(pk::t(lang, K::TabPackages)), | ||
| 293 | - ]; | ||
| 294 | - if private { | ||
| 295 | - sub.push(SubPart::text(pk::t(lang, K::PackagePrivate))); | ||
| 296 | - } | ||
| 297 | - if has_repo { | ||
| 298 | - sub.push(SubPart::link( | ||
| 299 | - format!("{}: {}", pk::t(lang, K::PackageRepoLink), repo_text), | ||
| 300 | - repo_href.as_str(), | ||
| 301 | - )); | ||
| 302 | - } | ||
| 303 | - let heading = format!("{} {}", package.name, latest_text) | ||
| 304 | - .trim_end() | ||
| 305 | - .to_owned(); | ||
| 306 | - Ok(view! { | ||
| 307 | - head(title: heading.as_str(), sub: sub) | ||
| 308 | - <nav class="tabs" aria-label=(package.name.as_str())> | ||
| 309 | - <a href=(readme_href.as_str()) aria-current=(readme_current)>(readme_label)</a> | ||
| 310 | - <a href=(versions_href.as_str()) aria-current=(versions_current)>(versions_label)</a> | ||
| 311 | - </nav> | ||
| 312 | - <div class="sheet" data-live=(events.as_str())> | ||
| 313 | - <section class="sec"> | ||
| 314 | - if !description.is_empty() { | ||
| 315 | - <p>(description.as_str())</p> | ||
| 316 | - } | ||
| 317 | - <h2>(install)</h2> | ||
| 318 | - for (hint, id, cmd) in install_cmds { | ||
| 319 | - <p class="hint">(hint)</p> | ||
| 320 | - <div class="copy-box"> | ||
| 321 | - <code id=(id)>(cmd.as_str())</code> | ||
| 322 | - <button type="button" data-copy=(id)>(copy_label)</button> | ||
| 323 | - </div> | ||
| 324 | - } | ||
| 325 | - </section> | ||
| 326 | - if versions_tab { | ||
| 327 | - if has_versions { | ||
| 328 | - for v in versions.iter() { | ||
| 329 | - <details class="row-open" data-kb-row=""> | ||
| 330 | - <summary class="line"> | ||
| 331 | - <span class="name"> | ||
| 332 | - (v.version.as_str()) | ||
| 333 | - if v.yanked { | ||
| 334 | - " " <span class="badge">(pk::t(lang, K::VersionYanked))</span> | ||
| 335 | - } | ||
| 336 | - </span> | ||
| 337 | - <span class="val">rel_time(lang: lang, stamp: v.created_at.as_str())</span> | ||
| 338 | - </summary> | ||
| 339 | - <div class="opened"> | ||
| 340 | - <code class="hint">(v.checksum.as_str())</code> | ||
| 341 | - </div> | ||
| 342 | - </details> | ||
| 343 | - } | ||
| 344 | - } else { | ||
| 345 | - empty_state(title: pk::t(lang, K::NoVersions)) | ||
| 346 | - } | ||
| 347 | - } else { | ||
| 348 | - if has_readme { | ||
| 349 | - <section class="sec"> | ||
| 350 | - <div class="markdown-body package-readme">(Unescaped::new_unchecked(readme_html))</div> | ||
| 351 | - </section> | ||
| 352 | - } else { | ||
| 353 | - <p class="state">(no_readme)</p> | ||
| 354 | - } | ||
| 355 | - } | ||
| 356 | - </div> | ||
| 357 | - }) | ||
| 358 | -} | ||
| 359 | - | ||
| 360 | -#[route(GET "/{owner}/-/packages/events")] | ||
| 361 | -async fn packages_events(cx: &Cx) -> Result<Response> { | ||
| 362 | - let owner_name = owner(cx); | ||
| 363 | - let state = context::<AppState>(cx); | ||
| 364 | - let Some(owner) = state.store.user_by_username(owner_name).await? else { | ||
| 365 | - return Err(not_found().into()); | ||
| 366 | - }; | ||
| 367 | - let wake = state.packages_live.subscribe(&owner.id); | ||
| 368 | - events_response(cx, owner_changes(wake)) | ||
| 369 | -} | ||
| 370 | - | ||
| 371 | -fn owner_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static { | ||
| 372 | - stream::unfold(wake, |mut wake| async move { | ||
| 373 | - wake.changed().await.ok()?; | ||
| 374 | - Some((changed_event("list".to_owned()), wake)) | ||
| 375 | - }) | ||
| 376 | -} | ||
| 377 | - | ||
| 378 | -pub struct PackageLink { | ||
| 379 | - pub name: String, | ||
| 380 | - pub href: String, | ||
| 381 | - pub latest: String, | ||
| 382 | -} | ||
| 383 | - | ||
| 384 | -pub async fn repo_package_links( | ||
| 385 | - state: &AppState, | ||
| 386 | - viewer: Option<&User>, | ||
| 387 | - repo_id: &str, | ||
| 388 | -) -> forge_core::Result<Vec<PackageLink>> { | ||
| 389 | - let mut links = Vec::new(); | ||
| 390 | - for package in state.store.packages_for_repo(repo_id).await? { | ||
| 391 | - let Some(owner) = state.store.user_by_id(&package.owner_id).await? else { | ||
| 392 | - continue; | ||
| 393 | - }; | ||
| 394 | - let readable = match package_ops::may_read(state, viewer, &owner, &package).await { | ||
| 395 | - Ok(readable) => readable, | ||
| 396 | - Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg)), | ||
| 397 | - Err(_) => false, | ||
| 398 | - }; | ||
| 399 | - if !readable { | ||
| 400 | - continue; | ||
| 401 | - } | ||
| 402 | - let versions = state.store.package_versions(&package.id).await?; | ||
| 403 | - let Some(latest) = versions.iter().find(|v| !v.yanked).or(versions.first()) else { | ||
| 404 | - continue; | ||
| 405 | - }; | ||
| 406 | - links.push(PackageLink { | ||
| 407 | - href: package_href(&owner.username, &package.name), | ||
| 408 | - name: package.name, | ||
| 409 | - latest: latest.version.clone(), | ||
| 410 | - }); | ||
| 411 | - } | ||
| 412 | - Ok(links) | ||
| 413 | -} | ||
| 414 | - | ||
| 415 | -#[component] | ||
| 416 | -pub async fn repo_packages_card(cx: &Cx, links: Vec<PackageLink>, lang: Lang) -> Result<impl View> { | ||
| 417 | - let heading = pk::t(lang, K::TabPackages); | ||
| 418 | - Ok(view! { | ||
| 419 | - <section class="sec repo-packages"> | ||
| 420 | - <h2>(heading)</h2> | ||
| 421 | - <div> | ||
| 422 | - for link in links.into_iter() { | ||
| 423 | - <a class="line" href=(link.href.as_str()) data-kb-row=""> | ||
| 424 | - <span class="name">(link.name.as_str())</span> | ||
| 425 | - <span class="val">(link.latest.as_str())</span> | ||
| 426 | - </a> | ||
| 427 | - } | ||
| 428 | - </div> | ||
| 429 | - </section> | ||
| 430 | - }) | ||
| 431 | -} | ||
crates/forge-web-pages/src/pages/packages_oci.rsdeleted+0 -146
| @@ -1,146 +0,0 @@ | |||
| 1 | -use forge_core::User; | ||
| 2 | -use forge_core::packages::{OciTag, Package}; | ||
| 3 | -use topcoat::Result; | ||
| 4 | -use topcoat::context::Cx; | ||
| 5 | -use topcoat::view::{View, component, view}; | ||
| 6 | - | ||
| 7 | -use crate::i18n::Lang; | ||
| 8 | -use crate::i18n::packages::{self as pk, K}; | ||
| 9 | -use crate::package_ops; | ||
| 10 | -use crate::state::AppState; | ||
| 11 | -use crate::views::parts::{SubPart, confirm_act, head}; | ||
| 12 | -use crate::views::{empty_state, enc, human_size, rel_time}; | ||
| 13 | - | ||
| 14 | -pub struct OciPage { | ||
| 15 | - pub owner_name: String, | ||
| 16 | - pub package: Package, | ||
| 17 | - pub newest_tag: String, | ||
| 18 | - pub host: String, | ||
| 19 | - pub tags: Vec<OciTag>, | ||
| 20 | - pub can_delete: bool, | ||
| 21 | - pub csrf: String, | ||
| 22 | - pub events: String, | ||
| 23 | - pub lang: Lang, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -pub async fn model( | ||
| 27 | - state: &AppState, | ||
| 28 | - viewer: Option<&User>, | ||
| 29 | - csrf: String, | ||
| 30 | - owner: &User, | ||
| 31 | - package: Package, | ||
| 32 | - lang: Lang, | ||
| 33 | -) -> forge_core::Result<OciPage> { | ||
| 34 | - let tags = state.store.oci_tags(&package.id).await?; | ||
| 35 | - let can_delete = match viewer { | ||
| 36 | - Some(user) => package_ops::may_publish(state, user, owner).await?, | ||
| 37 | - None => false, | ||
| 38 | - }; | ||
| 39 | - let base = state.config.base_url.trim_end_matches('/'); | ||
| 40 | - let host = base | ||
| 41 | - .split_once("://") | ||
| 42 | - .map_or(base, |(_, rest)| rest) | ||
| 43 | - .to_owned(); | ||
| 44 | - let newest_tag = tags.first().map(|t| t.tag.clone()).unwrap_or_default(); | ||
| 45 | - Ok(OciPage { | ||
| 46 | - owner_name: owner.username.clone(), | ||
| 47 | - package, | ||
| 48 | - newest_tag, | ||
| 49 | - host, | ||
| 50 | - tags, | ||
| 51 | - can_delete, | ||
| 52 | - csrf, | ||
| 53 | - events: crate::pages::packages::events_href(&owner.username), | ||
| 54 | - lang, | ||
| 55 | - }) | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -fn short_digest(digest: &str) -> String { | ||
| 59 | - match digest.split_once(':') { | ||
| 60 | - Some((alg, hex)) => format!("{alg}:{}", hex.get(..12).unwrap_or(hex)), | ||
| 61 | - None => digest.to_owned(), | ||
| 62 | - } | ||
| 63 | -} | ||
| 64 | - | ||
| 65 | -#[component] | ||
| 66 | -pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> { | ||
| 67 | - let lang = page.lang; | ||
| 68 | - let OciPage { | ||
| 69 | - owner_name, | ||
| 70 | - package, | ||
| 71 | - newest_tag, | ||
| 72 | - host, | ||
| 73 | - tags, | ||
| 74 | - can_delete, | ||
| 75 | - csrf, | ||
| 76 | - events, | ||
| 77 | - .. | ||
| 78 | - } = page; | ||
| 79 | - let image = format!("{host}/{owner_name}/{}", package.name); | ||
| 80 | - let has_tags = !tags.is_empty(); | ||
| 81 | - let pull = if newest_tag.is_empty() { | ||
| 82 | - format!("docker pull {image}") | ||
| 83 | - } else { | ||
| 84 | - format!("docker pull {image}:{newest_tag}") | ||
| 85 | - }; | ||
| 86 | - let login = format!("docker login {host}"); | ||
| 87 | - let push = format!("docker push {image}:<tag>"); | ||
| 88 | - let copy_label = pk::t(lang, K::CopyCommand); | ||
| 89 | - let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name)); | ||
| 90 | - let private = package.private; | ||
| 91 | - let tag_count = tags.len().to_string(); | ||
| 92 | - let mut sub = vec![SubPart::text(format!( | ||
| 93 | - "{owner_name} / {}", | ||
| 94 | - pk::t(lang, K::ContainerKind) | ||
| 95 | - ))]; | ||
| 96 | - if !newest_tag.is_empty() { | ||
| 97 | - sub.push(SubPart::mono(newest_tag.clone())); | ||
| 98 | - } | ||
| 99 | - if private { | ||
| 100 | - sub.push(SubPart::strong(pk::t(lang, K::PackagePrivate))); | ||
| 101 | - } | ||
| 102 | - Ok(view! { | ||
| 103 | - head(title: package.name.as_str(), sub: sub, live: Some(events.as_str())) | ||
| 104 | - <div class="sheet"> | ||
| 105 | - <section class="sec"> | ||
| 106 | - <h2>(pk::t(lang, K::Install))</h2> | ||
| 107 | - <p class="state">(pk::t(lang, K::ContainerLogin))</p> | ||
| 108 | - <div class="copy-box"> | ||
| 109 | - <code id="oci-login">(login.as_str())</code> | ||
| 110 | - <button type="button" data-copy="oci-login">(copy_label)</button> | ||
| 111 | - </div> | ||
| 112 | - if has_tags { | ||
| 113 | - <p class="state">(pk::t(lang, K::ContainerPull))</p> | ||
| 114 | - <div class="copy-box"> | ||
| 115 | - <code id="oci-pull">(pull.as_str())</code> | ||
| 116 | - <button type="button" data-copy="oci-pull">(copy_label)</button> | ||
| 117 | - </div> | ||
| 118 | - } | ||
| 119 | - <p class="state">(pk::t(lang, K::ContainerPush))</p> | ||
| 120 | - <div class="copy-box"> | ||
| 121 | - <code id="oci-push">(push.as_str())</code> | ||
| 122 | - <button type="button" data-copy="oci-push">(copy_label)</button> | ||
| 123 | - </div> | ||
| 124 | - </section> | ||
| 125 | - <section class="sec"> | ||
| 126 | - <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2> | ||
| 127 | - if has_tags { | ||
| 128 | - <div> | ||
| 129 | - for t in tags.iter() { | ||
| 130 | - <div class="line" data-kb-row=""> | ||
| 131 | - <span class="name"><code>(t.tag.as_str())</code></span> | ||
| 132 | - <span class="val"><code>(short_digest(&t.digest))</code> " · " (human_size(lang, t.size)) " · " rel_time(lang: lang, stamp: t.created_at.as_str()) " · " <code>(t.digest.as_str())</code></span> | ||
| 133 | - if can_delete { | ||
| 134 | - confirm_act(lang: lang, label: pk::t(lang, K::DeleteTag), action: delete_action.as_str(), csrf: csrf.as_str(), | ||
| 135 | - fields: vec![("package".to_owned(), package.name.clone()), ("tag".to_owned(), t.tag.clone())]) | ||
| 136 | - } | ||
| 137 | - </div> | ||
| 138 | - } | ||
| 139 | - </div> | ||
| 140 | - } else { | ||
| 141 | - empty_state(title: pk::t(lang, K::NoTags)) | ||
| 142 | - } | ||
| 143 | - </section> | ||
| 144 | - </div> | ||
| 145 | - }) | ||
| 146 | -} | ||
crates/forge-web-pages/src/pages/repo.rsmodified+1 -4
| @@ -19,7 +19,6 @@ use crate::i18n::{self, Lang}; | |||
| 19 | use crate::pages::code_live::{follows_branch, home_live_url}; | 19 | use crate::pages::code_live::{follows_branch, home_live_url}; |
| 20 | use crate::pages::finder::file_finder; | 20 | use crate::pages::finder::file_finder; |
| 21 | use crate::pages::notifications::watch_form; | 21 | use crate::pages::notifications::watch_form; |
| 22 | -use crate::pages::packages; | ||
| 23 | use crate::pages::refs::{load_refs, ref_links}; | 22 | use crate::pages::refs::{load_refs, ref_links}; |
| 24 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 23 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| 25 | use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts}; | 24 | use crate::pages::repo_side::{StripFacts, code_sub, commit_strip, run_pips, run_rows, tree_facts}; |
| @@ -422,8 +421,6 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | |||
| 422 | let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; | 421 | let latest = crate::pages::releases::latest_release_for_home(state, &ctx).await?; |
| 423 | let runs = run_rows(state, lang, repo).await?; | 422 | let runs = run_rows(state, lang, repo).await?; |
| 424 | let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; | 423 | let banners = recent_push_banners(state, &ctx, header.forked_from.clone()).await?; |
| 425 | - let viewer_user = ctx.viewer_user(); | ||
| 426 | - let packages = packages::repo_package_links(state, viewer_user, &repo.id).await?; | ||
| 427 | let now = now_unix(); | 424 | let now = now_unix(); |
| 428 | if head.is_none() { | 425 | if head.is_none() { |
| 429 | header.clone.downloads = None; | 426 | header.clone.downloads = None; |
| @@ -434,7 +431,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | |||
| 434 | }; | 431 | }; |
| 435 | let readme_file = readme.as_ref().map(|readme| readme.name.clone()); | 432 | let readme_file = readme.as_ref().map(|readme| readme.name.clone()); |
| 436 | let pips = run_pips(&runs); | 433 | let pips = run_pips(&runs); |
| 437 | - let sub = code_sub(lang, bar, facts, latest, packages, strip.total); | 434 | + let sub = code_sub(lang, bar, facts, latest, strip.total); |
| 438 | Ok(view! { | 435 | Ok(view! { |
| 439 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), | 436 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| 440 | repo_head(head: header, sub: sub, pips: pips) | 437 | repo_head(head: header, sub: sub, pips: pips) |
crates/forge-web-pages/src/pages/repo_side.rsmodified+0 -5
| @@ -12,7 +12,6 @@ use crate::i18n::Lang; | |||
| 12 | use crate::i18n::s; | 12 | use crate::i18n::s; |
| 13 | use crate::i18n::timeline as tl; | 13 | use crate::i18n::timeline as tl; |
| 14 | use crate::pages::ci_runs::run_href; | 14 | use crate::pages::ci_runs::run_href; |
| 15 | -use crate::pages::packages::PackageLink; | ||
| 16 | use crate::pages::releases::LatestRelease; | 15 | use crate::pages::releases::LatestRelease; |
| 17 | use crate::pages::tree::LatestBar; | 16 | use crate::pages::tree::LatestBar; |
| 18 | use crate::repo_stats::{LangShare, languages, license_file, license_id}; | 17 | use crate::repo_stats::{LangShare, languages, license_file, license_id}; |
| @@ -216,7 +215,6 @@ pub fn code_sub( | |||
| 216 | latest: Option<LatestBar>, | 215 | latest: Option<LatestBar>, |
| 217 | facts: Option<TreeFacts>, | 216 | facts: Option<TreeFacts>, |
| 218 | release: Option<LatestRelease>, | 217 | release: Option<LatestRelease>, |
| 219 | - packages: Vec<PackageLink>, | ||
| 220 | total: u64, | 218 | total: u64, |
| 221 | ) -> Vec<SubPart> { | 219 | ) -> Vec<SubPart> { |
| 222 | let mut parts = Vec::new(); | 220 | let mut parts = Vec::new(); |
| @@ -248,9 +246,6 @@ pub fn code_sub( | |||
| 248 | release.href.as_str(), | 246 | release.href.as_str(), |
| 249 | )); | 247 | )); |
| 250 | } | 248 | } |
| 251 | - for link in packages { | ||
| 252 | - parts.push(SubPart::link(link.name.as_str(), link.href.as_str())); | ||
| 253 | - } | ||
| 254 | parts | 249 | parts |
| 255 | } | 250 | } |
| 256 | 251 | ||
crates/forge-web-pages/src/pages/tree.rsmodified+1 -1
| @@ -443,7 +443,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> { | |||
| 443 | let runs = runs?; | 443 | let runs = runs?; |
| 444 | let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?; | 444 | let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?; |
| 445 | let pips = run_pips(&runs); | 445 | let pips = run_pips(&runs); |
| 446 | - let sub = code_sub(lang, bar, Some(facts), None, Vec::new(), strip.total); | 446 | + let sub = code_sub(lang, bar, Some(facts), None, strip.total); |
| 447 | let refs: Vec<RefInfo> = load_refs(ctx.path.clone()).await?; | 447 | let refs: Vec<RefInfo> = load_refs(ctx.path.clone()).await?; |
| 448 | let readme = load_readme(state, repo, &ctx.path, &ref_name, &commit, &dir, &entries).await?; | 448 | let readme = load_readme(state, repo, &ctx.path, &ref_name, &commit, &dir, &entries).await?; |
| 449 | let rows = entry_rows( | 449 | let rows = entry_rows( |
crates/forge-web-repo/src/pages/blob.rsmodified+1 -1
| @@ -265,7 +265,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | |||
| 265 | let runs = runs?; | 265 | let runs = runs?; |
| 266 | let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?; | 266 | let facts = tree_facts(state, repo, &ctx.path, &commit, &root_names).await?; |
| 267 | let pips = run_pips(&runs); | 267 | let pips = run_pips(&runs); |
| 268 | - let sub = code_sub(lang, bar, Some(facts), None, Vec::new(), strip.total); | 268 | + let sub = code_sub(lang, bar, Some(facts), None, strip.total); |
| 269 | let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo); | 269 | let (branches, tags) = ref_links(&refs, &ref_name, &repo.default_branch, repo); |
| 270 | let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", ""); | 270 | let branches_href = repo_href(&repo.owner_name, &repo.name, "branches", ""); |
| 271 | let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", ""); | 271 | let tags_href = repo_href(&repo.owner_name, &repo.name, "tags", ""); |
crates/forge-web/src/boot.rsmodified+0 -1
| @@ -126,7 +126,6 @@ pub async fn serve( | |||
| 126 | runner_logs: Arc::new(forge_web_app::ci::runner_log::RunnerLogs::default()), | 126 | runner_logs: Arc::new(forge_web_app::ci::runner_log::RunnerLogs::default()), |
| 127 | runner_metrics: Arc::new(forge_web_app::ci::runner_metrics::RunnerMetrics::default()), | 127 | runner_metrics: Arc::new(forge_web_app::ci::runner_metrics::RunnerMetrics::default()), |
| 128 | live: Arc::new(forge_web_app::live::LiveHub::default()), | 128 | live: Arc::new(forge_web_app::live::LiveHub::default()), |
| 129 | - packages_live: Arc::new(forge_web_app::packages_live::PackagesLive::default()), | ||
| 130 | }; | 129 | }; |
| 131 | if let Err(e) = forge_web_app::signatures::rebuild_allowed_signers(&state).await { | 130 | if let Err(e) = forge_web_app::signatures::rebuild_allowed_signers(&state).await { |
| 132 | tracing::error!(error = %e, "building the SSH allowed-signers file failed"); | 131 | tracing::error!(error = %e, "building the SSH allowed-signers file failed"); |
crates/forge-web/src/routes.snapmodified+0 -19
| @@ -84,7 +84,6 @@ page /snippets/{id}/edit Only([POST]) | |||
| 84 | page /snippets/{id}/revisions Only([GET]) | 84 | page /snippets/{id}/revisions Only([GET]) |
| 85 | page /verify/{token} Only([GET]) | 85 | page /verify/{token} Only([GET]) |
| 86 | page /verify/{token} Only([POST]) | 86 | page /verify/{token} Only([POST]) |
| 87 | -page /{owner}/-/packages/{*pkg} Only([GET]) | ||
| 88 | page /{owner}/{repo} Only([GET]) | 87 | page /{owner}/{repo} Only([GET]) |
| 89 | page /{owner}/{repo}/blame/{*rest} Only([GET]) | 88 | page /{owner}/{repo}/blame/{*rest} Only([GET]) |
| 90 | page /{owner}/{repo}/blob/{*rest} Only([GET]) | 89 | page /{owner}/{repo}/blob/{*rest} Only([GET]) |
| @@ -221,15 +220,6 @@ route /admin/server/reset Only([POST]) | |||
| 221 | route /admin/server/restart Only([POST]) | 220 | route /admin/server/restart Only([POST]) |
| 222 | route /admin/users/events Only([GET]) | 221 | route /admin/users/events Only([GET]) |
| 223 | route /admin/users/{user_id}/events Only([GET]) | 222 | route /admin/users/{user_id}/events Only([GET]) |
| 224 | -route /api/packages/{owner}/cargo/1/{name} Only([GET]) | ||
| 225 | -route /api/packages/{owner}/cargo/2/{name} Only([GET]) | ||
| 226 | -route /api/packages/{owner}/cargo/api/v1/crates/new Only([PUT]) | ||
| 227 | -route /api/packages/{owner}/cargo/api/v1/crates/{name}/owners Only([GET]) | ||
| 228 | -route /api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank Only([PUT]) | ||
| 229 | -route /api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank Only([DELETE]) | ||
| 230 | -route /api/packages/{owner}/cargo/config.json Only([GET]) | ||
| 231 | -route /api/packages/{owner}/cargo/download/{name}/{version} Only([GET]) | ||
| 232 | -route /api/packages/{owner}/cargo/{ab}/{cd}/{name} Only([GET]) | ||
| 233 | route /api/v1/ci/jobs/{job_id}/artifacts/{artifact_name} Only([PUT]) | 223 | route /api/v1/ci/jobs/{job_id}/artifacts/{artifact_name} Only([PUT]) |
| 234 | route /api/v1/ci/jobs/{job_id}/finish Only([POST]) | 224 | route /api/v1/ci/jobs/{job_id}/finish Only([POST]) |
| 235 | route /api/v1/ci/jobs/{job_id}/heartbeat Only([POST]) | 225 | route /api/v1/ci/jobs/{job_id}/heartbeat Only([POST]) |
| @@ -358,15 +348,6 @@ route /snippets/{id}/delete Only([POST]) | |||
| 358 | route /snippets/{id}/events Only([GET]) | 348 | route /snippets/{id}/events Only([GET]) |
| 359 | route /theme/custom.css Only([GET]) | 349 | route /theme/custom.css Only([GET]) |
| 360 | route /users/{username}/events Only([GET]) | 350 | route /users/{username}/events Only([GET]) |
| 361 | -route /v2/ Only([GET]) | ||
| 362 | -route /v2/token Only([GET]) | ||
| 363 | -route /v2/{*rest} Only([DELETE]) | ||
| 364 | -route /v2/{*rest} Only([GET]) | ||
| 365 | -route /v2/{*rest} Only([PATCH]) | ||
| 366 | -route /v2/{*rest} Only([POST]) | ||
| 367 | -route /v2/{*rest} Only([PUT]) | ||
| 368 | -route /{owner}/-/packages/events Only([GET]) | ||
| 369 | -route /{owner}/-/packages/tags/delete Only([POST]) | ||
| 370 | route /{owner}/{repo} Any | 351 | route /{owner}/{repo} Any |
| 371 | route /{owner}/{repo}/archive/{*rest} Only([GET]) | 352 | route /{owner}/{repo}/archive/{*rest} Only([GET]) |
| 372 | route /{owner}/{repo}/attachments Only([POST]) | 353 | route /{owner}/{repo}/attachments Only([POST]) |
docs/architecture.mdmodified+1 -1
| @@ -48,7 +48,7 @@ project_git/ | |||
| 48 | forge-ssh/ russh server: pubkey auth, exec allow-list and parse, GIT_PROTOCOL env, piping, timeouts | 48 | forge-ssh/ russh server: pubkey auth, exec allow-list and parse, GIT_PROTOCOL env, piping, timeouts |
| 49 | forge-web/ builds the `forge` binary: boot, admin CLI, and the route tests that span page crates | 49 | forge-web/ builds the `forge` binary: boot, admin CLI, and the route tests that span page crates |
| 50 | forge-web-base/ modules with no routes: i18n, render, theme and accents, templates, blobs | 50 | forge-web-base/ modules with no routes: i18n, render, theme and accents, templates, blobs |
| 51 | - forge-web-app/ everything below the pages: state, auth, live, views, CI, mail, backup, replication, git smart-HTTP, LFS, OCI, the HTTP APIs, test_support; its build.rs compiles the stylesheet | 51 | + forge-web-app/ everything below the pages: state, auth, live, views, CI, mail, backup, replication, git smart-HTTP, LFS, the HTTP APIs, test_support; its build.rs compiles the stylesheet |
| 52 | forge-web-pages/ pages the others build on: repo, tree, issues, pulls core, CI runs, wiki, releases, repo settings | 52 | forge-web-pages/ pages the others build on: repo, tree, issues, pulls core, CI runs, wiki, releases, repo settings |
| 53 | forge-web-account/ account, admin, org and profile pages (on forge-web-pages) | 53 | forge-web-account/ account, admin, org and profile pages (on forge-web-pages) |
| 54 | forge-web-repo/ code, commits, pull views, discussions, issue view pages (on forge-web-pages) | 54 | forge-web-repo/ code, commits, pull views, discussions, issue view pages (on forge-web-pages) |
docs/packages.mddeleted+0 -217
| @@ -1,217 +0,0 @@ | |||
| 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/_repo.scssmodified+1 -1
| @@ -339,7 +339,7 @@ html.tree-resizing .repo-split::before { | |||
| 339 | } | 339 | } |
| 340 | 340 | ||
| 341 | // The facts line under the repo header: license and size, a bar of the languages with its legend, | 341 | // The facts line under the repo header: license and size, a bar of the languages with its legend, |
| 342 | -// then the latest release and the packages as chips at the right end. | 342 | +// then the latest release as a chip at the right end. |
| 343 | .repo-strip { | 343 | .repo-strip { |
| 344 | display: flex; | 344 | display: flex; |
| 345 | flex-wrap: wrap; | 345 | flex-wrap: wrap; |
style/main.scssmodified+1 -1
| @@ -1922,7 +1922,7 @@ code { | |||
| 1922 | 1922 | ||
| 1923 | } | 1923 | } |
| 1924 | 1924 | ||
| 1925 | -// Phones: the four tabs fit the screen width with tighter padding, so Packages is not cut off. | 1925 | +// Phones: the tabs fit the screen width with tighter padding. |
| 1926 | @media (max-width: 480px) { | 1926 | @media (max-width: 480px) { |
| 1927 | 1927 | ||
| 1928 | } | 1928 | } |