forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

blobs.rs458 lines, 15.2 KiBHistoryRawDownload
1//! Blobs of the container registry: upload sessions, the digest check, the blob store writes, and
2//! the blob reads.
3//!
4//! An upload session is a temp file under `<data_dir>/oci/uploads`, named by a ULID, with a
5//! sidecar `<id>.repo` that names the repository it belongs to. Chunks are appended to it. When
6//! the client finishes, the file's sha256 must match the digest it names; then the bytes move into
7//! the blob store under `oci/<hex>`, shared by every package that links the digest. A session that
8//! is never finished is removed once it is a day old; the check runs when a new session starts, so
9//! no timer is needed.
10
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime};
13
14use forge_core::oci as rules;
15use forge_core::packages::{KIND_OCI, Package};
16use futures_util::StreamExt;
17use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
18use http_body::Frame;
19use http_body_util::StreamBody;
20use sha2::{Digest, Sha256};
21use tokio::io::{AsyncReadExt, AsyncWriteExt};
22use topcoat::router::response::Response;
23use topcoat::router::{Body, StatusCode};
24
25use super::auth::{self, Caller, Target, internal, internal_refusal};
26use super::{gc, oci_error};
27use crate::api::Refusal;
28use crate::state::AppState;
29
30/// Largest blob accepted, in bytes.
31pub const MAX_BLOB_BYTES: u64 = 10 * 1024 * 1024 * 1024;
32/// Bytes read from a temp file at a time.
33const CHUNK: usize = 1024 * 1024;
34/// How long an unfinished upload is kept.
35const SESSION_TTL: Duration = Duration::from_secs(24 * 60 * 60);
36
37/// The directory of upload sessions: `<data_dir>/oci/uploads`.
38pub fn uploads_dir(data_dir: &Path) -> PathBuf {
39 data_dir.join("oci").join("uploads")
40}
41
42/// The blob store key of a digest's bytes.
43pub fn blob_key(hex: &str) -> String {
44 format!("oci/{hex}")
45}
46
47/// A session id as this module makes them: 26 ASCII letters or digits. Anything else is not a
48/// session, so no id can name a path outside the uploads directory.
49pub fn valid_session_id(id: &str) -> bool {
50 id.len() == 26 && id.bytes().all(|b| b.is_ascii_alphanumeric())
51}
52
53fn session_path(dir: &Path, id: &str) -> PathBuf {
54 dir.join(id)
55}
56
57fn sidecar_path(dir: &Path, id: &str) -> PathBuf {
58 dir.join(format!("{id}.repo"))
59}
60
61/// Starts a session for `name`, after removing sessions that were left unfinished for a day.
62pub async fn new_session(data_dir: &Path, name: &str) -> std::io::Result<String> {
63 let dir = uploads_dir(data_dir);
64 tokio::fs::create_dir_all(&dir).await?;
65 remove_stale(&dir).await;
66 let id = ulid::Ulid::generate().to_string();
67 tokio::fs::File::create_new(session_path(&dir, &id)).await?;
68 tokio::fs::write(sidecar_path(&dir, &id), name).await?;
69 Ok(id)
70}
71
72/// Removes every session whose file has not changed for [`SESSION_TTL`]. Failures are ignored: a
73/// session that cannot be removed now is tried again at the next start.
74async fn remove_stale(dir: &Path) {
75 let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
76 return;
77 };
78 let now = SystemTime::now();
79 while let Ok(Some(entry)) = entries.next_entry().await {
80 let path = entry.path();
81 if path.extension().is_some_and(|ext| ext == "repo") {
82 continue;
83 }
84 let Ok(meta) = entry.metadata().await else {
85 continue;
86 };
87 let age = meta
88 .modified()
89 .ok()
90 .and_then(|at| now.duration_since(at).ok());
91 if age.is_some_and(|age| age > SESSION_TTL) {
92 if let Some(id) = path.file_name().and_then(|n| n.to_str()) {
93 let _ = tokio::fs::remove_file(sidecar_path(dir, id)).await;
94 }
95 let _ = tokio::fs::remove_file(&path).await;
96 }
97 }
98}
99
100/// True when session `id` exists and belongs to repository `name`.
101pub async fn session_belongs_to(data_dir: &Path, id: &str, name: &str) -> bool {
102 if !valid_session_id(id) {
103 return false;
104 }
105 let dir = uploads_dir(data_dir);
106 match tokio::fs::read_to_string(sidecar_path(&dir, id)).await {
107 Ok(owner) => owner == name && tokio::fs::metadata(session_path(&dir, id)).await.is_ok(),
108 Err(_) => false,
109 }
110}
111
112/// Removes a session's files, once it is finished or cancelled.
113pub async fn remove_session(data_dir: &Path, id: &str) {
114 let dir = uploads_dir(data_dir);
115 let _ = tokio::fs::remove_file(sidecar_path(&dir, id)).await;
116 let _ = tokio::fs::remove_file(session_path(&dir, id)).await;
117}
118
119/// The size of a session file so far.
120pub async fn session_size(data_dir: &Path, id: &str) -> std::io::Result<u64> {
121 let meta = tokio::fs::metadata(session_path(&uploads_dir(data_dir), id)).await?;
122 Ok(meta.len())
123}
124
125/// Appends the request body to a session. `expected_start` is the offset a `Content-Range` names,
126/// when the client sent one; a mismatch is refused without writing. Returns the new size.
127pub async fn append(
128 data_dir: &Path,
129 id: &str,
130 body: Body,
131 expected_start: Option<u64>,
132) -> Result<u64, Box<Response>> {
133 let path = session_path(&uploads_dir(data_dir), id);
134 let mut file = tokio::fs::OpenOptions::new()
135 .append(true)
136 .open(&path)
137 .await
138 .map_err(|e| Box::new(internal(e)))?;
139 let size = file
140 .metadata()
141 .await
142 .map_err(|e| Box::new(internal(e)))?
143 .len();
144 if expected_start.is_some_and(|start| start != size) {
145 return Err(Box::new(range_not_satisfiable(size)));
146 }
147 let mut written = size;
148 let mut stream = std::pin::pin!(body.into_data_stream());
149 while let Some(chunk) = stream.next().await {
150 let Ok(chunk) = chunk else {
151 return Err(Box::new(oci_error(
152 StatusCode::BAD_REQUEST,
153 "BLOB_UPLOAD_INVALID",
154 "the request body could not be read",
155 )));
156 };
157 written = written.saturating_add(chunk.len() as u64);
158 if written > MAX_BLOB_BYTES {
159 return Err(Box::new(oci_error(
160 StatusCode::PAYLOAD_TOO_LARGE,
161 "SIZE_INVALID",
162 "the blob is larger than the registry accepts",
163 )));
164 }
165 file.write_all(&chunk)
166 .await
167 .map_err(|e| Box::new(internal(e)))?;
168 }
169 file.flush().await.map_err(|e| Box::new(internal(e)))?;
170 Ok(written)
171}
172
173/// The sha256 of a file, hex.
174pub async fn file_sha256(path: &Path) -> std::io::Result<String> {
175 let mut file = tokio::fs::File::open(path).await?;
176 let mut hasher = Sha256::new();
177 let mut buf = vec![0u8; CHUNK];
178 loop {
179 let read = file.read(&mut buf).await?;
180 if read == 0 {
181 break;
182 }
183 hasher.update(&buf[..read]);
184 }
185 Ok(hex::encode(hasher.finalize()))
186}
187
188/// Links `digest` to `package` once its bytes are in the blob store. Holds the garbage collection
189/// lock, so a sweep cannot remove bytes between the check and the link.
190pub async fn link(
191 state: &AppState,
192 package: &Package,
193 hex: &str,
194 size: u64,
195 source: Option<&Path>,
196) -> Result<(), Refusal> {
197 let _gc = gc::lock().await;
198 let key = blob_key(hex);
199 let exists = state.blobs.exists(&key).await.map_err(internal_refusal)?;
200 if !exists {
201 let Some(source) = source else {
202 return Err(Box::new(oci_error(
203 StatusCode::NOT_FOUND,
204 "BLOB_UNKNOWN",
205 "blob unknown to registry",
206 )));
207 };
208 copy_into_store(state, &key, source).await?;
209 }
210 state
211 .store
212 .oci_link_blob(&package.id, &format!("sha256:{hex}"), size)
213 .await
214 .map_err(internal_refusal)
215}
216
217async fn copy_into_store(state: &AppState, key: &str, source: &Path) -> Result<(), Refusal> {
218 let mut file = tokio::fs::File::open(source)
219 .await
220 .map_err(internal_refusal)?;
221 let mut writer = state
222 .blobs
223 .begin(key, MAX_BLOB_BYTES)
224 .await
225 .map_err(internal_refusal)?;
226 let mut buf = vec![0u8; CHUNK];
227 loop {
228 let read = match file.read(&mut buf).await {
229 Ok(read) => read,
230 Err(e) => {
231 writer.abort().await;
232 return Err(internal_refusal(e));
233 }
234 };
235 if read == 0 {
236 break;
237 }
238 if let Err(e) = writer.push(&buf[..read]).await {
239 writer.abort().await;
240 return Err(internal_refusal(e));
241 }
242 }
243 writer.finish().await.map_err(internal_refusal)?;
244 Ok(())
245}
246
247/// The response that closes an upload with its blob's location.
248pub fn created(name: &str, hex: &str) -> Response {
249 let digest = format!("sha256:{hex}");
250 let mut res = Response::new(Body::empty());
251 *res.status_mut() = StatusCode::CREATED;
252 insert(&mut res, "location", &format!("/v2/{name}/blobs/{digest}"));
253 insert(&mut res, "docker-content-digest", &digest);
254 res
255}
256
257/// A 202 for an upload still open, with the bytes received so far.
258pub fn upload_progress(name: &str, id: &str, size: u64) -> Response {
259 let mut res = Response::new(Body::empty());
260 *res.status_mut() = StatusCode::ACCEPTED;
261 insert(
262 &mut res,
263 "location",
264 &format!("/v2/{name}/blobs/uploads/{id}"),
265 );
266 insert(&mut res, "docker-upload-uuid", id);
267 insert(&mut res, "range", &range_of(size));
268 res
269}
270
271/// The `Range` a registry answers with: the bytes received, `0-n`, or `0-0` when none.
272pub fn range_of(size: u64) -> String {
273 format!("0-{}", size.saturating_sub(1))
274}
275
276fn range_not_satisfiable(size: u64) -> Response {
277 let mut res = oci_error(
278 StatusCode::RANGE_NOT_SATISFIABLE,
279 "BLOB_UPLOAD_INVALID",
280 "the chunk does not start where the upload ends",
281 );
282 insert(&mut res, "range", &range_of(size));
283 res
284}
285
286/// Sets a header from a string value. A value that is not a valid header is left out.
287pub fn insert(res: &mut Response, name: &'static str, value: &str) {
288 if let Ok(value) = HeaderValue::from_str(value) {
289 res.headers_mut()
290 .insert(http::HeaderName::from_static(name), value);
291 }
292}
293
294/// A blob GET or HEAD. The blob must be linked to the package the caller may read.
295pub async fn get_blob(
296 state: &AppState,
297 caller: &Caller,
298 name: &str,
299 digest: &str,
300 head: bool,
301) -> Response {
302 let target = match auth::authorize(state, caller, name, false).await {
303 Ok(target) => target,
304 Err(res) => return *res,
305 };
306 let Some(hex) = rules::parse_digest(digest) else {
307 return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest");
308 };
309 let Some(package) = target.package.as_ref() else {
310 return unknown_blob();
311 };
312 let size = match state.store.oci_blob_size(&package.id, digest).await {
313 Ok(Some(size)) => size,
314 Ok(None) => return unknown_blob(),
315 Err(e) => return internal(e),
316 };
317 let mut res = Response::new(Body::empty());
318 *res.status_mut() = StatusCode::OK;
319 insert(&mut res, "docker-content-digest", digest);
320 res.headers_mut().insert(
321 CONTENT_TYPE,
322 HeaderValue::from_static("application/octet-stream"),
323 );
324 res.headers_mut()
325 .insert(CONTENT_LENGTH, HeaderValue::from(size));
326 if head {
327 return res;
328 }
329 match state.blobs.read(&blob_key(hex)).await {
330 Ok(Some(read)) => {
331 let chunks = read.stream.map(|chunk| chunk.map(Frame::data));
332 *res.body_mut() = Body::new(StreamBody::new(chunks));
333 res
334 }
335 // Linked but missing from the store: the store is damaged, not the request.
336 Ok(None) => internal("a linked blob is missing from the blob store"),
337 Err(e) => internal(e),
338 }
339}
340
341fn unknown_blob() -> Response {
342 oci_error(
343 StatusCode::NOT_FOUND,
344 "BLOB_UNKNOWN",
345 "blob unknown to registry",
346 )
347}
348
349/// Unlinks a blob from the repository. A blob a manifest of the repo still names is kept, so no
350/// image breaks; the caller deletes the manifest first. Bytes no package links are removed.
351pub async fn delete_blob(state: &AppState, target: &Target, digest: &str) -> Response {
352 let Some(hex) = rules::parse_digest(digest) else {
353 return oci_error(StatusCode::BAD_REQUEST, "DIGEST_INVALID", "invalid digest");
354 };
355 let Some(package) = target.package.as_ref() else {
356 return unknown_blob();
357 };
358 match state.store.oci_blob_size(&package.id, digest).await {
359 Ok(Some(_)) => {}
360 Ok(None) => return unknown_blob(),
361 Err(e) => return internal(e),
362 }
363 match state.store.oci_digest_referenced(&package.id, digest).await {
364 Ok(true) => {
365 return oci_error(
366 StatusCode::BAD_REQUEST,
367 "UNSUPPORTED",
368 "a manifest still uses this blob; delete the manifest first",
369 );
370 }
371 Ok(false) => {}
372 Err(e) => return internal(e),
373 }
374 let _gc = gc::lock().await;
375 if let Err(e) = state.store.oci_unlink_blob(&package.id, digest).await {
376 return internal(e);
377 }
378 match state.store.oci_digest_linked(digest).await {
379 Ok(false) => {
380 if let Err(e) = state.blobs.delete(&blob_key(hex)).await {
381 return internal(e);
382 }
383 }
384 Ok(true) => {}
385 Err(e) => return internal(e),
386 }
387 let mut res = Response::new(Body::empty());
388 *res.status_mut() = StatusCode::ACCEPTED;
389 res
390}
391
392/// The package a write goes to, created on first use.
393pub async fn write_package(state: &AppState, target: &Target) -> Result<Package, Refusal> {
394 if let Some(package) = target.package.as_ref() {
395 return Ok(package.clone());
396 }
397 state
398 .store
399 .ensure_package(&target.owner.id, KIND_OCI, &target.image, &target.image)
400 .await
401 .map_err(internal_refusal)
402}
403
404/// Mounts `digest` from repository `from` into the target when the caller may read `from` and
405/// the blob is there. Returns false when the mount is not possible, so the caller starts an upload.
406pub async fn try_mount(
407 state: &AppState,
408 caller: &Caller,
409 target: &Target,
410 digest: &str,
411 from: &str,
412) -> Result<bool, Refusal> {
413 let Some(hex) = rules::parse_digest(digest) else {
414 return Ok(false);
415 };
416 let Ok(source) = auth::authorize(state, caller, from, false).await else {
417 return Ok(false);
418 };
419 let Some(source_package) = source.package.as_ref() else {
420 return Ok(false);
421 };
422 let Some(size) = state
423 .store
424 .oci_blob_size(&source_package.id, digest)
425 .await
426 .map_err(internal_refusal)?
427 else {
428 return Ok(false);
429 };
430 if !state
431 .blobs
432 .exists(&blob_key(hex))
433 .await
434 .map_err(internal_refusal)?
435 {
436 return Ok(false);
437 }
438 let package = write_package(state, target).await?;
439 link(state, &package, hex, size, None).await?;
440 Ok(true)
441}
442
443/// Reads the digest a request names, or the 400 when it is malformed.
444pub fn digest_arg(digest: &str) -> Result<&str, Box<Response>> {
445 rules::parse_digest(digest).ok_or_else(|| {
446 Box::new(oci_error(
447 StatusCode::BAD_REQUEST,
448 "DIGEST_INVALID",
449 "invalid digest",
450 ))
451 })
452}
453
454/// The offset a `Content-Range` header starts at, when the client sent one.
455pub fn content_range_start(headers: &http::HeaderMap) -> Option<u64> {
456 let value = headers.get("content-range")?.to_str().ok()?;
457 value.split('-').next()?.trim().parse().ok()
458}