diff --git a/README.md b/README.md
index b620935..a89e469 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,13 @@
# orbit
-A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, with [ORAS](https://github.com/oras-project/oras) as the transport.
+A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, speaking the OCI Distribution v2 protocol directly over HTTP/TLS.
-> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` with ORAS 1.2.3.
+> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` and Gitea.
## What it does
- **Publish:** `orbit publish
` packs `/files/` into `pkg.tar.gz` and pushes it with `/orbit.json` as the OCI config blob.
-- **Install with dependencies:** it reads only the small config blob (`oras manifest fetch-config`) to plan, then pulls the layers by digest.
+- **Install with dependencies:** it reads only the small config blob from the OCI registry to plan, then streams the layers by digest with SHA-256 verification.
- **Version constraints:** `1.2.3`, `1.2`, `^1.2.0`, `~1.2.0`, `>=1.2`, `*`. Prereleases match only when the constraint asks for one.
- **Content-addressed store:** packages unpack into `~/.orbit/store///`, and their binaries are symlinked into `~/.orbit/bin/`.
- **File ownership:** two packages can't provide the same binary.
@@ -53,7 +53,7 @@ Because these are ordinary OCI artifacts, you can sign them with `cosign` or `no
## Usage
```sh
-oras login git.site.latha.org # once, with a Gitea token (needed to publish)
+orbit login git.site.latha.org # once, with a Gitea token (needed to publish)
eval "$(orbit env)"
orbit publish examples/hello
@@ -64,6 +64,8 @@ orbit rollback hello
orbit remove hello
```
+Credentials are stored in `~/.orbit/auth.json` (`$ORBIT_ROOT/auth.json`, mode `0600`). Orbit also falls back to `~/.docker/config.json` (`$DOCKER_CONFIG/config.json`) including `credHelpers` and `credsStore`. Use `orbit logout ` to remove stored credentials from Orbit.
+
## Channels
Packages come from **channels**, which work like channels in pixi. A channel is a name for a registry namespace. The built-in `main` channel is `git.site.latha.org/nandi`, so no setup is needed.
@@ -119,7 +121,7 @@ isn't already there. Open a new Bash shell or run `source ~/.bashrc` to pick
up the change in your current shell. `~/.local/bin` must already be on `PATH`
to run `orbit` itself by name.
-Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`.
+Linux only for now: arguments come from `/proc/self/cmdline`. It needs `tar` and `/bin/sh` on `PATH`.
### Package Orbit with Orbit
@@ -131,10 +133,10 @@ package_dir=$(sh scripts/package-orbit.sh) &&
_build/native/release/build/main/main.exe publish "$package_dir"
```
-This publishes to the `main` channel (use `--channel ` for another), so log in with `oras login ` first if needed. The
+This publishes to the `main` channel (use `--channel ` for another), so log in with `orbit login ` first if needed. The
package contains a native Linux binary for the build machine's architecture.
-Use the same architecture on the install machine. `oras` and `tar` are still
-system prerequisites; the package does not bundle them.
+Use the same architecture on the install machine. `tar` is still a
+system prerequisite; the package does not bundle it.
To bootstrap from source, install the published package with the binary you just
built. After adding Orbit's bin directory to `PATH`, use the installed binary
@@ -152,11 +154,14 @@ orbit upgrade orbit
```
src/main/
- stub.c C glue: system(), popen(), file read/write, getenv, exit
- sys.mbt FFI bindings, UTF-8, string helpers, shell quoting
+ stub.c C glue: time, termios echo toggle, getenv, symlink, stderr, exit
+ sys.mbt FFI bindings, UTF-8, string helpers, spinner, atomic writes
+ sha256.mbt streaming FIPS 180-4 SHA-256 (+ tests)
+ auth.mbt credentials store (~/.orbit/auth.json + Docker config fallback)
+ oci.mbt OCI Distribution v2 HTTP transport, Bearer/Basic auth, redirects
semver.mbt versions, constraints, tag selection (+ tests)
model.mbt orbit.json / state.json / config.json (+ tests)
- registry.mbt oras wrappers: tags, resolve, fetch-config, pull, push
+ registry.mbt OCI registry ops: tags, resolve, fetch, publish, login verify
ops.mbt dependency planner, install/remove/upgrade/rollback/gc
channels.mbt config.toml, channel priority and lookup (+ tests)
main.mbt CLI
diff --git a/moon.mod b/moon.mod
index 9e61525..fc4b219 100644
--- a/moon.mod
+++ b/moon.mod
@@ -6,9 +6,9 @@ readme = "README.md"
license = "Apache-2.0"
-keywords = [ "package-manager", "oras", "oci" ]
+keywords = [ "package-manager", "oci" ]
-description = "A small package manager that stores packages as OCI artifacts via ORAS"
+description = "A small package manager that stores packages as OCI artifacts"
source = "src"
diff --git a/src/main/auth.mbt b/src/main/auth.mbt
new file mode 100644
index 0000000..cd610ef
--- /dev/null
+++ b/src/main/auth.mbt
@@ -0,0 +1,442 @@
+// Registry credentials stored in $ORBIT_ROOT/auth.json, with read fallback
+// to $DOCKER_CONFIG/config.json (or ~/.docker/config.json).
+
+///|
+struct Creds {
+ username : String
+ password : String
+}
+
+///|
+fn strip_url_scheme(s : String) -> String {
+ if has_prefix(s, "https://") {
+ drop_chars(s, 8)
+ } else if has_prefix(s, "http://") {
+ drop_chars(s, 7)
+ } else {
+ s
+ }
+}
+
+///|
+fn ascii_lower(s : String) -> String {
+ let sb = StringBuilder()
+ for c in s {
+ if c >= 'A' && c <= 'Z' {
+ sb.write_char(Int32::unsafe_to_char(c.to_int() + 32))
+ } else {
+ sb.write_char(c)
+ }
+ }
+ sb.to_string()
+}
+
+///|
+fn normalize_host(raw : String) -> String {
+ let t = trim(raw)
+ let no_scheme = if has_prefix(ascii_lower(t), "https://") {
+ drop_chars(t, 8)
+ } else if has_prefix(ascii_lower(t), "http://") {
+ drop_chars(t, 7)
+ } else {
+ t
+ }
+ let (host, _) = split_first(no_scheme, '/')
+ ascii_lower(trim(host))
+}
+
+///|
+fn is_docker_hub_host(h : String) -> Bool {
+ h == "docker.io" || h == "registry-1.docker.io" || h == "index.docker.io"
+}
+
+///|
+fn host_matches(stored_key : String, host : String) -> Bool {
+ let a = normalize_host(stored_key)
+ let b = normalize_host(host)
+ if a == "" || b == "" {
+ return false
+ }
+ if a == b {
+ return true
+ }
+ is_docker_hub_host(a) && is_docker_hub_host(b)
+}
+
+///|
+fn auth_file_path(root : String) -> String {
+ root + "/auth.json"
+}
+
+///|
+fn docker_config_path() -> String {
+ let dir = getenv("DOCKER_CONFIG")
+ if dir != "" {
+ dir + "/config.json"
+ } else {
+ getenv("HOME") + "/.docker/config.json"
+ }
+}
+
+///|
+fn encode_basic_auth(creds : Creds) -> String {
+ let raw = utf8_encode(creds.username + ":" + creds.password)
+ @base64.encode(raw[:])
+}
+
+///|
+fn decode_basic_auth(b64 : String) -> Creds? {
+ let raw = @base64.decode(trim(b64), ignore_whitespace=true) catch {
+ _ => return None
+ }
+ let decoded = utf8_decode(raw)
+ if !has_char(decoded, ':') {
+ return None
+ }
+ let (username, password) = split_first(decoded, ':')
+ if username == "" && password == "" {
+ return None
+ }
+ Some(Creds::{ username, password })
+}
+
+///|
+async fn creds_from_helper(
+ helper : String,
+ server_url : String,
+) -> Creds? noraise {
+ if helper == "" || has_char(helper, '/') || has_char(helper, ' ') {
+ return None
+ }
+ let bin = "docker-credential-" + helper
+ let (code, stdout) = run_with_stdin(bin, ["get"], server_url + "\n") catch {
+ _ => return None
+ }
+ if code != 0 {
+ return None
+ }
+ let obj = parse_object(stdout, "credential helper") catch { _ => return None }
+ let username = jstr(obj, "Username", "")
+ let password = jstr(obj, "Secret", "")
+ if username == "" && password == "" {
+ None
+ } else {
+ Some(Creds::{ username, password })
+ }
+}
+
+///|
+async fn load_creds_from_file(path : String, host : String) -> Creds? noraise {
+ let text = match read_text(path) {
+ Some(t) => t
+ None => return None
+ }
+ let top = parse_object(text, path) catch { _ => return None }
+ match top.get("credHelpers") {
+ Some(Json::Object(helpers)) =>
+ for k, v in helpers {
+ if host_matches(k, host) {
+ match v {
+ Json::String(helper) =>
+ if helper != "" {
+ match creds_from_helper(helper, k) {
+ Some(c) => return Some(c)
+ None =>
+ if k != host {
+ match creds_from_helper(helper, host) {
+ Some(c) => return Some(c)
+ None => ()
+ }
+ }
+ }
+ }
+ _ => ()
+ }
+ }
+ }
+ _ => ()
+ }
+ match top.get("auths") {
+ Some(Json::Object(auths)) =>
+ for k, v in auths {
+ if host_matches(k, host) {
+ match v {
+ Json::Object(entry) => {
+ let b64 = jstr(entry, "auth", "")
+ if b64 != "" {
+ match decode_basic_auth(b64) {
+ Some(c) => return Some(c)
+ None => ()
+ }
+ }
+ let u = jstr(entry, "username", "")
+ let p = jstr(entry, "password", "")
+ if u != "" || p != "" {
+ return Some(Creds::{ username: u, password: p })
+ }
+ }
+ _ => ()
+ }
+ }
+ }
+ _ => ()
+ }
+ let store = jstr(top, "credsStore", "")
+ if store != "" {
+ match creds_from_helper(store, host) {
+ Some(c) => return Some(c)
+ None =>
+ if is_docker_hub_host(normalize_host(host)) {
+ return creds_from_helper(store, "https://index.docker.io/v1/")
+ }
+ }
+ }
+ None
+}
+
+///|
+async fn load_creds(host : String) -> Creds? noraise {
+ let nhost = normalize_host(host)
+ if nhost == "" {
+ return None
+ }
+ match load_creds_from_file(auth_file_path(orbit_root()), nhost) {
+ Some(c) => Some(c)
+ None => load_creds_from_file(docker_config_path(), nhost)
+ }
+}
+
+///|
+async fn save_creds(
+ root : String,
+ host : String,
+ creds : Creds,
+) -> Unit raise OrbitError {
+ let nhost = normalize_host(host)
+ let path = auth_file_path(root)
+ let top = match read_text(path) {
+ Some(t) => parse_object(t, "auth.json")
+ None => Map([])
+ }
+ let auths : Map[String, Json] = match top.get("auths") {
+ Some(Json::Object(m)) => m
+ None => Map([])
+ _ => raise OrbitError("auth.json: expected 'auths' to be an object")
+ }
+ let stale : Array[String] = []
+ for k, _ in auths {
+ if host_matches(k, nhost) {
+ stale.push(k)
+ }
+ }
+ for k in stale {
+ auths.remove(k)
+ }
+ let entry : Map[String, Json] = Map([])
+ entry["auth"] = Json::string(encode_basic_auth(creds))
+ auths[nhost] = Json::object(entry)
+ top["auths"] = Json::object(auths)
+ @fs.mkdir(root, recursive=true, allow_exist=true) catch {
+ e => raise OrbitError("cannot create \{root}: \{e}")
+ }
+ write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
+}
+
+///|
+async fn remove_creds(root : String, host : String) -> Bool raise OrbitError {
+ let nhost = normalize_host(host)
+ let path = auth_file_path(root)
+ let text = match read_text(path) {
+ Some(t) => t
+ None => return false
+ }
+ let top = parse_object(text, "auth.json")
+ let auths : Map[String, Json] = match top.get("auths") {
+ Some(Json::Object(m)) => m
+ None => return false
+ _ => raise OrbitError("auth.json: expected 'auths' to be an object")
+ }
+ let matching : Array[String] = []
+ for k, _ in auths {
+ if host_matches(k, nhost) {
+ matching.push(k)
+ }
+ }
+ if matching.length() == 0 {
+ return false
+ }
+ for k in matching {
+ auths.remove(k)
+ }
+ top["auths"] = Json::object(auths)
+ write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
+ true
+}
+
+///|
+fn strip_trailing_cr(s : String) -> String {
+ let a = chars(s)
+ let mut end = a.length()
+ if end > 0 && a[end - 1] == '\r' {
+ end = end - 1
+ }
+ slice(a, 0, end)
+}
+
+///|
+fn strip_trailing_newlines(s : String) -> String {
+ let a = chars(s)
+ let mut end = a.length()
+ while end > 0 && (a[end - 1] == '\n' || a[end - 1] == '\r') {
+ end = end - 1
+ }
+ slice(a, 0, end)
+}
+
+///|
+async fn read_stdin_line() -> String raise OrbitError {
+ let line = @stdio.stdin.read_until("\n") catch {
+ e => raise OrbitError("cannot read stdin: \{e}")
+ }
+ match line {
+ Some(s) => strip_trailing_cr(s)
+ None => ""
+ }
+}
+
+///|
+async fn read_password_prompt() -> String raise OrbitError {
+ c_print_err(utf8_encode("Password: "))
+ let echo_disabled = c_set_echo(0) == 0
+ defer {
+ if echo_disabled {
+ ignore(c_set_echo(1))
+ c_print_err(utf8_encode("\n"))
+ }
+ }
+ read_stdin_line()
+}
+
+///|
+async fn resolve_login_plain_http(
+ raw_host : String,
+ host : String,
+ plain_http_flag : Bool,
+) -> Bool raise OrbitError {
+ let lower = ascii_lower(trim(raw_host))
+ if plain_http_flag || has_prefix(lower, "http://") {
+ return true
+ }
+ if has_prefix(lower, "https://") {
+ return false
+ }
+ let ctx = load_ctx()
+ for ch in ctx.channels {
+ let (ch_host, _) = split_first(ch.url, '/')
+ if host_matches(ch_host, host) && ch.plain_http {
+ return true
+ }
+ }
+ false
+}
+
+///|
+async fn cmd_login(
+ raw_host : String,
+ username_opt : String?,
+ password_opt : String?,
+ password_stdin : Bool,
+ plain_http_flag : Bool,
+) -> Unit raise OrbitError {
+ if password_opt is Some(_) && password_stdin {
+ raise OrbitError("use either --password or --password-stdin, not both")
+ }
+ let host = normalize_host(raw_host)
+ if host == "" || has_char(host, ' ') || has_char(host, '\t') {
+ raise OrbitError("invalid registry host '\{raw_host}'")
+ }
+ let plain_http = resolve_login_plain_http(raw_host, host, plain_http_flag)
+ let username = match username_opt {
+ Some(u) => u
+ None => {
+ c_print_err(utf8_encode("Username: "))
+ trim(read_stdin_line())
+ }
+ }
+ let password = if password_stdin {
+ let raw = @stdio.stdin.read_all().text() catch {
+ e => raise OrbitError("cannot read password from stdin: \{e}")
+ }
+ strip_trailing_newlines(raw)
+ } else {
+ match password_opt {
+ Some(p) => p
+ None => read_password_prompt()
+ }
+ }
+ if username == "" && password == "" {
+ raise OrbitError("username or password is required")
+ }
+ let creds = Creds::{ username, password }
+ with_spinner("Logging in to \{host}", () => {
+ verify_login(host, plain_http, creds)
+ })
+ save_creds(orbit_root(), host, creds)
+ println("Login succeeded for \{host}")
+}
+
+///|
+async fn cmd_logout(raw_host : String) -> Unit raise OrbitError {
+ let host = normalize_host(raw_host)
+ if host == "" {
+ raise OrbitError("invalid registry host '\{raw_host}'")
+ }
+ if remove_creds(orbit_root(), host) {
+ println("Removed credentials for \{host}")
+ } else {
+ println("No stored credentials for \{host}")
+ }
+ let docker_path = docker_config_path()
+ match load_creds_from_file(docker_path, host) {
+ Some(_) =>
+ println("note: credentials for \{host} still exist in \{docker_path}")
+ None => ()
+ }
+}
+
+///|
+test "host normalization and matching" {
+ assert_eq(normalize_host("https://git.site.latha.org/nandi"), "git.site.latha.org")
+ assert_eq(normalize_host("http://localhost:5000/"), "localhost:5000")
+ assert_true(host_matches("https://index.docker.io/v1/", "registry-1.docker.io"))
+ assert_true(host_matches("docker.io", "index.docker.io"))
+ assert_false(host_matches("ghcr.io", "git.site.latha.org"))
+}
+
+///|
+test "basic auth encode and decode roundtrip" {
+ let c = Creds::{ username: "nandi", password: "s:e:c/r+e=t" }
+ let b64 = encode_basic_auth(c)
+ let decoded = decode_basic_auth(b64).unwrap()
+ assert_eq(decoded.username, "nandi")
+ assert_eq(decoded.password, "s:e:c/r+e=t")
+ assert_true(decode_basic_auth("not-valid-b64!!!") is None)
+ assert_true(decode_basic_auth(@base64.encode(b"nocolon"[:])) is None)
+}
+
+///|
+async test "save and remove credentials in auth.json" {
+ let root = @fs.tmpdir(prefix="orbit-auth-test-")
+ defer (@fs.rmdir(root, recursive=true, allow_missing=true) catch { _ => () })
+ let c = Creds::{ username: "alice", password: "secret" }
+ save_creds(root, "https://git.site.latha.org", c)
+ let loaded = load_creds_from_file(auth_file_path(root), "git.site.latha.org")
+ guard loaded is Some(got) else { fail("expected saved credentials") }
+ assert_eq(got.username, "alice")
+ assert_eq(got.password, "secret")
+ assert_true(remove_creds(root, "git.site.latha.org"))
+ assert_true(
+ load_creds_from_file(auth_file_path(root), "git.site.latha.org") is None,
+ )
+ assert_false(remove_creds(root, "git.site.latha.org"))
+}
diff --git a/src/main/channels.mbt b/src/main/channels.mbt
index bb7cad1..4a05cec 100644
--- a/src/main/channels.mbt
+++ b/src/main/channels.mbt
@@ -349,9 +349,9 @@ test "channel spec" {
///|
test "only a missing repository falls through to the next channel" {
- assert_true(is_missing_repo("Error response from registry: name unknown"))
- assert_true(is_missing_repo("GET \"u\": response status code 404: Not Found"))
- assert_false(is_missing_repo("dial tcp: lookup x: no such host"))
- assert_false(is_missing_repo("connect: connection refused"))
- assert_false(is_missing_repo("response status code 401: Unauthorized"))
+ assert_true(is_missing_status(404))
+ assert_false(is_missing_status(401))
+ assert_false(is_missing_status(403))
+ assert_false(is_missing_status(500))
+ assert_false(is_missing_status(502))
}
diff --git a/src/main/main.mbt b/src/main/main.mbt
index a76c1b8..92acc9f 100644
--- a/src/main/main.mbt
+++ b/src/main/main.mbt
@@ -1,11 +1,14 @@
-// orbit: a package manager whose repository is any OCI registry, via ORAS.
+// orbit: a package manager whose repository is any OCI registry.
///|
let usage : String =
- #|orbit - packages as OCI artifacts (via oras)
+ #|orbit - packages as OCI artifacts
#|
#|usage:
#| orbit init create folders and config.toml
+ #| orbit login [-u ] [-p | --password-stdin] [--plain-http]
+ #| log in to an OCI registry
+ #| orbit logout remove stored registry credentials
#| orbit channel list channels, highest priority first
#| orbit channel add [--plain-http]
#| orbit publish [--channel ] [--no-latest]
@@ -24,9 +27,9 @@ let usage : String =
#|
#|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 *
#|config: /config.toml
+ #|credentials: /auth.json (falls back to ~/.docker/config.json)
#|environment: ORBIT_ROOT (default ~/.orbit); ORBIT_REGISTRY and
#| ORBIT_PLAIN_HTTP=1 override the built-in main channel
- #|authentication: run `oras login ` once.
///|
/// Create the directories, and a config.toml if there is no config yet.
@@ -69,18 +72,47 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
let pos : Array[String] = []
let flags : Array[String] = []
let mut publish_to = MAIN_CHANNEL
+ let mut username : String? = None
+ let mut password : String? = None
let mut i = 1
while i < args.length() {
- if args[i] == "--channel" {
+ let a = args[i]
+ if a == "--channel" {
if cmd != "publish" || i + 1 >= args.length() {
raise OrbitError("usage: orbit publish --channel ")
}
publish_to = args[i + 1]
i = i + 1
- } else if has_prefix(args[i], "--") {
- flags.push(args[i])
+ } else if a == "-u" || a == "--username" {
+ if cmd != "login" || i + 1 >= args.length() {
+ raise OrbitError(
+ "usage: orbit login [-u ] [-p | --password-stdin] [--plain-http]",
+ )
+ }
+ username = Some(args[i + 1])
+ i = i + 1
+ } else if has_prefix(a, "--username=") {
+ if cmd != "login" {
+ raise OrbitError("unknown flag '\{a}'")
+ }
+ username = Some(drop_chars(a, 11))
+ } else if a == "-p" || a == "--password" {
+ if cmd != "login" || i + 1 >= args.length() {
+ raise OrbitError(
+ "usage: orbit login [-u ] [-p | --password-stdin] [--plain-http]",
+ )
+ }
+ password = Some(args[i + 1])
+ i = i + 1
+ } else if has_prefix(a, "--password=") {
+ if cmd != "login" {
+ raise OrbitError("unknown flag '\{a}'")
+ }
+ password = Some(drop_chars(a, 11))
+ } else if has_prefix(a, "--") {
+ flags.push(a)
} else {
- pos.push(args[i])
+ pos.push(a)
}
i = i + 1
}
@@ -94,6 +126,24 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
}
cmd_init()
}
+ "login" => {
+ need(
+ pos,
+ 1,
+ "login [-u ] [-p | --password-stdin] [--plain-http]",
+ )
+ cmd_login(
+ pos[0],
+ username,
+ password,
+ flags.contains("--password-stdin"),
+ flags.contains("--plain-http"),
+ )
+ }
+ "logout" => {
+ need(pos, 1, "logout ")
+ cmd_logout(pos[0])
+ }
"channel" => {
need(pos, 1, "channel list|add")
match pos[0] {
@@ -141,10 +191,6 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
///|
async fn main {
- if sh("command -v oras >/dev/null 2>&1") != 0 {
- println("orbit: error: `oras` not found on PATH (https://oras.land)")
- c_exit(1)
- }
dispatch(cli_args()) catch {
OrbitError(msg) => {
println("orbit: error: \{msg}")
diff --git a/src/main/moon.pkg b/src/main/moon.pkg
index d0e8c77..120738a 100644
--- a/src/main/moon.pkg
+++ b/src/main/moon.pkg
@@ -1,11 +1,20 @@
import {
"moonbitlang/core/json",
+ "moonbitlang/core/encoding/base64",
+ "moonbitlang/core/encoding/hex",
+ "moonbitlang/core/encoding/percent",
"moonbit-community/toml",
"moonbitlang/async",
"moonbitlang/async/fs",
+ "moonbitlang/async/http",
"moonbitlang/async/process",
+ "moonbitlang/async/stdio",
}
+import {
+ "moonbitlang/async/socket",
+} for "wbtest"
+
pkgtype(kind: "executable")
options(
diff --git a/src/main/oci.mbt b/src/main/oci.mbt
new file mode 100644
index 0000000..70eba69
--- /dev/null
+++ b/src/main/oci.mbt
@@ -0,0 +1,858 @@
+// 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", ""))
+}
diff --git a/src/main/ops.mbt b/src/main/ops.mbt
index fd9a6c4..179a9af 100644
--- a/src/main/ops.mbt
+++ b/src/main/ops.mbt
@@ -230,7 +230,7 @@ async fn link_bins(
dir : String,
bins : Array[String],
) -> Unit raise OrbitError {
- @fs.mkdir(bin_dir(ctx), recursive=true) catch {
+ @fs.mkdir(bin_dir(ctx), recursive=true, allow_exist=true) catch {
e => raise OrbitError("cannot create bin dir: " + e.to_string())
}
for b in bins {
@@ -681,18 +681,16 @@ fn orbit_info(text : String) -> RepoInfo? {
/// Any failure counts as "not an Orbit package", so one broken repo can't hide
/// the others.
async fn orbit_repo_info(ch : Channel, repo : String) -> RepoInfo? noraise {
- let tags = lines(capture(oras(ch, "repo tags " + sq(repo_of(ch, repo))))) catch {
- _ => return None
+ let tags = match
+ (list_tags_quiet(ch, repo) catch { _ => return None }) {
+ Some(ts) => ts
+ None => return None
}
if tags.length() == 0 {
return None
}
let tag = if tags.contains("latest") { "latest" } else { tags[0] }
- let text = capture(
- oras(ch, "manifest fetch " + sq(repo_of(ch, repo) + ":" + tag)),
- ) catch {
- _ => return None
- }
+ let text = fetch_raw_manifest(ch, repo, tag) catch { _ => return None }
orbit_info(text)
}
@@ -789,10 +787,7 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
]
let mut listed = 0
for ch in ctx.channels {
- let out = capture(
- oras(ch, "repo ls " + sq(ch.url)),
- progress="Listing packages in \{ch.name}",
- ) catch {
+ let repos = list_repos(ch) catch {
_ => {
println("warning: channel '\{ch.name}' does not allow listing packages")
continue
@@ -800,7 +795,7 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
}
listed = listed + 1
let candidates : Array[String] = []
- for r in lines(out) {
+ for r in repos {
// A name with "/" is a nested channel namespace (e.g. example/greet under
// main), not a package name that `orbit install` could use.
if valid_name(r) && contains_str(r, term) {
diff --git a/src/main/registry.mbt b/src/main/registry.mbt
index 2119c11..99b459a 100644
--- a/src/main/registry.mbt
+++ b/src/main/registry.mbt
@@ -1,10 +1,4 @@
-// Everything that talks to the registry goes through the `oras` CLI.
-// Authentication is whatever `oras login` has stored.
-
-///|
-fn oras(ch : Channel, args : String) -> String {
- "oras " + args + (if ch.plain_http { " --plain-http" } else { "" })
-}
+// Native OCI Distribution v2 registry client operations.
///|
fn repo_of(ch : Channel, name : String) -> String {
@@ -12,39 +6,189 @@ fn repo_of(ch : Channel, name : String) -> String {
}
///|
-/// Whether oras output says the repository doesn't exist, as opposed to the
-/// registry being unreachable or refusing access.
-fn is_missing_repo(err : String) -> Bool {
- contains_str(err, "name unknown") ||
- contains_str(err, "response status code 404")
+fn channel_base_url(ch : Channel) -> String {
+ let (host, _) = split_channel_url(ch.url)
+ channel_scheme(ch) + "://" + host
+}
+
+///|
+fn channel_repo_path(ch : Channel, name : String) -> String {
+ let (_, ns) = split_channel_url(ch.url)
+ if ns == "" {
+ name
+ } else {
+ ns + "/" + name
+ }
+}
+
+///|
+/// Whether an HTTP status says the repository doesn't exist, as opposed to
+/// the registry being unreachable or refusing access.
+fn is_missing_status(code : Int32) -> Bool {
+ code == 404
+}
+
+///|
+async fn verify_login(
+ host : String,
+ plain_http : Bool,
+ creds : Creds,
+) -> Unit raise OrbitError {
+ let scheme = if plain_http { "http" } else { "https" }
+ let url = scheme + "://" + host + "/v2/"
+ let (resp, body) = oci_request(
+ Get,
+ url,
+ Map([("Accept", "application/json")]),
+ b"",
+ "",
+ creds_override=creds,
+ )
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "login to \{host} failed (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+ }
+}
+
+///|
+async fn list_repos(ch : Channel) -> Array[String] raise OrbitError {
+ with_spinner("Listing packages in \{ch.name}", () => {
+ let base = channel_base_url(ch)
+ let (_, ns) = split_channel_url(ch.url)
+ let ns_prefix = if ns == "" { "" } else { ns + "/" }
+ let out : Array[String] = []
+ let seen : Array[String] = []
+ let mut next_url : String? = Some(base + "/v2/_catalog")
+ while next_url is Some(url) {
+ if seen.contains(url) {
+ break
+ }
+ seen.push(url)
+ let (resp, body) = oci_request(
+ Get,
+ url,
+ Map([("Accept", "application/json")]),
+ b"",
+ "catalog",
+ )
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
+ )
+ }
+ let obj = parse_object(utf8_decode(body), "catalog")
+ let page = jstrs(obj, "repositories")
+ if page.length() == 0 {
+ break
+ }
+ for r in page {
+ if ns_prefix == "" {
+ out.push(r)
+ } else if has_prefix(r, ns_prefix) {
+ out.push(drop_chars(r, chars(ns_prefix).length()))
+ }
+ }
+ next_url = match resp.headers.get(hdr("Link")) {
+ Some(link) =>
+ match parse_next_link(link) {
+ Some(target) => {
+ let resolved = resolve_location(parse_url(url), target)
+ let full = resolved.scheme + "://" + resolved.host + resolved.path
+ if seen.contains(full) {
+ None
+ } else {
+ Some(full)
+ }
+ }
+ None => None
+ }
+ None => None
+ }
+ }
+ out
+ })
}
///|
/// The tags of `name` in a channel, or None if the channel doesn't have it.
/// Any other failure is an error: falling through to a lower priority channel
/// could install a different package with the same name.
-async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
- let errfile = trim(capture("mktemp"))
- let cmd = oras(ch, "repo tags " + sq(repo_of(ch, name))) + " 2>" + sq(errfile)
- let out = Some(
- capture(cmd, progress="Checking versions of \{ch.name}::\{name}"),
- ) catch {
- _ => None
- }
- let err = match read_text(errfile) {
- Some(t) => trim(t)
- None => ""
- }
- sh("rm -f " + sq(errfile)) |> ignore
- match out {
- Some(o) => Some(lines(o))
- None =>
- if is_missing_repo(err) {
- None
- } else {
- raise OrbitError("channel '\{ch.name}' (\{ch.url}): \{err}")
+async fn list_tags_inner(
+ ch : Channel,
+ name : String,
+) -> Array[String]? raise OrbitError {
+ let base = channel_base_url(ch)
+ let repo = channel_repo_path(ch, name)
+ let scope_key = repo + ":pull"
+ let out : Array[String] = []
+ let seen : Array[String] = []
+ let mut next_url : String? = Some(base + "/v2/" + repo + "/tags/list")
+ let mut first = true
+ while next_url is Some(url) {
+ if seen.contains(url) {
+ break
+ }
+ seen.push(url)
+ let (resp, body) = oci_request(
+ Get,
+ url,
+ Map([("Accept", "application/json")]),
+ b"",
+ scope_key,
+ )
+ if first && is_missing_status(resp.code) {
+ return None
+ }
+ first = false
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
+ )
+ }
+ let obj = parse_object(utf8_decode(body), "tags/list")
+ let page = jstrs(obj, "tags")
+ if page.length() == 0 {
+ break
+ }
+ for t in page {
+ if !out.contains(t) {
+ out.push(t)
}
+ }
+ next_url = match resp.headers.get(hdr("Link")) {
+ Some(link) =>
+ match parse_next_link(link) {
+ Some(target) => {
+ let resolved = resolve_location(parse_url(url), target)
+ let full = resolved.scheme + "://" + resolved.host + resolved.path
+ if seen.contains(full) {
+ None
+ } else {
+ Some(full)
+ }
+ }
+ None => None
+ }
+ None => None
+ }
}
+ Some(out)
+}
+
+///|
+async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
+ with_spinner("Checking versions of \{ch.name}::\{name}", () => {
+ list_tags_inner(ch, name)
+ })
+}
+
+///|
+async fn list_tags_quiet(
+ ch : Channel,
+ name : String,
+) -> Array[String]? raise OrbitError {
+ list_tags_inner(ch, name)
}
///|
@@ -53,16 +197,91 @@ async fn resolve_digest(
name : String,
tag : String,
) -> String raise OrbitError {
- let d = trim(
- capture(
- oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag)),
- progress="Resolving \{ch.name}::\{name}@\{tag}",
- ),
+ with_spinner("Resolving \{ch.name}::\{name}@\{tag}", () => {
+ let repo = channel_repo_path(ch, name)
+ let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + tag
+ let scope_key = repo + ":pull"
+ let req_headers = Map([("Accept", MANIFEST_ACCEPT)])
+ let (head_resp, head_body) = oci_request(
+ Head,
+ url,
+ req_headers,
+ b"",
+ scope_key,
+ )
+ let mut digest = if head_resp.code >= 200 && head_resp.code < 300 {
+ extract_digest_header(head_resp.headers).unwrap_or("")
+ } else {
+ ""
+ }
+ if head_resp.code == 405 ||
+ (head_resp.code >= 200 && head_resp.code < 300 && digest == "") {
+ let (get_resp, get_body) = oci_request(
+ Get,
+ url,
+ req_headers,
+ b"",
+ scope_key,
+ )
+ if get_resp.code < 200 || get_resp.code >= 300 {
+ raise OrbitError(
+ "cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(get_resp.code, get_resp.reason, get_body)}",
+ )
+ }
+ digest = match extract_digest_header(get_resp.headers) {
+ Some(d) => d
+ None => sha256_digest(get_body)
+ }
+ } else if head_resp.code < 200 || head_resp.code >= 300 {
+ raise OrbitError(
+ "cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(head_resp.code, head_resp.reason, head_body)}",
+ )
+ }
+ if !(has_prefix(digest, "sha256:") || has_prefix(digest, "sha512:")) {
+ raise OrbitError("unexpected digest for \{name}:\{tag}: '\{digest}'")
+ }
+ digest
+ })
+}
+
+///|
+async fn fetch_raw_manifest_bytes(
+ ch : Channel,
+ name : String,
+ ref_str : String,
+) -> Bytes raise OrbitError {
+ let repo = channel_repo_path(ch, name)
+ let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + ref_str
+ let (resp, body) = oci_request(
+ Get,
+ url,
+ Map([("Accept", MANIFEST_ACCEPT)]),
+ b"",
+ repo + ":pull",
)
- if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) {
- raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'")
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "cannot fetch manifest \{ch.name}::\{name}@\{ref_str}: \{format_oci_error(resp.code, resp.reason, body)}",
+ )
}
- d
+ if has_prefix(ref_str, "sha256:") {
+ let actual = sha256_digest(body)
+ if actual != ref_str {
+ raise OrbitError(
+ "manifest digest mismatch for \{name}@\{ref_str}: got \{actual}",
+ )
+ }
+ }
+ body
+}
+
+///|
+async fn fetch_raw_manifest(
+ ch : Channel,
+ name : String,
+ ref_str : String,
+) -> String raise OrbitError {
+ utf8_decode(fetch_raw_manifest_bytes(ch, name, ref_str))
}
///|
@@ -72,17 +291,83 @@ async fn fetch_manifest(
name : String,
digest : String,
) -> Manifest raise OrbitError {
- let text = capture(
- oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)),
- progress="Reading metadata for \{ch.name}::\{name}",
- )
- let m = parse_manifest(text)
- if m.name != name {
- raise OrbitError(
- "\{name}@\{digest} declares name '\{m.name}'; refusing to install",
+ with_spinner("Reading metadata for \{ch.name}::\{name}", () => {
+ let repo = channel_repo_path(ch, name)
+ let manifest_text = fetch_raw_manifest(ch, name, digest)
+ let manifest_obj = parse_object(manifest_text, "manifest")
+ let cfg_digest = match manifest_obj.get("config") {
+ Some(Json::Object(c)) => jstr(c, "digest", "")
+ _ => ""
+ }
+ if cfg_digest == "" {
+ raise OrbitError("\{name}@\{digest} manifest missing config.digest")
+ }
+ let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + cfg_digest
+ let (resp, body) = oci_request(
+ Get,
+ blob_url,
+ Map([("Accept", CONFIG_MEDIA_TYPE + ", application/json")]),
+ b"",
+ repo + ":pull",
)
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "cannot fetch config for \{name}@\{digest}: \{format_oci_error(resp.code, resp.reason, body)}",
+ )
+ }
+ if has_prefix(cfg_digest, "sha256:") {
+ let actual = sha256_digest(body)
+ if actual != cfg_digest {
+ raise OrbitError(
+ "config digest mismatch for \{name}@\{digest}: expected \{cfg_digest}, got \{actual}",
+ )
+ }
+ }
+ let m = parse_manifest(utf8_decode(body))
+ if m.name != name {
+ raise OrbitError(
+ "\{name}@\{digest} declares name '\{m.name}'; refusing to install",
+ )
+ }
+ m
+ })
+}
+
+///|
+fn find_pkg_layer_digest(manifest_obj : Map[String, Json]) -> String? {
+ let layers = match manifest_obj.get("layers") {
+ Some(Json::Array(xs)) => xs
+ _ => return None
}
- m
+ for item in layers {
+ match item {
+ Json::Object(l) =>
+ if jstr(l, "mediaType", "") == LAYER_MEDIA_TYPE {
+ let d = jstr(l, "digest", "")
+ if d != "" {
+ return Some(d)
+ }
+ }
+ _ => ()
+ }
+ }
+ for item in layers {
+ match item {
+ Json::Object(l) =>
+ match l.get("annotations") {
+ Some(Json::Object(ann)) =>
+ if jstr(ann, "org.opencontainers.image.title", "") == "pkg.tar.gz" {
+ let d = jstr(l, "digest", "")
+ if d != "" {
+ return Some(d)
+ }
+ }
+ _ => ()
+ }
+ _ => ()
+ }
+ }
+ None
}
///|
@@ -99,14 +384,39 @@ async fn fetch_into_store(
if exists(dir) {
return dir
}
+ let manifest_text = fetch_raw_manifest(ch, name, digest)
+ let manifest_obj = parse_object(manifest_text, "manifest")
+ let layer_digest = match find_pkg_layer_digest(manifest_obj) {
+ Some(d) => d
+ None => raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
+ }
+ let repo = channel_repo_path(ch, name)
+ let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + layer_digest
let tmp = ctx.root + "/tmp/" + name + "-" + store_id(digest)
sh_ok("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp + "/root"))
- sh_ok(
- oras(ch, "pull -o " + sq(tmp) + " " + sq(repo_of(ch, name) + "@" + digest)) +
- " >/dev/null",
- )
- if !exists(tmp + "/pkg.tar.gz") {
- raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
+ let dl_res : Result[Unit, Error] = try {
+ with_spinner("Downloading \{ch.name}::\{name}", () => {
+ oci_download_to_file(
+ blob_url,
+ tmp + "/pkg.tar.gz",
+ layer_digest,
+ repo + ":pull",
+ )
+ })
+ Ok(())
+ } catch {
+ e => Err(e)
+ }
+ match dl_res {
+ Ok(_) => ()
+ Err(OrbitError(msg)) => {
+ sh("rm -rf " + sq(tmp)) |> ignore
+ raise OrbitError(msg)
+ }
+ Err(e) => {
+ sh("rm -rf " + sq(tmp)) |> ignore
+ raise OrbitError(e.to_string())
+ }
}
sh_ok(
"tar -xzf " +
@@ -182,6 +492,164 @@ test "package config exposes Gitea labels and preserves Orbit metadata" {
)
}
+///|
+fn json_int64(n : Int64) -> Json {
+ Json::number(n.to_double(), repr=n.to_string())
+}
+
+///|
+fn append_digest_param(upload_url : String, digest : String) -> String {
+ let sep = if has_char(upload_url, '?') { "&" } else { "?" }
+ upload_url + sep + "digest=" + @percent.encode(digest)
+}
+
+///|
+async fn blob_exists(
+ base : String,
+ repo : String,
+ digest : String,
+) -> Bool raise OrbitError {
+ let url = base + "/v2/" + repo + "/blobs/" + digest
+ let (resp, body) = oci_request(Head, url, Map([]), b"", repo + ":pull")
+ if resp.code >= 200 && resp.code < 300 {
+ return true
+ }
+ if resp.code == 404 {
+ return false
+ }
+ raise OrbitError(
+ "blob check failed (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+}
+
+///|
+async fn start_blob_upload(base : String, repo : String) -> String raise OrbitError {
+ let init_url = base + "/v2/" + repo + "/blobs/uploads/"
+ let (resp, body) = oci_request(Post, init_url, Map([]), b"", repo + ":push")
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "failed to initiate blob upload (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+ }
+ let loc = match resp.headers.get(hdr("Location")) {
+ Some(l) => l
+ None => raise OrbitError("blob upload response missing Location header")
+ }
+ let resolved = resolve_location(parse_url(init_url), loc)
+ resolved.scheme + "://" + resolved.host + resolved.path
+}
+
+///|
+async fn upload_blob_bytes(
+ base : String,
+ repo : String,
+ digest : String,
+ data : Bytes,
+) -> Unit raise OrbitError {
+ if blob_exists(base, repo, digest) {
+ return
+ }
+ let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
+ let (resp, body) = oci_request(
+ Put,
+ upload_url,
+ Map([("Content-Type", "application/octet-stream")]),
+ data,
+ repo + ":push",
+ )
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "blob upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+ }
+}
+
+///|
+async fn upload_blob_file(
+ base : String,
+ repo : String,
+ digest : String,
+ path : String,
+ size : Int64,
+) -> Unit raise OrbitError {
+ if blob_exists(base, repo, digest) {
+ return
+ }
+ let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
+ let (resp, body) = oci_upload_file(
+ upload_url,
+ path,
+ size,
+ "application/octet-stream",
+ repo + ":push",
+ )
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "layer upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+ }
+}
+
+///|
+fn build_oci_manifest_bytes(
+ m : Manifest,
+ config_digest : String,
+ config_size : Int64,
+ layer_digest : String,
+ layer_size : Int64,
+) -> Bytes {
+ let cfg : Map[String, Json] = Map([])
+ cfg["mediaType"] = Json::string(CONFIG_MEDIA_TYPE)
+ cfg["digest"] = Json::string(config_digest)
+ cfg["size"] = json_int64(config_size)
+
+ let layer_ann : Map[String, Json] = Map([])
+ layer_ann["org.opencontainers.image.title"] = Json::string("pkg.tar.gz")
+ let layer : Map[String, Json] = Map([])
+ layer["mediaType"] = Json::string(LAYER_MEDIA_TYPE)
+ layer["digest"] = Json::string(layer_digest)
+ layer["size"] = json_int64(layer_size)
+ layer["annotations"] = Json::object(layer_ann)
+
+ let ann : Map[String, Json] = Map([])
+ ann["org.opencontainers.image.created"] = Json::string(utc_now())
+ ann["org.opencontainers.image.version"] = Json::string(m.version)
+ if m.description != "" {
+ ann["org.opencontainers.image.description"] = Json::string(m.description)
+ }
+
+ let manifest : Map[String, Json] = Map([])
+ manifest["schemaVersion"] = json_int64(2L)
+ manifest["mediaType"] = Json::string(OCI_MANIFEST_MEDIA_TYPE)
+ manifest["artifactType"] = Json::string(ORBIT_ARTIFACT_TYPE)
+ manifest["config"] = Json::object(cfg)
+ manifest["layers"] = Json::array([Json::object(layer)])
+ manifest["annotations"] = Json::object(ann)
+ utf8_encode(Json::object(manifest).stringify() + "\n")
+}
+
+///|
+async fn put_manifest(
+ base : String,
+ repo : String,
+ tag : String,
+ manifest_bytes : Bytes,
+) -> Unit raise OrbitError {
+ let url = base + "/v2/" + repo + "/manifests/" + tag
+ let (resp, body) = oci_request(
+ Put,
+ url,
+ Map([("Content-Type", OCI_MANIFEST_MEDIA_TYPE)]),
+ manifest_bytes,
+ repo + ":push",
+ )
+ if resp.code < 200 || resp.code >= 300 {
+ raise OrbitError(
+ "manifest push failed for tag '\{tag}' (\{format_oci_error(resp.code, resp.reason, body)})",
+ )
+ }
+}
+
///|
/// Pack `/files` and push it with the enriched Orbit config blob.
async fn publish(
@@ -204,39 +672,28 @@ async fn publish(
raise OrbitError("bin '\{b}' listed in orbit.json is missing from files/")
}
}
- let tmp = trim(capture("mktemp -d"))
- sh_ok(
- "tar -czf " +
- sq(tmp + "/pkg.tar.gz") +
- " --owner=0 --group=0 -C " +
- sq(files) +
- " .",
- )
- write_text_atomic(tmp + "/orbit.json", config)
- let tags = if also_latest { m.version + ",latest" } else { m.version }
- let push = oras(
- ch,
- "push " +
- sq(repo_of(ch, m.name) + ":" + tags) +
- " --artifact-type " +
- sq(ORBIT_ARTIFACT_TYPE) +
- " --config " +
- sq("orbit.json:" + CONFIG_MEDIA_TYPE) +
- " --annotation " +
- sq("org.opencontainers.image.version=" + m.version) +
- (if m.description != "" {
- " --annotation " +
- sq("org.opencontainers.image.description=" + m.description)
- } else {
- ""
- }) +
- " " +
- sq("pkg.tar.gz:" + LAYER_MEDIA_TYPE),
- )
- let rc = sh("cd " + sq(tmp) + " && " + push)
- sh("rm -rf " + sq(tmp)) |> ignore
- if rc != 0 {
- raise OrbitError("oras push failed (exit \{rc})")
+ let tmp = @fs.tmpdir(prefix="orbit-publish-") catch {
+ e => raise OrbitError("cannot create temp dir: \{e}")
}
+ defer (@fs.rmdir(tmp, recursive=true, allow_missing=true) catch { _ => () })
+ let pkg_path = tmp + "/pkg.tar.gz"
+ sh_ok("tar -czf " + sq(pkg_path) + " --owner=0 --group=0 -C " + sq(files) + " .")
+ let config_bytes = utf8_encode(config)
+ let config_digest = sha256_digest(config_bytes)
+ let config_size = config_bytes.length().to_int64()
+ let (layer_digest, layer_size) = sha256_file(pkg_path)
+ let base = channel_base_url(ch)
+ let repo = channel_repo_path(ch, m.name)
+ let manifest_bytes = build_oci_manifest_bytes(
+ m, config_digest, config_size, layer_digest, layer_size,
+ )
+ with_spinner("Publishing \{m.name} \{m.version} to \{ch.name}", () => {
+ upload_blob_bytes(base, repo, config_digest, config_bytes)
+ upload_blob_file(base, repo, layer_digest, pkg_path, layer_size)
+ put_manifest(base, repo, m.version, manifest_bytes)
+ if also_latest {
+ put_manifest(base, repo, "latest", manifest_bytes)
+ }
+ })
println("published \{m.name} \{m.version} to \{repo_of(ch, m.name)}")
}
diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt
new file mode 100644
index 0000000..cdd9528
--- /dev/null
+++ b/src/main/registry_wbtest.mbt
@@ -0,0 +1,376 @@
+// In-process mock OCI Distribution v2 integration tests.
+
+///|
+fn strip_query(path : String) -> (String, String) {
+ split_first(path, '?')
+}
+
+///|
+async test "native OCI publish, search catalog, tags pagination, resolve, and install" {
+ token_cache.clear()
+ let work = @fs.tmpdir(prefix="orbit-wb-reg-")
+ defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
+
+ // Stage a test package under work/pkg.
+ let pkg_dir = work + "/pkg"
+ @fs.mkdir(pkg_dir + "/files/bin", recursive=true)
+ @fs.write_file(
+ pkg_dir + "/orbit.json",
+ (
+ #|{
+ #| "name": "mytool",
+ #| "version": "1.2.0",
+ #| "description": "Mock OCI tool",
+ #| "documentation": "https://example.com/mytool",
+ #| "bin": ["bin/mytool"],
+ #| "depends": {}
+ #|}
+ ),
+ create_mode=CreateOrTruncate,
+ )
+ @fs.write_file(
+ pkg_dir + "/files/bin/mytool",
+ "#!/bin/sh\necho ok\n",
+ create_mode=CreateOrTruncate,
+ permission=0o755,
+ )
+
+ let blobs : Map[String, Bytes] = Map([])
+ let uploads : Map[String, String] = Map([])
+ let manifests : Map[String, (String, Bytes)] = Map([])
+ let tags : Array[String] = []
+ let mut upload_seq = 0
+ let head_405 = Ref(false)
+
+ let server = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ @async.with_task_group(group => {
+ defer server.close()
+ group.spawn_bg(no_wait=true, () => {
+ server.run_forever((req, body, conn) => {
+ let req_bytes = body.read_all().binary()
+ let (path, query) = strip_query(req.path)
+ if req.meth is Get && path == "/v2/_catalog" {
+ let payload = "{\"repositories\":[\"other/ignored\",\"pkgs/mytool\"]}"
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write(payload)
+ conn.end_response()
+ return
+ }
+ if req.meth is Get && path == "/v2/pkgs/mytool/tags/list" {
+ if query == "" {
+ let t0 = if tags.length() > 0 { tags[0] } else { "" }
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ "Link": "; rel=\"next\"",
+ })
+ conn.write("{\"name\":\"pkgs/mytool\",\"tags\":[\"" + t0 + "\"]}")
+ } else if query == "page=2" {
+ let t1 = if tags.length() > 1 { tags[1] } else { "" }
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ // Trailing Link header with next empty page (emulates Gitea).
+ "Link": "; rel=\"next\"",
+ })
+ conn.write("{\"name\":\"pkgs/mytool\",\"tags\":[\"" + t1 + "\"]}")
+ } else {
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write("{\"name\":\"pkgs/mytool\",\"tags\":null}")
+ }
+ conn.end_response()
+ return
+ }
+ if has_prefix(path, "/v2/pkgs/mytool/blobs/uploads/") {
+ if req.meth is Post {
+ upload_seq = upload_seq + 1
+ let id = upload_seq.to_string()
+ uploads[id] = "pkgs/mytool"
+ conn.send_response(202, "Accepted", extra_headers={
+ "Location": "/v2/pkgs/mytool/blobs/uploads/" + id,
+ })
+ conn.end_response()
+ return
+ }
+ if req.meth is Put {
+ let (_, dq) = split_first(query, '=')
+ let digest = @percent.decode(dq) catch { _ => "" }
+ blobs[digest] = req_bytes
+ conn.send_response(201, "Created", extra_headers={
+ "Docker-Content-Digest": digest,
+ })
+ conn.end_response()
+ return
+ }
+ }
+ if has_prefix(path, "/v2/pkgs/mytool/blobs/") {
+ let digest = drop_chars(path, 22)
+ match blobs.get(digest) {
+ Some(data) => {
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/octet-stream",
+ "Docker-Content-Digest": digest,
+ "Content-Length": data.length().to_string(),
+ })
+ if !(req.meth is Head) {
+ conn.write(data)
+ }
+ conn.end_response()
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ }
+ }
+ return
+ }
+ if has_prefix(path, "/v2/pkgs/mytool/manifests/") {
+ let ref_str = drop_chars(path, 26)
+ if req.meth is Put {
+ let d = sha256_digest(req_bytes)
+ manifests[ref_str] = (d, req_bytes)
+ manifests[d] = (d, req_bytes)
+ if !tags.contains(ref_str) {
+ tags.push(ref_str)
+ }
+ conn.send_response(201, "Created", extra_headers={
+ "Docker-Content-Digest": d,
+ })
+ conn.end_response()
+ return
+ }
+ if req.meth is Head && head_405.val {
+ conn.send_response(405, "Method Not Allowed")
+ conn.end_response()
+ return
+ }
+ match manifests.get(ref_str) {
+ Some((d, data)) => {
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": OCI_MANIFEST_MEDIA_TYPE,
+ "Docker-Content-Digest": d,
+ "Content-Length": data.length().to_string(),
+ })
+ if !(req.meth is Head) {
+ conn.write(data)
+ }
+ conn.end_response()
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ }
+ }
+ return
+ }
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ })
+ })
+
+ let addr = "127.0.0.1:" + server.addr.port().to_string()
+ let ch = Channel::{ name: "local", url: addr + "/pkgs", plain_http: true }
+ publish(ch, pkg_dir, true)
+
+ let repos = list_repos(ch)
+ assert_eq(repos, ["mytool"])
+
+ let got_tags = list_tags(ch, "mytool").unwrap()
+ assert_eq(got_tags, ["1.2.0", "latest"])
+
+ let d1 = resolve_digest(ch, "mytool", "1.2.0")
+ head_405.val = true
+ let d2 = resolve_digest(ch, "mytool", "1.2.0")
+ assert_eq(d1, d2)
+
+ let mf = fetch_manifest(ch, "mytool", d1)
+ assert_eq(mf.name, "mytool")
+ assert_eq(mf.version, "1.2.0")
+ assert_eq(mf.description, "Mock OCI tool")
+ assert_eq(mf.bins, ["bin/mytool"])
+
+ let orbit_dir = work + "/orbit"
+ let ctx = Ctx::{ root: orbit_dir, channels: [ch], state: Map([]) }
+ let installed_dir = fetch_into_store(ctx, ch, "mytool", d1)
+ assert_true(exists(installed_dir + "/bin/mytool"))
+ })
+}
+
+///|
+async test "Bearer token exchange, Basic auth login, and cross-origin redirect strip" {
+ token_cache.clear()
+ let work = @fs.tmpdir(prefix="orbit-wb-auth-")
+ defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
+
+ let payload = b"hello-blob-payload"
+ let payload_digest = sha256_digest(payload)
+ let cdn_auth_seen : Ref[String?] = Ref(None)
+
+ let cdn = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ let reg = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ @async.with_task_group(group => {
+ defer cdn.close()
+ defer reg.close()
+ let cdn_addr = "127.0.0.1:" + cdn.addr.port().to_string()
+ let reg_addr = "127.0.0.1:" + reg.addr.port().to_string()
+
+ group.spawn_bg(no_wait=true, () => {
+ cdn.run_forever((req, body, conn) => {
+ ignore(body.read_all())
+ cdn_auth_seen.val = req.headers.get(hdr("Authorization"))
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Length": payload.length().to_string(),
+ })
+ conn.write(payload)
+ conn.end_response()
+ })
+ })
+
+ group.spawn_bg(no_wait=true, () => {
+ reg.run_forever((req, body, conn) => {
+ ignore(body.read_all())
+ let (path, _) = strip_query(req.path)
+ let auth = req.headers.get(hdr("Authorization")).unwrap_or("")
+ if path == "/v2/token" {
+ let expected = "Basic " +
+ encode_basic_auth(Creds::{ username: "alice", password: "pw" })
+ if auth == expected {
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write("{\"token\":\"tok123\"}")
+ } else {
+ conn.send_response(401, "Unauthorized")
+ }
+ conn.end_response()
+ return
+ }
+ if path == "/v2/" {
+ if auth == "Bearer tok123" {
+ conn.send_response(200, "OK")
+ } else {
+ conn.send_response(401, "Unauthorized", extra_headers={
+ "WWW-Authenticate": "Bearer realm=\"http://" +
+ reg_addr +
+ "/v2/token\",service=\"test\",scope=\"*\"",
+ })
+ }
+ conn.end_response()
+ return
+ }
+ if path == "/v2/pkgs/a/blobs/" + payload_digest {
+ if auth == "Bearer tok123" {
+ conn.send_response(307, "Temporary Redirect", extra_headers={
+ "Location": "http://" + cdn_addr + "/blob-data",
+ })
+ } else {
+ conn.send_response(401, "Unauthorized", extra_headers={
+ "WWW-Authenticate": "Bearer realm=\"http://" +
+ reg_addr +
+ "/v2/token\",service=\"test\",scope=\"repository:pkgs/a:pull\"",
+ })
+ }
+ conn.end_response()
+ return
+ }
+ if path == "/v2/pkgs/a/blobs/sha256:0000" {
+ conn.send_response(200, "OK")
+ conn.write(b"corrupted-bytes")
+ conn.end_response()
+ return
+ }
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ })
+ })
+
+ verify_login(reg_addr, true, Creds::{ username: "alice", password: "pw" })
+
+ let bad_login = try {
+ verify_login(reg_addr, true, Creds::{ username: "alice", password: "bad" })
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(bad_login)
+
+ // Pre-seed token cache for reg_addr to verify cross-origin redirect strips Authorization.
+ token_cache[token_cache_key(reg_addr, "pkgs/a:pull")] = "tok123"
+ let dl_path = work + "/blob.bin"
+ oci_download_to_file(
+ "http://" + reg_addr + "/v2/pkgs/a/blobs/" + payload_digest,
+ dl_path,
+ payload_digest,
+ "pkgs/a:pull",
+ )
+ assert_true(cdn_auth_seen.val is None)
+ assert_eq(@fs.read_file(dl_path).binary(), payload)
+
+ let mismatch_err = try {
+ oci_download_to_file(
+ "http://" + reg_addr + "/v2/pkgs/a/blobs/sha256:0000",
+ work + "/bad.bin",
+ "sha256:0000",
+ "pkgs/a:pull",
+ )
+ false
+ } catch {
+ OrbitError(msg) => contains_str(msg, "digest mismatch")
+ }
+ assert_true(mismatch_err)
+ })
+}
+
+///|
+async test "channel locate falls through on 404 and fails on 500" {
+ token_cache.clear()
+ let mode1 = Ref(404)
+ let s1 = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ let s2 = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ @async.with_task_group(group => {
+ defer s1.close()
+ defer s2.close()
+ group.spawn_bg(no_wait=true, () => {
+ s1.run_forever((_req, body, conn) => {
+ ignore(body.read_all())
+ conn.send_response(mode1.val, "Status")
+ conn.end_response()
+ })
+ })
+ group.spawn_bg(no_wait=true, () => {
+ s2.run_forever((_req, body, conn) => {
+ ignore(body.read_all())
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write("{\"name\":\"c2/pkg\",\"tags\":[\"1.0.0\"]}")
+ conn.end_response()
+ })
+ })
+ let ch1 = Channel::{
+ name: "first",
+ url: "127.0.0.1:" + s1.addr.port().to_string() + "/c1",
+ plain_http: true,
+ }
+ let ch2 = Channel::{
+ name: "second",
+ url: "127.0.0.1:" + s2.addr.port().to_string() + "/c2",
+ plain_http: true,
+ }
+ let ctx = Ctx::{ root: "/tmp/unused", channels: [ch1, ch2], state: Map([]) }
+ let (picked, ts) = locate(ctx, "pkg", None)
+ assert_eq(picked.name, "second")
+ assert_eq(ts, ["1.0.0"])
+
+ mode1.val = 500
+ let failed = try {
+ ignore(locate(ctx, "pkg", None))
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(failed)
+ })
+}
diff --git a/src/main/sha256.mbt b/src/main/sha256.mbt
new file mode 100644
index 0000000..ccc6e1d
--- /dev/null
+++ b/src/main/sha256.mbt
@@ -0,0 +1,226 @@
+// Pure MoonBit streaming SHA-256 (FIPS 180-4).
+
+///|
+let sha256_k : FixedArray[UInt32] = [
+ 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U,
+ 0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
+ 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U,
+ 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
+ 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U,
+ 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
+ 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU,
+ 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
+ 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU,
+ 0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
+ 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U,
+]
+
+///|
+struct Sha256 {
+ state : FixedArray[UInt32]
+ block : FixedArray[Byte]
+ mut buf_len : Int32
+ mut total_len : UInt64
+}
+
+///|
+fn rotr(x : UInt32, n : Int32) -> UInt32 {
+ (x >> n) | (x << (32 - n))
+}
+
+///|
+fn Sha256::new() -> Sha256 {
+ {
+ state: [
+ 0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU,
+ 0x1f83d9abU, 0x5be0cd19U,
+ ],
+ block: FixedArray::make(64, b'\x00'),
+ buf_len: 0,
+ total_len: 0UL,
+ }
+}
+
+///|
+fn Sha256::compress(self : Sha256) -> Unit {
+ let w = FixedArray::make(64, 0U)
+ for i = 0; i < 16; i = i + 1 {
+ let j = i * 4
+ w[i] = (self.block[j].to_uint() << 24) |
+ (self.block[j + 1].to_uint() << 16) |
+ (self.block[j + 2].to_uint() << 8) |
+ self.block[j + 3].to_uint()
+ }
+ for i = 16; i < 64; i = i + 1 {
+ let x = w[i - 15]
+ let y = w[i - 2]
+ let s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
+ let s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >> 10)
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1
+ }
+ let mut a = self.state[0]
+ let mut b = self.state[1]
+ let mut c = self.state[2]
+ let mut d = self.state[3]
+ let mut e = self.state[4]
+ let mut f = self.state[5]
+ let mut g = self.state[6]
+ let mut h = self.state[7]
+ for i = 0; i < 64; i = i + 1 {
+ let s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
+ let ch = (e & f) ^ ((e ^ 0xFFFFFFFFU) & g)
+ let temp1 = h + s1 + ch + sha256_k[i] + w[i]
+ let s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
+ let maj = (a & b) ^ (a & c) ^ (b & c)
+ let temp2 = s0 + maj
+ h = g
+ g = f
+ f = e
+ e = d + temp1
+ d = c
+ c = b
+ b = a
+ a = temp1 + temp2
+ }
+ self.state[0] = self.state[0] + a
+ self.state[1] = self.state[1] + b
+ self.state[2] = self.state[2] + c
+ self.state[3] = self.state[3] + d
+ self.state[4] = self.state[4] + e
+ self.state[5] = self.state[5] + f
+ self.state[6] = self.state[6] + g
+ self.state[7] = self.state[7] + h
+}
+
+///|
+fn Sha256::push_byte(self : Sha256, byte : Byte) -> Unit {
+ self.block[self.buf_len] = byte
+ self.buf_len = self.buf_len + 1
+ self.total_len = self.total_len + 1UL
+ if self.buf_len == 64 {
+ self.compress()
+ self.buf_len = 0
+ }
+}
+
+///|
+fn Sha256::update_bytes(self : Sha256, data : Bytes) -> Unit {
+ for i = 0; i < data.length(); i = i + 1 {
+ self.push_byte(data[i])
+ }
+}
+
+///|
+fn Sha256::update_fixed(
+ self : Sha256,
+ data : FixedArray[Byte],
+ len : Int32,
+) -> Unit {
+ for i = 0; i < len; i = i + 1 {
+ self.push_byte(data[i])
+ }
+}
+
+///|
+fn Sha256::finish_hex(self : Sha256) -> String {
+ let bit_len = self.total_len * 8UL
+ self.block[self.buf_len] = b'\x80'
+ self.buf_len = self.buf_len + 1
+ if self.buf_len > 56 {
+ while self.buf_len < 64 {
+ self.block[self.buf_len] = b'\x00'
+ self.buf_len = self.buf_len + 1
+ }
+ self.compress()
+ self.buf_len = 0
+ }
+ while self.buf_len < 56 {
+ self.block[self.buf_len] = b'\x00'
+ self.buf_len = self.buf_len + 1
+ }
+ let len_bytes = bit_len.to_be_bytes()
+ for i = 0; i < 8; i = i + 1 {
+ self.block[56 + i] = len_bytes[i]
+ }
+ self.compress()
+ self.buf_len = 0
+ let digest = FixedArray::make(32, b'\x00')
+ for i = 0; i < 8; i = i + 1 {
+ let w = self.state[i]
+ let j = i * 4
+ digest[j] = (w >> 24).to_byte()
+ digest[j + 1] = (w >> 16).to_byte()
+ digest[j + 2] = (w >> 8).to_byte()
+ digest[j + 3] = w.to_byte()
+ }
+ @hex.encode(Bytes::makei(32, fn(i) { digest[i] })[:])
+}
+
+///|
+fn sha256_digest(data : Bytes) -> String {
+ let h = Sha256::new()
+ h.update_bytes(data)
+ "sha256:" + h.finish_hex()
+}
+
+///|
+async fn sha256_file(path : String) -> (String, Int64) raise OrbitError {
+ let file = @fs.open(path, mode=ReadOnly) catch {
+ e => raise OrbitError("cannot read \{path}: \{e}")
+ }
+ defer file.close()
+ let h = Sha256::new()
+ let buf = FixedArray::make(32768, b'\x00')
+ let mut total = 0L
+ for ;; {
+ let n = file.read(buf) catch {
+ e => raise OrbitError("cannot read \{path}: \{e}")
+ }
+ if n == 0 {
+ break
+ }
+ h.update_fixed(buf, n)
+ total = total + n.to_int64()
+ }
+ ("sha256:" + h.finish_hex(), total)
+}
+
+///|
+test "sha256 FIPS 180-4 vectors" {
+ assert_eq(
+ sha256_digest(b""),
+ "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ )
+ assert_eq(
+ sha256_digest(b"abc"),
+ "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+ )
+ let msg56 = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+ assert_eq(
+ sha256_digest(msg56),
+ "sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
+ )
+}
+
+///|
+test "sha256 chunked updates match single-shot across block boundaries" {
+ let payload = FixedArray::make(135, b'\x00')
+ for i = 0; i < payload.length(); i = i + 1 {
+ payload[i] = ((i * 31 + 7) & 0xFF).to_byte()
+ }
+ let full = Bytes::makei(payload.length(), fn(i) { payload[i] })
+ let expected = sha256_digest(full)
+ let h = Sha256::new()
+ let mut offset = 0
+ let chunk_sizes = [1, 7, 47, 1, 8, 64, 7]
+ for sz in chunk_sizes {
+ let part = FixedArray::make(sz, b'\x00')
+ for i = 0; i < sz; i = i + 1 {
+ part[i] = payload[offset + i]
+ }
+ h.update_fixed(part, sz)
+ offset = offset + sz
+ }
+ assert_eq(offset, payload.length())
+ assert_eq("sha256:" + h.finish_hex(), expected)
+}
diff --git a/src/main/stub.c b/src/main/stub.c
index 462848e..e313446 100644
--- a/src/main/stub.c
+++ b/src/main/stub.c
@@ -3,6 +3,8 @@
#include
#include
#include
+#include
+#include
#include "moonbit.h"
static char *to_cstr(moonbit_bytes_t b) {
@@ -49,3 +51,26 @@ void orbit_print_err(moonbit_bytes_t msg) {
fflush(stderr);
free(m);
}
+
+moonbit_bytes_t orbit_utc_now(void) {
+ time_t t = time(NULL);
+ struct tm tm_utc;
+ if (!gmtime_r(&t, &tm_utc)) {
+ return from_buf("1970-01-01T00:00:00Z", 20);
+ }
+ char buf[32];
+ size_t n = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm_utc);
+ return from_buf(buf, n);
+}
+
+int32_t orbit_set_echo(int32_t enable) {
+ if (!isatty(0)) return -1;
+ struct termios t;
+ if (tcgetattr(0, &t) != 0) return -1;
+ if (enable) {
+ t.c_lflag |= (tcflag_t)ECHO;
+ } else {
+ t.c_lflag &= ~(tcflag_t)ECHO;
+ }
+ return tcsetattr(0, TCSANOW, &t);
+}
diff --git a/src/main/sys.mbt b/src/main/sys.mbt
index baaf8c3..bf3420c 100644
--- a/src/main/sys.mbt
+++ b/src/main/sys.mbt
@@ -23,6 +23,12 @@ extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err"
#borrow(target, linkpath)
extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink"
+///|
+extern "C" fn c_utc_now() -> Bytes = "orbit_utc_now"
+
+///|
+extern "C" fn c_set_echo(enable : Int32) -> Int32 = "orbit_set_echo"
+
// ---------------------------------------------------------------- UTF-8
///|
@@ -209,19 +215,6 @@ fn trim(s : String) -> String {
slice(a, start, end)
}
-///|
-/// Non-empty, trimmed lines.
-fn lines(s : String) -> Array[String] {
- let out : Array[String] = []
- for l in split_on(s, '\n') {
- let t = trim(l)
- if t != "" {
- out.push(t)
- }
- }
- out
-}
-
///|
fn join(xs : Array[String], sep : String) -> String {
let sb = StringBuilder()
@@ -287,47 +280,6 @@ async fn spin(label : String) -> Unit noraise {
}
}
-///|
-/// Return stdout; stderr goes to the terminal unless captured. A label shows a
-/// braille spinner on a terminal while the command runs. The spinner is a child
-/// task that is cancelled as soon as the command finishes, so nothing keeps the
-/// group alive.
-async fn capture(cmd : String, progress~ : String = "") -> String raise OrbitError {
- let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
- let spinning = is_tty && progress != ""
- let res : Result[String, Error] = try {
- let out = @async.with_task_group(group => {
- let spinner = if spinning {
- Some(group.spawn(() => {
- ignore(@async.handle_cancellation(() => spin(progress)))
- }))
- } else {
- None
- }
- let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd])
- match spinner {
- Some(task) => task.cancel()
- None => ()
- }
- if spinning {
- c_print_err(utf8_encode("\r\u001B[2K"))
- }
- if code != 0 {
- raise OrbitError("command failed (exit \{code}): \{cmd}")
- }
- stdout.text()
- })
- Ok(out)
- } catch {
- e => Err(e)
- }
- match res {
- Ok(s) => s
- Err(OrbitError(msg)) => raise OrbitError(msg)
- Err(e) => raise OrbitError(e.to_string())
- }
-}
-
///|
async fn exists(path : String) -> Bool noraise {
try {
@@ -364,6 +316,83 @@ fn getenv(name : String) -> String {
utf8_decode(c_getenv(utf8_encode(name)))
}
+///|
+fn utc_now() -> String {
+ utf8_decode(c_utc_now())
+}
+
+///|
+async fn[T] with_spinner(
+ label : String,
+ f : async () -> T,
+) -> T raise OrbitError {
+ let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
+ if !is_tty || label == "" {
+ try f() catch {
+ OrbitError(msg) => raise OrbitError(msg)
+ e => raise OrbitError(e.to_string())
+ }
+ } else {
+ let res : Result[T, Error] = try {
+ let out = @async.with_task_group(group => {
+ let spinner = group.spawn(() => {
+ ignore(@async.handle_cancellation(() => spin(label)))
+ })
+ defer {
+ spinner.cancel()
+ c_print_err(utf8_encode("\r\u001B[2K"))
+ }
+ f()
+ })
+ Ok(out)
+ } catch {
+ e => Err(e)
+ }
+ match res {
+ Ok(v) => v
+ Err(OrbitError(msg)) => raise OrbitError(msg)
+ Err(e) => raise OrbitError(e.to_string())
+ }
+ }
+}
+
+///|
+async fn write_secret_atomic(
+ path : String,
+ text : String,
+) -> Unit raise OrbitError {
+ let tmp = path + ".tmp"
+ try {
+ @fs.write_file(tmp, text, create_mode=CreateOrTruncate, permission=0o600)
+ @fs.chmod(tmp, 0o600)
+ @fs.rename(tmp, path)
+ } catch {
+ e => raise OrbitError("cannot write " + path + ": " + e.to_string())
+ }
+}
+
+///|
+async fn run_with_stdin(
+ cmd : String,
+ args : Array[String],
+ stdin_text : String,
+) -> (Int32, String) raise OrbitError {
+ try {
+ @async.with_task_group(group => {
+ let (stdin, writer) = @process.write_to_process()
+ let runner = group.spawn(() => @process.collect_output(cmd, args, stdin~))
+ group.spawn_bg(allow_failure=true, () => {
+ defer writer.close()
+ writer.write(utf8_encode(stdin_text))
+ })
+ let (code, stdout, _) = runner.wait()
+ (code, stdout.text())
+ })
+ } catch {
+ e => raise OrbitError(e.to_string())
+ }
+}
+
///|
/// Command-line arguments without the program name (Linux: /proc/self/cmdline).
async fn cli_args() -> Array[String] noraise {