forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

oci.rs296 lines, 10.8 KiBHistoryRawDownload
1//! Container registry rules shared by the web layer: repository names, digests, tags, the
2//! manifest media types, the reference scan of a manifest, and the short-lived bearer token that
3//! `docker login` and `podman` exchange for their credentials.
4//!
5//! Token format: `base64url("oci1|<user id or empty>|<expires>") + "." + base64url(hmac)`. The
6//! MAC covers the payload under its own domain tag, so an LFS token never verifies here.
7
8use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
9use hmac::{Hmac, KeyInit, Mac};
10use serde_json::Value;
11use sha2::Sha256;
12use subtle::ConstantTimeEq;
13
14type HmacSha256 = Hmac<Sha256>;
15
16/// The media types a manifest may be pushed as.
17pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [
18 "application/vnd.oci.image.manifest.v1+json",
19 "application/vnd.oci.image.index.v1+json",
20 "application/vnd.docker.distribution.manifest.v2+json",
21 "application/vnd.docker.distribution.manifest.list.v2+json",
22];
23
24/// Longest repository name the spec allows.
25const MAX_REPO_NAME: usize = 255;
26/// Longest tag the spec allows.
27const MAX_TAG: usize = 128;
28
29/// True for one of [`MANIFEST_MEDIA_TYPES`].
30pub fn is_manifest_media_type(media_type: &str) -> bool {
31 MANIFEST_MEDIA_TYPES.contains(&media_type)
32}
33
34/// True for one path segment of a repository name: lowercase letters and digits, joined by a
35/// single `.` or `_`, or by runs of `-`, and starting and ending with a letter or digit.
36fn valid_segment(segment: &str) -> bool {
37 let bytes = segment.as_bytes();
38 if bytes.is_empty() {
39 return false;
40 }
41 let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
42 if !alnum(bytes[0]) || !alnum(bytes[bytes.len() - 1]) {
43 return false;
44 }
45 let mut prev_sep = false;
46 for &b in bytes {
47 if alnum(b) {
48 prev_sep = false;
49 } else if matches!(b, b'.' | b'_' | b'-') {
50 if prev_sep && b != b'-' {
51 return false;
52 }
53 prev_sep = true;
54 } else {
55 return false;
56 }
57 }
58 true
59}
60
61/// The owner and the image path of a repository name such as `tahinli/app` or `tahinli/a/b`.
62/// `None` when the name has no owner segment or no image segment, or a segment is malformed.
63pub fn split_repo_name(name: &str) -> Option<(&str, &str)> {
64 if name.len() > MAX_REPO_NAME {
65 return None;
66 }
67 let (owner, image) = name.split_once('/')?;
68 if !image.split('/').all(valid_segment) || !valid_segment(owner) {
69 return None;
70 }
71 Some((owner, image))
72}
73
74/// The lowercase `sha256:<hex>` digest, returned as its 64 hex characters. `None` for any other
75/// algorithm or a malformed value.
76pub fn parse_digest(digest: &str) -> Option<&str> {
77 let hex = digest.strip_prefix("sha256:")?;
78 let valid = hex.len() == 64
79 && hex
80 .bytes()
81 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
82 valid.then_some(hex)
83}
84
85/// True for a tag: up to 128 characters from `[A-Za-z0-9_.-]`, not starting with `.` or `-`.
86pub fn valid_tag(tag: &str) -> bool {
87 let bytes = tag.as_bytes();
88 !bytes.is_empty()
89 && bytes.len() <= MAX_TAG
90 && !matches!(bytes[0], b'.' | b'-')
91 && bytes
92 .iter()
93 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
94}
95
96/// What a manifest refers to.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct ManifestRefs {
99 /// `sha256:<hex>` digests of the config and layers, or of the child manifests of an index.
100 pub digests: Vec<String>,
101 /// Bytes of the image: its config and layers. For an index, the manifest's own length.
102 pub total_size: u64,
103 /// True for an index or manifest list, whose digests name manifests rather than blobs.
104 pub is_index: bool,
105}
106
107/// Reads the digests a manifest names. A manifest with a `manifests` array is an index. Any other
108/// manifest must name a `config` and may name layers. Every digest must be `sha256:<hex>`.
109pub fn scan_manifest(bytes: &[u8]) -> Result<ManifestRefs, String> {
110 let value: Value =
111 serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?;
112 if !value.is_object() {
113 return Err("manifest is not a JSON object".into());
114 }
115 if let Some(children) = value.get("manifests").and_then(Value::as_array) {
116 let digests = children
117 .iter()
118 .map(descriptor_digest)
119 .collect::<Result<Vec<_>, _>>()?;
120 return Ok(ManifestRefs {
121 digests,
122 total_size: bytes.len() as u64,
123 is_index: true,
124 });
125 }
126 let config = value
127 .get("config")
128 .ok_or_else(|| "manifest has no config".to_owned())?;
129 let mut digests = vec![descriptor_digest(config)?];
130 let mut total = descriptor_size(config);
131 if let Some(layers) = value.get("layers") {
132 let layers = layers
133 .as_array()
134 .ok_or_else(|| "manifest layers is not an array".to_owned())?;
135 for layer in layers {
136 digests.push(descriptor_digest(layer)?);
137 total = total.saturating_add(descriptor_size(layer));
138 }
139 }
140 Ok(ManifestRefs {
141 digests,
142 total_size: total,
143 is_index: false,
144 })
145}
146
147fn descriptor_digest(descriptor: &Value) -> Result<String, String> {
148 let digest = descriptor
149 .get("digest")
150 .and_then(Value::as_str)
151 .ok_or_else(|| "a descriptor has no digest".to_owned())?;
152 parse_digest(digest)
153 .map(|hex| format!("sha256:{hex}"))
154 .ok_or_else(|| format!("unsupported digest {digest}"))
155}
156
157fn descriptor_size(descriptor: &Value) -> u64 {
158 descriptor.get("size").and_then(Value::as_u64).unwrap_or(0)
159}
160
161fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 {
162 // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail.
163 let mut mac =
164 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
165 mac.update(b"oci\0");
166 mac.update(payload);
167 mac
168}
169
170/// Issues a bearer token for `subject` (a user id, or `None` for anonymous), valid until
171/// `expires_unix` seconds since the epoch.
172pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String {
173 let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or(""));
174 let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes();
175 format!(
176 "{}.{}",
177 BASE64_URL_SAFE_NO_PAD.encode(payload.as_bytes()),
178 BASE64_URL_SAFE_NO_PAD.encode(tag)
179 )
180}
181
182/// Checks a bearer token at `now_unix`. Returns the subject it names (`None` for anonymous), or
183/// `None` when the token is malformed, forged, or expired.
184pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option<String>> {
185 let (payload_b64, mac_b64) = token.split_once('.')?;
186 let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
187 let tag = BASE64_URL_SAFE_NO_PAD.decode(mac_b64).ok()?;
188 let expected = mac_for(key, &payload).finalize().into_bytes();
189 if !bool::from(expected.as_slice().ct_eq(&tag)) {
190 return None;
191 }
192 let payload = std::str::from_utf8(&payload).ok()?;
193 let mut parts = payload.split('|');
194 if parts.next()? != "oci1" {
195 return None;
196 }
197 let subject = parts.next()?;
198 let expires: i64 = parts.next()?.parse().ok()?;
199 if parts.next().is_some() || now_unix >= expires {
200 return None;
201 }
202 Some((!subject.is_empty()).then(|| subject.to_owned()))
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 const KEY: [u8; 32] = [3; 32];
210 const NOW: i64 = 1_700_000_000;
211 const HEX: &str = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393";
212
213 #[test]
214 fn repo_names_need_an_owner_and_an_image() {
215 assert_eq!(split_repo_name("tahinli/app"), Some(("tahinli", "app")));
216 assert_eq!(split_repo_name("tahinli/a/b"), Some(("tahinli", "a/b")));
217 assert_eq!(split_repo_name("tahinli"), None);
218 assert_eq!(split_repo_name("Tahinli/app"), None);
219 assert_eq!(split_repo_name("tahinli/app/"), None);
220 assert_eq!(split_repo_name("tahinli//app"), None);
221 assert_eq!(split_repo_name("tahinli/app__/x"), None);
222 assert_eq!(
223 split_repo_name("tahinli/my.app-v2_x"),
224 Some(("tahinli", "my.app-v2_x"))
225 );
226 assert_eq!(split_repo_name("tahinli/a..b"), None);
227 }
228
229 #[test]
230 fn digests_must_be_lowercase_sha256_hex() {
231 assert_eq!(parse_digest(&format!("sha256:{HEX}")), Some(HEX));
232 assert_eq!(parse_digest(HEX), None);
233 assert_eq!(parse_digest(&format!("sha512:{HEX}")), None);
234 assert_eq!(
235 parse_digest(&format!("sha256:{}", HEX.to_uppercase())),
236 None
237 );
238 assert_eq!(parse_digest(&format!("sha256:{}", &HEX[..63])), None);
239 }
240
241 #[test]
242 fn tags_follow_the_spec_charset() {
243 assert!(valid_tag("latest"));
244 assert!(valid_tag("v1.2.3-rc_1"));
245 assert!(!valid_tag(""));
246 assert!(!valid_tag(".hidden"));
247 assert!(!valid_tag("a/b"));
248 assert!(!valid_tag(&"a".repeat(129)));
249 }
250
251 #[test]
252 fn an_image_manifest_names_its_config_and_layers() {
253 let manifest = format!(
254 r#"{{"schemaVersion":2,"config":{{"digest":"sha256:{HEX}","size":10}},
255 "layers":[{{"digest":"sha256:{HEX}","size":100}}]}}"#
256 );
257 let refs = scan_manifest(manifest.as_bytes()).unwrap();
258 assert!(!refs.is_index);
259 assert_eq!(refs.digests, vec![format!("sha256:{HEX}"); 2]);
260 assert_eq!(refs.total_size, 110);
261 }
262
263 #[test]
264 fn an_index_names_child_manifests() {
265 let manifest = format!(r#"{{"manifests":[{{"digest":"sha256:{HEX}","size":5}}]}}"#);
266 let refs = scan_manifest(manifest.as_bytes()).unwrap();
267 assert!(refs.is_index);
268 assert_eq!(refs.digests, vec![format!("sha256:{HEX}")]);
269 }
270
271 #[test]
272 fn bad_manifests_are_refused() {
273 assert!(scan_manifest(b"not json").is_err());
274 assert!(scan_manifest(b"[]").is_err());
275 assert!(scan_manifest(b"{}").is_err());
276 assert!(scan_manifest(br#"{"config":{"digest":"md5:x"}}"#).is_err());
277 }
278
279 #[test]
280 fn a_token_round_trips_for_a_user_and_for_anonymous() {
281 let token = issue_token(&KEY, Some("user-1"), NOW + 60);
282 assert_eq!(verify_token(&KEY, &token, NOW), Some(Some("user-1".into())));
283 let anon = issue_token(&KEY, None, NOW + 60);
284 assert_eq!(verify_token(&KEY, &anon, NOW), Some(None));
285 }
286
287 #[test]
288 fn a_token_is_refused_when_expired_forged_or_from_another_key() {
289 let token = issue_token(&KEY, Some("user-1"), NOW + 60);
290 assert_eq!(verify_token(&KEY, &token, NOW + 60), None);
291 assert_eq!(verify_token(&[9; 32], &token, NOW), None);
292 assert_eq!(verify_token(&KEY, "garbage", NOW), None);
293 let forged = token.replacen(&BASE64_URL_SAFE_NO_PAD.encode("oci1|user-1|"), "x", 1);
294 assert_eq!(verify_token(&KEY, &forged, NOW), None);
295 }
296}