//! The object store API for family services (contracts.md 5). `iz` keeps its blobs here, under its own //! namespace, with its own quota. Every route needs a client-credentials token with `aud = "in"` and scope //! `files.service`, checked in `machine_auth.rs`; the namespace is the token's `svc` and nothing else. //! //! The routes: //! - `PUT /api/v1/objects/{external_id}` stores the raw body. The bytes stream to a staged file while their //! SHA-256 is computed. The body may not be longer than the quota that is left (the service quota, less //! what the service uses, plus the bytes of the object being replaced), and the limit is enforced while it //! is read, so nothing above it is stored. The bytes are put at `objects//`, and the row //! is committed in the same step that moves the quota. A new id answers `201`, a replaced one `200`. //! `If-None-Match: *` refuses an existing id with `409`. //! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support. //! The cache policy is `private, no-cache`, because a replace changes what the id names. //! - A write reserves the bytes it may stage for its service before it reads the body. A write that would //! take the service past its headroom, together with the writes in flight, is `429 rate_limited`. //! - `DELETE` removes the object. It answers `204` also when the object was already absent. //! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects. //! //! Blob removal goes through `Store::retire_blob`, so bytes that another object still names, or that a //! write is storing right now, are never removed. A removal that is refused is left to the sweeper. use futures_util::StreamExt; use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH, RETRY_AFTER}; use http::{HeaderValue, StatusCode}; use in_core::error::Error as CoreError; use in_core::names; use in_core::staging::StagedFile; use in_core::store::objects::{NewObject, Object, PutOutcome, check_external_id, object_blob_key}; use serde_json::{Value, json}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderMap, path_param_segment, route}; use crate::api::machine_auth::{Refusal, json_response, machine_caller}; use crate::serve_bytes::{ByteSource, Disposition, SHARE_CACHE, serve_bytes_with}; use crate::state::AppState; /// The `Content-Type` of an object whose PUT names none. const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream"; /// Longest `Content-Type` value kept, in bytes. const MAX_CONTENT_TYPE_BYTES: usize = 255; /// Longest `X-Object-Name`, in bytes, after decoding. const MAX_NAME_BYTES: usize = 255; /// The cache policy of object bytes: the id can be replaced at any time, so a cached copy must be checked. const OBJECT_CACHE: &str = SHARE_CACHE; /// A `400` with the stable word `invalid_request`. fn bad_request(message: &'static str) -> Refusal { Refusal { status: StatusCode::BAD_REQUEST, error: "invalid_request", message, } } /// The headers of a PUT that the handler reads before it touches the body. #[derive(Debug, PartialEq, Eq)] struct PutRequest { /// The `Content-Length` the client declared, if any. Checked against the quota before a byte is read. declared: Option, /// The `Content-Type`, stored as given. content_type: String, /// The cleaned `X-Object-Name`, if one was sent. name: Option, /// `true` for `If-None-Match: *`: the PUT must create the id, not replace it. create_only: bool, } impl PutRequest { /// Reads the PUT headers. Malformed ones are `400`, and nothing is stored. fn from_headers(request: &HeaderMap) -> std::result::Result { let declared = match request.get(CONTENT_LENGTH) { None => None, Some(value) => Some( value .to_str() .ok() .and_then(|text| text.parse::().ok()) .ok_or_else(|| bad_request("Content-Length is not a number"))?, ), }; let create_only = match request.get(IF_NONE_MATCH) { None => false, Some(value) if value.as_bytes() == b"*" => true, Some(_) => return Err(bad_request("If-None-Match must be *")), }; Ok(Self { declared, content_type: content_type_of(request)?, name: object_name(request)?, create_only, }) } } /// The stored `Content-Type`: the client's value when it is a `type/subtype` with printable ASCII, else /// `application/octet-stream`. fn content_type_of(request: &HeaderMap) -> std::result::Result { let Some(value) = request.get(CONTENT_TYPE) else { return Ok(DEFAULT_CONTENT_TYPE.to_owned()); }; let text = value .to_str() .map_err(|_| bad_request("Content-Type is not ASCII"))? .trim(); let essence = text.split(';').next().unwrap_or_default().trim(); let well_formed = essence .split_once('/') .is_some_and(|(main, sub)| is_token(main) && is_token(sub)); if !well_formed || text.len() > MAX_CONTENT_TYPE_BYTES { return Err(bad_request("Content-Type must be type/subtype")); } Ok(text.to_owned()) } /// Whether `text` is a non-empty HTTP token (RFC 9110 section 5.6.2). fn is_token(text: &str) -> bool { !text.is_empty() && text .bytes() .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) } /// The `X-Object-Name`: percent-encoded UTF-8, at most 255 bytes once decoded. It is cleaned like a file /// name (`names::display_name`), so a path or control characters cannot reach a download header. fn object_name(request: &HeaderMap) -> std::result::Result, Refusal> { let Some(value) = request.get("x-object-name") else { return Ok(None); }; let raw = value .to_str() .map_err(|_| bad_request("X-Object-Name is not ASCII"))?; let decoded = percent_decode(raw).ok_or_else(|| bad_request("X-Object-Name is not percent-encoded"))?; if decoded.len() > MAX_NAME_BYTES { return Err(bad_request("X-Object-Name is longer than 255 bytes")); } let text = String::from_utf8(decoded).map_err(|_| bad_request("X-Object-Name is not UTF-8"))?; if text.trim().is_empty() { return Ok(None); } Ok(Some(names::display_name(&text))) } /// Decodes `%XX` escapes. Every other byte stands for itself, `+` included. `None` for a broken escape or /// a decoded value that is not text. fn percent_decode(raw: &str) -> Option> { let bytes = raw.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { if bytes[i] == b'%' { let hex = bytes.get(i + 1..i + 3)?; let text = std::str::from_utf8(hex).ok()?; out.push(u8::from_str_radix(text, 16).ok()?); i += 3; } else { out.push(bytes[i]); i += 1; } } Some(out) } /// The JSON of an object as the PUT answers it (contracts.md 5). fn object_json(object: &Object) -> Value { json!({ "external_id": object.external_id, "size": object.size, "sha256": object.sha256, "content_type": object.content_type, "created_at": object.created_at, }) } /// An empty `204` with no cache. fn no_content() -> Response { let mut response = http::Response::new(Body::empty()); *response.status_mut() = StatusCode::NO_CONTENT; response } /// Removes a blob that a write or a delete has released. A blob that cannot be removed now is logged and /// left for the sweeper, because the row change has already committed. async fn retire_quietly(state: &AppState, key: &str) { if let Err(error) = state.store.retire_blob(key, state.blobs.as_ref()).await { tracing::warn!(key = %key, error = %error, "objects: released blob not removed"); } } /// `PUT /api/v1/objects/{external_id}`: stores the body as the object `external_id` of the caller. #[route(PUT "/api/v1/objects/{external_id}")] async fn put_object(cx: &Cx, body: Body) -> Result { let state = app_context::(cx); let caller = match machine_caller(cx).await? { Ok(caller) => caller, Err(refusal) => return Ok(refusal.answer()), }; let external_id = path_param_segment(cx, "external_id").to_owned(); if check_external_id(&external_id).is_err() { return Ok( bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), ); } let request = match PutRequest::from_headers(headers(cx)) { Ok(request) => request, Err(refusal) => return Ok(refusal.answer()), }; let service = caller.service; let existing = state.store.service_object(&service, &external_id).await?; if request.create_only && existing.is_some() { return Ok(Refusal { status: StatusCode::CONFLICT, error: "conflict", message: "an object with this external_id already exists", } .answer()); } let row = state .store .service(&service) .await? .ok_or(CoreError::NotFound)?; // The object being replaced gives its bytes back first, so a replace may grow only as far as the quota // allows. The same arithmetic is repeated inside the write transaction, which has the final say. let replaced = existing.as_ref().map_or(0, |object| object.size); let headroom = (row.quota_bytes - row.used_bytes + replaced).max(0) as u64; let quota_refusal = Refusal { status: StatusCode::PAYLOAD_TOO_LARGE, error: "quota_exceeded", message: "the service quota is used up", }; if request.declared.is_some_and(|length| length > headroom) { return Ok(quota_refusal.answer()); } // The bytes this write may stage: its declared length, or the whole headroom when none was declared. // They are reserved for the service before a byte is read, so writes in flight together cannot stage // more than the headroom. The reservation is released when this handler returns, on every path. let reserve = request.declared.unwrap_or(headroom); let Some(_staging) = state.staging.reserve(&service, reserve, headroom) else { let mut response = Refusal { status: StatusCode::TOO_MANY_REQUESTS, error: "rate_limited", message: "other writes to this service are staging; retry shortly", } .answer(); response .headers_mut() .insert(RETRY_AFTER, HeaderValue::from_static("1")); return Ok(response); }; let mut staged = StagedFile::create(&state.config.data_dir, reserve).await?; let mut frames = body.into_data_stream(); while let Some(frame) = frames.next().await { let written = match frame { Ok(bytes) => staged.write(&bytes).await, Err(_) => { staged.abort().await; return Ok(bad_request("the request body could not be read").answer()); } }; if let Err(error) = written { staged.abort().await; return match error { CoreError::Invalid(_) => Ok(quota_refusal.answer()), other => Err(other.into()), }; } } let staged = staged.finish().await?; // The claim is taken before the bytes are put, so a removal of the same blob cannot run in between. let key = object_blob_key(&service, &staged.sha256); let hold = state.store.hold_blob(&key).await; if let Err(error) = state.blobs.put_file(&key, &staged.path).await { drop(hold); return Err(error.into()); } let outcome = state .store .put_object(NewObject { service: service.clone(), external_id: external_id.clone(), size: staged.size as i64, sha256: staged.sha256.clone(), content_type: request.content_type, name: request.name, create_only: request.create_only, }) .await; drop(hold); match outcome? { PutOutcome::Stored { object, created, replaced_blob, } => { if let Some(old) = replaced_blob { retire_quietly(state, &old).await; } let status = if created { StatusCode::CREATED } else { StatusCode::OK }; Ok(json_response(status, &object_json(&object))) } PutOutcome::QuotaExceeded => { retire_quietly(state, &key).await; Ok(quota_refusal.answer()) } PutOutcome::Exists => { retire_quietly(state, &key).await; Ok(Refusal { status: StatusCode::CONFLICT, error: "conflict", message: "an object with this external_id already exists", } .answer()) } } } /// `GET /api/v1/objects/{external_id}` and `HEAD` (the router answers HEAD with this handler). #[route(GET "/api/v1/objects/{external_id}")] async fn get_object(cx: &Cx) -> Result { let state = app_context::(cx); let caller = match machine_caller(cx).await? { Ok(caller) => caller, Err(refusal) => return Ok(refusal.answer()), }; let external_id = path_param_segment(cx, "external_id").to_owned(); if check_external_id(&external_id).is_err() { return Ok( bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), ); } let Some(object) = state .store .service_object(&caller.service, &external_id) .await? else { return Ok(not_found().answer()); }; let name = object .name .clone() .unwrap_or_else(|| object.external_id.clone()); let source = ByteSource { blob_key: &object.blob_key, size: object.size as u64, // The object API's validator is the content's SHA-256 (contracts.md 5). The caller holds the // object's bytes already, so the hash reveals nothing new to it. validator: &object.sha256, content_sha256: Some(&object.sha256), mime: &object.content_type, name: &name, }; let (status, response_headers, body) = serve_bytes_with( cx, state.blobs.as_ref(), &source, Disposition::Attachment, OBJECT_CACHE, ) .await?; let mut response = http::Response::new(body); *response.status_mut() = status; *response.headers_mut() = response_headers; Ok(response) } /// The `404` of a missing object. The same answer for an id that another service holds, since namespaces /// are separate. fn not_found() -> Refusal { Refusal { status: StatusCode::NOT_FOUND, error: "not_found", message: "no such object", } } /// `DELETE /api/v1/objects/{external_id}`: removes the object, idempotently. #[route(DELETE "/api/v1/objects/{external_id}")] async fn delete_object(cx: &Cx) -> Result { let state = app_context::(cx); let caller = match machine_caller(cx).await? { Ok(caller) => caller, Err(refusal) => return Ok(refusal.answer()), }; let external_id = path_param_segment(cx, "external_id").to_owned(); if check_external_id(&external_id).is_err() { return Ok( bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), ); } if let Some(removed) = state .store .delete_object(&caller.service, &external_id) .await? { retire_quietly(state, &removed.blob_key).await; } Ok(no_content()) } /// `PUT`, `GET` and `DELETE` on a path with more than one segment after `objects/`. The id cannot contain /// `/`, so the answer is the contract's `400`, not a bare `404`. #[route(PUT "/api/v1/objects/{external_id}/{rest}")] async fn put_nested(cx: &Cx) -> Result { nested_id(cx).await } /// See [`put_nested`]. #[route(GET "/api/v1/objects/{external_id}/{rest}")] async fn get_nested(cx: &Cx) -> Result { nested_id(cx).await } /// See [`put_nested`]. #[route(DELETE "/api/v1/objects/{external_id}/{rest}")] async fn delete_nested(cx: &Cx) -> Result { nested_id(cx).await } /// The answer of a nested object path: authenticated callers get `400`, others get the token refusal. async fn nested_id(cx: &Cx) -> Result { if let Err(refusal) = machine_caller(cx).await? { return Ok(refusal.answer()); } Ok(bad_request("external_id must not contain '/'").answer()) } /// `GET /api/v1/usage`: the caller's quota, bytes used and object count. #[route(GET "/api/v1/usage")] async fn usage_report(cx: &Cx) -> Result { let state = app_context::(cx); let caller = match machine_caller(cx).await? { Ok(caller) => caller, Err(refusal) => return Ok(refusal.answer()), }; let usage = state.store.service_usage(&caller.service).await?; Ok(json_response( StatusCode::OK, &json!({ "quota_bytes": usage.quota_bytes, "used_bytes": usage.used_bytes, "objects": usage.objects, }), )) } #[cfg(test)] mod tests { use super::*; use http::HeaderValue; #[test] fn percent_decoding_takes_escapes_and_refuses_broken_ones() { assert_eq!(percent_decode("a%20b+c").as_deref(), Some(&b"a b+c"[..])); assert_eq!(percent_decode("%C3%BC").as_deref(), Some("ΓΌ".as_bytes())); assert_eq!(percent_decode("%2"), None); assert_eq!(percent_decode("%zz"), None); } #[test] fn content_type_must_be_a_media_type() { let mut request = HeaderMap::new(); request.insert( CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"), ); assert_eq!( content_type_of(&request).unwrap(), "text/plain; charset=utf-8" ); for bad in ["no-slash", "text/", "a b/c", "text/html\u{7f}"] { let mut request = HeaderMap::new(); if let Ok(value) = HeaderValue::from_str(bad) { request.insert(CONTENT_TYPE, value); assert!(content_type_of(&request).is_err(), "{bad:?}"); } } assert_eq!( content_type_of(&HeaderMap::new()).unwrap(), DEFAULT_CONTENT_TYPE ); } #[test] fn names_are_decoded_and_cleaned_like_file_names() { let mut request = HeaderMap::new(); request.insert( "x-object-name", HeaderValue::from_static("..%2F..%2Fetc%2Fpasswd"), ); assert_eq!(object_name(&request).unwrap().as_deref(), Some("passwd")); request.insert("x-object-name", HeaderValue::from_static("%FF")); assert!(object_name(&request).is_err()); } } #[cfg(test)] mod router_tests { //! Router-level tests of the object API: the token rules, the namespace, the id rules, the quota and //! the replace and sharing of blobs. The keys are a fresh Ed25519 key injected into the JWKS cache, so //! no request reaches `im`. use super::*; use crate::boot::{router, test_state}; use crate::oidc::OidcClient; use crate::oidc::test_support::{CLIENT, ISSUER, sign, test_key}; use crate::state::AppState; use http::Request; use http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; use in_core::store::objects::SERVICE_QUOTA_SETTING; use serde_json::json; use sha2::{Digest, Sha256}; use topcoat::router::{Body, to_bytes}; /// A state with the object API's keys in place, and a fresh signing key for the test's tokens. async fn setup() -> (tempfile::TempDir, AppState, Vec) { let (dir, mut state) = test_state().await; let (der, keys) = test_key(); state.oidc = Some(std::sync::Arc::new(OidcClient::with_keys_for_tests( ISSUER, CLIENT, keys, ))); (dir, state, der) } /// A client token for `svc` with `scope` and `aud`. `sub` defaults to the client form. fn machine_token(der: &[u8], svc: &str, scope: &str, aud: &str) -> String { let now = crate::oidc::now_secs(); sign( der, &json!({ "iss": ISSUER, "sub": format!("client:{svc}"), "azp": svc, "aud": aud, "scope": scope, "svc": svc, "iat": now, "exp": now + 600, "jti": "t-1", }), ) } /// One call to the object API. Returns the status, the headers and the body bytes. async fn call( state: &AppState, method: &str, path: &str, token: Option<&str>, extra: &[(&str, &str)], body: Vec, ) -> (StatusCode, http::HeaderMap, Vec) { let mut request = Request::builder().method(method).uri(path); if let Some(token) = token { request = request.header(AUTHORIZATION, format!("Bearer {token}")); } for (name, value) in extra { request = request.header(*name, *value); } let request = request.body(Body::from(body)).expect("request"); let response = router(state.clone()).handle(request).await; let status = response.status(); let headers = response.headers().clone(); let bytes = to_bytes(response.into_body(), 1 << 20).await.expect("body"); (status, headers, bytes.to_vec()) } fn json_of(bytes: &[u8]) -> Value { serde_json::from_slice(bytes).unwrap_or(Value::Null) } fn sha_hex(bytes: &[u8]) -> String { Sha256::digest(bytes) .iter() .map(|byte| format!("{byte:02x}")) .collect() } const PUT_PATH: &str = "/api/v1/objects/task-1"; /// A token for an audience other than `in` is refused with 401 and the Bearer challenge. A token without /// `files.service` is 403. A user's token (no client subject, no `svc`) is 401. #[tokio::test] async fn the_token_must_be_for_in_and_carry_the_scope() { let (_dir, state, der) = setup().await; let for_im = machine_token(&der, "iz", "files.service", "im"); let (status, headers, _) = call(&state, "GET", "/api/v1/usage", Some(&for_im), &[], vec![]).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\""); let no_scope = machine_token(&der, "iz", "directory.read", "in"); let (status, _, body) = call(&state, "GET", "/api/v1/usage", Some(&no_scope), &[], vec![]).await; assert_eq!(status, StatusCode::FORBIDDEN); assert_eq!(json_of(&body)["error"], "insufficient_scope"); let now = crate::oidc::now_secs(); let user = sign( &der, &json!({"iss": ISSUER, "sub": "01JUSER", "aud": "in", "scope": "files.service", "iat": now, "exp": now + 600}), ); let (status, _, _) = call(&state, "GET", "/api/v1/usage", Some(&user), &[], vec![]).await; assert_eq!(status, StatusCode::UNAUTHORIZED); let (status, _, _) = call(&state, "GET", "/api/v1/usage", None, &[], vec![]).await; assert_eq!(status, StatusCode::UNAUTHORIZED); } /// Two services that use the same id hold two objects. Service `im` cannot read, replace or delete the /// object that `iz` stored, and its own delete leaves `iz`'s object alone. #[tokio::test] async fn a_service_cannot_reach_another_services_object() { let (_dir, state, der) = setup().await; let iz = machine_token(&der, "iz", "files.service", "in"); let im = machine_token(&der, "im", "files.service", "in"); let (status, _, _) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"from iz".to_vec()).await; assert_eq!(status, StatusCode::CREATED); let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&im), &[], vec![]).await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, _, _) = call(&state, "DELETE", PUT_PATH, Some(&im), &[], vec![]).await; assert_eq!(status, StatusCode::NO_CONTENT); let (status, _, body) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; assert_eq!(status, StatusCode::OK); assert_eq!(body, b"from iz"); } /// An id with `/` or a charset break is 400, and nothing is stored under it. #[tokio::test] async fn an_external_id_outside_the_contract_is_400() { let (_dir, state, der) = setup().await; let iz = machine_token(&der, "iz", "files.service", "in"); for path in [ "/api/v1/objects/a/b", "/api/v1/objects/..%2Fx", "/api/v1/objects/a%20b", ] { let (status, _, body) = call(&state, "PUT", path, Some(&iz), &[], b"x".to_vec()).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{path}"); assert_eq!(json_of(&body)["error"], "invalid_request", "{path}"); } let usage = state.store.service_usage("iz").await.unwrap(); assert_eq!(usage.objects, 0); } /// A body above the quota is refused with 413 `quota_exceeded`. Nothing is stored and no bytes stay /// counted. A `Content-Length` above the quota is refused before the body is read. #[tokio::test] async fn a_body_over_the_quota_is_refused_and_stores_nothing() { let (_dir, state, der) = setup().await; state .store .set_setting(SERVICE_QUOTA_SETTING, "10") .await .unwrap(); let iz = machine_token(&der, "iz", "files.service", "in"); let (status, _, body) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], vec![7u8; 11]).await; assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); assert_eq!(json_of(&body)["error"], "quota_exceeded"); let (status, _, _) = call( &state, "PUT", PUT_PATH, Some(&iz), &[("content-length", "11")], vec![7u8; 11], ) .await; assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); let usage = state.store.service_usage("iz").await.unwrap(); assert_eq!( (usage.objects, usage.used_bytes, usage.quota_bytes), (0, 0, 10) ); let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; assert_eq!(status, StatusCode::NOT_FOUND); } /// A replace keeps one row and reports 200. The old bytes are removed once no object names them, and /// identical content from two ids shares one blob until the last of them is deleted. #[tokio::test] async fn a_replace_keeps_one_row_and_shared_bytes_outlive_one_object() { let (_dir, state, der) = setup().await; let iz = machine_token(&der, "iz", "files.service", "in"); let (status, _, _) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"first".to_vec()).await; assert_eq!(status, StatusCode::CREATED); let old_key = object_blob_key("iz", &sha_hex(b"first")); let (status, _, body) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"second!".to_vec()).await; assert_eq!(status, StatusCode::OK); assert_eq!(json_of(&body)["size"], 7); assert_eq!(state.blobs.size(&old_key).await.unwrap(), None); assert_eq!(state.store.service_usage("iz").await.unwrap().objects, 1); // Two ids with the same bytes share one blob. let (status, _, _) = call( &state, "PUT", "/api/v1/objects/copy-a", Some(&iz), &[], b"same".to_vec(), ) .await; assert_eq!(status, StatusCode::CREATED); let (status, _, _) = call( &state, "PUT", "/api/v1/objects/copy-b", Some(&iz), &[], b"same".to_vec(), ) .await; assert_eq!(status, StatusCode::CREATED); let shared = object_blob_key("iz", &sha_hex(b"same")); let (status, _, _) = call( &state, "DELETE", "/api/v1/objects/copy-a", Some(&iz), &[], vec![], ) .await; assert_eq!(status, StatusCode::NO_CONTENT); assert_eq!(state.blobs.size(&shared).await.unwrap(), Some(4)); let (status, _, body) = call( &state, "GET", "/api/v1/objects/copy-b", Some(&iz), &[], vec![], ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(body, b"same"); } /// A GET answers the stored bytes as an attachment with the stored type and the sha256 as its ETag, and /// honours one `Range`. `If-None-Match` with the same hash is `304`. A DELETE of an absent id is `204`. #[tokio::test] async fn get_serves_the_bytes_as_an_attachment_with_range() { let (_dir, state, der) = setup().await; let iz = machine_token(&der, "iz", "files.service", "in"); let (status, _, _) = call( &state, "PUT", PUT_PATH, Some(&iz), &[ ("content-type", "text/plain"), ("x-object-name", "notes%2Fa%20b.txt"), ], b"0123456789".to_vec(), ) .await; assert_eq!(status, StatusCode::CREATED); let (status, headers, body) = call( &state, "GET", PUT_PATH, Some(&iz), &[("range", "bytes=2-4")], vec![], ) .await; assert_eq!(status, StatusCode::PARTIAL_CONTENT); assert_eq!(body, b"234"); assert_eq!( headers["content-disposition"] .to_str() .unwrap() .split(';') .next(), Some("attachment") ); assert_eq!( headers["etag"], format!("\"{}\"", sha_hex(b"0123456789")).as_str() ); let etag = format!("\"{}\"", sha_hex(b"0123456789")); let (status, _, _) = call( &state, "GET", PUT_PATH, Some(&iz), &[("if-none-match", etag.as_str())], vec![], ) .await; assert_eq!(status, StatusCode::NOT_MODIFIED); let (status, _, _) = call( &state, "DELETE", "/api/v1/objects/never-was", Some(&iz), &[], vec![], ) .await; assert_eq!(status, StatusCode::NO_CONTENT); } }