From 67c69e7e7110030f00a95704ea486bc137e91e20 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:15:46 +0000 Subject: [PATCH] pull: gated and private repos come down with a Hugging Face token, sent only to the hub's own host The token is HF_TOKEN, then HUGGING_FACE_HUB_TOKEN, then the one token file the hf tools read: HF_TOKEN_PATH, else $HF_HOME/token, else ~/.cache/huggingface/token. Pull follows redirects itself, so a hop to another scheme, host or port, such as the storage a download is redirected to, goes without it; std.http.Client keeps the header on such hops. A 401 or 403 from the hub names the repo and whether a token is missing or lacks access, and is not retried. --- docs/glm-5.3-exlr8.md | 3 +- docs/supported-models.md | 4 + zig/src/cli/cli.zig | 1 + zig/src/cli/hub.zig | 22 +- zig/src/cli/pull.zig | 75 +++-- zig/src/cli/pull_auth.zig | 156 ++++++++++ zig/src/cli/pull_auth_test.zig | 400 ++++++++++++++++++++++++++ zig/src/cli/pull_exlr8.zig | 27 +- zig/src/cli/pull_file.zig | 16 +- zig/src/cli/pull_parts.zig | 15 +- zig/src/cli/pull_runs.zig | 26 +- zig/src/cli/pull_test.zig | 30 +- zig/src/platform/environment.zig | 7 +- zig/src/platform/environment_test.zig | 5 +- 14 files changed, 693 insertions(+), 94 deletions(-) create mode 100644 zig/src/cli/pull_auth.zig create mode 100644 zig/src/cli/pull_auth_test.zig diff --git a/docs/glm-5.3-exlr8.md b/docs/glm-5.3-exlr8.md index 26159250e8..1c872625b9 100644 --- a/docs/glm-5.3-exlr8.md +++ b/docs/glm-5.3-exlr8.md @@ -30,7 +30,8 @@ tensorfold pull kindlingai/glm-5.3-exlr8-k2-k3-k4@f459f5d0272a529403dd9b3fd32f77 On the second Mac, pass `--node 1/2`. Every whole file must equal the hub's sha256, every expert file's published hash must equal the hub's, and each expert half must equal its xxhash64 before it is written. A pull that stops resumes: run the same command again, and it checks what is on disk and fetches only what is missing. Our two Macs took 43 -minutes over a shared uplink, at about 55 MiB/s each. +minutes over a shared uplink, at about 55 MiB/s each. A gated or private release needs a Hugging Face token, which a +node pull reads as `pull` does ([models on disk](supported-models.md#models-on-disk)). ## Serve diff --git a/docs/supported-models.md b/docs/supported-models.md index 20fa2f8f9c..3e16288ce6 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -87,6 +87,10 @@ It refuses a checkpoint whose `model_type` has no native family, and fetches the Each line gives the memory the engine keeps (weights, any drafter and a 2 GiB margin; context and caches take more) and a one-stream speed with drafts as shipped: measured on this chip, or `~` estimated from a measurement on another chip of the same backend, scaled by memory bandwidth. Quality is the share of TensorFold Web's 228-item quality suite the checkpoint answers right, greedy with thinking off, measured once a checkpoint with `tools/quality_suite.py`; each score's receipt is in [quality receipts](receipts/quality-suite/README.md), and `-` means not rated yet. The line under it installs the checkpoint. `--all` also lists what needs more memory, two machines or the other backend. Last come the cached checkpoints with a model type it knows. +A gated repo (one whose terms you accept on its Hugging Face page first, such as Llama or Gemma) or a private one needs your Hugging Face token. +`pull` reads `HF_TOKEN`, then `HUGGING_FACE_HUB_TOKEN`, then the one token file the `hf` tools read: the file `HF_TOKEN_PATH` names, else `$HF_HOME/token`, else `~/.cache/huggingface/token`, where `hf auth login` saves it. +It sends the token only to the hub's own host (`huggingface.co`, or the host of `HF_ENDPOINT`), never to the storage hosts the hub redirects downloads to, and never prints it. +When the hub refuses a repo, `pull` names it and says whether a token is missing or the token lacks access; without a token, Hugging Face refuses a mistyped repo name the same way. `models --json` prints one document for programs: `schema` 1 and `models`, each cached checkpoint's `repo`, `family` and `model_type` (`family` is a display title and `model_type` is the key to match on), plus `machine` and `catalog`, each entry's `need_bytes`, `fit`, `tok_s` (null when unmeasured), `quality` (passed, items, share, suite digest and receipt; null when unrated), `on_disk` and `install`. `tensorfold serve REPO` serves a cached checkpoint by its repository name. `rm REPO` removes a cached checkpoint with all its snapshots, blobs and refs, and then the repo's folder. diff --git a/zig/src/cli/cli.zig b/zig/src/cli/cli.zig index 848dfadbc7..8bfff15469 100644 --- a/zig/src/cli/cli.zig +++ b/zig/src/cli/cli.zig @@ -16,6 +16,7 @@ const usage = \\ tensorfold rm REPO[@REVISION] [--yes] [--dry-run] \\ tensorfold pull REPO[@REVISION] \\ tensorfold pull REPO[@REVISION] --exlr8 PROFILE --node R/N --dir DIR + \\ (a gated or private REPO: set HF_TOKEN, or log in with `hf auth login`) \\ tensorfold plan MODEL [--memory-gb GIB] [--ram GB]... \\ tensorfold merge MODEL ADAPTER OUT \\ tensorfold merge DENSE ADAPTER OUT --quantize SHIPPED diff --git a/zig/src/cli/hub.zig b/zig/src/cli/hub.zig index 51cf5e0c9c..54b9862eb9 100644 --- a/zig/src/cli/hub.zig +++ b/zig/src/cli/hub.zig @@ -42,18 +42,22 @@ pub fn family(model_type: []const u8) ?Family { return null; } +/// The value of `name` in `env`, or null when it is unset or there is no environment. +pub fn envValue(env: ?*const std.process.Environ.Map, name: []const u8) ?[]const u8 { + return if (env) |m| m.get(name) else null; +} + +/// The home directory: HOME, else USERPROFILE (Windows sets USERPROFILE, not HOME). +pub fn homeDir(env: ?*const std.process.Environ.Map) ?[]const u8 { + return envValue(env, "HOME") orelse envValue(env, "USERPROFILE"); +} + /// HF_HUB_CACHE, or HF_HOME/hub, or the default cache under the home directory. pub fn cacheDir(a: Allocator, env: ?*const std.process.Environ.Map, override: ?[]const u8) ![]const u8 { if (override) |o| return o; - const get = struct { - fn f(e: ?*const std.process.Environ.Map, name: []const u8) ?[]const u8 { - return if (e) |m| m.get(name) else null; - } - }.f; - if (get(env, "HF_HUB_CACHE")) |c| return c; - const home = get(env, "HOME") orelse get(env, "USERPROFILE") orelse ""; // Windows sets USERPROFILE, not HOME - if (get(env, "HF_HOME")) |h| return std.fs.path.join(a, &.{ h, "hub" }); - return std.fs.path.join(a, &.{ home, ".cache", "huggingface", "hub" }); + if (envValue(env, "HF_HUB_CACHE")) |c| return c; + if (envValue(env, "HF_HOME")) |h| return std.fs.path.join(a, &.{ h, "hub" }); + return std.fs.path.join(a, &.{ homeDir(env) orelse "", ".cache", "huggingface", "hub" }); } /// The repo's cache folder name: models--org--name. diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 177c4635fd..4837955c88 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -2,6 +2,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const hub = @import("hub.zig"); +const Auth = @import("pull_auth.zig").Auth; const ranged = @import("pull_parts.zig"); const single = @import("pull_file.zig"); const Entry = single.Entry; @@ -32,7 +33,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W try err_out.print("{s} is not a Hugging Face repo id (owner/name)\n", .{spec}); return 2; } - const endpoint = envValue(env, "HF_ENDPOINT") orelse "https://huggingface.co"; + const auth = try Auth.init(a, io, env, err_out) orelse return 1; const root = try hub.cacheDir(a, env, override); const w = std.Io.Dir.cwd(); try w.createDirPath(io, root); @@ -44,8 +45,9 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W var client = @import("pull_http.zig").client(a, io); defer client.deinit(); - const sha = resolveRevision(a, &client, out, endpoint, repo, revision) catch |e| switch (e) { + const sha = resolveRevision(a, &client, out, auth, repo, revision) catch |e| switch (e) { error.HubStatus => return 1, + error.HubDenied => return auth.refuse(err_out, repo), error.BadRevision => { try err_out.print("{s}@{s}: not a revision Hugging Face names (a branch, tag or 40-hex commit)\n", .{ repo, revision }); return 1; @@ -56,8 +58,9 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W }, }; - const entries = listTree(a, &client, endpoint, repo, sha) catch |e| switch (e) { + const entries = listTree(a, &client, auth, repo, sha) catch |e| switch (e) { error.HubStatus, error.NoConfig => return 1, + error.HubDenied => return auth.refuse(err_out, repo), else => { try err_out.print("{s}@{s}: the hub's file tree is unreachable ({t})\n", .{ repo, revision, e }); return 1; @@ -74,7 +77,10 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W try err_out.print("{s}: the hub tree has no config.json; refusing\n", .{repo}); return 1; } - const config_bytes = try fetchOne(a, &client, endpoint, repo, sha, "config.json"); + const config_bytes = fetchOne(a, &client, auth, repo, sha, "config.json") catch |e| switch (e) { + error.HubDenied => return auth.refuse(err_out, repo), + else => return e, + }; const kind = configKind(a, config_bytes); const model_type = kind.model_type; if (kind.drafter) { @@ -109,33 +115,39 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W try linkIntoSnapshot(a, io, snapshot_dir, e.path, blob_name); continue; } - const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ endpoint, repo, sha, e.path }); + const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ auth.endpoint, repo, sha, e.path }); if (e.sha256 != null and e.size >= sizes.threshold) { try big.append(a, .{ .entry = e, .blob = blob_name, .file = .{ .url = url, .path = try std.fmt.allocPrint(a, "{s}.ranges", .{blob_path}), .size = e.size } }); continue; } - const got = downloadRetrying(a, io, &client, out, url, blobs_dir, e) catch |err| { + const got = downloadRetrying(a, io, &client, auth, out, url, blobs_dir, e) catch |err| { + if (err == error.HubDenied) return auth.refuse(err_out, repo); try err_out.print(" {s}: the download failed ({t})\n", .{ e.path, err }); return 1; }; try linkIntoSnapshot(a, io, snapshot_dir, e.path, got); } - if (!try fetchBig(a, io, &client, out, err_out, blobs_dir, snapshot_dir, big.items, sizes.piece)) return 1; + const fetched = fetchBig(a, io, &client, auth, out, err_out, blobs_dir, snapshot_dir, big.items, sizes.piece) catch |e| switch (e) { + error.HubDenied => return auth.refuse(err_out, repo), + else => return e, + }; + if (!fetched) return 1; try w.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ refs_dir, "main" }), .data = sha }); try out.print("stored {s}@{s} at {s}\n", .{ repo, sha, snapshot_dir }); return 0; } /// The large files as pieces on one queue; each matches its sha256 before it becomes a blob, else it comes once more. -fn fetchBig(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, err_out: *std.Io.Writer, blobs_dir: []const u8, snapshot_dir: []const u8, big: []const Big, piece: u64) !bool { +fn fetchBig(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: *std.Io.Writer, err_out: *std.Io.Writer, blobs_dir: []const u8, snapshot_dir: []const u8, big: []const Big, piece: u64) !bool { if (big.len == 0) return true; const files = try a.alloc(ranged.File, big.len); for (files, big) |*f, b| f.* = b.file; - ranged.fetch(a, io, files, piece, out) catch |err| switch (err) { + ranged.fetch(a, io, files, piece, auth, out) catch |err| switch (err) { error.RangeUnsupported => { for (big) |b| { ranged.discard(a, io, b.file, piece); // the hub sent whole files: one stream each - const got = downloadRetrying(a, io, client, out, b.file.url, blobs_dir, b.entry) catch |e| { + const got = downloadRetrying(a, io, client, auth, out, b.file.url, blobs_dir, b.entry) catch |e| { + if (e == error.HubDenied) return e; try err_out.print(" {s}: the download failed ({t})\n", .{ b.entry.path, e }); return false; }; @@ -143,6 +155,7 @@ fn fetchBig(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Wri } return true; }, + error.HubDenied => return err, else => { try err_out.print(" the download failed ({t}); pull again to fetch only the missing pieces\n", .{err}); return false; @@ -151,7 +164,8 @@ fn fetchBig(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Wri for (big) |b| { if (!try matches(a, io, b)) { ranged.discard(a, io, b.file, piece); - ranged.fetch(a, io, &.{b.file}, piece, out) catch |err| { + ranged.fetch(a, io, &.{b.file}, piece, auth, out) catch |err| { + if (err == error.HubDenied) return err; try err_out.print(" {s}: the download failed ({t})\n", .{ b.entry.path, err }); return false; }; @@ -172,15 +186,11 @@ fn matches(a: Allocator, io: std.Io, b: Big) !bool { return std.mem.eql(u8, &(try ranged.digest(a, io, b.file.path, b.file.size)), &b.entry.sha256.?); } -pub fn envValue(env: ?*const std.process.Environ.Map, key: []const u8) ?[]const u8 { - return if (env) |m| m.get(key) else null; -} - /// The commit the hub serves for ``repo@revision``. -pub fn resolveRevision(a: Allocator, client: *std.http.Client, out: *std.Io.Writer, endpoint: []const u8, repo: []const u8, revision: []const u8) ![]const u8 { +pub fn resolveRevision(a: Allocator, client: *std.http.Client, out: *std.Io.Writer, auth: Auth, repo: []const u8, revision: []const u8) ![]const u8 { if (!revisionOk(revision)) return error.BadRevision; - const url = try std.fmt.allocPrint(a, "{s}/api/models/{s}/revision/{s}", .{ endpoint, repo, revision }); - const body = try getJson(a, client, url); + const url = try std.fmt.allocPrint(a, "{s}/api/models/{s}/revision/{s}", .{ auth.endpoint, repo, revision }); + const body = try getJson(a, client, auth, url); try out.print("[tensorfold] downloading {s}@{s} from Hugging Face\n", .{ repo, revision }); var parsed = std.json.parseFromSlice(std.json.Value, a, body, .{}) catch return error.BadHubJson; defer parsed.deinit(); @@ -193,9 +203,9 @@ pub fn resolveRevision(a: Allocator, client: *std.http.Client, out: *std.Io.Writ } /// The revision's files: path, size and the sha256 the hub states for LFS objects. -pub fn listTree(a: Allocator, client: *std.http.Client, endpoint: []const u8, repo: []const u8, sha: []const u8) ![]Entry { - const url = try std.fmt.allocPrint(a, "{s}/api/models/{s}/tree/{s}?recursive=true", .{ endpoint, repo, sha }); - const body = try getJson(a, client, url); +pub fn listTree(a: Allocator, client: *std.http.Client, auth: Auth, repo: []const u8, sha: []const u8) ![]Entry { + const url = try std.fmt.allocPrint(a, "{s}/api/models/{s}/tree/{s}?recursive=true", .{ auth.endpoint, repo, sha }); + const body = try getJson(a, client, auth, url); var parsed = std.json.parseFromSlice(std.json.Value, a, body, .{}) catch return error.BadHubJson; defer parsed.deinit(); if (parsed.value != .array) return error.BadHubJson; @@ -250,18 +260,23 @@ fn parseHex(comptime n: usize, text: []const u8) ?[n]u8 { } /// One small file fetched whole into memory. -fn fetchOne(a: Allocator, client: *std.http.Client, endpoint: []const u8, repo: []const u8, sha: []const u8, path: []const u8) ![]u8 { - const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ endpoint, repo, sha, path }); - var body: std.Io.Writer.Allocating = .init(a); - const result = client.fetch(.{ .location = .{ .url = url }, .response_writer = &body.writer }) catch return error.HubUnreachable; - if (result.status != .ok) return error.HubStatus; - return body.toOwnedSlice(); +fn fetchOne(a: Allocator, client: *std.http.Client, auth: Auth, repo: []const u8, sha: []const u8, path: []const u8) ![]u8 { + return getJson(a, client, auth, try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ auth.endpoint, repo, sha, path })); } -fn getJson(a: Allocator, client: *std.http.Client, url: []const u8) ![]u8 { +/// A hub answer's whole body, decompressed as a fetch would; error.HubDenied when the hub refused the request. +fn getJson(a: Allocator, client: *std.http.Client, auth: Auth, url: []const u8) ![]u8 { + const uri = std.Uri.parse(url) catch return error.HubUnreachable; + var req: std.http.Client.Request = undefined; + var redirect_buf: [8 << 10]u8 = undefined; + var response = auth.send(client, &req, .GET, uri, .{}, &redirect_buf) catch |e| return if (e == error.HubDenied) e else error.HubUnreachable; + defer req.deinit(); + if (response.head.status != .ok) return error.HubStatus; + const window: []u8 = if (response.head.content_encoding == .identity) &.{} else try a.alloc(u8, std.compress.flate.max_window_len); + var transfer: [64]u8 = undefined; + var decompress: std.http.Decompress = undefined; var body: std.Io.Writer.Allocating = .init(a); - const result = client.fetch(.{ .location = .{ .url = url }, .response_writer = &body.writer }) catch return error.HubUnreachable; - if (result.status != .ok) return error.HubStatus; + _ = response.readerDecompressing(&transfer, &decompress, window).streamRemaining(&body.writer) catch return error.HubUnreachable; return body.toOwnedSlice(); } diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig new file mode 100644 index 0000000000..55b22b4926 --- /dev/null +++ b/zig/src/cli/pull_auth.zig @@ -0,0 +1,156 @@ +//! The Hugging Face token for gated and private repos: where pull reads it, the one origin it goes to, the refusals. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const http = std.http; +const hub = @import("hub.zig"); +const environment = @import("sys").environment; + +/// The hub pull talks to when HF_ENDPOINT names none. +pub const default_endpoint = "https://huggingface.co"; +/// The most bytes a token may have. +const max_token = 4096; + +/// A token and where it came from: an environment variable's name or a file's path, never the token itself. +pub const Token = struct { value: []const u8, source: []const u8 }; + +/// The hub endpoint pull talks to, and the token that only requests to that endpoint's own origin carry. +pub const Auth = struct { + /// What request URLs are built on: HF_ENDPOINT, else the public hub. + endpoint: []const u8 = default_endpoint, + /// "Bearer TOKEN", or null when no token is set. + bearer: ?[]const u8 = null, + /// The token's source, which a refusal names in the token's place. + source: []const u8 = "", + + /// The hub from HF_ENDPOINT and the first token set; null once `err_out` names a token pull cannot send. + pub fn init(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, err_out: *std.Io.Writer) !?Auth { + var auth: Auth = .{ .endpoint = hub.envValue(env, "HF_ENDPOINT") orelse default_endpoint }; + var problem: []const u8 = ""; + const found = token(a, io, env, &problem) catch |e| switch (e) { + error.BadToken => { + try err_out.print("{s}\n", .{problem}); + return null; + }, + else => return e, + }; + if (found) |t| { + auth.bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{t.value}); + auth.source = t.source; + } + return auth; + } + + /// Whether `uri` is on the endpoint's own origin: the same scheme, host and port. + pub fn owns(auth: Auth, uri: std.Uri) bool { + var mine: [255]u8 = undefined; + var theirs: [255]u8 = undefined; + const own = origin(std.Uri.parse(auth.endpoint) catch return false, &mine) orelse return false; + const other = origin(uri, &theirs) orelse return false; + return std.ascii.eqlIgnoreCase(own.scheme, other.scheme) and std.ascii.eqlIgnoreCase(own.host, other.host) and own.port == other.port; + } + + /// The Authorization a request to `uri` sends: the token on the endpoint's origin, the client's default elsewhere. + pub fn header(auth: Auth, uri: std.Uri) http.Client.Request.Headers.Value { + const bearer = auth.bearer orelse return .default; + return if (auth.owns(uri)) .{ .override = bearer } else .default; + } + + /// One bodiless request into `req`, redirects followed here so each hop decides the token anew; see `header`. + pub fn send(auth: Auth, client: *http.Client, req: *http.Client.Request, method: http.Method, uri: std.Uri, options: http.Client.RequestOptions, buf: []u8) !http.Client.Response { + var o = options; + o.redirect_behavior = .unhandled; + var left = options.redirect_behavior; + var at = uri; + var rest = buf; + while (true) { + o.headers.authorization = auth.header(at); + req.* = try client.request(method, at, o); + errdefer req.deinit(); + try req.sendBodiless(); + const response = try req.receiveHead(&.{}); + const status = response.head.status; + if ((status == .unauthorized or status == .forbidden) and auth.owns(at)) return error.HubDenied; + if (status.class() != .redirect or left == .unhandled) return response; + if (left == .not_allowed) return error.TooManyHttpRedirects; + const location = response.head.location orelse return error.HttpRedirectLocationMissing; + if (location.len > rest.len) return error.HttpRedirectLocationOversize; + @memcpy(rest[0..location.len], location); // the head's bytes go when the connection does + at = at.resolveInPlace(location.len, &rest) catch return error.HttpRedirectLocationInvalid; + left.subtractOne(); + req.deinit(); + } + } + + /// The refusal of a repo the hub answered 401 or 403; it names the token's source, never the token. Returns 1. + pub fn refuse(auth: Auth, err_out: *std.Io.Writer, repo: []const u8) !u8 { + var buf: [255]u8 = undefined; + const parsed = std.Uri.parse(auth.endpoint) catch null; + const own = if (parsed) |u| origin(u, &buf) else null; + const host = if (own) |o| o.host else auth.endpoint; + if (auth.bearer == null) { + try err_out.print("{s} was refused: it is gated or private, or no repo has that name. Check the name; for a gated or private repo, accept its terms on {s}, then set HF_TOKEN or log in with `hf auth login`\n", .{ repo, host }); + } else { + try err_out.print("{s} is gated or private, and the token from {s} lacks access: accept its terms on {s} with that account, or use a token that can read it\n", .{ repo, auth.source, host }); + } + return 1; + } +}; + +const Origin = struct { scheme: []const u8, host: []const u8, port: u16 }; + +/// `uri`'s scheme, host (decoded into `buf`) and port, the scheme's default port when it names none. +fn origin(uri: std.Uri, buf: []u8) ?Origin { + const host = (uri.host orelse return null).toRaw(buf) catch return null; + if (host.len == 0) return null; + const port: u16 = uri.port orelse if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else if (std.ascii.eqlIgnoreCase(uri.scheme, "http")) 80 else return null; + return .{ .scheme = uri.scheme, .host = host, .port = port }; +} + +/// The first non-empty of HF_TOKEN and HUGGING_FACE_HUB_TOKEN, else the one token file the `hf` tools read. +pub fn token(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, problem: *[]const u8) !?Token { + for ([_][:0]const u8{ "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN" }) |name| { + const text = (environment.path(name, hub.envValue(env, name)) catch return bad(a, problem, unsendable, .{name})) orelse ""; + if (text.len > 0) return try usable(a, .{ .value = text, .source = name }, problem); + } + const path = try tokenPath(a, env, problem) orelse return null; + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(max_token + 1)) catch |e| switch (e) { + error.FileNotFound => return null, + error.StreamTooLong => return bad(a, problem, "the Hugging Face token file {s} is larger than a token; refusing to send it", .{path}), + else => return bad(a, problem, "the Hugging Face token file {s} cannot be read ({t}); fix it, or set HF_TOKEN", .{ path, e }), + }; + const text = std.mem.trim(u8, bytes, &std.ascii.whitespace); + return if (text.len > 0) try usable(a, .{ .value = text, .source = path }, problem) else null; +} + +/// HF_TOKEN_PATH, else $HF_HOME/token, else the home cache's; an empty value is unset, so no `token` where pull runs. +fn tokenPath(a: Allocator, env: ?*const std.process.Environ.Map, problem: *[]const u8) !?[]const u8 { + const named = environment.path("HF_TOKEN_PATH", hub.envValue(env, "HF_TOKEN_PATH")) catch return bad(a, problem, "HF_TOKEN_PATH has a control character in it; fix it, or set HF_TOKEN", .{}); + if (named) |p| return p; + if (nonEmpty(hub.envValue(env, "HF_HOME"))) |h| return try std.fs.path.join(a, &.{ h, "token" }); + if (nonEmpty(hub.homeDir(env))) |h| return try std.fs.path.join(a, &.{ h, ".cache", "huggingface", "token" }); + return null; +} + +fn nonEmpty(value: ?[]const u8) ?[]const u8 { + const v = value orelse return null; + return if (v.len > 0) v else null; +} + +const unsendable = "the Hugging Face token in {s} has a space or control character in it, or passes 4096 bytes; refusing to send it"; + +/// `t` when a header can carry it, visible ASCII of at most 4096 bytes; else error.BadToken naming its source. +fn usable(a: Allocator, t: Token, problem: *[]const u8) !Token { + var ok = t.value.len <= max_token; + for (t.value) |ch| ok = ok and ch > ' ' and ch < 0x7f; + if (ok) return t; + return bad(a, problem, unsendable, .{t.source}); +} + +fn bad(a: Allocator, problem: *[]const u8, comptime fmt: []const u8, args: anytype) error{ BadToken, OutOfMemory } { + problem.* = try std.fmt.allocPrint(a, fmt, args); + return error.BadToken; +} + +test { + _ = @import("pull_auth_test.zig"); +} diff --git a/zig/src/cli/pull_auth_test.zig b/zig/src/cli/pull_auth_test.zig new file mode 100644 index 0000000000..2b32788d81 --- /dev/null +++ b/zig/src/cli/pull_auth_test.zig @@ -0,0 +1,400 @@ +//! The Hugging Face token: its sources in order, the one origin it goes to, and a fake gated hub with its CDN. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const auth = @import("pull_auth.zig"); +const pull = @import("pull.zig"); +const single = @import("pull_file.zig"); +const ranged = @import("pull_parts.zig"); +const exlr8_pull = @import("pull_exlr8.zig"); +const FakeHub = @import("pull_test.zig").FakeHub; +const Map = std.process.Environ.Map; + +const token = "hf_ExampleGatedToken0001"; +const wrong = "hf_ExampleOtherToken0002"; +const gated_sha = "fffffffffffffffffffffffffffffffffffffff6"; + +/// What the gated routes saw: hub requests with the token and without it, CDN requests, and CDN requests with one. +const Seen = struct { + hub_token: std.atomic.Value(u32) = .init(0), + hub_other: std.atomic.Value(u32) = .init(0), + cdn: std.atomic.Value(u32) = .init(0), + cdn_auth: std.atomic.Value(u32) = .init(0), +}; +var seen: Seen = .{}; + +/// Org/Gated's files need the token, its weights redirect to the CDN host; Org/Private is 401; /denied is 403 anywhere. +fn gated(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + const line_end = std.mem.indexOf(u8, head, "\r\n") orelse return null; + var parts = std.mem.tokenizeScalar(u8, head[0..line_end], ' '); + _ = parts.next() orelse return null; + const target = parts.next() orelse return null; + const path = target[0 .. std.mem.indexOfScalar(u8, target, '?') orelse target.len]; + const authorization = header(head, "authorization"); + if (std.mem.eql(u8, path, "/denied")) return refuse(fake, conn, "403 Forbidden"); + // the CDN is this fake under another host name: its own weights route serves the bytes, never to a token + if (std.mem.startsWith(u8, header(head, "host") orelse "", "localhost:")) { + _ = seen.cdn.fetchAdd(1, .monotonic); + if (authorization == null) return null; + _ = seen.cdn_auth.fetchAdd(1, .monotonic); + return refuse(fake, conn, "400 Bad Request"); + } + const good = authorization != null and std.mem.eql(u8, authorization.?, "Bearer " ++ token); + _ = (if (good) &seen.hub_token else &seen.hub_other).fetchAdd(1, .monotonic); + if (std.mem.startsWith(u8, path, "/api/models/Org/Private/")) return refuse(fake, conn, "401 Unauthorized"); + if (std.mem.eql(u8, path, "/loop")) return moved(fake, conn, "/loop"); + if (std.mem.eql(u8, path, "/moved")) return moved(fake, conn, "/Org/Gated/resolve/" ++ gated_sha ++ "/config.json"); + if (std.mem.eql(u8, path, "/api/models/Org/Gated/revision/main")) { + fake.respond(conn, "{\"sha\": \"" ++ gated_sha ++ "\"}"); + return true; + } + var buf: [512]u8 = undefined; + if (std.mem.eql(u8, path, "/api/models/Org/Gated/tree/" ++ gated_sha)) { + const tree = "[{{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"config.json\", \"size\": {d}}}, {{\"type\": \"file\", \"oid\": \"1111111111111111111111111111111111111111\", \"path\": \"weights.safetensors\", \"size\": {d}, \"lfs\": {{\"oid\": \"{s}\", \"size\": {d}}}}}]"; + fake.respond(conn, std.fmt.bufPrint(&buf, tree, .{ &fake.config_git_hex, fake.config.len, fake.weights.len, fake.weights_sha_hex, fake.weights.len }) catch return false); + return true; + } + if (!std.mem.startsWith(u8, path, "/Org/Gated/resolve/" ++ gated_sha ++ "/")) return null; + if (authorization == null) return refuse(fake, conn, "401 Unauthorized"); + if (!good) return refuse(fake, conn, "403 Forbidden"); + if (std.mem.endsWith(u8, path, "/config.json")) { + fake.respond(conn, fake.config); + return true; + } + return moved(fake, conn, std.fmt.bufPrint(&buf, "http://localhost:{d}{s}", .{ fake.port, FakeHub.weights_path }) catch return false); +} + +/// A redirect to `location`, the connection kept. +fn moved(fake: *FakeHub, conn: std.Io.net.Stream, location: []const u8) bool { + var buf: [256]u8 = undefined; + const text = "HTTP/1.1 302 Found\r\nLocation: {s}\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n"; + fake.sendAll(conn, std.fmt.bufPrint(&buf, text, .{location}) catch return false); + return true; +} + +/// A refusal with a body the hub might send, on a connection that then closes. +fn refuse(fake: *FakeHub, conn: std.Io.net.Stream, status: []const u8) bool { + const body = "{\"error\": \"Access to this repo is restricted\"}"; + var buf: [192]u8 = undefined; + const text = "HTTP/1.1 {s}\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}"; + fake.sendAll(conn, std.fmt.bufPrint(&buf, text, .{ status, body.len, body }) catch return false); + return false; +} + +fn header(head: []const u8, name: []const u8) ?[]const u8 { + var it = std.mem.splitSequence(u8, head, "\r\n"); + _ = it.next(); + while (it.next()) |h| { + const colon = std.mem.indexOfScalar(u8, h, ':') orelse continue; + if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, h[0..colon], " "), name)) return std.mem.trim(u8, h[colon + 1 ..], " "); + } + return null; +} + +/// The fake under the name localhost, the CDN's host; a system that cannot reach it skips the test. +fn cdnReachable(io: std.Io, port: u16) !void { + const host = try std.Io.net.HostName.init("localhost"); + const probe = host.connect(io, port, .{ .mode = .stream }) catch return error.SkipZigTest; + probe.close(io); +} + +fn gatedEnv(a: Allocator, fake: *FakeHub, with: ?[]const u8) !std.process.Environ.Map { + var env: std.process.Environ.Map = .{ .array_hash_map = .empty, .allocator = a }; + try env.put("HF_ENDPOINT", try fake.endpoint(a)); + if (with) |t| try env.put("HF_TOKEN", t); + return env; +} + +fn has(text: []const u8, part: []const u8) bool { + return std.mem.indexOf(u8, text, part) != null; +} + +/// No file under `root` holds `secret`: not a blob, a snapshot link's target, a ref nor a partial download. +fn expectNoFileHolds(a: Allocator, io: std.Io, root: []const u8, secret: []const u8) !void { + var dir = try std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }); + defer dir.close(io); + var walker = try dir.walk(a); + defer walker.deinit(); + var files: usize = 0; + while (try walker.next(io)) |entry| { + if (entry.kind != .file) continue; + files += 1; + try std.testing.expect(!has(try entry.dir.readFileAlloc(io, entry.basename, a, .limited(1 << 20)), secret)); + } + try std.testing.expect(files > 0); +} + +/// Org/Gated pulled with the token at `sizes`: its files land whole, and no output or file shows the token. +fn pullGated(a: Allocator, io: std.Io, fake: *FakeHub, cache: []const u8, sizes: pull.Sizes) !void { + const env = try gatedEnv(a, fake, token); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 0), try pull.runWith(a, io, &out.writer, &err_out.writer, &env, cache, "Org/Gated", sizes)); + const snapshot = try std.fs.path.join(a, &.{ cache, "models--Org--Gated/snapshots", gated_sha }); + const weights = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ snapshot, "weights.safetensors" }), a, .limited(1 << 20)); + try std.testing.expectEqualSlices(u8, fake.weights, weights); + const config = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(a, &.{ snapshot, "config.json" }), a, .limited(1 << 20)); + try std.testing.expectEqualStrings(fake.config, config); + try std.testing.expect(!has(out.written(), token) and !has(err_out.written(), token)); + try expectNoFileHolds(a, io, cache, token); + // every hub request carried the token, and no CDN request did + try std.testing.expect(seen.hub_token.load(.monotonic) > 0); + try std.testing.expectEqual(@as(u32, 0), seen.hub_other.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 0), seen.cdn_auth.load(.monotonic)); +} + +test "security: a gated repo comes down with HF_TOKEN, sent to the hub's host and never after the CDN redirect" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = gated; + fake.start(); + defer fake.stopServer(); + try cdnReachable(io, fake.port); + seen = .{}; + const root = try std.fmt.allocPrint(a, ".tf-pull-gated-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try pullGated(a, io, &fake, root, .{}); + try std.testing.expectEqual(@as(u32, 1), seen.cdn.load(.monotonic)); // the weights, from the CDN +} + +test "a gated repo's large file comes down as pieces, each redirected to the CDN without the token" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = gated; + fake.start(); + defer fake.stopServer(); + try cdnReachable(io, fake.port); + seen = .{}; + const root = try std.fmt.allocPrint(a, ".tf-pull-gated-pieces-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try pullGated(a, io, &fake, root, .{ .threshold = 4096, .piece = 1250 }); + try std.testing.expectEqual(@as(u32, 4), seen.cdn.load(.monotonic)); // four pieces, four redirects + // a piece the hub refuses is not asked for again + const before = seen.hub_other.load(.monotonic); + const url = try std.fmt.allocPrint(a, "{s}/Org/Gated/resolve/{s}/weights.safetensors", .{ try fake.endpoint(a), gated_sha }); + const file: ranged.File = .{ .url = url, .path = try std.fs.path.join(a, &.{ root, "refused.ranges" }), .size = fake.weights.len }; + try std.testing.expectError(error.HubDenied, ranged.fetch(a, io, &.{file}, 1 << 20, .{ .endpoint = try fake.endpoint(a) }, null)); + try std.testing.expectEqual(before + 1, seen.hub_other.load(.monotonic)); +} + +test "security: a gated or private repo is refused by name, and a token without access is called that" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = gated; + fake.start(); + defer fake.stopServer(); + seen = .{}; + const root = try std.fmt.allocPrint(a, ".tf-pull-refused-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const anonymous = try gatedEnv(a, &fake, null); + for ([_][]const u8{ "Org/Gated", "Org/Private" }) |repo| { + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &anonymous, root, repo)); + const text = err_out.written(); + try std.testing.expect(has(text, try std.fmt.allocPrint(a, "{s} was refused: it is gated or private, or no repo has that name", .{repo}))); + try std.testing.expect(has(text, "accept its terms on 127.0.0.1")); + try std.testing.expect(has(text, "set HF_TOKEN or log in with `hf auth login`")); + } + const other = try gatedEnv(a, &fake, wrong); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &other, root, "Org/Gated")); + try std.testing.expect(has(err_out.written(), "Org/Gated is gated or private, and the token from HF_TOKEN lacks access")); + try std.testing.expect(!has(err_out.written(), wrong) and !has(out.written(), wrong)); + // each gated refusal took the revision, the tree and config.json, the private one its revision; none the CDN + try std.testing.expectEqual(@as(u32, 7), seen.hub_other.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 0), seen.cdn.load(.monotonic)); + // a download the hub refuses is not tried again + const public_hub: auth.Auth = .{ .endpoint = try fake.endpoint(a) }; + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + const url = try std.fmt.allocPrint(a, "{s}/Org/Gated/resolve/{s}/config.json", .{ public_hub.endpoint, gated_sha }); + try std.testing.expectError(error.HubDenied, single.downloadRetrying(a, io, &client, public_hub, &out.writer, url, root, .{ .path = "config.json", .size = fake.config.len })); + try std.testing.expectEqual(@as(u32, 8), seen.hub_other.load(.monotonic)); +} + +fn expectToken(a: Allocator, io: std.Io, env: *const Map, value: []const u8, source: []const u8) !void { + var problem: []const u8 = ""; + const t = (try auth.token(a, io, env, &problem)).?; + try std.testing.expectEqualStrings(value, t.value); + try std.testing.expectEqualStrings(source, t.source); +} + +test "the token is HF_TOKEN, HUGGING_FACE_HUB_TOKEN, or the one file the hf tools read: HF_TOKEN_PATH, HF_HOME's, home's" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + for ([_][]const u8{ "hf-home", "home/.cache/huggingface", "profile/.cache/huggingface" }) |d| try tmp.dir.createDirPath(io, d); + // the files' own whitespace and line ends are trimmed + try tmp.dir.writeFile(io, .{ .sub_path = "path-token", .data = " hf_FromTokenPath\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "hf-home/token", .data = "hf_FromHfHome\r\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "home/.cache/huggingface/token", .data = "\thf_FromHomeCache \n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "profile/.cache/huggingface/token", .data = "hf_FromProfileCache" }); + const path_token = try std.fs.path.join(a, &.{ dir, "path-token" }); + var env: Map = .init(a); + try env.put("HF_TOKEN", " hf_FromEnv\n"); + try env.put("HUGGING_FACE_HUB_TOKEN", "hf_FromOldEnv"); + try env.put("HF_TOKEN_PATH", path_token); + try env.put("HF_HOME", try std.fs.path.join(a, &.{ dir, "hf-home" })); + try env.put("HOME", try std.fs.path.join(a, &.{ dir, "home" })); + try expectToken(a, io, &env, "hf_FromEnv", "HF_TOKEN"); + try env.put("HF_TOKEN", " \t\n"); // blank is unset + try expectToken(a, io, &env, "hf_FromOldEnv", "HUGGING_FACE_HUB_TOKEN"); + _ = env.swapRemove("HUGGING_FACE_HUB_TOKEN"); + try expectToken(a, io, &env, "hf_FromTokenPath", path_token); + // only the one file is read: a missing or blank one means no token, not the next folder's + var problem: []const u8 = ""; + try env.put("HF_TOKEN_PATH", try std.fs.path.join(a, &.{ dir, "missing" })); + try std.testing.expect(try auth.token(a, io, &env, &problem) == null); + _ = env.swapRemove("HF_TOKEN_PATH"); + try expectToken(a, io, &env, "hf_FromHfHome", try std.fs.path.join(a, &.{ dir, "hf-home", "token" })); + try tmp.dir.writeFile(io, .{ .sub_path = "hf-home/token", .data = "\n" }); + try std.testing.expect(try auth.token(a, io, &env, &problem) == null); + _ = env.swapRemove("HF_HOME"); + try expectToken(a, io, &env, "hf_FromHomeCache", try std.fs.path.join(a, &.{ dir, "home", ".cache", "huggingface", "token" })); + // Windows sets USERPROFILE, not HOME, as the cache folder reads it + _ = env.swapRemove("HOME"); + try env.put("USERPROFILE", try std.fs.path.join(a, &.{ dir, "profile" })); + try expectToken(a, io, &env, "hf_FromProfileCache", try std.fs.path.join(a, &.{ dir, "profile", ".cache", "huggingface", "token" })); + // an empty value is unset, so no file named token is read where pull runs + for ([_][]const u8{ "HF_TOKEN_PATH", "HF_HOME", "USERPROFILE" }) |name| try env.put(name, ""); + try std.testing.expect(try auth.token(a, io, &env, &problem) == null); + var none: Map = .init(a); + try std.testing.expect(try auth.token(a, io, &none, &problem) == null); +} + +test "security: a token pull cannot send is refused by its source, and never shown" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + try tmp.dir.writeFile(io, .{ .sub_path = "two-lines", .data = "hf_ExampleLineOne\nhf_ExampleLineTwo\n" }); + const big: [5000]u8 = @splat('h'); + try tmp.dir.writeFile(io, .{ .sub_path = "big", .data = &big }); + const Case = struct { name: []const u8, value: []const u8, says: []const u8 }; + const cases = [_]Case{ + .{ .name = "HF_TOKEN", .value = "hf_Example Spaced", .says = "the Hugging Face token in HF_TOKEN has a space or control character" }, + .{ .name = "HUGGING_FACE_HUB_TOKEN", .value = "hf_Example\x01Control", .says = "in HUGGING_FACE_HUB_TOKEN has a space or control character" }, + .{ .name = "HF_TOKEN_PATH", .value = try std.fs.path.join(a, &.{ dir, "two-lines" }), .says = "two-lines has a space or control character" }, + .{ .name = "HF_TOKEN_PATH", .value = try std.fs.path.join(a, &.{ dir, "big" }), .says = "big is larger than a token" }, + .{ .name = "HF_TOKEN_PATH", .value = dir, .says = "cannot be read (" }, + .{ .name = "HF_TOKEN_PATH", .value = "hf_Example\x1btoken", .says = "HF_TOKEN_PATH has a control character" }, // a folder: the error's name is the system's + }; + for (cases) |c| { + var env: Map = .init(a); + try env.put(c.name, c.value); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expect(try auth.Auth.init(a, io, &env, &err_out.writer) == null); + const text = err_out.written(); + try std.testing.expect(has(text, c.says)); + try std.testing.expect(!has(text, "hf_Example") and !has(text, "hhhh")); + } + // pull stops there, before it asks the hub anything (here a closed loopback port, never the network) + var env: Map = .init(a); + try env.put("HF_ENDPOINT", "http://127.0.0.1:9"); + try env.put("HF_TOKEN", "hf_Example Spaced"); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, dir, "Org/Name")); + try std.testing.expectEqualStrings("", out.written()); + try std.testing.expect(has(err_out.written(), "in HF_TOKEN has a space") and !has(err_out.written(), "hf_Example")); +} + +test "security: the token goes only to the endpoint's own scheme, host and port" { + const bearer = "Bearer hf_ExampleToken"; + const public_hub: auth.Auth = .{ .bearer = bearer, .source = "HF_TOKEN" }; + for ([_][]const u8{ "https://huggingface.co/api/models/Org/Name", "https://HuggingFace.co/Org/Name/resolve/main/config.json", "https://huggingface.co:443/x" }) |url| { + const v = public_hub.header(try std.Uri.parse(url)); + try std.testing.expect(v == .override and std.mem.eql(u8, v.override, bearer)); + } + // another host, a subdomain, a lookalike, plain HTTP and another port each lose it + for ([_][]const u8{ "https://cdn-lfs.huggingface.co/x", "https://huggingface.co.example.com/x", "http://huggingface.co/x", "https://huggingface.co:8443/x", "https://example.com/huggingface.co" }) |url| { + try std.testing.expect(public_hub.header(try std.Uri.parse(url)) == .default); + } + const mirror: auth.Auth = .{ .endpoint = "https://mirror.example.com/hf", .bearer = bearer, .source = "HF_TOKEN" }; + try std.testing.expect(mirror.header(try std.Uri.parse("https://mirror.example.com/hf/api/models/Org/Name")) == .override); + try std.testing.expect(mirror.header(try std.Uri.parse("https://huggingface.co/api/models/Org/Name")) == .default); + const anonymous: auth.Auth = .{}; + try std.testing.expect(anonymous.header(try std.Uri.parse("https://huggingface.co/api/models/Org/Name")) == .default); +} + +test "security: a redirect on the hub keeps the token, another host's 403 is no refusal, and three hops is the most" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = gated; + fake.start(); + defer fake.stopServer(); + try cdnReachable(io, fake.port); + seen = .{}; + const hub: auth.Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ token, .source = "HF_TOKEN" }; + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + var buf: [8 << 10]u8 = undefined; + var req: std.http.Client.Request = undefined; + // the gated file answers only to the token, so the relative redirect kept it + const kept = try hub.send(&client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "{s}/moved", .{hub.endpoint})), .{}, &buf); + try std.testing.expectEqual(std.http.Status.ok, kept.head.status); + req.deinit(); + try std.testing.expectError(error.HubDenied, hub.send(&client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "{s}/denied", .{hub.endpoint})), .{}, &buf)); + const elsewhere = try hub.send(&client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "http://localhost:{d}/denied", .{fake.port})), .{}, &buf); + try std.testing.expectEqual(std.http.Status.forbidden, elsewhere.head.status); + req.deinit(); + try std.testing.expectError(error.TooManyHttpRedirects, hub.send(&client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "{s}/loop", .{hub.endpoint})), .{}, &buf)); + try std.testing.expectEqual(@as(u32, 0), seen.hub_other.load(.monotonic)); +} + +test "an EXLR8 node's whole files of a gated repo resolve with the token, and come from the CDN without it" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = gated; + fake.start(); + defer fake.stopServer(); + try cdnReachable(io, fake.port); + seen = .{}; + const dir = try std.fmt.allocPrint(a, ".tf-pull-gated-exlr8-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, dir) catch {}; + var sha256: [32]u8 = undefined; + _ = try std.fmt.hexToBytes(&sha256, fake.weights_sha_hex); + var git_sha1: [20]u8 = undefined; + _ = try std.fmt.hexToBytes(&git_sha1, &fake.config_git_hex); + const whole = [_]single.Entry{ + .{ .path = "config.json", .size = fake.config.len, .git_sha1 = git_sha1 }, + .{ .path = "weights.safetensors", .size = fake.weights.len, .sha256 = sha256 }, + }; + const hub: auth.Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ token, .source = "HF_TOKEN" }; + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u32, 2), try exlr8_pull.fetchWhole(a, io, &client, &out.writer, &err_out.writer, hub, "Org/Gated", gated_sha, dir, &whole)); + const cwd = std.Io.Dir.cwd(); + try std.testing.expectEqualStrings(fake.config, try cwd.readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 20))); + try std.testing.expectEqualSlices(u8, fake.weights, try cwd.readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "weights.safetensors" }), a, .limited(1 << 20))); + // the weights' link was resolved on the hub with the token, then fetched from the CDN without it + try std.testing.expect(seen.hub_token.load(.monotonic) >= 2); + try std.testing.expectEqual(@as(u32, 0), seen.hub_other.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 1), seen.cdn.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 0), seen.cdn_auth.load(.monotonic)); +} diff --git a/zig/src/cli/pull_exlr8.zig b/zig/src/cli/pull_exlr8.zig index a98665cb5c..ee6e8b408d 100644 --- a/zig/src/cli/pull_exlr8.zig +++ b/zig/src/cli/pull_exlr8.zig @@ -3,6 +3,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const exlr8 = @import("exlr8"); const pull = @import("pull.zig"); +const Auth = @import("pull_auth.zig").Auth; const ranged = @import("pull_parts.zig"); const single = @import("pull_file.zig"); const runs = @import("pull_runs.zig"); @@ -18,14 +19,16 @@ pub fn run(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.Write const at = std.mem.indexOfScalar(u8, spec, '@'); const repo = if (at) |i| spec[0..i] else spec; const revision = if (at) |i| spec[i + 1 ..] else "main"; - const endpoint = pull.envValue(env, "HF_ENDPOINT") orelse "https://huggingface.co"; + const auth = try Auth.init(a, io, env, err_out) orelse return 1; var client = @import("pull_http.zig").client(a, io); defer client.deinit(); - const sha = pull.resolveRevision(a, &client, out, endpoint, repo, revision) catch |e| { + const sha = pull.resolveRevision(a, &client, out, auth, repo, revision) catch |e| { + if (e == error.HubDenied) return auth.refuse(err_out, repo); try err_out.print("{s}@{s}: the hub did not name a commit ({t})\n", .{ repo, revision, e }); return 1; }; - const entries = pull.listTree(a, &client, endpoint, repo, sha) catch |e| { + const entries = pull.listTree(a, &client, auth, repo, sha) catch |e| { + if (e == error.HubDenied) return auth.refuse(err_out, repo); try err_out.print("{s}@{s}: the hub's file tree is unreachable ({t})\n", .{ repo, revision, e }); return 1; }; @@ -48,7 +51,8 @@ pub fn run(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.Write } try out.print("[tensorfold] EXLR8 {s}, profile {s}, node {d}/{d} (halves {d}-{d} of every expert) into {s}\n", .{ repo, o.profile, o.node.rank, o.node.ranks, o.node.first(), o.node.end() - 1, o.dir }); try out.flush(); - const files = fetchWhole(a, io, &client, out, err_out, endpoint, repo, sha, o.dir, whole.items) catch |e| { + const files = fetchWhole(a, io, &client, out, err_out, auth, repo, sha, o.dir, whole.items) catch |e| { + if (e == error.HubDenied) return auth.refuse(err_out, repo); try err_out.print(" a whole file failed ({t}); pull again to resume\n", .{e}); return 1; }; @@ -65,14 +69,15 @@ pub fn run(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.Write defer p.deinit(io); const targets = try a.alloc(runs.Target, p.targets.items.len); for (targets, p.targets.items) |*t, pt| t.* = .{ - .url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ endpoint, repo, sha, pt.rel }), + .url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ auth.endpoint, repo, sha, pt.rel }), .path = try std.fs.path.join(a, &.{ o.dir, pt.rel }), .size = pt.size, }; const todo = try p.missing(a, io, targets); try out.print(" {d} width files, {d} halves ({d:.2} GiB); {d} of {d} runs to fetch\n", .{ targets.len, p.units.items.len, gib(p.expert_bytes), todo.len, p.runs.items.len }); try out.flush(); - runs.fetch(a, io, targets, todo, p.check(), out) catch |e| { + runs.fetch(a, io, targets, todo, p.check(), auth, out) catch |e| { + if (e == error.HubDenied) return auth.refuse(err_out, repo); try err_out.print(" the expert halves failed ({t}); pull again to fetch only what is missing\n", .{e}); return 1; }; @@ -101,7 +106,7 @@ fn gib(n: u64) f64 { } /// Every file the node needs whole, each equal to the hub's sha256 (LFS) or git blob sha1; returns how many. -pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, err_out: *std.Io.Writer, endpoint: []const u8, repo: []const u8, sha: []const u8, dir: []const u8, whole: []const single.Entry) !u32 { +pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, err_out: *std.Io.Writer, auth: Auth, repo: []const u8, sha: []const u8, dir: []const u8, whole: []const single.Entry) !u32 { const w = std.Io.Dir.cwd(); const tmp = try std.fs.path.join(a, &.{ dir, ".pull" }); try w.createDirPath(io, tmp); @@ -111,21 +116,21 @@ pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std. const final = try std.fs.path.join(a, &.{ dir, e.path }); if (std.fs.path.dirname(final)) |parent| try w.createDirPath(io, parent); if (try present(a, io, final, e)) continue; - const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ endpoint, repo, sha, e.path }); + const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ auth.endpoint, repo, sha, e.path }); if (e.sha256 != null) { // the storage link, not the hub's: pieces then skip a redirect each - const link = try runs.resolve(a, client, url); + const link = try runs.resolve(a, client, auth, url); try big.append(a, .{ .url = link, .path = try std.fmt.allocPrint(a, "{s}.part", .{final}), .size = e.size }); try big_entries.append(a, e); continue; } - const got = try single.downloadRetrying(a, io, client, out, url, tmp, e); + const got = try single.downloadRetrying(a, io, client, auth, out, url, tmp, e); try w.rename(try std.fs.path.join(a, &.{ tmp, got }), w, final, io); } if (big.items.len > 0) { try out.print(" {d} whole files in {d} MiB pieces\n", .{ big.items.len, whole_piece >> 20 }); try out.flush(); - try ranged.fetch(a, io, big.items, whole_piece, out); + try ranged.fetch(a, io, big.items, whole_piece, auth, out); for (big.items, big_entries.items) |f, e| { const d = try ranged.digest(a, io, f.path, f.size); if (!std.mem.eql(u8, &d, &e.sha256.?)) { diff --git a/zig/src/cli/pull_file.zig b/zig/src/cli/pull_file.zig index da36624c8f..e8224168f6 100644 --- a/zig/src/cli/pull_file.zig +++ b/zig/src/cli/pull_file.zig @@ -2,6 +2,7 @@ const std = @import("std"); const platform = @import("sys"); const Allocator = std.mem.Allocator; +const Auth = @import("pull_auth.zig").Auth; /// One file the hub's tree lists for the revision: LFS files carry their sha256, small files their git blob sha1. pub const Entry = struct { path: []const u8, size: u64, sha256: ?[32]u8 = null, git_sha1: ?[20]u8 = null }; @@ -25,13 +26,13 @@ fn partialPath(a: Allocator, blobs_dir: []const u8, e: Entry) ![]const u8 { } /// `download` again after a reset or a short body, waiting longer each time; a sha256 mismatch starts over once. -pub fn downloadRetrying(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, url: []const u8, blobs_dir: []const u8, e: Entry) ![]const u8 { +pub fn downloadRetrying(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: *std.Io.Writer, url: []const u8, blobs_dir: []const u8, e: Entry) ![]const u8 { var wait_ms: i64 = 250; var restarted = false; var attempt: u32 = 1; while (true) : (attempt += 1) { - if (download(a, io, client, out, url, blobs_dir, e)) |name| return name else |err| { - if (attempt == attempts or (err == error.ShaMismatch and restarted)) return err; + if (download(a, io, client, auth, out, url, blobs_dir, e)) |name| return name else |err| { + if (attempt == attempts or err == error.HubDenied or (err == error.ShaMismatch and restarted)) return err; if (err == error.ShaMismatch) { restarted = true; std.Io.Dir.cwd().deleteFile(io, try partialPath(a, blobs_dir, e)) catch {}; @@ -43,7 +44,7 @@ pub fn downloadRetrying(a: Allocator, io: std.Io, client: *std.http.Client, out: } /// Downloads one file into ``blobs`` with HTTP range resume, verifies size and sha256, and returns the blob name. -fn download(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, url: []const u8, blobs_dir: []const u8, e: Entry) ![]const u8 { +fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: *std.Io.Writer, url: []const u8, blobs_dir: []const u8, e: Entry) ![]const u8 { const final_name = try blobName(a, e); const final_path = try std.fs.path.join(a, &.{ blobs_dir, final_name }); const partial_path = try partialPath(a, blobs_dir, e); @@ -63,11 +64,10 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Wri extra = &headers; } const uri = std.Uri.parse(url) catch return error.BadUrl; - var req = try client.request(.GET, uri, .{ .extra_headers = extra, .headers = .{ .accept_encoding = .{ .override = "identity" } } }); // the file's own bytes: sizes, digests and ranges count them - defer req.deinit(); - try req.sendBodiless(); + var req: std.http.Client.Request = undefined; var redirect_buf: [8 << 10]u8 = undefined; - var response = try req.receiveHead(&redirect_buf); + var response = try auth.send(client, &req, .GET, uri, .{ .extra_headers = extra, .headers = .{ .accept_encoding = .{ .override = "identity" } } }, &redirect_buf); // the file's own bytes: sizes, digests and ranges count them + defer req.deinit(); const status = response.head.status; if (status != .ok and status != .partial_content) return error.HubStatus; var restart = false; diff --git a/zig/src/cli/pull_parts.zig b/zig/src/cli/pull_parts.zig index d81cd6223c..05e2220c4a 100644 --- a/zig/src/cli/pull_parts.zig +++ b/zig/src/cli/pull_parts.zig @@ -1,6 +1,7 @@ //! Large files as fixed pieces on one shared queue; a finished piece leaves a marker, so a restart fetches the rest. const std = @import("std"); const Allocator = std.mem.Allocator; +const Auth = @import("pull_auth.zig").Auth; /// Files at least this large come down in pieces. pub const threshold: u64 = 64 << 20; @@ -25,6 +26,7 @@ fn marker(a: Allocator, path: []const u8, i: u64) ![]const u8 { const Shared = struct { io: std.Io, + auth: Auth, files: []const File, handles: []const std.Io.File, todo: []const Piece, @@ -35,7 +37,7 @@ const Shared = struct { }; /// `files` as `bytes`-sized pieces over up to 16 connections; error.RangeUnsupported when a range gets the whole file. -pub fn fetch(a: Allocator, io: std.Io, files: []const File, bytes: u64, progress: ?*std.Io.Writer) !void { +pub fn fetch(a: Allocator, io: std.Io, files: []const File, bytes: u64, auth: Auth, progress: ?*std.Io.Writer) !void { const w = std.Io.Dir.cwd(); const handles = try a.alloc(std.Io.File, files.len); var opened: usize = 0; @@ -53,7 +55,7 @@ pub fn fetch(a: Allocator, io: std.Io, files: []const File, bytes: u64, progress left += todo.getLast().end - todo.getLast().first; } } - var s: Shared = .{ .io = io, .files = files, .handles = handles, .todo = todo.items }; + var s: Shared = .{ .io = io, .auth = auth, .files = files, .handles = handles, .todo = todo.items }; var failures: [workers]?anyerror = @splat(null); var threads: [workers]std.Thread = undefined; const n = @min(workers, todo.items.len); @@ -108,7 +110,7 @@ fn get(s: *Shared, client: *std.http.Client, p: Piece) !void { var last: anyerror = error.ReadFailed; for (0..attempts) |_| { range(s, client, p, &done) catch |e| { - if (e == error.RangeUnsupported) return e; + if (e == error.RangeUnsupported or e == error.HubDenied) return e; last = e; continue; }; @@ -123,11 +125,10 @@ fn range(s: *Shared, client: *std.http.Client, p: Piece, done: *u64) !void { if (from >= p.end) return; var range_buf: [64]u8 = undefined; const headers = [_]std.http.Header{.{ .name = "Range", .value = try std.fmt.bufPrint(&range_buf, "bytes={d}-{d}", .{ from, p.end - 1 }) }}; - var req = try client.request(.GET, try std.Uri.parse(s.files[p.file].url), .{ .extra_headers = &headers, .headers = .{ .accept_encoding = .{ .override = "identity" } } }); - defer req.deinit(); - try req.sendBodiless(); + var req: std.http.Client.Request = undefined; var redirect_buf: [8 << 10]u8 = undefined; - var response = try req.receiveHead(&redirect_buf); + var response = try s.auth.send(client, &req, .GET, try std.Uri.parse(s.files[p.file].url), .{ .extra_headers = &headers, .headers = .{ .accept_encoding = .{ .override = "identity" } } }, &redirect_buf); + defer req.deinit(); if (response.head.status != .partial_content or startOf(response.head) != from) return error.RangeUnsupported; var reader_buf: [64 << 10]u8 = undefined; var r = response.reader(&reader_buf); diff --git a/zig/src/cli/pull_runs.zig b/zig/src/cli/pull_runs.zig index f8828a04a9..9b35b76a60 100644 --- a/zig/src/cli/pull_runs.zig +++ b/zig/src/cli/pull_runs.zig @@ -1,6 +1,7 @@ //! Byte runs of large files on one shared queue: each is checked in memory before it is written to its file. const std = @import("std"); const Allocator = std.mem.Allocator; +const Auth = @import("pull_auth.zig").Auth; pub const workers = 16; const attempts = 6; @@ -33,6 +34,7 @@ const Link = struct { const Shared = struct { io: std.Io, + auth: Auth, targets: []const Target, links: []Link, runs: []const Run, @@ -45,7 +47,7 @@ const Shared = struct { }; /// Fetches every run over up to 16 connections; a run whose bytes fail `check` comes again, up to six times. -pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Run, check: Check, progress: ?*std.Io.Writer) !void { +pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Run, check: Check, auth: Auth, progress: ?*std.Io.Writer) !void { if (runs.len == 0) return; const w = std.Io.Dir.cwd(); for (targets) |t| { @@ -62,7 +64,7 @@ pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Ru max = @max(max, r.end - r.first); left += r.end - r.first; } - var s: Shared = .{ .io = io, .targets = targets, .links = links, .runs = runs, .check = check, .max = max }; + var s: Shared = .{ .io = io, .auth = auth, .targets = targets, .links = links, .runs = runs, .check = check, .max = max }; var failures: [workers]?anyerror = @splat(null); var threads: [workers]std.Thread = undefined; const n = @min(workers, runs.len); @@ -143,12 +145,14 @@ fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u var wait_ms: u64 = 250; for (0..attempts) |_| { const link = location(s, client, r.file) catch |e| { + if (e == error.HubDenied) return e; last = e; std.Io.sleep(s.io, .fromMilliseconds(@intCast(wait_ms)), .awake) catch {}; wait_ms *= 2; continue; }; - get(client, link, r.first, buf) catch |e| { + get(client, s.auth, link, r.first, buf) catch |e| { + if (e == error.HubDenied) return e; last = e; if (e == error.Forbidden) forget(s, r.file, link); std.Io.sleep(s.io, .fromMilliseconds(@intCast(wait_ms)), .awake) catch {}; @@ -174,7 +178,7 @@ fn location(s: *Shared, client: *std.http.Client, file: u32) ![]const u8 { const now = std.Io.Clock.awake.now(s.io).toNanoseconds(); if (l.url) |u| if (now - l.at < fresh_ns) return u; // an older link may still be in use by another worker: it stays allocated (a few a file an hour) - const u = try resolve(std.heap.page_allocator, client, s.targets[file].url); + const u = try resolve(std.heap.page_allocator, client, s.auth, s.targets[file].url); l.url = u; l.at = now; return u; @@ -188,11 +192,10 @@ fn forget(s: *Shared, file: u32, link: []const u8) void { } /// Where `url` lands: the Location of a redirect, else `url` itself. -pub fn resolve(a: Allocator, client: *std.http.Client, url: []const u8) ![]u8 { - var req = try client.request(.HEAD, try std.Uri.parse(url), .{ .redirect_behavior = .unhandled, .headers = .{ .accept_encoding = .{ .override = "identity" } } }); +pub fn resolve(a: Allocator, client: *std.http.Client, auth: Auth, url: []const u8) ![]u8 { + var req: std.http.Client.Request = undefined; + const response = try auth.send(client, &req, .HEAD, try std.Uri.parse(url), .{ .redirect_behavior = .unhandled, .headers = .{ .accept_encoding = .{ .override = "identity" } } }, &.{}); defer req.deinit(); - try req.sendBodiless(); - const response = try req.receiveHead(&.{}); if (response.head.status.class() == .redirect) { const to = response.head.location orelse return error.HttpRedirectLocationMissing; if (!std.mem.startsWith(u8, to, "https://") and !std.mem.startsWith(u8, to, "http://")) return error.RelativeRedirect; @@ -203,13 +206,12 @@ pub fn resolve(a: Allocator, client: *std.http.Client, url: []const u8) ![]u8 { } /// Bytes [first, first + buf.len) of `link` into `buf`; the storage must answer 206 for exactly that range. -fn get(client: *std.http.Client, link: []const u8, first: u64, buf: []u8) !void { +fn get(client: *std.http.Client, auth: Auth, link: []const u8, first: u64, buf: []u8) !void { var range_buf: [64]u8 = undefined; const headers = [_]std.http.Header{.{ .name = "Range", .value = try std.fmt.bufPrint(&range_buf, "bytes={d}-{d}", .{ first, first + buf.len - 1 }) }}; - var req = try client.request(.GET, try std.Uri.parse(link), .{ .redirect_behavior = .not_allowed, .extra_headers = &headers, .headers = .{ .accept_encoding = .{ .override = "identity" } } }); + var req: std.http.Client.Request = undefined; + var response = try auth.send(client, &req, .GET, try std.Uri.parse(link), .{ .redirect_behavior = .not_allowed, .extra_headers = &headers, .headers = .{ .accept_encoding = .{ .override = "identity" } } }, &.{}); defer req.deinit(); - try req.sendBodiless(); - var response = try req.receiveHead(&.{}); if (response.head.status == .forbidden or response.head.status == .gone) return error.Forbidden; if (response.head.status != .partial_content) return error.RangeUnsupported; var reader_buf: [64 << 10]u8 = undefined; diff --git a/zig/src/cli/pull_test.zig b/zig/src/cli/pull_test.zig index 087d806a3a..118a27cb81 100644 --- a/zig/src/cli/pull_test.zig +++ b/zig/src/cli/pull_test.zig @@ -8,7 +8,7 @@ const exlr8_pull = @import("pull_exlr8.zig"); const TestClient = @import("pull_test_client.zig").Client; /// A fake hub on 127.0.0.1: revision and tree APIs, ranged resolve endpoints, a body cut once, a repo ignoring ranges. -const FakeHub = struct { +pub const FakeHub = struct { allocator: Allocator = std.heap.page_allocator, // the fake server owns its worker allocations server: std.Io.net.Server, io: std.Io, @@ -28,8 +28,9 @@ const FakeHub = struct { config_git_hex: [40]u8, flaky_git_hex: [40]u8, port: u16, - - const weights_path = "/Org/Flash/resolve/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1/weights.safetensors"; + /// Routes a test puts before the fake's own: the answer's keep-alive, or null when the request is not theirs. + route: ?*const fn (fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool = null, + pub const weights_path = "/Org/Flash/resolve/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1/weights.safetensors"; const config_path = "/Org/Flash/resolve/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1/config.json"; const nested_path = "/Org/Flash/resolve/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1/tensors/model-00001-of-00001.safetensors"; const flaky_body = "{\"chat_template\": \"{{ messages }}\"}"; @@ -38,7 +39,7 @@ const FakeHub = struct { var nested_body_storage: [1234]u8 = @splat(0x5A); const nested_body: []const u8 = &nested_body_storage; - fn open() !FakeHub { + pub fn open() !FakeHub { const a = std.heap.page_allocator; const threaded = try a.create(std.Io.Threaded); errdefer a.destroy(threaded); @@ -141,6 +142,7 @@ const FakeHub = struct { /// Answers one request; false closes the connection. fn respondOne(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) bool { + if (fake.route) |r| if (r(fake, conn, head)) |keep| return keep; var tree_buf: [256]u8 = undefined; const line_end = std.mem.indexOf(u8, head, "\r\n") orelse return false; var parts = std.mem.tokenizeScalar(u8, head[0..line_end], ' '); @@ -244,25 +246,25 @@ const FakeHub = struct { fake.sendAll(conn, body); } - fn respond(fake: *FakeHub, conn: std.Io.net.Stream, body: []const u8) void { + pub fn respond(fake: *FakeHub, conn: std.Io.net.Stream, body: []const u8) void { var head_buf: [128]u8 = undefined; const head_text = std.fmt.bufPrint(&head_buf, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: keep-alive\r\n\r\n", .{body.len}) catch return; fake.sendAll(conn, head_text); fake.sendAll(conn, body); } - fn sendAll(fake: *FakeHub, conn: std.Io.net.Stream, bytes: []const u8) void { + pub fn sendAll(fake: *FakeHub, conn: std.Io.net.Stream, bytes: []const u8) void { var buf: [4096]u8 = undefined; var w = conn.writer(fake.io, &buf); w.interface.writeAll(bytes) catch return; w.interface.flush() catch return; } - fn start(fake: *FakeHub) void { + pub fn start(fake: *FakeHub) void { fake.thread = std.Thread.spawn(.{}, serve, .{fake}) catch null; } - fn endpoint(fake: *FakeHub, a: Allocator) ![]const u8 { + pub fn endpoint(fake: *FakeHub, a: Allocator) ![]const u8 { return std.fmt.allocPrint(a, "http://127.0.0.1:{d}", .{fake.port}); } @@ -277,7 +279,7 @@ const FakeHub = struct { } } - fn stopServer(fake: *FakeHub) void { + pub fn stopServer(fake: *FakeHub) void { fake.stop.store(true, .release); fake.live_lock.lockUncancelable(fake.io); for (fake.live.items) |conn| conn.shutdown(fake.io, .both) catch {}; @@ -438,7 +440,7 @@ test "shared pieces fill every byte across files, restart only unmarked pieces a .{ .url = url, .path = try std.fs.path.join(a, &.{ root, "second.ranges" }), .size = size }, }; - try ranged.fetch(a, io, &files, 1250, null); + try ranged.fetch(a, io, &files, 1250, .{}, null); try std.testing.expectEqual(@as(u32, 8), fake_hub.weight_requests.load(.monotonic)); for (files) |f| try std.testing.expectEqualSlices(u8, FakeHub.weights_body, try std.Io.Dir.cwd().readFileAlloc(io, f.path, a, .limited(1 << 20))); @@ -447,13 +449,13 @@ test "shared pieces fill every byte across files, restart only unmarked pieces a try std.Io.Dir.cwd().deleteFile(io, first.path); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = first.path, .data = FakeHub.weights_body }); for ([_]u32{ 0, 2 }) |i| try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}.part{d}", .{ first.path, i }), .data = "" }); - try ranged.fetch(a, io, &.{first}, 1250, null); + try ranged.fetch(a, io, &.{first}, 1250, .{}, null); try std.testing.expectEqual(@as(u32, 10), fake_hub.weight_requests.load(.monotonic)); try std.testing.expectEqualSlices(u8, &(try ranged.digest(a, io, first.path, size)), &(try hexBytes(fake_hub.weights_sha_hex))); // A server that answers a range with the whole file (the config endpoint here) is refused for pieces. const config_url = try std.fmt.allocPrint(a, "{s}{s}", .{ try fake_hub.endpoint(a), FakeHub.config_path }); - try std.testing.expectError(error.RangeUnsupported, ranged.fetch(a, io, &.{.{ .url = config_url, .path = try std.fs.path.join(a, &.{ root, "config.ranges" }), .size = FakeHub.config_body.len }}, 50, null)); + try std.testing.expectError(error.RangeUnsupported, ranged.fetch(a, io, &.{.{ .url = config_url, .path = try std.fs.path.join(a, &.{ root, "config.ranges" }), .size = FakeHub.config_body.len }}, 50, .{}, null)); } fn hexBytes(text: []const u8) ![32]u8 { @@ -487,7 +489,7 @@ test "an EXLR8 node's whole files land in a relative directory, small files and defer client.deinit(); var out: std.Io.Writer.Allocating = .init(a); var err_out: std.Io.Writer.Allocating = .init(a); - try std.testing.expectEqual(@as(u32, 2), try exlr8_pull.fetchWhole(a, io, &client, &out.writer, &err_out.writer, try fake_hub.endpoint(a), "Org/Flash", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1", dir, &whole)); + try std.testing.expectEqual(@as(u32, 2), try exlr8_pull.fetchWhole(a, io, &client, &out.writer, &err_out.writer, .{ .endpoint = try fake_hub.endpoint(a) }, "Org/Flash", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1", dir, &whole)); const cwd = std.Io.Dir.cwd(); try std.testing.expectEqualStrings(FakeHub.config_body, try cwd.readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 20))); try std.testing.expectEqualSlices(u8, FakeHub.weights_body, try cwd.readFileAlloc(io, try std.fs.path.join(a, &.{ dir, "weights.safetensors" }), a, .limited(1 << 20))); @@ -511,7 +513,7 @@ test "security: a hub response cannot write beyond the manifest file size" { var client = @import("pull_http.zig").client(a, io); defer client.deinit(); var out: std.Io.Writer.Allocating = .init(a); - try std.testing.expectError(error.SizeMismatch, single.downloadRetrying(a, io, &client, &out.writer, url, dir, .{ + try std.testing.expectError(error.SizeMismatch, single.downloadRetrying(a, io, &client, .{}, &out.writer, url, dir, .{ .path = "overflow.bin", .size = 8, })); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 60f2617404..b35c321abf 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -3,7 +3,7 @@ const std = @import("std"); const sys = @import("sys.zig"); pub const Error = error{InvalidEnvironment}; -pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3, chat }; +pub const Scope = enum { common, cuda, metal, xpu, slide, hooks, dsv41, gemma4, drama3, glm, flashnext, nemotron, minimax_m3, chat, hub }; pub const Kind = enum { u32, u64, size, percent, positive, device, segments, mib, bit_width, word, prompt, flag, toggle, real, positive_real, signed_real, range, path }; pub const Rule = struct { name: [:0]const u8, @@ -235,6 +235,9 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_CONFIDENCE", .scope = .flashnext, .kind = .signed_real, .forms = "a finite number (default -0.4)" }, .{ .name = "TF_FLASHNEXT_PROMPT", .scope = .flashnext, .kind = .word, .words = &.{"rows"}, .forms = "rows for the rows path (unset or blank keeps the plain path)" }, .{ .name = "TENSORFOLD_API_KEY", .scope = .chat, .kind = .path, .trim = " \t\n\r\x0b\x0c", .forms = "API keys split by commas, without control characters (checked here by tensorfold chat --url)" }, + .{ .name = "HF_TOKEN", .scope = .hub, .kind = .path, .trim = " \t\n\r\x0b\x0c", .forms = "a Hugging Face token without control characters (pull only)" }, + .{ .name = "HUGGING_FACE_HUB_TOKEN", .scope = .hub, .kind = .path, .trim = " \t\n\r\x0b\x0c", .forms = "a Hugging Face token without control characters (pull only)" }, + .{ .name = "HF_TOKEN_PATH", .scope = .hub, .kind = .path, .forms = "a path without control characters to the Hugging Face token file (pull only)" }, // Family rank and prompt settings below are read through their own family's startup scope. .{ .name = "TF_GLM_INDEX_CUDA", .scope = .glm, .kind = .word, .words = &.{ "1", "0", "scores" }, .forms = "1 (both kernels), 0 (neither) or scores (scores only; unset or blank is both)" }, .{ .name = "TF_GLM_KV_HOST_GIB", .scope = .glm, .kind = .real, .forms = "a finite GiB amount of at least 0 (unset or blank uses one full window and 16 rows a page)" }, @@ -415,6 +418,7 @@ pub const Flags = struct { nemotron: bool = false, minimax_m3: bool = false, chat: bool = false, + hub: bool = false, device: ?u32 = null, segments: ?u32 = null, carveout: bool = false, @@ -435,6 +439,7 @@ pub const Flags = struct { .nemotron => f.nemotron, .minimax_m3 => f.minimax_m3, .chat => f.chat, + .hub => f.hub, }; } }; diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 06605e1fc9..9fcfb2977d 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -3,7 +3,7 @@ const std = @import("std"); const e = @import("environment.zig"); const t = std.testing; const a = t.allocator; -const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true, .nemotron = true, .minimax_m3 = true, .chat = true }; +const all: e.Flags = .{ .cuda = true, .metal = true, .xpu = true, .slide = true, .hooks = true, .dsv41 = true, .gemma4 = true, .drama3 = true, .glm = true, .flashnext = true, .nemotron = true, .minimax_m3 = true, .chat = true, .hub = true }; const Env = struct { name: []const u8, raw: ?[]const u8, @@ -166,6 +166,9 @@ const valid = [_]Case{ .{ .name = "TF_DSV41_ENGRAM_VERIFY", .raw = "full", .n = 1 }, .{ .name = "TF_DSV41_ENGRAM_CACHE", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_API_KEY", .raw = " example-key-1, example-key-2\n", .n = 0 }, + .{ .name = "HF_TOKEN", .raw = " hf_Example\n", .n = 0 }, + .{ .name = "HUGGING_FACE_HUB_TOKEN", .raw = "hf_Example", .n = 0 }, + .{ .name = "HF_TOKEN_PATH", .raw = "/srv/hf/token", .n = 0 }, .{ .name = "TF_NEMOTRON_RANK", .raw = "1", .n = 1 }, .{ .name = "TF_NEMOTRON_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_MINIMAX_RANK", .raw = "1", .n = 1 },