diff --git a/README.md b/README.md index bc6f9bf..27e1dd8 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,8 @@ See [examples/project](examples/project/README.md) for a working example project 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. +If a registry rejects the saved login, Orbit warns and reads anonymously, so public packages still work. Publishing always needs a valid login. When an anonymous read is refused or finds nothing, Orbit reports the rejected login instead of moving to the next channel, because the package may be private. + ## 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. @@ -250,4 +252,4 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp - There's no lock file for concurrent runs, and no install hooks, by design. - `orbit gc` only preserves global current and rollback builds (run `orbit install` / `orbit sync` in a project to re-populate missing store entries from its `orbit.lock`). - `orbit info ` reads globally installed package details without contacting the registry. Use `orbit versions ` to check published versions. -- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions ` if you already know the package name. +- `search` needs the registry's catalog API (Gitea has it, also without a login). If a registry doesn't offer it, use `orbit versions `. diff --git a/src/main/auth.mbt b/src/main/auth.mbt index cd610ef..01cb1cf 100644 --- a/src/main/auth.mbt +++ b/src/main/auth.mbt @@ -195,15 +195,19 @@ async fn load_creds_from_file(path : String, host : String) -> Creds? noraise { } ///| -async fn load_creds(host : String) -> Creds? noraise { +/// The saved login for a host and the file it came from. +async fn load_creds(host : String) -> (Creds, String)? 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) + for path in [auth_file_path(orbit_root()), docker_config_path()] { + match load_creds_from_file(path, nhost) { + Some(c) => return Some((c, path)) + None => () + } } + None } ///| diff --git a/src/main/oci.mbt b/src/main/oci.mbt index 70eba69..0324708 100644 --- a/src/main/oci.mbt +++ b/src/main/oci.mbt @@ -23,6 +23,11 @@ enum AuthChallenge { ///| let token_cache : Map[String, String] = Map([]) +///| +/// Hosts that rejected the saved login in this run, with the error to report +/// when anonymous access isn't enough. +let rejected_logins : Map[String, String] = Map([]) + ///| fn hdr(name : String) -> @http.CaseInsensitiveString { @http.CaseInsensitiveString(name) @@ -468,12 +473,7 @@ async fn raw_http_bytes( } ///| -async fn fetch_bearer_token( - realm : String, - service : String, - scope : String, - creds : Creds?, -) -> String raise OrbitError { +fn bearer_token_url(realm : String, service : String, scope : String) -> String { let mut token_url = realm let mut sep = if has_char(realm, '?') { "&" } else { "?" } if service != "" { @@ -483,6 +483,15 @@ async fn fetch_bearer_token( if scope != "" { token_url = token_url + sep + "scope=" + @percent.encode(scope) } + token_url +} + +///| +/// A token, or the HTTP status and message of the token endpoint's refusal. +async fn fetch_bearer_token( + token_url : String, + creds : Creds?, +) -> Result[String, (Int32, String)] raise OrbitError { let auth_header = creds.map(fn(c) { "Basic " + encode_basic_auth(c) }) let (_, resp, body) = raw_http_bytes( Get, @@ -492,22 +501,78 @@ async fn fetch_bearer_token( b"", ) if resp.code < 200 || resp.code >= 300 { - raise OrbitError( - "authentication failed (\{format_oci_error(resp.code, resp.reason, body)})", - ) + return Err((resp.code, 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 + return Ok(tok) } let access = jstr(obj, "access_token", "") if access != "" { - return access + return Ok(access) } raise OrbitError("token response missing token") } +///| +/// Get a token, retrying without the saved login if the registry rejects it +/// and the request only reads. `source` is the file the login came from. +async fn bearer_token_or_anonymous( + host : String, + token_url : String, + creds : Creds?, + source : String, + read_only : Bool, +) -> String raise OrbitError { + // Don't offer a login the host has already rejected again for every repo. + let creds = if read_only && source != "" && rejected_logins.contains(host) { + None + } else { + creds + } + let (code, msg) = match fetch_bearer_token(token_url, creds) { + Ok(tok) => return tok + Err(e) => e + } + if creds is None { + check_rejected_login(host, code) + } + if creds is None || source == "" || (code != 401 && code != 403) { + raise OrbitError("authentication failed (\{msg})") + } + let rejected = "\{host} rejected the login saved in \{source} (\{msg}); run `orbit login \{host}`" + if !read_only { + raise OrbitError(rejected) + } + match fetch_bearer_token(token_url, None) { + Ok(tok) => { + if !rejected_logins.contains(host) { + rejected_logins[host] = rejected + let start = if c_isatty(2) != 0 { "\r\u001B[2K" } else { "" } + c_print_err( + utf8_encode("\{start}warning: \{rejected}; reading anonymously\n"), + ) + } + tok + } + Err(_) => raise OrbitError(rejected) + } +} + +///| +/// After falling back to anonymous access, a refusal may only mean the package +/// is private. Report the rejected login rather than "missing", which would let +/// a lower priority channel supply a package with the same name. +fn check_rejected_login(host : String, code : Int32) -> Unit raise OrbitError { + if code == 401 || code == 403 || code == 404 { + match rejected_logins.get(host) { + Some(msg) => raise OrbitError(msg) + None => () + } + } +} + ///| async fn resolve_auth_retry( host : String, @@ -515,17 +580,28 @@ async fn resolve_auth_retry( used_cached : Bool, www_auth : String, creds_override : Creds?, + read_only : Bool, ) -> 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) + let (creds, source) = match creds_override { + Some(c) => (Some(c), "") + None => + match load_creds(host) { + Some((c, path)) => (Some(c), path) + None => (None, "") + } } match parse_www_authenticate(www_auth) { Bearer(realm, service, scope) => { - let tok = fetch_bearer_token(realm, service, scope, creds) + let tok = bearer_token_or_anonymous( + host, + bearer_token_url(realm, service, scope), + creds, + source, + read_only, + ) if creds_override is None && scope_key != "" { token_cache[token_cache_key(host, scope_key)] = tok } @@ -562,6 +638,9 @@ async fn oci_request( meth, url_str, headers, initial_auth, body, ) if resp.code != 401 { + if creds_override is None { + check_rejected_login(final_url.host, resp.code) + } return (resp, resp_body) } let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) { @@ -575,6 +654,7 @@ async fn oci_request( used_cached, www_auth, creds_override, + (meth is Get || meth is Head) && !scope_key.has_suffix(":push"), ) { Some(a) => a None => return (resp, resp_body) @@ -586,6 +666,9 @@ async fn oci_request( Some(retry_auth), body, ) + if creds_override is None { + check_rejected_login(final_url.host, retry_resp.code) + } (retry_resp, retry_body) } @@ -686,7 +769,14 @@ async fn oci_download_to_file( match resp.headers.get(hdr("WWW-Authenticate")) { Some(www_auth) => match - resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) { + resolve_auth_retry( + final_url.host, + scope_key, + used_cached, + www_auth, + None, + true, + ) { Some(retry_auth) => { let (_, retry_resp, retry_err) = try_download_once( url_str, @@ -697,6 +787,7 @@ async fn oci_download_to_file( if retry_resp.code >= 200 && retry_resp.code < 300 { return } + check_rejected_login(final_url.host, retry_resp.code) raise OrbitError( "download failed (\{format_oci_error(retry_resp.code, retry_resp.reason, retry_err)})", ) @@ -706,6 +797,7 @@ async fn oci_download_to_file( None => () } } + check_rejected_login(final_url.host, resp.code) raise OrbitError( "download failed (\{format_oci_error(resp.code, resp.reason, err_body)})", ) @@ -789,7 +881,14 @@ async fn oci_upload_file( None => return (resp, resp_body) } let retry_auth = match - resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) { + resolve_auth_retry( + final_url.host, + scope_key, + used_cached, + www_auth, + None, + false, + ) { Some(a) => a None => return (resp, resp_body) } diff --git a/src/main/ops.mbt b/src/main/ops.mbt index dad56b8..eb40292 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -875,8 +875,8 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { let mut listed = 0 for ch in ctx.channels { let repos = list_repos(ch) catch { - _ => { - println("warning: channel '\{ch.name}' does not allow listing packages") + OrbitError(msg) => { + println("warning: cannot list channel '\{ch.name}': \{msg}") continue } } @@ -913,7 +913,7 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { } if listed == 0 { raise OrbitError( - "no channel allows listing packages (catalog API); try `orbit versions `", + "no channel could be listed; if you know the package name, try `orbit versions `", ) } if rows.length() == 1 { diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt index f5aaa29..3fc8b08 100644 --- a/src/main/registry_wbtest.mbt +++ b/src/main/registry_wbtest.mbt @@ -870,3 +870,63 @@ async test "Pixi-style project workflow: new, add, sync --locked, run, update, r e => raise e } } + +///| +async test "a rejected login falls back to anonymous for reads only" { + token_cache.clear() + rejected_logins.clear() + let anonymous_ok = Ref(true) + let anonymous_calls = Ref(0) + 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) => { + ignore(body.read_all()) + let has_login = req.headers.get(hdr("Authorization")) is Some(_) + if !has_login { + anonymous_calls.val = anonymous_calls.val + 1 + } + if !has_login && anonymous_ok.val { + conn.send_response(200, "OK") + conn.write("{\"token\":\"anon\"}") + } else { + conn.send_response(401, "Unauthorized") + } + conn.end_response() + }) + }) + let host = "127.0.0.1:" + server.addr.port().to_string() + let url = "http://" + host + "/token" + let creds = Some(Creds::{ username: "u", password: "stale" }) + let fails = async fn(source : String, read_only : Bool) { + try { + ignore(bearer_token_or_anonymous(host, url, creds, source, read_only)) + false + } catch { + OrbitError(_) => true + } + } + // Writes and `orbit login` (no source file) never go anonymous. + assert_true(fails("auth.json", false)) + assert_true(fails("", true)) + assert_eq(anonymous_calls.val, 0) + check_rejected_login(host, 404) + // Reads do, but a later 404 is then reported as the rejected login. + assert_eq( + bearer_token_or_anonymous(host, url, creds, "auth.json", true), + "anon", + ) + check_rejected_login(host, 200) + let blocked = try { + check_rejected_login(host, 404) + false + } catch { + OrbitError(msg) => contains_str(msg, "orbit login") + } + assert_true(blocked) + anonymous_ok.val = false + assert_true(fails("auth.json", true)) + }) + rejected_logins.clear() +}