forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

package_ops.rs363 lines, 12.7 KiBHistoryRawDownload
1//! Package registry rules of the web layer: who may read or publish a package, publishing a
2//! `.crate`, yanking a version, and the index and config files cargo reads. The protocol
3//! rules (names, index lines, publish bodies) live in `forge_core::cargo`; the HTTP routes in
4//! `api::packages` and the pages translate these results. Bytes go to the blob store under
5//! `packages/<version id>`, and each change is announced on the owner's live signal.
6
7use forge_core::authz::{Action, authorize};
8use forge_core::cargo;
9use forge_core::model::User;
10use forge_core::packages::{KIND_CARGO, KIND_OCI, NewPackageVersion, Package};
11use forge_core::store::orgs::OrgMemberRole;
12use forge_core::{Error, Repo};
13use serde_json::{Value, json};
14use sha2::{Digest, Sha256};
15
16use crate::blobs::BlobRead;
17use crate::state::AppState;
18
19/// Largest `.crate` accepted, in bytes. The limit crates.io uses.
20pub const MAX_CRATE_BYTES: u64 = 10 * 1024 * 1024;
21/// Largest publish body accepted: the crate plus its JSON metadata.
22pub const MAX_PUBLISH_BYTES: usize = 16 * 1024 * 1024;
23/// Bytes handed to the blob writer at a time.
24const PUSH_CHUNK: usize = 1024 * 1024;
25
26/// Why a registry request failed. The API maps each to a status and a cargo error body.
27#[derive(Debug)]
28pub enum PackageError {
29 Invalid(String),
30 NotFound,
31 Forbidden,
32 Conflict(String),
33 TooLarge,
34 Internal(String),
35}
36
37impl From<Error> for PackageError {
38 fn from(e: Error) -> Self {
39 match e {
40 Error::InvalidName(msg) | Error::Invalid(msg) => Self::Invalid(msg),
41 Error::NotFound => Self::NotFound,
42 Error::Conflict(msg) => Self::Conflict(msg),
43 other => Self::Internal(other.to_string()),
44 }
45 }
46}
47
48/// The user or org a registry path names. `None` when no such account exists.
49pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> {
50 Ok(state.store.user_by_username(name).await?)
51}
52
53/// True when `actor` may read the repo a package is linked to. A link to a missing repo counts
54/// as unreadable, so a dangling link never exposes the package.
55async fn linked_repo_readable(
56 state: &AppState,
57 actor: Option<&User>,
58 repo_id: &str,
59) -> Result<bool, PackageError> {
60 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
61 return Ok(false);
62 };
63 let (role, org_role) = match actor {
64 Some(user) => (
65 state.store.collaborator_role(&repo.id, &user.id).await?,
66 state
67 .store
68 .org_repo_role(&repo.owner_id, &user.id, &repo.id)
69 .await?,
70 ),
71 None => (None, None),
72 };
73 Ok(authorize(actor, &repo, role, org_role, Action::Read).is_ok())
74}
75
76/// True when `actor` may read `package`. A public package is readable by anyone, unless it is
77/// linked to a repo the actor may not read. A private one is readable by the instance admin, the
78/// owner and the owner's org members.
79pub async fn may_read(
80 state: &AppState,
81 actor: Option<&User>,
82 owner: &User,
83 package: &Package,
84) -> Result<bool, PackageError> {
85 if !package.private {
86 return match &package.repo_id {
87 Some(repo_id) => linked_repo_readable(state, actor, repo_id).await,
88 None => Ok(true),
89 };
90 }
91 let Some(actor) = actor else {
92 return Ok(false);
93 };
94 if actor.is_admin || actor.id == owner.id {
95 return Ok(true);
96 }
97 Ok(owner.is_org()
98 && state
99 .store
100 .org_member_role(&owner.id, &actor.id)
101 .await?
102 .is_some())
103}
104
105/// True when `actor` may publish, yank or unyank in `owner`'s registry: the owner themselves,
106/// an org owner, or the instance admin.
107pub async fn may_publish(
108 state: &AppState,
109 actor: &User,
110 owner: &User,
111) -> Result<bool, PackageError> {
112 if actor.is_admin || actor.id == owner.id {
113 return Ok(true);
114 }
115 if !owner.is_org() {
116 return Ok(false);
117 }
118 let role = state.store.org_member_role(&owner.id, &actor.id).await?;
119 Ok(role == Some(OrgMemberRole::Owner))
120}
121
122/// The package `name` of `owner` as the actor may see it. A missing package and a private one
123/// the actor may not read are the same `NotFound`.
124pub async fn readable_package(
125 state: &AppState,
126 actor: Option<&User>,
127 owner: &User,
128 name: &str,
129) -> Result<Package, PackageError> {
130 let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?;
131 let package = state
132 .store
133 .package_by_name(&owner.id, KIND_CARGO, &key)
134 .await?
135 .ok_or(PackageError::NotFound)?;
136 if !may_read(state, actor, owner, &package).await? {
137 return Err(PackageError::NotFound);
138 }
139 Ok(package)
140}
141
142/// A container image of `owner` that the viewer may read. The name is the image path below the
143/// owner, as the registry stores it.
144pub async fn readable_oci_package(
145 state: &AppState,
146 actor: Option<&User>,
147 owner: &User,
148 name: &str,
149) -> Result<Package, PackageError> {
150 let package = state
151 .store
152 .package_by_name(&owner.id, KIND_OCI, name)
153 .await?
154 .ok_or(PackageError::NotFound)?;
155 if !may_read(state, actor, owner, &package).await? {
156 return Err(PackageError::NotFound);
157 }
158 Ok(package)
159}
160
161/// The `config.json` of an owner's registry. `auth-required` is set when the owner has a private
162/// package, since cargo then needs a token for every request to that registry.
163pub async fn config_json(state: &AppState, owner: &User) -> Result<Value, PackageError> {
164 let base = state.config.base_url.trim_end_matches('/');
165 let auth_required = state.store.owner_has_private_packages(&owner.id).await?;
166 Ok(json!({
167 "dl": format!("{base}/api/packages/{}/cargo/download/{{crate}}/{{version}}", owner.username),
168 "api": format!("{base}/api/packages/{}/cargo", owner.username),
169 "auth-required": auth_required,
170 }))
171}
172
173/// The index file of a package: one JSON line per version, oldest first, each with the current
174/// yank state. A package with no versions has no index.
175pub async fn index_file(state: &AppState, package: &Package) -> Result<String, PackageError> {
176 let mut versions = state.store.package_versions(&package.id).await?;
177 versions.reverse();
178 let mut out = String::new();
179 for version in versions {
180 let mut line: Value = serde_json::from_str(&version.index_json)
181 .map_err(|e| PackageError::Internal(format!("stored index line: {e}")))?;
182 line["yanked"] = json!(version.yanked);
183 out.push_str(&line.to_string());
184 out.push('\n');
185 }
186 Ok(out)
187}
188
189/// Publishes a `.crate` from a publish body. The version row is written first, so a repeated
190/// version is a `Conflict` before any bytes are stored. A failed byte write removes the row.
191pub async fn publish(
192 state: &AppState,
193 owner: &User,
194 actor: &User,
195 body: &[u8],
196) -> Result<(), PackageError> {
197 if !may_publish(state, actor, owner).await? {
198 return Err(PackageError::Forbidden);
199 }
200 let parsed = cargo::parse_publish(body).map_err(|e| PackageError::Invalid(e.to_string()))?;
201 let meta = &parsed.metadata;
202 let name = cargo::meta_str(meta, "name")
203 .ok_or_else(|| PackageError::Invalid("metadata has no name".into()))?;
204 let vers = cargo::meta_str(meta, "vers")
205 .ok_or_else(|| PackageError::Invalid("metadata has no vers".into()))?;
206 let key = cargo::crate_name_key(name).map_err(|e| PackageError::Invalid(e.to_string()))?;
207 cargo::parse_version(vers).map_err(|e| PackageError::Invalid(e.to_string()))?;
208 let krate = parsed.crate_file;
209 if krate.len() as u64 > MAX_CRATE_BYTES {
210 return Err(PackageError::TooLarge);
211 }
212
213 let checksum = hex::encode(Sha256::digest(krate));
214 let index_line = cargo::index_line(meta, &checksum)
215 .map_err(|e| PackageError::Invalid(e.to_string()))?
216 .to_string();
217 let readme = cargo::crate_readme(krate)
218 .or_else(|| cargo::meta_str(meta, "readme").map(str::to_owned))
219 .filter(|text| !text.trim().is_empty());
220 let description = cargo::meta_str(meta, "description")
221 .map(str::trim)
222 .filter(|text| !text.is_empty());
223
224 let package = state
225 .store
226 .ensure_package(&owner.id, KIND_CARGO, name, &key)
227 .await?;
228 link_repo(state, owner, &package, meta).await?;
229
230 let version = state
231 .store
232 .publish_package_version(&NewPackageVersion {
233 package_id: &package.id,
234 version: vers,
235 checksum: &checksum,
236 size: krate.len() as u64,
237 index_json: &index_line,
238 description,
239 readme: readme.as_deref(),
240 publisher_id: &actor.id,
241 })
242 .await
243 .map_err(|e| match e {
244 Error::Conflict(_) => {
245 PackageError::Conflict(format!("crate version `{name}@{vers}` is already uploaded"))
246 }
247 other => other.into(),
248 })?;
249
250 if let Err(e) = store_bytes(state, &blob_key(&version.id), krate).await {
251 // Best effort: the row must not outlive its bytes.
252 let _ = state.store.delete_package_version(&package.id, vers).await;
253 return Err(PackageError::Internal(e.to_string()));
254 }
255 state.packages_live.bump(&owner.id);
256 bump_linked_repo(state, &package.id).await;
257 Ok(())
258}
259
260/// Wakes the repo that `package_id` is linked to, if any: its home page shows the package's newest
261/// version. A failed lookup skips the wake only, since the write has already happened.
262pub async fn bump_linked_repo(state: &AppState, package_id: &str) {
263 if let Ok(Some(package)) = state.store.package(package_id).await
264 && let Some(repo_id) = package.repo_id
265 {
266 state.live.bump(&crate::live::Topic::Repo(repo_id));
267 }
268}
269
270/// Sets the yank state of a version. Yanked versions stay in the index and stay downloadable,
271/// marked as yanked, so existing lockfiles keep working.
272pub async fn set_yanked(
273 state: &AppState,
274 owner: &User,
275 actor: &User,
276 name: &str,
277 version: &str,
278 yanked: bool,
279) -> Result<(), PackageError> {
280 if !may_publish(state, actor, owner).await? {
281 return Err(PackageError::Forbidden);
282 }
283 let key = cargo::crate_name_key(name).map_err(|_| PackageError::NotFound)?;
284 let package = state
285 .store
286 .package_by_name(&owner.id, KIND_CARGO, &key)
287 .await?
288 .ok_or(PackageError::NotFound)?;
289 if !state
290 .store
291 .set_package_version_yanked(&package.id, version, yanked)
292 .await?
293 {
294 return Err(PackageError::NotFound);
295 }
296 state.packages_live.bump(&owner.id);
297 bump_linked_repo(state, &package.id).await;
298 Ok(())
299}
300
301/// The `.crate` bytes of a version, for a download. Yanked versions still download.
302pub async fn download(
303 state: &AppState,
304 actor: Option<&User>,
305 owner: &User,
306 name: &str,
307 version: &str,
308) -> Result<BlobRead, PackageError> {
309 let package = readable_package(state, actor, owner, name).await?;
310 let found = state
311 .store
312 .package_version(&package.id, version)
313 .await?
314 .ok_or(PackageError::NotFound)?;
315 state
316 .blobs
317 .read(&blob_key(&found.id))
318 .await?
319 .ok_or(PackageError::NotFound)
320}
321
322/// The blob key of a version's `.crate` file.
323pub fn blob_key(version_id: &str) -> String {
324 format!("packages/{version_id}")
325}
326
327/// Points the package at the repo its `repository` field names, when that repo belongs to the
328/// same owner. A repo of another owner is never linked, so nobody can claim it.
329async fn link_repo(
330 state: &AppState,
331 owner: &User,
332 package: &Package,
333 meta: &Value,
334) -> Result<(), PackageError> {
335 let linked: Option<Repo> = match cargo::meta_str(meta, "repository")
336 .and_then(|url| cargo::repo_link(url, &state.config.base_url))
337 {
338 Some((repo_owner, repo_name)) if repo_owner.eq_ignore_ascii_case(&owner.username) => state
339 .store
340 .repo_by_owner_and_name(&repo_owner, &repo_name)
341 .await?
342 .filter(|repo| repo.owner_id == owner.id),
343 _ => None,
344 };
345 let repo_id = linked.as_ref().map(|repo| repo.id.as_str());
346 if package.repo_id.as_deref() != repo_id {
347 state.store.set_package_repo(&package.id, repo_id).await?;
348 }
349 Ok(())
350}
351
352/// Streams `bytes` into the blob store under `key`, returning the sha256 the store computed.
353async fn store_bytes(state: &AppState, key: &str, bytes: &[u8]) -> forge_core::Result<String> {
354 let mut writer = state.blobs.begin(key, MAX_CRATE_BYTES).await?;
355 for chunk in bytes.chunks(PUSH_CHUNK) {
356 if let Err(e) = writer.push(chunk).await {
357 writer.abort().await;
358 return Err(e);
359 }
360 }
361 let (_, sha) = writer.finish().await?;
362 Ok(sha)
363}