diff --git a/AGENTS.md b/AGENTS.md index b898044..43944bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,11 +17,12 @@ It is born once and never replaced by a fresh context. ## Status Implemented (2026-11-21). The binary builds against the sibling splinter -checkout and `make check` passes six offline suites: config/birth/stuck/state/ +checkout and `make check` passes seven offline suites: config/birth/stuck/state/ HTTP/MCP, a real scripted engine turn, the dashboard and MCP sockets, Landlock -plus seccomp, the engine running a turn with both layers active, and -`kdaemon_run` itself (temp state/workspace, script transport, one birth -impulse, no provider). The root-only phase (debootstrap, mount namespace, +plus seccomp, the engine running a turn with both layers active, `kdaemon_run` +itself (temp state/workspace, script transport, one birth impulse, no +provider), and a turn cancelled by `max_turn_seconds`. The root-only phase +(debootstrap, mount namespace, chroot, uid drop) is exercised by `sudo tests/root-integration.sh`, which runs `--prepare-rootfs` and `--sandbox-test` but never the autonomous daemon. @@ -46,7 +47,7 @@ Do not start the daemon as part of a code change. Verification is `make check`, src/journal.c journal_search over the full session log src/httpd.c dashboard, HTTP API, MCP server (TCP and POST /mcp) docs/DESIGN.md prior art and the mapping to this loop - tests/ six offline test binaries + root-integration.sh + tests/ seven offline test binaries + root-integration.sh `libkrang.a` is every source except `main.c`; the binary and the tests link it. The Makefile uses `SPLINTER ?= ../splinter`; the checkout is a sibling, not @@ -56,20 +57,21 @@ The Makefile uses `SPLINTER ?= ../splinter`; the checkout is a sibling, not make -C ../splinter # once, or after splinter changes make # krang + libkrang.a - make check # six offline suites + make check # seven offline suites make check-asan # the same under ASAN/UBSAN ./krang --self-test # one scripted turn - ./krang --check --config krang.conf.example + ./krang --check --config krang.conf.example # config + plan + turn ./krang --plan --config krang.conf.example sudo make check-root # debootstrap + chroot + drop; root/net `make check` proves: config parsing and inline comments; the birth prompt; the stuck ladder; birth/newborn detection and goal persistence; the snapshot JSON; HTTP routing; MCP tools/list and tools/call; the dashboard and MCP listeners on -real sockets; Landlock denying a write outside the allowed set; seccomp denying -`mount(2)` while fork/execve/network still work; a scripted engine turn with -both layers active; and `kdaemon_run` with one birth impulse and a clean stop. -It needs no root, no network and no model. +real sockets; HTTP Host/Origin refusal and token enforcement; Landlock denying +a write outside the allowed set; seccomp denying `mount(2)` while +fork/execve/network still work; a scripted engine turn with both layers active; +`kdaemon_run` with one birth impulse and a clean stop; and a turn cancelled by +`max_turn_seconds`. It needs no root, no network and no model. `tests/root-integration.sh` is the root-only proof: it runs `krang --prepare-rootfs` (debootstrap, network), then `krang --sandbox-test` @@ -365,6 +367,14 @@ both logs. Neither starts the autonomous daemon with a provider. - The dashboard/MCP have no TLS. Use loopback, an SSH tunnel, or a terminator. - `tests/root-integration.sh` is manual: it needs root and network and leaves the offline `make check` unchanged. Run it after touching the root phase. +- The impulse ledger, the stuck counter and the token/cost totals live in + memory. The event log keeps the history, but replay at startup is not + implemented; after a restart the dashboard's totals start again at zero. +- `ksession_meta()` counts the whole session file on every turn (via + `sp_session_count`). That is linear per turn and quadratic over a long life; + an incremental offset-based count is the fix. +- HTTP chat (`POST /api/say`) blocks one connection thread until the turn + finishes or `say_timeout` expires; MCP clients are better for long turns. ## Open decisions diff --git a/Makefile b/Makefile index d21a793..bd00853 100644 --- a/Makefile +++ b/Makefile @@ -25,7 +25,8 @@ SRC = src/util.c src/config.c src/log.c src/session.c src/birth.c \ src/sandbox.c src/httpd.c OBJ = $(SRC:.c=.o) TESTS = tests/test_krang tests/test_engine tests/test_server \ - tests/test_sandbox tests/test_sandbox_engine tests/test_daemon + tests/test_sandbox tests/test_sandbox_engine tests/test_daemon \ + tests/test_timeout all: $(BIN) @@ -67,6 +68,10 @@ tests/test_daemon: tests/test_daemon.c $(LIB) $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_daemon.c $(LIB) \ $(LIBS) $(TEST_RPATH) +tests/test_timeout: tests/test_timeout.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_timeout.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + check: $(TESTS) @echo "== tests/test_krang"; ./tests/test_krang @echo "== tests/test_engine"; ./tests/test_engine @@ -74,15 +79,19 @@ check: $(TESTS) @echo "== tests/test_sandbox"; ./tests/test_sandbox @echo "== tests/test_sandbox_engine"; ./tests/test_sandbox_engine @echo "== tests/test_daemon"; ./tests/test_daemon + @echo "== tests/test_timeout"; ./tests/test_timeout @echo "all tests passed" check-root: $(BIN) tests/root-integration.sh +# The sanitizer build reuses the same object paths, so it starts and ends with +# a clean tree; a plain `make` after it must not link instrumented objects. check-asan: $(MAKE) clean $(MAKE) CFLAGS="$(CFLAGS) -g -fsanitize=address,undefined" \ LDFLAGS="-fsanitize=address,undefined" check + $(MAKE) clean install: $(BIN) install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib \ diff --git a/README.md b/README.md index 2d5a3ea..348db82 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,12 @@ If a token is set in the config, loopback is not required and every request needs it (`Authorization: Bearer`, `?token=`, or the MCP `AUTH ` line). Without a token krang refuses to bind to a non-loopback address. +A loopback dashboard without a token is still a local service, so the HTTP +surface checks the names a browser sends: a request whose `Host` is not a +loopback name is refused (DNS rebinding), and an `Origin` that does not match +the `Host` is refused (cross-site requests). There is no CORS grant; the +dashboard is same-origin. + ## The experiment log - `state/sessions/krang.jsonl` is the conversation and the model's memory. @@ -91,17 +97,18 @@ Without a token krang refuses to bind to a non-loopback address. ```sh make check make check-asan -./krang --check --config krang.conf.example # config + one scripted turn +./krang --check --config krang.conf.example # config + plan + scripted turn ./krang --self-test # one scripted turn, no network sudo tests/root-integration.sh # debootstrap + chroot + drop ``` -`make check` covers config parsing, the birth prompt, stuck detection, the -snapshot/HTTP/MCP surfaces, a real scripted engine turn, the engine under -Landlock + seccomp, and `kdaemon_run` itself (one birth impulse on the script -transport, then a clean stop). The sandbox tests prove Landlock denies a write -outside the allowed set and seccomp denies `mount(2)` while -fork/execve/network still work. +`make check` covers config parsing and path guards, the birth prompt, stuck +detection, the snapshot/HTTP/MCP surfaces (including the Host/Origin refusal +and token check), a real scripted engine turn, the engine under Landlock + +seccomp, `kdaemon_run` itself (one birth impulse on the script transport, then +a clean stop), and a turn cancelled by `max_turn_seconds`. The sandbox tests +prove Landlock denies a write outside the allowed set and seccomp denies +`mount(2)` while fork/execve/network still work. `tests/root-integration.sh` is the root-only proof: it prepares a real rootfs with debootstrap, enters it with `--sandbox-test`, loads the clock plugin from diff --git a/krang.conf.example b/krang.conf.example index c66e672..0a91f82 100644 --- a/krang.conf.example +++ b/krang.conf.example @@ -41,6 +41,7 @@ max_bytes = 0 # 0: splinter's default request budget compact_threshold = 60000 # tokens; set in conf, not base (engine.c) compact_target = 20000 max_impulses_per_hour = 30 +max_turn_seconds = 1800 # wall clock per turn; 0 = no cap max_cost = 0 # USD; 0 = no cost cap # Loopback by default. A non-loopback bind without a token is refused. diff --git a/src/birth.c b/src/birth.c index 847d090..2e30635 100644 --- a/src/birth.c +++ b/src/birth.c @@ -162,7 +162,7 @@ k_selfcheck_prompt(struct krang *k, struct sp_buf *out) snprintf(err, sizeof(err), "%s", k->last_error); snprintf(tool, sizeof(tool), "%s", k->st.last_tool); snprintf(result, sizeof(result), "%s", k->st.last_tool_result); - level = k->stuck.level; + level = k->st.stuck_level; pthread_mutex_unlock(&k->lock); (void)sp_buf_puts(out, "[self-check]\n"); diff --git a/src/config.c b/src/config.c index 2e02800..fd35f28 100644 --- a/src/config.c +++ b/src/config.c @@ -45,6 +45,7 @@ kconfig_defaults(struct kconfig *c) c->compact_threshold = 60000; c->compact_target = 20000; c->max_impulses_per_hour = 60; + c->max_turn_seconds = 1800; c->max_cost = 0.0; copy_str(c->dashboard_host, sizeof(c->dashboard_host), "127.0.0.1"); c->dashboard_port = 8096; @@ -63,7 +64,7 @@ parse_size(const char *s, size_t *out) char *end = NULL; unsigned long long v; - if (s == NULL || *s == '\0') + if (s == NULL || *s == '\0' || s[0] == '-') return -1; errno = 0; v = strtoull(s, &end, 10); @@ -95,7 +96,7 @@ parse_double(const char *s, double *out) char *end = NULL; double v; - if (s == NULL || *s == '\0') + if (s == NULL || *s == '\0' || s[0] == '-') return -1; errno = 0; v = strtod(s, &end); @@ -111,6 +112,31 @@ looks_absolute(const char *p) return p != NULL && p[0] == '/'; } +static int +path_has_dotdot(const char *p) +{ + const char *q = p; + + while ((q = strstr(q, "..")) != NULL) { + if ((q == p || q[-1] == '/') && + (q[2] == '/' || q[2] == '\0')) + return 1; + q += 2; + } + return 0; +} + +/* 1 when a is b or lies beneath b; both are absolute and clean */ +static int +path_within(const char *a, const char *b) +{ + size_t n = strlen(b); + + if (!strcmp(b, "/")) + return 1; + return strncmp(a, b, n) == 0 && (a[n] == '/' || a[n] == '\0'); +} + static int apply_user(struct kconfig *c, const char *val) { @@ -200,6 +226,10 @@ set_key(struct kconfig *c, const char *key, const char *val, int line, if (parse_int(val, &c->max_impulses_per_hour) != 0 || c->max_impulses_per_hour < 1) goto bad; + } else if (!strcmp(key, "max_turn_seconds")) { + if (parse_int(val, &c->max_turn_seconds) != 0 || + c->max_turn_seconds < 0) + goto bad; } else if (!strcmp(key, "max_cost")) { if (parse_double(val, &c->max_cost) != 0 || c->max_cost < 0) goto bad; @@ -302,6 +332,34 @@ kconfig_load(struct kconfig *c, const char *path, char *err, size_t errlen) "state_dir, workspace and rootfs must be absolute paths"); return -1; } + if (path_has_dotdot(c->state_dir) || path_has_dotdot(c->workspace) || + path_has_dotdot(c->rootfs)) { + snprintf(err, errlen, + "state_dir, workspace and rootfs may not contain '..'"); + return -1; + } + /* + * The root phase strips setuid bits and bind-mounts over these paths. + * "/" would do that to the live host, and a state or workspace inside + * the disposable rootfs would be deleted with it. + */ + if (!strcmp(c->rootfs, "/") || !strcmp(c->state_dir, "/") || + !strcmp(c->workspace, "/")) { + snprintf(err, errlen, + "rootfs, state_dir and workspace must not be /"); + return -1; + } + if (!strcmp(c->state_dir, c->workspace) || + path_within(c->rootfs, c->state_dir) || + path_within(c->rootfs, c->workspace) || + path_within(c->state_dir, c->rootfs) || + path_within(c->workspace, c->rootfs) || + path_within(c->state_dir, c->workspace) || + path_within(c->workspace, c->state_dir)) { + snprintf(err, errlen, + "rootfs, state_dir and workspace must be separate trees"); + return -1; + } if (c->sandbox_uid == 0 || c->sandbox_gid == 0) { snprintf(err, errlen, "refusing to drop to uid/gid 0"); return -1; @@ -416,6 +474,8 @@ kconfig_json(const struct kconfig *c, struct sp_buf *out, int redact) (void)sp_buf_puts(out, ","); json_number(out, "max_impulses_per_hour", c->max_impulses_per_hour); + (void)sp_buf_puts(out, ","); + json_number(out, "max_turn_seconds", c->max_turn_seconds); (void)sp_buf_printf(out, ",\"max_cost\":%.6f", c->max_cost); (void)sp_buf_puts(out, ","); json_string(out, "dashboard_host", c->dashboard_host); diff --git a/src/daemon.c b/src/daemon.c index de0a249..0dcdc85 100644 --- a/src/daemon.c +++ b/src/daemon.c @@ -120,7 +120,8 @@ session_refresh(struct krang *k) static void record_impulse(struct krang *k, const char *cause, int rc, - unsigned long steps, unsigned long calls, const char *answer) + unsigned long steps, unsigned long calls, unsigned long tokens_in, + unsigned long tokens_out, double cost, const char *answer) { struct kimpulse *imp; unsigned long id; @@ -135,9 +136,9 @@ record_impulse(struct krang *k, const char *cause, int rc, imp->rc = rc; imp->steps = steps; imp->tool_calls = calls; - imp->tokens_in = k->st.tokens_in; - imp->tokens_out = k->st.tokens_out; - imp->cost = k->st.cost; + imp->tokens_in = tokens_in; + imp->tokens_out = tokens_out; + imp->cost = cost; copy_trunc(imp->answer, sizeof(imp->answer), answer, sizeof(imp->answer) - 1); pthread_mutex_unlock(&k->lock); @@ -322,15 +323,24 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, struct kchat *chat) { struct sp_event ev; - int rc = -1, saw_end = 0, idle_guard = 0; + int rc = -1, saw_end = 0, idle_guard = 0, timed_out = 0; unsigned long steps = 0, calls = 0; + unsigned long tin0, tout0, d_in, d_out; + double cost0, d_cost; + long started; int mutating = 0; char answer[KRANG_TEXT] = "", error[KRANG_ERR] = ""; - char num[64], tok[32], cost[64]; + char num[64], tok[32], tout[32], cost[64]; int is_external = chat != NULL; if (k == NULL || k->eng == NULL || prompt == NULL) return -1; + pthread_mutex_lock(&k->lock); + tin0 = k->st.tokens_in; + tout0 = k->st.tokens_out; + cost0 = k->st.cost; + pthread_mutex_unlock(&k->lock); + started = k_now(); if (sp_engine_submit(k->eng, prompt) != 0) { klog_emit(&k->log, "submit_failed", "cause", cause, NULL); if (chat != NULL) @@ -368,6 +378,17 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, k->stop = 1; (void)sp_engine_cancel(k->eng); } + if (!timed_out && k->cfg.max_turn_seconds > 0 && + k_now() - started >= k->cfg.max_turn_seconds) { + char sec[32]; + + timed_out = 1; + snprintf(sec, sizeof(sec), "%d", + k->cfg.max_turn_seconds); + klog_emit(&k->log, "turn_timeout", "seconds", sec, + NULL); + (void)sp_engine_cancel(k->eng); + } if (!got) { k_sleep_ms(10); if (!sp_engine_busy(k->eng) && ++idle_guard > 200) @@ -378,7 +399,28 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, kstate_sync(k); session_refresh(k); + if (timed_out) { + char engine_err[KRANG_ERR]; + + /* an answer produced after the cancel is not an answer */ + answer[0] = '\0'; + snprintf(engine_err, sizeof(engine_err), "%s", error); + if (engine_err[0] != '\0') + snprintf(error, sizeof(error), + "turn exceeded max_turn_seconds (%d): %.200s", + k->cfg.max_turn_seconds, engine_err); + else + snprintf(error, sizeof(error), + "turn exceeded max_turn_seconds (%d)", + k->cfg.max_turn_seconds); + if (rc == 0) + rc = -1; + } + pthread_mutex_lock(&k->lock); + d_in = k->st.tokens_in >= tin0 ? k->st.tokens_in - tin0 : 0; + d_out = k->st.tokens_out >= tout0 ? k->st.tokens_out - tout0 : 0; + d_cost = k->st.cost >= cost0 ? k->st.cost - cost0 : 0.0; k->st.turns++; k->st.last_turn_rc = rc; if (answer[0] != '\0') @@ -407,6 +449,10 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, k->turn_failures = 0; } kstuck_turn(&k->stuck, rc, calls, mutating); + pthread_mutex_lock(&k->lock); + k->st.stuck_level = k->stuck.level; + k->st.stuck_attempts = k->stuck.attempts; + pthread_mutex_unlock(&k->lock); if (answer[0] != '\0' && strstr(answer, "GOAL_COMPLETE") != NULL) { struct sp_buf e; @@ -425,21 +471,22 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, sp_buf_free(&e); } - pthread_mutex_lock(&k->lock); - snprintf(tok, sizeof(tok), "%lu", k->st.tokens_in); + snprintf(tok, sizeof(tok), "%lu", d_in); + snprintf(tout, sizeof(tout), "%lu", d_out); snprintf(num, sizeof(num), "%d", rc); - snprintf(cost, sizeof(cost), "%.6f", k->st.cost); - pthread_mutex_unlock(&k->lock); + snprintf(cost, sizeof(cost), "%.6f", d_cost); { char sk[32], sc[32]; snprintf(sk, sizeof(sk), "%lu", steps); snprintf(sc, sizeof(sc), "%lu", calls); klog_emit(&k->log, "turn_end", "rc", num, "steps", sk, - "calls", sc, "tokens_in", tok, "cost", cost, + "calls", sc, "tokens_in", tok, "tokens_out", tout, + "cost", cost, "cause", cause != NULL ? cause : "timer", "answer", answer, "error", error, NULL); } - record_impulse(k, cause, rc, steps, calls, answer); + record_impulse(k, cause, rc, steps, calls, d_in, d_out, d_cost, + answer); if (chat != NULL) { const char *out = rc == 0 ? answer : error; @@ -466,7 +513,7 @@ schedule_next(struct krang *k, int failed) k->next_at = k_now() + delay; pthread_mutex_lock(&k->lock); k->st.next_impulse_at = k->next_at; - if (!failed && k->stuck.level == 0) + if (!failed && k->st.stuck_level == 0) snprintf(k->st.state, sizeof(k->st.state), "sleeping"); pthread_mutex_unlock(&k->lock); } @@ -658,6 +705,13 @@ kdaemon_run(struct krang *k) kstate_sync(k); chat = kchat_take(k); if (chat != NULL) { + if (rate_limit(k, now)) { + kchat_complete(k, chat->id, + "rate limited: the hourly impulse budget " + "is exhausted; try again later", -1); + continue; + } + k->hour_count++; set_state(k, "thinking"); (void)krun_turn(k, chat->text, "chat", chat); schedule_next(k, 0); @@ -681,6 +735,12 @@ kdaemon_run(struct krang *k) if (rate_limit(k, now)) continue; level = kstuck_should_check(&k->stuck, now); + if (level > 0) { + pthread_mutex_lock(&k->lock); + k->st.stuck_level = k->stuck.level; + k->st.stuck_attempts = k->stuck.attempts; + pthread_mutex_unlock(&k->lock); + } sp_buf_init(&prompt); if (level >= 1) { k_selfcheck_prompt(k, &prompt); diff --git a/src/httpd.c b/src/httpd.c index f0c1e99..5bed294 100644 --- a/src/httpd.c +++ b/src/httpd.c @@ -11,6 +11,7 @@ */ #define _GNU_SOURCE #include +#include #include #include #include @@ -21,6 +22,7 @@ #include #include #include +#include #include #include @@ -35,6 +37,8 @@ struct http_req { char method[16]; char path[1024]; char query[1024]; + char host[256]; + char origin[512]; char token[512]; char *body; size_t body_len; @@ -78,6 +82,96 @@ token_ok(struct krang *k, const struct http_req *r) return 0; } +/* + * A loopback dashboard without a token is reachable by any web page the user + * visits: CORS does not stop the request from being sent, and a DNS-rebinding + * page reaches 127.0.0.1 under its own name. The defence is to look at the + * names the browser already sends. With a token configured the token is the + * gate and these checks would only break legitimate clients. + */ +static void +header_value(const char *raw, const char *hdr_end, const char *name, + char *out, size_t cap) +{ + char pattern[64]; + const char *p, *v, *e; + size_t n; + + out[0] = '\0'; + snprintf(pattern, sizeof(pattern), "\r\n%s:", name); + p = strcasestr(raw, pattern); + if (p == NULL || p >= hdr_end) + return; + v = p + strlen(pattern); + while (*v == ' ' || *v == '\t') + v++; + e = strstr(v, "\r\n"); + if (e == NULL || e > hdr_end) + e = hdr_end; + n = (size_t)(e - v); + if (n >= cap) + n = cap - 1; + memcpy(out, v, n); + out[n] = '\0'; +} + +static int +host_is_loopback(const char *host) +{ + char buf[256]; + char *colon; + + if (host == NULL || *host == '\0') + return 1; /* HTTP/1.0 client: no name to rebind */ + snprintf(buf, sizeof(buf), "%s", host); + if (buf[0] == '[') { + char *close = strchr(buf, ']'); + + if (close == NULL) + return 0; + close[1] = '\0'; + } else { + colon = strchr(buf, ':'); + if (colon != NULL) + *colon = '\0'; + } + if (!strcasecmp(buf, "localhost")) + return 1; + if (!strcmp(buf, "::1") || !strcmp(buf, "[::1]")) + return 1; + if (!strncmp(buf, "127.", 4)) { + const char *p; + + for (p = buf; *p != '\0'; p++) + if (!isdigit((unsigned char)*p) && *p != '.') + return 0; /* 127.evil.example */ + return 1; + } + return 0; +} + +static int +origin_matches_host(const struct http_req *r) +{ + const char *p, *end; + char origin_host[256]; + size_t n; + + if (r->origin[0] == '\0') + return 1; /* not a browser request */ + p = strstr(r->origin, "://"); + if (p == NULL) + return 0; + p += 3; + end = strchr(p, '/'); + n = end != NULL ? (size_t)(end - p) : strlen(p); + if (n == 0 || n >= sizeof(origin_host)) + return 0; + memcpy(origin_host, p, n); + origin_host[n] = '\0'; + return strcasecmp(origin_host, r->host) == 0; +} + static const char * query_value(const char *query, const char *key, char *out, size_t cap) { @@ -156,8 +250,7 @@ send_res(int fd, struct http_res *r) "Content-Length: %zu\r\n" "Cache-Control: no-store\r\n" "Connection: close\r\n" - "Access-Control-Allow-Origin: *\r\n" - "Access-Control-Allow-Headers: Authorization, Content-Type\r\n" + "X-Content-Type-Options: nosniff\r\n" "%s" "\r\n", r->code, r->reason, r->type, r->body.len, r->extra); @@ -292,6 +385,8 @@ parse_request(const char *raw, size_t len, struct http_req *r) if (r->token[0] == '\0') (void)query_value(r->query, "token", r->token, sizeof(r->token)); + header_value(raw, hdr_end, "Host", r->host, sizeof(r->host)); + header_value(raw, hdr_end, "Origin", r->origin, sizeof(r->origin)); return 0; } @@ -630,15 +725,22 @@ static void route(struct krang *k, struct http_req *q, struct http_res *r) { res_init(r); - if (!strcmp(q->method, "OPTIONS")) { - r->code = 204; - r->reason = "No Content"; + if ((k->cfg.token[0] == '\0' && !host_is_loopback(q->host)) || + !origin_matches_host(q)) { + res_json_error(r, 403, "Forbidden", + "unexpected Host or Origin header"); return; } if (!token_ok(k, q) && strcmp(q->path, "/healthz") != 0) { res_json_error(r, 401, "Unauthorized", "a token is required"); return; } + if (!strcmp(q->method, "OPTIONS")) { + /* no CORS grant: a preflight from another origin must fail */ + r->code = 204; + r->reason = "No Content"; + return; + } if (!strcmp(q->method, "GET") && (!strcmp(q->path, "/") || !strcmp(q->path, "/index.html"))) { r->type = "text/html; charset=utf-8"; @@ -1169,8 +1271,14 @@ mcp_conn_thread(void *arg) { struct http_conn *c = arg; struct sp_buf line; + struct timeval tv; char buf[4096]; + /* an idle or silent client must not pin a thread forever */ + tv.tv_sec = 300; + tv.tv_usec = 0; + (void)setsockopt(c->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + (void)setsockopt(c->fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); if (mcp_auth(c->fd, c->k) != 0) { const char *no = "{\"error\":\"unauthorized\"}\n"; diff --git a/src/krang.h b/src/krang.h index f9c666b..9028342 100644 --- a/src/krang.h +++ b/src/krang.h @@ -71,6 +71,7 @@ struct kconfig { size_t compact_threshold; size_t compact_target; int max_impulses_per_hour; + int max_turn_seconds; /* wall clock per turn, 0 = off */ double max_cost; /* USD, 0 = off */ char dashboard_host[64]; @@ -129,6 +130,8 @@ struct kstats { unsigned long chat_pending; unsigned long stuck_events; unsigned long blocked_events; + int stuck_level; /* snapshot; k->stuck is daemon-private */ + int stuck_attempts; unsigned long goal_completes; unsigned long self_edits; diff --git a/src/log.c b/src/log.c index 91ef6d7..2f7cd05 100644 --- a/src/log.c +++ b/src/log.c @@ -132,7 +132,8 @@ klog_open(struct klog *l, const char *path, char *err, size_t errlen) memset(l, 0, sizeof(*l)); l->fd = -1; pthread_mutex_init(&l->lock, NULL); - l->fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0600); + l->fd = open(path, O_RDWR | O_CREAT | O_APPEND | O_NOFOLLOW | + O_CLOEXEC, 0600); if (l->fd < 0) { snprintf(err, errlen, "cannot open event log %s: %s", path, strerror(errno)); diff --git a/src/main.c b/src/main.c index 8e09f68..bcfd2d7 100644 --- a/src/main.c +++ b/src/main.c @@ -53,7 +53,7 @@ usage(FILE *out) } static int -self_test(const char *config_path) +self_test(const char *config_path, int require_config) { struct krang k; char tmpl[512], *dir, script[600], logpath[700], answer[KRANG_GOAL]; @@ -66,9 +66,16 @@ self_test(const char *config_path) pthread_cond_init(&k.cond, NULL); sp_buf_init(&k.err); kconfig_defaults(&k.cfg); - if (config_path != NULL) - (void)kconfig_load(&k.cfg, config_path, k.last_error, - sizeof(k.last_error)); + if (config_path != NULL && + kconfig_load(&k.cfg, config_path, k.last_error, + sizeof(k.last_error)) != 0) { + if (require_config) { + fprintf(stderr, "krang: %s\n", k.last_error); + goto out; + } + /* --self-test still proves the apparatus without a config */ + kconfig_defaults(&k.cfg); + } snprintf(tmpl, sizeof(tmpl), "/tmp/krang-selftest-XXXXXX"); dir = mkdtemp(tmpl); if (dir == NULL) { @@ -78,7 +85,6 @@ self_test(const char *config_path) snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); (void)mkdir(k.session_dir, 0700); - (void)mkdir(k.cfg.workspace, 0700); if (klog_open(&k.log, logpath, k.last_error, sizeof(k.last_error)) != 0) { fprintf(stderr, "krang: %s\n", k.last_error); @@ -234,8 +240,25 @@ main(int argc, char **argv) return 1; } } - if (do_self || do_check) - return self_test(config_path) == 0 ? 0 : 1; + if (do_check) { + struct krang ck; + struct sp_buf plan; + + memset(&ck, 0, sizeof(ck)); + if (kconfig_load(&ck.cfg, config_path, ck.last_error, + sizeof(ck.last_error)) != 0) { + fprintf(stderr, "krang: %s\n", ck.last_error); + return 1; + } + printf("config: ok (%s)\n", config_path); + sp_buf_init(&plan); + ksandbox_plan(&ck, &plan); + fputs(plan.p != NULL ? plan.p : "", stdout); + sp_buf_free(&plan); + return self_test(config_path, 1) == 0 ? 0 : 1; + } + if (do_self) + return self_test(config_path, 0) == 0 ? 0 : 1; memset(&k, 0, sizeof(k)); k.log.fd = -1; diff --git a/src/state.c b/src/state.c index 74a9063..176f09d 100644 --- a/src/state.c +++ b/src/state.c @@ -71,6 +71,8 @@ kstate_sync(struct krang *k) k->st.compactions = (unsigned long)es.compactions; k->st.busy = es.busy; k->st.waiting = es.waiting; + k->st.stuck_level = k->stuck.level; + k->st.stuck_attempts = k->stuck.attempts; pthread_mutex_unlock(&k->lock); } @@ -171,13 +173,13 @@ kstate_json(struct krang *k, struct sp_buf *out) (void)sp_buf_puts(out, "},"); (void)sp_buf_puts(out, "\"stuck\":{"); - jnum(out, "level", k->stuck.level); + jnum(out, "level", s.stuck_level); (void)sp_buf_puts(out, ","); jnum(out, "events", (long long)s.stuck_events); (void)sp_buf_puts(out, ","); jnum(out, "blocked", (long long)s.blocked_events); (void)sp_buf_puts(out, ","); - jnum(out, "attempts", k->stuck.attempts); + jnum(out, "attempts", s.stuck_attempts); (void)sp_buf_puts(out, "},"); (void)sp_buf_puts(out, "\"busy\":"); diff --git a/src/stuck.c b/src/stuck.c index d919674..617c6a8 100644 --- a/src/stuck.c +++ b/src/stuck.c @@ -84,10 +84,18 @@ kstuck_turn(struct kstuck *s, int rc, unsigned long calls, int mutating) } if (calls == 0 && !mutating) { s->no_progress_turns++; - } else { - s->no_progress_turns = 0; + return; } - if (mutating) + s->no_progress_turns = 0; + /* + * A turn that used tools and ends with no failure signal is progress: + * the episode is over, so the escalation ladder resets. Merely + * *calling* a mutating tool says nothing - `run false` is as mutating + * as `run make`, and resetting on the attempt is how a retry loop + * hides itself from the detector. + */ + if (s->consecutive_failures == 0 && s->same_error == 0 && + s->repeated_calls == 0) kstuck_reset(s); } diff --git a/tests/test_krang.c b/tests/test_krang.c index 36f4c0d..2faf7e9 100644 --- a/tests/test_krang.c +++ b/tests/test_krang.c @@ -76,6 +76,7 @@ test_config(void) fprintf(f, "impulse_seconds = 7\n"); fprintf(f, "max_steps = 9\n"); fprintf(f, "dashboard_port = 18096\n"); + fprintf(f, "max_turn_seconds = 42\n"); fprintf(f, "seccomp = no\n"); fclose(f); CHECK(kconfig_load(&c, path, err, sizeof(err)) == 0); @@ -83,10 +84,55 @@ test_config(void) CHECK(c.impulse_seconds == 7); CHECK(c.max_steps == 9); CHECK(c.dashboard_port == 18096); + CHECK(c.max_turn_seconds == 42); CHECK(c.seccomp == 0); unlink(path); } +static void +test_config_guards(void) +{ + struct kconfig c; + char path[] = "/tmp/krang-guard-XXXXXX"; + char err[512]; + int fd; + FILE *f; + + fd = mkstemp(path); + CHECK(fd >= 0); + if (fd < 0) + return; + f = fdopen(fd, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "rootfs = /\n"); + fclose(f); + CHECK(kconfig_load(&c, path, err, sizeof(err)) != 0); + CHECK(contains(err, "must not be /")); + + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "rootfs = /tmp/krang-guard-rootfs\n"); + fprintf(f, "state_dir = /tmp/krang-guard-rootfs/state\n"); + fprintf(f, "workspace = /tmp/krang-guard-workspace\n"); + fclose(f); + CHECK(kconfig_load(&c, path, err, sizeof(err)) != 0); + CHECK(contains(err, "separate trees")); + + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "rootfs = /tmp/../krang-guard-rootfs\n"); + fclose(f); + CHECK(kconfig_load(&c, path, err, sizeof(err)) != 0); + CHECK(contains(err, "..")); + unlink(path); +} + static void test_birth(void) { @@ -119,6 +165,23 @@ test_stuck(void) CHECK(s.same_error >= 2); CHECK(kstuck_level(&s) >= 1); CHECK(kstuck_should_check(&s, k_now()) >= 1); + CHECK(s.attempts == 1); + + /* a successful tool turn ends the episode and resets the ladder */ + kstuck_result(&s, "run", "[exit status 0]", 0); + kstuck_turn(&s, 0, 1, 0); + CHECK(s.attempts == 0); + CHECK(kstuck_level(&s) == 0); + + /* a turn that ends on a failing tool is not progress, even if the + * tool is classed as mutating (run/write/edit) */ + kstuck_result(&s, "run", "error: nope", 1); + kstuck_result(&s, "run", "error: nope", 1); + CHECK(kstuck_should_check(&s, k_now()) >= 1); + kstuck_result(&s, "run", "error: nope", 1); + kstuck_turn(&s, 0, 1, 1); + CHECK(s.attempts >= 1); + CHECK(kstuck_level(&s) >= 1); kstuck_reset(&s); CHECK(s.level == 0); CHECK(s.attempts == 0); @@ -223,21 +286,21 @@ test_http(void) init_krang(&k); sp_buf_init(&b); - khttp_handle_buffer(&k, "GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n", + khttp_handle_buffer(&k, "GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n", &b); CHECK(contains(b.p, "200 OK")); CHECK(contains(b.p, "\"ok\":true")); sp_buf_free(&b); sp_buf_init(&b); - khttp_handle_buffer(&k, "GET /api/state HTTP/1.1\r\nHost: x\r\n\r\n", + khttp_handle_buffer(&k, "GET /api/state HTTP/1.1\r\nHost: localhost\r\n\r\n", &b); CHECK(contains(b.p, "200 OK")); CHECK(contains(b.p, "\"state\":\"sleeping\"")); sp_buf_free(&b); sp_buf_init(&b); - khttp_handle_buffer(&k, "GET /nope HTTP/1.1\r\nHost: x\r\n\r\n", &b); + khttp_handle_buffer(&k, "GET /nope HTTP/1.1\r\nHost: localhost\r\n\r\n", &b); CHECK(contains(b.p, "404 Not Found")); sp_buf_free(&b); pthread_mutex_destroy(&k.lock); @@ -274,6 +337,7 @@ int main(void) { test_config(); + test_config_guards(); test_birth(); test_stuck(); test_birth_flow(); diff --git a/tests/test_server.c b/tests/test_server.c index 469aa92..5f7e80a 100644 --- a/tests/test_server.c +++ b/tests/test_server.c @@ -107,6 +107,48 @@ main(void) "GET /api/state HTTP/1.1\r\nHost: localhost\r\n\r\n"); CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); CHECK(strstr(out, "\"goal\":\"test the server\"") != NULL); + + /* a page reached through DNS rebinding carries a foreign Host */ + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: evil.example\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "403 Forbidden") != NULL); + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: 127.evil.example\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "403 Forbidden") != NULL); + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: 127.0.0.1:8096\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "200 OK") != NULL); + + /* cross-origin requests are refused, same-origin ones are not */ + snprintf(req, sizeof(req), + "POST /api/say HTTP/1.1\r\nHost: localhost\r\n" + "Origin: http://evil.example\r\n" + "Content-Type: application/json\r\nContent-Length: 12\r\n" + "\r\n{\"text\":\"x\"}"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "403 Forbidden") != NULL); + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: localhost\r\n" + "Origin: http://localhost\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "200 OK") != NULL); + + /* with a token, OPTIONS is not a free pass either */ + snprintf(k.cfg.token, sizeof(k.cfg.token), "s3cret"); + snprintf(req, sizeof(req), + "OPTIONS /api/state HTTP/1.1\r\nHost: localhost\r\n" + "Origin: http://localhost\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "401 Unauthorized") != NULL); + snprintf(req, sizeof(req), + "GET /api/state HTTP/1.1\r\nHost: localhost\r\n" + "Authorization: Bearer s3cret\r\n\r\n"); + CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0); + CHECK(strstr(out, "200 OK") != NULL); + k.cfg.token[0] = '\0'; khttp_stop(&k); CHECK(kmcp_start(&k, err, sizeof(err)) == 0); diff --git a/tests/test_timeout.c b/tests/test_timeout.c new file mode 100644 index 0000000..ec037bc --- /dev/null +++ b/tests/test_timeout.c @@ -0,0 +1,114 @@ +/* + * krang -- the wall-clock budget. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The script transport is instant except for a tool that really sleeps. With + * max_turn_seconds = 1 the turn must be cancelled and recorded as a timeout, + * not reported as a normal answer. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static int failures; + +#define CHECK(cond) do {\ + if (!(cond)) {\ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__,\ + #cond);\ + failures++;\ + }\ +} while (0) + +static int +contains(const char *hay, const char *needle) +{ + return hay != NULL && strstr(hay, needle) != NULL; +} + +int +main(void) +{ + struct krang k; + char tmpl[512], *dir, script[700], logpath[800], logbuf[65536]; + struct sp_buf sp; + FILE *f; + int rc; + + dir = mkdtemp(strcpy(tmpl, "/tmp/krang-timeout-XXXXXX")); + CHECK(dir != NULL); + if (dir == NULL) + return 1; + (void)setenv("HOME", dir, 1); + + memset(&k, 0, sizeof(k)); + k.log.fd = -1; + pthread_mutex_init(&k.lock, NULL); + pthread_cond_init(&k.cond, NULL); + sp_buf_init(&k.err); + kconfig_defaults(&k.cfg); + snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the wall clock"); + snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model"); + k.cfg.max_turn_seconds = 1; + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + (void)mkdir(k.session_dir, 0700); + snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); + CHECK(klog_open(&k.log, logpath, k.last_error, + sizeof(k.last_error)) == 0); + sp_buf_init(&sp); + k_system_prompt(&k, &sp); + snprintf(k.system_prompt, sizeof(k.system_prompt), "%s", + sp.p != NULL ? sp.p : ""); + sp_buf_free(&sp); + snprintf(script, sizeof(script), "%s/script.txt", dir); + f = fopen(script, "w"); + CHECK(f != NULL); + if (f == NULL) + return 1; + fprintf(f, "tool run {\"command\":\"sleep 2\"}\n"); + fprintf(f, "answer too-late\n"); + fclose(f); + + CHECK(kengine_open(&k, script, k.last_error, + sizeof(k.last_error)) == 0); + if (k.eng == NULL) + return 1; + rc = krun_turn(&k, "take longer than the budget", "test", NULL); + CHECK(rc != 0); + CHECK(contains(k.st.last_error, "max_turn_seconds")); + CHECK(!contains(k.st.last_outcome, "too-late")); + { + FILE *lf = fopen(logpath, "r"); + size_t n = 0; + + if (lf != NULL) { + n = fread(logbuf, 1, sizeof(logbuf) - 1, lf); + logbuf[n] = '\0'; + fclose(lf); + } else { + logbuf[0] = '\0'; + } + } + CHECK(contains(logbuf, "\"kind\":\"turn_timeout\"")); + CHECK(contains(logbuf, "\"kind\":\"turn_end\"")); + + kengine_close(&k); + klog_close(&k.log); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_timeout: ok\n"); + return 0; +}