forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

packages.rs348 lines, 12.3 KiBHistoryRawDownload
1//! The Cargo registry protocol under `/api/packages/{owner}/cargo/`: the sparse index and
2//! `config.json` that cargo reads, the `.crate` downloads, and the web API that `cargo publish`,
3//! `cargo yank` and `cargo owner --list` call. Documented for users in docs/packages.md.
4//!
5//! Cargo sends the bare token in `Authorization`, so a token with no scheme is accepted here
6//! and read as a Bearer token. Reads are public for public packages. Private packages, and any
7//! write, need a token with the `packages` scope. Errors use cargo's body, `{"errors":[{"detail":...}]}`.
8
9use forge_core::User;
10use futures_util::StreamExt;
11use http::HeaderMap;
12use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
13use http_body::Frame;
14use http_body_util::StreamBody;
15use serde_json::{Value, json};
16use topcoat::context::{Cx, context};
17use topcoat::router::request::headers;
18use topcoat::router::response::Response;
19use topcoat::router::{Body, StatusCode, path_param, route};
20
21use crate::api::{self, Refusal};
22use crate::client_ip::client_ip;
23use crate::package_ops::{self, PackageError};
24use crate::state::AppState;
25
26/// The scope a token needs for registry writes and private reads.
27pub const PACKAGES_SCOPE: &str = "packages";
28
29path_param!(owner);
30path_param!(name);
31path_param!(version);
32
33/// The caller of a registry request. Reads with a token that lacks the scope are served as
34/// anonymous, so a token made for another purpose cannot break a public install. Writes refuse.
35async fn caller(cx: &Cx, scope_required: bool) -> Result<Option<User>, Refusal> {
36 let state = context::<AppState>(cx);
37 let normalized = bare_token_as_bearer(headers(cx));
38 let (user, token_id, scopes) =
39 match api::authenticate_token(state, client_ip(cx), &normalized).await {
40 Ok(Some(found)) => found,
41 Ok(None) => return Ok(None),
42 Err(refusal) => {
43 return Err(Box::new(cargo_error(
44 refusal.status(),
45 "authentication required",
46 )));
47 }
48 };
49 if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) {
50 return if scope_required {
51 Err(Box::new(cargo_error(
52 StatusCode::FORBIDDEN,
53 "the token lacks the packages scope",
54 )))
55 } else {
56 Ok(None)
57 };
58 }
59 if let Err(e) = state.store.touch_token(&token_id).await {
60 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));
61 }
62 crate::live::bump_account(state, &user.id);
63 Ok(Some(user))
64}
65
66/// The headers with a bare token rewritten to `Bearer <token>`. Anything with a scheme is left
67/// as it was.
68fn bare_token_as_bearer(headers: &HeaderMap) -> HeaderMap {
69 let mut out = headers.clone();
70 let bare = headers
71 .get(AUTHORIZATION)
72 .and_then(|value| value.to_str().ok())
73 .map(str::trim)
74 .filter(|value| !value.is_empty() && !value.contains(' '))
75 .map(str::to_owned);
76 if let Some(token) = bare
77 && let Ok(value) = HeaderValue::from_str(&format!("Bearer {token}"))
78 {
79 out.insert(AUTHORIZATION, value);
80 }
81 out
82}
83
84/// A cargo-style error response.
85fn cargo_error(status: StatusCode, detail: &str) -> Response {
86 api::json(status, &json!({ "errors": [{ "detail": detail }] }))
87}
88
89/// Maps a registry failure to its status and cargo error body.
90fn failure(e: PackageError) -> Response {
91 match e {
92 PackageError::Invalid(msg) => cargo_error(StatusCode::BAD_REQUEST, &msg),
93 PackageError::NotFound => cargo_error(StatusCode::NOT_FOUND, "not found"),
94 PackageError::Forbidden => cargo_error(
95 StatusCode::FORBIDDEN,
96 "you do not have permission to publish to this registry",
97 ),
98 PackageError::Conflict(msg) => cargo_error(StatusCode::CONFLICT, &msg),
99 PackageError::TooLarge => cargo_error(
100 StatusCode::PAYLOAD_TOO_LARGE,
101 "the crate is larger than the registry accepts",
102 ),
103 PackageError::Internal(cause) => {
104 tracing::error!(error = %cause, "package request failed");
105 cargo_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")
106 }
107 }
108}
109
110/// A plain text response, used for index files.
111fn text(body: String) -> Response {
112 let mut res = Response::new(Body::from(body));
113 *res.status_mut() = StatusCode::OK;
114 res.headers_mut().insert(
115 CONTENT_TYPE,
116 HeaderValue::from_static("text/plain; charset=utf-8"),
117 );
118 res
119}
120
121/// Loads the registry owner named in the path, as the caller may see it. A missing owner is 404.
122async fn owner_of(cx: &Cx) -> Result<User, Refusal> {
123 let state = context::<AppState>(cx);
124 match package_ops::owner_named(state, owner(cx)).await {
125 Ok(Some(found)) => Ok(found),
126 Ok(_) => Err(Box::new(failure(PackageError::NotFound))),
127 Err(e) => Err(Box::new(failure(e))),
128 }
129}
130
131#[route(GET "/api/packages/{owner}/cargo/config.json")]
132async fn config(cx: &Cx) -> topcoat::Result<Response> {
133 let state = context::<AppState>(cx);
134 if let Err(res) = caller(cx, false).await {
135 return Ok(*res);
136 }
137 let owner = match owner_of(cx).await {
138 Ok(owner) => owner,
139 Err(res) => return Ok(*res),
140 };
141 match package_ops::config_json(state, &owner).await {
142 Ok(value) => Ok(api::json(StatusCode::OK, &value)),
143 Err(e) => Ok(failure(e)),
144 }
145}
146
147/// The index file of a one-letter crate.
148#[route(GET "/api/packages/{owner}/cargo/1/{name}")]
149async fn index_one(cx: &Cx) -> topcoat::Result<Response> {
150 Ok(index_response(cx).await)
151}
152
153/// The index file of a two-letter crate.
154#[route(GET "/api/packages/{owner}/cargo/2/{name}")]
155async fn index_two(cx: &Cx) -> topcoat::Result<Response> {
156 Ok(index_response(cx).await)
157}
158
159/// The index file of a crate with three or more letters. The prefix segments are derived from
160/// the name, so only the name is looked up.
161#[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")]
162async fn index_long(cx: &Cx) -> topcoat::Result<Response> {
163 Ok(index_response(cx).await)
164}
165
166async fn index_response(cx: &Cx) -> Response {
167 let state = context::<AppState>(cx);
168 let actor = match caller(cx, false).await {
169 Ok(actor) => actor,
170 Err(res) => return *res,
171 };
172 let owner = match owner_of(cx).await {
173 Ok(owner) => owner,
174 Err(res) => return *res,
175 };
176 let package = match package_ops::readable_package(state, actor.as_ref(), &owner, name(cx)).await
177 {
178 Ok(package) => package,
179 Err(e) => return failure(e),
180 };
181 match package_ops::index_file(state, &package).await {
182 Ok(body) => text(body),
183 Err(e) => failure(e),
184 }
185}
186
187/// The `.crate` file of one version, streamed from the blob store.
188#[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")]
189async fn download(cx: &Cx) -> topcoat::Result<Response> {
190 let state = context::<AppState>(cx);
191 let actor = match caller(cx, false).await {
192 Ok(actor) => actor,
193 Err(res) => return Ok(*res),
194 };
195 let owner = match owner_of(cx).await {
196 Ok(owner) => owner,
197 Err(res) => return Ok(*res),
198 };
199 let read =
200 match package_ops::download(state, actor.as_ref(), &owner, name(cx), version(cx)).await {
201 Ok(read) => read,
202 Err(e) => return Ok(failure(e)),
203 };
204 let chunks = read.stream.map(|chunk| chunk.map(Frame::data));
205 let mut res = Response::new(Body::new(StreamBody::new(chunks)));
206 *res.status_mut() = StatusCode::OK;
207 res.headers_mut().insert(
208 CONTENT_TYPE,
209 HeaderValue::from_static("application/octet-stream"),
210 );
211 res.headers_mut()
212 .insert(CONTENT_LENGTH, HeaderValue::from(read.size));
213 Ok(res)
214}
215
216/// `cargo publish`. The body is the publish format: a length-prefixed JSON document and a
217/// length-prefixed `.crate`. It is read whole, up to the publish limit.
218#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")]
219async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
220 let state = context::<AppState>(cx);
221 let actor = match caller(cx, true).await {
222 Ok(Some(actor)) => actor,
223 Ok(None) => {
224 return Ok(cargo_error(
225 StatusCode::UNAUTHORIZED,
226 "authentication required",
227 ));
228 }
229 Err(res) => return Ok(*res),
230 };
231 let owner = match owner_of(cx).await {
232 Ok(owner) => owner,
233 Err(res) => return Ok(*res),
234 };
235 let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await {
236 Ok(bytes) => bytes,
237 Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))),
238 };
239 match package_ops::publish(state, &owner, &actor, &bytes).await {
240 Ok(()) => Ok(api::json(
241 StatusCode::OK,
242 &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }),
243 )),
244 Err(e) => Ok(failure(e)),
245 }
246}
247
248fn read_failure(e: &impl std::fmt::Display) -> String {
249 format!("the request body could not be read: {e}")
250}
251
252/// `cargo yank`: marks a version yanked. It stays in the index and downloadable.
253#[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")]
254async fn yank(cx: &Cx) -> topcoat::Result<Response> {
255 set_yank(cx, true).await
256}
257
258/// `cargo yank --undo`.
259#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")]
260async fn unyank(cx: &Cx) -> topcoat::Result<Response> {
261 set_yank(cx, false).await
262}
263
264async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> {
265 let state = context::<AppState>(cx);
266 let actor = match caller(cx, true).await {
267 Ok(Some(actor)) => actor,
268 Ok(None) => {
269 return Ok(cargo_error(
270 StatusCode::UNAUTHORIZED,
271 "authentication required",
272 ));
273 }
274 Err(res) => return Ok(*res),
275 };
276 let owner = match owner_of(cx).await {
277 Ok(owner) => owner,
278 Err(res) => return Ok(*res),
279 };
280 match package_ops::set_yanked(state, &owner, &actor, name(cx), version(cx), yanked).await {
281 Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))),
282 Err(e) => Ok(failure(e)),
283 }
284}
285
286/// `cargo owner --list`: the people who may publish. For a user registry that is the user; for
287/// an org, its owners. Read-only: adding or removing owners is done in the forge.
288#[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")]
289async fn owners(cx: &Cx) -> topcoat::Result<Response> {
290 let state = context::<AppState>(cx);
291 let actor = match caller(cx, false).await {
292 Ok(actor) => actor,
293 Err(res) => return Ok(*res),
294 };
295 let owner = match owner_of(cx).await {
296 Ok(owner) => owner,
297 Err(res) => return Ok(*res),
298 };
299 if let Err(e) = package_ops::readable_package(state, actor.as_ref(), &owner, name(cx)).await {
300 return Ok(failure(e));
301 }
302 let people: Vec<User> = if owner.is_org() {
303 match state.store.org_members(&owner.id).await {
304 Ok(members) => members
305 .into_iter()
306 .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner)
307 .map(|(user, _)| user)
308 .collect(),
309 Err(e) => return Ok(failure(e.into())),
310 }
311 } else {
312 vec![owner.clone()]
313 };
314 let users: Vec<Value> = people
315 .iter()
316 .map(|user| {
317 json!({
318 "id": user.id,
319 "login": user.username,
320 "name": user.display_name,
321 "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username),
322 })
323 })
324 .collect();
325 Ok(api::json(StatusCode::OK, &json!({ "users": users })))
326}
327
328#[cfg(test)]
329mod tests {
330 use http::HeaderValue;
331
332 use super::*;
333
334 #[test]
335 fn a_bare_token_becomes_a_bearer_token() {
336 let mut headers = HeaderMap::new();
337 headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc"));
338 let rewritten = bare_token_as_bearer(&headers);
339 assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc");
340
341 let mut bearer = HeaderMap::new();
342 bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc"));
343 assert_eq!(
344 bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(),
345 "Bearer forge_abc"
346 );
347 }
348}