registry_testkit/
server.rs

1//! OCI-compliant registry server implementation.
2
3use crate::config::RegistryConfig;
4use crate::error::Result;
5use crate::storage::{create_storage, ManifestEntry, Storage};
6use axum::{
7    body::Bytes,
8    extract::{Path, Query, State},
9    http::{HeaderMap, StatusCode},
10    response::{IntoResponse, Json},
11    routing::{get, head, patch, post, put},
12    Router,
13};
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use std::net::SocketAddr;
17use std::sync::Arc;
18use tokio::net::TcpListener;
19use tower_http::trace::TraceLayer;
20use tracing::{debug, info, warn};
21
22fn strip_leading_slash(s: &str) -> &str {
23    s.strip_prefix('/').unwrap_or(s)
24}
25
26type SharedStorage = Arc<dyn Storage>;
27
28#[derive(Clone)]
29struct AppState {
30    storage: SharedStorage,
31}
32
33#[derive(Serialize)]
34struct ApiVersion {
35    version: String,
36}
37
38#[derive(Deserialize)]
39struct UploadParams {
40    digest: Option<String>,
41}
42
43/// The main registry server.
44///
45/// Implements an OCI-compliant container registry that can be used for
46/// testing Docker/container workflows.
47pub struct RegistryServer {
48    addr: SocketAddr,
49    _handle: tokio::task::JoinHandle<()>,
50}
51
52impl RegistryServer {
53    /// Creates and starts a new registry server with the given configuration.
54    ///
55    /// # Examples
56    ///
57    /// ```no_run
58    /// use registry_testkit::{RegistryServer, RegistryConfig};
59    ///
60    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
61    /// let config = RegistryConfig::memory();
62    /// let server = RegistryServer::new(config).await?;
63    /// # Ok(())
64    /// # }
65    /// ```
66    pub async fn new(config: RegistryConfig) -> Result<Self> {
67        let storage = create_storage(&config.storage).await?;
68
69        let state = AppState { storage };
70
71        let app = Router::new()
72            .route("/v2/", get(api_version))
73            .route("/v2/{name}/blobs/{digest}", head(check_blob))
74            .route("/v2/{name}/blobs/{digest}", get(get_blob))
75            .route("/v2/{name}/blobs/uploads/", post(start_upload))
76            .route("/v2/{name}/blobs/uploads/{uuid}", patch(upload_chunk))
77            .route("/v2/{name}/blobs/uploads/{uuid}", put(finish_upload))
78            .route("/v2/{name}/manifests/{reference}", put(put_manifest))
79            .route("/v2/{name}/manifests/{reference}", get(get_manifest))
80            .route("/v2/{name}/manifests/{reference}", head(check_manifest))
81            .layer(
82                tower::ServiceBuilder::new()
83                    .layer(axum::extract::DefaultBodyLimit::max(512 * 1024 * 1024))
84                    .layer(TraceLayer::new_for_http()),
85            )
86            .with_state(state);
87
88        let bind_addr = if let Some(port) = config.port {
89            format!("{}:{}", config.host, port)
90        } else {
91            format!("{}:0", config.host)
92        };
93
94        let listener = TcpListener::bind(&bind_addr).await?;
95        let addr = listener.local_addr()?;
96
97        info!("Registry listening on {}", addr);
98
99        let handle = tokio::spawn(async move {
100            axum::serve(listener, app).await.ok();
101        });
102
103        Ok(Self {
104            addr,
105            _handle: handle,
106        })
107    }
108
109    /// Returns the socket address the server is bound to.
110    pub fn addr(&self) -> SocketAddr {
111        self.addr
112    }
113
114    /// Returns the full URL of the registry server.
115    ///
116    /// # Examples
117    ///
118    /// ```no_run
119    /// # use registry_testkit::{RegistryServer, RegistryConfig};
120    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
121    /// # let server = RegistryServer::new(RegistryConfig::memory()).await?;
122    /// println!("Registry URL: {}", server.url());
123    /// # Ok(())
124    /// # }
125    /// ```
126    pub fn url(&self) -> String {
127        format!("http://{}", self.addr)
128    }
129
130    /// Returns the port number the server is listening on.
131    pub fn port(&self) -> u16 {
132        self.addr.port()
133    }
134}
135
136async fn api_version() -> Json<ApiVersion> {
137    Json(ApiVersion {
138        version: "registry/2.0".to_string(),
139    })
140}
141
142async fn check_blob(
143    State(state): State<AppState>,
144    Path((name, digest)): Path<(String, String)>,
145) -> impl IntoResponse {
146    let name = strip_leading_slash(&name);
147    info!("Checking blob: {}/{}", name, digest);
148
149    match state.storage.get_blob(&digest).await {
150        Ok(Some(blob)) => (StatusCode::OK, [("Content-Length", blob.len().to_string())]),
151        _ => (StatusCode::NOT_FOUND, [("Content-Length", "0".to_string())]),
152    }
153}
154
155async fn get_blob(
156    State(state): State<AppState>,
157    Path((name, digest)): Path<(String, String)>,
158) -> impl IntoResponse {
159    let name = strip_leading_slash(&name);
160    info!("Getting blob: {}/{}", name, digest);
161
162    match state.storage.get_blob(&digest).await {
163        Ok(Some(blob)) => (StatusCode::OK, blob),
164        _ => (StatusCode::NOT_FOUND, vec![]),
165    }
166}
167
168async fn start_upload(
169    Path(name): Path<String>,
170    State(state): State<AppState>,
171) -> impl IntoResponse {
172    let name = strip_leading_slash(&name);
173    let uuid = uuid::Uuid::new_v4().to_string();
174    info!("Starting upload: {} ({})", name, uuid);
175
176    if let Err(e) = state.storage.create_upload(uuid.clone()).await {
177        warn!("Failed to create upload: {}", e);
178        return (
179            StatusCode::INTERNAL_SERVER_ERROR,
180            [("Location", String::new())],
181        );
182    }
183
184    (
185        StatusCode::ACCEPTED,
186        [("Location", format!("/v2/{}/blobs/uploads/{}", name, uuid))],
187    )
188}
189
190async fn upload_chunk(
191    State(state): State<AppState>,
192    Path((name, uuid)): Path<(String, String)>,
193    body: Bytes,
194) -> impl IntoResponse {
195    let name = strip_leading_slash(&name);
196    debug!("Uploading chunk: {}/{} ({} bytes)", name, uuid, body.len());
197
198    match state.storage.append_upload(&uuid, &body).await {
199        Ok(_) => {
200            let end = body.len().saturating_sub(1);
201            (
202                StatusCode::ACCEPTED,
203                [
204                    ("Location", format!("/v2/{}/blobs/uploads/{}", name, uuid)),
205                    ("Range", format!("0-{}", end)),
206                    ("Docker-Upload-UUID", uuid),
207                ],
208            )
209        }
210        Err(_) => {
211            warn!("Upload not found: {}", uuid);
212            (
213                StatusCode::NOT_FOUND,
214                [
215                    ("Location", String::new()),
216                    ("Range", String::new()),
217                    ("Docker-Upload-UUID", String::new()),
218                ],
219            )
220        }
221    }
222}
223
224async fn finish_upload(
225    State(state): State<AppState>,
226    Path((name, uuid)): Path<(String, String)>,
227    Query(params): Query<UploadParams>,
228    headers: HeaderMap,
229    body: Bytes,
230) -> impl IntoResponse {
231    let name = strip_leading_slash(&name);
232    debug!("Finishing upload: {}/{}", name, uuid);
233
234    let upload_data = match state.storage.finish_upload(&uuid).await {
235        Ok(Some(mut data)) => {
236            data.extend_from_slice(&body);
237            data
238        }
239        _ => {
240            warn!("Upload not found: {}", uuid);
241            return (
242                StatusCode::NOT_FOUND,
243                [
244                    ("Location", String::new()),
245                    ("Docker-Content-Digest", String::new()),
246                ],
247            );
248        }
249    };
250
251    let digest_str = params
252        .digest
253        .or_else(|| {
254            headers
255                .get("digest")
256                .or_else(|| headers.get("Docker-Content-Digest"))
257                .and_then(|v| v.to_str().ok())
258                .map(|s| s.to_string())
259        })
260        .unwrap_or_else(|| {
261            let mut hasher = Sha256::new();
262            hasher.update(&upload_data);
263            format!("sha256:{}", hex::encode(hasher.finalize()))
264        });
265
266    if let Err(e) = state
267        .storage
268        .store_blob(digest_str.clone(), upload_data)
269        .await
270    {
271        warn!("Failed to store blob: {}", e);
272        return (
273            StatusCode::INTERNAL_SERVER_ERROR,
274            [
275                ("Location", String::new()),
276                ("Docker-Content-Digest", String::new()),
277            ],
278        );
279    }
280
281    info!("Stored blob: {}", digest_str);
282
283    (
284        StatusCode::CREATED,
285        [
286            ("Location", format!("/v2/{}/blobs/{}", name, digest_str)),
287            ("Docker-Content-Digest", digest_str),
288        ],
289    )
290}
291
292async fn put_manifest(
293    State(state): State<AppState>,
294    Path((name, reference)): Path<(String, String)>,
295    headers: HeaderMap,
296    body: Bytes,
297) -> impl IntoResponse {
298    let name = strip_leading_slash(&name);
299    info!("Putting manifest: {}/{}", name, reference);
300
301    let content_type = headers
302        .get("content-type")
303        .and_then(|v| v.to_str().ok())
304        .unwrap_or("application/vnd.docker.distribution.manifest.v2+json")
305        .to_string();
306
307    let mut hasher = Sha256::new();
308    hasher.update(&body);
309    let digest = format!("sha256:{}", hex::encode(hasher.finalize()));
310
311    let entry = ManifestEntry {
312        data: body.to_vec(),
313        content_type: content_type.clone(),
314    };
315
316    let key = format!("{}:{}", name, reference);
317    let digest_key = format!("{}:{}", name, digest);
318
319    if let Err(e) = state.storage.store_manifest(key, entry.clone()).await {
320        warn!("Failed to store manifest: {}", e);
321        return (
322            StatusCode::INTERNAL_SERVER_ERROR,
323            [
324                ("Location", String::new()),
325                ("Content-Type", String::new()),
326                ("Docker-Content-Digest", String::new()),
327            ],
328        );
329    }
330
331    if let Err(e) = state.storage.store_manifest(digest_key, entry).await {
332        warn!("Failed to store manifest by digest: {}", e);
333    }
334
335    info!(
336        "Stored manifest with digest: {} (type: {})",
337        digest, content_type
338    );
339
340    (
341        StatusCode::CREATED,
342        [
343            ("Location", format!("/v2/{}/manifests/{}", name, reference)),
344            ("Content-Type", content_type),
345            ("Docker-Content-Digest", digest),
346        ],
347    )
348}
349
350async fn get_manifest(
351    State(state): State<AppState>,
352    Path((name, reference)): Path<(String, String)>,
353) -> impl IntoResponse {
354    let name = strip_leading_slash(&name);
355    info!("Getting manifest: {}/{}", name, reference);
356
357    let key = format!("{}:{}", name, reference);
358
359    match state.storage.get_manifest(&key).await {
360        Ok(Some(entry)) => (
361            StatusCode::OK,
362            [("Content-Type", entry.content_type)],
363            entry.data,
364        ),
365        _ => (
366            StatusCode::NOT_FOUND,
367            [("Content-Type", "text/plain".to_string())],
368            vec![],
369        ),
370    }
371}
372
373async fn check_manifest(
374    State(state): State<AppState>,
375    Path((name, reference)): Path<(String, String)>,
376) -> impl IntoResponse {
377    let name = strip_leading_slash(&name);
378    info!("Checking manifest: {}/{}", name, reference);
379
380    let key = format!("{}:{}", name, reference);
381
382    match state.storage.get_manifest(&key).await {
383        Ok(Some(entry)) => {
384            let mut hasher = Sha256::new();
385            hasher.update(&entry.data);
386            let digest = format!("sha256:{}", hex::encode(hasher.finalize()));
387
388            (
389                StatusCode::OK,
390                [
391                    ("Content-Type", entry.content_type),
392                    ("Docker-Content-Digest", digest),
393                ],
394            )
395        }
396        _ => (
397            StatusCode::NOT_FOUND,
398            [
399                ("Content-Type", "text/plain".to_string()),
400                ("Docker-Content-Digest", String::new()),
401            ],
402        ),
403    }
404}