summaryrefslogtreecommitdiffstats
path: root/src/validate.c
blob: 799d686b684f78a02fb2a3323eb7efc1aa267b2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// 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.

#include "authz.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

// One validate per process, so file scope is enough.

static int g_errors;
static int g_warnings;

// One message, three voices.  The tag is five columns wide so the findings line
// up when they are read back out of a log, and the counter is what --strict turns
// into a failure - an 'ok' counts nothing, so it passes NULL.

static void vmsgv(FILE *f, const char *tag, int *counter, const char *fmt, ...)
{
    va_list ap;

    if (counter != NULL)
        (*counter)++;
    fputs(tag, f);
    va_start(ap, fmt);
    vfprintf(f, fmt, ap);
    va_end(ap);
    fputc('\n', f);
}

#define verr(...)  vmsgv(stderr, "err  ", &g_errors, __VA_ARGS__)
#define vwarn(...) vmsgv(stderr, "warn ", &g_warnings, __VA_ARGS__)
#define vok(...)   vmsgv(stdout, "ok   ", NULL, __VA_ARGS__)

int cmd_validate(const policy_t *p, validate_opts o)
{
    size_t i;
    struct stat st;

    g_errors = 0;
    g_warnings = 0;

    // 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);
        return 3;
    }
    if (p->errors > 0) {
        verr("%s: %d error(s): the policy is not used, and every push is denied",
             p->path, p->errors);
        return 3;
    }
    vok("%s: %zu rule(s)", p->path, p->nrules);

    if (stat(p->path, &st) == 0 && (st.st_mode & 0004) == 0)
        vwarn("%s is not readable by anyone outside its owner and group: the hook "
              "runs as the git account and fails closed when it cannot read this",
              p->path);

    for (i = 0; i < p->nrules; i++) {
        if (strcmp(p->rules[i].user, "@all") == 0 && p->rules[i].nrefs == 0)
            vwarn("line %zu gives @all the whole of %s, which is not a default "
                  "anybody chose", p->rules[i].line, p->rules[i].repo);
    }

    if (g_errors > 0 || (o.strict && g_warnings > 0)) {
        fprintf(stderr, "%s: validate: %d error(s), %d warning(s)\n",
                progname, g_errors, g_warnings);
        return 1;
    }
    printf("validate: %s is in force, %d rule(s), %d warning(s)\n",
           p->path, (int)p->nrules, g_warnings);
    return 0;
}