forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

packages.rs368 lines, 12.6 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, app_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 = app_context::<AppState>(cx);
37 let normalized = bare_token_as_bearer(headers(cx));
38 let (user, token_id, scopes) =
39 match api::authenticate_token(state, client_ip(cx), &normalized).await {
40 Ok(Some(found)) => found,
41 Ok(None) => return Ok(None),
42 Err(refusal) => {
43 return Err(Box::new(cargo_error(
44 refusal.status(),
45 "authentication required",
46 )));
47 }
48 };
49 if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) {
50 return if scope_required {
51 Err(Box::new(cargo_error(
52 StatusCode::FORBIDDEN,
53 "the token lacks the packages scope",
54 )))
55 } else {
56 Ok(None)
57 };
58 }
59 if let Err(e) = state.store.touch_token(&token_id).await {
60 return Err(Box::new(failure(PackageError::Internal(e.to_string()))));
61 }
62 crate::pages::settings_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 = app_context::<AppState>(cx);
124 match package_ops::owner_named(state, path_param::<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 = app_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 = app_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 =
177 match package_ops::readable_package(state, actor.as_ref(), &owner, path_param::<Name>(cx))
178 .await
179 {
180 Ok(package) => package,
181 Err(e) => return failure(e),
182 };
183 match package_ops::index_file(state, &package).await {
184 Ok(body) => text(body),
185 Err(e) => failure(e),
186 }
187}
188
189/// The `.crate` file of one version, streamed from the blob store.
190#[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")]
191async fn download(cx: &Cx) -> topcoat::Result<Response> {
192 let state = app_context::<AppState>(cx);
193 let actor = match caller(cx, false).await {
194 Ok(actor) => actor,
195 Err(res) => return Ok(*res),
196 };
197 let owner = match owner_of(cx).await {
198 Ok(owner) => owner,
199 Err(res) => return Ok(*res),
200 };
201 let read = match package_ops::download(
202 state,
203 actor.as_ref(),
204 &owner,
205 path_param::<Name>(cx),
206 path_param::<Version>(cx),
207 )
208 .await
209 {
210 Ok(read) => read,
211 Err(e) => return Ok(failure(e)),
212 };
213 let chunks = read.stream.map(|chunk| chunk.map(Frame::data));
214 let mut res = Response::new(Body::new(StreamBody::new(chunks)));
215 *res.status_mut() = StatusCode::OK;
216 res.headers_mut().insert(
217 CONTENT_TYPE,
218 HeaderValue::from_static("application/octet-stream"),
219 );
220 res.headers_mut()
221 .insert(CONTENT_LENGTH, HeaderValue::from(read.size));
222 Ok(res)
223}
224
225/// `cargo publish`. The body is the publish format: a length-prefixed JSON document and a
226/// length-prefixed `.crate`. It is read whole, up to the publish limit.
227#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")]
228async fn publish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
229 let state = app_context::<AppState>(cx);
230 let actor = match caller(cx, true).await {
231 Ok(Some(actor)) => actor,
232 Ok(None) => {
233 return Ok(cargo_error(
234 StatusCode::UNAUTHORIZED,
235 "authentication required",
236 ));
237 }
238 Err(res) => return Ok(*res),
239 };
240 let owner = match owner_of(cx).await {
241 Ok(owner) => owner,
242 Err(res) => return Ok(*res),
243 };
244 let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await {
245 Ok(bytes) => bytes,
246 Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))),
247 };
248 match package_ops::publish(state, &owner, &actor, &bytes).await {
249 Ok(()) => Ok(api::json(
250 StatusCode::OK,
251 &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }),
252 )),
253 Err(e) => Ok(failure(e)),
254 }
255}
256
257fn read_failure(e: &impl std::fmt::Display) -> String {
258 format!("the request body could not be read: {e}")
259}
260
261/// `cargo yank`: marks a version yanked. It stays in the index and downloadable.
262#[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")]
263async fn yank(cx: &Cx) -> topcoat::Result<Response> {
264 set_yank(cx, true).await
265}
266
267/// `cargo yank --undo`.
268#[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")]
269async fn unyank(cx: &Cx) -> topcoat::Result<Response> {
270 set_yank(cx, false).await
271}
272
273async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result<Response> {
274 let state = app_context::<AppState>(cx);
275 let actor = match caller(cx, true).await {
276 Ok(Some(actor)) => actor,
277 Ok(None) => {
278 return Ok(cargo_error(
279 StatusCode::UNAUTHORIZED,
280 "authentication required",
281 ));
282 }
283 Err(res) => return Ok(*res),
284 };
285 let owner = match owner_of(cx).await {
286 Ok(owner) => owner,
287 Err(res) => return Ok(*res),
288 };
289 match package_ops::set_yanked(
290 state,
291 &owner,
292 &actor,
293 path_param::<Name>(cx),
294 path_param::<Version>(cx),
295 yanked,
296 )
297 .await
298 {
299 Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))),
300 Err(e) => Ok(failure(e)),
301 }
302}
303
304/// `cargo owner --list`: the people who may publish. For a user registry that is the user; for
305/// an org, its owners. Read-only: adding or removing owners is done in the forge.
306#[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")]
307async fn owners(cx: &Cx) -> topcoat::Result<Response> {
308 let state = app_context::<AppState>(cx);
309 let actor = match caller(cx, false).await {
310 Ok(actor) => actor,
311 Err(res) => return Ok(*res),
312 };
313 let owner = match owner_of(cx).await {
314 Ok(owner) => owner,
315 Err(res) => return Ok(*res),
316 };
317 if let Err(e) =
318 package_ops::readable_package(state, actor.as_ref(), &owner, path_param::<Name>(cx)).await
319 {
320 return Ok(failure(e));
321 }
322 let people: Vec<User> = if owner.is_org() {
323 match state.store.org_members(&owner.id).await {
324 Ok(members) => members
325 .into_iter()
326 .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner)
327 .map(|(user, _)| user)
328 .collect(),
329 Err(e) => return Ok(failure(e.into())),
330 }
331 } else {
332 vec![owner.clone()]
333 };
334 let users: Vec<Value> = people
335 .iter()
336 .map(|user| {
337 json!({
338 "id": user.id,
339 "login": user.username,
340 "name": user.display_name,
341 "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username),
342 })
343 })
344 .collect();
345 Ok(api::json(StatusCode::OK, &json!({ "users": users })))
346}
347
348#[cfg(test)]
349mod tests {
350 use http::HeaderValue;
351
352 use super::*;
353
354 #[test]
355 fn a_bare_token_becomes_a_bearer_token() {
356 let mut headers = HeaderMap::new();
357 headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc"));
358 let rewritten = bare_token_as_bearer(&headers);
359 assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc");
360
361 let mut bearer = HeaderMap::new();
362 bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc"));
363 assert_eq!(
364 bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(),
365 "Bearer forge_abc"
366 );
367 }
368}