Skip to content
suit Artifact [7cfb608339]
Login

Artifact [7cfb608339]

Artifact 7cfb60833965eae1cf0ca5a1e199ab09799322ac066e4ab3907a6ddcb996a6f2:


#include "lint.h"

#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

// ---- the line scanner -----------------------------------------------------

constexpr size_t SECRET_VALUE_MIN = 24;

static unsigned char lower(char c)
{
    return (unsigned char)(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c);
}

static bool is_alnum(char c)
{
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}

// The first place NEEDLE (lower case when CI) is in HAY, or nullptr.
static const char *find(const char *hay, size_t n, const char *needle, size_t m, bool ci)
{
    for (size_t i = 0; i + m <= n; i++) {
        size_t k = 0;
        while (k < m && (ci ? lower(hay[i + k]) : (unsigned char)hay[i + k]) == (unsigned char)needle[k]) k++;
        if (k == m) return hay + i;
    }
    return nullptr;
}

typedef enum { SET_UPPER_DIGIT, SET_WORD, SET_KEY } CharSet;

static bool in_set(CharSet set, char c)
{
    if (set == SET_UPPER_DIGIT) return (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
    if (set == SET_WORD) return is_alnum(c) || c == '_';
    return is_alnum(c) || c == '_' || c == '-';
}

typedef struct {
    const char *prefix;
    size_t min;  // characters of SET that must follow
    CharSet set;
} Prefix;

static const Prefix prefixes[] = {
    {"AKIA", 16, SET_UPPER_DIGIT}, {"ghp_", 20, SET_WORD}, {"gho_", 20, SET_WORD},
    {"ghs_", 20, SET_WORD}, {"github_pat_", 20, SET_WORD}, {"sk-", 20, SET_KEY},
    {"xoxb-", 10, SET_KEY}, {"xoxp-", 10, SET_KEY}, {"xoxa-", 10, SET_KEY},
};

static bool has_prefix_token(const char *line, size_t len)
{
    for (size_t i = 0; i < len; i++) {
        for (size_t k = 0; k < sizeof prefixes / sizeof prefixes[0]; k++) {
            const Prefix *p = &prefixes[k];
            size_t m = strlen(p->prefix);
            if (i + m + p->min > len || memcmp(line + i, p->prefix, m) != 0) continue;
            size_t n = 0;
            while (n < p->min && in_set(p->set, line[i + m + n])) n++;
            if (n == p->min) return true;
        }
    }
    return false;
}

static bool has_private_key(const char *line, size_t len)
{
    static const char begin[] = "-----BEGIN";
    static const char end[] = "PRIVATE KEY-----";
    const char *b = find(line, len, begin, sizeof begin - 1, false);
    if (b == nullptr) return false;
    const char *after = b + sizeof begin - 1;
    return find(after, len - (size_t)(after - line), end, sizeof end - 1, false) != nullptr;
}

static bool is_value_char(char c)
{
    return is_alnum(c) || c == '+' || c == '/' || c == '=' || c == '-' || c == '_';
}

// A run of value characters at S that is long enough and is not one character
// repeated. A reference such as $TOKEN or <your token> starts with a character
// that is no value character, so it has no run at all.
static bool long_value(const char *s, size_t n)
{
    size_t k = 0;
    bool differs = false;
    while (k < n && is_value_char(s[k])) {
        differs |= s[k] != s[0];
        k++;
        if (k >= SECRET_VALUE_MIN && differs) return true;
    }
    return false;
}

static bool is_gap(char c)
{
    return c == ' ' || c == '\t' || c == '"' || c == '\'';
}

static const char *const key_words[] = {"token", "secret", "password", "passwd", "api_key", "apikey", "api-key"};

// A word holding a credential's name, spaces and quotes, = or :, spaces and
// quotes, then a long value. WORD_END is where the last word that was looked
// at ended: a keyword inside it leads to the same place and is not looked at.
static bool has_credential(const char *line, size_t len)
{
    size_t word_end = 0;
    for (size_t i = 0; i < len; i++) {
        for (size_t k = 0; k < sizeof key_words / sizeof key_words[0]; k++) {
            size_t m = strlen(key_words[k]);
            if (i + m > len || find(line + i, m, key_words[k], m, true) == nullptr) continue;
            size_t j = i + m;
            if (j < word_end) continue;
            while (j < len && (is_alnum(line[j]) || line[j] == '_' || line[j] == '-')) j++;
            word_end = j;
            while (j < len && is_gap(line[j])) j++;
            if (j == len || (line[j] != '=' && line[j] != ':')) continue;
            j++;
            while (j < len && is_gap(line[j])) j++;
            if (long_value(line + j, len - j)) return true;
        }
    }
    return false;
}

static const char *const attributions[] = {
    "co-authored-by:", "generated with", "generated by ai", "claude-session:", "written by ai", "assisted by ai",
};

static bool has_attribution(const char *line, size_t len)
{
    for (size_t k = 0; k < sizeof attributions / sizeof attributions[0]; k++)
        if (find(line, len, attributions[k], strlen(attributions[k]), true) != nullptr) return true;
    return false;
}

const char *lint_line(const LintRules *r, const char *line, size_t len)
{
    if (has_private_key(line, len) || has_prefix_token(line, len) || has_credential(line, len))
        return "token-shaped value";
    if (has_attribution(line, len)) return "attribution text";
    for (uint32_t k = 0; k < r->n_forbid; k++)
        if (find(line, len, r->forbid[k], strlen(r->forbid[k]), true) != nullptr) return "text this wardrobe forbids";
    return nullptr;
}

size_t lint_text(const LintRules *r, bool exempt, const char *data, size_t len, LintSink sink, void *state)
{
    size_t probe = len < LINT_BINARY_PROBE ? len : LINT_BINARY_PROBE;
    if (memchr(data, '\0', probe) != nullptr) return 0;
    size_t problems = 0;
    size_t line = 0;
    size_t pos = 0;
    while (pos < len) {
        const char *nl = memchr(data + pos, '\n', len - pos);
        size_t end = nl != nullptr ? (size_t)(nl - data) : len;
        size_t n = end - pos;
        line++;
        const char *what = n > LINT_LINE_MAX ? "line is longer than 64 KiB" : (exempt ? nullptr : lint_line(r, data + pos, n));
        if (what != nullptr) {
            sink(state, line, what);
            problems++;
        }
        pos = end + 1;
    }
    return problems;
}

bool lint_has_header(const char *data, size_t len)
{
    const char *nl = memchr(data, '\n', len);
    size_t n = nl != nullptr ? (size_t)(nl - data) : len;
    if (n > 0 && data[n - 1] == '\r') n--;
    return n == 3 && memcmp(data, "---", 3) == 0;
}

// ---- rule 6: the scripts a SKILL.md names -------------------------------------

static const char *const script_exts[] = {".sh", ".bash", ".py", ".js", ".mjs", ".cjs", ".ts", ".rb", ".pl"};
static const char *const skill_dirs[] = {"./", "${SKILL_DIR}/", "$SKILL_DIR/", "<skill-dir>/"};
static const char *const shell_langs[] = {"", "sh", "bash", "shell", "zsh", "console"};
static const char trim_set[] = "\"'(),;:";

typedef struct {
    const char *skill;
    LintLookup look;
    void *look_state;
    LintSink sink;
    void *state;
    size_t problems;
} ScriptScan;

// A word's path joined to skills/..., and room for any word of a line.
static char script_path[LINT_LINE_MAX + 300];

static bool is_space(char c)
{
    return c == ' ' || c == '\t' || c == '\r';
}

static bool starts(const char *s, size_t n, const char *head)
{
    size_t m = strlen(head);
    return n >= m && memcmp(s, head, m) == 0;
}

static bool is_script(const char *w, size_t n)
{
    for (size_t k = 0; k < sizeof script_exts / sizeof script_exts[0]; k++) {
        size_t m = strlen(script_exts[k]);
        if (n > m && memcmp(w + n - m, script_exts[k], m) == 0) return true;
    }
    return false;
}

// Join REST (N bytes) to script_path, which holds DEPTH folders, folding "."
// and "..". False when ".." climbs out of a skill folder or the end is not
// inside one.
static bool join(size_t depth, const char *rest, size_t n)
{
    size_t at = strlen(script_path);
    size_t i = 0;
    while (i < n) {
        size_t m = 0;
        while (i + m < n && rest[i + m] != '/') m++;
        bool up = m == 2 && rest[i] == '.' && rest[i + 1] == '.';
        if (up && depth <= 2) return false;
        if (up) {
            while (script_path[at - 1] != '/') at--;
            at--;
            depth--;
        } else if (m > 0 && !(m == 1 && rest[i] == '.')) {
            script_path[at++] = '/';
            memcpy(script_path + at, rest + i, m);
            at += m;
            depth++;
        }
        script_path[at] = '\0';
        i += m + 1;
    }
    return depth >= 3;
}

static void problem(ScriptScan *c, size_t line, const char *what, const char *w, size_t n)
{
    char text[300];
    snprintf(text, sizeof text, "%s: %.*s", what, (int)(n < 200 ? n : 200), w);
    c->sink(c->state, line, text);
    c->problems++;
}

// One word of a code span or shell line; RUNS when it starts a shell line.
static void scan_word(ScriptScan *c, size_t line, const char *w, size_t n, bool runs)
{
    while (n > 0 && memchr(trim_set, w[0], sizeof trim_set - 1) != nullptr) {
        w++;
        n--;
    }
    while (n > 0 && memchr(trim_set, w[n - 1], sizeof trim_set - 1) != nullptr) n--;
    if (!is_script(w, n) || find(w, n, "://", 3, false) != nullptr || memchr(w, '*', n) != nullptr) return;
    snprintf(script_path, sizeof script_path, "skills/%s", c->skill);
    size_t skip = 0;
    for (size_t k = 0; k < sizeof skill_dirs / sizeof skill_dirs[0]; k++)
        if (starts(w, n, skill_dirs[k])) skip = strlen(skill_dirs[k]);
    bool inside;
    if (skip > 0 || starts(w, n, "../")) {
        inside = join(2, w + skip, n - skip);
    } else if (starts(w, n, "skills/")) {
        script_path[6] = '\0';
        inside = join(1, w + 7, n - 7);
    } else {
        const char *slash = memchr(w, '/', n);
        if (slash == nullptr || slash == w) return;
        size_t at = strlen(script_path);
        script_path[at] = '/';
        memcpy(script_path + at + 1, w, (size_t)(slash - w));
        script_path[at + 1 + (size_t)(slash - w)] = '\0';
        if (c->look(c->look_state, script_path) != LINT_DIR) return;
        script_path[at] = '\0';
        inside = join(2, w, n);
    }
    LintKind kind = inside ? c->look(c->look_state, script_path) : LINT_NONE;
    if (!inside) problem(c, line, "names a script outside its skill folder", w, n);
    else if (kind == LINT_NONE || kind == LINT_DIR) problem(c, line, "names a script that is not there", w, n);
    else if (runs && kind == LINT_FILE) problem(c, line, "runs a script that is not executable", w, n);
}

static void scan_words(ScriptScan *c, size_t line, const char *s, size_t n, bool shell)
{
    size_t i = 0;
    bool first = true;
    while (i < n) {
        while (i < n && is_space(s[i])) i++;
        size_t m = 0;
        while (i + m < n && !is_space(s[i + m])) m++;
        if (m > 0) scan_word(c, line, s + i, m, shell && first);
        first = false;
        i += m;
    }
}

static bool shell_lang(const char *s, size_t n)
{
    size_t w = 0;
    while (w < n && !is_space(s[w])) w++;
    for (size_t k = 0; k < sizeof shell_langs / sizeof shell_langs[0]; k++)
        if (strlen(shell_langs[k]) == w && find(s, w, shell_langs[k], w, true) != nullptr) return true;
    return false;
}

size_t lint_scripts(const char *skill, const char *data, size_t len, LintLookup look, void *look_state,
    LintSink sink, void *state)
{
    ScriptScan c = {skill, look, look_state, sink, state, 0};
    bool fence = false;
    bool shell = false;
    size_t line = 0;
    size_t pos = 0;
    while (pos < len) {
        const char *nl = memchr(data + pos, '\n', len - pos);
        size_t end = nl != nullptr ? (size_t)(nl - data) : len;
        const char *s = data + pos;
        size_t n = end - pos;
        size_t k = 0;
        while (k < n && is_space(s[k])) k++;
        line++;
        pos = end + 1;
        if (n > LINT_LINE_MAX) continue;
        if (starts(s + k, n - k, "```") || starts(s + k, n - k, "~~~")) {
            shell = !fence && shell_lang(s + k + 3, n - k - 3);
            fence = !fence;
        } else if (fence) {
            if (shell) scan_words(&c, line, s, n, true);
        } else {
            const char *open = nullptr;
            for (size_t i = 0; i < n; i++) {
                if (s[i] != '`') continue;
                if (open != nullptr) scan_words(&c, line, open, (size_t)(s + i - open), false);
                open = open != nullptr ? nullptr : s + i + 1;
            }
        }
    }
    return c.problems;
}

// ---- suit.lint --------------------------------------------------------------

__attribute__((format(printf, 3, 4)))
static bool fail(LintError *e, int line, const char *fmt, ...)
{
    va_list ap;
    e->line = line;
    e->err = 0;
    va_start(ap, fmt);
    vsnprintf(e->msg, sizeof e->msg, fmt, ap);
    va_end(ap);
    return false;
}

static bool fail_io(LintError *e, const char *what, int err)
{
    fail(e, 0, "cannot %s: %s", what, strerror(err));
    e->err = err;
    return false;
}

// No control byte, and no space at either end, which nobody could see.
static bool text_ok(const char *s)
{
    size_t n = strlen(s);
    for (size_t i = 0; i < n; i++)
        if ((unsigned char)s[i] < 0x20 || s[i] == 0x7f) return false;
    return s[0] != ' ' && s[n - 1] != ' ';
}

// Relative, with no empty, "." or ".." folder in it and no slash at the end.
static bool path_ok(const char *s)
{
    while (true) {
        size_t n = strcspn(s, "/");
        bool dot = (n == 1 && s[0] == '.') || (n == 2 && s[0] == '.' && s[1] == '.');
        if (n == 0 || dot) return false;
        if (s[n] == '\0') return true;
        s += n + 1;
    }
}

static bool add_allow(LintRules *r, LintError *e, int line, const char *arg)
{
    if (!path_ok(arg) || !text_ok(arg))
        return fail(e, line, "allow takes a path relative to the wardrobe's top, with no space at either end");
    for (uint32_t i = 0; i < r->n_allow; i++)
        if (strcmp(r->allow[i], arg) == 0) return fail(e, line, "duplicate allow %.80s", arg);
    if (r->n_allow == LINT_ALLOW_MAX) return fail(e, line, "too many allow lines (limit %u)", LINT_ALLOW_MAX);
    r->allow[r->n_allow++] = arg;
    return true;
}

static bool add_forbid(LintRules *r, LintError *e, int line, char *arg)
{
    if (strlen(arg) > LINT_TEXT_MAX) return fail(e, line, "forbid text is over %zu bytes", LINT_TEXT_MAX);
    if (!text_ok(arg)) return fail(e, line, "forbid takes text with no control byte and no space at either end");
    for (char *c = arg; *c != '\0'; c++) *c = (char)lower(*c);
    for (uint32_t i = 0; i < r->n_forbid; i++)
        if (strcmp(r->forbid[i], arg) == 0) return fail(e, line, "duplicate forbid %.80s", arg);
    if (r->n_forbid == LINT_FORBID_MAX) return fail(e, line, "too many forbid lines (limit %u)", LINT_FORBID_MAX);
    r->forbid[r->n_forbid++] = arg;
    return true;
}

static bool parse_line(LintRules *r, LintError *e, int line, char *s)
{
    bool allow = strncmp(s, "allow ", 6) == 0;
    if (!allow && strncmp(s, "forbid ", 7) != 0) return fail(e, line, "expected 'allow PATH' or 'forbid TEXT'");
    char *arg = s + (allow ? 6 : 7);
    if (arg[0] == '\0') return fail(e, line, "%s needs an argument", allow ? "allow" : "forbid");
    return allow ? add_allow(r, e, line, arg) : add_forbid(r, e, line, arg);
}

static bool parse_in_place(LintRules *r, size_t len, LintError *e)
{
    r->n_allow = 0;
    r->n_forbid = 0;
    r->buf[len] = '\0';
    char *p = r->buf;
    char *end = r->buf + len;
    int line = 0;
    while (p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        line++;
        if (nl == nullptr) return fail(e, line, "line has no newline");
        size_t n = (size_t)(nl - p);
        if (n > LINT_RULES_LINE_MAX) return fail(e, line, "line is %zu bytes, limit is %zu", n, LINT_RULES_LINE_MAX);
        if (memchr(p, '\0', n) != nullptr) return fail(e, line, "NUL byte in line");
        *nl = '\0';
        char *s = p;
        p = nl + 1;
        if (!parse_line(r, e, line, s)) return false;
    }
    return true;
}

static bool finish(LintRules *r, bool ok)
{
    if (!ok) {
        r->n_allow = 0;
        r->n_forbid = 0;
    }
    return ok;
}

bool lint_rules_parse(LintRules *r, const char *data, size_t len, LintError *e)
{
    r->n_allow = 0;
    r->n_forbid = 0;
    if (len > LINT_RULES_FILE_MAX) return fail(e, 0, "file is %zu bytes, limit is %zu", len, LINT_RULES_FILE_MAX);
    memcpy(r->buf, data, len);
    return finish(r, parse_in_place(r, len, e));
}

bool lint_rules_load(LintRules *r, const char *path, LintError *e)
{
    r->n_allow = 0;
    r->n_forbid = 0;
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0 && errno == ENOENT) return true;
    if (fd < 0) return fail_io(e, "open", errno);
    size_t len = 0;
    ssize_t n = 1;
    while (len <= LINT_RULES_FILE_MAX && n > 0) {
        n = sys_read(fd, r->buf + len, LINT_RULES_FILE_MAX + 1 - len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        len += n > 0 ? (size_t)n : 0;
    }
    int err = errno;
    (void)sys_close(fd);
    if (n < 0) return fail_io(e, "read", err);
    if (len > LINT_RULES_FILE_MAX) return fail(e, 0, "file is over the limit of %zu bytes", LINT_RULES_FILE_MAX);
    return finish(r, parse_in_place(r, len, e));
}

bool lint_allowed(const LintRules *r, const char *path)
{
    for (uint32_t i = 0; i < r->n_allow; i++)
        if (strcmp(r->allow[i], path) == 0) return true;
    return false;
}