summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authordev <dev@example>2026-11-14 01:05:08 +0000
committerdev <dev@example>2026-11-14 01:05:08 +0000
commit312ddd4936f09ae27a180ca495cacf2c06faf33e (patch)
tree2fa46ab568ad55f7e8fb844c3447b1d296b2e340 /src
parente737f3d560de2b8172e6dd83901bc1359283303c (diff)
downloadaccess-control-312ddd4936f09ae27a180ca495cacf2c06faf33e.tar.gz
access-control-312ddd4936f09ae27a180ca495cacf2c06faf33e.zip
Comments: cut to what the code cannot say
The comments had grown into essays. A file header explaining why the file exists, then a paragraph above each function restating what the next eight lines do, then a paragraph above that one explaining why that matters. The reader gets no further than the first paragraph, and the second is the one that goes stale: it describes code that has since changed, and nothing fails when it does. Cut by about half. What is left is the three things a comment can do that code cannot: say why the constraint exists (no regex because a hook must not depend on what might be missing at 3am), say what is not obvious from the shape (a bare ref name is a branch, never a tag; the seventh field of /etc/passwd is the shell), and say where it hurts (the NULL in an execvp array, the mode and owner that have to survive an atomic rewrite, the child that must not keep the hook's stdin). Block comments became // lines, which is also what the other C trees here use, and the file headers went to two or three lines. Section banners stayed: they are navigation, not prose. Behaviour is unchanged and the suites prove it: 171 direct checks, 162 behavioural, clean under -Werror and under ASan/UBSan.
Diffstat (limited to 'src')
-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
7 files changed, 225 insertions, 316 deletions
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);