| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use forge_core::User; |
| 10 | use futures_util::StreamExt; |
| 11 | use http::HeaderMap; |
| 12 | use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; |
| 13 | use http_body::Frame; |
| 14 | use http_body_util::StreamBody; |
| 15 | use serde_json::{Value, json}; |
| 16 | use topcoat::context::{Cx, app_context}; |
| 17 | use topcoat::router::request::headers; |
| 18 | use topcoat::router::response::Response; |
| 19 | use topcoat::router::{Body, StatusCode, path_param, route}; |
| 20 | |
| 21 | use crate::api::{self, Refusal}; |
| 22 | use crate::client_ip::client_ip; |
| 23 | use crate::package_ops::{self, PackageError}; |
| 24 | use crate::state::AppState; |
| 25 | |
| 26 | |
| 27 | pub const PACKAGES_SCOPE: &str = "packages"; |
| 28 | |
| 29 | path_param!(owner); |
| 30 | path_param!(name); |
| 31 | path_param!(version); |
| 32 | |
| 33 | |
| 34 | |
| 35 | async 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 | |
| 67 | |
| 68 | fn 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 | |
| 85 | fn cargo_error(status: StatusCode, detail: &str) -> Response { |
| 86 | api::json(status, &json!({ "errors": [{ "detail": detail }] })) |
| 87 | } |
| 88 | |
| 89 | |
| 90 | fn 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 | |
| 111 | fn 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 | |
| 122 | async 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")] |
| 132 | async 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 | |
| 148 | #[route(GET "/api/packages/{owner}/cargo/1/{name}")] |
| 149 | async fn index_one(cx: &Cx) -> topcoat::Result<Response> { |
| 150 | Ok(index_response(cx).await) |
| 151 | } |
| 152 | |
| 153 | |
| 154 | #[route(GET "/api/packages/{owner}/cargo/2/{name}")] |
| 155 | async fn index_two(cx: &Cx) -> topcoat::Result<Response> { |
| 156 | Ok(index_response(cx).await) |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | #[route(GET "/api/packages/{owner}/cargo/{ab}/{cd}/{name}")] |
| 162 | async fn index_long(cx: &Cx) -> topcoat::Result<Response> { |
| 163 | Ok(index_response(cx).await) |
| 164 | } |
| 165 | |
| 166 | async 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 | |
| 190 | #[route(GET "/api/packages/{owner}/cargo/download/{name}/{version}")] |
| 191 | async 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 | |
| 226 | |
| 227 | #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/new")] |
| 228 | async 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 | |
| 257 | fn read_failure(e: &impl std::fmt::Display) -> String { |
| 258 | format!("the request body could not be read: {e}") |
| 259 | } |
| 260 | |
| 261 | |
| 262 | #[route(DELETE "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/yank")] |
| 263 | async fn yank(cx: &Cx) -> topcoat::Result<Response> { |
| 264 | set_yank(cx, true).await |
| 265 | } |
| 266 | |
| 267 | |
| 268 | #[route(PUT "/api/packages/{owner}/cargo/api/v1/crates/{name}/{version}/unyank")] |
| 269 | async fn unyank(cx: &Cx) -> topcoat::Result<Response> { |
| 270 | set_yank(cx, false).await |
| 271 | } |
| 272 | |
| 273 | async 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 | |
| 305 | |
| 306 | #[route(GET "/api/packages/{owner}/cargo/api/v1/crates/{name}/owners")] |
| 307 | async 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)] |
| 349 | mod 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 | } |