Skip to content
zit Artifact [0021691ca9]
Login

Artifact [0021691ca9]

Artifact 0021691ca9d5bda691b99c5b6579a532589ca3892930463d61100dc568d4acdb:


//! `zit users`: list the user table: logins and capabilities, with
//! password hashes only under `--raw`.

const std = @import("std");
const cli = @import("zit").cli;
const cmd_sync = @import("sync.zig");
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const reasonOf = diagnostics.reasonOf;
const stateOom = diagnostics.stateOom;
const repoReadFail = diagnostics.repoReadFail;
const storeReadFail = diagnostics.storeReadFail;

/// `zit stat` — answer questions about the store itself: how large it is, how
/// much of that is artifact content, and which artifacts it holds.
///
/// The honesty constraint that shapes this verb: `content-bytes` is MEASURED,
/// by summing each artifact frame's payload length during the walk. It is
/// never the `.zit` file size, which additionally carries the store header, a
/// header per frame, and the padding that aligns each frame to 8 bytes.
/// Reporting the file size as content would look like a result and be a
/// fabrication, so the two travel as separate fields and the overhead that
/// separates them is reported alongside, making the accounting checkable:
/// `header-bytes + content-bytes + frame-overhead-bytes + config-bytes +
/// shun-bytes` is the file, exactly — the shun table's frames are part of the
/// store, so leaving them out of the report would leave an unlabelled gap on
/// every repository an operator has shunned anything in.
///
/// Two traversals, both bounded by the store rather than by the artifact
/// count. `openReadOnly` is the first: it whole-frame-CRC-verifies every frame
/// and builds the in-memory index, which is what `--artifacts` enumerates and
/// what lets `storestat.walk` trust the prefix bytes it reads. The summary path
/// then runs the walk, a prefix-only second pass. The open is not skippable on
/// the summary path: unverified frame prefixes would make the totals a report
/// about bytes nobody checked. What is avoided is the per-artifact shape — no
/// invocation, and no payload decode, per stored artifact. Read-only; the
/// store is not modified.
/// `zit users [--raw]` — emit the repository's user table, one row per
/// line, TAB-separated, sorted by login. Machine-consumable like
/// `zit crosslink`: a consumer (quarry, hosting a mirrored fossil repository)
/// ingests it verbatim.
///
/// `pw` IS WITHHELD BY DEFAULT and printed only under `--raw`. The column is
/// the RFC §6.3 shared-secret hash, and fossil guards the whole user area
/// behind Admin on the wire (`configure.c`'s
/// `m &= ~(CONFIGSET_USER|CONFIGSET_SCRIBER)` for a non-admin client). A
/// default listing that spilled hashes would make them easier to lift from a
/// zit mirror than from the fossil repository it mirrors — so the operator
/// asks for them explicitly, and the flag's presence is the audit trail.
///
/// `cap` is passed through verbatim and never interpreted: the capability
/// vocabulary is fossil's, and a zit that parsed it would need changing every
/// time fossil adds a letter.
pub fn runUsers(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    if (verb_args.len > 0 and std.mem.eql(u8, verb_args[0], "contact"))
        return runUsersContact(gpa, io, arena, verb_args[1..], streams, amb);
    var raw = false;
    for (verb_args) |tok| {
        if (std.mem.eql(u8, tok, "-h") or std.mem.eql(u8, tok, "--help")) {
            streams.out.writeAll(help_pages.users_help) catch {};
            return .ok;
        } else if (std.mem.eql(u8, tok, "--raw")) {
            raw = true;
        } else if (tok.len > 1 and tok[0] == '-') {
            return cli.usageError(streams, "users", .unknown_option, tok);
        } else {
            return cli.usageError(streams, "users", .extra_argument, tok);
        }
    }

    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch
        return stateOom(streams, "users")) orelse {
        diagnostics.reportNoRoot(streams, io, "users", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    var file = cli.openStoreRead(io, root_dir) catch |e| return storeReadFail(streams, "users", e);
    defer file.close(io);
    const st = file.stat(io) catch return repoReadFail(streams, "users");
    var fs = storage.FileStorage.init(io, file, st.size);
    var store = cmd_sync.openLogAdoptingIndex(gpa, io, root_dir, fs.storageFile(), .refresh_on_scan) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "users"),
        else => {
            streams.err.print("zit users: cannot read repository: {s}\n", .{reasonOf(e)}) catch {};
            return .failure;
        },
    };
    defer store.deinit(gpa);

    const table = store.userTable(gpa) catch return stateOom(streams, "users");
    defer gpa.free(table);
    for (table) |row| {
        if (raw) {
            streams.out.print("{s}\t{s}\t{s}\t{d}\t{s}\n", .{ row.login, row.cap, row.pw, row.mtime, row.info }) catch {};
        } else {
            streams.out.print("{s}\t{s}\t{d}\t{s}\n", .{ row.login, row.cap, row.mtime, row.info }) catch {};
        }
    }
    return .ok;
}

/// `zit users contact LOGIN [INFO]`: print a user's contact, or set it, as
/// `fossil user contact` does. The contact is free text; `zit git export`
/// takes the email address in it as the author's Git identity.
fn runUsersContact(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    for (args) |tok| {
        if (std.mem.eql(u8, tok, "-h") or std.mem.eql(u8, tok, "--help")) {
            streams.out.writeAll(help_pages.users_help) catch {};
            return .ok;
        }
    }
    if (args.len == 0 or args.len > 2) {
        streams.err.writeAll("usage: zit users contact LOGIN [INFO]\n") catch {};
        return .usage;
    }
    const login = args[0];
    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch
        return stateOom(streams, "users")) orelse {
        diagnostics.reportNoRoot(streams, io, "users", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    if (args.len == 1) {
        var file = cli.openStoreRead(io, root_dir) catch |e| return storeReadFail(streams, "users", e);
        defer file.close(io);
        const st = file.stat(io) catch return repoReadFail(streams, "users");
        var fs = storage.FileStorage.init(io, file, st.size);
        var store = logstore.LogStore.openReadOnly(gpa, fs.storageFile()) catch return repoReadFail(streams, "users");
        defer store.deinit(gpa);
        const table = store.userTable(gpa) catch return stateOom(streams, "users");
        defer gpa.free(table);
        for (table) |row| if (std.mem.eql(u8, row.login, login)) {
            streams.out.print("{s}\n", .{row.info}) catch {};
            return .ok;
        };
        streams.err.print("zit users: no user named '{s}'\n", .{login}) catch {};
        return .failure;
    }

    const info = args[1];
    var store_append = cli.openStoreAppend(io, root_dir) catch |e| switch (e) {
        error.StoreBusy => return .failure, // the lock notice already said it
        else => return repoReadFail(streams, "users"),
    };
    defer store_append.close(io);
    const st = store_append.file.stat(io) catch return repoReadFail(streams, "users");
    var fs = storage.FileStorage.init(io, store_append.file, st.size);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch return repoReadFail(streams, "users");
    defer log.deinit(gpa);
    const table = log.userTable(gpa) catch return stateOom(streams, "users");
    defer gpa.free(table);
    const row = for (table) |r| {
        if (std.mem.eql(u8, r.login, login)) break r;
    } else {
        streams.err.print("zit users: no user named '{s}'\n", .{login}) catch {};
        return .failure;
    };
    // A row supersedes the one before it only when strictly newer.
    const now: i64 = @intCast(@divTrunc(std.Io.Timestamp.now(io, .real).toNanoseconds(), std.time.ns_per_s));
    log.putUser(.{
        .login = row.login,
        .pw = row.pw,
        .cap = row.cap,
        .info = info,
        .mtime = @max(now, row.mtime + 1),
    }) catch |e| switch (e) {
        error.OutOfMemory => return stateOom(streams, "users"),
        error.LoginTooLong, error.FieldTooLong => {
            streams.err.writeAll("zit users: the contact is too long\n") catch {};
            return .failure;
        },
        else => return repoReadFail(streams, "users"),
    };
    log.commit() catch return repoReadFail(streams, "users");
    return .ok;
}