//! The Cargo registry protocol under `/api/packages/{owner}/cargo/`: the sparse index and //! `config.json` that cargo reads, the `.crate` downloads, and the web API that `cargo publish`, //! `cargo yank` and `cargo owner --list` call. Documented for users in docs/packages.md. //! //! Cargo sends the bare token in `Authorization`, so a token with no scheme is accepted here //! and read as a Bearer token. Reads are public for public packages. Private packages, and any //! write, need a token with the `packages` scope. Errors use cargo's body, `{"errors":[{"detail":...}]}`. use forge_core::User; use futures_util::StreamExt; use http::HeaderMap; use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; use http_body::Frame; use http_body_util::StreamBody; use serde_json::{Value, json}; use topcoat::context::{Cx, app_context}; use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, path_param, route}; use crate::api::{self, Refusal}; use crate::client_ip::client_ip; use crate::package_ops::{self, PackageError}; use crate::state::AppState; /// The scope a token needs for registry writes and private reads. pub const PACKAGES_SCOPE: &str = "packages"; path_param!(owner); path_param!(name); path_param!(version); /// The caller of a registry request. Reads with a token that lacks the scope are served as /// anonymous, so a token made for another purpose cannot break a public install. Writes refuse. async fn caller(cx: &Cx, scope_required: bool) -> Result, Refusal> { let state = app_context::(cx); let normalized = bare_token_as_bearer(headers(cx)); let (user, token_id, scopes) = match api::authenticate_token(state, client_ip(cx), &normalized).await { Ok(Some(found)) => found, Ok(None) => return Ok(None), Err(refusal) => { return Err(Box::new(cargo_error( refusal.status(), "authentication required", ))); } }; if !scopes.iter().any(|scope| scope == PACKAGES_SCOPE) { return if scope_required { Err(Box::new(cargo_error( StatusCode::FORBIDDEN, "the token lacks the packages scope", ))) } else { Ok(None) }; } if let Err(e) = state.store.touch_token(&token_id).await { return Err(Box::new(failure(PackageError::Internal(e.to_string())))); } crate::pages::settings_live::bump_account(state, &user.id); Ok(Some(user)) } /// The headers with a bare token rewritten to `Bearer `. Anything with a scheme is left /// as it was. fn bare_token_as_bearer(headers: &HeaderMap) -> HeaderMap { let mut out = headers.clone(); let bare = headers .get(AUTHORIZATION) .and_then(|value| value.to_str().ok()) .map(str::trim) .filter(|value| !value.is_empty() && !value.contains(' ')) .map(str::to_owned); if let Some(token) = bare && let Ok(value) = HeaderValue::from_str(&format!("Bearer {token}")) { out.insert(AUTHORIZATION, value); } out } /// A cargo-style error response. fn cargo_error(status: StatusCode, detail: &str) -> Response { api::json(status, &json!({ "errors": [{ "detail": detail }] })) } /// Maps a registry failure to its status and cargo error body. fn failure(e: PackageError) -> Response { match e { PackageError::Invalid(msg) => cargo_error(StatusCode::BAD_REQUEST, &msg), PackageError::NotFound => cargo_error(StatusCode::NOT_FOUND, "not found"), PackageError::Forbidden => cargo_error( StatusCode::FORBIDDEN, "you do not have permission to publish to this registry", ), PackageError::Conflict(msg) => cargo_error(StatusCode::CONFLICT, &msg), PackageError::TooLarge => cargo_error( StatusCode::PAYLOAD_TOO_LARGE, "the crate is larger than the registry accepts", ), PackageError::Internal(cause) => { tracing::error!(error = %cause, "package request failed"); cargo_error(StatusCode::INTERNAL_SERVER_ERROR, "internal server error") } } } /// A plain text response, used for index files. fn text(body: String) -> Response { let mut res = Response::new(Body::from(body)); *res.status_mut() = StatusCode::OK; res.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"), ); res } /// Loads the registry owner named in the path, as the caller may see it. A missing owner is 404. async fn owner_of(cx: &Cx) -> Result { let state = app_context::(cx); match package_ops::owner_named(state, path_param::(cx)).await { Ok(Some(found)) => Ok(found), Ok(_) => Err(Box::new(failure(PackageError::NotFound))), Err(e) => Err(Box::new(failure(e))), } } #[route(GET "/api/packages/{owner}/cargo/config.json")] async fn config(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); if let Err(res) = caller(cx, false).await { return Ok(*res); } let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return Ok(*res), }; match package_ops::config_json(state, &owner).await { Ok(value) => Ok(api::json(StatusCode::OK, &value)), Err(e) => Ok(failure(e)), } } /// The index file of a one-letter crate. #[route(GET "/api/packages/{owner}/cargo/1/{name}")] async fn index_one(cx: &Cx) -> topcoat::Result { Ok(index_response(cx).await) } /// The index file of a two-letter crate. #[route(GET "/api/packages/{owner}/cargo/2/{name}")] async fn index_two(cx: &Cx) -> topcoat::Result { Ok(index_response(cx).await) } /// The index file of a crate with three or more letters. The prefix segments are derived from /// the name, so only the name is looked up. #[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")] async fn index_long(cx: &Cx) -> topcoat::Result { Ok(index_response(cx).await) } async fn index_response(cx: &Cx) -> Response { let state = app_context::(cx); let actor = match caller(cx, false).await { Ok(actor) => actor, Err(res) => return *res, }; let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return *res, }; let package = match package_ops::readable_package(state, actor.as_ref(), &owner, path_param::(cx)) .await { Ok(package) => package, Err(e) => return failure(e), }; match package_ops::index_file(state, &package).await { Ok(body) => text(body), Err(e) => failure(e), } } /// The `.crate` file of one version, streamed from the blob store. #[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")] async fn download(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let actor = match caller(cx, false).await { Ok(actor) => actor, Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return Ok(*res), }; let read = match package_ops::download( state, actor.as_ref(), &owner, path_param::(cx), path_param::(cx), ) .await { Ok(read) => read, Err(e) => return Ok(failure(e)), }; let chunks = read.stream.map(|chunk| chunk.map(Frame::data)); let mut res = Response::new(Body::new(StreamBody::new(chunks))); *res.status_mut() = StatusCode::OK; res.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_static("application/octet-stream"), ); res.headers_mut() .insert(CONTENT_LENGTH, HeaderValue::from(read.size)); Ok(res) } /// `cargo publish`. The body is the publish format: a length-prefixed JSON document and a /// length-prefixed `.crate`. It is read whole, up to the publish limit. #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] async fn publish(cx: &Cx, body: Body) -> topcoat::Result { let state = app_context::(cx); let actor = match caller(cx, true).await { Ok(Some(actor)) => actor, Ok(None) => { return Ok(cargo_error( StatusCode::UNAUTHORIZED, "authentication required", )); } Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return Ok(*res), }; let bytes = match topcoat::router::to_bytes(body, package_ops::MAX_PUBLISH_BYTES).await { Ok(bytes) => bytes, Err(e) => return Ok(cargo_error(StatusCode::BAD_REQUEST, &read_failure(&e))), }; match package_ops::publish(state, &owner, &actor, &bytes).await { Ok(()) => Ok(api::json( StatusCode::OK, &json!({ "warnings": { "invalid_categories": [], "invalid_badges": [], "other": [] } }), )), Err(e) => Ok(failure(e)), } } fn read_failure(e: &impl std::fmt::Display) -> String { format!("the request body could not be read: {e}") } /// `cargo yank`: marks a version yanked. It stays in the index and downloadable. #[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")] async fn yank(cx: &Cx) -> topcoat::Result { set_yank(cx, true).await } /// `cargo yank --undo`. #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")] async fn unyank(cx: &Cx) -> topcoat::Result { set_yank(cx, false).await } async fn set_yank(cx: &Cx, yanked: bool) -> topcoat::Result { let state = app_context::(cx); let actor = match caller(cx, true).await { Ok(Some(actor)) => actor, Ok(None) => { return Ok(cargo_error( StatusCode::UNAUTHORIZED, "authentication required", )); } Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return Ok(*res), }; match package_ops::set_yanked( state, &owner, &actor, path_param::(cx), path_param::(cx), yanked, ) .await { Ok(()) => Ok(api::json(StatusCode::OK, &json!({ "ok": true }))), Err(e) => Ok(failure(e)), } } /// `cargo owner --list`: the people who may publish. For a user registry that is the user; for /// an org, its owners. Read-only: adding or removing owners is done in the forge. #[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")] async fn owners(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); let actor = match caller(cx, false).await { Ok(actor) => actor, Err(res) => return Ok(*res), }; let owner = match owner_of(cx).await { Ok(owner) => owner, Err(res) => return Ok(*res), }; if let Err(e) = package_ops::readable_package(state, actor.as_ref(), &owner, path_param::(cx)).await { return Ok(failure(e)); } let people: Vec = if owner.is_org() { match state.store.org_members(&owner.id).await { Ok(members) => members .into_iter() .filter(|(_, role)| *role == forge_core::store::orgs::OrgMemberRole::Owner) .map(|(user, _)| user) .collect(), Err(e) => return Ok(failure(e.into())), } } else { vec![owner.clone()] }; let users: Vec = people .iter() .map(|user| { json!({ "id": user.id, "login": user.username, "name": user.display_name, "url": format!("{}/{}", state.config.base_url.trim_end_matches('/'), user.username), }) }) .collect(); Ok(api::json(StatusCode::OK, &json!({ "users": users }))) } #[cfg(test)] mod tests { use http::HeaderValue; use super::*; #[test] fn a_bare_token_becomes_a_bearer_token() { let mut headers = HeaderMap::new(); headers.insert(AUTHORIZATION, HeaderValue::from_static("forge_abc")); let rewritten = bare_token_as_bearer(&headers); assert_eq!(rewritten.get(AUTHORIZATION).unwrap(), "Bearer forge_abc"); let mut bearer = HeaderMap::new(); bearer.insert(AUTHORIZATION, HeaderValue::from_static("Bearer forge_abc")); assert_eq!( bare_token_as_bearer(&bearer).get(AUTHORIZATION).unwrap(), "Bearer forge_abc" ); } }