1use anyhow::{Context, Result, bail};
10use odk_schema::CompiledSchema;
11use serde::Serialize;
12use sha2::{Digest, Sha256};
13
14const MANIFEST_MEDIA_TYPE: &str = "application/vnd.oci.image.manifest.v1+json";
16const EMPTY_CONFIG_MEDIA_TYPE: &str = "application/vnd.oci.empty.v1+json";
18const SCHEMA_ARTIFACT_TYPE: &str = "application/vnd.omni.odk.schema.v1+json";
20const EMPTY_CONFIG: &[u8] = b"{}";
22
23pub struct PublishTarget {
25 pub registry: String,
27 pub repository: String,
29 pub tag: String,
31 pub token: Option<String>,
33}
34
35fn sha256_digest(data: &[u8]) -> String {
37 let mut hasher = Sha256::new();
38 hasher.update(data);
39 let hex: String = hasher
40 .finalize()
41 .iter()
42 .map(|byte| format!("{byte:02x}"))
43 .collect();
44 format!("sha256:{hex}")
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize)]
49struct Descriptor {
50 #[serde(rename = "mediaType")]
51 media_type: String,
52 digest: String,
53 size: u64,
54}
55
56impl Descriptor {
57 fn new(media_type: &str, data: &[u8]) -> Self {
58 Self {
59 media_type: media_type.to_string(),
60 digest: sha256_digest(data),
61 size: data.len() as u64,
62 }
63 }
64}
65
66fn build_manifest(config: &Descriptor, layers: &[Descriptor]) -> serde_json::Value {
68 serde_json::json!({
69 "schemaVersion": 2,
70 "mediaType": MANIFEST_MEDIA_TYPE,
71 "artifactType": SCHEMA_ARTIFACT_TYPE,
72 "config": config,
73 "layers": layers,
74 })
75}
76
77fn upload_url_with_digest(location: &str, digest: &str) -> String {
82 let separator = if location.contains('?') { '&' } else { '?' };
83 format!("{location}{separator}digest={digest}")
84}
85
86fn base(target: &PublishTarget) -> String {
87 format!(
88 "{}/v2/{}",
89 target.registry.trim_end_matches('/'),
90 target.repository
91 )
92}
93
94fn bearer(token: &Option<String>) -> Option<String> {
96 token.as_ref().map(|token| format!("Bearer {token}"))
97}
98
99fn push_blob(target: &PublishTarget, descriptor: &Descriptor, data: &[u8]) -> Result<()> {
101 let base = base(target);
102 let auth = bearer(&target.token);
103
104 let mut head = ureq::head(format!("{base}/blobs/{}", descriptor.digest));
106 if let Some(auth) = &auth {
107 head = head.header("Authorization", auth);
108 }
109 let head = head
110 .config()
111 .http_status_as_error(false)
112 .build()
113 .call()
114 .with_context(|| format!("HEAD blob {} failed", descriptor.digest))?;
115 if head.status() == 200 {
116 return Ok(());
117 }
118
119 let mut start = ureq::post(format!("{base}/blobs/uploads/"));
121 if let Some(auth) = &auth {
122 start = start.header("Authorization", auth);
123 }
124 let started = start
125 .config()
126 .http_status_as_error(false)
127 .build()
128 .send_empty()
129 .context("failed to start blob upload")?;
130 if started.status() != 202 {
131 bail!(
132 "registry rejected blob upload start: HTTP {}",
133 started.status()
134 );
135 }
136 let location = started
137 .headers()
138 .get("location")
139 .and_then(|value| value.to_str().ok())
140 .context("blob upload response missing Location header")?
141 .to_string();
142
143 let mut put = ureq::put(upload_url_with_digest(&location, &descriptor.digest))
145 .header("Content-Type", "application/octet-stream");
146 if let Some(auth) = &auth {
147 put = put.header("Authorization", auth);
148 }
149 let done = put
150 .config()
151 .http_status_as_error(false)
152 .build()
153 .send(data)
154 .context("failed to upload blob")?;
155 if done.status() != 201 {
156 bail!("registry rejected blob upload: HTTP {}", done.status());
157 }
158 Ok(())
159}
160
161fn push_manifest(target: &PublishTarget, manifest: &[u8]) -> Result<String> {
163 let url = format!("{}/manifests/{}", base(target), target.tag);
164 let mut put = ureq::put(&url).header("Content-Type", MANIFEST_MEDIA_TYPE);
165 if let Some(auth) = bearer(&target.token) {
166 put = put.header("Authorization", auth);
167 }
168 let response = put
169 .config()
170 .http_status_as_error(false)
171 .build()
172 .send(manifest)
173 .context("failed to upload manifest")?;
174 if response.status() != 201 {
175 bail!("registry rejected manifest: HTTP {}", response.status());
176 }
177 Ok(sha256_digest(manifest))
178}
179
180pub fn publish(schema: &CompiledSchema, target: &PublishTarget) -> Result<String> {
184 let schema_json =
185 serde_json::to_vec(schema).context("failed to serialize schema to its IR JSON")?;
186
187 let config = Descriptor::new(EMPTY_CONFIG_MEDIA_TYPE, EMPTY_CONFIG);
188 let layer = Descriptor::new(SCHEMA_ARTIFACT_TYPE, &schema_json);
189 let manifest = build_manifest(&config, std::slice::from_ref(&layer));
190 let manifest_bytes =
191 serde_json::to_vec(&manifest).context("failed to serialize OCI manifest")?;
192
193 push_blob(target, &config, EMPTY_CONFIG).context("failed to push config blob")?;
194 push_blob(target, &layer, &schema_json).context("failed to push schema layer")?;
195 let digest = push_manifest(target, &manifest_bytes)?;
196
197 Ok(format!(
198 "{}/{}:{}@{}",
199 target.registry.trim_end_matches('/'),
200 target.repository,
201 target.tag,
202 digest
203 ))
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn sha256_digest_matches_the_oci_format_and_known_value() {
212 assert_eq!(
214 sha256_digest(b"{}"),
215 "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
216 );
217 }
218
219 #[test]
220 fn descriptor_records_media_type_digest_and_size() {
221 let descriptor = Descriptor::new("application/json", b"{}");
222 assert_eq!(descriptor.media_type, "application/json");
223 assert_eq!(descriptor.size, 2);
224 assert_eq!(
225 descriptor.digest,
226 "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
227 );
228 }
229
230 #[test]
231 fn manifest_is_a_v2_artifact_manifest() {
232 let config = Descriptor::new(EMPTY_CONFIG_MEDIA_TYPE, EMPTY_CONFIG);
233 let layer = Descriptor::new(SCHEMA_ARTIFACT_TYPE, b"{\"name\":\"X\"}");
234 let manifest = build_manifest(&config, std::slice::from_ref(&layer));
235
236 assert_eq!(manifest["schemaVersion"], 2);
237 assert_eq!(manifest["mediaType"], MANIFEST_MEDIA_TYPE);
238 assert_eq!(manifest["artifactType"], SCHEMA_ARTIFACT_TYPE);
239 assert_eq!(manifest["config"]["mediaType"], EMPTY_CONFIG_MEDIA_TYPE);
240 assert_eq!(manifest["layers"][0]["mediaType"], SCHEMA_ARTIFACT_TYPE);
241 assert_eq!(manifest["layers"][0]["digest"], layer.digest);
242 assert_eq!(manifest["layers"][0]["size"], 12);
243 }
244
245 #[test]
246 fn upload_url_appends_digest_preserving_existing_query() {
247 assert_eq!(
248 upload_url_with_digest("https://r/v2/x/blobs/uploads/abc", "sha256:d"),
249 "https://r/v2/x/blobs/uploads/abc?digest=sha256:d"
250 );
251 assert_eq!(
252 upload_url_with_digest("https://r/v2/x/blobs/uploads/abc?state=y", "sha256:d"),
253 "https://r/v2/x/blobs/uploads/abc?state=y&digest=sha256:d"
254 );
255 }
256
257 #[test]
258 fn base_url_trims_trailing_slash() {
259 let target = PublishTarget {
260 registry: "https://manifold.omni.dev/".to_string(),
261 repository: "team/api".to_string(),
262 tag: "latest".to_string(),
263 token: None,
264 };
265 assert_eq!(base(&target), "https://manifold.omni.dev/v2/team/api");
266 }
267}