diff options
| author | dev <dev@example> | 2026-11-13 19:04:50 +0000 |
|---|---|---|
| committer | dev <dev@example> | 2026-11-13 19:04:50 +0000 |
| commit | f87a792743227ea06cfa1580f8d30a618b4d1a04 (patch) | |
| tree | 7af494393b4a316f620bab7de79b15230df2cf36 | |
| download | access-control-f87a792743227ea06cfa1580f8d30a618b4d1a04.tar.gz access-control-f87a792743227ea06cfa1580f8d30a618b4d1a04.zip | |
git-authz: one C program for who may move which refs
A git host that anonymous-clones and shared-pushes has one question left to
answer: which human may move which ref. This answers it from one plain file,
in one binary, with no runtime beyond libc.
Four modes, because they must agree exactly about what a rule means - a check
that answers differently from the hook is a program that lies:
check one question, for an operator or a script
authorize a whole push, the way core.hooksPath hands it over: identity from
GIT_HOST_USER (ssh key option) or REMOTE_USER (http auth), and one
"old new ref" line per ref on stdin. Also runs as "pre-receive",
which is how git finds it.
validate does the policy parse, and is the host wired to run it
edit grant, revoke, protect (the deployed policy is a read-only mount on
purpose, so these are for the source copy and say so when told)
The verdict is the exit status, since the caller is a hook: 0 allowed, 1 denied,
3 no usable policy, 64 usage. A policy that cannot be read or does not parse
denies everything rather than guessing, and one bad line poisons the whole file
on purpose: a mistyped rule that quietly widens access is worse than an evening
of refused pushes.
Semantics kept from the shell engine this replaces: levels are monotone (admin
implies force implies write), rules add up rather than order, "@" is only
everyone the policy already names, protected refs cost one step more than the
action asked for, and refs that are neither branches nor tags are for admins.
"main", "heads/main" and "refs/heads/main" are one branch; a bare name is never
a tag.
Two facts a push does not carry - is old an ancestor of new, and which branch
HEAD points at - are asked of git, and an answer that cannot be had is taken the
expensive way. tests/unit.c covers the matcher directly (173 checks); the
behavioural suite that drives this the way git does follows next.
| -rw-r--r-- | .gitignore | 4 | ||||
| -rw-r--r-- | Makefile | 66 | ||||
| -rw-r--r-- | build/relpath.awk | 22 | ||||
| -rw-r--r-- | src/authz.h | 214 | ||||
| -rw-r--r-- | src/edit.c | 516 | ||||
| -rw-r--r-- | src/glob.c | 105 | ||||
| -rw-r--r-- | src/hook.c | 381 | ||||
| -rw-r--r-- | src/main.c | 271 | ||||
| -rw-r--r-- | src/policy.c | 651 | ||||
| -rw-r--r-- | src/util.c | 118 | ||||
| -rw-r--r-- | src/validate.c | 483 | ||||
| -rw-r--r-- | tests/unit.c | 540 |
12 files changed, 3371 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..86d6bb6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.o +/git-authz +/tests/unit +/tests/tmp/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..167c6ed --- /dev/null +++ b/Makefile @@ -0,0 +1,66 @@ +# git-authz - who may move which refs. C99 and libc, nothing else. +# +# make build ./git-authz +# make test build, then run the unit suite and the behavioural suite +# make install install into $(DESTDIR)$(PREFIX) +# make clean +# +# No configure script, no cmake, no generated headers: the only portability +# knob this program needs is CFLAGS. Warnings are variables so that a strict +# build is a command line and not a build system: +# +# make WARN="-Wall -Wextra -Wpedantic -Werror" + +CC ?= cc +PREFIX ?= /usr/local +BINDIR ?= $(PREFIX)/bin +SHAREDIR ?= $(PREFIX)/share/git-host +SYSCONFDIR ?= /etc/git-host +HOOKDIR ?= $(SHAREDIR)/hooks + +STD ?= -std=c99 +WARN ?= -Wall -Wextra -Wpedantic +CFLAGS ?= -O2 -g +CPPFLAGS += -D_POSIX_C_SOURCE=200809L + +PROG = git-authz +UNIT = tests/unit +OBJS = src/util.o src/glob.o src/policy.o src/hook.o src/validate.o src/edit.o \ + src/main.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) + +src/%.o: src/%.c src/authz.h + $(CC) $(STD) $(WARN) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< + +# The unit test links the parts it tests, not the command line, so that a +# broken argument parser cannot hide a working matcher (or the other way round). +$(UNIT): tests/unit.c src/util.o src/glob.o src/policy.o + $(CC) $(STD) $(WARN) $(CPPFLAGS) $(CFLAGS) -o $@ tests/unit.c \ + src/util.o src/glob.o src/policy.o + +test: $(PROG) $(UNIT) + mkdir -p tests/tmp + $(UNIT) + AUTHZ=./$(PROG) sh tests/run.sh + +install: $(PROG) + install -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(HOOKDIR) $(DESTDIR)$(SYSCONFDIR) + install -m 0755 $(PROG) $(DESTDIR)$(BINDIR)/$(PROG) + install -m 0644 authz.conf $(DESTDIR)$(SYSCONFDIR)/authz.conf + rm -f $(DESTDIR)$(HOOKDIR)/pre-receive + cd $(DESTDIR)$(HOOKDIR) && \ + ln -s "`awk -v from='$(SHAREDIR)/hooks' -v to='$(BINDIR)/$(PROG)' \ + -f build/relpath.awk`" pre-receive + +uninstall: + rm -f $(DESTDIR)$(BINDIR)/$(PROG) $(DESTDIR)$(HOOKDIR)/pre-receive + +clean: + rm -f $(OBJS) $(PROG) $(UNIT) + rm -rf tests/tmp + +.PHONY: all test install uninstall clean diff --git a/build/relpath.awk b/build/relpath.awk new file mode 100644 index 0000000..6c9a031 --- /dev/null +++ b/build/relpath.awk @@ -0,0 +1,22 @@ +# The path from one directory to a file, expressed relative to that directory. +# +# The pre-receive hook is this same binary reached through a symlink, because +# that is how git's core.hooksPath finds it. An absolute symlink would be a +# hook that works at exactly one prefix; a relative one survives a staged +# install (DESTDIR), a prefix built elsewhere, and a container image that moves +# /usr/local around - and `ls -l` still says what the hook is. +BEGIN { + n = split(from, f, "/") + m = split(to, t, "/") + i = 1 + while (i <= n && i <= m && f[i] == t[i]) + i++ + rel = "" + for (k = i; k <= n; k++) + rel = rel (rel == "" ? "" : "/") ".." + for (k = i; k <= m; k++) + rel = rel (rel == "" ? "" : "/") t[k] + if (rel == "") + rel = "." + print rel +} diff --git a/src/authz.h b/src/authz.h new file mode 100644 index 0000000..9ca0eb6 --- /dev/null +++ b/src/authz.h @@ -0,0 +1,214 @@ +/* authz.h - who may move which refs. + * + * One policy file, one program, three modes: + * + * check answer one question (an operator, or a script) + * authorize answer the questions a push asks, the way git's receive hook + * asks them: identity in the environment, one "old new ref" line + * per ref on stdin + * validate say whether the policy, and the host around it, make sense + * grant/revoke/protect edit the policy file (it is a file; that is the + * whole point - but see the read-only rules in edit.c) + * + * The verdict travels in the exit status, because the caller is a hook: + * + * 0 allowed + * 1 denied + * 3 the policy could not be read, or does not parse - fail closed + * 64 usage + * + * Everything here is C99 plus libc. There is deliberately no regex library, + * no fnmatch, no YAML, no SQLite: the policy grammar is words and three glob + * metacharacters, and a hook must not depend on anything that can be missing + * at 3am when the push happens. + */ +#ifndef AUTHZ_H +#define AUTHZ_H + +#include <stddef.h> + +#define MAX_FIELDS 64 /* one rule line, split on whitespace */ + +typedef enum { + LV_NONE = 0, + LV_WRITE = 1, /* create and fast-forward */ + LV_FORCE = 2, /* + rewrite history and delete */ + LV_ADMIN = 3 /* + protected refs, odd refs, the default branch */ +} level_t; + +typedef struct { + char *user; /* pattern, as written */ + char *repo; /* pattern, normalised (no .git) */ + level_t level; + char **refs; /* normalised patterns; NULL/0 = whole repository */ + size_t nrefs; + int line; /* 1-based, for messages */ +} rule_t; + +typedef struct { + rule_t *rules; + size_t nrules, rcap; + + char *protected_global; /* space separated normalised patterns, or NULL */ + char **prot_repo; /* repositories with their own list */ + char **prot_refs; /* and the list that goes with each */ + size_t nprot, pcap; + + int errors; + int warnings; + char *path; /* what messages call the file */ +} policy_t; + +typedef struct { + int allowed; + level_t need; /* what it cost in the end, after any raise */ + char why[512]; /* the sentence the person pushing reads */ +} decision_t; + +/* ---------------------------------------------------------------- glob.c */ + +/* Glob matching: '*' is any run of characters (including '/'), '?' is one + * character, '[abc]' and '[a-z]' are classes, '!' or '^' after the bracket + * negates. Everything else is literal, including '.'. + * + * Written out rather than reached for with fnmatch(3) or regex(3): both exist + * under different names and with different escapes on the systems this runs + * on, and neither is worth a dependency for three metacharacters. */ +int glob_match(const char *pattern, const char *s); + +/* -------------------------------------------------------------- policy.c */ + +void policy_init(policy_t *p, const char *path); +void policy_free(policy_t *p); + +/* Read and parse. Returns 0 when the file is usable, -1 when it produced + * errors, -2 when it could not be read at all. Errors and warnings are + * reported as they are found, on stderr, with the line number. */ +int policy_load(policy_t *p); + +/* Refs and repositories have one spelling each internally. A bare name is a + * branch, which is what makes "main" and "refs/heads/main" the same thing and + * keeps a branch from ever meaning a tag of the same name. Both return + * malloc'd strings. */ +char *authz_norm_ref(const char *in); + +/* Whitespace helpers, shared by the parser and the editor. authz_trim edits in + * place and returns the first non-blank byte. */ +char *authz_trim(char *s); +/* Splits in place, returning the field count; more than 'max' returns max+1 so + * the caller can complain rather than read past the array. */ +int authz_split_ws(char *line, char **fields, int max); + +/* The shapes a user and a repository name may take. Repository names are flat: + * two levels of namespace with a glob over each is all this model has, and the + * check that enforces it is the documentation for it. */ +int authz_user_pattern_ok(const char *s); +int authz_repo_pattern_ok(const char *s); +char *authz_norm_repo(const char *in); + +const char *authz_level_name(level_t l); +/* -1 for anything that is not a level. */ +int authz_level_of(const char *name); + +/* True if some rule other than an '@all' one names this user: '@all' means + * "everybody this policy already knows about", and never invents a name. */ +int authz_user_known(const policy_t *p, const char *user); + +/* What a ref really costs. Anything that is not a branch or a tag is for + * maintainers; on a protected ref 'write' is not enough and 'force' is not + * enough either. When the answer is higher than 'have', the reason + * ("protected", "neither a branch nor a tag") is written to raised, which must + * hold at least 64 bytes. */ +level_t authz_need_for(const policy_t *p, const char *repo, const char *ref, + level_t have, char *raised, size_t raisedsz); + +/* The decision. 'ref' may be NULL, which asks "may this user do this + * somewhere in the repository" rather than about one ref. */ +void authz_check(const policy_t *p, const char *user, const char *repo, + level_t need, const char *ref, decision_t *out); + +/* True if any rule reaches this repository at all: an unreadable-by-nobody + * repository is readable and unpushable, which is usually a name that stopped + * matching rather than a decision. */ +int authz_repo_reachable(const policy_t *p, const char *repo); + +/* The protected list in force for one repository, as stored (normalised + * patterns, space separated). Never NULL. */ +const char *authz_protected_for(const policy_t *p, const char *repo); + +/* --------------------------------------------------------------- hook.c */ + +/* authorize mode: identity from the environment, ref lines from stdin, the + * shape git hands a receive hook. Returns the exit status. + * + * Whether an update is a fast-forward, and which ref HEAD points at, are facts + * about the object store that only git knows. They are asked of git unless + * asked not to be, and an answer that cannot be had is the conservative one: + * treat the update as a rewrite, and treat any deleted ref as the default + * branch. */ +typedef struct { + const char *user; /* overrides the environment (tests, debugging) */ + const char *repo; /* ditto */ + const char *ff; /* "auto" (ask git), "yes", "no" */ + const char *head; /* "auto" (ask git), "none", or a refname */ + int use_git; /* 0 never runs git, whatever 'ff'/'head' say */ + int explain; /* print every verdict, not only the denials */ +} hook_opts; + +int cmd_authorize(const policy_t *p, hook_opts o, int argc, char **argv); + +/* ------------------------------------------------------------ validate.c */ + +typedef struct { + const char *root; /* where the repositories live */ + const char *hook_dir; + const char *gitconfig; + const char *sshd_config; + const char *passwd; + const char *keys; + const char *htpasswd; + int strict; /* warnings are errors */ +} validate_opts; + +int cmd_validate(const policy_t *p, validate_opts o); + +/* ---------------------------------------------------------------- edit.c */ + +typedef struct { + const char *out; /* NULL edits in place; "-" is stdout */ +} edit_opts; + +/* Shared by the three editing commands: leading --out/--stdout flags, and how + * many arguments they consumed. Returns -1 on an unknown option. */ +int authz_parse_out(int argc, char **argv, edit_opts *o, int *consumed); + +int cmd_grant(const char *path, edit_opts o, int argc, char **argv); +int cmd_revoke(const char *path, edit_opts o, int argc, char **argv); +int cmd_protect(const char *path, edit_opts o, int argc, char **argv); + +/* ---------------------------------------------------------------- main.c + * Shared little helpers, so that no file invents its own way to fail. */ + +/* A growing string. The policy is assembled and explained in pieces, and + * strncat with hand-computed room is how buffer bugs are born. */ +typedef struct { + char *s; /* never NULL once sb_init has run */ + size_t len; + size_t cap; +} strbuf_t; + +void sb_init(strbuf_t *b); +void sb_add(strbuf_t *b, const char *s); +void sb_addf(strbuf_t *b, const char *fmt, ...); +void sb_free(strbuf_t *b); + +void *xmalloc(size_t n); +void *xrealloc(void *p, size_t n); +char *xstrdup(const char *s); +char *xsubstr(const char *s, size_t len); + +/* The name of this program as it should appear in messages: 'pre-receive' when + * it was invoked through the hook symlink, 'git-authz' otherwise. */ +extern const char *progname; + +#endif /* AUTHZ_H */ diff --git a/src/edit.c b/src/edit.c new file mode 100644 index 0000000..4193b44 --- /dev/null +++ b/src/edit.c @@ -0,0 +1,516 @@ +/* edit.c - change the policy file, without losing the file. + * + * The deployed policy is a read-only mount, usually a ConfigMap, and that is + * not a bug to work around: it is what makes the policy reviewable and the + * rollout visible. So these commands are for the source copy - a checkout, a + * CI job, a notebook - and they say so plainly when the file they were given + * cannot be written, rather than pretending to have granted something. + * + * What they preserve is the thing a generator cannot: the comments. A policy + * file is also the record of why an access exists, so lines are replaced in + * place and everything else is left exactly as it was. When a line has to be + * written, it is written whole; the file is never truncated and rebuilt in + * place, because a policy that disappears half way through a write is a policy + * that denies everything (or, if the order were different, nothing). + * + * A file that does not parse is refused: editing a broken policy would hide the + * breakage. + */ +#include "authz.h" + +#include <ctype.h> +#include <errno.h> +#include <libgen.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +#define TEMPLATE_SUFFIX ".XXXXXX" + +typedef struct { + char **v; + size_t n; + size_t cap; +} lines_t; + +static void lines_init(lines_t *l) +{ + l->v = NULL; + l->n = 0; + l->cap = 0; +} + +static void lines_push(lines_t *l, char *s) /* takes ownership */ +{ + if (l->n == l->cap) { + l->cap = l->cap != 0 ? l->cap * 2 : 64; + l->v = xrealloc(l->v, l->cap * sizeof(*l->v)); + } + l->v[l->n++] = s; +} + +static void lines_free(lines_t *l) +{ + size_t i; + + for (i = 0; i < l->n; i++) + free(l->v[i]); + free(l->v); + lines_init(l); +} + +/* Every line, newline included, exactly as it was. */ +static int read_lines(const char *path, lines_t *l) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + + lines_init(l); + f = fopen(path, "r"); + if (f == NULL) { + fprintf(stderr, "%s: cannot read %s: %s\n", progname, path, strerror(errno)); + return -1; + } + while ((len = getline(&line, &cap, f)) != -1) { + size_t n = strlen(line); + + if (n == 0 || line[n - 1] == '\n') { + lines_push(l, xstrdup(line)); + continue; + } + { /* a last line without its newline: + * keep the file well formed */ + char *own = xmalloc(n + 2); + + memcpy(own, line, n); + own[n] = '\n'; + own[n + 1] = '\0'; + lines_push(l, own); + } + } + free(line); + fclose(f); + return 0; +} + +/* Write to a temporary file beside the target, then rename. The reader either + * sees the old file or the new one; and the mode and owner survive, because a + * policy that becomes 0600 root-owned stops working for the git account. */ +static int write_atomic(const lines_t *l, const char *path) +{ + char *dirtext = xstrdup(path); + char *dir = dirname(dirtext); + char *template; + struct stat st; + int fd; + size_t i; + int had = stat(path, &st) == 0; + + template = xmalloc(strlen(dir) + strlen(TEMPLATE_SUFFIX) + 2); + sprintf(template, "%s/.authz%s", dir, TEMPLATE_SUFFIX); + fd = mkstemp(template); + if (fd < 0) { + fprintf(stderr, "%s: cannot write beside %s: %s\n", progname, path, + strerror(errno)); + free(template); + free(dirtext); + return -1; + } + for (i = 0; i < l->n; i++) { + size_t n = strlen(l->v[i]); + size_t off = 0; + + while (off < n) { + ssize_t w = write(fd, l->v[i] + off, n - off); + + if (w <= 0) { + fprintf(stderr, "%s: write failed: %s\n", progname, strerror(errno)); + close(fd); + unlink(template); + free(template); + free(dirtext); + return -1; + } + off += (size_t)w; + } + } + if (fchmod(fd, had ? (st.st_mode & 07777) : 0644) != 0) + fprintf(stderr, "%s: warning: chmod: %s\n", progname, strerror(errno)); + if (had && geteuid() == 0 && fchown(fd, st.st_uid, st.st_gid) != 0) + fprintf(stderr, "%s: warning: chown: %s\n", progname, strerror(errno)); + if (fsync(fd) != 0) + fprintf(stderr, "%s: warning: fsync: %s\n", progname, strerror(errno)); + if (close(fd) != 0) { + fprintf(stderr, "%s: close failed: %s\n", progname, strerror(errno)); + unlink(template); + free(template); + free(dirtext); + return -1; + } + if (rename(template, path) != 0) { + fprintf(stderr, "%s: cannot replace %s: %s\n", progname, path, strerror(errno)); + if (errno == EROFS || errno == EACCES || errno == EPERM) + fprintf(stderr, "%s: the policy is read-only by design. Edit the " + "source copy (git-host/authz.conf), roll the ConfigMap, or " + "write elsewhere with --out.\n", progname); + unlink(template); + free(template); + free(dirtext); + return -1; + } + free(template); + free(dirtext); + return 0; +} + +/* ------------------------------------------------------------------ matching */ + +/* Does this line grant to exactly this user and repository? + * + * The line is copied first: splitting writes over the text, and these lines are + * the file - a matcher that flattened the comments out of the ones it did not + * change would be a vandal. */ +static int is_rule_for(const char *line, const char *user, const char *repo) +{ + char *copy = xstrdup(line); + char *fields[MAX_FIELDS]; + char *text = authz_trim(copy); + char *hash = strchr(text, '#'); + char *want; + char *have; + int same = 0; + + if (hash != NULL) + *hash = '\0'; + if (authz_split_ws(text, fields, MAX_FIELDS) >= 3) { + want = authz_norm_repo(repo); + have = authz_norm_repo(fields[1]); + same = strcmp(fields[0], user) == 0 && strcmp(have, want) == 0; + free(want); + free(have); + } + free(copy); + return same; +} + +static int is_set_for(const char *line, const char *key) +{ + char *copy = xstrdup(line); + char *text = authz_trim(copy); + char *hash = strchr(text, '#'); + size_t klen = strlen(key); + int hit = 0; + + if (hash != NULL) + *hash = '\0'; + if (strncmp(text, "set", 3) == 0 && isspace((unsigned char)text[3])) { + text = authz_trim(text + 3); + hit = strncmp(text, key, klen) == 0 && + (text[klen] == '\0' || isspace((unsigned char)text[klen])); + } + free(copy); + return hit; +} + +/* --------------------------------------------------------------- emitting */ + +/* "user repo level ref ref" - one line, no alignment tricks, because the next + * tool to read this is diff. */ +static char *rule_text(const char *user, const char *repo, const char *level, + int nrefs, char **refs) +{ + strbuf_t b; + int i; + + sb_init(&b); + sb_addf(&b, "%s %s %s", user, repo, level); + for (i = 0; i < nrefs; i++) { + char *one = authz_norm_ref(refs[i]); + + sb_addf(&b, " %s", one); + free(one); + } + sb_add(&b, "\n"); + return b.s; +} + +/* Fail before touching anything if the file cannot be parsed. */ +static int refuse_broken(const char *path) +{ + policy_t probe; + int rc; + + policy_init(&probe, path); + rc = policy_load(&probe); + policy_free(&probe); + if (rc == -2) + return 3; + if (rc == -1) { + fprintf(stderr, "%s: %s does not parse; fix it before editing\n", progname, path); + return 3; + } + return 0; +} + +/* Parse the shared options of the three editing commands. + * Returns -1 and prints a message on an unknown argument. */ +int authz_parse_out(int argc, char **argv, edit_opts *o, int *consumed) +{ + int n = 0; + + while (n < argc && strncmp(argv[n], "--", 2) == 0) { + if (strcmp(argv[n], "--stdout") == 0) { + o->out = "-"; + } else if (strncmp(argv[n], "--out=", 6) == 0) { + o->out = argv[n] + 6; + } else { + fprintf(stderr, "%s: unknown option %s\n", progname, argv[n]); + return -1; + } + n++; + } + *consumed = n; + return 0; +} + +static int finish(const lines_t *l, const char *path, edit_opts o, const char *what) +{ + if (o.out != NULL && strcmp(o.out, "-") == 0) { + size_t i; + + for (i = 0; i < l->n; i++) + fputs(l->v[i], stdout); + fprintf(stderr, "%s: %s (to stdout; %s untouched)\n", progname, what, path); + return 0; + } + if (write_atomic(l, o.out != NULL ? o.out : path) != 0) + return 1; + printf("%s: %s: %s\n", progname, what, o.out != NULL ? o.out : path); + return 0; +} + +/* ------------------------------------------------------------------ commands */ + +int cmd_grant(const char *path, edit_opts o, int argc, char **argv) +{ + lines_t lines; + char *text; + int i; + int first = -1; + int replaced = -1; + int dropped = 0; + + if (argc < 3) { + fprintf(stderr, "%s: grant wants " + "<user> <repo> <write|force|admin> [ref ...]\n", progname); + return 64; + } + if (authz_level_of(argv[2]) < 0) { + fprintf(stderr, "%s: unknown access level \"%s\" (write force admin)\n", + progname, argv[2]); + return 64; + } + if (strcmp(argv[0], "@all") != 0 && !authz_user_pattern_ok(argv[0])) { + fprintf(stderr, "%s: invalid user pattern \"%s\"\n", progname, argv[0]); + return 64; + } + if (!authz_repo_pattern_ok(argv[1])) { + fprintf(stderr, "%s: invalid repo pattern \"%s\" (flat names only, no slashes)\n", + progname, argv[1]); + return 64; + } + for (i = 3; i < argc; i++) { + if (argv[i][0] == '!' || argv[i][0] == '-') { + fprintf(stderr, "%s: ref patterns are additive, there is no deny: %s\n", + progname, argv[i]); + return 64; + } + } + + if (refuse_broken(path) != 0) + return 3; + if (read_lines(path, &lines) != 0) + return 3; + + /* More than one rule for the same pair is legal but pointless - the + * strongest wins - so the pair is collapsed into one line, in the place of + * the first. Everything else, comments included, is byte for byte what it + * was. */ + text = rule_text(argv[0], argv[1], argv[2], argc - 3, argv + 3); + for (i = 0; i < (int)lines.n; i++) { + if (!is_rule_for(lines.v[i], argv[0], argv[1])) + continue; + if (first < 0) + first = i; + else + dropped++; + } + + if (first < 0) { + lines_push(&lines, text); + replaced = (int)lines.n; + } else if (dropped == 0) { + free(lines.v[first]); + lines.v[first] = text; + replaced = first + 1; + } else { + lines_t kept; + + lines_init(&kept); + for (i = 0; i < (int)lines.n; i++) { + if (i == first) { + lines_push(&kept, text); + continue; + } + if (is_rule_for(lines.v[i], argv[0], argv[1])) { + free(lines.v[i]); + continue; + } + lines_push(&kept, lines.v[i]); + } + free(lines.v); + lines = kept; + replaced = first + 1; + } + + { + char what[128]; + + if (dropped > 0) + snprintf(what, sizeof(what), "granted %s %s %s (line %d, %d duplicate(s) removed)", + argv[0], argv[1], argv[2], replaced, dropped); + else if ((int)lines.n == replaced) + snprintf(what, sizeof(what), "granted %s %s %s (appended as line %d)", + argv[0], argv[1], argv[2], replaced); + else + snprintf(what, sizeof(what), "granted %s %s %s (replaced line %d)", + argv[0], argv[1], argv[2], replaced); + return finish(&lines, path, o, what); + } +} + +int cmd_revoke(const char *path, edit_opts o, int argc, char **argv) +{ + lines_t lines; + lines_t kept; + int i; + int gone = 0; + + if (argc != 2) { + fprintf(stderr, "%s: revoke wants <user> <repo>\n", progname); + return 64; + } + if (refuse_broken(path) != 0) + return 3; + if (read_lines(path, &lines) != 0) + return 3; + + lines_init(&kept); + for (i = 0; i < (int)lines.n; i++) { + if (is_rule_for(lines.v[i], argv[0], argv[1])) { + free(lines.v[i]); + gone++; + continue; + } + lines_push(&kept, lines.v[i]); + } + if (gone == 0) { + fprintf(stderr, "%s: no rule for %s on %s to remove\n", progname, argv[0], + argv[1]); + lines_free(&lines); + lines_free(&kept); + return 1; + } + { + char what[128]; + + snprintf(what, sizeof(what), "revoked %s on %s (%d rule(s) removed)", argv[0], + argv[1], gone); + return finish(&kept, path, o, what); + } +} + +int cmd_protect(const char *path, edit_opts o, int argc, char **argv) +{ + lines_t lines; + const char *repo = NULL; + char key[256]; + strbuf_t text; + int i; + int replaced = -1; + + if (argc < 1) { + fprintf(stderr, "%s: protect wants [--repo <name>] <ref pattern> ...\n", + progname); + return 64; + } + if (strcmp(argv[0], "--repo") == 0) { + if (argc < 2) { + fprintf(stderr, "%s: --repo wants a repository name\n", progname); + return 64; + } + repo = argv[1]; + argv += 2; + argc -= 2; + if (argc < 1) { + fprintf(stderr, "%s: protect wants at least one ref pattern\n", progname); + return 64; + } + } + if (repo != NULL && !authz_repo_pattern_ok(repo)) { + fprintf(stderr, "%s: invalid repo pattern \"%s\"\n", progname, repo); + return 64; + } + for (i = 0; i < argc; i++) { + if (argv[i][0] == '!' || argv[i][0] == '-') { + fprintf(stderr, "%s: ref patterns are additive, there is no deny: %s\n", + progname, argv[i]); + return 64; + } + } + if (refuse_broken(path) != 0) + return 3; + if (read_lines(path, &lines) != 0) + return 3; + + if (repo != NULL) + snprintf(key, sizeof(key), "protected-refs.%s", repo); + else + snprintf(key, sizeof(key), "protected-refs"); + + sb_init(&text); + sb_addf(&text, "set %s", key); + for (i = 0; i < argc; i++) { + char *one = authz_norm_ref(argv[i]); + + sb_addf(&text, " %s", one); + free(one); + } + sb_add(&text, "\n"); + + for (i = 0; i < (int)lines.n; i++) { + if (!is_set_for(lines.v[i], key)) + continue; + free(lines.v[i]); + lines.v[i] = text.s; + replaced = i + 1; + break; + } + if (replaced < 0) { + lines_push(&lines, text.s); + replaced = (int)lines.n; + } else { + free(text.s); + } + { + char what[160]; + + snprintf(what, sizeof(what), "protected refs for %s (%s, line %d)", + repo != NULL ? repo : "every repository", key, replaced); + return finish(&lines, path, o, what); + } +} diff --git a/src/glob.c b/src/glob.c new file mode 100644 index 0000000..7c6b969 --- /dev/null +++ b/src/glob.c @@ -0,0 +1,105 @@ +/* glob.c - the only pattern matching in this program. + * + * Three metacharacters, no library. See the note in authz.h for why this is + * not fnmatch(3) or regex(3). */ +#include "authz.h" + +/* Length of the class starting at p ('[' ... ']'), or 0 when it is not closed + * and therefore means a literal '['. A ']' first - or first after a negation - + * is a member, like everywhere else. */ +static int class_len(const char *p) +{ + const char *c = p + 1; + + if (*c == '!' || *c == '^') + c++; + if (*c == ']') + c++; + while (*c != '\0' && *c != ']') + c++; + return (*c == ']') ? (int)(c - p) + 1 : 0; +} + +/* text is a complete class of len bytes, including the brackets. */ +static int class_match(const char *text, int len, char c) +{ + const char *p = text + 1; + const char *end = text + len - 1; /* the ']' */ + int negate = 0; + int hit = 0; + + if (p < end && (*p == '!' || *p == '^')) { + negate = 1; + p++; + } + while (p < end) { + char lo = *p++; + if (p + 1 < end && *p == '-') { /* 'a-z'; a trailing '-' is literal */ + char hi = p[1]; + p += 2; + if (c >= lo && c <= hi) + hit = 1; + } else if (lo == c) { + hit = 1; + } + } + return negate ? !hit : hit; +} + +int glob_match(const char *pattern, const char *s) +{ + const char *p = pattern; + const char *t = s; + const char *star = NULL; /* in the pattern, just after the last '*' */ + const char *back = NULL; /* in the text, where that '*' may yet start */ + int clen; + + if (pattern == NULL || s == NULL) + return 0; + + while (*t != '\0') { + if (*p == '*') { + star = p + 1; + back = t; + p++; + continue; + } + + clen = (*p == '[') ? class_len(p) : 0; + if (clen > 0) { + if (!class_match(p, clen, *t)) { + /* The class was well formed and said no. Backtrack to the + * last '*' rather than comparing '[' against the text: a + * negated class must be able to fail. */ + if (star == NULL) + return 0; + p = star; + t = ++back; + continue; + } + p += clen; + t++; + continue; + } + + if (*p == '?') { + p++; + t++; + continue; + } + if (*p == *t) { + p++; + t++; + continue; + } + + if (star == NULL) + return 0; + p = star; + t = ++back; + } + + while (*p == '*') + p++; + return *p == '\0'; +} diff --git a/src/hook.c b/src/hook.c new file mode 100644 index 0000000..d4d801b --- /dev/null +++ b/src/hook.c @@ -0,0 +1,381 @@ +/* hook.c - the mode git calls, and the only one a push depends on. + * + * This is what `core.hooksPath` points at. The shape is git's: an identity in + * the environment, one "old new ref" line per ref on stdin, and a non-zero exit + * to stop the whole push. Nothing is asked of the client and nothing is + * inferred from the transport, because ref names travel inside a compressed + * request body - the hook is the first place they exist as data. + * + * Two facts are not in the hook's input, and only the object store has them: + * whether "old -> new" is a fast-forward, and which branch HEAD points at. + * Those are asked of git, and an answer that cannot be had is taken the + * expensive way: a rewrite until proven a fast-forward, and any deletion of a + * branch treated as the default one while HEAD itself is unknown. Guessing the + * cheap way would be the hole. + */ +#include "authz.h" + +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/wait.h> +#include <unistd.h> + +#define DEV_NULL "/dev/null" + +/* Run a program, optionally keeping the first line of its stdout. + * + * stdin is shut off from /dev/null: a child left holding the hook's stdin eats + * the ref lines that have not been read yet, and a push that loses refs from + * its own list is a push that skips checks. stderr goes to /dev/null too, so + * that a failed lookup does not shout "fatal:" at the person pushing about + * machinery they cannot touch. */ +static int spawn(const char *const argv[], int capture, char **out) +{ + int fds[2] = { -1, -1 }; + int status = -1; + pid_t pid; + + if (out != NULL) + *out = NULL; + if (capture && pipe(fds) != 0) + return -1; + + pid = fork(); + if (pid < 0) { + if (capture) { + close(fds[0]); + close(fds[1]); + } + return -1; + } + if (pid == 0) { + int devnull = open(DEV_NULL, O_RDWR); + + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (!capture) + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + if (devnull > 2) + close(devnull); + } + if (capture) { + dup2(fds[1], STDOUT_FILENO); + close(fds[0]); + close(fds[1]); + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + + if (capture) { + FILE *f; + + close(fds[1]); + f = fdopen(fds[0], "r"); + if (f != NULL) { + char *line = NULL; + size_t cap = 0; + + if (getline(&line, &cap, f) != -1) { + size_t n = strlen(line); + + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) + line[--n] = '\0'; + *out = line; + } else { + free(line); + } + fclose(f); + } else { + close(fds[0]); + } + } + + while (waitpid(pid, &status, 0) == -1) + ; + if (WIFEXITED(status)) + return WEXITSTATUS(status); + return -1; +} + +static int is_zero(const char *s) +{ + int i; + + if (s == NULL || s[0] == '\0') + return 0; + for (i = 0; s[i] != '\0'; i++) { + if (s[i] != '0') + return 0; + } + return 1; +} + +/* Object ids are 40 or 64 hex digits, or all zeroes for "does not exist". + * Anything else is a protocol oddity, and an oddity gets denied rather than + * interpreted. */ +static int object_id_ok(const char *s) +{ + size_t i; + int hex = 0; + + for (i = 0; s[i] != '\0'; i++) { + char c = s[i]; + + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F'))) + return 0; + hex++; + } + return hex == 40 || hex == 64; +} + +static char *head_ref(hook_opts o, int *unknown) +{ + const char *argv[4]; + char *out = NULL; + int rc; + + *unknown = 0; + if (strcmp(o.head, "none") == 0) + return NULL; + if (strcmp(o.head, "auto") != 0) + return xstrdup(o.head); + if (!o.use_git) + return NULL; /* told not to ask, so do not guess either way */ + + argv[0] = "git"; + argv[1] = "symbolic-ref"; + argv[2] = "-q"; + argv[3] = "HEAD"; + rc = spawn(argv, 1, &out); + if (rc == 0 && out != NULL && out[0] != '\0') + return out; + free(out); + *unknown = 1; /* cannot tell: charge deletions the most */ + return NULL; +} + +/* Is old an ancestor of new? */ +static int fast_forward(hook_opts o, const char *old, const char *new) +{ + const char *argv[5]; + int rc; + + if (strcmp(o.ff, "yes") == 0) + return 1; + if (strcmp(o.ff, "no") == 0) + return 0; + if (!o.use_git) + return 0; + + argv[0] = "git"; + argv[1] = "merge-base"; + argv[2] = "--is-ancestor"; + argv[3] = old; + argv[4] = new; + rc = spawn(argv, 0, NULL); + return rc == 0; +} + +static char *derive_repo(hook_opts o) +{ + const char *e; + const char *root; + size_t rootlen; + char *cwd; + char *name; + + if (o.repo != NULL) + return authz_norm_repo(o.repo); + e = getenv("GIT_HOST_REPO"); + if (e != NULL && e[0] != '\0') + return authz_norm_repo(e); + + cwd = getcwd(NULL, 0); + if (cwd == NULL) + return xstrdup(""); + root = getenv("GIT_REPO_ROOT"); + if (root == NULL || root[0] == '\0') + root = "/var/lib/git"; + rootlen = strlen(root); + while (rootlen > 1 && root[rootlen - 1] == '/') + rootlen--; /* "/var/lib/git/" is "/var/lib/git" */ + + if (strncmp(cwd, root, rootlen) == 0 && cwd[rootlen] == '/') + name = cwd + rootlen + 1; + else { + char *slash = strrchr(cwd, '/'); + + name = (slash != NULL && slash[1] != '\0') ? slash + 1 : cwd; + } + { + char *out = authz_norm_repo(name); + + free(cwd); + return out; + } +} + +static const char *identity(hook_opts o) +{ + const char *e; + + if (o.user != NULL) + return o.user; + e = getenv("GIT_HOST_USER"); + if (e != NULL && e[0] != '\0') + return e; + e = getenv("REMOTE_USER"); + if (e != NULL && e[0] != '\0') + return e; + return NULL; +} + +static int flag(const char *arg, const char *name, const char **slot) +{ + size_t n = strlen(name); + + if (strncmp(arg, name, n) != 0 || arg[n] != '=') + return 0; + *slot = arg + n + 1; + return 1; +} + +int cmd_authorize(const policy_t *p, hook_opts o, int argc, char **argv) +{ + char *line = NULL; + size_t cap = 0; + ssize_t len; + char *repo; + const char *user; + const char *head; + int head_unknown; + int seen = 0; + int i; + + if (o.ff == NULL) + o.ff = "auto"; + if (o.head == NULL) + o.head = "auto"; + + for (i = 0; i < argc; i++) { + if (flag(argv[i], "--user", &o.user)) + continue; + if (flag(argv[i], "--repo", &o.repo)) + continue; + if (flag(argv[i], "--ff", &o.ff)) + continue; + if (flag(argv[i], "--head", &o.head)) + continue; + if (strcmp(argv[i], "--no-git") == 0) { + o.use_git = 0; + continue; + } + if (strcmp(argv[i], "--explain") == 0) { + o.explain = 1; + continue; + } + fprintf(stderr, "%s: authorize: unknown argument %s\n", progname, argv[i]); + return 64; + } + if (strcmp(o.ff, "auto") != 0 && strcmp(o.ff, "yes") != 0 && + strcmp(o.ff, "no") != 0) { + fprintf(stderr, "%s: --ff wants auto, yes or no\n", progname); + return 64; + } + + user = identity(o); + repo = derive_repo(o); + head = head_ref(o, &head_unknown); + + while ((len = getline(&line, &cap, stdin)) != -1) { + char *fields[4]; + int nf = 0; + char *ref; + char *old; + char *new; + level_t need; + decision_t d; + + /* Split on whitespace by hand: the object ids and refnames in this line + * never contain it, and it keeps the reader's index the same as the + * writer's. */ + { + char *q = line; + + while (*q != '\0') { + while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r') + q++; + if (*q == '\0') + break; + fields[nf++] = q; + while (*q != '\0' && *q != ' ' && *q != '\t' && *q != '\n' && *q != '\r') + q++; + if (*q != '\0') + *q++ = '\0'; + if (nf == 4) + break; + } + } + if (nf == 0) + continue; + if (nf != 3) { + fprintf(stderr, "%s: deny: expected \"old new ref\", got %d field(s)\n", + progname, nf); + free(line); + free(repo); + free((char *)head); + return 1; + } + + old = fields[0]; + new = fields[1]; + ref = fields[2]; + seen++; + + if (!object_id_ok(old) || !object_id_ok(new) || + strncmp(ref, "refs/", 5) != 0) { + fprintf(stderr, "%s: deny: \"%s %s %s\" is not an update git would send\n", + progname, old, new, ref); + free(line); + free(repo); + free((char *)head); + return 1; + } + + if (is_zero(new)) { + /* A deletion. Branches cost force; the one HEAD points at costs + * an admin, because a repository without a default branch is a + * repository whose clones check out nothing. */ + need = LV_FORCE; + if (head_unknown || (head != NULL && strcmp(ref, head) == 0)) + need = LV_ADMIN; + } else if (is_zero(old)) { + need = LV_WRITE; /* a creation */ + } else { + need = fast_forward(o, old, new) ? LV_WRITE : LV_FORCE; + } + + authz_check(p, user, repo, need, ref, &d); + if (!d.allowed) { + fprintf(stderr, "%s: deny: %s\n", progname, d.why); + free(line); + free(repo); + free((char *)head); + return 1; + } + if (o.explain) + printf("%s: allow: %s\n", progname, d.why); + } + free(line); + free(repo); + free((char *)head); + + if (seen == 0 && o.explain) + printf("%s: nothing to check\n", progname); + return 0; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..1d7879b --- /dev/null +++ b/src/main.c @@ -0,0 +1,271 @@ +/* main.c - one program, four jobs. + * + * check an operator asking, or a script + * authorize git asking, once per push (also reached as 'pre-receive') + * validate the entrypoint and CI asking before anything is served + * edit changing the file (grant, revoke, protect) + * + * They are one program because they must agree, exactly, about what a rule + * means: a check that answers differently from the hook is worse than two + * programs, it is a program that lies. The exit status is the interface, and + * it never changes: 0 allowed, 1 denied, 3 no usable policy, 64 usage. + */ +#include "authz.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define POLICY_ENV "GIT_HOST_AUTHZ" +#define DEFAULT_POLICY "/etc/git-host/authz.conf" +#define DEFAULT_ROOT "/var/lib/git" +#define DEFAULT_HOOKS "/usr/local/share/git-host/hooks" +#define DEFAULT_GITCONFIG "/etc/gitconfig" +#define DEFAULT_SSHD "/etc/ssh/sshd_config" +#define DEFAULT_PASSWD "/etc/passwd" +#define DEFAULT_KEYS "/run/git-host/secrets/authorized_keys" +#define DEFAULT_HTPASSWD "/etc/git-host/secrets/htpasswd" + +static void usage(FILE *f) +{ + fprintf(f, +"usage: git-authz [--policy PATH] <command> [arguments]\n" +"\n" +" check <user> <repo> <write|force|admin> [ref]\n" +" one question: allow or deny on stdout, the reason with it.\n" +" Without a ref it asks about the repository as a whole.\n" +"\n" +" authorize read a push exactly as git's receive hook does - identity from\n" +" GIT_HOST_USER (ssh) or REMOTE_USER (http), one \"old new ref\" line per\n" +" ref on stdin - and deny the push on the first ref it may not allow.\n" +" This also runs as 'pre-receive', which is how core.hooksPath finds it.\n" +" --user U --repo R override the identity and the repository\n" +" --ff auto|yes|no whether to ask git if old is an ancestor of new\n" +" --head auto|none|REF the default branch, or how to treat deletions\n" +" --no-git ask git nothing (an unknown HEAD is not guessed)\n" +" --explain report the allows too\n" +"\n" +" validate is the policy parseable, and is the host wired to run it?\n" +" --no-host only the policy, none of the wiring below\n" +" --root DIR repositories (default %s)\n" +" --hook-dir DIR hooks (default %s)\n" +" --gitconfig FILE (default %s)\n" +" --sshd-config FILE (default %s)\n" +" --passwd FILE (default %s)\n" +" --keys FILE (default %s)\n" +" --htpasswd FILE (default %s)\n" +" --strict warnings are failures too\n" +"\n" +" grant <user> <repo> <level> [ref ...] add one rule, or replace that pair's\n" +" revoke <user> <repo> take it away again\n" +" protect [--repo R] <ref pattern> ... set which refs need an extra level\n" +" --out FILE | --stdout write elsewhere instead of in place\n" +" The deployed policy is a read-only mount on purpose; these are for the\n" +" source copy, and they say so when they are pointed at a read-only file.\n" +"\n" +"Levels are monotone: admin implies force implies write. '@all' means everyone\n" +"the policy already names. \"main\", \"heads/main\" and \"refs/heads/main\" are the\n" +"same branch; a bare name is always a branch and never a tag.\n" +"\n" +"Exit status: 0 allowed, 1 denied, 3 the policy could not be read or does not\n" +"parse - nothing is allowed on a policy that cannot be read - and 64 for usage.\n", +DEFAULT_ROOT, DEFAULT_HOOKS, DEFAULT_GITCONFIG, DEFAULT_SSHD, DEFAULT_PASSWD, +DEFAULT_KEYS, DEFAULT_HTPASSWD); +} + +static int one_option(int argc, char **argv, int *i, const char *name, const char **slot) +{ + size_t n = strlen(name); + + if (strcmp(argv[*i], name) == 0) { + if (*i + 1 >= argc) { + fprintf(stderr, "%s: %s wants a value\n", progname, name); + return -1; + } + *slot = argv[++*i]; + return 1; + } + if (strncmp(argv[*i], name, n) == 0 && argv[*i][n] == '=') { + *slot = argv[*i] + n + 1; + return 1; + } + return 0; +} + +/* Called when the policy is not usable: the only safe answer is no. */ +static int deny_policy(const char *path, int rc) +{ + fprintf(stderr, "%s: deny: the policy at %s %s\n", progname, path, + rc == -2 ? "cannot be read" : "does not parse"); + return 3; +} + +int main(int argc, char **argv) +{ + const char *path; + const char *base; + const char *cmd; + policy_t p; + hook_opts ho; + validate_opts vo; + edit_opts eo; + int i; + int rc; + + base = strrchr(argv[0], '/'); + progname = base != NULL ? base + 1 : argv[0]; + + path = getenv(POLICY_ENV); + if (path == NULL || path[0] == '\0') + path = DEFAULT_POLICY; + + memset(&ho, 0, sizeof(ho)); + ho.use_git = 1; + memset(&vo, 0, sizeof(vo)); + vo.root = DEFAULT_ROOT; + vo.hook_dir = DEFAULT_HOOKS; + vo.gitconfig = DEFAULT_GITCONFIG; + vo.sshd_config = DEFAULT_SSHD; + vo.passwd = DEFAULT_PASSWD; + vo.keys = DEFAULT_KEYS; + vo.htpasswd = DEFAULT_HTPASSWD; + memset(&eo, 0, sizeof(eo)); + + /* Reached as the hook itself: git's arguments to a hook are not ours, so + * they are ignored, and the policy comes from the environment. */ + if (strcmp(progname, "pre-receive") == 0) { + policy_init(&p, path); + rc = policy_load(&p); + if (rc != 0) + return deny_policy(path, rc); + return cmd_authorize(&p, ho, 0, NULL); + } + + i = 1; + while (i < argc && argv[i][0] == '-' && argv[i][1] != '\0') { + int got = one_option(argc, argv, &i, "--policy", &path); + + if (got < 0) + return 64; + if (got == 0 && (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)) { + usage(stdout); + return 0; + } + if (got == 0) { + fprintf(stderr, "%s: unknown option before the command: %s\n", progname, + argv[i]); + usage(stderr); + return 64; + } + i++; + } + if (i >= argc) { + usage(stderr); + return 64; + } + cmd = argv[i++]; + argc -= i; + argv += i; + + if (strcmp(cmd, "help") == 0 || strcmp(cmd, "-h") == 0 || + strcmp(cmd, "--help") == 0) { + usage(stdout); + return 0; + } + + if (strcmp(cmd, "grant") == 0 || strcmp(cmd, "revoke") == 0 || + strcmp(cmd, "protect") == 0) { + int consumed = 0; + + if (authz_parse_out(argc, argv, &eo, &consumed) != 0) + return 64; + argc -= consumed; + argv += consumed; + if (strcmp(cmd, "grant") == 0) + return cmd_grant(path, eo, argc, argv); + if (strcmp(cmd, "revoke") == 0) + return cmd_revoke(path, eo, argc, argv); + return cmd_protect(path, eo, argc, argv); + } + + /* Everything else answers from the policy, so read it once, here. */ + policy_init(&p, path); + rc = policy_load(&p); + + if (strcmp(cmd, "validate") == 0) { + int j; + + for (j = 0; j < argc; j++) { + int got; + + got = one_option(argc, argv, &j, "--root", &vo.root); + if (got == 0) + got = one_option(argc, argv, &j, "--hook-dir", &vo.hook_dir); + if (got == 0) + got = one_option(argc, argv, &j, "--gitconfig", &vo.gitconfig); + if (got == 0) + got = one_option(argc, argv, &j, "--sshd-config", &vo.sshd_config); + if (got == 0) + got = one_option(argc, argv, &j, "--passwd", &vo.passwd); + if (got == 0) + got = one_option(argc, argv, &j, "--keys", &vo.keys); + if (got == 0) + got = one_option(argc, argv, &j, "--htpasswd", &vo.htpasswd); + if (got < 0) + return 64; + if (got == 0 && strcmp(argv[j], "--strict") == 0) { + vo.strict = 1; + continue; + } + if (got == 0 && strcmp(argv[j], "--no-host") == 0) { + vo.root = NULL; + vo.hook_dir = NULL; + vo.sshd_config = NULL; + vo.passwd = NULL; + vo.keys = NULL; + vo.htpasswd = NULL; + vo.gitconfig = NULL; + continue; + } + if (got == 0) { + fprintf(stderr, "%s: validate: unknown argument %s\n", progname, + argv[j]); + return 64; + } + } + /* cmd_validate reports the parse errors itself: a policy that does not + * parse is the finding, not a reason to say nothing. */ + return cmd_validate(&p, vo); + } + + if (strcmp(cmd, "authorize") == 0) { + if (rc != 0) + return deny_policy(path, rc); + return cmd_authorize(&p, ho, argc, argv); + } + + if (strcmp(cmd, "check") == 0) { + decision_t d; + int level; + + if (rc != 0) + return deny_policy(path, rc); + if (argc < 3 || argc > 4) { + fprintf(stderr, "%s: check wants <user> <repo> <level> [ref]\n", progname); + return 64; + } + level = authz_level_of(argv[2]); + if (level < 0) { + fprintf(stderr, "%s: unknown access level \"%s\" (write force admin)\n", + progname, argv[2]); + return 64; + } + authz_check(&p, argv[0], argv[1], (level_t)level, argc > 3 ? argv[3] : NULL, &d); + printf("%s: %s\n", d.allowed ? "allow" : "deny", d.why); + return d.allowed ? 0 : 1; + } + + fprintf(stderr, "%s: unknown command \"%s\"\n", progname, cmd); + usage(stderr); + return 64; +} diff --git a/src/policy.c b/src/policy.c new file mode 100644 index 0000000..ffce34d --- /dev/null +++ b/src/policy.c @@ -0,0 +1,651 @@ +/* policy.c - reading the policy, and answering from it. + * + * Grammar (see authz.conf for the prose version): + * + * set protected-refs <pattern> ... globally, default refs/heads/main + * set protected-refs.<repo> <pattern> ... for one repository, replacing it + * <user> <repo> <write|force|admin> [<ref pattern> ...] + * + * '#' starts a comment wherever it appears. Rules are additive and the + * strongest match wins; there is no 'deny', so a rule is taken away by editing + * the file, not by ordering it after another one. + * + * A line that does not parse is an error, and a policy with errors is not used + * at all: it is better for every push to be refused for one evening than for a + * mistyped line to quietly widen somebody's access. */ +#include "authz.h" + +#include <ctype.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define DEFAULT_PROTECTED "refs/heads/main" + +/* The characters a name may contain, spelled out rather than as a regular + * expression: the engine has none, and the message says why. */ +static const char letters[] = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +static const char user_first[] = "_@*?["; +static const char user_rest[] = "_@*?[].-"; +static const char repo_chars[] = "._*?-"; + +static int in_set(unsigned char c, const char *extra) +{ + return c != '\0' && (strchr(letters, (int)c) != NULL || + strchr(extra, (int)c) != NULL); +} + +/* ------------------------------------------------------------------ little */ + +/* Trims in place: leading by moving the pointer, trailing by writing over it. */ +char *authz_trim(char *s) +{ + char *end; + + while (*s != '\0' && isspace((unsigned char)*s)) + s++; + end = s + strlen(s); + while (end > s && isspace((unsigned char)end[-1])) + end--; + *end = '\0'; + return s; +} + +int authz_split_ws(char *line, char **f, int max) +{ + int n = 0; + char *p = line; + + while (*p != '\0') { + while (*p != '\0' && isspace((unsigned char)*p)) + p++; + if (*p == '\0') + break; + f[n++] = p; + while (*p != '\0' && !isspace((unsigned char)*p)) + p++; + if (*p != '\0') + *p++ = '\0'; + if (n == max) + return n + 1; /* "too many", the caller decides */ + } + return n; +} + +static void report(policy_t *p, int line, const char *kind, + const char *fmt, va_list ap) +{ + fprintf(stderr, "%s:%d: %s: ", p->path != NULL ? p->path : "authz.conf", line, kind); + vfprintf(stderr, fmt, ap); + fputc('\n', stderr); +} + +static void perr(policy_t *p, int line, const char *fmt, ...) +{ + va_list ap; + + p->errors++; + va_start(ap, fmt); + report(p, line, "error", fmt, ap); + va_end(ap); +} + +static void pwarn(policy_t *p, int line, const char *fmt, ...) +{ + va_list ap; + + p->warnings++; + va_start(ap, fmt); + report(p, line, "warning", fmt, ap); + va_end(ap); +} + +/* ------------------------------------------------------------ name shapes */ + +int authz_user_pattern_ok(const char *s) +{ + size_t i; + + if (s[0] == '\0' || !in_set((unsigned char)s[0], user_first)) + return 0; + for (i = 1; s[i] != '\0'; i++) { + if (!in_set((unsigned char)s[i], user_rest)) + return 0; + } + return 1; +} + +int authz_repo_pattern_ok(const char *s) +{ + size_t i; + + if (s[0] == '\0') + return 0; + for (i = 0; s[i] != '\0'; i++) { + if (!in_set((unsigned char)s[i], repo_chars)) + return 0; + } + return 1; +} + +/* ------------------------------------------------------------------ levels */ + +const char *authz_level_name(level_t l) +{ + switch (l) { + case LV_WRITE: return "write"; + case LV_FORCE: return "force"; + case LV_ADMIN: return "admin"; + default: return "none"; + } +} + +int authz_level_of(const char *name) +{ + if (name == NULL) + return -1; + if (strcmp(name, "write") == 0) + return LV_WRITE; + if (strcmp(name, "force") == 0) + return LV_FORCE; + if (strcmp(name, "admin") == 0) + return LV_ADMIN; + return -1; +} + +/* ----------------------------------------------------------- normalisation */ + +char *authz_norm_repo(const char *in) +{ + size_t n; + + if (in == NULL) + return xstrdup(""); + if (strcmp(in, "*") == 0) + return xstrdup("*"); + n = strlen(in); + if (n > 4 && strcmp(in + n - 4, ".git") == 0) + return xsubstr(in, n - 4); + return xstrdup(in); +} + +/* One spelling for a ref, so that "main", "heads/main" and "refs/heads/main" + * are the same branch - and so that a bare name can never mean a tag. */ +char *authz_norm_ref(const char *in) +{ + size_t n; + char *out; + + if (in == NULL || *in == '\0') + return xstrdup("refs/*"); + if (strcmp(in, "*") == 0 || strcmp(in, "all") == 0 || + strcmp(in, "refs") == 0 || strcmp(in, "refs/*") == 0) + return xstrdup("refs/*"); + if (strncmp(in, "refs/", 5) == 0) + return xstrdup(in); + + /* "heads/main", "tags/v1" and "notes/x" are half a refname: the "refs/" is + * missing and nothing else. Anything at all, including a path with slashes + * in it, is a branch name. */ + if (strncmp(in, "heads/", 6) == 0 || strncmp(in, "tags/", 5) == 0 || + strncmp(in, "notes/", 6) == 0) { + n = strlen(in) + 6; + out = xmalloc(n); + snprintf(out, n, "refs/%s", in); + return out; + } + n = strlen(in) + 12; + out = xmalloc(n); + snprintf(out, n, "refs/heads/%s", in); + return out; +} + +/* A whole list of them, space separated, the way 'set' lines store them. */ +static char *norm_ref_list(const char *value) +{ + char *copy = xstrdup(value); + char *fields[MAX_FIELDS]; + strbuf_t out; + int i, n; + + sb_init(&out); + n = authz_split_ws(copy, fields, MAX_FIELDS); + for (i = 0; i < n; i++) { + char *one = authz_norm_ref(fields[i]); + + if (out.len != 0) + sb_add(&out, " "); + sb_add(&out, one); + free(one); + } + free(copy); + return out.s; +} + +/* ------------------------------------------------------------------ tables */ + +static rule_t *rule_slot(policy_t *p) +{ + rule_t *r; + + if (p->nrules == p->rcap) { + p->rcap = p->rcap != 0 ? p->rcap * 2 : 32; + p->rules = xrealloc(p->rules, p->rcap * sizeof(*p->rules)); + } + r = &p->rules[p->nrules++]; + memset(r, 0, sizeof(*r)); + return r; +} + +static void set_protected_for(policy_t *p, const char *repo, const char *refs, int line) +{ + size_t i; + + for (i = 0; i < p->nprot; i++) { + if (strcmp(p->prot_repo[i], repo) == 0) { + pwarn(p, line, "protected-refs for %s is set twice; the last one wins", repo); + free(p->prot_refs[i]); + p->prot_refs[i] = xstrdup(refs); + return; + } + } + if (p->nprot == p->pcap) { + p->pcap = p->pcap != 0 ? p->pcap * 2 : 8; + p->prot_repo = xrealloc(p->prot_repo, p->pcap * sizeof(*p->prot_repo)); + p->prot_refs = xrealloc(p->prot_refs, p->pcap * sizeof(*p->prot_refs)); + } + p->prot_repo[p->nprot] = xstrdup(repo); + p->prot_refs[p->nprot] = xstrdup(refs); + p->nprot++; +} + +/* ---------------------------------------------------------------- the file */ + +static void parse_set(policy_t *p, char *line, int lineno) +{ + char *body = authz_trim(line + 3); + char *sp = body; + char *key, *val, *repo; + + while (*sp != '\0' && !isspace((unsigned char)*sp)) + sp++; + if (*sp == '\0') { + perr(p, lineno, "set needs a value"); + return; + } + key = xsubstr(body, (size_t)(sp - body)); + val = authz_trim(sp); + + if (strcmp(key, "protected-refs") == 0) { + if (p->protected_global != NULL) + pwarn(p, lineno, "set protected-refs appears twice; the last one wins"); + free(p->protected_global); + p->protected_global = norm_ref_list(val); + } else if (strncmp(key, "protected-refs.", 15) == 0) { + repo = authz_norm_repo(key + 15); + if (repo[0] == '\0' || strcmp(repo, "*") == 0) { + perr(p, lineno, "protected-refs. needs one repository, not \"%s\"", key + 15); + } else { + set_protected_for(p, repo, val, lineno); + } + free(repo); + } else { + perr(p, lineno, "unknown setting \"%s\"", key); + } + free(key); +} + +static void parse_rule(policy_t *p, char *line, int lineno) +{ + char *fields[MAX_FIELDS]; + rule_t *r; + int n, i, level; + + n = authz_split_ws(line, fields, MAX_FIELDS); + if (n > MAX_FIELDS) { + perr(p, lineno, "more than %d fields on one line", MAX_FIELDS); + return; + } + if (n < 3) { + perr(p, lineno, "expected \"<user> <repo> <level> [ref ...]\": %s", line); + return; + } + level = authz_level_of(fields[2]); + if (level < 0) { + perr(p, lineno, "unknown access level \"%s\" (write force admin)", fields[2]); + return; + } + if (strcmp(fields[0], "@all") != 0 && !authz_user_pattern_ok(fields[0])) { + perr(p, lineno, "invalid user pattern \"%s\"", fields[0]); + return; + } + if (!authz_repo_pattern_ok(fields[1])) { + perr(p, lineno, "invalid repo pattern \"%s\" (flat names only, no slashes)", + fields[1]); + return; + } + for (i = 3; i < n; i++) { + if (fields[i][0] == '!' || fields[i][0] == '-') { + perr(p, lineno, "ref patterns are additive, there is no deny: %s", fields[i]); + return; + } + } + + r = rule_slot(p); + r->user = xstrdup(fields[0]); + r->repo = authz_norm_repo(fields[1]); + r->level = (level_t)level; + r->line = lineno; + if (n > 3) { + r->refs = xmalloc((size_t)(n - 3) * sizeof(*r->refs)); + for (i = 3; i < n; i++) + r->refs[r->nrefs++] = authz_norm_ref(fields[i]); + } +} + +void policy_init(policy_t *p, const char *path) +{ + memset(p, 0, sizeof(*p)); + p->path = xstrdup(path); +} + +void policy_free(policy_t *p) +{ + size_t i; + size_t j; + + for (i = 0; i < p->nrules; i++) { + free(p->rules[i].user); + free(p->rules[i].repo); + for (j = 0; j < p->rules[i].nrefs; j++) + free(p->rules[i].refs[j]); + free(p->rules[i].refs); + } + free(p->rules); + free(p->protected_global); + for (i = 0; i < p->nprot; i++) { + free(p->prot_repo[i]); + free(p->prot_refs[i]); + } + free(p->prot_repo); + free(p->prot_refs); + free(p->path); + memset(p, 0, sizeof(*p)); +} + +int policy_load(policy_t *p) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + int lineno = 0; + + f = fopen(p->path, "r"); + if (f == NULL) { + fprintf(stderr, "%s: cannot read the policy: ", p->path); + perror(""); + return -2; + } + while ((len = getline(&line, &cap, f)) != -1) { + char *hash; + char *text; + + lineno++; + text = authz_trim(line); + hash = strchr(text, '#'); + if (hash != NULL) { + *hash = '\0'; + text = authz_trim(text); + } + if (*text == '\0') + continue; + + if (strncmp(text, "set", 3) == 0 && isspace((unsigned char)text[3])) + parse_set(p, text, lineno); + else + parse_rule(p, text, lineno); + } + free(line); + fclose(f); + return p->errors > 0 ? -1 : 0; +} + +/* ------------------------------------------------------------- the answers */ + +static int user_match(const policy_t *p, const char *pat, const char *user) +{ + if (user == NULL || user[0] == '\0') + return 0; + if (strcmp(pat, "@all") == 0) + return authz_user_known(p, user); + return glob_match(pat, user); +} + +static int repo_match(const char *pat, const char *repo) +{ + char *want; + int hit; + + if (strcmp(pat, "*") == 0) + return 1; + want = authz_norm_repo(repo); + hit = glob_match(pat, want); + free(want); + return hit; +} + +int authz_user_known(const policy_t *p, const char *user) +{ + size_t i; + + if (user == NULL || user[0] == '\0') + return 0; + for (i = 0; i < p->nrules; i++) { + if (strcmp(p->rules[i].user, "@all") == 0) + continue; + if (glob_match(p->rules[i].user, user)) + return 1; + } + return 0; +} + +int authz_repo_reachable(const policy_t *p, const char *repo) +{ + size_t i; + + for (i = 0; i < p->nrules; i++) { + if (repo_match(p->rules[i].repo, repo)) + return 1; + } + return 0; +} + +const char *authz_protected_for(const policy_t *p, const char *repo) +{ + char *want; + size_t i; + + want = authz_norm_repo(repo); + for (i = 0; i < p->nprot; i++) { + if (strcmp(p->prot_repo[i], want) == 0) { + free(want); + return p->prot_refs[i]; + } + } + free(want); + if (p->protected_global != NULL && p->protected_global[0] != '\0') + return p->protected_global; + return DEFAULT_PROTECTED; +} + +static int is_protected(const policy_t *p, const char *repo, const char *ref) +{ + const char *list = authz_protected_for(p, repo); + char *copy = xstrdup(list); + char *fields[MAX_FIELDS]; + int n, i, hit = 0; + + n = authz_split_ws(copy, fields, MAX_FIELDS); + for (i = 0; i < n; i++) { + if (glob_match(fields[i], ref)) { + hit = 1; + break; + } + } + free(copy); + return hit; +} + +static int ordinary_ref(const char *ref) +{ + return strncmp(ref, "refs/heads/", 11) == 0 || strncmp(ref, "refs/tags/", 10) == 0; +} + +level_t authz_need_for(const policy_t *p, const char *repo, const char *ref, + level_t have, char *raised, size_t raisedsz) +{ + if (raised != NULL && raisedsz > 0) + raised[0] = '\0'; + + /* Anything that is not a branch or a tag is for maintainers: refs/notes, + * refs/merge-requests, whatever a tool invents next. */ + if (!ordinary_ref(ref) && have != LV_ADMIN) { + if (raised != NULL) + snprintf(raised, raisedsz, "neither a branch nor a tag"); + return LV_ADMIN; + } + if (!is_protected(p, repo, ref)) + return have; + if (have == LV_WRITE || have == LV_FORCE) { + if (raised != NULL) + snprintf(raised, raisedsz, "protected"); + return have == LV_WRITE ? LV_FORCE : LV_ADMIN; + } + return have; +} + +/* Everything one user may do to one repository at or above 'min': whether any + * of it is unscoped, whether 'ref' is covered, and the strongest level the user + * holds there at all (which is what a denial names). */ +typedef struct { + int unscoped; /* a rule with no ref list: the whole repository */ + int scoped; /* a rule with a ref list, at or above the level */ + int hit; /* and one of its patterns is this ref */ + level_t strongest; /* the best this user holds there at all */ + int any; /* any rule at all, at any level */ +} scope_t; + +static void scope(const policy_t *p, const char *user, const char *repo, + level_t min, const char *ref, scope_t *s) +{ + size_t i; + size_t j; + + s->unscoped = 0; + s->scoped = 0; + s->hit = 0; + s->strongest = LV_NONE; + s->any = 0; + + for (i = 0; i < p->nrules; i++) { + if (!user_match(p, p->rules[i].user, user)) + continue; + if (!repo_match(p->rules[i].repo, repo)) + continue; + s->any = 1; + if (p->rules[i].level > s->strongest) + s->strongest = p->rules[i].level; + if (p->rules[i].level < min) + continue; + if (p->rules[i].nrefs == 0) { + s->unscoped = 1; + continue; + } + s->scoped = 1; + for (j = 0; ref != NULL && j < p->rules[i].nrefs; j++) { + if (glob_match(p->rules[i].refs[j], ref)) { + s->hit = 1; + break; + } + } + } +} + +void authz_check(const policy_t *p, const char *user, const char *repo, + level_t need, const char *ref, decision_t *out) +{ + scope_t s; + char raised[64]; + char *nref = NULL; + level_t want = need; + + out->allowed = 0; + out->need = need; + out->why[0] = '\0'; + + if (user == NULL || user[0] == '\0') { + out->need = need; + snprintf(out->why, sizeof(out->why), "no identity was presented"); + return; + } + + if (ref == NULL) { + /* No ref named: "may this user do this somewhere in the repository?" */ + scope(p, user, repo, need, NULL, &s); + if (s.unscoped || s.scoped) { + snprintf(out->why, sizeof(out->why), "%s has %s on %s of %s", + user, authz_level_name(need), + s.unscoped ? "all" : "some refs", authz_norm_repo(repo)); + out->allowed = 1; + } else { + snprintf(out->why, sizeof(out->why), "%s has no %s on %s", + user, authz_level_name(need), authz_norm_repo(repo)); + } + return; + } + + nref = authz_norm_ref(ref); + want = authz_need_for(p, repo, nref, need, raised, sizeof(raised)); + out->need = want; + + scope(p, user, repo, want, nref, &s); + + if (s.unscoped || s.hit) { + char *r = authz_norm_repo(repo); + + if (raised[0] != '\0') + snprintf(out->why, sizeof(out->why), + "%s has %s on %s %s (raised from %s: %s is %s)", + user, authz_level_name(want), r, nref, + authz_level_name(need), nref, raised); + else + snprintf(out->why, sizeof(out->why), "%s has %s on %s %s", + user, authz_level_name(want), r, nref); + free(r); + out->allowed = 1; + free(nref); + return; + } + + { + char *r = authz_norm_repo(repo); + + if (!s.any) + snprintf(out->why, sizeof(out->why), "%s has no rule for %s; %s needs %s", + user, authz_norm_repo(repo), nref, authz_level_name(want)); + else if (raised[0] != '\0') + snprintf(out->why, sizeof(out->why), + "%s has %s on %s; %s needs %s (raised from %s: %s is %s)", + user, authz_level_name(s.strongest), r, nref, + authz_level_name(want), authz_level_name(need), nref, raised); + else + snprintf(out->why, sizeof(out->why), "%s has %s on %s; %s needs %s", + user, authz_level_name(s.strongest), r, nref, + authz_level_name(want)); + free(r); + } + free(nref); +} diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..a7513b3 --- /dev/null +++ b/src/util.c @@ -0,0 +1,118 @@ +/* util.c - allocation that stops rather than limps, and a name for messages. + * + * A hook that cannot allocate is not in a position to decide anything, so + * these exit with the policy-unavailable status rather than returning NULL + * somewhere the caller forgot to look. */ +#include "authz.h" + +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +const char *progname = "git-authz"; + +static void oom(void) +{ + fprintf(stderr, "%s: out of memory\n", progname); + exit(3); +} + +void sb_init(strbuf_t *b) +{ + b->cap = 64; + b->len = 0; + b->s = xmalloc(b->cap); + b->s[0] = '\0'; +} + +static void sb_room(strbuf_t *b, size_t extra) +{ + if (b->len + extra + 1 <= b->cap) + return; + while (b->len + extra + 1 > b->cap) + b->cap *= 2; + b->s = xrealloc(b->s, b->cap); +} + +void sb_add(strbuf_t *b, const char *s) +{ + size_t n; + + if (s == NULL) + return; + n = strlen(s); + sb_room(b, n); + memcpy(b->s + b->len, s, n + 1); + b->len += n; +} + +void sb_addf(strbuf_t *b, const char *fmt, ...) +{ + va_list ap; + int n; + char *out; + + va_start(ap, fmt); + n = vsnprintf(NULL, 0, fmt, ap); + va_end(ap); + if (n < 0) + return; + sb_room(b, (size_t)n); + va_start(ap, fmt); + out = b->s + b->len; + n = vsnprintf(out, b->cap - b->len, fmt, ap); + va_end(ap); + if (n < 0) { + b->s[b->len] = '\0'; + return; + } + b->len += (size_t)n; +} + +void sb_free(strbuf_t *b) +{ + free(b->s); + b->s = NULL; + b->len = b->cap = 0; +} + +void *xmalloc(size_t n) +{ + void *p = malloc(n != 0 ? n : 1); + + if (p == NULL) + oom(); + return p; +} + +void *xrealloc(void *ptr, size_t n) +{ + void *p = realloc(ptr, n != 0 ? n : 1); + + if (p == NULL) + oom(); + return p; +} + +char *xstrdup(const char *s) +{ + size_t n; + char *p; + + if (s == NULL) + return NULL; + n = strlen(s) + 1; + p = xmalloc(n); + memcpy(p, s, n); + return p; +} + +char *xsubstr(const char *s, size_t len) +{ + char *p = xmalloc(len + 1); + + memcpy(p, s, len); + p[len] = '\0'; + return p; +} diff --git a/src/validate.c b/src/validate.c new file mode 100644 index 0000000..fd8abb9 --- /dev/null +++ b/src/validate.c @@ -0,0 +1,483 @@ +/* validate.c - does this policy, and the host around it, add up? + * + * Run from the entrypoint before anything is served, and from CI. A container + * that starts with a policy nobody can read, or a hooks path that points + * nowhere, is a container that serves repositories nobody can push to - or + * anybody can. Both are found here, in the second, rather than in the first + * push of the morning. + * + * Errors mean "a push would be authorised wrongly". Warnings mean "a human is + * going to file a ticket". Missing files are skipped, not warned about: on a + * developer machine there is no sshd_config here, and a validator that cries + * about that gets ignored, which is worse than not checking. + */ +#include "authz.h" + +#include <ctype.h> +#include <dirent.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +/* Tally of what this one run found. One validate per process, so file scope + * is enough and the helpers stay readable. */ +static int g_errors; +static int g_warnings; + +static void verr(const char *fmt, ...) +{ + va_list ap; + + g_errors++; + fputs("err ", stderr); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); +} + +static void vwarn(const char *fmt, ...) +{ + va_list ap; + + g_warnings++; + fputs("warn ", stderr); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); +} + +static void vok(const char *fmt, ...) +{ + va_list ap; + + fputs("ok ", stdout); + va_start(ap, fmt); + vfprintf(stdout, fmt, ap); + va_end(ap); + fputc('\n', stdout); +} + +/* ------------------------------------------------------------- file lookups */ + +static int ci_equal(const char *a, const char *b) +{ + for (; *a != '\0' && *b != '\0'; a++, b++) { + if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) + return 0; + } + return *a == '\0' && *b == '\0'; +} + +static char *strip(char *s) +{ + char *end; + + while (*s != '\0' && isspace((unsigned char)*s)) + s++; + end = s + strlen(s); + while (end > s && isspace((unsigned char)end[-1])) + end--; + *end = '\0'; + return s; +} + +/* An ini file's value for [section] key = value, last one winning. Used for + * gitconfig, where a value set twice is exactly the mistake worth reporting. */ +static int ini_value(const char *path, const char *section, const char *key, + char *out, size_t outsz) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + char here[64]; + int in = 0; + int found = 0; + + snprintf(here, sizeof(here), "[%s]", section); + f = fopen(path, "r"); + if (f == NULL) + return -1; + while ((len = getline(&line, &cap, f)) != -1) { + char *t = strip(line); + char *eq; + + if (*t == '\0' || *t == '#' || *t == ';') + continue; + if (*t == '[') { + in = strncmp(t, here, strlen(here)) == 0; + continue; + } + if (!in) + continue; + eq = strchr(t, '='); + if (eq == NULL) + continue; + *eq = '\0'; + if (!ci_equal(strip(t), key)) + continue; + snprintf(out, outsz, "%s", strip(eq + 1)); + { /* gitconfig allows quoting */ + size_t n = strlen(out); + + if (n >= 2 && out[0] == '"' && out[n - 1] == '"') { + memmove(out, out + 1, n - 2); + out[n - 2] = '\0'; + } + } + found = 1; + } + free(line); + fclose(f); + return found; +} + +/* sshd_config's "Directive value", last one winning, case-insensitive. */ +static int directive_value(const char *path, const char *name, char *out, size_t outsz) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + int found = 0; + + f = fopen(path, "r"); + if (f == NULL) + return -1; + while ((len = getline(&line, &cap, f)) != -1) { + char *t = strip(line); + char *sp; + + if (*t == '\0' || *t == '#') + continue; + sp = t; + while (*sp != '\0' && !isspace((unsigned char)*sp)) + sp++; + if (*sp == '\0') + continue; + *sp = '\0'; + if (!ci_equal(t, name)) + continue; + snprintf(out, outsz, "%s", strip(sp + 1)); + found = 1; + } + free(line); + fclose(f); + return found; +} + +/* -------------------------------------------------------------- the checks */ + +static void check_repos(const policy_t *p, const char *root) +{ + DIR *d; + struct dirent *ent; + int ondisk = 0; + size_t i; + + d = opendir(root); + if (d == NULL) { + vok("no repository root at %s (nothing to cross-check)", root); + return; + } + while ((ent = readdir(d)) != NULL) { + size_t n = strlen(ent->d_name); + char path[4096]; + struct stat st; + + if (n <= 4 || strcmp(ent->d_name + n - 4, ".git") != 0) + continue; + snprintf(path, sizeof(path), "%s/%s", root, ent->d_name); + if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) + continue; + ondisk++; + { + char *name = authz_norm_repo(ent->d_name); + + if (!authz_repo_reachable(p, name)) + vwarn("%s is readable and nobody can push to it", name); + free(name); + } + } + closedir(d); + + /* The other direction: a rule naming a repository that is not there is + * almost always a repository that was renamed, and the rule looks fine. */ + for (i = 0; i < p->nrules; i++) { + const char *r = p->rules[i].repo; + + if (r == NULL || strpbrk(r, "*?[") != NULL || strcmp(r, "*") == 0) + continue; + { + char path[4096]; + struct stat st; + + snprintf(path, sizeof(path), "%s/%s.git", root, r); + if (stat(path, &st) != 0) + vwarn("line %d gives %s access to %s, which is not in %s", + p->rules[i].line, p->rules[i].user, r, root); + } + } + if (ondisk > 0) + vok("%d repository/repositories under %s", ondisk, root); +} + +static void check_hook(const policy_t *p, validate_opts o) +{ + char path[4096]; + struct stat st; + char hooks[4096]; + int rc; + + (void)p; + snprintf(path, sizeof(path), "%s/pre-receive", o.hook_dir); + if (stat(path, &st) != 0) { + verr("no hook at %s: every push would be accepted unchecked", path); + return; + } + if (access(path, X_OK) != 0) + verr("%s is not executable: git would skip it", path); + else + vok("hook %s", path); + + rc = ini_value(o.gitconfig, "core", "hooksPath", hooks, sizeof(hooks)); + if (rc == -1) { + vok("no gitconfig at %s (nothing to cross-check)", o.gitconfig); + return; + } + if (rc == 0) + verr("%s does not set core.hooksPath: %s is never run", o.gitconfig, path); + else if (strcmp(hooks, o.hook_dir) != 0) + verr("core.hooksPath is %s, not %s: pushes are checked by something else", + hooks, o.hook_dir); + else + vok("core.hooksPath -> %s", hooks); +} + +static void check_sshd(const policy_t *p, validate_opts o) +{ + char value[4096]; + int rc; + + rc = directive_value(o.sshd_config, "PermitUserEnvironment", value, sizeof(value)); + if (rc == -1) { + vok("no sshd config at %s (nothing to cross-check)", o.sshd_config); + return; + } + if (rc == 0 || !ci_equal(value, "yes")) + verr("PermitUserEnvironment is not yes in %s: key identities are dropped, " + "and every push arrives anonymous", o.sshd_config); + else + vok("PermitUserEnvironment yes"); + + rc = directive_value(o.sshd_config, "ForceCommand", value, sizeof(value)); + if (rc == 0) + verr("%s sets no ForceCommand: a key can run an interactive shell", + o.sshd_config); + else + vok("ForceCommand %s", value); + + rc = directive_value(o.sshd_config, "AuthorizedKeysFile", value, sizeof(value)); + if (rc == 1 && o.keys != NULL && strstr(value, o.keys) == NULL) + vwarn("AuthorizedKeysFile is \"%s\", which does not include %s", value, o.keys); + (void)p; +} + +static void check_account(const policy_t *p, validate_opts o) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + int found = 0; + + (void)p; + f = fopen(o.passwd, "r"); + if (f == NULL) { + vok("no %s (nothing to cross-check)", o.passwd); + return; + } + while ((len = getline(&line, &cap, f)) != -1) { + char *fields[9]; + int nf = 0; + char *q = line; + + while (*q != '\0') { + while (*q != '\0' && *q != ':') + q++; + fields[nf++] = q; + if (*q == '\0') + break; + *q++ = '\0'; + if (nf == 8) + break; + } + if (nf == 8 && strcmp(fields[0], "git") == 0) { + char *shell = strip(fields[7]); + + found = 1; + if (strstr(shell, "git-shell") == NULL) + verr("the git account's shell is %s, not git-shell: ssh keys " + "would land in a real shell", shell); + else + vok("git account shell %s", shell); + break; + } + } + free(line); + fclose(f); + if (!found) + vwarn("no git account in %s", o.passwd); +} + +static void check_keys(const policy_t *p, validate_opts o) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + int n = 0; + + f = fopen(o.keys, "r"); + if (f == NULL) { + vok("no authorized_keys at %s (nothing to cross-check)", o.keys); + return; + } + while ((len = getline(&line, &cap, f)) != -1) { + char *t = strip(line); + char *at; + + if (*t == '\0' || *t == '#') + continue; + n++; + at = strstr(t, "GIT_HOST_USER="); + if (at == NULL) { + char *nl = strchr(t, '\n'); + char *sp; + + if (nl != NULL) + *nl = '\0'; + sp = strchr(t, ' '); + if (sp != NULL) + *sp = '\0'; /* leave the key type, e.g. ssh-ed25519 */ + vwarn("a %s key carries no GIT_HOST_USER: pushes made with it are " + "anonymous and will be denied", t); + continue; + } + at += strlen("GIT_HOST_USER="); + { + char name[256]; + size_t i = 0; + + while (at[i] != '\0' && at[i] != '"' && at[i] != ',' && at[i] != ' ' && + i + 1 < sizeof(name)) { + name[i] = at[i]; + i++; + } + name[i] = '\0'; + if (i == 0) + vwarn("an empty GIT_HOST_USER: pushes made with that key are denied"); + else if (!authz_user_known(p, name)) + vwarn("key identity \"%s\" has no rule in %s: the key works and " + "every push is denied", name, p->path); + } + } + free(line); + fclose(f); + if (n > 0) + vok("%d ssh key(s) in %s", n, o.keys); +} + +static void check_htpasswd(const policy_t *p, validate_opts o) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + ssize_t len; + int n = 0; + + f = fopen(o.htpasswd, "r"); + if (f == NULL) { + vok("no htpasswd at %s (nothing to cross-check)", o.htpasswd); + return; + } + while ((len = getline(&line, &cap, f)) != -1) { + char *t = strip(line); + char *colon; + + if (*t == '\0' || *t == '#') + continue; + n++; + colon = strchr(t, ':'); + if (colon == NULL) { + vwarn("%s: a line with no \":\" is not an htpasswd entry", o.htpasswd); + continue; + } + *colon = '\0'; + if (!authz_user_known(p, t)) + vwarn("htpasswd user \"%s\" has no rule in %s: they can authenticate " + "and change nothing", t, p->path); + } + free(line); + fclose(f); + if (n > 0) + vok("%d http user(s) in %s", n, o.htpasswd); +} + +int cmd_validate(const policy_t *p, validate_opts o) +{ + size_t i; + struct stat st; + + g_errors = 0; + g_warnings = 0; + + /* Anything the parser already complained about went to stderr with its line + * number. A policy with errors is not used at all, so nothing else here + * matters until it is fixed. */ + if (p->errors > 0) { + verr("%s: %d error(s): the policy is not used, and every push is denied", + p->path, p->errors); + return 3; + } + vok("%s: %zu rule(s), protected refs: %s", p->path, p->nrules, + authz_protected_for(p, "*")); + + if (stat(p->path, &st) == 0 && (st.st_mode & 0004) == 0) + vwarn("%s is not readable by anyone outside its owner and group: the hook " + "runs as the git account and fails closed when it cannot read this", + p->path); + + for (i = 0; i < p->nrules; i++) { + if (strcmp(p->rules[i].user, "@all") == 0 && p->rules[i].nrefs == 0) + vwarn("line %zu gives @all the whole of %s, which is not a default " + "anybody chose", p->rules[i].line, p->rules[i].repo); + } + + if (o.root != NULL) + check_repos(p, o.root); + if (o.hook_dir != NULL) + check_hook(p, o); + if (o.sshd_config != NULL) + check_sshd(p, o); + if (o.passwd != NULL) + check_account(p, o); + if (o.keys != NULL) + check_keys(p, o); + if (o.htpasswd != NULL) + check_htpasswd(p, o); + + if (g_errors > 0 || (o.strict && g_warnings > 0)) { + fprintf(stderr, "%s: validate: %d error(s), %d warning(s)\n", + progname, g_errors, g_warnings); + return 1; + } + printf("validate: %s is in force, %d rule(s), %d warning(s)\n", + p->path, (int)p->nrules, g_warnings); + return 0; +} diff --git a/tests/unit.c b/tests/unit.c new file mode 100644 index 0000000..5932d46 --- /dev/null +++ b/tests/unit.c @@ -0,0 +1,540 @@ +/* unit.c - the pieces, tested directly. + * + * This links the matcher, not the command line: what a glob does, what a ref + * normalises to, what a policy parses into and what it therefore decides. The + * behavioural suite (tests/run.sh) drives the program the way git does; this + * file is for the cases that would need a whole push to reach otherwise. + * + * No test framework, because a test suite with a dependency is a test suite + * that does not run at 3am. Failures print "not ok" with the expression. + */ +#include "../src/authz.h" + +#include <fcntl.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +static int checks; +static int failures; +static char tmproot[128]; + +#define CHECK(cond) \ + do { \ + checks++; \ + if (!(cond)) { \ + failures++; \ + printf("not ok %d: %s [%s:%d]\n", failures, #cond, __FILE__, __LINE__);\ + } \ + } while (0) + +#define CHECK_STR(got, want) \ + do { \ + checks++; \ + if (strcmp((got), (want)) != 0) { \ + failures++; \ + printf("not ok %d: got \"%s\", want \"%s\" [%s:%d]\n", failures, \ + (got), (want), __FILE__, __LINE__); \ + } \ + } while (0) + +#define CHECK_INT(got, want) \ + do { \ + checks++; \ + if ((got) != (want)) { \ + failures++; \ + printf("not ok %d: got %ld, want %ld [%s:%d]\n", failures, \ + (long)(got), (long)(want), __FILE__, __LINE__); \ + } \ + } while (0) + +static void note(const char *fmt, ...) +{ + va_list ap; + + fputs(" # ", stdout); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + fputc('\n', stdout); +} + +/* ------------------------------------------------------------- fixtures */ + +/* A policy from a string. The file is unlinked straight after loading: the + * decisions are made in memory, and a test that left policies behind would + * leave them to be trusted. */ +static int load_text(policy_t *p, const char *text) +{ + static int seq; + char path[512]; + FILE *f; + int rc; + + snprintf(path, sizeof(path), "%s/unit-%d", tmproot, ++seq); + f = fopen(path, "w"); + if (f == NULL) { + printf("not ok %d: cannot write %s\n", ++failures, path); + return -1; + } + fputs(text, f); + fclose(f); + + policy_init(p, path); + rc = policy_load(p); + unlink(path); + return rc; +} + +static void expect_allow(const policy_t *p, const char *user, const char *repo, + level_t need, const char *ref) +{ + decision_t d; + + authz_check(p, user, repo, need, ref, &d); + checks++; + if (!d.allowed) { + failures++; + printf("not ok %d: expected %s %s %s %s to be allowed, got: %s\n", failures, + user, repo, authz_level_name(need), ref != NULL ? ref : "(no ref)", d.why); + } +} + +static void expect_deny(const policy_t *p, const char *user, const char *repo, + level_t need, const char *ref, const char *needle) +{ + decision_t d; + + authz_check(p, user, repo, need, ref, &d); + checks++; + if (d.allowed) { + failures++; + printf("not ok %d: expected %s %s %s %s to be denied\n", failures, user, repo, + authz_level_name(need), ref != NULL ? ref : "(no ref)"); + } else if (needle != NULL && strstr(d.why, needle) == NULL) { + failures++; + printf("not ok %d: denial said \"%s\", expected it to mention \"%s\"\n", + failures, d.why, needle); + } +} + +/* ------------------------------------------------------------------ tests */ + +static void test_glob(void) +{ + CHECK(glob_match("*", "")); + CHECK(glob_match("*", "anything/at/all")); + CHECK(!glob_match("", "x")); + CHECK(glob_match("", "")); + CHECK(glob_match("refs/heads/*", "refs/heads/main")); + CHECK(glob_match("refs/heads/*", "refs/heads/a/b/c")); /* '*' crosses '/' */ + CHECK(!glob_match("refs/heads/*", "refs/tags/v1")); + CHECK(glob_match("refs/heads/feature/*", "refs/heads/feature/login")); + CHECK(!glob_match("refs/heads/feature/*", "refs/heads/featurey")); + CHECK(glob_match("refs/tags/v?", "refs/tags/v1")); + CHECK(!glob_match("refs/tags/v?", "refs/tags/v12")); + CHECK(glob_match("refs/heads/[ab]*", "refs/heads/beta")); + CHECK(glob_match("refs/heads/[ab]*", "refs/heads/alpha")); + CHECK(!glob_match("refs/heads/[ab]*", "refs/heads/delta")); + CHECK(glob_match("refs/heads/[!ab]*", "refs/heads/delta")); + CHECK(!glob_match("refs/heads/[!ab]*", "refs/heads/alpha")); + CHECK(glob_match("refs/heads/[a-c]1", "refs/heads/b1")); + CHECK(!glob_match("refs/heads/[a-c]1", "refs/heads/d1")); + CHECK(glob_match("refs/heads/]", "refs/heads/]")); /* ']' first is a member */ + CHECK(glob_match("refs/heads/a[-]z", "refs/heads/a-z")); /* trailing '-' literal */ + CHECK(glob_match("refs/heads/[", "refs/heads/[")); /* unclosed is literal */ + CHECK(glob_match("a*b*c", "aXXbYYc")); + CHECK(!glob_match("a*b*c", "aXXbYY")); + CHECK(glob_match("*.git", "team.git")); + CHECK(glob_match("team*", "team")); + CHECK(glob_match("refs/heads/ma?n", "refs/heads/main")); + CHECK(!glob_match("refs/heads/main", "refs/heads/MAIN")); /* case matters */ + CHECK(glob_match("refs/*/x", "refs/a/b/x")); + CHECK(glob_match("**", "x")); /* redundant stars */ + CHECK(!glob_match("refs/heads/*", "")); +} + +static void test_normalisation(void) +{ + char *s; + + s = authz_norm_ref("main"); + CHECK_STR(s, "refs/heads/main"); + free(s); + s = authz_norm_ref("heads/main"); + CHECK_STR(s, "refs/heads/main"); + free(s); + s = authz_norm_ref("refs/heads/main"); + CHECK_STR(s, "refs/heads/main"); + free(s); + s = authz_norm_ref("v1.0"); + CHECK_STR(s, "refs/heads/v1.0"); /* a bare name is never a tag */ + free(s); + s = authz_norm_ref("tags/v1.0"); + CHECK_STR(s, "refs/tags/v1.0"); + free(s); + s = authz_norm_ref("notes/commits"); + CHECK_STR(s, "refs/notes/commits"); + free(s); + s = authz_norm_ref("*"); + CHECK_STR(s, "refs/*"); + free(s); + s = authz_norm_ref("all"); + CHECK_STR(s, "refs/*"); + free(s); + s = authz_norm_ref("refs"); + CHECK_STR(s, "refs/*"); + free(s); + + s = authz_norm_repo("web.git"); + CHECK_STR(s, "web"); + free(s); + s = authz_norm_repo("web"); + CHECK_STR(s, "web"); + free(s); + s = authz_norm_repo("*"); + CHECK_STR(s, "*"); + free(s); + s = authz_norm_repo(".git"); + CHECK_STR(s, ".git"); /* a repository called ".git" is not a suffix */ + free(s); + + CHECK_INT(authz_level_of("write"), LV_WRITE); + CHECK_INT(authz_level_of("force"), LV_FORCE); + CHECK_INT(authz_level_of("admin"), LV_ADMIN); + CHECK_INT(authz_level_of("deny"), -1); + CHECK_INT(authz_level_of("read"), -1); + CHECK_STR(authz_level_name(LV_NONE), "none"); + CHECK(authz_level_of("admin") > authz_level_of("force")); + CHECK(authz_level_of("force") > authz_level_of("write")); + + CHECK(authz_user_pattern_ok("alice")); + CHECK(authz_user_pattern_ok("a.b-c_1")); + CHECK(authz_user_pattern_ok("@all")); + CHECK(authz_user_pattern_ok("a[bc]d")); + CHECK(!authz_user_pattern_ok("")); + CHECK(!authz_user_pattern_ok("a/b")); /* a path is not a user name */ + CHECK(!authz_user_pattern_ok("a$b")); + CHECK(!authz_user_pattern_ok("-x")); + CHECK(authz_repo_pattern_ok("team")); + CHECK(authz_repo_pattern_ok("*")); + CHECK(authz_repo_pattern_ok("team-*")); + CHECK(!authz_repo_pattern_ok("group/team")); /* flat names only */ + CHECK(!authz_repo_pattern_ok("")); + CHECK(!authz_repo_pattern_ok("a$b")); +} + +static void test_parse(void) +{ + policy_t p; + int rc; + + rc = load_text(&p, + "# a comment\n" + "\n" + " \n" + "alice web admin # trailing comment\n" + "bob web write refs/heads/feature/* refs/heads/dev\n" + "@all team write main\n" + "set protected-refs main refs/tags/*\n"); + CHECK_INT(rc, 0); + CHECK_INT(p.errors, 0); + CHECK_INT(p.nrules, 3); + CHECK_STR(p.rules[0].user, "alice"); + CHECK_STR(p.rules[0].repo, "web"); + CHECK_INT(p.rules[0].level, LV_ADMIN); + CHECK_INT(p.rules[0].nrefs, 0); + CHECK_INT(p.rules[0].line, 4); + CHECK_STR(p.rules[1].refs[0], "refs/heads/feature/*"); + CHECK_INT(p.rules[1].nrefs, 2); + CHECK_STR(p.rules[2].refs[0], "refs/heads/main"); /* normalised at parse time */ + CHECK_STR(p.protected_global, "refs/heads/main refs/tags/*"); + policy_free(&p); + + /* Errors: each of these must stop the file being used at all. The complaints + * are asserted as counts, and the parser writes them to stderr as it goes, so + * stderr is set aside here - a wall of expected errors would hide the failures. + * The descriptor is redirected rather than freopen'd, because freopen would + * quietly make stderr block-buffered and hand the whole wall back at exit. */ + { + int keep = dup(2); + int devnull = open("/dev/null", O_WRONLY); + + if (devnull >= 0) { + dup2(devnull, 2); + close(devnull); + } + + rc = load_text(&p, "alice web everything\n"); + CHECK_INT(rc, -1); + CHECK_INT(p.errors, 1); + policy_free(&p); + + rc = load_text(&p, "alice web/extra write\n"); + CHECK_INT(rc, -1); + policy_free(&p); + + rc = load_text(&p, "alice web write !refs/heads/main\n"); + CHECK_INT(rc, -1); + policy_free(&p); + + rc = load_text(&p, "alice web\n"); + CHECK_INT(rc, -1); + policy_free(&p); + + rc = load_text(&p, "set other-thing refs/heads/main\n"); + CHECK_INT(rc, -1); + policy_free(&p); + + rc = load_text(&p, "set protected-refs\n"); + CHECK_INT(rc, -1); + policy_free(&p); + + rc = load_text(&p, "alice web write refs/heads/main\nbob web nope refs/heads/dev\n"); + CHECK_INT(rc, -1); /* one bad line poisons the file: nothing is used */ + policy_free(&p); + + fflush(stderr); + dup2(keep, 2); + close(keep); + } + + /* The default protected list, and the two ways to replace it. */ + rc = load_text(&p, "alice * admin\n"); + CHECK_INT(rc, 0); + CHECK_STR(authz_protected_for(&p, "web"), "refs/heads/main"); + policy_free(&p); + + rc = load_text(&p, + "set protected-refs refs/heads/main refs/heads/stable\n" + "set protected-refs.web refs/heads/release\n" + "alice * admin\n"); + CHECK_INT(rc, 0); + CHECK_STR(authz_protected_for(&p, "web"), "refs/heads/release"); + CHECK_STR(authz_protected_for(&p, "other"), "refs/heads/main refs/heads/stable"); + policy_free(&p); +} + +static void test_known_users(void) +{ + policy_t p; + int rc; + + rc = load_text(&p, + "alice web admin\n" + "bob web write\n" + "@all web write refs/heads/*\n"); + CHECK_INT(rc, 0); + CHECK(authz_user_known(&p, "alice")); + CHECK(authz_user_known(&p, "bob")); + CHECK(!authz_user_known(&p, "carol")); /* '@all' never invents a name */ + CHECK(!authz_user_known(&p, "")); + policy_free(&p); + + rc = load_text(&p, "@all web write\n"); + CHECK_INT(rc, 0); + CHECK(!authz_user_known(&p, "alice")); /* nobody is known yet */ + policy_free(&p); + + rc = load_text(&p, "ali* web write\n"); + CHECK_INT(rc, 0); + CHECK(authz_user_known(&p, "alice")); /* a pattern is still a name */ + CHECK(!authz_user_known(&p, "bob")); + policy_free(&p); +} + +static void test_need_for(void) +{ + policy_t p; + char raised[64]; + int rc; + + rc = load_text(&p, + "set protected-refs refs/heads/main refs/tags/*\n" + "alice * admin\n"); + CHECK_INT(rc, 0); + CHECK_INT(authz_need_for(&p, "web", "refs/heads/dev", LV_WRITE, raised, + sizeof(raised)), LV_WRITE); + CHECK_STR(raised, ""); + CHECK_INT(authz_need_for(&p, "web", "refs/heads/main", LV_WRITE, raised, + sizeof(raised)), LV_FORCE); + CHECK_STR(raised, "protected"); + CHECK_INT(authz_need_for(&p, "web", "refs/heads/main", LV_FORCE, raised, + sizeof(raised)), LV_ADMIN); + CHECK_INT(authz_need_for(&p, "web", "refs/heads/main", LV_ADMIN, raised, + sizeof(raised)), LV_ADMIN); + CHECK_STR(raised, ""); /* admin is already the top */ + CHECK_INT(authz_need_for(&p, "web", "refs/tags/v1", LV_WRITE, raised, + sizeof(raised)), LV_FORCE); + CHECK_INT(authz_need_for(&p, "web", "refs/pull/1/head", LV_WRITE, raised, + sizeof(raised)), LV_ADMIN); + CHECK_STR(raised, "neither a branch nor a tag"); + CHECK_INT(authz_need_for(&p, "web", "refs/pull/1/head", LV_FORCE, raised, + sizeof(raised)), LV_ADMIN); + CHECK_INT(authz_need_for(&p, "web", "refs/notes/x", LV_ADMIN, raised, + sizeof(raised)), LV_ADMIN); + policy_free(&p); +} + +static void test_check(void) +{ + policy_t p; + int rc; + + rc = load_text(&p, + "set protected-refs refs/heads/main refs/tags/*\n" + "alice * admin\n" + "@all * write refs/heads/*\n" + "bob team write refs/heads/feature/*\n" + "carol team force refs/heads/feature/*\n" + "dave team admin\n" + "erin secrets admin\n"); + CHECK_INT(rc, 0); + + /* the ladder */ + expect_allow(&p, "bob", "team", LV_WRITE, "refs/heads/feature/x"); + expect_deny(&p, "bob", "team", LV_FORCE, "refs/heads/feature/x", "needs force"); + expect_deny(&p, "bob", "team", LV_ADMIN, "refs/heads/feature/x", "needs admin"); + expect_allow(&p, "carol", "team", LV_FORCE, "refs/heads/feature/x"); + expect_allow(&p, "dave", "team", LV_ADMIN, "refs/heads/main"); + + /* strongest match wins, additively */ + expect_allow(&p, "dave", "team", LV_WRITE, "refs/heads/feature/x"); + expect_allow(&p, "alice", "anything", LV_ADMIN, "refs/heads/main"); + + /* '@all' reaches the named, and nobody else. Note that the '@all *' rule + * below reaches every repository, so a named user is not confined to the + * repository their own rule names - that is what the rule says. */ + expect_allow(&p, "carol", "web", LV_WRITE, "refs/heads/any"); + expect_allow(&p, "erin", "web", LV_WRITE, "refs/heads/any"); + expect_deny(&p, "nobody", "web", LV_WRITE, "refs/heads/any", "no rule"); + expect_deny(&p, "", "web", LV_WRITE, "refs/heads/any", "no identity"); + expect_deny(&p, NULL, "web", LV_WRITE, "refs/heads/any", "no identity"); + + /* protected refs raise the cost, and say so */ + expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/main", "raised from write"); + expect_deny(&p, "carol", "team", LV_FORCE, "refs/heads/main", "raised from force"); + /* the raise applies to the level the action asked for, not to the best + * level the user happens to hold somewhere else */ + expect_deny(&p, "carol", "team", LV_WRITE, "refs/heads/main", "needs force"); + expect_allow(&p, "dave", "team", LV_WRITE, "refs/heads/main"); + + /* refs that are not branches or tags: only an admin, at any request level */ + expect_allow(&p, "dave", "team", LV_WRITE, "refs/pull/1/head"); + expect_allow(&p, "dave", "team", LV_ADMIN, "refs/pull/1/head"); + expect_deny(&p, "bob", "team", LV_ADMIN, "refs/notes/x", "needs admin"); + + /* the same branch, three spellings */ + expect_deny(&p, "bob", "team", LV_WRITE, "main", "protected"); + expect_deny(&p, "bob", "team", LV_WRITE, "heads/main", "protected"); + expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/main", "protected"); + + /* repository matching: .git is the same repository */ + expect_allow(&p, "bob", "team.git", LV_WRITE, "refs/heads/feature/x"); + expect_allow(&p, "erin", "secrets.git", LV_ADMIN, "refs/heads/main"); + + /* the question without a ref */ + expect_allow(&p, "dave", "team", LV_FORCE, NULL); + expect_allow(&p, "alice", "team", LV_ADMIN, NULL); + expect_allow(&p, "bob", "team", LV_WRITE, NULL); + expect_deny(&p, "bob", "team", LV_FORCE, NULL, "no force"); + expect_allow(&p, "erin", "team", LV_WRITE, NULL); /* via '@all *' */ + expect_deny(&p, "nobody", "team", LV_WRITE, NULL, "no write"); + + /* what a denial names: the level held, and the level needed */ + { + decision_t d; + + authz_check(&p, "bob", "team", LV_ADMIN, "refs/heads/feature/x", &d); + CHECK(!d.allowed); + CHECK_INT(d.need, LV_ADMIN); + CHECK(strstr(d.why, "bob has write") != NULL); + CHECK(strstr(d.why, "needs admin") != NULL); + + authz_check(&p, "nobody", "team", LV_WRITE, "refs/heads/dev", &d); + CHECK(!d.allowed); + CHECK(strstr(d.why, "nobody has no rule for team") != NULL); + } + policy_free(&p); +} + +static void test_scope_edges(void) +{ + policy_t p; + int rc; + + /* a rule with no refs is the whole repository, protected refs included */ + rc = load_text(&p, "bob team write\n"); + CHECK_INT(rc, 0); + expect_allow(&p, "bob", "team", LV_WRITE, "refs/heads/anything"); + expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/main", "protected"); + /* write on everything still is not force: the raise asks for the next step + * up, and bob never got it */ + expect_deny(&p, "bob", "team", LV_FORCE, "refs/heads/main", "needs admin"); + policy_free(&p); + + /* a bare name is a branch, and only a branch */ + rc = load_text(&p, "bob web write refs/heads/*\n"); + CHECK_INT(rc, 0); + expect_allow(&p, "bob", "web", LV_WRITE, "v1"); /* refs/heads/v1 */ + expect_deny(&p, "bob", "web", LV_WRITE, "refs/tags/v1", "needs write"); + expect_deny(&p, "bob", "web", LV_WRITE, "tags/v1", "needs write"); + policy_free(&p); + + /* a user may hold several rules for one repository; all of them count */ + rc = load_text(&p, + "bob team write refs/heads/dev\n" + "bob team force refs/heads/feature/*\n"); + CHECK_INT(rc, 0); + expect_allow(&p, "bob", "team", LV_WRITE, "refs/heads/dev"); + expect_allow(&p, "bob", "team", LV_FORCE, "refs/heads/feature/x"); + expect_deny(&p, "bob", "team", LV_FORCE, "refs/heads/dev", "has force on team"); + expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/other", "needs write"); + policy_free(&p); + + /* per-repository protection replaces the global list, it does not add to it */ + rc = load_text(&p, + "set protected-refs refs/heads/main\n" + "set protected-refs.web refs/heads/release\n" + "bob web write refs/heads/*\n"); + CHECK_INT(rc, 0); + expect_allow(&p, "bob", "web", LV_WRITE, "refs/heads/main"); + expect_deny(&p, "bob", "web", LV_WRITE, "refs/heads/release", "protected"); + expect_deny(&p, "bob", "api", LV_WRITE, "refs/heads/release", "no rule"); + policy_free(&p); + + /* reachable-by-nobody detection, which validate reports */ + rc = load_text(&p, "bob team write\n"); + CHECK_INT(rc, 0); + CHECK(authz_repo_reachable(&p, "team")); + CHECK(authz_repo_reachable(&p, "team.git")); + CHECK(!authz_repo_reachable(&p, "other")); + policy_free(&p); + + rc = load_text(&p, "bob * write\n"); + CHECK_INT(rc, 0); + CHECK(authz_repo_reachable(&p, "anything")); + policy_free(&p); +} + +int main(void) +{ + const char *dir = getenv("UNIT_TMPDIR"); + + snprintf(tmproot, sizeof(tmproot), "%s", dir != NULL ? dir : "tests/tmp"); + + test_glob(); + test_normalisation(); + test_parse(); + test_known_users(); + test_need_for(); + test_check(); + test_scope_edges(); + + printf("unit: %d checks, %d failure(s)\n", checks, failures); + if (failures != 0) + note("these are the semantics; the behavioural suite assumes them"); + return failures != 0; +} |
