oci-core 0.1.0

Lightweight OCI registry primitives extracted from docker-image-pusher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};

use bytes::Bytes;
use futures::stream::StreamExt;
use reqwest::header::CONTENT_LENGTH;
use reqwest::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderValue, LOCATION, WWW_AUTHENTICATE};
use reqwest::{Method, StatusCode, Url};
use serde_json::Value;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::Mutex;

use crate::auth::RegistryAuth;
use crate::errors::OciError;
use crate::manifest::{OciDescriptor, OciImageManifest};
use crate::reference::Reference;

const MANIFEST_MEDIA_TYPE: &str = "application/vnd.docker.distribution.manifest.v2+json";
const OCTET_STREAM: &str = "application/octet-stream";
const OCI_CHUNK_MIN_LENGTH: &str = "OCI-Chunk-Min-Length";

#[derive(Clone, Default)]
pub struct ClientConfig {
    pub user_agent: Option<String>,
}

fn env_flag(name: &str) -> bool {
    std::env::var(name)
        .map(|value| {
            let value = value.trim();
            !(value.is_empty()
                || value == "0"
                || value.eq_ignore_ascii_case("false")
                || value.eq_ignore_ascii_case("off"))
        })
        .unwrap_or(false)
}

fn oci_debug_enabled() -> bool {
    static FLAG: OnceLock<bool> = OnceLock::new();
    *FLAG.get_or_init(|| env_flag("OCI_DEBUG"))
}

fn upload_debug_enabled() -> bool {
    static FLAG: OnceLock<bool> = OnceLock::new();
    *FLAG.get_or_init(|| env_flag("OCI_DEBUG_UPLOAD") || oci_debug_enabled())
}

fn log_debug<F>(message: F)
where
    F: FnOnce() -> String,
{
    if oci_debug_enabled() {
        println!("[OCI] {}", message());
    }
}

#[derive(Clone)]
pub struct Client {
    http: reqwest::Client,
    _config: ClientConfig,
    tokens: Arc<Mutex<HashMap<String, String>>>,
}

impl Client {
    pub fn new(config: ClientConfig) -> Self {
        let builder = reqwest::Client::builder().user_agent(
            config
                .user_agent
                .clone()
                .unwrap_or_else(|| "docker-image-pusher/0.0".to_string()),
        );
        let http = builder.build().expect("Failed to build client");
        Self {
            http,
            _config: config,
            tokens: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    fn base_url(reference: &Reference) -> Result<Url, OciError> {
        let url = format!("https://{}/v2/{}", reference.registry, reference.repository);
        Url::parse(&url).map_err(|e| OciError::Reference(format!("Invalid URL: {}", e)))
    }

    fn pull_scope(reference: &Reference) -> String {
        format!("repository:{}:pull", reference.repository)
    }

    fn push_scope(reference: &Reference) -> String {
        format!("repository:{}:push,pull", reference.repository)
    }

    async fn get_cached_token(&self, scope: &str) -> Option<String> {
        let guard = self.tokens.lock().await;
        guard.get(scope).cloned()
    }

    async fn store_token(&self, scope: &str, token: &str) {
        let mut guard = self.tokens.lock().await;
        guard.insert(scope.to_string(), token.to_string());
    }

    fn parse_bearer_challenge(value: &str) -> Result<(String, HashMap<String, String>), OciError> {
        let mut parts = value.splitn(2, ' ');
        let scheme = parts.next().unwrap_or("").trim().to_owned();
        let remainder = parts.next().unwrap_or("").trim();
        let mut params = HashMap::new();
        for segment in remainder.split(',') {
            let segment = segment.trim();
            if segment.is_empty() {
                continue;
            }
            if let Some((k, v)) = segment.split_once('=') {
                let key = k.trim().to_ascii_lowercase();
                let value = v.trim().trim_matches('"').to_string();
                params.insert(key, value);
            }
        }
        Ok((scheme.to_ascii_lowercase(), params))
    }

    async fn fetch_bearer_token(
        &self,
        challenge: &str,
        scope: &str,
        auth: &RegistryAuth,
    ) -> Result<String, OciError> {
        let (scheme, params) = Self::parse_bearer_challenge(challenge)?;
        if scheme != "bearer" {
            return Err(OciError::Auth(format!(
                "Unsupported auth scheme: {}",
                scheme
            )));
        }

        let realm = params
            .get("realm")
            .ok_or_else(|| OciError::Auth("Missing realm in auth challenge".to_string()))?;
        let mut url = Url::parse(realm)
            .map_err(|e| OciError::Auth(format!("Invalid auth realm URL: {}", e)))?;
        {
            let mut pairs = url.query_pairs_mut();
            if let Some(service) = params.get("service") {
                pairs.append_pair("service", service);
            }
            let scope_value = if scope.is_empty() {
                params.get("scope").cloned()
            } else {
                Some(scope.to_string())
            };
            if let Some(value) = scope_value {
                pairs.append_pair("scope", &value);
            }
        }

        let mut req = self.http.get(url);
        req = auth.apply(req);
        let resp = req.send().await?;
        if !resp.status().is_success() {
            return Err(OciError::Auth(format!(
                "Failed to obtain bearer token: {}",
                resp.status()
            )));
        }
        let payload: Value = resp
            .json()
            .await
            .map_err(|e| OciError::Auth(e.to_string()))?;
        let token = payload
            .get("token")
            .or_else(|| payload.get("access_token"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| OciError::Auth("Bearer token missing in response".to_string()))?;
        Ok(token.to_string())
    }

    async fn request(
        &self,
        method: Method,
        url: Url,
        auth: &RegistryAuth,
        headers: Option<HeaderMap>,
        body: Option<Bytes>,
        scope: Option<String>,
    ) -> Result<reqwest::Response, OciError> {
        let headers_clone = headers.clone();
        let body_clone = body.clone();
        let scope_clone = scope.clone();

        let mut req = self.http.request(method.clone(), url.clone());
        if let Some(ref hdrs) = headers_clone {
            req = req.headers(hdrs.clone());
        }

        if let Some(ref scope_value) = scope_clone {
            if let Some(token) = self.get_cached_token(scope_value).await {
                req = req.bearer_auth(token);
            } else {
                req = auth.apply(req);
            }
        } else {
            req = auth.apply(req);
        }

        if let Some(ref body_value) = body_clone {
            req = req.body(body_value.clone());
        }
        let body_len = body_clone.as_ref().map(|b| b.len()).unwrap_or(0);
        log_debug(|| {
            let scope_label = scope_clone.as_deref().unwrap_or("-");
            format!(
                "➡️  {} {} scope={} bytes={}",
                method, url, scope_label, body_len
            )
        });
        let resp = req.send().await?;
        log_debug(|| format!("⬅️  {} {}", resp.status(), resp.url()));
        if resp.status() != StatusCode::UNAUTHORIZED {
            return Ok(resp);
        }

        let scope_value = match scope {
            Some(value) => value,
            None => return Ok(resp),
        };

        let challenge = resp
            .headers()
            .get(WWW_AUTHENTICATE)
            .and_then(|v| v.to_str().ok())
            .ok_or_else(|| OciError::Auth("Registry returned 401 without challenge".to_string()))?
            .to_string();

        log_debug(|| format!("🔐 Fetching bearer token for scope {}", scope_value));
        let token = self
            .fetch_bearer_token(&challenge, &scope_value, auth)
            .await?;
        self.store_token(&scope_value, &token).await;
        log_debug(|| "🔐 Bearer token obtained".to_string());

        let mut retry_req = self.http.request(method, url);
        if let Some(hdrs) = headers_clone {
            retry_req = retry_req.headers(hdrs);
        }
        if let Some(body_value) = body_clone {
            retry_req = retry_req.body(body_value);
        }
        log_debug(|| "↻ Retrying request with bearer token".to_string());
        let resp = retry_req.bearer_auth(token).send().await?;
        log_debug(|| format!("⬅️  {} {}", resp.status(), resp.url()));
        Ok(resp)
    }

    fn manifest_accept_header() -> HeaderValue {
        HeaderValue::from_static(MANIFEST_MEDIA_TYPE)
    }

    fn resolve_upload_url(base: &Url, location: Option<&HeaderValue>) -> Result<Url, OciError> {
        let location = location
            .ok_or_else(|| OciError::InvalidResponse("Missing upload location".to_string()))?
            .to_str()
            .map_err(|_| OciError::InvalidResponse("Invalid upload location header".to_string()))?;
        if location.starts_with("http://") || location.starts_with("https://") {
            Url::parse(location)
                .map_err(|e| OciError::InvalidResponse(format!("Invalid upload URL: {}", e)))
        } else {
            base.join(location).map_err(|e| {
                OciError::InvalidResponse(format!("Failed to resolve upload URL: {}", e))
            })
        }
    }

    fn parse_chunk_hint(headers: &HeaderMap) -> Option<usize> {
        headers
            .get(OCI_CHUNK_MIN_LENGTH)
            .and_then(|value| value.to_str().ok())
            .and_then(|raw| raw.trim().parse::<u64>().ok())
            .and_then(|value| {
                if value > usize::MAX as u64 {
                    None
                } else {
                    Some(value as usize)
                }
            })
    }

    async fn begin_upload(
        &self,
        reference: &Reference,
        auth: &RegistryAuth,
    ) -> Result<(Url, Option<usize>), OciError> {
        let mut url = Self::base_url(reference)?;
        url.path_segments_mut()
            .map_err(|_| OciError::Reference("Invalid repository path".to_string()))?
            .push("blobs")
            .push("uploads")
            .push("");
        let scope = Self::push_scope(reference);
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
        let resp = self
            .request(
                Method::POST,
                url.clone(),
                auth,
                Some(headers),
                None,
                Some(scope),
            )
            .await?;
        if resp.status() != StatusCode::ACCEPTED {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        let chunk_hint = Self::parse_chunk_hint(resp.headers());
        let resolved = Self::resolve_upload_url(resp.url(), resp.headers().get(LOCATION))?;
        Ok((resolved, chunk_hint))
    }

    pub async fn pull_image_manifest(
        &self,
        reference: &Reference,
        auth: &RegistryAuth,
    ) -> Result<(OciImageManifest, Option<String>), OciError> {
        let tag = reference
            .tag
            .as_ref()
            .ok_or_else(|| OciError::Reference("Cannot pull manifest without tag".to_string()))?;
        let mut url = Self::base_url(reference)?;
        url.path_segments_mut()
            .map_err(|_| OciError::Reference("Invalid repository path".to_string()))?
            .push("manifests")
            .push(tag);

        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT, Self::manifest_accept_header());

        let scope = Self::pull_scope(reference);
        let resp = self
            .request(Method::GET, url, auth, Some(headers), None, Some(scope))
            .await?;
        if !resp.status().is_success() {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        let digest = resp
            .headers()
            .get("Docker-Content-Digest")
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());
        let manifest = resp.json::<OciImageManifest>().await?;
        Ok((manifest, digest))
    }

    pub async fn pull_blob<W: AsyncWrite + Unpin + Send>(
        &self,
        reference: &Reference,
        descriptor: &OciDescriptor,
        auth: &RegistryAuth,
        writer: &mut W,
    ) -> Result<(), OciError> {
        let mut url = Self::base_url(reference)?;
        url.path_segments_mut()
            .map_err(|_| OciError::Reference("Invalid repository path".to_string()))?
            .push("blobs")
            .push(&descriptor.digest);

        let scope = Self::pull_scope(reference);
        let resp = self
            .request(Method::GET, url, auth, None, None, Some(scope))
            .await?;
        if !resp.status().is_success() {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }

        let mut stream = resp.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let data = chunk?;
            writer.write_all(&data).await?;
        }
        Ok(())
    }

    pub async fn blob_exists(
        &self,
        reference: &Reference,
        digest: &str,
        auth: &RegistryAuth,
    ) -> Result<bool, OciError> {
        let mut url = Self::base_url(reference)?;
        url.path_segments_mut()
            .map_err(|_| OciError::Reference("Invalid repository path".to_string()))?
            .push("blobs")
            .push(digest);
        let scope = Self::pull_scope(reference);
        let resp = self
            .request(Method::HEAD, url, auth, None, None, Some(scope))
            .await?;
        match resp.status() {
            StatusCode::OK => Ok(true),
            StatusCode::NOT_FOUND => Ok(false),
            status => Err(OciError::Status {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            }),
        }
    }

    pub async fn push_blob(
        &self,
        reference: &Reference,
        auth: &RegistryAuth,
        data: &[u8],
        digest: &str,
    ) -> Result<(), OciError> {
        let (mut upload_url, _) = self.begin_upload(reference, auth).await?;
        let scope = Self::push_scope(reference);

        if upload_debug_enabled() {
            println!("   🔗 Upload session started at {}", upload_url);
        }

        if !data.is_empty() {
            let mut headers = HeaderMap::new();
            headers.insert(CONTENT_TYPE, HeaderValue::from_static(OCTET_STREAM));
            headers.insert(
                CONTENT_LENGTH,
                HeaderValue::from_str(&data.len().to_string()).map_err(|_| {
                    OciError::InvalidResponse("Failed to encode content length".to_string())
                })?,
            );
            let resp = self
                .request(
                    Method::PATCH,
                    upload_url.clone(),
                    auth,
                    Some(headers),
                    Some(Bytes::copy_from_slice(data)),
                    Some(scope.clone()),
                )
                .await?;
            if resp.status() != StatusCode::ACCEPTED {
                return Err(OciError::Status {
                    status: resp.status().as_u16(),
                    message: resp.text().await.unwrap_or_default(),
                });
            }
            if let Some(next) = resp.headers().get(LOCATION) {
                if upload_debug_enabled() {
                    if let Ok(loc) = next.to_str() {
                        println!("   ↪️  Upload redirected to {}", loc);
                    }
                }
                upload_url = Self::resolve_upload_url(resp.url(), Some(next))?;
            }
        }

        upload_url.query_pairs_mut().append_pair("digest", digest);
        let mut final_headers = HeaderMap::new();
        final_headers.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));

        if upload_debug_enabled() {
            println!("   ✅ Finalizing upload via {}", upload_url);
        }
        let resp = self
            .request(
                Method::PUT,
                upload_url,
                auth,
                Some(final_headers),
                None,
                Some(scope),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        Ok(())
    }

    pub async fn push_blob_stream<R: AsyncRead + Unpin + Send>(
        &self,
        reference: &Reference,
        auth: &RegistryAuth,
        reader: &mut R,
        digest: &str,
        chunk_size: usize,
        progress: Option<Arc<AtomicU64>>,
        initial_chunk: Option<Vec<u8>>,
    ) -> Result<(), OciError> {
        let (mut upload_url, initial_chunk_hint) = self.begin_upload(reference, auth).await?;
        let scope = Self::push_scope(reference);
        let mut effective_chunk = chunk_size.max(1);
        if let Some(min_required) = initial_chunk_hint {
            if min_required > effective_chunk {
                println!(
                    "   📏 Registry requested {:.0} MB minimum chunks; increasing buffer",
                    min_required as f64 / (1024.0 * 1024.0)
                );
                effective_chunk = min_required;
            }
        }

        if upload_debug_enabled() {
            println!("   🔗 Upload session started at {}", upload_url);
        }

        if let Some(mut chunk_vec) = initial_chunk {
            if let Some(min_required) = initial_chunk_hint {
                if chunk_vec.len() < min_required {
                    Self::top_up_initial_chunk(reader, &mut chunk_vec, min_required).await?;
                }
            }
            if !chunk_vec.is_empty() {
                let (next_url, next_hint) = self
                    .transmit_chunk(upload_url, auth, &scope, chunk_vec, progress.as_ref())
                    .await?;
                upload_url = next_url;
                if let Some(min_required) = next_hint {
                    if min_required > effective_chunk {
                        println!(
                            "   📏 Registry increased minimum chunk to {:.0} MB; adjusting",
                            min_required as f64 / (1024.0 * 1024.0)
                        );
                        effective_chunk = min_required;
                    }
                }
            }
        }

        let mut buffer = vec![0u8; effective_chunk];

        loop {
            let read = reader.read(&mut buffer).await?;
            if read == 0 {
                break;
            }
            let (next_url, next_hint) = self
                .transmit_chunk(
                    upload_url,
                    auth,
                    &scope,
                    buffer[..read].to_vec(),
                    progress.as_ref(),
                )
                .await?;
            upload_url = next_url;

            if let Some(min_required) = next_hint {
                if min_required > effective_chunk {
                    println!(
                        "   📏 Registry increased minimum chunk to {:.0} MB; adjusting",
                        min_required as f64 / (1024.0 * 1024.0)
                    );
                    effective_chunk = min_required;
                    buffer.resize(effective_chunk, 0);
                }
            }
        }

        upload_url.query_pairs_mut().append_pair("digest", digest);
        let mut final_headers = HeaderMap::new();
        final_headers.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));

        if upload_debug_enabled() {
            println!("   ✅ Finalizing upload via {}", upload_url);
        }
        let resp = self
            .request(
                Method::PUT,
                upload_url,
                auth,
                Some(final_headers),
                None,
                Some(scope),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        Ok(())
    }

    async fn transmit_chunk(
        &self,
        upload_url: Url,
        auth: &RegistryAuth,
        scope: &str,
        chunk: Vec<u8>,
        progress: Option<&Arc<AtomicU64>>,
    ) -> Result<(Url, Option<usize>), OciError> {
        let chunk_len = chunk.len();
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static(OCTET_STREAM));
        headers.insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&chunk_len.to_string()).map_err(|_| {
                OciError::InvalidResponse("Failed to encode chunk length".to_string())
            })?,
        );
        let chunk_bytes = Bytes::from(chunk);
        let resp = self
            .request(
                Method::PATCH,
                upload_url.clone(),
                auth,
                Some(headers),
                Some(chunk_bytes),
                Some(scope.to_string()),
            )
            .await?;
        if resp.status() != StatusCode::ACCEPTED {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        let mut next_url = upload_url;
        if let Some(next) = resp.headers().get(LOCATION) {
            if upload_debug_enabled() {
                if let Ok(loc) = next.to_str() {
                    println!("   ↪️  Upload redirected to {}", loc);
                }
            }
            next_url = Self::resolve_upload_url(resp.url(), Some(next))?;
        }

        if let Some(counter) = progress {
            counter.fetch_add(chunk_len as u64, Ordering::Relaxed);
        }

        Ok((next_url, Self::parse_chunk_hint(resp.headers())))
    }

    async fn top_up_initial_chunk<R: AsyncRead + Unpin + Send>(
        reader: &mut R,
        chunk: &mut Vec<u8>,
        min_required: usize,
    ) -> Result<(), OciError> {
        while chunk.len() < min_required {
            let remaining = min_required - chunk.len();
            let mut pad = vec![0u8; remaining.min(4 * 1024 * 1024).max(1)];
            let read = reader.read(&mut pad).await?;
            if read == 0 {
                break;
            }
            chunk.extend_from_slice(&pad[..read]);
        }
        Ok(())
    }

    pub async fn push_manifest(
        &self,
        reference: &Reference,
        manifest: &OciImageManifest,
        auth: &RegistryAuth,
    ) -> Result<String, OciError> {
        let tag = reference
            .tag
            .as_ref()
            .ok_or_else(|| OciError::Reference("Cannot push manifest without tag".to_string()))?;
        let mut url = Self::base_url(reference)?;
        url.path_segments_mut()
            .map_err(|_| OciError::Reference("Invalid repository path".to_string()))?
            .push("manifests")
            .push(tag);
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static(MANIFEST_MEDIA_TYPE));
        let body = serde_json::to_vec(manifest)
            .map_err(|e| OciError::InvalidResponse(format!("Failed to encode manifest: {}", e)))?;
        let scope = Self::push_scope(reference);
        let resp = self
            .request(
                Method::PUT,
                url,
                auth,
                Some(headers),
                Some(Bytes::from(body)),
                Some(scope),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(OciError::Status {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        let location = resp
            .headers()
            .get(LOCATION)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string())
            .unwrap_or_else(|| reference.to_string());
        Ok(location)
    }
}