Skip to content

Commit 886a885

Browse files
committed
fix: bound response buffers, parse depth and glob matching
A pass over places where a bound was either miscalculated or missing. UI response builders (src/ui/http_server.c) mixed the clamping helper http_appendf with raw cursor indexing. Route the per-line separators and quotes through the helper too, so the cursor cannot leave the buffer once output saturates it, and terminate explicitly afterwards — the helper pins the cursor and then writes nothing, which would otherwise leave the "%s" reply with no terminator in range. The log buffer was budgeted at LOG_LINE_MAX + 10 per line while JSON escaping can double every byte, so size it for the escaped worst case. Job status entries now escape their path and error fields, which were interpolated raw. Cypher (src/cypher/cypher.c): the WHERE grammar descends once per nested '(' and once per NOT, so parse depth followed the query text rather than anything bounded. Track depth on parser_t and refuse past 256 levels with a parse error. Bounding parse depth also bounds the resulting tree, so the recursive evaluator inherits the limit. Gitignore (src/discover/gitignore.c): '**' retries the remainder at every position and consecutive groups multiply, so match cost is exponential in the number of groups. Thread a step budget through the matcher and give up past 20000 steps, reporting no-match so a pathological pattern fails to ignore rather than ignoring the wrong files. glob_match keeps its name so recursion_whitelist.h still describes the functions that recurse; the new non-recursive wrapper that seeds the budget is glob_match_bounded. Call extraction (internal/cbm/extract_calls.c): extract_fp_callee recursed once per applied argument, so stack use followed the parse-tree depth of the indexed file. Rewritten as a left-spine loop. Reassigning node/nk before continuing leaves the fall-through cases where the recursive form left them, so behaviour is unchanged and the extraction suite is untouched. CALLS props (src/pipeline/pass_calls.c): `cap - pos - PAIR_LEN` wraps once pos reaches cap - PAIR_LEN and stops bounding the copy below. Guard additively, matching the closing write in the same function. Shell-bound paths (src/foundation/str_util.*): the three git shell-out sites each wrap a repo path in cmd.exe-compatible double quotes, where %VAR%, !VAR! and ^ remain active. Two carried private copies of the check that rejects those three on Windows and the third used the bare validator. Promote the stricter form to cbm_validate_shell_path_arg and route all three through it, so the copies cannot drift apart again. Tests cover the buffer bounds, the parse-depth refusal, matcher termination and the validator. The bounds tests run in a forked child so a violation surfaces as a signal instead of silently. Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent 4bbe098 commit 886a885

14 files changed

Lines changed: 475 additions & 69 deletions

File tree

‎internal/cbm/extract_calls.c‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -326,26 +326,36 @@ static char *extract_callee_from_fields(CBMArena *a, TSNode node, const char *so
326326
}
327327

328328
// Haskell/OCaml: extract callee from apply/infix nodes.
329+
/* Apply-style node kinds whose function head can nest another application. */
330+
static bool fp_is_apply_kind(const char *kind) {
331+
return strcmp(kind, "apply") == 0 || strcmp(kind, "application_expression") == 0 ||
332+
strcmp(kind, "exp_apply") == 0;
333+
}
334+
329335
static char *extract_fp_callee(CBMArena *a, TSNode node, const char *source, const char *nk) {
330-
if (strcmp(nk, "apply") == 0 || strcmp(nk, "application_expression") == 0 ||
331-
strcmp(nk, "exp_apply") == 0) {
332-
if (ts_node_child_count(node) > 0) {
333-
TSNode callee = ts_node_child(node, 0);
334-
const char *ck = ts_node_type(callee);
335-
if (strcmp(ck, "identifier") == 0 || strcmp(ck, "variable") == 0 ||
336-
strcmp(ck, "constructor") == 0 || strcmp(ck, "value_path") == 0 ||
337-
/* PureScript: exp_apply's function head is an `exp_name` whose
338-
* text is the (possibly qualified) function name. */
339-
strcmp(ck, "exp_name") == 0) {
340-
return cbm_node_text(a, callee, source);
341-
}
342-
/* Curried application `f a b` nests exp_apply/apply — descend the
343-
* function head to recover the leftmost callee. */
344-
if (strcmp(ck, "exp_apply") == 0 || strcmp(ck, "apply") == 0 ||
345-
strcmp(ck, "application_expression") == 0) {
346-
return extract_fp_callee(a, callee, source, ck);
347-
}
336+
/* Curried application `f a b …` nests one apply node per argument on the
337+
* function head. Walk that left spine iteratively: recursing once per
338+
* application makes stack use follow the parse-tree depth of the indexed
339+
* file, and a long enough chain runs out. The other descendant finders in
340+
* this tree are already depth-bounded.
341+
*
342+
* Reassigning node/nk before continuing leaves the fall-through below
343+
* operating on the innermost apply node — where the recursive form left it. */
344+
while (fp_is_apply_kind(nk) && ts_node_child_count(node) > 0) {
345+
TSNode callee = ts_node_child(node, 0);
346+
const char *ck = ts_node_type(callee);
347+
if (strcmp(ck, "identifier") == 0 || strcmp(ck, "variable") == 0 ||
348+
strcmp(ck, "constructor") == 0 || strcmp(ck, "value_path") == 0 ||
349+
/* PureScript: exp_apply's function head is an `exp_name` whose
350+
* text is the (possibly qualified) function name. */
351+
strcmp(ck, "exp_name") == 0) {
352+
return cbm_node_text(a, callee, source);
353+
}
354+
if (!fp_is_apply_kind(ck)) {
355+
break;
348356
}
357+
node = callee;
358+
nk = ck;
349359
}
350360
if (strcmp(nk, "infix") == 0 || strcmp(nk, "infix_expression") == 0) {
351361
TSNode op = ts_node_child_by_field_name(node, TS_FIELD("operator"));

‎src/cypher/cypher.c‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,13 +432,36 @@ void cbm_lex_free(cbm_lex_result_t *r) {
432432
* PARSER
433433
* ══════════════════════════════════════════════════════════════════ */
434434

435+
/* The WHERE grammar descends once per nested '(' and once per NOT, so parse
436+
* depth follows the query text rather than anything bounded. A few tens of KB of
437+
* either exhausts the stack before any semantic limit applies. 256 is far past
438+
* any hand-written or generated query while leaving the stack untouched. */
439+
enum { CYPHER_MAX_PARSE_DEPTH = 256 };
440+
435441
typedef struct {
436442
const cbm_token_t *tokens;
437443
int count;
438444
int pos;
445+
int depth; /* current recursive-descent depth; see CYPHER_MAX_PARSE_DEPTH */
439446
char error[CBM_SZ_512];
440447
} parser_t;
441448

449+
/* Enter one level of recursive descent. Returns false when the cap is hit, in
450+
* which case the caller must return NULL without recursing. */
451+
static bool parse_depth_enter(parser_t *p) {
452+
if (p->depth >= CYPHER_MAX_PARSE_DEPTH) {
453+
snprintf(p->error, sizeof(p->error), "expression nested deeper than %d levels",
454+
CYPHER_MAX_PARSE_DEPTH);
455+
return false;
456+
}
457+
p->depth++;
458+
return true;
459+
}
460+
461+
static void parse_depth_leave(parser_t *p) {
462+
p->depth--;
463+
}
464+
442465
static const cbm_token_t *peek(parser_t *p) {
443466
if (p->pos >= p->count) {
444467
return &p->tokens[p->count - SKIP_ONE]; /* EOF */
@@ -1203,7 +1226,11 @@ static cbm_expr_t *parse_condition_expr(parser_t *p) {
12031226
/* Atom: ( expr ) | condition */
12041227
static cbm_expr_t *parse_atom_expr(parser_t *p) { // NOLINT(misc-no-recursion)
12051228
if (match(p, TOK_LPAREN)) {
1229+
if (!parse_depth_enter(p)) {
1230+
return NULL;
1231+
}
12061232
cbm_expr_t *e = parse_or_expr(p);
1233+
parse_depth_leave(p);
12071234
expect(p, TOK_RPAREN);
12081235
return e;
12091236
}
@@ -1213,7 +1240,11 @@ static cbm_expr_t *parse_atom_expr(parser_t *p) { // NOLINT(misc-no-recursion)
12131240
/* NOT: NOT atom | atom */
12141241
static cbm_expr_t *parse_not_expr(parser_t *p) { // NOLINT(misc-no-recursion)
12151242
if (match(p, TOK_NOT)) {
1243+
if (!parse_depth_enter(p)) {
1244+
return NULL;
1245+
}
12161246
cbm_expr_t *child = parse_not_expr(p);
1247+
parse_depth_leave(p);
12171248
return child ? expr_not(child) : NULL;
12181249
}
12191250
return parse_atom_expr(p);

‎src/discover/gitignore.c‎

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,31 @@ struct cbm_gitignore {
3939

4040
/* ── Pattern matching engine ─────────────────────────────────────── */
4141

42+
/* Backtracking budget. `**` retries the remainder at every position, and
43+
* consecutive literal + `**` groups multiply, so cost is exponential in the
44+
* number of groups. Patterns come from a committed .gitignore / .cbmignore and
45+
* every discovered path is matched against every pattern, so a small ignore file
46+
* can make discovery take unbounded time. Cap the match steps per
47+
* (pattern, path) pair.
48+
*
49+
* Exhausting the budget reports "no match", so a pathological pattern fails to
50+
* ignore rather than ignoring the wrong files: the file gets indexed, which is
51+
* the recoverable direction. The cap is far above any real pattern — ordinary
52+
* globs finish in tens of steps. */
53+
enum { GI_MATCH_MAX_STEPS = 20000 };
54+
4255
/* Forward declaration for recursive calls. */
43-
static bool glob_match(const char *pat, const char *str); // NOLINT(misc-no-recursion)
56+
static bool glob_match(const char *pat, const char *str,
57+
int *budget); // NOLINT(misc-no-recursion)
4458

4559
/* Match a ** (doublestar-slash) pattern: try rest at every / boundary. */
4660
static bool glob_match_doublestar_slash(const char *pat, // NOLINT(misc-no-recursion)
47-
const char *str) {
48-
if (glob_match(pat, str)) {
61+
const char *str, int *budget) {
62+
if (glob_match(pat, str, budget)) {
4963
return true;
5064
}
5165
for (const char *s = str; *s; s++) {
52-
if (*s == '/' && glob_match(pat, s + SKIP_ONE)) {
66+
if (*s == '/' && glob_match(pat, s + SKIP_ONE, budget)) {
5367
return true;
5468
}
5569
}
@@ -58,9 +72,9 @@ static bool glob_match_doublestar_slash(const char *pat, // NOLINT(misc-no-recur
5872

5973
/* Match a ** (doublestar) followed by non-slash: try at every position. */
6074
static bool glob_match_doublestar_any(const char *pat, // NOLINT(misc-no-recursion)
61-
const char *str) {
75+
const char *str, int *budget) {
6276
for (const char *s = str;; s++) {
63-
if (glob_match(pat, s)) {
77+
if (glob_match(pat, s, budget)) {
6478
return true;
6579
}
6680
if (!*s) {
@@ -70,9 +84,10 @@ static bool glob_match_doublestar_any(const char *pat, // NOLINT(misc-no-recursi
7084
}
7185

7286
/* Match a * (single star): match any sequence not containing /. */
73-
static bool glob_match_star(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
87+
static bool glob_match_star(const char *pat, const char *str,
88+
int *budget) { // NOLINT(misc-no-recursion)
7489
for (const char *s = str;; s++) {
75-
if (glob_match(pat, s)) {
90+
if (glob_match(pat, s, budget)) {
7691
return true;
7792
}
7893
if (!*s || *s == '/') {
@@ -119,24 +134,29 @@ static bool glob_match_charclass(const char *pat, char ch, const char **pat_out)
119134
* Handles: * (non-slash), ** (any path), ? (single non-slash), [class]
120135
*/
121136
/* Handle ** at current position. Returns match result. */
122-
static bool glob_match_doublestar(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
137+
static bool glob_match_doublestar(const char *pat, const char *str,
138+
int *budget) { // NOLINT(misc-no-recursion)
123139
if (pat[GI_CHAR_IDX2] == '/') {
124-
return glob_match_doublestar_slash(pat + GI_SKIP3, str);
140+
return glob_match_doublestar_slash(pat + GI_SKIP3, str, budget);
125141
}
126142
if (pat[GI_CHAR_IDX2] == '\0') {
127143
return true;
128144
}
129-
return glob_match_doublestar_any(pat + GI_CHAR_IDX2, str);
145+
return glob_match_doublestar_any(pat + GI_CHAR_IDX2, str, budget);
130146
}
131147

132-
static bool glob_match(const char *pat, const char *str) { // NOLINT(misc-no-recursion)
148+
static bool glob_match(const char *pat, const char *str,
149+
int *budget) { // NOLINT(misc-no-recursion)
150+
if (--*budget <= 0) {
151+
return false; /* budget exhausted — see GI_MATCH_MAX_STEPS */
152+
}
133153
while (*pat && *str) {
134154
if (pat[0] == '*' && pat[GI_CHAR_IDX1] == '*') {
135-
return glob_match_doublestar(pat, str);
155+
return glob_match_doublestar(pat, str, budget);
136156
}
137157

138158
if (*pat == '*') {
139-
return glob_match_star(pat + SKIP_ONE, str);
159+
return glob_match_star(pat + SKIP_ONE, str, budget);
140160
}
141161

142162
if (*pat == '?') {
@@ -171,6 +191,13 @@ static bool glob_match(const char *pat, const char *str) { // NOLINT(misc-no-rec
171191
return *pat == '\0' && *str == '\0';
172192
}
173193

194+
/* Match one pattern against one path with a fresh backtracking budget. Not
195+
* recursive itself — it seeds the budget and hands off to the engine. */
196+
static bool glob_match_bounded(const char *pat, const char *str) {
197+
int budget = GI_MATCH_MAX_STEPS;
198+
return glob_match(pat, str, &budget);
199+
}
200+
174201
/* ── Pattern parsing ─────────────────────────────────────────────── */
175202

176203
static void gi_add_pattern(cbm_gitignore_t *gi, const char *line, int len) {
@@ -320,7 +347,7 @@ cbm_gitignore_t *cbm_gitignore_load(const char *path) {
320347

321348
/* Match a non-rooted pattern against basename and path suffixes. */
322349
static bool match_unrooted(const char *pattern, const char *rel_path, const char *basename) {
323-
if (glob_match(pattern, basename)) {
350+
if (glob_match_bounded(pattern, basename)) {
324351
return true;
325352
}
326353
if (!strchr(rel_path, '/')) {
@@ -329,7 +356,7 @@ static bool match_unrooted(const char *pattern, const char *rel_path, const char
329356
/* Try matching at every / boundary */
330357
const char *s = rel_path;
331358
while (*s) {
332-
if (glob_match(pattern, s)) {
359+
if (glob_match_bounded(pattern, s)) {
333360
return true;
334361
}
335362
const char *next = strchr(s, '/');
@@ -359,7 +386,7 @@ int cbm_gitignore_match_result(const cbm_gitignore_t *gi, const char *rel_path,
359386
continue;
360387
}
361388

362-
bool this_match = p->rooted ? glob_match(p->pattern, rel_path)
389+
bool this_match = p->rooted ? glob_match_bounded(p->pattern, rel_path)
363390
: match_unrooted(p->pattern, rel_path, basename);
364391

365392
if (this_match) {

‎src/foundation/str_util.c‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,23 @@ bool cbm_validate_shell_arg(const char *s) {
271271
return true;
272272
}
273273

274+
bool cbm_validate_shell_path_arg(const char *path) {
275+
if (!cbm_validate_shell_arg(path)) {
276+
return false;
277+
}
278+
#ifdef _WIN32
279+
/* cmd.exe expands %VAR% and, with delayed expansion, !VAR! inside the
280+
* double quotes these commands use; ^ is its escape character. None of the
281+
* three can be neutralised by quoting, so reject them outright. */
282+
for (const char *p = path; *p; p++) {
283+
if (*p == '%' || *p == '!' || *p == '^') {
284+
return false;
285+
}
286+
}
287+
#endif
288+
return true;
289+
}
290+
274291
bool cbm_validate_project_name(const char *name) {
275292
if (!name || !*name)
276293
return false;

‎src/foundation/str_util.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ char **cbm_str_split(CBMArena *a, const char *s, char delim, int *out_count);
5757
* Returns true if safe, false if the string contains shell metacharacters. */
5858
bool cbm_validate_shell_arg(const char *s);
5959

60+
/* Validate a filesystem path that will be interpolated into a shell command.
61+
* Everything cbm_validate_shell_arg rejects, plus the cmd.exe expansion
62+
* metacharacters % ! ^ on Windows: a path reaching `git -C "%s"` through
63+
* cmd.exe would otherwise get %VAR% / delayed-!VAR! expansion applied to it.
64+
*
65+
* Use this — not cbm_validate_shell_arg — for every path that crosses into a
66+
* shell command, so the three git shell-out sites cannot drift apart again.
67+
* Returns true if safe. */
68+
bool cbm_validate_shell_path_arg(const char *path);
69+
6070
/* Validate a project name is safe for file path construction.
6171
* Allows: alphanumeric, dash, underscore, dot (but not leading dot or dot-dot).
6272
* Rejects: path separators (/ \), directory traversal (..), and control chars.

‎src/git/git_context.c‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,7 @@ static void trim_newlines(char *s) {
4040
}
4141

4242
static bool git_validate_repo_path(const char *repo_path) {
43-
if (!cbm_validate_shell_arg(repo_path)) {
44-
return false;
45-
}
46-
#ifdef _WIN32
47-
for (const char *p = repo_path; *p; p++) {
48-
if (*p == '%' || *p == '!' || *p == '^') {
49-
return false;
50-
}
51-
}
52-
#endif
53-
return true;
43+
return cbm_validate_shell_path_arg(repo_path);
5444
}
5545

5646
static int git_capture(const char *repo_path, const char *git_args, char **out) {

‎src/pipeline/artifact.c‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -221,17 +221,7 @@ static int write_file_atomic(const char *path, const char *data, size_t len,
221221
* % ! ^. Callers then use DOUBLE quotes (honored by both POSIX sh and cmd.exe, unlike
222222
* single quotes on cmd.exe), so a repo path may legitimately contain spaces. */
223223
bool cbm_artifact_repo_path_is_shell_safe(const char *repo_path) {
224-
if (!cbm_validate_shell_arg(repo_path)) {
225-
return false;
226-
}
227-
#ifdef _WIN32
228-
for (const char *p = repo_path; *p; p++) {
229-
if (*p == '%' || *p == '!' || *p == '^') {
230-
return false;
231-
}
232-
}
233-
#endif
234-
return true;
224+
return cbm_validate_shell_path_arg(repo_path);
235225
}
236226

237227
/* Get current git HEAD hash. buf must be >= CBM_SZ_64. Returns false on error. */

‎src/pipeline/pass_calls.c‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,11 @@ static void calls_append_args(char *props, size_t cap, const CBMCall *call) {
303303
n = snprintf(one, sizeof(one), "%s{\"i\":%d,\"e\":\"%s\"}", i > 0 ? "," : "", a->index,
304304
esc_e);
305305
}
306-
if (n <= 0 || (size_t)n >= cap - pos - PAIR_LEN) {
306+
/* Add rather than subtract: pos is unsigned, so `cap - pos - PAIR_LEN`
307+
* wraps once pos reaches cap - PAIR_LEN and stops bounding the memcpy
308+
* below. The closing write at the end of this function already guards
309+
* additively; match it. */
310+
if (n <= 0 || pos + (size_t)n + PAIR_LEN >= cap) {
307311
break; /* not enough room — close the array with what fits */
308312
}
309313
memcpy(props + pos, one, (size_t)n);

‎src/pipeline/pass_githistory.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ static int parse_git_log(const char *repo_path, commit_t **out, int *out_count)
111111
*out = NULL;
112112
*out_count = 0;
113113

114-
if (!cbm_validate_shell_arg(repo_path)) {
114+
if (!cbm_validate_shell_path_arg(repo_path)) {
115115
return CBM_NOT_FOUND;
116116
}
117117

0 commit comments

Comments
 (0)