// OCI Distribution v2 HTTP transport, auth challenges, redirects, and streaming. ///| const OCI_MANIFEST_MEDIA_TYPE : String = "application/vnd.oci.image.manifest.v1+json" ///| const MANIFEST_ACCEPT : String = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json" ///| struct ParsedUrl { scheme : String host : String path : String } ///| enum AuthChallenge { Bearer(String, String, String) Basic(String) Unknown } ///| let token_cache : Map[String, String] = Map([]) ///| fn hdr(name : String) -> @http.CaseInsensitiveString { @http.CaseInsensitiveString(name) } ///| fn split_channel_url(url : String) -> (String, String) { let clean = strip_url_scheme(trim(url)) let (host, ns) = split_first(clean, '/') (host, trim_slashes(ns)) } ///| fn trim_slashes(s : String) -> String { let a = chars(s) let mut start = 0 let mut end = a.length() while start < end && a[start] == '/' { start = start + 1 } while end > start && a[end - 1] == '/' { end = end - 1 } slice(a, start, end) } ///| fn channel_scheme(ch : Channel) -> String { if ch.plain_http { "http" } else { "https" } } ///| fn parse_url(raw : String) -> ParsedUrl raise OrbitError { let u = trim(raw) guard u.find("://") is Some(idx) else { raise OrbitError("invalid URL '\{raw}'") } let scheme = ascii_lower(u[:idx].to_owned()) if scheme != "http" && scheme != "https" { raise OrbitError("unsupported URL scheme '\{scheme}'") } let rest = u[idx + 3:].to_owned() let a = chars(rest) let mut split_at = a.length() let mut needs_slash = true for i = 0; i < a.length(); i = i + 1 { if a[i] == '/' { split_at = i needs_slash = false break } if a[i] == '?' { split_at = i needs_slash = true break } } let host = slice(a, 0, split_at) if host == "" { raise OrbitError("URL missing host: '\{raw}'") } let path = if split_at == a.length() { "/" } else if needs_slash { "/" + slice(a, split_at, a.length()) } else { slice(a, split_at, a.length()) } ParsedUrl::{ scheme, host, path } } ///| fn same_origin(a : ParsedUrl, b : ParsedUrl) -> Bool { ascii_lower(a.scheme) == ascii_lower(b.scheme) && ascii_lower(a.host) == ascii_lower(b.host) } ///| fn resolve_location( base : ParsedUrl, location : String, ) -> ParsedUrl raise OrbitError { let loc = trim(location) if loc == "" { raise OrbitError("empty redirect Location") } let lower = ascii_lower(loc) if has_prefix(lower, "http://") || has_prefix(lower, "https://") { return parse_url(loc) } if has_prefix(loc, "//") { return parse_url(base.scheme + ":" + loc) } if has_prefix(loc, "/") { return ParsedUrl::{ scheme: base.scheme, host: base.host, path: loc } } let (path_only, _) = split_first(base.path, '?') let a = chars(path_only) let mut last_slash = -1 for i = 0; i < a.length(); i = i + 1 { if a[i] == '/' { last_slash = i } } let dir = if last_slash >= 0 { slice(a, 0, last_slash + 1) } else { "/" } ParsedUrl::{ scheme: base.scheme, host: base.host, path: dir + loc } } ///| fn parse_auth_params(rest : String) -> Map[String, String] { let out : Map[String, String] = Map([]) let a = chars(rest) let n = a.length() let mut i = 0 while i < n { while i < n && (is_space(a[i]) || a[i] == ',') { i = i + 1 } if i >= n { break } let key_start = i while i < n && a[i] != '=' && a[i] != ',' && !is_space(a[i]) { i = i + 1 } let key = ascii_lower(slice(a, key_start, i)) while i < n && is_space(a[i]) { i = i + 1 } if i >= n || a[i] != '=' { while i < n && a[i] != ',' { i = i + 1 } continue } i = i + 1 while i < n && is_space(a[i]) { i = i + 1 } let val = StringBuilder() if i < n && a[i] == '"' { i = i + 1 while i < n && a[i] != '"' { if a[i] == '\\' && i + 1 < n { val.write_char(a[i + 1]) i = i + 2 } else { val.write_char(a[i]) i = i + 1 } } if i < n && a[i] == '"' { i = i + 1 } } else { while i < n && a[i] != ',' { val.write_char(a[i]) i = i + 1 } } if key != "" { out[key] = val.to_string() } } out } ///| fn parse_www_authenticate(value : String) -> AuthChallenge { let s = trim(value) if s == "" { return Unknown } let a = chars(s) let mut i = 0 while i < a.length() && !is_space(a[i]) { i = i + 1 } let scheme = ascii_lower(slice(a, 0, i)) let rest = trim(slice(a, i, a.length())) if scheme == "bearer" { let params = parse_auth_params(rest) let realm = params.get("realm").unwrap_or("") if realm == "" { return Unknown } let service = params.get("service").unwrap_or("") let scope = params.get("scope").unwrap_or("") Bearer(realm, service, scope) } else if scheme == "basic" { let params = parse_auth_params(rest) Basic(params.get("realm").unwrap_or("")) } else { Unknown } } ///| fn unquote(s : String) -> String { let t = trim(s) let a = chars(t) if a.length() >= 2 && a[0] == '"' && a[a.length() - 1] == '"' { slice(a, 1, a.length() - 1) } else { t } } ///| fn is_next_rel_param(params : String) -> Bool { for part in split_on(params, ';') { let p = trim(part) if p == "" { continue } let (k, v) = split_first(p, '=') if ascii_lower(trim(k)) == "rel" { let rels = unquote(v) for tok in split_on(rels, ' ') { if ascii_lower(trim(tok)) == "next" { return true } } } } false } ///| fn parse_next_link(value : String) -> String? { let a = chars(value) let n = a.length() let mut i = 0 while i < n { while i < n && a[i] != '<' { i = i + 1 } if i >= n { break } i = i + 1 let url_start = i while i < n && a[i] != '>' { i = i + 1 } if i >= n { break } let target = trim(slice(a, url_start, i)) i = i + 1 let param_start = i let mut in_quotes = false while i < n { if a[i] == '"' { in_quotes = !in_quotes } else if a[i] == ',' && !in_quotes { break } i = i + 1 } let params = slice(a, param_start, i) if target != "" && is_next_rel_param(params) { return Some(target) } if i < n && a[i] == ',' { i = i + 1 } } None } ///| fn extract_digest_header(headers : @http.Headers) -> String? { match headers.get(hdr("Docker-Content-Digest")) { Some(v) => { let t = trim(v) if t != "" { return Some(t) } } None => () } match headers.get(hdr("ETag")) { Some(v) => { let mut t = trim(v) if has_prefix(t, "W/") || has_prefix(t, "w/") { t = trim(drop_chars(t, 2)) } let d = unquote(t) if has_prefix(d, "sha256:") || has_prefix(d, "sha512:") { return Some(d) } } None => () } None } ///| fn format_oci_error(code : Int32, reason : String, body : Bytes) -> String { let text = utf8_decode(body) let obj : Map[String, Json]? = Some(parse_object(text, "oci error")) catch { _ => None } match obj { Some(o) => match o.get("errors") { Some(Json::Array(errs)) => if errs.length() > 0 { match errs[0] { Json::Object(e) => { let c = jstr(e, "code", "") let m = jstr(e, "message", "") if c != "" && m != "" { return "HTTP \{code}: \{c}: \{m}" } else if m != "" { return "HTTP \{code}: \{m}" } else if c != "" { return "HTTP \{code}: \{c}" } } _ => () } } _ => () } None => () } let base = if reason != "" { "HTTP \{code} \{reason}" } else { "HTTP \{code}" } let snippet = trim(text) if snippet != "" && chars(snippet).length() < 200 { base + ": " + snippet } else { base } } ///| fn token_cache_key(host : String, scope_key : String) -> String { ascii_lower(host) + "|" + scope_key } ///| fn is_redirect_code(code : Int32) -> Bool { code == 301 || code == 302 || code == 303 || code == 307 || code == 308 } ///| fn build_http_headers( headers : Map[String, String], auth_header : String?, content_length : Int64?, ) -> @http.Headers { let out : @http.Headers = Map([]) for k, v in headers { out[hdr(k)] = v } match auth_header { Some(a) => out[hdr("Authorization")] = a None => () } match content_length { Some(n) => out[hdr("Content-Length")] = n.to_string() None => () } out } ///| async fn connect_http(url : ParsedUrl) -> @http.Client raise OrbitError { let base_headers : @http.Headers = Map([]) base_headers[hdr("User-Agent")] = "orbit/0.1" base_headers[hdr("Accept-Encoding")] = "identity" @http.Client::Client(url.scheme + "://" + url.host, headers=base_headers) catch { e => raise OrbitError("cannot connect to \{url.host}: \{e}") } } ///| async fn raw_http_bytes( meth : @http.RequestMethod, url_str : String, headers : Map[String, String], auth_header : String?, body : Bytes, ) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError { let mut cur_url = parse_url(url_str) let mut cur_meth = meth let mut cur_body = body let mut cur_auth = auth_header for hop = 0; hop < 10; hop = hop + 1 { let clen : Int64? = if cur_body.length() > 0 || cur_meth is Post || cur_meth is Put { Some(cur_body.length().to_int64()) } else { None } let extra = build_http_headers(headers, cur_auth, clen) let client = connect_http(cur_url) defer client.close() let resp = try { client.request(cur_meth, cur_url.path, extra_headers=extra) if cur_body.length() > 0 { client.write(cur_body) } client.end_request() } catch { e => raise OrbitError("HTTP request to \{cur_url.host} failed: \{e}") } if is_redirect_code(resp.code) { match resp.headers.get(hdr("Location")) { Some(loc) => { let next_url = resolve_location(cur_url, loc) if !same_origin(cur_url, next_url) { cur_auth = None } if (resp.code == 301 || resp.code == 302 || resp.code == 303) && cur_meth is Post { cur_meth = Get cur_body = b"" } cur_url = next_url continue } None => () } } let resp_body = if cur_meth is Head { b"" } else { client.read_all().binary() catch { e => raise OrbitError("failed reading response from \{cur_url.host}: \{e}") } } return (cur_url, resp, resp_body) } raise OrbitError("too many redirects for \{url_str}") } ///| async fn fetch_bearer_token( realm : String, service : String, scope : String, creds : Creds?, ) -> String raise OrbitError { let mut token_url = realm let mut sep = if has_char(realm, '?') { "&" } else { "?" } if service != "" { token_url = token_url + sep + "service=" + @percent.encode(service) sep = "&" } if scope != "" { token_url = token_url + sep + "scope=" + @percent.encode(scope) } let auth_header = creds.map(fn(c) { "Basic " + encode_basic_auth(c) }) let (_, resp, body) = raw_http_bytes( Get, token_url, Map([("Accept", "application/json")]), auth_header, b"", ) if resp.code < 200 || resp.code >= 300 { raise OrbitError( "authentication failed (\{format_oci_error(resp.code, resp.reason, body)})", ) } let obj = parse_object(utf8_decode(body), "token response") let tok = jstr(obj, "token", "") if tok != "" { return tok } let access = jstr(obj, "access_token", "") if access != "" { return access } raise OrbitError("token response missing token") } ///| async fn resolve_auth_retry( host : String, scope_key : String, used_cached : Bool, www_auth : String, creds_override : Creds?, ) -> String? raise OrbitError { if used_cached && scope_key != "" { token_cache.remove(token_cache_key(host, scope_key)) } let creds = match creds_override { Some(c) => Some(c) None => load_creds(host) } match parse_www_authenticate(www_auth) { Bearer(realm, service, scope) => { let tok = fetch_bearer_token(realm, service, scope, creds) if creds_override is None && scope_key != "" { token_cache[token_cache_key(host, scope_key)] = tok } Some("Bearer " + tok) } Basic(_) => match creds { Some(c) => Some("Basic " + encode_basic_auth(c)) None => None } Unknown => None } } ///| async fn oci_request( meth : @http.RequestMethod, url_str : String, headers : Map[String, String], body : Bytes, scope_key : String, creds_override? : Creds, ) -> (@http.Response, Bytes) raise OrbitError { let initial_url = parse_url(url_str) let (initial_auth, used_cached) = if creds_override is None && scope_key != "" { match token_cache.get(token_cache_key(initial_url.host, scope_key)) { Some(t) => (Some("Bearer " + t), true) None => (None, false) } } else { (None, false) } let (final_url, resp, resp_body) = raw_http_bytes( meth, url_str, headers, initial_auth, body, ) if resp.code != 401 { return (resp, resp_body) } let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) { Some(v) => v None => return (resp, resp_body) } let retry_auth = match resolve_auth_retry( final_url.host, scope_key, used_cached, www_auth, creds_override, ) { Some(a) => a None => return (resp, resp_body) } let (_, retry_resp, retry_body) = raw_http_bytes( meth, url_str, headers, Some(retry_auth), body, ) (retry_resp, retry_body) } ///| async fn try_download_once( url_str : String, dest_path : String, expected_digest : String, auth_header : String?, ) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError { let mut cur_url = parse_url(url_str) let mut cur_auth = auth_header for hop = 0; hop < 10; hop = hop + 1 { let extra = build_http_headers(Map([]), cur_auth, None) let client = connect_http(cur_url) defer client.close() let resp = try { client.request(Get, cur_url.path, extra_headers=extra) client.end_request() } catch { e => raise OrbitError("download from \{cur_url.host} failed: \{e}") } if is_redirect_code(resp.code) { match resp.headers.get(hdr("Location")) { Some(loc) => { let next_url = resolve_location(cur_url, loc) if !same_origin(cur_url, next_url) { cur_auth = None } cur_url = next_url continue } None => () } } if resp.code < 200 || resp.code >= 300 { let err_body = client.read_all().binary() catch { _ => b"" } return (cur_url, resp, err_body) } let out = @fs.open( dest_path, mode=WriteOnly, create_mode=CreateOrTruncate, ) catch { e => raise OrbitError("cannot write \{dest_path}: \{e}") } defer out.close() let hasher = Sha256::new() let buf = FixedArray::make(32768, b'\x00') for ;; { let n = client.read(buf) catch { e => raise OrbitError("download interrupted from \{cur_url.host}: \{e}") } if n == 0 { break } hasher.update_fixed(buf, n) out.write(buf.unsafe_reinterpret_as_bytes()[:n]) catch { e => raise OrbitError("cannot write \{dest_path}: \{e}") } } if has_prefix(expected_digest, "sha256:") { let actual = "sha256:" + hasher.finish_hex() if actual != expected_digest { raise OrbitError( "digest mismatch for \{dest_path}: expected \{expected_digest}, got \{actual}", ) } } return (cur_url, resp, b"") } raise OrbitError("too many redirects downloading \{url_str}") } ///| async fn oci_download_to_file( url_str : String, dest_path : String, expected_digest : String, scope_key : String, ) -> Unit raise OrbitError { let initial_url = parse_url(url_str) let (initial_auth, used_cached) = if scope_key != "" { match token_cache.get(token_cache_key(initial_url.host, scope_key)) { Some(t) => (Some("Bearer " + t), true) None => (None, false) } } else { (None, false) } let (final_url, resp, err_body) = try_download_once( url_str, dest_path, expected_digest, initial_auth, ) if resp.code >= 200 && resp.code < 300 { return } if resp.code == 401 { match resp.headers.get(hdr("WWW-Authenticate")) { Some(www_auth) => match resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) { Some(retry_auth) => { let (_, retry_resp, retry_err) = try_download_once( url_str, dest_path, expected_digest, Some(retry_auth), ) if retry_resp.code >= 200 && retry_resp.code < 300 { return } raise OrbitError( "download failed (\{format_oci_error(retry_resp.code, retry_resp.reason, retry_err)})", ) } None => () } None => () } } raise OrbitError( "download failed (\{format_oci_error(resp.code, resp.reason, err_body)})", ) } ///| async fn try_upload_file_once( url_str : String, file_path : String, size : Int64, content_type : String, auth_header : String?, ) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError { let mut cur_url = parse_url(url_str) let mut cur_auth = auth_header for hop = 0; hop < 10; hop = hop + 1 { let extra = build_http_headers( Map([("Content-Type", content_type)]), cur_auth, Some(size), ) let client = connect_http(cur_url) defer client.close() let file = @fs.open(file_path, mode=ReadOnly) catch { e => raise OrbitError("cannot open \{file_path}: \{e}") } defer file.close() let resp = try { client.request(Put, cur_url.path, extra_headers=extra) client.write_reader(file) client.end_request() } catch { e => raise OrbitError("upload to \{cur_url.host} failed: \{e}") } if is_redirect_code(resp.code) { match resp.headers.get(hdr("Location")) { Some(loc) => { let next_url = resolve_location(cur_url, loc) if !same_origin(cur_url, next_url) { cur_auth = None } cur_url = next_url continue } None => () } } let resp_body = client.read_all().binary() catch { e => raise OrbitError("failed reading upload response: \{e}") } return (cur_url, resp, resp_body) } raise OrbitError("too many redirects uploading to \{url_str}") } ///| async fn oci_upload_file( url_str : String, file_path : String, size : Int64, content_type : String, scope_key : String, ) -> (@http.Response, Bytes) raise OrbitError { let initial_url = parse_url(url_str) let (initial_auth, used_cached) = if scope_key != "" { match token_cache.get(token_cache_key(initial_url.host, scope_key)) { Some(t) => (Some("Bearer " + t), true) None => (None, false) } } else { (None, false) } let (final_url, resp, resp_body) = try_upload_file_once( url_str, file_path, size, content_type, initial_auth, ) if resp.code != 401 { return (resp, resp_body) } let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) { Some(v) => v None => return (resp, resp_body) } let retry_auth = match resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) { Some(a) => a None => return (resp, resp_body) } let (_, retry_resp, retry_body) = try_upload_file_once( url_str, file_path, size, content_type, Some(retry_auth), ) (retry_resp, retry_body) } ///| test "parse_url and resolve_location" { let base = parse_url("https://git.site.latha.org/v2/nandi/hello/tags/list") assert_eq(base.scheme, "https") assert_eq(base.host, "git.site.latha.org") assert_eq(base.path, "/v2/nandi/hello/tags/list") let root_rel = resolve_location(base, "/v2/nandi/hello/blobs/uploads/123") assert_eq(root_rel.host, "git.site.latha.org") assert_eq(root_rel.path, "/v2/nandi/hello/blobs/uploads/123") let abs = resolve_location(base, "https://cdn.example.com/blob?sig=1") assert_eq(abs.host, "cdn.example.com") assert_eq(abs.path, "/blob?sig=1") assert_false(same_origin(base, abs)) assert_true(same_origin(base, root_rel)) let rel = resolve_location(base, "next?n=10") assert_eq(rel.path, "/v2/nandi/hello/tags/next?n=10") } ///| test "parse_www_authenticate handles Bearer with commas in scope and Basic" { match parse_www_authenticate( "Bearer realm=\"https://git.site.latha.org/v2/token\",service=\"container_registry\",scope=\"repository:nandi/hello:pull,push\"", ) { Bearer(realm, service, scope) => { assert_eq(realm, "https://git.site.latha.org/v2/token") assert_eq(service, "container_registry") assert_eq(scope, "repository:nandi/hello:pull,push") } _ => fail("expected Bearer challenge") } match parse_www_authenticate("Basic realm=\"Registry\"") { Basic(realm) => assert_eq(realm, "Registry") _ => fail("expected Basic challenge") } } ///| test "parse_next_link and split_channel_url" { assert_eq( parse_next_link("; rel=\"next\""), Some("/v2/nandi/hello/tags/list?last=latest"), ) assert_eq( parse_next_link( "; rel=\"prev\", ; rel=\"next\"", ), Some("/v2/_catalog?last=b"), ) assert_eq(parse_next_link("; rel=\"prev\""), None) assert_eq(split_channel_url("git.site.latha.org/nandi/"), ("git.site.latha.org", "nandi")) assert_eq(split_channel_url("localhost:5000"), ("localhost:5000", "")) }