forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

objects.rs813 lines, 30.5 KiBHistoryRawDownload
1//! The object store API for family services (contracts.md 5). `iz` keeps its blobs here, under its own
2//! namespace, with its own quota. Every route needs a client-credentials token with `aud = "in"` and scope
3//! `files.service`, checked in `machine_auth.rs`; the namespace is the token's `svc` and nothing else.
4//!
5//! The routes:
6//! - `PUT /api/v1/objects/{external_id}` stores the raw body. The bytes stream to a staged file while their
7//! SHA-256 is computed. The body may not be longer than the quota that is left (the service quota, less
8//! what the service uses, plus the bytes of the object being replaced), and the limit is enforced while it
9//! is read, so nothing above it is stored. The bytes are put at `objects/<service>/<sha256>`, and the row
10//! is committed in the same step that moves the quota. A new id answers `201`, a replaced one `200`.
11//! `If-None-Match: *` refuses an existing id with `409`.
12//! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support.
13//! The cache policy is `private, no-cache`, because a replace changes what the id names.
14//! - A write reserves the bytes it may stage for its service before it reads the body. A write that would
15//! take the service past its headroom, together with the writes in flight, is `429 rate_limited`.
16//! - `DELETE` removes the object. It answers `204` also when the object was already absent.
17//! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects.
18//!
19//! Blob removal goes through `Store::retire_blob`, so bytes that another object still names, or that a
20//! write is storing right now, are never removed. A removal that is refused is left to the sweeper.
21
22use futures_util::StreamExt;
23use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH, RETRY_AFTER};
24use http::{HeaderValue, StatusCode};
25use in_core::error::Error as CoreError;
26use in_core::names;
27use in_core::staging::StagedFile;
28use in_core::store::objects::{NewObject, Object, PutOutcome, check_external_id, object_blob_key};
29use serde_json::{Value, json};
30use topcoat::Result;
31use topcoat::context::{Cx, app_context};
32use topcoat::router::request::headers;
33use topcoat::router::response::Response;
34use topcoat::router::{Body, HeaderMap, path_param_segment, route};
35
36use crate::api::machine_auth::{Refusal, json_response, machine_caller};
37use crate::serve_bytes::{ByteSource, Disposition, SHARE_CACHE, serve_bytes_with};
38use crate::state::AppState;
39
40/// The `Content-Type` of an object whose PUT names none.
41const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
42
43/// Longest `Content-Type` value kept, in bytes.
44const MAX_CONTENT_TYPE_BYTES: usize = 255;
45
46/// Longest `X-Object-Name`, in bytes, after decoding.
47const MAX_NAME_BYTES: usize = 255;
48
49/// The cache policy of object bytes: the id can be replaced at any time, so a cached copy must be checked.
50const OBJECT_CACHE: &str = SHARE_CACHE;
51
52/// A `400` with the stable word `invalid_request`.
53fn bad_request(message: &'static str) -> Refusal {
54 Refusal {
55 status: StatusCode::BAD_REQUEST,
56 error: "invalid_request",
57 message,
58 }
59}
60
61/// The headers of a PUT that the handler reads before it touches the body.
62#[derive(Debug, PartialEq, Eq)]
63struct PutRequest {
64 /// The `Content-Length` the client declared, if any. Checked against the quota before a byte is read.
65 declared: Option<u64>,
66 /// The `Content-Type`, stored as given.
67 content_type: String,
68 /// The cleaned `X-Object-Name`, if one was sent.
69 name: Option<String>,
70 /// `true` for `If-None-Match: *`: the PUT must create the id, not replace it.
71 create_only: bool,
72}
73
74impl PutRequest {
75 /// Reads the PUT headers. Malformed ones are `400`, and nothing is stored.
76 fn from_headers(request: &HeaderMap) -> std::result::Result<Self, Refusal> {
77 let declared = match request.get(CONTENT_LENGTH) {
78 None => None,
79 Some(value) => Some(
80 value
81 .to_str()
82 .ok()
83 .and_then(|text| text.parse::<u64>().ok())
84 .ok_or_else(|| bad_request("Content-Length is not a number"))?,
85 ),
86 };
87 let create_only = match request.get(IF_NONE_MATCH) {
88 None => false,
89 Some(value) if value.as_bytes() == b"*" => true,
90 Some(_) => return Err(bad_request("If-None-Match must be *")),
91 };
92 Ok(Self {
93 declared,
94 content_type: content_type_of(request)?,
95 name: object_name(request)?,
96 create_only,
97 })
98 }
99}
100
101/// The stored `Content-Type`: the client's value when it is a `type/subtype` with printable ASCII, else
102/// `application/octet-stream`.
103fn content_type_of(request: &HeaderMap) -> std::result::Result<String, Refusal> {
104 let Some(value) = request.get(CONTENT_TYPE) else {
105 return Ok(DEFAULT_CONTENT_TYPE.to_owned());
106 };
107 let text = value
108 .to_str()
109 .map_err(|_| bad_request("Content-Type is not ASCII"))?
110 .trim();
111 let essence = text.split(';').next().unwrap_or_default().trim();
112 let well_formed = essence
113 .split_once('/')
114 .is_some_and(|(main, sub)| is_token(main) && is_token(sub));
115 if !well_formed || text.len() > MAX_CONTENT_TYPE_BYTES {
116 return Err(bad_request("Content-Type must be type/subtype"));
117 }
118 Ok(text.to_owned())
119}
120
121/// Whether `text` is a non-empty HTTP token (RFC 9110 section 5.6.2).
122fn is_token(text: &str) -> bool {
123 !text.is_empty()
124 && text
125 .bytes()
126 .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
127}
128
129/// The `X-Object-Name`: percent-encoded UTF-8, at most 255 bytes once decoded. It is cleaned like a file
130/// name (`names::display_name`), so a path or control characters cannot reach a download header.
131fn object_name(request: &HeaderMap) -> std::result::Result<Option<String>, Refusal> {
132 let Some(value) = request.get("x-object-name") else {
133 return Ok(None);
134 };
135 let raw = value
136 .to_str()
137 .map_err(|_| bad_request("X-Object-Name is not ASCII"))?;
138 let decoded =
139 percent_decode(raw).ok_or_else(|| bad_request("X-Object-Name is not percent-encoded"))?;
140 if decoded.len() > MAX_NAME_BYTES {
141 return Err(bad_request("X-Object-Name is longer than 255 bytes"));
142 }
143 let text = String::from_utf8(decoded).map_err(|_| bad_request("X-Object-Name is not UTF-8"))?;
144 if text.trim().is_empty() {
145 return Ok(None);
146 }
147 Ok(Some(names::display_name(&text)))
148}
149
150/// Decodes `%XX` escapes. Every other byte stands for itself, `+` included. `None` for a broken escape or
151/// a decoded value that is not text.
152fn percent_decode(raw: &str) -> Option<Vec<u8>> {
153 let bytes = raw.as_bytes();
154 let mut out = Vec::with_capacity(bytes.len());
155 let mut i = 0;
156 while i < bytes.len() {
157 if bytes[i] == b'%' {
158 let hex = bytes.get(i + 1..i + 3)?;
159 let text = std::str::from_utf8(hex).ok()?;
160 out.push(u8::from_str_radix(text, 16).ok()?);
161 i += 3;
162 } else {
163 out.push(bytes[i]);
164 i += 1;
165 }
166 }
167 Some(out)
168}
169
170/// The JSON of an object as the PUT answers it (contracts.md 5).
171fn object_json(object: &Object) -> Value {
172 json!({
173 "external_id": object.external_id,
174 "size": object.size,
175 "sha256": object.sha256,
176 "content_type": object.content_type,
177 "created_at": object.created_at,
178 })
179}
180
181/// An empty `204` with no cache.
182fn no_content() -> Response {
183 let mut response = http::Response::new(Body::empty());
184 *response.status_mut() = StatusCode::NO_CONTENT;
185 response
186}
187
188/// Removes a blob that a write or a delete has released. A blob that cannot be removed now is logged and
189/// left for the sweeper, because the row change has already committed.
190async fn retire_quietly(state: &AppState, key: &str) {
191 if let Err(error) = state.store.retire_blob(key, state.blobs.as_ref()).await {
192 tracing::warn!(key = %key, error = %error, "objects: released blob not removed");
193 }
194}
195
196/// `PUT /api/v1/objects/{external_id}`: stores the body as the object `external_id` of the caller.
197#[route(PUT "/api/v1/objects/{external_id}")]
198async fn put_object(cx: &Cx, body: Body) -> Result<Response> {
199 let state = app_context::<AppState>(cx);
200 let caller = match machine_caller(cx).await? {
201 Ok(caller) => caller,
202 Err(refusal) => return Ok(refusal.answer()),
203 };
204 let external_id = path_param_segment(cx, "external_id").to_owned();
205 if check_external_id(&external_id).is_err() {
206 return Ok(
207 bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(),
208 );
209 }
210 let request = match PutRequest::from_headers(headers(cx)) {
211 Ok(request) => request,
212 Err(refusal) => return Ok(refusal.answer()),
213 };
214 let service = caller.service;
215 let existing = state.store.service_object(&service, &external_id).await?;
216 if request.create_only && existing.is_some() {
217 return Ok(Refusal {
218 status: StatusCode::CONFLICT,
219 error: "conflict",
220 message: "an object with this external_id already exists",
221 }
222 .answer());
223 }
224 let row = state
225 .store
226 .service(&service)
227 .await?
228 .ok_or(CoreError::NotFound)?;
229 // The object being replaced gives its bytes back first, so a replace may grow only as far as the quota
230 // allows. The same arithmetic is repeated inside the write transaction, which has the final say.
231 let replaced = existing.as_ref().map_or(0, |object| object.size);
232 let headroom = (row.quota_bytes - row.used_bytes + replaced).max(0) as u64;
233 let quota_refusal = Refusal {
234 status: StatusCode::PAYLOAD_TOO_LARGE,
235 error: "quota_exceeded",
236 message: "the service quota is used up",
237 };
238 if request.declared.is_some_and(|length| length > headroom) {
239 return Ok(quota_refusal.answer());
240 }
241 // The bytes this write may stage: its declared length, or the whole headroom when none was declared.
242 // They are reserved for the service before a byte is read, so writes in flight together cannot stage
243 // more than the headroom. The reservation is released when this handler returns, on every path.
244 let reserve = request.declared.unwrap_or(headroom);
245 let Some(_staging) = state.staging.reserve(&service, reserve, headroom) else {
246 let mut response = Refusal {
247 status: StatusCode::TOO_MANY_REQUESTS,
248 error: "rate_limited",
249 message: "other writes to this service are staging; retry shortly",
250 }
251 .answer();
252 response
253 .headers_mut()
254 .insert(RETRY_AFTER, HeaderValue::from_static("1"));
255 return Ok(response);
256 };
257
258 let mut staged = StagedFile::create(&state.config.data_dir, reserve).await?;
259 let mut frames = body.into_data_stream();
260 while let Some(frame) = frames.next().await {
261 let written = match frame {
262 Ok(bytes) => staged.write(&bytes).await,
263 Err(_) => {
264 staged.abort().await;
265 return Ok(bad_request("the request body could not be read").answer());
266 }
267 };
268 if let Err(error) = written {
269 staged.abort().await;
270 return match error {
271 CoreError::Invalid(_) => Ok(quota_refusal.answer()),
272 other => Err(other.into()),
273 };
274 }
275 }
276 let staged = staged.finish().await?;
277
278 // The claim is taken before the bytes are put, so a removal of the same blob cannot run in between.
279 let key = object_blob_key(&service, &staged.sha256);
280 let hold = state.store.hold_blob(&key).await;
281 if let Err(error) = state.blobs.put_file(&key, &staged.path).await {
282 drop(hold);
283 return Err(error.into());
284 }
285 let outcome = state
286 .store
287 .put_object(NewObject {
288 service: service.clone(),
289 external_id: external_id.clone(),
290 size: staged.size as i64,
291 sha256: staged.sha256.clone(),
292 content_type: request.content_type,
293 name: request.name,
294 create_only: request.create_only,
295 })
296 .await;
297 drop(hold);
298 match outcome? {
299 PutOutcome::Stored {
300 object,
301 created,
302 replaced_blob,
303 } => {
304 if let Some(old) = replaced_blob {
305 retire_quietly(state, &old).await;
306 }
307 let status = if created {
308 StatusCode::CREATED
309 } else {
310 StatusCode::OK
311 };
312 Ok(json_response(status, &object_json(&object)))
313 }
314 PutOutcome::QuotaExceeded => {
315 retire_quietly(state, &key).await;
316 Ok(quota_refusal.answer())
317 }
318 PutOutcome::Exists => {
319 retire_quietly(state, &key).await;
320 Ok(Refusal {
321 status: StatusCode::CONFLICT,
322 error: "conflict",
323 message: "an object with this external_id already exists",
324 }
325 .answer())
326 }
327 }
328}
329
330/// `GET /api/v1/objects/{external_id}` and `HEAD` (the router answers HEAD with this handler).
331#[route(GET "/api/v1/objects/{external_id}")]
332async fn get_object(cx: &Cx) -> Result<Response> {
333 let state = app_context::<AppState>(cx);
334 let caller = match machine_caller(cx).await? {
335 Ok(caller) => caller,
336 Err(refusal) => return Ok(refusal.answer()),
337 };
338 let external_id = path_param_segment(cx, "external_id").to_owned();
339 if check_external_id(&external_id).is_err() {
340 return Ok(
341 bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(),
342 );
343 }
344 let Some(object) = state
345 .store
346 .service_object(&caller.service, &external_id)
347 .await?
348 else {
349 return Ok(not_found().answer());
350 };
351 let name = object
352 .name
353 .clone()
354 .unwrap_or_else(|| object.external_id.clone());
355 let source = ByteSource {
356 blob_key: &object.blob_key,
357 size: object.size as u64,
358 // The object API's validator is the content's SHA-256 (contracts.md 5). The caller holds the
359 // object's bytes already, so the hash reveals nothing new to it.
360 validator: &object.sha256,
361 content_sha256: Some(&object.sha256),
362 mime: &object.content_type,
363 name: &name,
364 };
365 let (status, response_headers, body) = serve_bytes_with(
366 cx,
367 state.blobs.as_ref(),
368 &source,
369 Disposition::Attachment,
370 OBJECT_CACHE,
371 )
372 .await?;
373 let mut response = http::Response::new(body);
374 *response.status_mut() = status;
375 *response.headers_mut() = response_headers;
376 Ok(response)
377}
378
379/// The `404` of a missing object. The same answer for an id that another service holds, since namespaces
380/// are separate.
381fn not_found() -> Refusal {
382 Refusal {
383 status: StatusCode::NOT_FOUND,
384 error: "not_found",
385 message: "no such object",
386 }
387}
388
389/// `DELETE /api/v1/objects/{external_id}`: removes the object, idempotently.
390#[route(DELETE "/api/v1/objects/{external_id}")]
391async fn delete_object(cx: &Cx) -> Result<Response> {
392 let state = app_context::<AppState>(cx);
393 let caller = match machine_caller(cx).await? {
394 Ok(caller) => caller,
395 Err(refusal) => return Ok(refusal.answer()),
396 };
397 let external_id = path_param_segment(cx, "external_id").to_owned();
398 if check_external_id(&external_id).is_err() {
399 return Ok(
400 bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(),
401 );
402 }
403 if let Some(removed) = state
404 .store
405 .delete_object(&caller.service, &external_id)
406 .await?
407 {
408 retire_quietly(state, &removed.blob_key).await;
409 }
410 Ok(no_content())
411}
412
413/// `PUT`, `GET` and `DELETE` on a path with more than one segment after `objects/`. The id cannot contain
414/// `/`, so the answer is the contract's `400`, not a bare `404`.
415#[route(PUT "/api/v1/objects/{external_id}/{rest}")]
416async fn put_nested(cx: &Cx) -> Result<Response> {
417 nested_id(cx).await
418}
419
420/// See [`put_nested`].
421#[route(GET "/api/v1/objects/{external_id}/{rest}")]
422async fn get_nested(cx: &Cx) -> Result<Response> {
423 nested_id(cx).await
424}
425
426/// See [`put_nested`].
427#[route(DELETE "/api/v1/objects/{external_id}/{rest}")]
428async fn delete_nested(cx: &Cx) -> Result<Response> {
429 nested_id(cx).await
430}
431
432/// The answer of a nested object path: authenticated callers get `400`, others get the token refusal.
433async fn nested_id(cx: &Cx) -> Result<Response> {
434 if let Err(refusal) = machine_caller(cx).await? {
435 return Ok(refusal.answer());
436 }
437 Ok(bad_request("external_id must not contain '/'").answer())
438}
439
440/// `GET /api/v1/usage`: the caller's quota, bytes used and object count.
441#[route(GET "/api/v1/usage")]
442async fn usage_report(cx: &Cx) -> Result<Response> {
443 let state = app_context::<AppState>(cx);
444 let caller = match machine_caller(cx).await? {
445 Ok(caller) => caller,
446 Err(refusal) => return Ok(refusal.answer()),
447 };
448 let usage = state.store.service_usage(&caller.service).await?;
449 Ok(json_response(
450 StatusCode::OK,
451 &json!({
452 "quota_bytes": usage.quota_bytes,
453 "used_bytes": usage.used_bytes,
454 "objects": usage.objects,
455 }),
456 ))
457}
458
459#[cfg(test)]
460mod tests {
461 use super::*;
462 use http::HeaderValue;
463
464 #[test]
465 fn percent_decoding_takes_escapes_and_refuses_broken_ones() {
466 assert_eq!(percent_decode("a%20b+c").as_deref(), Some(&b"a b+c"[..]));
467 assert_eq!(percent_decode("%C3%BC").as_deref(), Some("ü".as_bytes()));
468 assert_eq!(percent_decode("%2"), None);
469 assert_eq!(percent_decode("%zz"), None);
470 }
471
472 #[test]
473 fn content_type_must_be_a_media_type() {
474 let mut request = HeaderMap::new();
475 request.insert(
476 CONTENT_TYPE,
477 HeaderValue::from_static("text/plain; charset=utf-8"),
478 );
479 assert_eq!(
480 content_type_of(&request).unwrap(),
481 "text/plain; charset=utf-8"
482 );
483 for bad in ["no-slash", "text/", "a b/c", "text/html\u{7f}"] {
484 let mut request = HeaderMap::new();
485 if let Ok(value) = HeaderValue::from_str(bad) {
486 request.insert(CONTENT_TYPE, value);
487 assert!(content_type_of(&request).is_err(), "{bad:?}");
488 }
489 }
490 assert_eq!(
491 content_type_of(&HeaderMap::new()).unwrap(),
492 DEFAULT_CONTENT_TYPE
493 );
494 }
495
496 #[test]
497 fn names_are_decoded_and_cleaned_like_file_names() {
498 let mut request = HeaderMap::new();
499 request.insert(
500 "x-object-name",
501 HeaderValue::from_static("..%2F..%2Fetc%2Fpasswd"),
502 );
503 assert_eq!(object_name(&request).unwrap().as_deref(), Some("passwd"));
504 request.insert("x-object-name", HeaderValue::from_static("%FF"));
505 assert!(object_name(&request).is_err());
506 }
507}
508
509#[cfg(test)]
510mod router_tests {
511 //! Router-level tests of the object API: the token rules, the namespace, the id rules, the quota and
512 //! the replace and sharing of blobs. The keys are a fresh Ed25519 key injected into the JWKS cache, so
513 //! no request reaches `im`.
514
515 use super::*;
516 use crate::boot::{router, test_state};
517 use crate::oidc::OidcClient;
518 use crate::oidc::test_support::{CLIENT, ISSUER, sign, test_key};
519 use crate::state::AppState;
520 use http::Request;
521 use http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
522 use in_core::store::objects::SERVICE_QUOTA_SETTING;
523 use serde_json::json;
524 use sha2::{Digest, Sha256};
525 use topcoat::router::{Body, to_bytes};
526
527 /// A state with the object API's keys in place, and a fresh signing key for the test's tokens.
528 async fn setup() -> (tempfile::TempDir, AppState, Vec<u8>) {
529 let (dir, mut state) = test_state().await;
530 let (der, keys) = test_key();
531 state.oidc = Some(std::sync::Arc::new(OidcClient::with_keys_for_tests(
532 ISSUER, CLIENT, keys,
533 )));
534 (dir, state, der)
535 }
536
537 /// A client token for `svc` with `scope` and `aud`. `sub` defaults to the client form.
538 fn machine_token(der: &[u8], svc: &str, scope: &str, aud: &str) -> String {
539 let now = crate::oidc::now_secs();
540 sign(
541 der,
542 &json!({
543 "iss": ISSUER, "sub": format!("client:{svc}"), "azp": svc, "aud": aud,
544 "scope": scope, "svc": svc, "iat": now, "exp": now + 600, "jti": "t-1",
545 }),
546 )
547 }
548
549 /// One call to the object API. Returns the status, the headers and the body bytes.
550 async fn call(
551 state: &AppState,
552 method: &str,
553 path: &str,
554 token: Option<&str>,
555 extra: &[(&str, &str)],
556 body: Vec<u8>,
557 ) -> (StatusCode, http::HeaderMap, Vec<u8>) {
558 let mut request = Request::builder().method(method).uri(path);
559 if let Some(token) = token {
560 request = request.header(AUTHORIZATION, format!("Bearer {token}"));
561 }
562 for (name, value) in extra {
563 request = request.header(*name, *value);
564 }
565 let request = request.body(Body::from(body)).expect("request");
566 let response = router(state.clone()).handle(request).await;
567 let status = response.status();
568 let headers = response.headers().clone();
569 let bytes = to_bytes(response.into_body(), 1 << 20).await.expect("body");
570 (status, headers, bytes.to_vec())
571 }
572
573 fn json_of(bytes: &[u8]) -> Value {
574 serde_json::from_slice(bytes).unwrap_or(Value::Null)
575 }
576
577 fn sha_hex(bytes: &[u8]) -> String {
578 Sha256::digest(bytes)
579 .iter()
580 .map(|byte| format!("{byte:02x}"))
581 .collect()
582 }
583
584 const PUT_PATH: &str = "/api/v1/objects/task-1";
585
586 /// A token for an audience other than `in` is refused with 401 and the Bearer challenge. A token without
587 /// `files.service` is 403. A user's token (no client subject, no `svc`) is 401.
588 #[tokio::test]
589 async fn the_token_must_be_for_in_and_carry_the_scope() {
590 let (_dir, state, der) = setup().await;
591 let for_im = machine_token(&der, "iz", "files.service", "im");
592 let (status, headers, _) =
593 call(&state, "GET", "/api/v1/usage", Some(&for_im), &[], vec![]).await;
594 assert_eq!(status, StatusCode::UNAUTHORIZED);
595 assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\"");
596
597 let no_scope = machine_token(&der, "iz", "directory.read", "in");
598 let (status, _, body) =
599 call(&state, "GET", "/api/v1/usage", Some(&no_scope), &[], vec![]).await;
600 assert_eq!(status, StatusCode::FORBIDDEN);
601 assert_eq!(json_of(&body)["error"], "insufficient_scope");
602
603 let now = crate::oidc::now_secs();
604 let user = sign(
605 &der,
606 &json!({"iss": ISSUER, "sub": "01JUSER", "aud": "in", "scope": "files.service",
607 "iat": now, "exp": now + 600}),
608 );
609 let (status, _, _) = call(&state, "GET", "/api/v1/usage", Some(&user), &[], vec![]).await;
610 assert_eq!(status, StatusCode::UNAUTHORIZED);
611
612 let (status, _, _) = call(&state, "GET", "/api/v1/usage", None, &[], vec![]).await;
613 assert_eq!(status, StatusCode::UNAUTHORIZED);
614 }
615
616 /// Two services that use the same id hold two objects. Service `im` cannot read, replace or delete the
617 /// object that `iz` stored, and its own delete leaves `iz`'s object alone.
618 #[tokio::test]
619 async fn a_service_cannot_reach_another_services_object() {
620 let (_dir, state, der) = setup().await;
621 let iz = machine_token(&der, "iz", "files.service", "in");
622 let im = machine_token(&der, "im", "files.service", "in");
623 let (status, _, _) =
624 call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"from iz".to_vec()).await;
625 assert_eq!(status, StatusCode::CREATED);
626
627 let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&im), &[], vec![]).await;
628 assert_eq!(status, StatusCode::NOT_FOUND);
629 let (status, _, _) = call(&state, "DELETE", PUT_PATH, Some(&im), &[], vec![]).await;
630 assert_eq!(status, StatusCode::NO_CONTENT);
631 let (status, _, body) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await;
632 assert_eq!(status, StatusCode::OK);
633 assert_eq!(body, b"from iz");
634 }
635
636 /// An id with `/` or a charset break is 400, and nothing is stored under it.
637 #[tokio::test]
638 async fn an_external_id_outside_the_contract_is_400() {
639 let (_dir, state, der) = setup().await;
640 let iz = machine_token(&der, "iz", "files.service", "in");
641 for path in [
642 "/api/v1/objects/a/b",
643 "/api/v1/objects/..%2Fx",
644 "/api/v1/objects/a%20b",
645 ] {
646 let (status, _, body) = call(&state, "PUT", path, Some(&iz), &[], b"x".to_vec()).await;
647 assert_eq!(status, StatusCode::BAD_REQUEST, "{path}");
648 assert_eq!(json_of(&body)["error"], "invalid_request", "{path}");
649 }
650 let usage = state.store.service_usage("iz").await.unwrap();
651 assert_eq!(usage.objects, 0);
652 }
653
654 /// A body above the quota is refused with 413 `quota_exceeded`. Nothing is stored and no bytes stay
655 /// counted. A `Content-Length` above the quota is refused before the body is read.
656 #[tokio::test]
657 async fn a_body_over_the_quota_is_refused_and_stores_nothing() {
658 let (_dir, state, der) = setup().await;
659 state
660 .store
661 .set_setting(SERVICE_QUOTA_SETTING, "10")
662 .await
663 .unwrap();
664 let iz = machine_token(&der, "iz", "files.service", "in");
665 let (status, _, body) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], vec![7u8; 11]).await;
666 assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
667 assert_eq!(json_of(&body)["error"], "quota_exceeded");
668 let (status, _, _) = call(
669 &state,
670 "PUT",
671 PUT_PATH,
672 Some(&iz),
673 &[("content-length", "11")],
674 vec![7u8; 11],
675 )
676 .await;
677 assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
678 let usage = state.store.service_usage("iz").await.unwrap();
679 assert_eq!(
680 (usage.objects, usage.used_bytes, usage.quota_bytes),
681 (0, 0, 10)
682 );
683 let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await;
684 assert_eq!(status, StatusCode::NOT_FOUND);
685 }
686
687 /// A replace keeps one row and reports 200. The old bytes are removed once no object names them, and
688 /// identical content from two ids shares one blob until the last of them is deleted.
689 #[tokio::test]
690 async fn a_replace_keeps_one_row_and_shared_bytes_outlive_one_object() {
691 let (_dir, state, der) = setup().await;
692 let iz = machine_token(&der, "iz", "files.service", "in");
693 let (status, _, _) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"first".to_vec()).await;
694 assert_eq!(status, StatusCode::CREATED);
695 let old_key = object_blob_key("iz", &sha_hex(b"first"));
696 let (status, _, body) =
697 call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"second!".to_vec()).await;
698 assert_eq!(status, StatusCode::OK);
699 assert_eq!(json_of(&body)["size"], 7);
700 assert_eq!(state.blobs.size(&old_key).await.unwrap(), None);
701 assert_eq!(state.store.service_usage("iz").await.unwrap().objects, 1);
702
703 // Two ids with the same bytes share one blob.
704 let (status, _, _) = call(
705 &state,
706 "PUT",
707 "/api/v1/objects/copy-a",
708 Some(&iz),
709 &[],
710 b"same".to_vec(),
711 )
712 .await;
713 assert_eq!(status, StatusCode::CREATED);
714 let (status, _, _) = call(
715 &state,
716 "PUT",
717 "/api/v1/objects/copy-b",
718 Some(&iz),
719 &[],
720 b"same".to_vec(),
721 )
722 .await;
723 assert_eq!(status, StatusCode::CREATED);
724 let shared = object_blob_key("iz", &sha_hex(b"same"));
725 let (status, _, _) = call(
726 &state,
727 "DELETE",
728 "/api/v1/objects/copy-a",
729 Some(&iz),
730 &[],
731 vec![],
732 )
733 .await;
734 assert_eq!(status, StatusCode::NO_CONTENT);
735 assert_eq!(state.blobs.size(&shared).await.unwrap(), Some(4));
736 let (status, _, body) = call(
737 &state,
738 "GET",
739 "/api/v1/objects/copy-b",
740 Some(&iz),
741 &[],
742 vec![],
743 )
744 .await;
745 assert_eq!(status, StatusCode::OK);
746 assert_eq!(body, b"same");
747 }
748
749 /// A GET answers the stored bytes as an attachment with the stored type and the sha256 as its ETag, and
750 /// honours one `Range`. `If-None-Match` with the same hash is `304`. A DELETE of an absent id is `204`.
751 #[tokio::test]
752 async fn get_serves_the_bytes_as_an_attachment_with_range() {
753 let (_dir, state, der) = setup().await;
754 let iz = machine_token(&der, "iz", "files.service", "in");
755 let (status, _, _) = call(
756 &state,
757 "PUT",
758 PUT_PATH,
759 Some(&iz),
760 &[
761 ("content-type", "text/plain"),
762 ("x-object-name", "notes%2Fa%20b.txt"),
763 ],
764 b"0123456789".to_vec(),
765 )
766 .await;
767 assert_eq!(status, StatusCode::CREATED);
768 let (status, headers, body) = call(
769 &state,
770 "GET",
771 PUT_PATH,
772 Some(&iz),
773 &[("range", "bytes=2-4")],
774 vec![],
775 )
776 .await;
777 assert_eq!(status, StatusCode::PARTIAL_CONTENT);
778 assert_eq!(body, b"234");
779 assert_eq!(
780 headers["content-disposition"]
781 .to_str()
782 .unwrap()
783 .split(';')
784 .next(),
785 Some("attachment")
786 );
787 assert_eq!(
788 headers["etag"],
789 format!("\"{}\"", sha_hex(b"0123456789")).as_str()
790 );
791 let etag = format!("\"{}\"", sha_hex(b"0123456789"));
792 let (status, _, _) = call(
793 &state,
794 "GET",
795 PUT_PATH,
796 Some(&iz),
797 &[("if-none-match", etag.as_str())],
798 vec![],
799 )
800 .await;
801 assert_eq!(status, StatusCode::NOT_MODIFIED);
802 let (status, _, _) = call(
803 &state,
804 "DELETE",
805 "/api/v1/objects/never-was",
806 Some(&iz),
807 &[],
808 vec![],
809 )
810 .await;
811 assert_eq!(status, StatusCode::NO_CONTENT);
812 }
813}