summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--build/relpath.awk22
-rw-r--r--cmd/main.c56
-rw-r--r--container/Dockerfile37
-rwxr-xr-xcontainer/create-repo13
-rwxr-xr-xcontainer/entrypoint.sh19
-rwxr-xr-xcontainer/git-host-key14
-rw-r--r--container/git-http-backend.cgi16
-rw-r--r--container/sshd_config16
-rw-r--r--src/authz.h178
-rw-r--r--src/edit.c100
-rw-r--r--src/glob.c26
-rw-r--r--src/hook.c73
-rw-r--r--src/policy.c101
-rw-r--r--src/util.c8
-rw-r--r--src/validate.c55
-rw-r--r--test/check.c67
-rw-r--r--test/glob.c19
-rw-r--r--test/need.c19
-rw-r--r--test/norm.c17
-rw-r--r--test/parse.c37
-rwxr-xr-xtest/run.sh71
-rw-r--r--test/test.h21
22 files changed, 402 insertions, 583 deletions
diff --git a/build/relpath.awk b/build/relpath.awk
index ea5ca99..10651d0 100644
--- a/build/relpath.awk
+++ b/build/relpath.awk
@@ -1,16 +1,10 @@
-# relpath.awk - the path from one directory to one file, relative to the
-# directory. Used by `make install' for the hook symlink:
+# The path from one directory to one file, relative to the directory; used by
+# `make install' for the hook symlink. A relative link survives a staged install,
+# an unpacked prefix, or an image built somewhere else; an absolute one points at
+# whatever lives at that path on the machine reading it.
#
-# awk -v from=/usr/local/share/git-host/hooks -v to=/usr/local/bin/git-authz \
-# -f build/relpath.awk -> ../../../bin/git-authz
-#
-# A relative link survives being moved: a staged install under DESTDIR, an
-# unpacked prefix, a container image built somewhere else. An absolute one
-# points at whatever happens to live at that path on the machine reading it,
-# which during a staged install is the wrong answer and after a failed one is a
-# broken link nothing explains.
-#
-# POSIX awk, so busybox awk and mawk and gawk all agree.
+# POSIX awk: busybox awk, mawk and gawk all agree on it.
+
function split_path(p, out, n, parts, i, depth) {
n = split(p, parts, "/")
@@ -43,8 +37,8 @@ BEGIN {
while (common < nf && common < nt && f[common + 1] == t[common + 1])
common++
- # Anything above a ".." we could not resolve has to be answered with an
- # absolute path: there is no relative route into a directory we cannot name.
+ # No relative route into a directory we cannot name.
+
if ((nf > common && f[common + 1] == "..") ||
(nt > common && t[common + 1] == "..")) {
print to
diff --git a/cmd/main.c b/cmd/main.c
index 8a42b72..0da308f 100644
--- a/cmd/main.c
+++ b/cmd/main.c
@@ -1,15 +1,8 @@
-/* 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)
- *
- * 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.
- */
+// One program, because check and the hook have to agree exactly about what a
+// rule means: a check that answers differently from the hook is a program that
+// lies. Exit status is the interface: 0 allowed, 1 denied, 3 no usable policy,
+// 64 usage.
+
#include "authz.h"
#include <stdio.h>
@@ -92,9 +85,9 @@ static int one_option(int argc, char **argv, int *i, const char *name, const cha
return 0;
}
-/* The policy is not usable, so the only safe answer is no. Three, not one:
- * the push was refused because this host is broken, not because that person is
- * not allowed, and whoever is debugging wants the two to sound different. */
+// 3 and not 1: a push refused because the host is broken has to sound different
+// from one refused because the person is not allowed.
+
static int deny_policy(const char *path, int rc)
{
fprintf(stderr, "%s: deny: the policy at %s %s\n", progname, path,
@@ -102,10 +95,10 @@ static int deny_policy(const char *path, int rc)
return 3;
}
-/* Everything that answers out of a loaded policy. Split out of main so the
- * policy is freed on the way out whichever way that is: a process this short
- * lived could leave the heap to the kernel, but then a sanitizer run reports
- * forty leaks and stops showing the one that matters. */
+// Split out of main so the policy is freed on every exit path: a short-lived
+// process can leave the heap to the kernel, but then the sanitizer reports
+// forty leaks and stops showing the one that matters.
+
static int dispatch(policy_t *p, int rc, const char *cmd, int argc, char **argv,
const char *path, hook_opts ho, validate_opts vo)
{
@@ -134,10 +127,9 @@ static int dispatch(policy_t *p, int rc, const char *cmd, int argc, char **argv,
vo.strict = 1;
continue;
}
- /* The policy is the part that decides who may push. Everything
- * else is how this host is wired, and a host without a git account
- * yet - a container being built, a config directory being checked
- * in - still wants its policy read. */
+ // A host without a git account yet - a container being built -
+ // still wants its policy read.
+
if (got == 0 && strcmp(argv[j], "--no-host") == 0) {
vo.root = NULL;
vo.hook_dir = NULL;
@@ -154,8 +146,9 @@ static int dispatch(policy_t *p, int rc, const char *cmd, int argc, char **argv,
return 64;
}
}
- /* A policy that does not parse is itself the finding, so it is passed
- * down and reported rather than turning this into a bare exit 3. */
+ // A policy that does not parse is the finding, so it is passed down
+ // rather than exiting 3 here.
+
return cmd_validate(p, vo);
}
@@ -223,10 +216,9 @@ int main(int argc, char **argv)
vo.htpasswd = DEFAULT_HTPASSWD;
memset(&eo, 0, sizeof(eo));
- /* Reached through the hook symlink. Git's own arguments to a hook are not
- * this program's, so they are dropped, and the policy comes from the
- * environment - a hook is not in a position to be told where the policy is
- * by a person who is not there. */
+ // Reached through the hook symlink: git's arguments are not this program's,
+ // so they are dropped, and the policy comes from the environment.
+
if (strcmp(progname, "pre-receive") == 0) {
policy_init(&p, path);
rc = policy_load(&p);
@@ -271,15 +263,13 @@ int main(int argc, char **argv)
return 0;
}
- /* The three commands that change the file. They read it themselves, and
- * they must not disagree with the checker about what a rule means, which is
- * why they are in the same binary. */
+
if (strcmp(cmd, "grant") == 0 || strcmp(cmd, "revoke") == 0) {
int consumed = 0;
if (authz_parse_out(argc, argv, &eo, &consumed) != 0)
return 64;
- argc -= consumed; /* what is left was compacted to the front */
+ argc -= consumed; // what is left was compacted to the front
if (strcmp(cmd, "grant") == 0)
return cmd_grant(path, eo, argc, argv);
return cmd_revoke(path, eo, argc, argv);
diff --git a/container/Dockerfile b/container/Dockerfile
index 1828748..ac0d898 100644
--- a/container/Dockerfile
+++ b/container/Dockerfile
@@ -1,22 +1,11 @@
-# git-host on top of the C program.
-#
-# podman build -t git-host-c .
-#
-# Two stages, because the runtime image has no business carrying a compiler.
-# The build stage compiles, runs the test suite, and installs into a staging
-# root; the runtime stage copies that staging root wholesale, so the paths in
-# the image are the paths `make install` produces - including the hook symlink
-# and its relative target - rather than a second list of destinations kept here,
-# which is how an image and a build start to disagree.
-#
-# The build stage is Alpine so that git-authz is musl-linked like everything
-# else in the runtime image. A glibc binary built on the machine doing the
-# building would not run in there, and would announce itself as "no such file"
-# for a file that is plainly present.
+# podman build -t git-host-c -f container/Dockerfile .
#
-# The build context is the program's directory, with this file in container/:
+# Two stages: the runtime image carries no compiler, and copies what `make
+# install` staged, so image paths cannot drift from build paths.
#
-# podman build -t git-host-c -f container/Dockerfile .
+# The build stage is Alpine so the binary is musl-linked like the rest of the
+# image. A glibc binary reports "no such file" for a file that is plainly there.
+
FROM alpine:3.22.4 AS build
RUN apk add --no-cache build-base
@@ -26,9 +15,8 @@ COPY src ./src
COPY cmd ./cmd
COPY test ./test
COPY build ./build
-# The suite runs in the image it ships in, against the musl build: that is the
-# only place the two are guaranteed to meet, and an image built from a tree
-# whose tests fail should not exist.
+# The suite runs against the musl build, which is the only place the two meet.
+
RUN make -j2 && make test && make install DESTDIR=/install
@@ -60,16 +48,17 @@ RUN addgroup -g 1000 -S git \
/var/www/localhost/htdocs \
&& chown -R git:git /var/lib/git
-# The binary, the hook symlink beside it, and the example policy, all placed by
-# the program's own installer.
+# Placed by the program's own installer.
+
COPY --from=build /install/ /
COPY container/create-repo /usr/local/bin/create-repo
COPY container/git-host-key /usr/local/bin/git-host-key
COPY container/entrypoint.sh /usr/local/bin/entrypoint.sh
-# lighttpd's mod_cgi dispatches by extension, so /git needs a *.cgi door. It
-# only execs the stock backend, leaving REMOTE_USER for the hooks to find.
+# mod_cgi dispatches by extension, so /git needs a *.cgi door onto the stock
+# backend. It must not touch the environment: REMOTE_USER is the identity.
+
COPY container/git-http-backend.cgi /usr/local/libexec/git-http-backend.cgi
COPY container/sshd_config /etc/ssh/sshd_config
diff --git a/container/create-repo b/container/create-repo
index 3accca8..5f80c92 100755
--- a/container/create-repo
+++ b/container/create-repo
@@ -1,14 +1,9 @@
#!/bin/sh
-# create-repo - create a bare repository the policy can talk about.
+# Create a bare repository. Nothing is installed in it: every repository reaches
+# the shared hook through core.hooksPath, so one made by hand is enforced the same.
#
-# Nothing is installed here, which is the point: every repository reaches the
-# shared hook through the global core.hooksPath in /etc/gitconfig, so a bare
-# repository you make by hand is enforced exactly like one made here.
-#
-# The policy is a read-only mount in a deployment, so this cannot grant
-# anything. It prints the line to add to your policy source; until a rule
-# reaches the new repository, 'git-authz validate' says so and every push to it
-# is refused.
+# The policy is a read-only mount, so this only prints the line to add.
+
set -eu
GIT_REPO_ROOT="${GIT_REPO_ROOT:-/var/lib/git}"
diff --git a/container/entrypoint.sh b/container/entrypoint.sh
index e82ae4f..df33b47 100755
--- a/container/entrypoint.sh
+++ b/container/entrypoint.sh
@@ -16,9 +16,9 @@ need_secret() { # <name> [mode] [owner-group]
chmod "$mode" "$SECRETS_DIR/$name"
}
-# Copy the secrets to /run and fix their modes. Mounted secrets arrive with
-# whatever mode the volume plugin chose, and sshd refuses keys that are too
-# loose while lighttpd must be able to read htpasswd as the git user.
+# Mounted secrets arrive with whatever mode the volume plugin chose. sshd refuses
+# keys that are too loose; lighttpd must read htpasswd as the git user.
+
mkdir -p "$SECRETS_DIR"
need_secret authorized_keys 0640 git
need_secret htpasswd 0640 git
@@ -28,15 +28,14 @@ need_secret ssh_host_rsa_key
need_secret ssh_host_rsa_key.pub 0644
chmod 0755 /run/git-host "$SECRETS_DIR"
-# One hook for every repository. This is the single most important line in the
-# container: without it a repository carries no policy and pushes go unchecked.
-# The policy file itself stays wherever it is mounted; it is never copied, so a
-# ConfigMap update takes effect on the next push with no restart.
+# The single most important line in the container: without it a repository carries
+# no policy and pushes go unchecked. The policy is never copied, so a ConfigMap
+# update takes effect on the next push.
+
git config --file /etc/gitconfig core.hooksPath "${GIT_HOST_HOOK_DIR:-/usr/local/share/git-host/hooks}"
-# Fail rather than serve a host that cannot enforce anything. A policy that
-# does not parse is only a warning inside validate: reads keep working and
-# pushes are denied, which is the correct direction for a mistake to fall in.
+# Do not serve a host that cannot enforce anything.
+
git-authz validate
/usr/sbin/sshd -D -e -f /etc/ssh/sshd_config &
diff --git a/container/git-host-key b/container/git-host-key
index a7fdfc8..10d8131 100755
--- a/container/git-host-key
+++ b/container/git-host-key
@@ -1,17 +1,11 @@
#!/bin/sh
-# git-host-key - ssh public keys that carry their own identity.
-#
-# sshd only knows the OS account, and every git user shares the single 'git'
-# account. So identity is written into the key's option list:
+# ssh public keys that carry their own identity. sshd only knows the OS account,
+# which every user shares, so identity goes in the key's option list:
#
# command="/usr/bin/git-shell",...,environment="GIT_HOST_USER=alice"
#
-# sshd puts that into the session environment (sshd_config needs
-# PermitUserEnvironment yes), git-receive-pack inherits it, and the pre-receive
-# hook authorises the push from it. A key without the option is anonymous as
-# far as policy is concerned, so its pushes are denied. 'git-authz validate'
-# reports keys with no identity, keys that pin something other than git-shell,
-# and identities the policy has never heard of.
+# A key without it is anonymous to the policy and every push with it is denied.
+
set -eu
KEYS="${GIT_HOST_AUTHORIZED_KEYS:-/etc/git-host/secrets/authorized_keys}"
diff --git a/container/git-http-backend.cgi b/container/git-http-backend.cgi
index e086525..c69758b 100644
--- a/container/git-http-backend.cgi
+++ b/container/git-http-backend.cgi
@@ -1,17 +1,9 @@
#!/bin/sh
-# git-http-backend.cgi - a .cgi-named door to the stock git-http-backend.
+# A .cgi-named door onto the stock backend, because mod_cgi dispatches by
+# extension. No policy in here: writes are decided by the pre-receive hook.
#
-# There is no policy in here. Reads are open, and writes are decided by the
-# global pre-receive hook, which is a symlink to git-authz and is reached by
-# every repository through core.hooksPath in /etc/gitconfig.
-#
-# This file exists for one reason: lighttpd's mod_cgi dispatches by extension,
-# and the alias in lighttpd.conf needs something named *.cgi in front of it.
-#
-# REMOTE_USER is set by mod_auth on push requests (auth.conf) and the receive
-# hooks authorise the push from it, so this script must stay a plain exec:
-# unsetting or rewriting the environment here turns every push into "no
-# identity" and denies them all.
+# It must stay a plain exec. REMOTE_USER is the identity the hooks authorise
+# from, and rewriting the environment here denies every push.
set -eu
BACKEND="${GIT_HOST_HTTP_BACKEND:-/usr/libexec/git-core/git-http-backend}"
diff --git a/container/sshd_config b/container/sshd_config
index c180f50..fca7e7b 100644
--- a/container/sshd_config
+++ b/container/sshd_config
@@ -4,22 +4,20 @@ HostKey /run/git-host/secrets/ssh_host_ed25519_key
HostKey /run/git-host/secrets/ssh_host_rsa_key
PidFile /run/sshd/sshd.pid
-# One OS account for everyone; the *name* behind a key comes from the key
-# itself. git-host-key writes
+# One OS account for everyone; the name behind a key comes from the key itself:
#
# environment="GIT_HOST_USER=alice",command="/usr/bin/git-shell",... ssh-ed25519 ...
-#
-# and git-authz reads GIT_HOST_USER out of the push environment.
+
AuthorizedKeysFile /run/git-host/secrets/authorized_keys
-# Without this line sshd silently drops the environment= key option, every
-# connection arrives anonymous, and every push is denied. The usual objection
-# does not apply here: the git account has no login shell worth having
+# Without this sshd silently drops the environment= option and every push arrives
+# anonymous. The usual objection does not apply: there is no login shell here
# (ForceCommand below), no writable files and no user rc file.
+
PermitUserEnvironment yes
-# Belt and braces for a hand-added key that forgot its command= option: nobody
-# gets a shell, only the git transport.
+# For a hand-added key that forgot its command= option: git transport, no shell.
+
ForceCommand /usr/bin/git-shell
PasswordAuthentication no
diff --git a/src/authz.h b/src/authz.h
index 794c12c..671b45f 100644
--- a/src/authz.h
+++ b/src/authz.h
@@ -1,48 +1,30 @@
-/* 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.
- */
+// No regex, no fnmatch, no libgit2: a hook must not depend on anything that can
+// be missing at 3am.
+//
+// The exit status is the interface: 0 allowed, 1 denied, 3 no usable policy,
+// 64 usage.
+
#ifndef AUTHZ_H
#define AUTHZ_H
#include <stddef.h>
-#define MAX_FIELDS 64 /* one rule line, split on whitespace */
+#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 */
+ LV_WRITE = 1, // create, fast-forward
+ LV_FORCE = 2, // + rewrite history, delete
+ LV_ADMIN = 3 // + the default branch, refs that are neither
} level_t;
typedef struct {
- char *user; /* pattern, as written */
- char *repo; /* pattern, normalised (no .git) */
+ char *user; // pattern, as written
+ char *repo; // pattern, normalised (no .git)
level_t level;
- char **refs; /* normalised patterns; NULL/0 = whole repository */
+ char **refs; // normalised patterns; NULL/0 = whole repository
size_t nrefs;
- int line; /* 1-based, for messages */
+ int line; // 1-based, for messages
} rule_t;
typedef struct {
@@ -50,146 +32,129 @@ typedef struct {
size_t nrules, rcap;
int errors;
- int unreadable; /* the file itself could not be opened */
- char *path; /* what messages call the file */
+ int unreadable; // the file itself could not be opened
+ char *path; // what messages call the file
} policy_t;
typedef struct {
int allowed;
- level_t need; /* what it cost in the end */
- char why[512]; /* the sentence the person pushing reads */
+ level_t need; // what it cost in the end
+ char why[512]; // the sentence the person pushing reads
} decision_t;
-/* ---------------------------------------------------------------- glob.c */
+// glob.c --------------------------------------------------------------------
+
+// '*' is any run including '/', '?' one character, [a-z] classes with ! or ^
+// negating, everything else literal. fnmatch and regex mean different things on
+// different systems; this does not.
-/* 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 */
+// 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 are reported as they are
- * found, on stderr, with the line number. */
+// 0 usable, -1 errors, -2 unreadable. Errors print as they are found.
+
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. */
+// A bare name is a branch: "main" and "refs/heads/main" are one thing, and a
+// branch never means a same-named tag. malloc'd.
+
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. */
+
+// More than 'max' fields returns max+1, so the caller complains rather than
+// reading 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. */
+// Repository names are flat: two levels with a glob over each is the whole model.
+
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);
+int authz_level_of(const char *name); // -1 for anything that is not one
-/* 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. */
+// '@all' means everybody this policy already names; it never invents a name.
int authz_user_known(const policy_t *p, const char *user);
-/* What a ref really costs beyond what the rule said. Anything that is not a
- * branch or a tag is for maintainers, whatever a rule about it appears to
- * grant: refs/notes, refs/merge-requests, whatever a tool invents next, are not
- * part of the namespace a policy was written with in mind, and the safe reading
- * of "not mentioned" is "not granted". When the answer is higher than 'have',
- * the reason is written to raised, which must hold at least 64 bytes. */
+// What a ref costs beyond what the rule said. Neither a branch nor a tag is
+// admin whatever a rule grants - refs/notes, refs/merge-requests, whatever a tool
+// invents next. The reason goes in raised (>= 64 bytes).
+
level_t authz_need_for(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. */
+// 'ref' may be NULL, which asks "somewhere in this 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. */
+// False means no rule reaches it at all - usually a name that stopped matching.
+
int authz_repo_reachable(const policy_t *p, const char *repo);
-/* --------------------------------------------------------------- hook.c */
+// hook.c --------------------------------------------------------------------
+
+// authorize mode: identity from the environment, "old new ref" on stdin, the
+// shape git hands a receive hook. Returns the exit status.
+//
+// Is old an ancestor of new, and which ref is HEAD, are asked of git. No answer
+// is the conservative answer: a rewrite, and any deleted ref the default branch.
-/* 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 */
+ 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 */
+// validate.c ----------------------------------------------------------------
typedef struct {
- const char *root; /* where the repositories live */
+ 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 */
+ int strict; // warnings are errors
} validate_opts;
int cmd_validate(const policy_t *p, validate_opts o);
-/* ---------------------------------------------------------------- edit.c */
+// edit.c --------------------------------------------------------------------
typedef struct {
- const char *out; /* NULL edits in place; "-" is stdout */
+ const char *out; // NULL edits in place; "-" is stdout
} edit_opts;
-/* Shared by the two editing commands: pulls --out and --stdout out of the
- * argument list wherever they sit (an option at the end reads better in a
- * shell history) and compacts what is left into argv, returning the count in
- * *consumed. Returns -1 on a missing value. */
+// Pulls --out and --stdout out of argv wherever they sit and compacts what is
+// left, returning the count in *consumed. -1 on a missing value.
int authz_parse_out(int argc, char **argv, edit_opts *o, int *consumed);
-/* A ref pattern or name that starts with "--" is a mistyped option, not
- * something to grant. Prints and returns 1 when it finds one. */
+// A name starting with "--" is a mistyped option, not something to grant.
+// Prints and returns 1 when it finds one.
int authz_reject_options(int argc, char **argv);
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);
-/* ---------------------------------------------------------------- main.c
- * Shared little helpers, so that no file invents its own way to fail. */
+// util.c --------------------------------------------------------------------
-/* A growing string. The policy is assembled and explained in pieces, and
- * strncat with hand-computed room is how buffer bugs are born. */
+// A growing string. strncat with hand-computed room is how buffer bugs are
+// born.
typedef struct {
- char *s; /* never NULL once sb_init has run */
+ char *s; // never NULL once sb_init has run
size_t len;
size_t cap;
} strbuf_t;
@@ -204,8 +169,7 @@ 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. */
+// 'pre-receive' when 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
index 9b3c233..5579b50 100644
--- a/src/edit.c
+++ b/src/edit.c
@@ -1,21 +1,12 @@
-/* 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.
- */
+// The deployed policy is a read-only mount, on purpose: that is what makes it
+// reviewable and the rollout visible. These are for the source copy, and say so
+// when the file cannot be written rather than pretending to have granted
+// something.
+//
+// Comments survive, because the file is also the record of why an access exists.
+// The rewrite is a whole file to a temporary and a rename: a policy truncated
+// half way through a write is a policy that denies everything.
+
#include "authz.h"
#include <ctype.h>
@@ -43,7 +34,7 @@ static void lines_init(lines_t *l)
l->cap = 0;
}
-static void lines_push(lines_t *l, char *s) /* takes ownership */
+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;
@@ -62,7 +53,7 @@ static void lines_free(lines_t *l)
lines_init(l);
}
-/* Every line, newline included, exactly as it was. */
+// Every line, newline included, exactly as it was.
static int read_lines(const char *path, lines_t *l)
{
FILE *f;
@@ -83,8 +74,7 @@ static int read_lines(const char *path, lines_t *l)
lines_push(l, xstrdup(line));
continue;
}
- { /* a last line without its newline:
- * keep the file well formed */
+ { // a last line without its newline
char *own = xmalloc(n + 2);
memcpy(own, line, n);
@@ -98,9 +88,10 @@ static int read_lines(const char *path, lines_t *l)
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. */
+// A temporary beside the target, then rename: a reader sees the old file or the
+// new one. Mode and owner are carried over, 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);
@@ -112,8 +103,8 @@ static int write_atomic(const lines_t *l, const char *path)
size_t i;
int had = stat(path, &st) == 0;
- /* dirname may return a pointer into its argument or a fresh one, and may
- * fail; the copy is ours either way and dirtext is freed at the end. */
+ // dirname may return a pointer into its argument or a fresh one.
+
dir = dirname(dirtext);
if (dir == NULL)
dir = (char *)".";
@@ -175,13 +166,11 @@ static int write_atomic(const lines_t *l, const char *path)
return 0;
}
-/* ------------------------------------------------------------------ matching */
+// ------------------------------------------------------------------ matching
+
+// Copied before splitting: splitting writes over the text, and these lines are
+// the file.
-/* 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);
@@ -223,12 +212,11 @@ static char *rule_text(const char *user, const char *repo, const char *level,
return b.s;
}
-/* Fail before touching anything if the file cannot be parsed. */
-/* Load a policy for editing. A policy that does not parse is refused: editing
- * a file we cannot read would rewrite the parts we can read and keep the
- * damage. A policy that is not there yet is a bootstrap, not an error - the
- * source copy has to start somewhere - so the file begins with the grammar
- * written down, which is also the least surprising thing to find in it. */
+// A file that does not parse is refused: rewriting the parts that parse would
+// keep the damage. A file that is not there yet is bootstrapped with the
+// grammar
+// written at the top.
+
static int refuse_broken(const char *path, int *created)
{
policy_t probe;
@@ -248,10 +236,11 @@ static int refuse_broken(const char *path, int *created)
return 0;
}
-/* Pull the shared options out of the argument list. They are allowed anywhere
- * rather than only at the front, because "grant bob team write --out
- * /tmp/new.conf" is what people type - and treating "--out" as a ref pattern
- * would grant something nobody asked for. */
+// --out and --stdout are allowed anywhere, because "grant bob team write --out
+// /tmp/new.conf" is what people type; parsing them only at the front made "--
+// out"
+// a ref pattern.
+
int authz_parse_out(int argc, char **argv, edit_opts *o, int *consumed)
{
int i;
@@ -294,8 +283,8 @@ int authz_reject_options(int argc, char **argv)
return 0;
}
-/* Write the result and release the lines: every command ends here, so this is
- * where the file it read stops being held. */
+// Every command ends here, so this is where the lines are released.
+
static int finish(lines_t *l, const char *path, edit_opts o, const char *what)
{
int rc;
@@ -317,7 +306,7 @@ static int finish(lines_t *l, const char *path, edit_opts o, const char *what)
return rc;
}
-/* ------------------------------------------------------------------ commands */
+// ------------------------------------------------------------------ commands
int cmd_grant(const char *path, edit_opts o, int argc, char **argv)
{
@@ -361,9 +350,9 @@ int cmd_grant(const char *path, edit_opts o, int argc, char **argv)
if (refuse_broken(path, &created) != 0)
return 3;
if (created) {
- /* Bootstrapped lines are xstrdup'd for the same reason as the rest:
- * lines_free frees every entry it holds, and a string literal is not
- * something free() may be handed. */
+ // xstrdup'd: lines_free frees every entry it holds, and a string
+ // literal is not something free() may be handed.
+
lines_init(&lines);
lines_push(&lines, xstrdup("# git-authz policy\n"));
lines_push(&lines, xstrdup("# <user> <repo> <write|force|admin> "
@@ -374,25 +363,24 @@ int cmd_grant(const char *path, edit_opts o, int argc, char **argv)
} else 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. */
+ // Several rules for one pair are legal and pointless - the strongest wins -
+ // so they collapse into one line, in the place of the first.
+
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; /* the line the new rule takes over */
+ first = i; // the line the new rule takes over
continue;
}
- free(lines.v[i]); /* a later rule for the same pair */
+ free(lines.v[i]); // a later rule for the same pair
lines.v[i] = NULL;
dropped++;
}
if (first < 0) {
- lines_push(&lines, text); /* the buffer belongs to the file now */
+ lines_push(&lines, text); // the buffer belongs to the file now
replaced = (int)lines.n;
} else {
size_t w;
diff --git a/src/glob.c b/src/glob.c
index 7c6b969..08a829d 100644
--- a/src/glob.c
+++ b/src/glob.c
@@ -1,12 +1,7 @@
-/* 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. */
+// Length of the class at p, or 0 when it is unclosed and so means a literal '['.
+// A ']' first, or first after a negation, is a member.
static int class_len(const char *p)
{
const char *c = p + 1;
@@ -20,11 +15,11 @@ static int class_len(const char *p)
return (*c == ']') ? (int)(c - p) + 1 : 0;
}
-/* text is a complete class of len bytes, including the brackets. */
+// text is a complete class of len bytes, brackets included.
static int class_match(const char *text, int len, char c)
{
const char *p = text + 1;
- const char *end = text + len - 1; /* the ']' */
+ const char *end = text + len - 1; // the ']'
int negate = 0;
int hit = 0;
@@ -34,7 +29,7 @@ static int class_match(const char *text, int len, char c)
}
while (p < end) {
char lo = *p++;
- if (p + 1 < end && *p == '-') { /* 'a-z'; a trailing '-' is literal */
+ if (p + 1 < end && *p == '-') { // 'a-z'; a trailing '-' is literal
char hi = p[1];
p += 2;
if (c >= lo && c <= hi)
@@ -50,8 +45,8 @@ 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 */
+ 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)
@@ -68,9 +63,10 @@ int glob_match(const char *pattern, const char *s)
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. */
+ // A well-formed class that says no has to backtrack rather
+ // than compare '[' literally: a negated class must be able to
+ // fail, and falling through here would match it against a
+ // pattern that only looked like a class.
if (star == NULL)
return 0;
p = star;
diff --git a/src/hook.c b/src/hook.c
index d581bc8..ddce87d 100644
--- a/src/hook.c
+++ b/src/hook.c
@@ -1,18 +1,11 @@
-/* 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.
- */
+// What core.hooksPath points at. Nothing is inferred from the transport: ref
+// names travel inside a compressed request body, and this is the first place
+// they exist as data.
+//
+// Two facts are not in the input and only git has them - is old an ancestor of
+// new, and which branch is HEAD. An answer that cannot be had is taken the
+// expensive way, because guessing the cheap way is the hole.
+
#include "authz.h"
#include <fcntl.h>
@@ -24,13 +17,13 @@
#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. */
+// Run a program, optionally keeping the first line of its stdout.
+//
+// The child gets /dev/null on stdin: one left holding the hook's stdin eats the
+// ref lines not yet read, and a push that loses refs from its own list is a push
+// that skips checks. stderr is /dev/null too, so 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 };
@@ -114,9 +107,9 @@ static int is_zero(const char *s)
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. */
+// 40 or 64 hex digits, or all zeroes. Anything else is denied rather than
+// interpreted.
+
static int object_id_ok(const char *s)
{
size_t i;
@@ -135,10 +128,10 @@ static int object_id_ok(const char *s)
static char *head_ref(hook_opts o, int *unknown)
{
- /* Terminated by hand, and by name: execvp walks this array until it finds
- * the NULL, and an array that runs off the end takes whatever is on the
- * stack next as an argument - which is not a crash you can read, and made
- * every deletion cost admin because the answer was never received. */
+ // The NULL is load-bearing: execvp walks until it finds one, and an array
+ // that runs off the end passes stack garbage as an argument. That bug was
+ // silent, and every deletion cost admin.
+
const char *argv[5] = { "git", "symbolic-ref", "-q", "HEAD", NULL };
char *out = NULL;
int rc;
@@ -149,20 +142,18 @@ static char *head_ref(hook_opts o, int *unknown)
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 */
+ return NULL; // told not to ask; so do not guess either
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 */
+ *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)
{
- /* Same as head_ref: the NULL is part of the contract, not padding. */
const char *argv[6] = { "git", "merge-base", "--is-ancestor",
NULL, NULL, NULL };
int rc;
@@ -202,7 +193,7 @@ static char *derive_repo(hook_opts o)
root = "/var/lib/git";
rootlen = strlen(root);
while (rootlen > 1 && root[rootlen - 1] == '/')
- rootlen--; /* "/var/lib/git/" is "/var/lib/git" */
+ rootlen--; // "/var/lib/git/" is "/var/lib/git"
if (strncmp(cwd, root, rootlen) == 0 && cwd[rootlen] == '/')
name = cwd + rootlen + 1;
@@ -300,9 +291,9 @@ int cmd_authorize(const policy_t *p, hook_opts o, int argc, char **argv)
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. */
+ // Split by hand: object ids and refnames never contain whitespace, and
+ // this keeps the reader's index the same as the writer's.
+
{
char *q = line;
@@ -347,14 +338,14 @@ int cmd_authorize(const policy_t *p, hook_opts o, int argc, char **argv)
}
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. */
+ // The branch HEAD points at costs admin: a repository whose
+ // clones check out nothing is a broken repository.
+
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 */
+ need = LV_WRITE; // a creation
} else {
need = fast_forward(o, old, new) ? LV_WRITE : LV_FORCE;
}
diff --git a/src/policy.c b/src/policy.c
index ef429e0..aae99a1 100644
--- a/src/policy.c
+++ b/src/policy.c
@@ -1,16 +1,12 @@
-/* policy.c - reading the policy, and answering from it.
- *
- * Grammar (see authz.conf for the prose version):
- *
- * <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. */
+// <user> <repo> <write|force|admin> [<ref pattern> ...]
+//
+// '#' starts a comment anywhere on a line. Rules are additive and the strongest
+// wins. There is no 'deny': a rule is taken away by editing the file, not by
+// ordering it after another one.
+//
+// A line that does not parse makes the whole file unusable. Every push refused
+// for an evening is better than a mistyped line quietly widening access.
+
#include "authz.h"
#include <ctype.h>
@@ -19,10 +15,8 @@
#include <stdlib.h>
#include <string.h>
-#define DEFAULT_PROTECTED "refs/heads/main"
+// Spelled out rather than as a regular expression: the engine has none.
-/* 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[] = "_@*?[";
@@ -35,9 +29,7 @@ static int in_set(unsigned char c, const char *extra)
strchr(extra, (int)c) != NULL);
}
-/* ------------------------------------------------------------------ little */
-
-/* Trims in place: leading by moving the pointer, trailing by writing over it. */
+// Trims in place: leading by moving the pointer, trailing by writing over it.
char *authz_trim(char *s)
{
char *end;
@@ -67,7 +59,7 @@ int authz_split_ws(char *line, char **f, int max)
if (*p != '\0')
*p++ = '\0';
if (n == max)
- return n + 1; /* "too many", the caller decides */
+ return n + 1; // "too many"; the caller decides
}
return n;
}
@@ -90,8 +82,6 @@ static void perr(policy_t *p, int line, const char *fmt, ...)
va_end(ap);
}
-/* ------------------------------------------------------------ name shapes */
-
int authz_user_pattern_ok(const char *s)
{
size_t i;
@@ -118,8 +108,6 @@ int authz_repo_pattern_ok(const char *s)
return 1;
}
-/* ------------------------------------------------------------------ levels */
-
const char *authz_level_name(level_t l)
{
switch (l) {
@@ -143,8 +131,6 @@ int authz_level_of(const char *name)
return -1;
}
-/* ----------------------------------------------------------- normalisation */
-
char *authz_norm_repo(const char *in)
{
size_t n;
@@ -159,8 +145,9 @@ char *authz_norm_repo(const char *in)
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. */
+// One spelling for a ref: "main", "heads/main" and "refs/heads/main" are one
+// branch, and a bare name can never mean a tag.
+
char *authz_norm_ref(const char *in)
{
size_t n;
@@ -174,9 +161,9 @@ char *authz_norm_ref(const char *in)
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. */
+ // "heads/main" and friends are half a refname. Anything else, slashes
+ // included, is a branch name.
+
if (strncmp(in, "heads/", 6) == 0 || strncmp(in, "tags/", 5) == 0 ||
strncmp(in, "notes/", 6) == 0) {
n = strlen(in) + 6;
@@ -190,7 +177,6 @@ char *authz_norm_ref(const char *in)
return out;
}
-/* A whole list of them, space separated, the way 'set' lines store them. */
static rule_t *rule_slot(policy_t *p)
{
rule_t *r;
@@ -218,12 +204,10 @@ static void parse_set(policy_t *p, char *line, int lineno)
}
key = xsubstr(body, (size_t)(sp - body));
- /* protected-refs was removed, and it is named rather than left to "unknown
- * setting" on purpose. A policy that still carries one of these lines has
- * to be refused rather than read as if the line were a comment: ignoring it
- * would leave every branch one fast-forward away from whoever holds 'write'
- * on them, which is the opposite of what the line was there to prevent, and
- * the operator would learn that from a push instead of from the parser. */
+ // Refused by name, not left to "unknown setting": a policy that still
+ // carries this line must not be read as if the line were a comment, which
+ // would hand every branch to whoever holds write on it.
+
if (strncmp(key, "protected-refs", 14) == 0)
perr(p, lineno, "protected-refs no longer exists: name the refs a rule "
"covers instead, for example \"dave team admin refs/heads/main\"");
@@ -343,8 +327,6 @@ int policy_load(policy_t *p)
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')
@@ -404,10 +386,9 @@ level_t authz_need_for(const char *ref, level_t have, char *raised,
if (raised != NULL && raisedsz > 0)
raised[0] = '\0';
- /* Anything that is not a branch or a tag is for maintainers, whatever a rule
- * appears to grant about it. Nothing else raises a price here: a rule says
- * what it says, and there is no second, invisible list that can make a ref
- * cost more behind the operator's back. */
+ // Neither a branch nor a tag is admin whatever a rule appears to grant.
+ // Nothing else raises a price: a rule says what it says.
+
if (!ordinary_ref(ref) && have != LV_ADMIN) {
if (raised != NULL)
snprintf(raised, raisedsz, "neither a branch nor a tag");
@@ -416,18 +397,16 @@ level_t authz_need_for(const char *ref, level_t have, char *raised,
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 */
- level_t here; /* the best held on this ref specifically */
- int any; /* any rule at all, at any level */
+ 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 in the repository at all
+ level_t here; // the best held on this ref specifically
+ 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)
{
@@ -450,10 +429,10 @@ static void scope(const policy_t *p, const char *user, const char *repo,
if (p->rules[i].level > s->strongest)
s->strongest = p->rules[i].level;
- /* What this rule says about the ref in question, whatever its level: a
- * refusal has to name the level the user actually holds on this ref,
- * because "carol has force on team" while refusing her a force push to
- * main is a sentence that sends somebody to open the file and stare. */
+ // What this rule says about this ref, whatever its level: a refusal
+ // that names a level held elsewhere sends somebody to open the file
+ // and stare at it.
+
if (ref != NULL) {
level_t covers = LV_NONE;
@@ -504,10 +483,10 @@ void authz_check(const policy_t *p, const char *user, const char *repo,
}
if (ref == NULL) {
- /* No ref named: "may this user do this somewhere in the repository?"
- * This is the question 'can this person push anything at all here', and
- * it is answered by whether any rule reaches the repository, not by
- * which refs a scoped rule would cover. */
+ // No ref named: can this person push anything here at all? Answered
+ // by whether any rule reaches the repository, not by which refs a
+ // scoped rule would cover.
+
char *r = authz_norm_repo(repo);
scope(p, user, repo, need, NULL, &s);
diff --git a/src/util.c b/src/util.c
index a7513b3..e099197 100644
--- a/src/util.c
+++ b/src/util.c
@@ -1,8 +1,6 @@
-/* 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. */
+// Allocation that stops rather than limps: a hook that cannot allocate is in no
+// position to decide anything, so these exit 3 instead of returning NULL
+// somewhere a caller forgot to look.
#include "authz.h"
#include <stdarg.h>
diff --git a/src/validate.c b/src/validate.c
index 81865d5..7004731 100644
--- a/src/validate.c
+++ b/src/validate.c
@@ -1,16 +1,10 @@
-/* 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.
- */
+// Run from the entrypoint before anything is served, and from CI.
+//
+// An error means a push would be authorised wrongly; a warning means a human is
+// about to file a ticket. Missing files are skipped rather than warned about: a
+// validator that cries about a developer machine gets ignored, which is worse
+// than not checking.
+
#include "authz.h"
#include <ctype.h>
@@ -22,8 +16,8 @@
#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. */
+// One validate per process, so file scope is enough.
+
static int g_errors;
static int g_warnings;
@@ -62,8 +56,6 @@ static void vok(const char *fmt, ...)
fputc('\n', stdout);
}
-/* ------------------------------------------------------------- file lookups */
-
static int ci_equal(const char *a, const char *b)
{
for (; *a != '\0' && *b != '\0'; a++, b++) {
@@ -86,8 +78,9 @@ static char *strip(char *s)
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. */
+// [section] key = value, last one winning - which is the mistake worth
+// reporting in a gitconfig.
+
static int ini_value(const char *path, const char *section, const char *key,
char *out, size_t outsz)
{
@@ -122,7 +115,7 @@ static int ini_value(const char *path, const char *section, const char *key,
if (!ci_equal(strip(t), key))
continue;
snprintf(out, outsz, "%s", strip(eq + 1));
- { /* gitconfig allows quoting */
+ { // gitconfig allows quoting
size_t n = strlen(out);
if (n >= 2 && out[0] == '"' && out[n - 1] == '"') {
@@ -137,7 +130,7 @@ static int ini_value(const char *path, const char *section, const char *key,
return found;
}
-/* sshd_config's "Directive value", last one winning, case-insensitive. */
+// 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;
@@ -171,8 +164,6 @@ static int directive_value(const char *path, const char *name, char *out, size_t
return found;
}
-/* -------------------------------------------------------------- the checks */
-
static void check_repos(const policy_t *p, const char *root)
{
DIR *d;
@@ -206,8 +197,9 @@ static void check_repos(const policy_t *p, const char *root)
}
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. */
+ // A rule naming a repository that is not there is a renamed repository,
+ // and the rule still looks fine.
+
for (i = 0; i < p->nrules; i++) {
const char *r = p->rules[i].repo;
@@ -307,8 +299,9 @@ static void check_account(const policy_t *p, validate_opts o)
int nf = 0;
char *q = line;
- /* name:password:uid:gid:gecos:home:shell - the seventh field decides
- * whether a key can open a shell at all. */
+ // The seventh field is the shell, which decides whether a key can open
+ // a shell at all. Splitting on eight would make the shell field 6.
+
while (*q != '\0') {
char *start = q;
@@ -370,7 +363,7 @@ static void check_keys(const policy_t *p, validate_opts o)
*nl = '\0';
sp = strchr(t, ' ');
if (sp != NULL)
- *sp = '\0'; /* leave the key type, e.g. ssh-ed25519 */
+ *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;
@@ -443,9 +436,9 @@ int cmd_validate(const policy_t *p, validate_opts o)
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. */
+ // The parser already printed the line numbers. A policy with errors is not
+ // used at all, so nothing else matters until it is fixed.
+
if (p->unreadable) {
verr("%s cannot be read: the hook fails closed on this, so every push is "
"denied until it is mounted", p->path);
diff --git a/test/check.c b/test/check.c
index 3df2ade..4db4b9e 100644
--- a/test/check.c
+++ b/test/check.c
@@ -1,10 +1,5 @@
-/* check.c - The decision, and the sentence that goes with it. A refusal has to name
- * the level held, the ref and the level required, because a person who is
- * refused should be able to fix it without opening the policy first.
- *
- * Part of the direct suite: this links the library, not the command
- * line. test/run.sh is the other half, and drives the program the way git does.
- */
+// The decision, and the sentence that goes with it: a refusal names the level
+// held, the ref, and the level required.
#include "test.h"
static void test_check(void)
@@ -22,65 +17,67 @@ static void test_check(void)
"erin secrets admin\n");
CHECK_INT(rc, 0);
- /* the ladder */
+ // 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 */
+ // 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. */
+ // '@all' reaches the named and nobody else. The '@all *' rule reaches every
+ // repository, so a named user is not confined to their own rule's repo.
+
expect_allow(&p, "carol", "web", LV_WRITE, "refs/heads/feature/any");
expect_allow(&p, "erin", "web", LV_WRITE, "refs/heads/feature/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");
- /* main is not special: it is refused here because no rule of bob's or
- * carol's names it, and allowed for dave because his names everything. */
+ // main is not special: refused because no rule of theirs names it, allowed for
+ // dave because his names everything.
+
expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/main",
"but not on refs/heads/main");
expect_deny(&p, "carol", "team", LV_FORCE, "refs/heads/main",
"but not on refs/heads/main");
expect_allow(&p, "dave", "team", LV_WRITE, "refs/heads/main");
- /* and the person whose rule does name main, and nothing else, gets main */
+ // and the person whose rule does name main, and nothing else, gets main
expect_allow(&p, "frank", "team", LV_WRITE, "refs/heads/main");
- /* frank reaches the '@all' rule like anyone else the policy names, so what
- * he lacks is a branch nobody's rule names, and a rewrite of his own */
+ // frank reaches '@all' like anyone named, so what he lacks is a branch nobody's
+ // rule names, and a rewrite of his own.
+
expect_allow(&p, "frank", "team", LV_WRITE, "refs/heads/feature/x");
expect_deny(&p, "frank", "team", LV_WRITE, "refs/heads/dev",
"but not on refs/heads/dev");
expect_deny(&p, "frank", "team", LV_FORCE, "refs/heads/main", "needs force");
- /* refs that are not branches or tags: only an admin, at any request level */
+ // 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 */
+ // the same branch, three spellings
expect_deny(&p, "bob", "team", LV_WRITE, "main", "but not on refs/heads/main");
expect_deny(&p, "bob", "team", LV_WRITE, "heads/main",
"but not on refs/heads/main");
- /* repository matching: .git is the same repository */
+ // 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 */
+ // 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_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 */
+ // what a denial names: the level held, and the level needed
{
decision_t d;
@@ -102,42 +99,42 @@ static void test_scope_edges(void)
policy_t p;
int rc;
- /* a rule with no refs is the whole repository: every branch, main included,
- * which is exactly why naming the refs is the honest way to write one */
+ // a rule with no refs is the whole repository: every branch, main included, *
+ // which is exactly why naming the refs is the honest way to write one
rc = load_text(&p, "bob team write\n");
CHECK_INT(rc, 0);
expect_allow(&p, "bob", "team", LV_WRITE, "refs/heads/anything");
expect_allow(&p, "bob", "team", LV_WRITE, "refs/heads/main");
- /* write on everything still is not force */
+ // write on everything still is not force
expect_deny(&p, "bob", "team", LV_FORCE, "refs/heads/main", "needs force");
policy_free(&p);
- /* a bare name is a branch, and only a branch */
+ // 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_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 */
+ // 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");
- /* A refusal names the level held on the ref in question, not the strongest
- * level held somewhere in the repository: "you have force here" next to a
- * refusal is a sentence nobody can act on. */
+ // A refusal names the level held on the ref in question, not the strongest
+ // level held somewhere in the repository: "you have force here" next to a
+ // refusal is a sentence nobody can act on.
expect_deny(&p, "bob", "team", LV_FORCE, "refs/heads/dev",
"bob has write on team refs/heads/dev; it needs force");
expect_deny(&p, "bob", "team", LV_WRITE, "refs/heads/other",
"but not on refs/heads/other");
policy_free(&p);
- /* naming refs in a rule is the whole of the mechanism: what is not named is
- * not granted, and the refusal says so rather than blaming a list */
+ // naming refs in a rule is the whole of the mechanism: what is not named is *
+ // not granted, and the refusal says so rather than blaming a list
rc = load_text(&p, "bob web write refs/heads/feature/* refs/heads/dev\n");
CHECK_INT(rc, 0);
expect_allow(&p, "bob", "web", LV_WRITE, "refs/heads/dev");
@@ -146,7 +143,7 @@ static void test_scope_edges(void)
expect_deny(&p, "bob", "api", LV_WRITE, "refs/heads/dev", "no rule");
policy_free(&p);
- /* reachable-by-nobody detection, which validate reports */
+ // 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"));
diff --git a/test/glob.c b/test/glob.c
index ee1bece..cbb97c8 100644
--- a/test/glob.c
+++ b/test/glob.c
@@ -1,9 +1,4 @@
-/* glob.c - What a glob matches. Written out rather than reached for with fnmatch(3)
- * or regex(3), so this is the file that says what "*" and "[!a-z]" mean here.
- *
- * Part of the direct suite: this links the library, not the command
- * line. test/run.sh is the other half, and drives the program the way git does.
- */
+// What a glob matches, since nothing here uses fnmatch or regex.
#include "test.h"
static void test_glob(void)
@@ -13,7 +8,7 @@ static void test_glob(void)
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/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"));
@@ -26,17 +21,17 @@ static void test_glob(void)
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("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/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("**", "x")); // redundant stars
CHECK(!glob_match("refs/heads/*", ""));
}
diff --git a/test/need.c b/test/need.c
index f831111..013674e 100644
--- a/test/need.c
+++ b/test/need.c
@@ -1,18 +1,13 @@
-/* need.c - What a ref costs beyond what the rule said - which is only ever the case
- * for refs outside refs/heads and refs/tags. There is no second list in the
- * policy that can raise the price of a ref behind the operator's back.
- *
- * Part of the direct suite: this links the library, not the command
- * line. test/run.sh is the other half, and drives the program the way git does.
- */
+// What a ref costs beyond what the rule said - only ever refs outside
+// refs/heads and refs/tags.
#include "test.h"
static void test_need_for(void)
{
char raised[64];
- /* A branch or a tag costs exactly what the rule said: there is no list
- * elsewhere in the file that can raise the price of one. */
+ // A branch or a tag costs exactly what the rule said: there is no list *
+ // elsewhere in the file that can raise the price of one.
CHECK_INT(authz_need_for("refs/heads/dev", LV_WRITE, raised, sizeof(raised)),
LV_WRITE);
CHECK_STR(raised, "");
@@ -23,8 +18,8 @@ static void test_need_for(void)
CHECK_INT(authz_need_for("refs/heads/feature/x", LV_FORCE, raised, sizeof(raised)),
LV_FORCE);
- /* Anything outside refs/heads and refs/tags is for maintainers, whatever a
- * rule appears to grant about it. */
+ // Anything outside refs/heads and refs/tags is for maintainers, whatever a *
+ // rule appears to grant about it.
CHECK_INT(authz_need_for("refs/pull/1/head", LV_WRITE, raised, sizeof(raised)),
LV_ADMIN);
CHECK_STR(raised, "neither a branch nor a tag");
@@ -34,7 +29,7 @@ static void test_need_for(void)
LV_ADMIN);
CHECK_INT(authz_need_for("refs/notes/x", LV_ADMIN, raised, sizeof(raised)),
LV_ADMIN);
- CHECK_STR(raised, ""); /* admin is already the top */
+ CHECK_STR(raised, ""); // admin is already the top
}
int main(void)
diff --git a/test/norm.c b/test/norm.c
index acfb6ec..4b8a35a 100644
--- a/test/norm.c
+++ b/test/norm.c
@@ -1,10 +1,5 @@
-/* norm.c - Refs and repositories have one spelling each internally. This is the file
- * that pins "main", "heads/main" and "refs/heads/main" being one branch, and
- * a bare name never meaning a tag.
- *
- * Part of the direct suite: this links the library, not the command
- * line. test/run.sh is the other half, and drives the program the way git does.
- */
+// One spelling per ref: "main", "heads/main" and "refs/heads/main" are one
+// branch, and a bare name is never a tag.
#include "test.h"
static void test_normalisation(void)
@@ -21,7 +16,7 @@ static void test_normalisation(void)
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 */
+ 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");
@@ -49,7 +44,7 @@ static void test_normalisation(void)
CHECK_STR(s, "*");
free(s);
s = authz_norm_repo(".git");
- CHECK_STR(s, ".git"); /* a repository called ".git" is not a suffix */
+ CHECK_STR(s, ".git"); // a repository called ".git" is not a suffix
free(s);
CHECK_INT(authz_level_of("write"), LV_WRITE);
@@ -66,13 +61,13 @@ static void test_normalisation(void)
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")); // 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("group/team")); // flat names only
CHECK(!authz_repo_pattern_ok(""));
CHECK(!authz_repo_pattern_ok("a$b"));
}
diff --git a/test/parse.c b/test/parse.c
index fb137c5..5c8cb5f 100644
--- a/test/parse.c
+++ b/test/parse.c
@@ -1,10 +1,5 @@
-/* parse.c - Reading the file: what parses, what is refused, and who "@all" turns out to
- * be. One bad line poisons the whole file, so the error cases matter as much
- * as the good ones.
- *
- * Part of the direct suite: this links the library, not the command
- * line. test/run.sh is the other half, and drives the program the way git does.
- */
+// What parses, what is refused, and who "@all" turns out to be. One bad line
+// poisons the whole file.
#include "test.h"
static void test_parse(void)
@@ -29,14 +24,14 @@ static void test_parse(void)
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.rules[2].refs[0], "refs/heads/main"); // normalised at parse time
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. */
+ // 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);
@@ -67,9 +62,9 @@ static void test_parse(void)
CHECK_INT(rc, -1);
policy_free(&p);
- /* Removed settings are refused by name, not ignored: a policy that
- * still carries one would otherwise mean "everyone with write can fast
- * -forward main" while looking like it said the opposite. */
+ // Removed settings are refused by name, not ignored: a policy that still
+ // carries one would otherwise mean "everyone with write can fast -forward main"
+ // while looking like it said the opposite.
rc = load_text(&p, "set protected-refs refs/heads/main\n");
CHECK_INT(rc, -1);
policy_free(&p);
@@ -79,7 +74,7 @@ static void test_parse(void)
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 */
+ CHECK_INT(rc, -1); // one bad line poisons the file: nothing is used
policy_free(&p);
fflush(stderr);
@@ -87,7 +82,7 @@ static void test_parse(void)
close(keep);
}
- /* There is no settings list any more: a rule says what it says. */
+ // There is no settings list any more: a rule says what it says.
rc = load_text(&p, "alice * admin\n");
CHECK_INT(rc, 0);
CHECK_INT(p.nrules, 1);
@@ -106,18 +101,18 @@ static void test_known_users(void)
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, "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 */
+ 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, "alice")); // a pattern is still a name
CHECK(!authz_user_known(&p, "bob"));
policy_free(&p);
}
diff --git a/test/run.sh b/test/run.sh
index 39f26b7..bc1a9e4 100755
--- a/test/run.sh
+++ b/test/run.sh
@@ -1,16 +1,11 @@
#!/bin/sh
-# run.sh - drive git-authz the way git does, without git.
+# Drive git-authz the way git does, without git: identity in the environment,
+# "old new ref" on stdin, the repository as cwd. The two facts only git knows are
+# supplied with --ff and --head, so no repository or commits are needed.
#
-# Everything a receive hook knows, this feeds it: an identity in the
-# environment, "old new ref" lines on stdin, the repository as the working
-# directory. What only the object store knows - whether old is an ancestor of
-# new, and which branch HEAD points at - is supplied explicitly (--ff, --head),
-# so the suite is deterministic and needs no repository, no commits, and no
-# git. hook.c asks git those questions in production; the answers it gets are
-# what the tests below pin the consequences of.
-#
-# POSIX sh: this runs under dash, busybox ash and bash alike, because the
-# container it has to survive is Alpine.
+# POSIX sh: runs under dash, busybox ash and bash, because the container it has to
+# survive is Alpine.
+
AUTHZ=${AUTHZ:-./git-authz}
if [ ! -x "$AUTHZ" ]; then
@@ -91,9 +86,9 @@ do_check() {
"$AUTHZ" --policy "$POLICY" check "$@" 2>&1
}
-# Which policy the two drivers below read. Overridden per test with
-# "out=$(POLICY=something push ...)", which is a subshell and therefore does not
-# leak into the next test.
+# Overridden per test with "out=$(POLICY=something push ...)", a subshell, so it
+# does not leak into the next test.
+
POLICY=$P
# push <user|none> <repo> [extra authorize args] (ref lines on stdin)
@@ -110,12 +105,10 @@ push() {
fi
}
-# hook <user|none> <repodir> (invoked through the hook name, as git does, with
-# the repository as the working directory and git's own argument in hand)
-# Reached the way core.hooksPath reaches it: by name, with the repository as the
-# working directory, git's own argument in hand (which is not ours, and must not
-# be read as one), and no --policy anywhere - the hook gets its policy from
-# GIT_HOST_AUTHZ or the default path, exactly as a deployed one does.
+# hook <user|none> <repodir>
+# The way core.hooksPath reaches it: by name, repo as cwd, git's own argument in
+# hand (not ours, and must not be read as one), no --policy anywhere.
+
hook() {
user=$1
dir=$2
@@ -154,8 +147,8 @@ if [ ! -L "$TMP/bin/pre-receive" ]; then
skip_it "hook reached by its own name" "cannot make a symlink here"
fi
-# A policy with no '@all' line, for the tests that need a repository and a
-# stranger rather than a policy that reaches everywhere.
+# No '@all' line: for tests that need a stranger and a specific repository.
+
cat >"$TMP/plain.conf" <<'EOF'
alice * admin
bob team write refs/heads/feature/*
@@ -429,14 +422,10 @@ expect "and the last path component works when it is not the root" 0 "team" "$rc
# ------------------------------------------- the two facts that belong to git
#
-# Everything else the hook knows it works out of the line git gave it. Two
-# facts do not come that way: whether HEAD is a branch, and whether old is an
-# ancestor of new. Those are asked of git, and asking them is a code path the
-# rest of this suite cannot reach, because there is no git in it.
-#
-# So: a stand-in named git, and the real one kept out of PATH. A fake that
-# answers whatever it is told is worth more here than the real thing, which
-# would answer a question about the host instead of the question the hook asked.
+# The two questions the rest of this suite cannot reach, because there is no git
+# in it. A stand-in named git answers to order, with the real one kept out of
+# PATH: the host's git would answer a different question than the one asked.
+
mkdir -p "$TMP/fakegit"
cat >"$TMP/fakegit/git" <<'EOF'
@@ -486,8 +475,8 @@ out=$(printf '%s %s %s\n' "$A" "$B" refs/heads/feature/x |
hookgit bob "$TMP/root/team.git" PATH="$TMP/fakegit" FAKE_HEAD=refs/heads/main FAKE_FF=1); rc=$?
expect "and one it does not, force" 1 "needs force" "$rc" "$out"
-# No git at all: the hook cannot ask, so it must not guess in the caller's
-# favour. A deletion it cannot place is charged the most, not the least.
+# No git to ask: the hook must not guess in the caller's favour.
+
out=$(printf '%s %s %s\n' "$A" "$ZERO" refs/heads/feature/x |
hookgit carol "$TMP/root/team.git" PATH="$TMP/empty"); rc=$?
expect "with no git to ask, a deletion is the expensive kind" 1 "needs admin" "$rc" "$out"
@@ -746,10 +735,9 @@ else
bad "--stdout lost the comments or the settings"
fi
-# A file whose *directory* is read-only cannot be replaced, which is what a
-# read-only ConfigMap mount means in practice. A 0444 file in a writable
-# directory is a different thing and worth pinning too: the grant succeeds and
-# the mode survives, because it is the directory that decides.
+# It is the directory that decides: a read-only mount is a read-only directory,
+# while a 0444 file in a writable directory is still replaceable.
+
cp "$TMP/edit.conf" "$TMP/ro.conf"
chmod 444 "$TMP/ro.conf"
out=$("$AUTHZ" --policy "$TMP/ro.conf" grant bob team admin 2>&1); rc=$?
@@ -808,9 +796,9 @@ else
out=$(make install DESTDIR="$S" 2>&1); rc=$?
expect "make install into a DESTDIR" 0 "pre-receive" "$rc" "$out"
- # The hook has to be a relative link: staged, unpacked, or shipped in an
- # image, it must point at the binary that came with it rather than at
- # whatever occupies that absolute path on the machine reading it.
+ # A relative link: an absolute one points at whatever occupies that path on
+ # whatever machine reads it.
+
link=$(ls -l "$S/usr/local/share/git-host/hooks/pre-receive")
case $link in
*'= /'*) bad "the installed hook is an absolute symlink: $link" ;;
@@ -818,9 +806,8 @@ else
*) bad "the installed hook is not a relative symlink: $link" ;;
esac
- # End to end through the installed name, with the installed policy, in a
- # repository under an installed root: nothing but the paths from the
- # installer here.
+ # Nothing here but the paths the installer chose.
+
mkdir -p "$S/var/lib/git/team.git"
out=$(printf '%s %s %s\n' "$ZERO" "$A" refs/heads/feature/x |
( cd "$S/var/lib/git/team.git" && env GIT_HOST_USER=bob \
diff --git a/test/test.h b/test/test.h
index c4f63d0..e60e5af 100644
--- a/test/test.h
+++ b/test/test.h
@@ -1,10 +1,5 @@
-/* test.h - the little harness the test programs share.
- *
- * No test framework, because a test suite with a dependency is a test suite
- * that does not run at 3am. Each program in test/ is its own: it links the
- * library, runs its own cases and reports its own count, so one failing file
- * says which area broke rather than taking the whole run down with it.
- */
+// No test framework: a suite with a dependency is a suite that does not run at
+// 3am. Each program in test/ links the library and reports its own count.
#ifndef TEST_H
#define TEST_H
@@ -61,8 +56,8 @@ static inline void note(const char *fmt, ...)
fputc('\n', stdout);
}
-/* Where the fixtures are written. UNIT_TMPDIR is there for a build that runs
- * the tests somewhere the source tree is not writable. */
+// Where the fixtures are written. UNIT_TMPDIR is there for a build that runs *
+// the tests somewhere the source tree is not writable.
static inline void test_init(const char *argv0)
{
const char *dir = getenv("UNIT_TMPDIR");
@@ -79,11 +74,11 @@ static inline int test_report(const char *what)
return failures != 0;
}
-/* ------------------------------------------------------------- fixtures */
+// ------------------------------------------------------------- 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. */
+// 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 inline int load_text(policy_t *p, const char *text)
{
static int seq;