diff --git a/Makefile b/Makefile index 7280bcb0..503cce1b 100644 --- a/Makefile +++ b/Makefile @@ -100,6 +100,7 @@ HTTP_LWS_O := $(if $(filter 1,$(GATEWAY)),src/gateway/http_lws.o,) ROUTES_O := $(if $(filter 1,$(GATEWAY)),src/gateway/routes.o,) ROUTES_HARDWARE_O := $(if $(filter 1,$(GATEWAY)),src/gateway/routes_hardware.o,) WS_O := $(if $(filter 1,$(GATEWAY)),src/gateway/ws.o,) +WS_RX_O := src/gateway/ws_rx.o # Tools (Task 7) SHELL_O := src/tools/shell.o WEBSEARCH_O := src/tools/web_search.o @@ -173,6 +174,7 @@ PROVIDER_OBJS := $(PROVIDER_COMMON_O) $(STUB_O) $(ROUTER_O) $(ANTHROPIC_O) $(OPE CHANNEL_OBJS := $(CHANNEL_COMMON_O) $(CHANNEL_CLI_O) $(CHANNEL_TG_O) $(CHANNEL_DISCORD_O) $(DISCORD_HELPERS_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_WEBCHAT_O) ASAP_HTTP_BODY_O := $(if $(filter 1,$(GATEWAY)),src/gateway/asap_http_body.o,) GATEWAY_OBJS := $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(WS_O) $(RATE_LIMIT_O) +GATEWAY_OBJS += $(if $(filter 1,$(GATEWAY)),$(WS_RX_O)) TOOL_OBJS := $(SHELL_O) $(WEBSEARCH_O) $(FILE_O) $(REGISTRY_O) $(CONTEXT_O) $(CONTEXT_CACHE_O) $(CONTEXT_HTTP_O) $(CONTEXT_GEO_O) $(CRYPTO_LINK) $(HARDWARE_STUB_O) $(HARDWARE_INIT_O) $(HARDWARE_GPIO_SNAPSHOT_O) $(HARDWARE_TEGRASTATS_O) $(HARDWARE_TOOLS_O) $(BOARD_DETECT_O) $(HARDWARE_I2C_O) $(HARDWARE_CAMERA_O) $(HARDWARE_LIBGPIOD_O) $(CRON_O) $(ASAP_INVOKE_O) ASAP_OBJS := $(MANIFEST_O) $(MANIFEST_PROFILES_O) $(MANIFEST_BUILD_O) $(MANIFEST_SIGN_O) $(MANIFEST_KEYS_O) $(JCS_O) $(ENVELOPE_O) $(ULID_O) $(CLIENT_O) $(ASAP_REGISTRY_O) $(SERVER_O) $(ASAP_LOG_O) SANDBOX_OBJS := $(SANDBOX_O) $(ALLOWLIST_O) @@ -225,7 +227,7 @@ $(RELOAD_CHANNEL_STUB_O): tests/stubs/reload_channel_stub.c src/channels/channel $(HTTP_RELOAD_STUB_O): tests/stubs/http_reload_stub.c src/gateway/http.h src/core/config.h $(CC) $(CFLAGS) $(INC) -c -o $@ tests/stubs/http_reload_stub.c -$(DISPATCH_O): src/core/dispatch.c src/core/dispatch.h src/core/agent.h src/core/bootstrap.h src/core/memory.h src/channels/channel.h src/tools/cron.h +$(DISPATCH_O): src/core/dispatch.c src/core/dispatch.h src/core/agent.h src/core/bootstrap.h src/core/memory.h src/channels/channel.h src/channels/heartbeat.h src/tools/cron.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/core/dispatch.c $(TOML_O): vendor/tomlc99/toml.c vendor/tomlc99/toml.h @@ -371,10 +373,10 @@ $(ASAP_REGISTRY_TEST_O): src/asap/registry.c src/asap/registry.h src/asap/client $(RATE_LIMIT_O): src/gateway/rate_limit.c src/gateway/rate_limit.h $(CC) $(CFLAGS) $(INC) -pthread -c -o $@ src/gateway/rate_limit.c -$(HTTP_O): src/gateway/http.c src/gateway/http.h src/gateway/http_lws.h src/gateway/ws.h src/providers/provider.h +$(HTTP_O): src/gateway/http.c src/gateway/http.h src/gateway/http_lws.h src/gateway/ws.h src/gateway/ws_rx.h src/providers/provider.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http.c -$(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h +$(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h src/gateway/ws_rx.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http_lws.c $(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h @@ -386,6 +388,9 @@ $(ROUTES_HARDWARE_O): src/gateway/routes_hardware.c src/gateway/routes_hardware. $(WS_O): src/gateway/ws.c src/gateway/ws.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -c -o $@ src/gateway/ws.c +$(WS_RX_O): src/gateway/ws_rx.c src/gateway/ws_rx.h src/gateway/ws.h vendor/cJSON/cJSON.h + $(CC) $(CFLAGS) $(INC) -c -o $@ $< + $(SHELL_O): src/tools/shell.c src/tools/tool.h src/tools/shell.h src/core/config.h \ src/sandbox/sandbox.h src/sandbox/allowlist.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/tools/shell.c @@ -478,7 +483,7 @@ $(HARDWARE_I2C_O): src/hardware/hardware_i2c.c src/hardware/hardware_i2c.h $(HARDWARE_CAMERA_O): src/hardware/hardware_camera.c src/hardware/hardware_camera.h src/hardware/board_detect.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/hardware/hardware_camera.c -$(CRON_O): src/tools/cron.c src/tools/cron.h src/crypto/crypto.h src/core/agent.h src/core/memory.h src/channels/channel.h src/core/config.h +$(CRON_O): src/tools/cron.c src/tools/cron.h src/crypto/crypto.h src/core/agent.h src/core/memory.h src/channels/channel.h src/channels/heartbeat.h src/core/config.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/tools/cron.c $(ASAP_INVOKE_O): src/tools/asap_invoke.c src/tools/asap_invoke.h src/tools/tool.h src/asap/envelope.h src/asap/client.h src/asap/registry.h src/asap/ulid.h src/asap/asap_version.h src/core/config.h vendor/cJSON/cJSON.h @@ -642,9 +647,9 @@ test_web_search: tests/test_web_search.c $(WEBSEARCH_O) $(CONFIG_O) $(TOML_O) $( $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_web_search.c $(WEBSEARCH_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(LDLIBS) $(DSYM_SCRIPT) -test_cron: tests/test_cron.c $(CRON_O) $(CRYPTO_LINK) $(MEMORY_O) $(SQLITE3_O) $(CHANNEL_COMMON_O) $(CJSON_O) $(AGENT_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(PROVIDER_COMMON_O) +test_cron: tests/test_cron.c $(CRON_O) $(CRYPTO_LINK) $(MEMORY_O) $(SQLITE3_O) $(CHANNEL_COMMON_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_CLI_O) $(CJSON_O) $(AGENT_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(PROVIDER_COMMON_O) @mkdir -p $(BINDIR) - $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_cron.c $(CRON_O) $(CRYPTO_LINK) $(MEMORY_O) $(SQLITE3_O) $(CHANNEL_COMMON_O) $(CJSON_O) $(AGENT_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(PROVIDER_COMMON_O) $(LDLIBS) -pthread + $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ $^ $(LDLIBS) -pthread $(DSYM_SCRIPT) test_ws: tests/test_ws.c $(WS_TEST_O) @@ -652,14 +657,19 @@ test_ws: tests/test_ws.c $(WS_TEST_O) $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_ws.c $(WS_TEST_O) $(LDLIBS) -pthread $(DSYM_SCRIPT) +test_ws_rx: tests/test_ws_rx.c $(WS_RX_O) $(CJSON_O) + @mkdir -p $(BINDIR) + $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ $^ $(LDLIBS) + $(DSYM_SCRIPT) + test_context: tests/test_context.c $(CONTEXT_TEST_OBJS) $(CONFIG_O) $(TOML_O) $(CJSON_O) @mkdir -p $(BINDIR) $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -DSHELLCLAW_CONTEXT_TEST -o $(BINDIR)/$@ tests/test_context.c $(CONTEXT_TEST_OBJS) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(LDLIBS) -pthread $(DSYM_SCRIPT) -test_dispatch: tests/test_dispatch.c $(DISPATCH_O) $(BOOTSTRAP_DISPATCH_STUB_O) $(AGENT_O) $(ROUTER_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(PROVIDER_COMMON_O) $(MEMORY_O) $(SQLITE3_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(CRON_O) $(CRYPTO_LINK) $(CHANNEL_COMMON_O) +test_dispatch: tests/test_dispatch.c $(DISPATCH_O) $(BOOTSTRAP_DISPATCH_STUB_O) $(AGENT_O) $(ROUTER_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(PROVIDER_COMMON_O) $(MEMORY_O) $(SQLITE3_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(CRON_O) $(CRYPTO_LINK) $(CHANNEL_COMMON_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_CLI_O) @mkdir -p $(BINDIR) - $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ tests/test_dispatch.c $(DISPATCH_O) $(BOOTSTRAP_DISPATCH_STUB_O) $(AGENT_O) $(ROUTER_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(PROVIDER_COMMON_O) $(MEMORY_O) $(SQLITE3_O) $(SKILL_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(CRON_O) $(CRYPTO_LINK) $(CHANNEL_COMMON_O) $(LDLIBS) -pthread + $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -o $(BINDIR)/$@ $^ $(LDLIBS) -pthread $(DSYM_SCRIPT) RELOAD_TEST_OBJS := $(RELOAD_O) $(BOOTSTRAP_DISPATCH_STUB_O) $(TOOL_RELOAD_STUB_O) $(RELOAD_CHANNEL_STUB_O) $(HTTP_RELOAD_STUB_O) $(CONFIG_O) $(TOML_O) \ @@ -865,7 +875,7 @@ static: --suppress=variableScope:src/vendor/tweetnacl/tweetnacl.c \ -q src/ -test: test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_gpio_snapshot test_hardware_tegrastats test_hardware_tools test_registry test_ws test_manifest $(ASAP_UNIT_TESTS) test_sandbox test_allowlist test_rate_limit test_daemon_smoke test_bootstrap_keys test_update_script test_install_script test_download_model test_web_dashboard test_routes_hardware +test: test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_gpio_snapshot test_hardware_tegrastats test_hardware_tools test_registry test_ws test_ws_rx test_manifest $(ASAP_UNIT_TESTS) test_sandbox test_allowlist test_rate_limit test_daemon_smoke test_bootstrap_keys test_update_script test_install_script test_download_model test_web_dashboard test_routes_hardware $(BINDIR)/test_config $(BINDIR)/test_config_patch $(BINDIR)/test_memory @@ -901,6 +911,7 @@ test: test_config test_config_patch test_memory test_skill test_provider test_an $(BINDIR)/test_hardware_tools $(BINDIR)/test_registry $(BINDIR)/test_ws + $(BINDIR)/test_ws_rx @for t in $(ASAP_UNIT_TESTS); do $(BINDIR)/$$t || exit 1; done $(BINDIR)/test_sandbox $(BINDIR)/test_allowlist @@ -922,7 +933,7 @@ COVERAGE_DIR := build/coverage COVERAGE_MIN := 80 coverage: clean - $(MAKE) BUILD=coverage GATEWAY=0 test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_gpio_snapshot test_hardware_tegrastats test_hardware_tools test_registry test_ws test_manifest_build test_manifest_keys test_jcs $(ASAP_UNIT_TESTS) test_sandbox test_allowlist test_rate_limit test_auth + $(MAKE) BUILD=coverage GATEWAY=0 test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_gpio_snapshot test_hardware_tegrastats test_hardware_tools test_registry test_ws test_ws_rx test_manifest_build test_manifest_keys test_jcs $(ASAP_UNIT_TESTS) test_sandbox test_allowlist test_rate_limit test_auth @if [ "$(GATEWAY)" = "1" ]; then $(MAKE) BUILD=coverage GATEWAY=1 shellclaw test_gateway_http test_static; fi @chmod +x scripts/coverage.sh @@ -935,7 +946,7 @@ clean-root-dsym: clean: clean-root-dsym rm -f $(OBJS) $(PROVIDER_COMMON_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(ROUTER_O) $(CJSON_O) $(TWEETNACL_O) $(ANTHROPIC_TEST_O) $(OPENAI_TEST_O) $(LOCAL_TEST_O) $(CONTEXT_TEST_OBJS) $(HEARTBEAT_TEST_O) $(CHANNEL_TG_TEST_O) $(CHANNEL_COMMON_O) $(CHANNEL_STUB_O) $(CHANNEL_CLI_O) $(CHANNEL_TG_O) $(CHANNEL_DISCORD_O) $(DISCORD_HELPERS_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_WEBCHAT_O) $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(WS_O) $(MANIFEST_O) $(MANIFEST_PROFILES_O) $(MANIFEST_BUILD_O) $(MANIFEST_SIGN_O) $(MANIFEST_KEYS_O) $(ENVELOPE_O) $(ULID_O) $(CLIENT_O) $(ASAP_REGISTRY_O) $(SERVER_O) $(ASAP_LOG_O) $(RATE_LIMIT_O) $(SHELL_O) $(WEBSEARCH_O) $(FILE_O) $(REGISTRY_O) $(CONTEXT_O) $(CONTEXT_CACHE_O) $(CONTEXT_HTTP_O) $(CONTEXT_GEO_O) $(CRYPTO_O) $(JCS_O) $(HARDWARE_STUB_O) $(HARDWARE_INIT_O) $(HARDWARE_GPIO_SNAPSHOT_O) $(HARDWARE_TEGRASTATS_O) $(HARDWARE_TOOLS_O) $(BOARD_DETECT_O) src/hardware/hardware_libgpiod.o $(HARDWARE_I2C_O) $(HARDWARE_CAMERA_O) $(CRON_O) $(ASAP_INVOKE_O) $(SANDBOX_CORE_O) $(SANDBOX_LANDLOCK_O) $(SANDBOX_ENV_O) $(ALLOWLIST_SCAN_O) $(ALLOWLIST_PATH_O) - rm -f src/gateway/ui_assets.h + rm -f src/gateway/ui_assets.h $(WS_RX_O) $(BINDIR)/test_ws_rx find . -name '*.gcno' -o -name '*.gcda' -o -name '*.gcov' | xargs rm -f 2>/dev/null || true rm -f $(WS_TEST_O) $(SANDBOX_TEST_O) $(BINDIR)/asap_registry_test.o $(BINDIR)/asap_invoke_test.o $(CONTEXT_TEST_OBJS) $(HEARTBEAT_TEST_O) $(BINDIR)/shellclaw $(BINDIR)/test_tweetnacl_smoke $(BINDIR)/test_config $(BINDIR)/test_config_patch $(BINDIR)/test_memory $(BINDIR)/test_skill $(BINDIR)/test_provider $(BINDIR)/test_anthropic $(BINDIR)/test_openai $(BINDIR)/test_local_provider $(BINDIR)/test_router $(BINDIR)/test_heartbeat $(BINDIR)/test_crypto $(BINDIR)/test_hardware_stub $(BINDIR)/test_board_detect $(BINDIR)/test_hardware_libgpiod $(BINDIR)/test_hardware_i2c $(BINDIR)/test_hardware_camera $(BINDIR)/test_pin_tables $(BINDIR)/test_hardware_init $(BINDIR)/test_hardware_tools $(BINDIR)/test_registry $(BINDIR)/test_ws $(BINDIR)/test_agent $(BINDIR)/test_channel $(BINDIR)/test_cli $(BINDIR)/test_shell $(BINDIR)/test_file $(BINDIR)/test_telegram $(BINDIR)/test_discord_helpers $(BINDIR)/test_web_search $(BINDIR)/test_cron $(BINDIR)/test_context $(BINDIR)/test_manifest_build $(BINDIR)/test_manifest_keys $(BINDIR)/test_jcs $(BINDIR)/test_asap_envelope $(BINDIR)/test_asap_ulid $(BINDIR)/test_asap_client $(BINDIR)/test_asap_registry $(BINDIR)/test_asap_server $(BINDIR)/test_asap_invoke $(BINDIR)/test_asap_log $(BINDIR)/test_auth $(BINDIR)/test_gateway_http $(BINDIR)/test_gateway_db_lock $(BINDIR)/test_static $(BINDIR)/test_sandbox $(BINDIR)/test_allowlist $(BINDIR)/test_rate_limit rm -rf $(BINDIR)/*.dSYM $(DSYMDIR) diff --git a/README.md b/README.md index 1afa7a3b..bbc1cf59 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and th **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). -**WebSocket auth (breaking vs early gateway builds):** browsers cannot send `Authorization` on WebSocket; use subprotocol `bearer.` when opening `/ws` (see `web/js/app.js`). +**WebSocket authentication.** Pair with the gateway before opening `/ws`. For a browser client, offer both `ws` and `bearer.` as subprotocols. The gateway selects `ws` and reads the token from the other entry. For a native client, offer `ws` and send the token in `Authorization: Bearer `. **Debug (macOS):** Symbols in `tests-dSYM/`. Use `lldb build/test_agent` then `settings set target.debug-file-search-path tests-dSYM`. Old `.dSYM` in repo root? Run `make clean-root-dsym`. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bd52b266..a198f3b3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -86,7 +86,7 @@ Convention: one primary `.c` + `.h` per module; new tools go in `src/tools/` (not `Authorization` header). +- **WebSocket.** The gateway selects the `ws` subprotocol and validates the pairing token before the connection opens. See [WebSocket authentication](../README.md) for the browser and native client contracts. - **Hardware API:** `/api/hardware/*` — board info, GPIO snapshot, tegrastats on Jetson; sensor/camera panels stubbed “Coming in v1.2”. - **Rate limits:** per-IP on `/asap`; per-token on camera snapshot (1/sec) when enabled. - **Signed manifest:** `GET /.well-known/asap/manifest.json` builds and signs the JSON synchronously in the HTTP handler (single-threaded today; not safe for concurrent manifest builds without locking). diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c6ac5e10..014a658d 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -100,6 +100,12 @@ The task checklist references `unshare(CLONE_NEWNS) + pivot_root` as a hardened ### JetPack 6 / kernel 5.15 note +Landlock ABI 3 and later restrict regular file truncation to the workspace. On ABI 1 and 2, including JetPack 6 with Linux 5.15, ShellClaw adds a read-only mount policy. +The policy applies in the command's private mount namespace. The workspace and its submounts keep their original mount permissions. The command can still resize files on writable workspace mounts. +ShellClaw removes `CAP_SYS_ADMIN` before it starts the command. The command and its descendants cannot change the protected mounts. +The legacy policy requires `open_tree`, `mount_setattr`, and `move_mount`. ShellClaw stops before it starts the command if the setup fails or the workspace is the root directory. +Linux 5.15 requires the system to mount its root filesystem during boot. If the system runs directly from the initial initramfs, ShellClaw stops before it starts the command. + Namespace behavior above was verified by **source audit**. On-device validation on JetPack 6.2.x is a [known pending](JETSON_SIGNOFF.md) item (not a CI or merge-to-`main` gate). --- @@ -300,7 +306,7 @@ This section summarizes Jetson Orin Nano Super / JetPack 6.2.x concerns that do |------|------------------|----------------------------| | Sandbox isolation | [`src/sandbox/sandbox.c`](../src/sandbox/sandbox.c), [`src/sandbox/sandbox_landlock.c`](../src/sandbox/sandbox_landlock.c) | user ns + `unshare` + PID-1 fork, Landlock workspace bound, cgroups v2, fail-closed isolation | | Command policy | [`src/sandbox/allowlist.c`](../src/sandbox/allowlist.c) | Blocklist (incl. Jetson GPU + Argus), workspace path containment (DiD) | -| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | `requires_auth()` Bearer gate for `/api/*` | +| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | The gateway validates the bearer token for `/api/*` and during the WebSocket handshake. | | Hardware HTTP API | [`src/gateway/routes_hardware.c`](../src/gateway/routes_hardware.c) | Read-only GET handlers, camera POST deferred stub | | Rate limits | [`src/gateway/rate_limit.c`](../src/gateway/rate_limit.c) | Per-IP `/asap` RPM (64-slot table); reuses expired windows; **fail-closed** (429) when table is full and no slot expired | | Camera spawn | [`src/hardware/hardware_camera.c`](../src/hardware/hardware_camera.c) | argv-only `execvp`, validated resolution/type/path | diff --git a/scripts/coverage.sh b/scripts/coverage.sh index 816dfae1..79f7ba25 100755 --- a/scripts/coverage.sh +++ b/scripts/coverage.sh @@ -13,7 +13,7 @@ LCOV_RC="lcov_branch_coverage=0" mkdir -p "$COVERAGE_DIR" rm -f "$COVERAGE_DIR"/*.info -TESTS="test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_tools test_registry test_ws test_manifest_build test_manifest_keys test_jcs test_asap_envelope test_asap_ulid test_asap_client test_asap_registry test_asap_server test_asap_invoke test_asap_log test_sandbox test_allowlist test_rate_limit test_auth test_static" +TESTS="test_config test_config_patch test_memory test_skill test_provider test_anthropic test_openai test_local_provider test_router test_heartbeat test_agent test_reload test_channel test_cli test_shell test_file test_telegram test_discord_helpers test_web_search test_cron test_context test_dispatch test_crypto test_hardware_stub test_board_detect test_hardware_libgpiod test_hardware_i2c test_hardware_camera test_pin_tables test_hardware_init test_hardware_tools test_registry test_ws test_ws_rx test_manifest_build test_manifest_keys test_jcs test_asap_envelope test_asap_ulid test_asap_client test_asap_registry test_asap_server test_asap_invoke test_asap_log test_sandbox test_allowlist test_rate_limit test_auth test_static" # ASAP tests must stay aligned with ASAP_UNIT_TESTS in the top-level Makefile. if [ "${GATEWAY:-}" = "1" ]; then TESTS="$TESTS test_gateway_http" diff --git a/src/channels/heartbeat.c b/src/channels/heartbeat.c index 457ae6c7..64cc7969 100644 --- a/src/channels/heartbeat.c +++ b/src/channels/heartbeat.c @@ -74,25 +74,50 @@ static int heartbeat_poll(channel_incoming_msg_t *out, int timeout_ms) return 1; } +static int heartbeat_log_send(const char *recipient, const char *text, + const channel_attachment_t *attachments, size_t att_count) +{ + (void)recipient; + (void)attachments; + (void)att_count; + if (!text) return -1; + fprintf(stderr, "[heartbeat] %s\n", text); + return 0; +} + +static const channel_t heartbeat_log_channel = {.send = heartbeat_log_send}; + +static const char *heartbeat_destination(const config_t *cfg) +{ + if (!cfg) return "log"; + const char *name = config_heartbeat_default_channel(cfg); + return name && name[0] ? name : "cli"; +} + +const channel_t *heartbeat_local_delivery(void) +{ + if (!config_heartbeat_enabled(g_heartbeat_cfg)) + return NULL; + const char *target = heartbeat_destination(g_heartbeat_cfg); + if (strcmp(target, "log") == 0) + return &heartbeat_log_channel; + if (strcmp(target, "cli") == 0) + return channel_get_by_name("cli"); + return NULL; +} + static int heartbeat_send(const char *recipient, const char *text, - const channel_attachment_t *attachments, size_t att_count) + const channel_attachment_t *attachments, size_t att_count) { (void)recipient; (void)attachments; (void)att_count; if (!text) return -1; - if (!g_heartbeat_cfg) { - fprintf(stderr, "[heartbeat] %s\n", text); - return 0; - } - const char *ch = config_heartbeat_default_channel(g_heartbeat_cfg); - if (ch && strcmp(ch, "log") == 0) { - fprintf(stderr, "[heartbeat] %s\n", text); - return 0; - } - const char *target = (ch && ch[0]) ? ch : "cli"; + const char *target = heartbeat_destination(g_heartbeat_cfg); + if (strcmp(target, "log") == 0) + return heartbeat_log_send("default", text, NULL, 0); const channel_t *dest = channel_get_by_name(target); - if (!dest || !dest->send) return -1; + if (!dest || dest == channel_heartbeat_get() || !dest->send) return -1; return dest->send("default", text, NULL, 0); } diff --git a/src/channels/heartbeat.h b/src/channels/heartbeat.h index b8334f43..a318f4fd 100644 --- a/src/channels/heartbeat.h +++ b/src/channels/heartbeat.h @@ -20,6 +20,11 @@ typedef struct channel channel_t; /** Get the heartbeat channel (poll returns tick when interval elapsed, send routes to default or log). */ const channel_t *channel_heartbeat_get(void); +/** Return the configured log or CLI delivery channel for cron, or NULL. + * Call with the agent lock held to serialize access with configuration reload. + */ +const channel_t *heartbeat_local_delivery(void); + /** After config reload without channel re-init (SIGHUP); updates live pointers only. */ void heartbeat_set_live_config(const config_t *cfg); diff --git a/src/core/agent.c b/src/core/agent.c index a3df2595..17f11c2d 100644 --- a/src/core/agent.c +++ b/src/core/agent.c @@ -82,8 +82,15 @@ static int copy_printed_session_json(char *dst, size_t dst_size, char *printed, static const char SUMMARIZE_SYSTEM[] = "Summarize the following conversation in one short paragraph. Output only the summary, no preamble."; -/** Marker appended by summary_source_append_truncated when a line was cut. */ -static const char SUMMARY_TRUNC_MARKER[] = "[truncated]"; +static const char TRUNCATED_MARKER[] = "[truncated]"; + +/* If the cut splits a UTF-8 character, exclude that character. */ +static size_t utf8_prefix_bytes(const char *text, size_t cut) +{ + while (cut > 0 && ((unsigned char)text[cut] & 0xC0) == 0x80) + cut--; + return cut; +} /** Append one "role: content" line, or roll back if the whole line does not fit. */ static int summary_source_append(char *buf, size_t cap, size_t *used, @@ -129,21 +136,15 @@ static int summary_source_append_truncated(char *buf, size_t cap, size_t *used, if (!buf || !used || *used + 1 >= cap) return 0; remain = cap - *used; - fixed = strlen(r) + 2 + strlen(SUMMARY_TRUNC_MARKER) + 1 + 1; /* ": " "\n" NUL */ + fixed = strlen(r) + 2 + sizeof(TRUNCATED_MARKER) + 1; /* ": " and newline */ if (remain <= fixed) return 0; cut = remain - fixed; if (cut > strlen(c)) cut = strlen(c); - /* The cut is a byte count, so it can land inside a multibyte UTF-8 - * codepoint. Back it up while the first dropped byte is a continuation - * byte: invalid UTF-8 in the stub makes providers reject the summarizer - * request, and compaction then returns -1 on every turn for that - * session. */ - while (cut > 0 && ((unsigned char)c[cut] & 0xC0) == 0x80) - cut--; + cut = utf8_prefix_bytes(c, cut); n = snprintf(buf + *used, remain, "%s: %.*s%s\n", r, (int)cut, c, - SUMMARY_TRUNC_MARKER); + TRUNCATED_MARKER); if (n < 0 || (size_t)n >= remain) { buf[*used] = '\0'; return 0; @@ -165,9 +166,8 @@ static int kept_tail_starts_with_user(const cJSON *root, int start) return cJSON_IsString(role) && role->valuestring && strcmp(role->valuestring, "user") == 0; } -/** Fold the summary into the first kept message: a user turn (a second user - * message 400s on Anthropic) or the oversized line a partial pass broke on, - * so the next pass starts on it with an empty source for the full stub. */ +/* Fold the summary into the first retained message. This gives a large + * message the full source buffer on the next pass. */ static int fold_summary_into_message(cJSON *item, const char *summary) { const cJSON *content; @@ -207,25 +207,17 @@ static int fold_summary_into_message(cJSON *item, const char *summary) return 0; } -static int append_summary_user(cJSON *arr, const char *summary) +static cJSON *append_session_message(cJSON *arr, const char *role, const char *text) { - cJSON *obj; - cJSON *role; - cJSON *content; - - obj = cJSON_CreateObject(); - role = cJSON_CreateString("user"); - content = cJSON_CreateString(summary ? summary : ""); - if (!obj || !role || !content) { + cJSON *obj = cJSON_CreateObject(); + if (!obj || + !cJSON_AddStringToObject(obj, "role", role) || + !cJSON_AddStringToObject(obj, "content", text ? text : "") || + !cJSON_AddItemToArray(arr, obj)) { cJSON_Delete(obj); - cJSON_Delete(role); - cJSON_Delete(content); - return -1; + return NULL; } - cJSON_AddItemToObject(obj, "role", role); - cJSON_AddItemToObject(obj, "content", content); - cJSON_AddItemToArray(arr, obj); - return 0; + return obj; } /** Summarize oldest messages when over max_ctx; replace with one summary + trailing. @@ -310,6 +302,11 @@ static int compact_session_via_llm(const char *session_id, char *session_buf, si memcpy(summary_buf, resp.content, sum_len); summary_buf[sum_len] = '\0'; provider_response_clear(&resp); + /* Keep the original history if the summary contains only whitespace. */ + if (strspn(summary_buf, " \t\n\r\v\f") == sum_len) { + cJSON_Delete(root); + return -1; + } cJSON *new_arr = cJSON_CreateArray(); int keep = max_ctx - 1; int start = (next_unsummarized < to_summarize_n) @@ -317,14 +314,11 @@ static int compact_session_via_llm(const char *session_id, char *session_buf, si int merge; int folded = 0; if (start < 0) start = 0; - /* Tail can start on a user turn (odd max_context_messages, or a cut that - * lands on user). Inserting another user role makes Anthropic reject the - * session on this turn and every later one. fold_into_oversized breaks on - * that rule for the line that stopped the pass: it is not a user turn, so - * the summary folds into it instead of a prepended wrapper (see the loop). */ + /* Fold into a user turn when possible. If the first pass stops at the + * second message, fold there so a later pass has room to summarize it. */ merge = kept_tail_starts_with_user(root, start); if (!new_arr) { cJSON_Delete(root); return -1; } - if (!merge && !fold_into_oversized && append_summary_user(new_arr, summary_buf) != 0) { + if (!merge && !fold_into_oversized && !append_session_message(new_arr, "user", summary_buf)) { cJSON_Delete(new_arr); cJSON_Delete(root); return -1; @@ -409,7 +403,8 @@ static void copy_response_to_buf(const char *content, char *response_buf, size_t if (!response_buf || response_size == 0) return; if (content) { size_t n = strlen(content); - if (n >= response_size) n = response_size - 1; + if (n >= response_size) + n = utf8_prefix_bytes(content, response_size - 1); memcpy(response_buf, content, n); response_buf[n] = '\0'; } else @@ -515,7 +510,47 @@ static void free_tool_calls_copy(const provider_tool_call_t *copy, size_t n) free(owned); } -/** Append user+assistant exchange to session JSON. Invalid or empty existing becomes []. */ +/* Drop the oldest exchanges until the JSON fits. If the newest exchange + * alone exceeds the limit, shorten its larger message and try again. */ +static char *print_session_within_limit(cJSON *arr, cJSON *user, cJSON *assistant, + size_t cap) +{ + char *printed = cJSON_PrintUnformatted(arr); + if (!printed || strlen(printed) < cap) + return printed; + + size_t len = strlen(printed); + cJSON_free(printed); + while (arr->child != user && (len >= cap || !kept_tail_starts_with_user(arr, 0))) { + char *head = cJSON_PrintUnformatted(arr->child); + if (!head) + return NULL; + len -= strlen(head) + 1; /* Include the separator after the removed message. */ + cJSON_free(head); + cJSON_DeleteItemFromArray(arr, 0); + } + if (len < cap) + return cJSON_PrintUnformatted(arr); + + char *user_text = cJSON_GetObjectItem(user, "content")->valuestring; + char *assistant_text = cJSON_GetObjectItem(assistant, "content")->valuestring; + for (;;) { + size_t user_len = strlen(user_text); + size_t assistant_len = strlen(assistant_text); + char *text = user_len >= assistant_len ? user_text : assistant_text; + size_t text_len = user_len >= assistant_len ? user_len : assistant_len; + size_t cut = utf8_prefix_bytes(text, text_len / 2); + if (cut + sizeof(TRUNCATED_MARKER) > text_len) + return NULL; + memcpy(text + cut, TRUNCATED_MARKER, sizeof(TRUNCATED_MARKER)); + printed = cJSON_PrintUnformatted(arr); + if (!printed || strlen(printed) < cap) + return printed; + cJSON_free(printed); + } +} + +/** Append a complete exchange to session JSON. Invalid or empty input becomes []. */ static int append_exchange_to_session_json(const char *existing_json, const char *user_message, const char *assistant_content, char *out_buf, size_t out_size, const char *session_id) { @@ -529,19 +564,10 @@ static int append_exchange_to_session_json(const char *existing_json, const char } if (!arr) arr = cJSON_CreateArray(); if (!arr) return -1; - cJSON *user_obj = cJSON_CreateObject(); - if (user_obj) { - cJSON_AddItemToObject(user_obj, "role", cJSON_CreateString("user")); - cJSON_AddItemToObject(user_obj, "content", cJSON_CreateString(user_message ? user_message : "")); - cJSON_AddItemToArray(arr, user_obj); - } - cJSON *asst_obj = cJSON_CreateObject(); - if (asst_obj) { - cJSON_AddItemToObject(asst_obj, "role", cJSON_CreateString("assistant")); - cJSON_AddItemToObject(asst_obj, "content", cJSON_CreateString(assistant_content ? assistant_content : "")); - cJSON_AddItemToArray(arr, asst_obj); - } - char *printed = cJSON_PrintUnformatted(arr); + cJSON *user = append_session_message(arr, "user", user_message); + cJSON *assistant = append_session_message(arr, "assistant", assistant_content); + char *printed = user && assistant + ? print_session_within_limit(arr, user, assistant, out_size) : NULL; cJSON_Delete(arr); return copy_printed_session_json(out_buf, out_size, printed, session_id); } @@ -669,14 +695,17 @@ static int agent_prepare_context(agent_run_ctx_t *ctx) return 0; } -/** Build provider message array: system + history + current user turn. */ +/** Build the provider request from the system prompt, history, and current turn. */ static int agent_build_messages(agent_run_ctx_t *ctx) { ctx->history_count = 0; parse_session_into_messages(ctx->session_buf, ctx->max_ctx, ctx->history_msgs, ctx->history_roles_buf, MAX_HISTORY_MESSAGES * ROLE_LEN, ctx->history_content, HISTORY_CONTENT_MAX, &ctx->history_count); - ctx->total_msgs = 1 + (size_t)ctx->history_count + 1; + /* Some providers require a user message first. A cut can leave an + * assistant message at the front of the window. Keep its original role. */ + int needs_prefix = ctx->history_count > 0 && strcmp(ctx->history_msgs[0].role, "assistant") == 0; + ctx->total_msgs = 2 + (size_t)ctx->history_count + (size_t)needs_prefix; ctx->messages = malloc(ctx->total_msgs * sizeof(provider_message_t)); if (!ctx->messages) { agent_oom_msg(ctx); @@ -685,12 +714,19 @@ static int agent_build_messages(agent_run_ctx_t *ctx) memset(ctx->messages, 0, ctx->total_msgs * sizeof(provider_message_t)); ctx->messages[0].role = "system"; ctx->messages[0].content = ctx->system_buf; + size_t next = 1; + if (needs_prefix) { + ctx->messages[next].role = "user"; + ctx->messages[next].content = "[Earlier user messages are unavailable.]"; + next++; + } for (int i = 0; i < ctx->history_count; i++) { - ctx->messages[1 + i].role = ctx->history_msgs[i].role; - ctx->messages[1 + i].content = ctx->history_msgs[i].content; + ctx->messages[next].role = ctx->history_msgs[i].role; + ctx->messages[next].content = ctx->history_msgs[i].content; + next++; } - ctx->messages[1 + ctx->history_count].role = "user"; - ctx->messages[1 + ctx->history_count].content = ctx->user_message; + ctx->messages[next].role = "user"; + ctx->messages[next].content = ctx->user_message; ctx->base_msg_count = ctx->total_msgs; return 0; } @@ -727,7 +763,10 @@ static int agent_react_loop(agent_run_ctx_t *ctx) return -1; } if (response.tool_calls_count == 0 || iteration >= ctx->max_iter) { - copy_response_to_buf(response.content, ctx->response_buf, ctx->response_size); + const char *text = response.content; + if (response.tool_calls_count > 0 && provider_text_is_blank(text)) + text = "Stopped: tool iteration limit reached."; + copy_response_to_buf(text, ctx->response_buf, ctx->response_size); provider_response_clear(&response); agent_persist_session(ctx, ctx->response_buf); return 0; diff --git a/src/core/dispatch.c b/src/core/dispatch.c index 68d24272..9f51edcc 100644 --- a/src/core/dispatch.c +++ b/src/core/dispatch.c @@ -4,27 +4,47 @@ */ #define _POSIX_C_SOURCE 200809L +#include "channels/heartbeat.h" #include "core/dispatch.h" #include "core/agent.h" #include "core/bootstrap.h" #include "core/memory.h" #include "core/version.h" +#include "providers/provider.h" #include "tools/cron.h" #include #include #define RESPONSE_BUF_SIZE (32 * 1024) -static int maybe_ack_cron(const channel_t *ch, const channel_incoming_msg_t *msg) +static int cron_target_available(const char *session_id) { - int ack_err; - if (!ch || !ch->name || strcmp(ch->name, "cron") != 0) + const char *separator = session_id ? strchr(session_id, ':') : NULL; + char name[64]; + if (!separator) return 0; - if (!msg || !msg->user_id) + size_t length = (size_t)(separator - session_id); + if (length >= sizeof(name)) return 0; - /* SQLITE_THREADSAFE=0: serialize ack SQL with other g_db writers. */ + memcpy(name, session_id, length); + name[length] = '\0'; + const channel_t *target = channel_get_by_name(name); + if (strcmp(name, "heartbeat") == 0 || target == channel_heartbeat_get()) + target = target == channel_heartbeat_get() ? heartbeat_local_delivery() : NULL; + return target && target->send; +} + +static int maybe_ack_cron(const char *job_id, const channel_incoming_msg_t *silent_reply) +{ + int ack_err; + if (!job_id) + return 0; + /* Check the current destination and acknowledge a silent reply under one lock. */ agent_lock(); - ack_err = cron_ack_delivery(msg->user_id); + if (silent_reply && !cron_target_available(silent_reply->session_id)) + ack_err = -1; + else + ack_err = cron_ack_delivery(job_id); agent_unlock(); return ack_err; } @@ -32,15 +52,18 @@ static int maybe_ack_cron(const channel_t *ch, const channel_incoming_msg_t *msg static int send_then_maybe_ack_cron(const channel_t *ch, const channel_incoming_msg_t *msg, const char *text, int agent_err) { + const char *cron_job_id; int send_err; if (!ch || !ch->send || !msg) return -1; + cron_job_id = ch->name && strcmp(ch->name, "cron") == 0 ? msg->user_id : NULL; + /* Keep a silent job due until its destination is available. */ + if (cron_job_id && agent_err == 0 && provider_text_is_blank(text)) + return maybe_ack_cron(cron_job_id, msg); send_err = ch->send(msg->session_id, text, NULL, 0); if (send_err != 0) return send_err; - if (agent_err != 0) - return 0; - return maybe_ack_cron(ch, msg); + return agent_err == 0 ? maybe_ack_cron(cron_job_id, NULL) : 0; } int dispatch_delete_session(const char *session_id) diff --git a/src/core/memory.c b/src/core/memory.c index 8e7f0ab1..91c35677 100644 --- a/src/core/memory.c +++ b/src/core/memory.c @@ -398,6 +398,8 @@ static int fill_cron_job_row(sqlite3_stmt *stmt, cron_job_row_t *out) copy_str_bounded(out->id, sizeof(out->id), (const char *)sqlite3_column_text(stmt, 0)); out->schedule = dup_sqlite_text(stmt, 1); out->message = dup_sqlite_text(stmt, 2); + out->channel_truncated = (size_t)sqlite3_column_bytes(stmt, 3) >= sizeof(out->channel); + out->recipient_truncated = (size_t)sqlite3_column_bytes(stmt, 4) >= sizeof(out->recipient); copy_str_bounded(out->channel, sizeof(out->channel), (const char *)sqlite3_column_text(stmt, 3)); copy_str_bounded(out->recipient, sizeof(out->recipient), (const char *)sqlite3_column_text(stmt, 4)); out->next_run = sqlite3_column_int64(stmt, 5); @@ -449,19 +451,32 @@ int cron_job_delete(const char *id) return ret; } -int cron_job_toggle(const char *id) +static int cron_job_set_enabled(const char *id, int disable) { if (!g_db || !id) return -1; memory_sqlite_entry_probe(); - const char *sql = "UPDATE cron_jobs SET enabled = 1 - enabled WHERE id = ?1"; + const char *sql = disable + ? "UPDATE cron_jobs SET enabled = 0 WHERE id = ?1 AND enabled = 1" + : "UPDATE cron_jobs SET enabled = 1 - enabled WHERE id = ?1"; sqlite3_stmt *stmt = NULL; if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) != SQLITE_OK) return -1; sqlite3_bind_text(stmt, 1, id, -1, SQLITE_TRANSIENT); - int ret = (sqlite3_step(stmt) == SQLITE_DONE && sqlite3_changes(g_db) > 0) ? 0 : -1; + int ret = (sqlite3_step(stmt) == SQLITE_DONE && + (disable || sqlite3_changes(g_db) > 0)) ? 0 : -1; sqlite3_finalize(stmt); return ret; } +int cron_job_toggle(const char *id) +{ + return cron_job_set_enabled(id, 0); +} + +int cron_job_disable(const char *id) +{ + return cron_job_set_enabled(id, 1); +} + int cron_job_update_next_run(const char *id, long long next_run) { if (!g_db || !id) return -1; @@ -497,22 +512,37 @@ int cron_job_list(cron_job_row_t *out, int max_count) return count; } -int cron_job_list_due(long long now, cron_due_key_t *out, int max_count) +int cron_job_list_due(long long now, const cron_due_key_t *after, + cron_due_key_t *out, int max_count) { - const char *sql; + const char *sql = "SELECT id, next_run, channel, recipient FROM cron_jobs " + "WHERE next_run <= ?1 AND enabled = 1 " + "AND (?2 IS NULL OR next_run > ?2 OR (next_run = ?2 AND id > ?3)) " + "ORDER BY next_run ASC, id ASC LIMIT ?4"; sqlite3_stmt *stmt = NULL; int count = 0; if (!g_db || !out || max_count <= 0) return -1; memory_sqlite_entry_probe(); - sql = "SELECT id, next_run FROM cron_jobs WHERE next_run <= ?1 AND enabled = 1 " - "ORDER BY next_run ASC, id ASC"; if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) != SQLITE_OK) return -1; sqlite3_bind_int64(stmt, 1, now); + if (after) { + sqlite3_bind_int64(stmt, 2, after->next_run); + sqlite3_bind_text(stmt, 3, after->id, -1, SQLITE_TRANSIENT); + } + sqlite3_bind_int(stmt, 4, max_count); while (count < max_count && sqlite3_step(stmt) == SQLITE_ROW) { copy_str_bounded(out[count].id, sizeof(out[count].id), (const char *)sqlite3_column_text(stmt, 0)); out[count].next_run = sqlite3_column_int64(stmt, 1); + out[count].channel_truncated = + (size_t)sqlite3_column_bytes(stmt, 2) >= sizeof(out[count].channel); + out[count].recipient_truncated = + (size_t)sqlite3_column_bytes(stmt, 3) >= sizeof(out[count].recipient); + copy_str_bounded(out[count].channel, sizeof(out[count].channel), + (const char *)sqlite3_column_text(stmt, 2)); + copy_str_bounded(out[count].recipient, sizeof(out[count].recipient), + (const char *)sqlite3_column_text(stmt, 3)); count++; } sqlite3_finalize(stmt); diff --git a/src/core/memory.h b/src/core/memory.h index e433fac8..e2dd9638 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -148,6 +148,8 @@ typedef struct cron_job_row { char *message; char channel[64]; char recipient[64]; + int channel_truncated; + int recipient_truncated; long long next_run; int enabled; } cron_job_row_t; @@ -181,6 +183,9 @@ int cron_job_delete(const char *id); */ int cron_job_toggle(const char *id); +/** Disable the stored job. Returns 0 if the update succeeds. */ +int cron_job_disable(const char *id); + /** * Update next_run for a job. * @@ -191,21 +196,27 @@ int cron_job_update_next_run(const char *id, long long next_run); /** * Key of a due cron job. No heap fields. Example: * cron_due_key_t keys[8]; - * int n = cron_job_list_due(now, keys, 8); + * int n = cron_job_list_due(now, NULL, keys, 8); */ typedef struct cron_due_key { char id[128]; long long next_run; + char channel[sizeof(((cron_job_row_t *)0)->channel)]; + char recipient[sizeof(((cron_job_row_t *)0)->recipient)]; + int channel_truncated; + int recipient_truncated; } cron_due_key_t; /** * List enabled jobs with next_run <= now, ordered by next_run then id. * + * @param after Optional last key from the previous page. * @param out Array to fill (caller-allocated). * @param max_count Maximum keys to return. * @return Number of keys written, or -1 on error. */ -int cron_job_list_due(long long now, cron_due_key_t *out, int max_count); +int cron_job_list_due(long long now, const cron_due_key_t *after, + cron_due_key_t *out, int max_count); /** * List cron jobs into output array. diff --git a/src/gateway/http.c b/src/gateway/http.c index 976a30cf..6b571ffb 100644 --- a/src/gateway/http.c +++ b/src/gateway/http.c @@ -7,6 +7,7 @@ #include "gateway/http.h" #include "gateway/http_lws.h" #include "gateway/ws.h" +#include "gateway/ws_rx.h" #include "providers/provider.h" #include "cJSON.h" #include @@ -37,14 +38,12 @@ static const struct lws_protocols protocols[] = { { .name = "ws", .callback = ws_callback, + .per_session_data_size = sizeof(ws_session_t), .rx_buffer_size = WS_RX_BUFFER_SIZE, }, { .name = NULL }, }; -_Static_assert(WS_RX_BUFFER_SIZE >= (size_t)WS_TEXT_MAX + 32, - "WebChat rx_buffer_size must fit JSON envelope around WS_TEXT_MAX"); - static const struct lws_http_mount mount_http = { .mountpoint = "/", .origin = "http", diff --git a/src/gateway/http_lws.c b/src/gateway/http_lws.c index 97940070..478215fa 100644 --- a/src/gateway/http_lws.c +++ b/src/gateway/http_lws.c @@ -11,11 +11,12 @@ #include "gateway/uri_match.h" #include "gateway/static.h" #include "gateway/ws.h" -#include "cJSON.h" +#include "gateway/ws_rx.h" #include #include #include #include +#include static void http_lws_tx_completed(struct lws *wsi) { @@ -129,41 +130,32 @@ const char *http_request_bearer_token(struct lws *wsi, char *buf, size_t buf_siz return buf + 7; } -/** WebSocket upgrade: Bearer from Authorization (or custom header); browser may send bearer. subprotocol. */ -static int ws_copy_upgrade_token(struct lws *wsi, char *token_out, size_t token_size) +/* Browsers offer ws for negotiation and bearer. for authentication. */ +static const char *ws_subprotocol_token(char *list) { - char auth_buf[256]; - const char *token; - if (!wsi || !token_out || token_size == 0) return -1; - token_out[0] = '\0'; - token = http_request_bearer_token(wsi, auth_buf, sizeof(auth_buf)); - if (!token) { - int n = lws_hdr_custom_copy(wsi, auth_buf, sizeof(auth_buf), "authorization", 13); - if (n > 7 && strncmp(auth_buf, "Bearer ", 7) == 0) - token = auth_buf + 7; + char *next = NULL; + for (char *entry = strtok_r(list, ",", &next); entry; + entry = strtok_r(NULL, ",", &next)) { + entry += strspn(entry, " \t"); + char *end = entry + strlen(entry); + while (end > entry && (end[-1] == ' ' || end[-1] == '\t')) + end--; + *end = '\0'; + if (end - entry > 7 && strncmp(entry, "bearer.", 7) == 0) + return entry + 7; } - if (token && token[0] != '\0') { - size_t len = strlen(token); - if (len >= token_size) len = token_size - 1; - memcpy(token_out, token, len); - token_out[len] = '\0'; + return NULL; +} + +static int ws_upgrade_allowed(const http_server_ctx_t *ctx, struct lws *wsi) +{ + char header[512]; + if (!ctx || !ctx->auth) return 0; - } - { - char proto[512]; - int n = lws_hdr_copy(wsi, proto, sizeof(proto), WSI_TOKEN_COLON_PROTOCOL); - if (n <= 0) - n = lws_hdr_custom_copy(wsi, proto, sizeof(proto), "sec-websocket-protocol", 22); - if (n > 7 && strncmp(proto, "bearer.", 7) == 0) { - const char *sub = proto + 7; - size_t len = (size_t)(n - 7); - if (len >= token_size) len = token_size - 1; - memcpy(token_out, sub, len); - token_out[len] = '\0'; - return token_out[0] != '\0' ? 0 : -1; - } - } - return -1; + const char *token = http_request_bearer_token(wsi, header, sizeof(header)); + if (!token && lws_hdr_copy(wsi, header, sizeof(header), WSI_TOKEN_PROTOCOL) > 0) + token = ws_subprotocol_token(header); + return token && auth_validate_token(ctx->auth, token); } static int is_static_path(const char *uri, int uri_len, int method) @@ -190,6 +182,10 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, { http_server_ctx_t *ctx = http_ctx_get(); (void)user; + /* libwebsockets calls the HTTP protocol before it selects ws. */ + if (reason == LWS_CALLBACK_HTTP_CONFIRM_UPGRADE && in && + strcasecmp(in, "websocket") == 0) + return ws_upgrade_allowed(ctx, wsi) ? 0 : -1; if (!ctx) return 0; switch (reason) { case LWS_CALLBACK_HTTP: { @@ -341,11 +337,13 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, conn->headers_sent = 1; } if (conn->static_sent < conn->static_len) { + unsigned char chunk[LWS_PRE + 4096]; + const size_t capacity = sizeof(chunk) - LWS_PRE; size_t to_send = conn->static_len - conn->static_sent; - if (to_send > 4096) to_send = 4096; - int m = lws_write(wsi, - (unsigned char *)(conn->static_data + conn->static_sent), - to_send, + if (to_send > capacity) to_send = capacity; + /* HTTP/2 writes a frame header before the payload. */ + memcpy(chunk + LWS_PRE, conn->static_data + conn->static_sent, to_send); + int m = lws_write(wsi, chunk + LWS_PRE, to_send, conn->static_sent + to_send >= conn->static_len ? LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP); if (m < 0) return -1; @@ -355,6 +353,8 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, free(conn); lws_set_wsi_user(wsi, NULL); http_lws_tx_completed(wsi); + } else { + lws_callback_on_writable(wsi); } return 0; } @@ -435,59 +435,45 @@ int ws_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { http_server_ctx_t *ctx = http_ctx_get(); - (void)user; + ws_session_t *session = user; switch (reason) { - case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: { - char token_buf[256] = {0}; - if (!ctx || !ctx->auth) return -1; - if (ws_copy_upgrade_token(wsi, token_buf, sizeof(token_buf)) != 0) - return -1; - if (!auth_validate_token(ctx->auth, token_buf)) - return -1; - return 0; - } + case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: + case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: + return ws_upgrade_allowed(ctx, wsi) ? 0 : -1; case LWS_CALLBACK_ESTABLISHED: { + if (!session) + return -1; int conn_id = ws_next_conn_id(); - lws_set_wsi_user(wsi, (void *)(intptr_t)conn_id); if (ws_register_conn(conn_id, (ws_conn_t)wsi) != 0) { fprintf(stderr, "shellclaw: ws: connection table full\n"); return -1; } + session->conn_id = conn_id; break; } - case LWS_CALLBACK_SERVER_WRITEABLE: { - int conn_id = (int)(intptr_t)lws_wsi_user(wsi); - if (conn_id <= 0) break; - ws_on_writable(wsi, conn_id); + case LWS_CALLBACK_SERVER_WRITEABLE: + if (session && session->conn_id > 0) + ws_on_writable(wsi, session->conn_id); break; - } case LWS_CALLBACK_RECEIVE: { - int conn_id = (int)(intptr_t)lws_wsi_user(wsi); - if (conn_id <= 0) break; - if (len > 0 && in) { - char *buf = malloc(len + 1); - if (buf) { - memcpy(buf, in, len); - buf[len] = '\0'; - cJSON *root = cJSON_Parse(buf); - free(buf); - if (root) { - cJSON *type = cJSON_GetObjectItem(root, "type"); - cJSON *text = cJSON_GetObjectItem(root, "text"); - if (cJSON_IsString(type) && strcmp(type->valuestring, "message") == 0 && - cJSON_IsString(text) && text->valuestring) - ws_push_incoming(conn_id, text->valuestring); - cJSON_Delete(root); - } - } + if (!session || session->conn_id <= 0) + break; + char *text = NULL; + int result = ws_rx_feed(&session->rx, in, len, lws_is_final_fragment(wsi), &text); + if (result < 0) + return -1; + if (result == 1) { + ws_push_incoming(session->conn_id, text); + free(text); } break; } - case LWS_CALLBACK_CLOSED: { - int conn_id = (int)(intptr_t)lws_wsi_user(wsi); - if (conn_id > 0) ws_unregister_conn(conn_id); + case LWS_CALLBACK_CLOSED: + if (session && session->conn_id > 0) { + ws_rx_clear(&session->rx); + ws_unregister_conn(session->conn_id); + } break; - } case LWS_CALLBACK_EVENT_WAIT_CANCELLED: /* wsi here is not a client socket. Mark real conns from our table. */ ws_on_service_cancel(); diff --git a/src/gateway/http_lws.h b/src/gateway/http_lws.h index 45954b39..5f6f3e8f 100644 --- a/src/gateway/http_lws.h +++ b/src/gateway/http_lws.h @@ -25,8 +25,6 @@ extern "C" { #define CONFIG_BODY_MAX 65536 #define BODY_BUF_SIZE CONFIG_BODY_MAX #define ASAP_BODY_MAX (1024 * 1024) -/** Per-callback WebChat RX. Must fit `{"type":"message","text":...}` at WS_TEXT_MAX. */ -#define WS_RX_BUFFER_SIZE (WS_TEXT_MAX + 64) enum http_method { HTTP_GET = 1, diff --git a/src/gateway/routes.c b/src/gateway/routes.c index da4e1db5..e53b9752 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -644,7 +644,8 @@ static void handle_cron_create(const char *body, size_t body_len, char *buf, siz agent_unlock(); cJSON_Delete(root); if (ret != 0) { - json_error(buf, size, status, 400, "Failed to create job"); + json_error(buf, size, status, 400, ret == CRON_INVALID_DESTINATION + ? "Invalid cron destination." : "Failed to create job"); return; } cJSON *resp_obj = cJSON_CreateObject(); diff --git a/src/gateway/ws.c b/src/gateway/ws.c index 11b68a02..0bce15e2 100644 --- a/src/gateway/ws.c +++ b/src/gateway/ws.c @@ -66,6 +66,7 @@ typedef struct ws_msg { typedef struct { ws_conn_t wsi; int conn_id; + int replies_only; } ws_conn_entry_t; static ws_conn_entry_t g_conns[MAX_CONNECTIONS]; @@ -132,7 +133,7 @@ int ws_next_conn_id(void) return atomic_fetch_add(&g_next_conn_id, 1) + 1; } -int ws_register_conn(int conn_id, ws_conn_t wsi) +static int ws_register_conn_with_mode(int conn_id, ws_conn_t wsi, int replies_only) { int registered = 0; pthread_mutex_lock(&g_mutex); @@ -140,6 +141,7 @@ int ws_register_conn(int conn_id, ws_conn_t wsi) if (g_conns[i].wsi == NULL) { g_conns[i].wsi = wsi; g_conns[i].conn_id = conn_id; + g_conns[i].replies_only = replies_only; registered = 1; break; } @@ -148,6 +150,25 @@ int ws_register_conn(int conn_id, ws_conn_t wsi) return registered ? 0 : -1; } +#ifdef SHELLCLAW_WS_TEST +int ws_test_register_reply_conn(int conn_id, ws_conn_t wsi) +{ + return ws_register_conn_with_mode(conn_id, wsi, 1); +} +#endif + +int ws_register_conn(int conn_id, ws_conn_t wsi) +{ + int replies_only = 0; +#ifndef SHELLCLAW_WS_TEST + /* libwebsockets keeps the request headers during the established callback. */ + char value[16]; + const char *view = lws_get_urlarg_by_name(wsi, "view=", value, sizeof(value)); + replies_only = view && strcmp(view, "chat") == 0; +#endif + return ws_register_conn_with_mode(conn_id, wsi, replies_only); +} + static void ws_free_outgoing(ws_msg_t *m) { if (!m) @@ -398,7 +419,7 @@ void ws_broadcast_text(const char *text) pthread_mutex_lock(&g_mutex); for (i = 0; i < MAX_CONNECTIONS; i++) { ws_msg_t *m; - if (!g_conns[i].wsi) + if (!g_conns[i].wsi || g_conns[i].replies_only) continue; if (g_outgoing_count >= MAX_QUEUE) break; diff --git a/src/gateway/ws.h b/src/gateway/ws.h index 0d0fcbae..d6259813 100644 --- a/src/gateway/ws.h +++ b/src/gateway/ws.h @@ -32,7 +32,7 @@ static inline int ws_text_payload_fits(size_t len_out) typedef void *ws_conn_t; /** - * Register a WebSocket connection. Called when connection is established. + * Register a WebSocket connection during the libwebsockets established callback. * * @param conn_id Unique connection ID (e.g. incrementing integer). * @param wsi libwebsockets wsi (stored as ws_conn_t). @@ -83,7 +83,7 @@ int ws_pop_incoming(char *session_id_out, size_t session_size, */ int ws_send_to(const char *session_id, const char *text); -/** Queue @p text for every connected WebSocket client. */ +/** Queue @p text for open WebSockets that receive broadcast events. */ void ws_broadcast_text(const char *text); /** diff --git a/src/gateway/ws_rx.c b/src/gateway/ws_rx.c new file mode 100644 index 00000000..552ae1e6 --- /dev/null +++ b/src/gateway/ws_rx.c @@ -0,0 +1,75 @@ +#include "gateway/ws_rx.h" +#include "cJSON.h" +#include +#include + +void ws_rx_clear(ws_rx_t *rx) +{ + free(rx->data); + *rx = (ws_rx_t){0}; +} + +static int ws_rx_append(ws_rx_t *rx, const void *chunk, size_t len) +{ + const size_t need = rx->len + len + 1; + if (need > rx->capacity) { + size_t capacity = rx->capacity * 2; + if (capacity < need) + capacity = need; + if (capacity > WS_RX_JSON_MAX + 1) + capacity = WS_RX_JSON_MAX + 1; + char *data = realloc(rx->data, capacity); + if (!data) + return -1; + rx->data = data; + rx->capacity = capacity; + } + memcpy(rx->data + rx->len, chunk, len); + rx->len += len; + rx->data[rx->len] = '\0'; + return 0; +} + +static int ws_rx_take_text(const ws_rx_t *rx, char **text_out) +{ + int result = 0; + const char *end = NULL; + cJSON *root = cJSON_ParseWithLengthOpts(rx->data, rx->len + 1, &end, 1); + if (root && end == rx->data + rx->len) { + const char *type = cJSON_GetStringValue(cJSON_GetObjectItem(root, "type")); + const char *text = cJSON_GetStringValue(cJSON_GetObjectItem(root, "text")); + const size_t len = text ? strlen(text) : 0; + if (type && strcmp(type, "message") == 0 && len > 0 && len <= WS_TEXT_MAX) { + *text_out = malloc(len + 1); + if (*text_out) { + memcpy(*text_out, text, len + 1); + result = 1; + } else { + result = -1; + } + } + } + cJSON_Delete(root); + return result; +} + +int ws_rx_feed(ws_rx_t *rx, const void *chunk, size_t len, int final, char **text_out) +{ + *text_out = NULL; + if (rx->discarding) { + rx->discarding = !final; + return 0; + } + if (len > WS_RX_JSON_MAX - rx->len) { + ws_rx_clear(rx); + rx->discarding = !final; + return 0; + } + if (len && ws_rx_append(rx, chunk, len) != 0) + return -1; + if (!final || !rx->len) + return 0; + const int result = ws_rx_take_text(rx, text_out); + ws_rx_clear(rx); + return result; +} diff --git a/src/gateway/ws_rx.h b/src/gateway/ws_rx.h new file mode 100644 index 00000000..129c4fd7 --- /dev/null +++ b/src/gateway/ws_rx.h @@ -0,0 +1,33 @@ +#ifndef SHELLCLAW_GATEWAY_WS_RX_H +#define SHELLCLAW_GATEWAY_WS_RX_H + +#include "gateway/ws.h" + +/** libwebsockets can deliver one message through multiple receive callbacks. */ +#define WS_RX_BUFFER_SIZE ((size_t)WS_TEXT_MAX + 64u) +/** JSON can expand each byte to six bytes. Allow extra space for field names. */ +#define WS_RX_JSON_MAX ((size_t)WS_TEXT_MAX * 6u + 64u) + +typedef struct { + char *data; + size_t len; + size_t capacity; + int discarding; +} ws_rx_t; + +/** The libwebsockets service thread owns this state. */ +typedef struct { + int conn_id; + ws_rx_t rx; +} ws_session_t; + +/** Release a partial message and reset @p rx. */ +void ws_rx_clear(ws_rx_t *rx); + +/** Feed a chunk into a zero-initialized receiver. + * @return 1 for a complete message. The caller frees @p text_out. + * 0 for an incomplete or discarded message, -1 on allocation failure. + */ +int ws_rx_feed(ws_rx_t *rx, const void *chunk, size_t len, int final, char **text_out); + +#endif diff --git a/src/hardware/hardware_camera.c b/src/hardware/hardware_camera.c index f7e57f9b..2abd9772 100644 --- a/src/hardware/hardware_camera.c +++ b/src/hardware/hardware_camera.c @@ -329,10 +329,10 @@ static int output_jpeg_valid(const char *path) return hdr[0] == 0xff && hdr[1] == 0xd8; } -static int build_jetson_csi_argv(char **argv, char *arg0, char *arg1, char *arg2, - char *arg_q, size_t arg_bufsz, unsigned int width, - unsigned int height, int sensor_id, int quality, - const char *out_path) +static int build_jetson_csi_argv(char **argv, char *arg0, char *arg1, char *location, + size_t location_size, char *arg_q, size_t arg_bufsz, + unsigned int width, unsigned int height, int sensor_id, + int quality, const char *out_path) { int n; n = snprintf(arg0, arg_bufsz, "sensor-id=%d", sensor_id); @@ -343,8 +343,8 @@ static int build_jetson_csi_argv(char **argv, char *arg0, char *arg1, char *arg2 height); if (n < 0 || (size_t)n >= arg_bufsz) return -1; - n = snprintf(arg2, arg_bufsz, "location=%s", out_path); - if (n < 0 || (size_t)n >= arg_bufsz) + n = snprintf(location, location_size, "location=%s", out_path); + if (n < 0 || (size_t)n >= location_size) return -1; /* nvjpegenc exposes a 0-100 quality property; emit it as its own argv token. */ n = snprintf(arg_q, arg_bufsz, "quality=%d", quality); @@ -362,7 +362,7 @@ static int build_jetson_csi_argv(char **argv, char *arg0, char *arg1, char *arg2 argv[9] = arg_q; argv[10] = "!"; argv[11] = "filesink"; - argv[12] = arg2; + argv[12] = location; argv[13] = NULL; return 0; } @@ -443,7 +443,7 @@ int hardware_camera_output_allowed(const char *path) { if (!path || path[0] == '\0') return 1; - return path_inside_workspace(path); + return strlen(path) < PATH_MAX && path_inside_workspace(path); } void hardware_camera_shutdown(void) @@ -520,6 +520,11 @@ static int prepare_capture_output_path(const char *output_path, char *out_path, size_t errbufsz) { if (output_path && output_path[0] != '\0') { + size_t length = strlen(output_path); + if (length >= out_pathsz) { + set_err(errbuf, errbufsz, "camera: output path too long"); + return -1; + } if (!path_chars_safe(output_path)) { set_err(errbuf, errbufsz, "camera: unsafe output path"); return -1; @@ -528,7 +533,7 @@ static int prepare_capture_output_path(const char *output_path, char *out_path, set_err(errbuf, errbufsz, "camera: path outside workspace"); return -1; } - snprintf(out_path, out_pathsz, "%s", output_path); + memcpy(out_path, output_path, length + 1); *auto_output = 0; return 0; } @@ -550,7 +555,7 @@ static int build_argv_and_run(camera_cli_kind_t kind, unsigned int width, char *argv[HARDWARE_CAMERA_ARGV_MAX]; char arg0[ARG_BUF_SZ]; char arg1[CAPS_BUF_SZ]; - char arg2[ARG_BUF_SZ]; + char location[sizeof("location=") - 1 + PATH_MAX]; char arg_q[ARG_BUF_SZ]; char rpi_wbuf[16]; char rpi_hbuf[16]; @@ -558,8 +563,9 @@ static int build_argv_and_run(camera_cli_kind_t kind, unsigned int width, memset(argv, 0, sizeof(argv)); if (kind == CAMERA_CLI_JETSON_CSI) { - if (build_jetson_csi_argv(argv, arg0, arg1, arg2, arg_q, ARG_BUF_SZ, width, - height, sensor_id, quality, out_path) != 0) { + if (build_jetson_csi_argv(argv, arg0, arg1, location, sizeof(location), + arg_q, ARG_BUF_SZ, width, height, sensor_id, + quality, out_path) != 0) { set_err(errbuf, errbufsz, HARDWARE_CAMERA_ERR_UNAVAILABLE); return -1; } @@ -595,7 +601,7 @@ int hardware_camera_capture(board_id_t board, const char *camera_type, int video_index, const char *output_path, char *result_path, size_t result_pathsz, char *errbuf, size_t errbufsz) { - char out_path[256]; + char out_path[PATH_MAX]; unsigned int width = 0; unsigned int height = 0; camera_cli_kind_t kind = CAMERA_CLI_NONE; @@ -608,6 +614,12 @@ int hardware_camera_capture(board_id_t board, const char *camera_type, if (prepare_capture_output_path(output_path, out_path, sizeof(out_path), &auto_output, errbuf, errbufsz) != 0) return -1; + if (strlen(out_path) >= result_pathsz) { + set_err(errbuf, errbufsz, "camera: result buffer too small for output path"); + if (auto_output) + unlink(out_path); + return -1; + } return build_argv_and_run(kind, width, height, sensor_id, video_index, quality, auto_output, out_path, result_path, result_pathsz, errbuf, errbufsz); diff --git a/src/hardware/hardware_camera.h b/src/hardware/hardware_camera.h index 67156f6a..3f5d9dbd 100644 --- a/src/hardware/hardware_camera.h +++ b/src/hardware/hardware_camera.h @@ -38,8 +38,8 @@ int hardware_camera_is_available(void); * @param sensor_id CSI sensor index (Jetson nvarguscamerasrc). * @param video_index USB /dev/videoN index. * @param output_path Optional output path; NULL selects a secure temp file. - * @param result_path Buffer for the JPEG path written on success. - * @param result_pathsz Size of @p result_path. + * @param result_path Buffer that receives the complete JPEG path on success. + * @param result_pathsz Buffer size in bytes. Capture requires room for the path and its terminating null byte. * @param errbuf Error message on failure (e.g. #HARDWARE_CAMERA_ERR_UNAVAILABLE). * @param errbufsz Size of @p errbuf. * @return 0 on success, -1 on error. diff --git a/src/providers/anthropic.c b/src/providers/anthropic.c index 561f477f..9e7c107a 100644 --- a/src/providers/anthropic.c +++ b/src/providers/anthropic.c @@ -147,30 +147,25 @@ static int append_text_block(char **text, size_t *text_len, size_t *text_cap, co return 0; } -static int append_tool_use(provider_tool_call_t **tool_calls, size_t *tool_count, - size_t *tool_cap, cJSON *block) +static const char *append_tool_use(provider_tool_call_t **tool_calls, size_t *tool_count, + size_t *tool_cap, const cJSON *block) { - provider_tool_call_t *tc; - cJSON *id_item; - cJSON *name_item; - cJSON *input_item; + const cJSON *id = cJSON_GetObjectItem(block, "id"); + const cJSON *name = cJSON_GetObjectItem(block, "name"); + const cJSON *input = cJSON_GetObjectItem(block, "input"); + if (!cJSON_IsString(id) || !id->valuestring[0] || + !cJSON_IsString(name) || !name->valuestring[0] || !cJSON_IsObject(input)) + return "Anthropic response has an invalid tool_use block"; if (ensure_tool_cap(tool_calls, tool_cap, *tool_count) != 0) - return -1; - tc = &(*tool_calls)[*tool_count]; - tc->id = NULL; - tc->name = NULL; - tc->arguments = NULL; - id_item = cJSON_GetObjectItem(block, "id"); - name_item = cJSON_GetObjectItem(block, "name"); - input_item = cJSON_GetObjectItem(block, "input"); - if (cJSON_IsString(id_item)) - tc->id = provider_dup_str(id_item->valuestring); - if (cJSON_IsString(name_item)) - tc->name = provider_dup_str(name_item->valuestring); - if (input_item) - tc->arguments = cJSON_PrintUnformatted(input_item); + return "Out of memory growing Anthropic tool_use array"; + provider_tool_call_t *tc = &(*tool_calls)[*tool_count]; + tc->id = provider_dup_str(id->valuestring); + tc->name = provider_dup_str(name->valuestring); + tc->arguments = cJSON_PrintUnformatted(input); (*tool_count)++; - return 0; + if (!tc->id || !tc->name || !tc->arguments) + return "Out of memory reading Anthropic tool_use block"; + return NULL; } static int parse_response_body(const char *response_buf, provider_response_t *response) @@ -198,10 +193,8 @@ static int parse_response_body(const char *response_buf, provider_response_t *re return -1; } content = cJSON_GetObjectItem(root, "content"); - if (!cJSON_IsArray(content)) { - cJSON_Delete(root); - return 0; - } + if (!cJSON_IsArray(content)) + return parse_fail(root, NULL, NULL, 0, response, "Anthropic response has no content array"); text = malloc(text_cap); if (!text) return parse_fail(root, NULL, NULL, 0, response, @@ -212,18 +205,23 @@ static int parse_response_body(const char *response_buf, provider_response_t *re return parse_fail(root, text, NULL, 0, response, "Out of memory growing Anthropic tool_use array"); cJSON_ArrayForEach(block, content) { - cJSON *type_item = cJSON_GetObjectItem(block, "type"); - const char *type = cJSON_IsString(type_item) ? type_item->valuestring : NULL; - if (type && strcmp(type, "text") == 0) { - cJSON *text_item = cJSON_GetObjectItem(block, "text"); - const char *t = cJSON_IsString(text_item) ? text_item->valuestring : ""; - if (append_text_block(&text, &text_len, &text_cap, t) != 0) + const cJSON *type_item = cJSON_GetObjectItem(block, "type"); + if (!cJSON_IsString(type_item) || !type_item->valuestring[0]) + return parse_fail(root, text, tool_calls, tool_count, response, + "Anthropic content block has no type"); + const char *type = type_item->valuestring; + if (strcmp(type, "text") == 0) { + const cJSON *text_item = cJSON_GetObjectItem(block, "text"); + if (!cJSON_IsString(text_item)) return parse_fail(root, text, tool_calls, tool_count, response, - "Out of memory growing Anthropic text buffer"); - } else if (type && strcmp(type, "tool_use") == 0) { - if (append_tool_use(&tool_calls, &tool_count, &tool_cap, block) != 0) + "Anthropic response has an invalid text block"); + if (append_text_block(&text, &text_len, &text_cap, text_item->valuestring) != 0) return parse_fail(root, text, tool_calls, tool_count, response, - "Out of memory growing Anthropic tool_use array"); + "Out of memory growing Anthropic text buffer"); + } else if (strcmp(type, "tool_use") == 0) { + const char *error = append_tool_use(&tool_calls, &tool_count, &tool_cap, block); + if (error) + return parse_fail(root, text, tool_calls, tool_count, response, error); } } cJSON_Delete(root); @@ -336,7 +334,7 @@ static int append_assistant_tool_content(cJSON *msg, const provider_message_t *m size_t k; if (!content_arr) return -1; - if (message->content && message->content[0] != '\0') { + if (!provider_text_is_blank(message->content)) { cJSON *text_block = cJSON_CreateObject(); if (!text_block) { cJSON_Delete(content_arr); @@ -390,8 +388,11 @@ static int append_anthropic_messages(cJSON *msg_arr, const provider_message_t *m if (append_assistant_tool_content(msg, &messages[i]) != 0) return -1; } else { - cJSON_AddItemToObject(msg, "content", - cJSON_CreateString(messages[i].content ? messages[i].content : "")); + const char *text = messages[i].content ? messages[i].content : ""; + /* Anthropic rejects blank text in standalone assistant messages. */ + if (strcmp(role, "assistant") == 0 && provider_text_is_blank(text)) + text = "The model returned no text."; + cJSON_AddItemToObject(msg, "content", cJSON_CreateString(text)); } } return 0; diff --git a/src/providers/provider.h b/src/providers/provider.h index 9bceb973..8e3ea993 100644 --- a/src/providers/provider.h +++ b/src/providers/provider.h @@ -72,9 +72,12 @@ void provider_set_error(provider_response_t *response, const char *msg); /** strdup-equivalent for provider use. Returns NULL on NULL input. */ char *provider_dup_str(const char *s); +/** Return 1 if @p text is NULL, empty, or contains only ASCII whitespace. */ +int provider_text_is_blank(const char *text); + /** * Parse OpenAI-style chat/completions JSON into @p response. Caller must provider_response_clear on success. - * Returns -1 on invalid JSON or API error object. + * Returns -1 if the API reports an error or the response is invalid. */ int provider_parse_chat_completions_json(const char *response_body, provider_response_t *response); diff --git a/src/providers/provider_common.c b/src/providers/provider_common.c index de830f61..d7c62c7f 100644 --- a/src/providers/provider_common.c +++ b/src/providers/provider_common.c @@ -60,6 +60,11 @@ void provider_set_error(provider_response_t *response, const char *msg) response->content = msg ? provider_dup_str(msg) : NULL; } +int provider_text_is_blank(const char *text) +{ + return !text || text[strspn(text, " \t\r\n\v\f")] == '\0'; +} + char *provider_dup_str(const char *s) { if (!s) return NULL; @@ -142,6 +147,33 @@ int provider_error_allows_fallback_retry(const char *msg) return 1; } +static const char *parse_openai_tool_calls(const cJSON *items, size_t count, + provider_response_t *response) +{ + const cJSON *item; + size_t index = 0; + response->tool_calls = calloc(count, sizeof(*response->tool_calls)); + if (!response->tool_calls) + return "Out of memory reading OpenAI tool calls"; + response->tool_calls_count = count; + cJSON_ArrayForEach(item, items) { + const cJSON *id = cJSON_GetObjectItem(item, "id"); + const cJSON *function = cJSON_GetObjectItem(item, "function"); + const cJSON *name = cJSON_GetObjectItem(function, "name"); + const cJSON *arguments = cJSON_GetObjectItem(function, "arguments"); + if (!cJSON_IsString(id) || !id->valuestring[0] || !cJSON_IsObject(function) || + !cJSON_IsString(name) || !name->valuestring[0] || !cJSON_IsString(arguments)) + return "OpenAI message has an invalid function tool call"; + provider_tool_call_t *call = &response->tool_calls[index++]; + call->id = provider_dup_str(id->valuestring); + call->name = provider_dup_str(name->valuestring); + call->arguments = provider_dup_str(arguments->valuestring); + if (!call->id || !call->name || !call->arguments) + return "Out of memory reading OpenAI tool call"; + } + return NULL; +} + int provider_parse_chat_completions_json(const char *response_body, provider_response_t *response) { cJSON *root; @@ -171,53 +203,45 @@ int provider_parse_chat_completions_json(const char *response_body, provider_res } choices = cJSON_GetObjectItem(root, "choices"); if (!cJSON_IsArray(choices) || cJSON_GetArraySize(choices) == 0) { + provider_set_error(response, "OpenAI response has no completion choices"); cJSON_Delete(root); - return 0; + return -1; } choice = cJSON_GetArrayItem(choices, 0); msg_obj = cJSON_GetObjectItem(choice, "message"); if (!cJSON_IsObject(msg_obj)) { + provider_set_error(response, "OpenAI completion choice has no message"); cJSON_Delete(root); - return 0; + return -1; } - response->content = NULL; - response->tool_calls = NULL; - response->tool_calls_count = 0; content_item = cJSON_GetObjectItem(msg_obj, "content"); - if (cJSON_IsString(content_item) && content_item->valuestring) - response->content = provider_dup_str(content_item->valuestring); - else - response->content = malloc(1); - if (response->content && !cJSON_IsString(content_item)) - response->content[0] = '\0'; tool_calls_arr = cJSON_GetObjectItem(msg_obj, "tool_calls"); - if (cJSON_IsArray(tool_calls_arr)) { - int n = cJSON_GetArraySize(tool_calls_arr); - if (n > 0) { - provider_tool_call_t *calls = malloc((size_t)n * sizeof(provider_tool_call_t)); - if (calls) { - for (int i = 0; i < n; i++) { - cJSON *tc = cJSON_GetArrayItem(tool_calls_arr, i); - cJSON *id_item; - cJSON *fn; - calls[i].id = NULL; - calls[i].name = NULL; - calls[i].arguments = NULL; - id_item = cJSON_GetObjectItem(tc, "id"); - fn = cJSON_GetObjectItem(tc, "function"); - if (cJSON_IsString(id_item)) calls[i].id = provider_dup_str(id_item->valuestring); - if (cJSON_IsObject(fn)) { - cJSON *name_item = cJSON_GetObjectItem(fn, "name"); - cJSON *args_item = cJSON_GetObjectItem(fn, "arguments"); - if (cJSON_IsString(name_item)) calls[i].name = provider_dup_str(name_item->valuestring); - if (cJSON_IsString(args_item)) calls[i].arguments = provider_dup_str(args_item->valuestring); - } - } - response->tool_calls = calls; - response->tool_calls_count = (size_t)n; - } - } + if (tool_calls_arr && !cJSON_IsNull(tool_calls_arr) && !cJSON_IsArray(tool_calls_arr)) { + provider_set_error(response, "OpenAI tool_calls must be an array or null"); + cJSON_Delete(root); + return -1; } + size_t tool_count = (size_t)cJSON_GetArraySize(tool_calls_arr); + if (!cJSON_IsString(content_item) && !cJSON_IsNull(content_item) && + (content_item || tool_count == 0)) { + provider_set_error(response, "OpenAI message has invalid content"); + cJSON_Delete(root); + return -1; + } + response->content = provider_dup_str(cJSON_IsString(content_item) ? content_item->valuestring : ""); + response->tool_calls = NULL; + response->tool_calls_count = 0; + if (!response->content) { + provider_set_error(response, "Out of memory reading OpenAI message"); + cJSON_Delete(root); + return -1; + } + const char *error = tool_count ? parse_openai_tool_calls(tool_calls_arr, tool_count, response) : NULL; cJSON_Delete(root); + if (error) { + provider_response_clear(response); + provider_set_error(response, error); + return -1; + } return 0; } diff --git a/src/sandbox/sandbox.c b/src/sandbox/sandbox.c index fefddc54..f6dda8ff 100644 --- a/src/sandbox/sandbox.c +++ b/src/sandbox/sandbox.c @@ -6,12 +6,11 @@ * first when unprivileged). Isolation failure is reported on a control pipe, * not via sh-compatible exit codes. dup2, chdir, PID-1 fork, and workspace * setup failures write that byte before exiting; a 0-byte read is success. - * After CLONE_NEWPID, fork so the command - * is PID 1 (unshare does not move the caller). That child fchdir's the - * workspace (Landlock cannot walk `/tmp` after restrict_self), remounts - * procfs, applies Landlock, sets PR_SET_PDEATHSIG, and closes fds >= 3 - * so a timeout SIGKILL of the isolator cannot leave the command under - * host init. The isolator joins its cgroup before the command fork so + * After CLONE_NEWPID, fork so the command is PID 1. That child remounts + * procfs, enters the workspace, and applies the filesystem policy. It sets + * PR_SET_PDEATHSIG so a timeout cannot leave the command under host init. + * The child closes inherited file descriptors before exec. + * The isolator joins its cgroup before the command fork so * memory.max and cpu.max apply to sh -c. The command process then * replaces the inherited environment so provider keys and bot tokens * are not readable via printenv. Limits degrade if unavailable. @@ -38,6 +37,7 @@ #include #ifdef __linux__ +#include #include #include #include @@ -51,6 +51,7 @@ #define PIPE_POLL_SLICE_MS 500 #define SANDBOX_ISO_NS 1 #define SANDBOX_ISO_LL 2 +#define SANDBOX_ISO_MOUNTS 3 #ifdef __linux__ @@ -243,7 +244,7 @@ static int unshare_isolation_namespaces(void) return 0; } -static int isolate_namespaces(void) +SANDBOX_UNIT int sandbox_isolate_namespaces(void) { if (unshare_isolation_namespaces() == 0) return 0; @@ -274,16 +275,109 @@ static int enter_workspace_cwd(const char *workspace) return 0; } +#if defined(__NR_open_tree) && defined(__NR_mount_setattr) && defined(__NR_move_mount) +/* Mount UAPI for builds with an older libc. */ +#ifndef MOUNT_ATTR_SIZE_VER0 +#define MOUNT_ATTR_RDONLY 0x00000001 +#define MOUNT_ATTR_SIZE_VER0 32 +struct mount_attr { + __u64 attr_set; + __u64 attr_clr; + __u64 propagation; + __u64 userns_fd; +}; +#endif +#ifndef AT_RECURSIVE +#define AT_RECURSIVE 0x8000 +#endif +#ifndef OPEN_TREE_CLONE +#define OPEN_TREE_CLONE 1 +#endif +#ifndef MOVE_MOUNT_F_EMPTY_PATH +#define MOVE_MOUNT_F_EMPTY_PATH 0x00000004 +#endif +#ifndef MOVE_MOUNT_T_EMPTY_PATH +#define MOVE_MOUNT_T_EMPTY_PATH 0x00000040 +#endif + +static int drop_mount_admin(void) +{ + struct __user_cap_header_struct header = {.version = _LINUX_CAPABILITY_VERSION_3}; + struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3]; + unsigned int index = CAP_TO_INDEX(CAP_SYS_ADMIN); + __u32 mask = ~CAP_TO_MASK(CAP_SYS_ADMIN); + + if (prctl(PR_CAPBSET_DROP, CAP_SYS_ADMIN, 0, 0, 0) != 0 || + syscall(__NR_capget, &header, caps) != 0) + return -1; + caps[index].effective &= mask; + caps[index].permitted &= mask; + caps[index].inheritable &= mask; + return syscall(__NR_capset, &header, caps) == 0 ? 0 : -1; +} +#endif + +/* The caller must first create a private mount namespace. */ +SANDBOX_UNIT int sandbox_seal_workspace_mounts(const char *workspace) +{ +#if defined(__NR_open_tree) && defined(__NR_mount_setattr) && defined(__NR_move_mount) + const struct mount_attr attr = {.attr_set = MOUNT_ATTR_RDONLY}; + struct stat root_stat; + struct stat workspace_stat; + int ws_fd; + int clone_fd; + int rc = -1; + + ws_fd = open(workspace, O_PATH | O_DIRECTORY | O_CLOEXEC); + if (ws_fd < 0) + return -1; + /* The root directory cannot be the writable exception. */ + if (fstat(ws_fd, &workspace_stat) != 0 || stat("/", &root_stat) != 0 || + (root_stat.st_dev == workspace_stat.st_dev && + root_stat.st_ino == workspace_stat.st_ino)) { + close(ws_fd); + return -1; + } + /* The detached copy keeps the workspace mount flags and submounts. */ + clone_fd = (int)syscall(__NR_open_tree, ws_fd, "", + AT_EMPTY_PATH | AT_RECURSIVE | OPEN_TREE_CLONE | O_CLOEXEC); + if (clone_fd >= 0) { + if (syscall(__NR_mount_setattr, AT_FDCWD, "/", AT_RECURSIVE, &attr, + (size_t)MOUNT_ATTR_SIZE_VER0) == 0 && + syscall(__NR_move_mount, clone_fd, "", ws_fd, "", + MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_EMPTY_PATH) == 0 && + fchdir(clone_fd) == 0 && drop_mount_admin() == 0) + rc = 0; + close(clone_fd); + } + close(ws_fd); + return rc; +#else + (void)workspace; + return -1; +#endif +} + static unsigned char setup_command_process(const char *workspace) { + int needs_guard; + if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0) return SANDBOX_ISO_NS; - if (workspace && workspace[0] && enter_workspace_cwd(workspace) != 0) - return SANDBOX_ISO_NS; if (remount_procfs() != 0) return SANDBOX_ISO_NS; - if (workspace && workspace[0] && - sandbox_landlock_restrict_to_workspace(workspace) != 0) + if (!workspace || !workspace[0]) + return 0; + needs_guard = sandbox_landlock_needs_mount_guard(); + if (needs_guard < 0) + return SANDBOX_ISO_LL; + if (needs_guard) { + if (sandbox_seal_workspace_mounts(workspace) != 0) + return SANDBOX_ISO_MOUNTS; + } else if (enter_workspace_cwd(workspace) != 0) { + return SANDBOX_ISO_NS; + } + if (sandbox_landlock_restrict_to_workspace(".") != 0) return SANDBOX_ISO_LL; return 0; } @@ -330,7 +424,7 @@ static unsigned char setup_child_process(int pipe_wr, const char *workspace) #ifdef __linux__ (void)workspace; (void)setsid(); - if (isolate_namespaces() != 0) + if (sandbox_isolate_namespaces() != 0) return SANDBOX_ISO_NS; if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) return SANDBOX_ISO_NS; @@ -386,6 +480,8 @@ static int report_isolation_failure(char *out, size_t out_cap, unsigned char iso { if (iso == SANDBOX_ISO_LL) snprintf(out, out_cap, "sandbox: Landlock filesystem bound failed"); + else if (iso == SANDBOX_ISO_MOUNTS) + snprintf(out, out_cap, "sandbox: read-only mount guard failed"); else snprintf(out, out_cap, "sandbox: namespace isolation failed"); return -1; diff --git a/src/sandbox/sandbox_landlock.c b/src/sandbox/sandbox_landlock.c index 4dac6a73..38cdee0b 100644 --- a/src/sandbox/sandbox_landlock.c +++ b/src/sandbox/sandbox_landlock.c @@ -35,6 +35,11 @@ int sandbox_landlock_prepare(const char *workspace) } #else +#ifndef LANDLOCK_ACCESS_FS_TRUNCATE +/* This UAPI bit also applies to binaries built with older headers. */ +#define LANDLOCK_ACCESS_FS_TRUNCATE (1ULL << 14) +#endif + #ifndef LANDLOCK_ACCESS_FS_IOCTL_DEV #define LANDLOCK_ACCESS_FS_IOCTL_DEV (1ULL << 15) #endif @@ -56,6 +61,19 @@ static __u64 landlock_abi1_fs_rights(void) LANDLOCK_ACCESS_FS_MAKE_SYM; } +static int landlock_abi(void) +{ + return (int)syscall(__NR_landlock_create_ruleset, NULL, 0, + LANDLOCK_CREATE_RULESET_VERSION); +} + +int sandbox_landlock_needs_mount_guard(void) +{ + int abi = landlock_abi(); + + return abi < 1 ? -1 : abi < 3; +} + static int landlock_handled_fs(__u64 *handled_out) { int abi; @@ -63,8 +81,7 @@ static int landlock_handled_fs(__u64 *handled_out) if (!handled_out) return -1; - abi = (int)syscall(__NR_landlock_create_ruleset, NULL, 0, - LANDLOCK_CREATE_RULESET_VERSION); + abi = landlock_abi(); if (abi < 1) return -1; handled = landlock_abi1_fs_rights(); @@ -72,10 +89,8 @@ static int landlock_handled_fs(__u64 *handled_out) if (abi >= 2) handled |= LANDLOCK_ACCESS_FS_REFER; #endif -#ifdef LANDLOCK_ACCESS_FS_TRUNCATE if (abi >= 3) handled |= LANDLOCK_ACCESS_FS_TRUNCATE; -#endif if (abi >= 5) handled |= LANDLOCK_ACCESS_FS_IOCTL_DEV; *handled_out = handled; @@ -141,9 +156,7 @@ static __u64 mask_workspace_access(__u64 handled) #ifdef LANDLOCK_ACCESS_FS_REFER access |= (LANDLOCK_ACCESS_FS_REFER & handled); #endif -#ifdef LANDLOCK_ACCESS_FS_TRUNCATE access |= (LANDLOCK_ACCESS_FS_TRUNCATE & handled); -#endif return access; } @@ -185,9 +198,7 @@ static int landlock_make_ruleset(const char *workspace) rw_file = (LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE) & handled; -#ifdef LANDLOCK_ACCESS_FS_TRUNCATE rw_file |= (LANDLOCK_ACCESS_FS_TRUNCATE & handled); -#endif memset(&attr, 0, sizeof(attr)); attr.handled_access_fs = handled; ruleset_fd = (int)syscall(__NR_landlock_create_ruleset, &attr, @@ -243,7 +254,7 @@ int sandbox_landlock_restrict_to_workspace(const char *workspace) return -1; rc = syscall(__NR_landlock_restrict_self, fd, 0); close(fd); - return (rc == 0) ? 0 : -1; + return rc == 0 ? 0 : -1; } #endif /* __linux__ */ diff --git a/src/sandbox/sandbox_landlock.h b/src/sandbox/sandbox_landlock.h index ff488190..75ef1536 100644 --- a/src/sandbox/sandbox_landlock.h +++ b/src/sandbox/sandbox_landlock.h @@ -16,7 +16,8 @@ extern "C" { * Restrict the calling thread to @p workspace (RW) plus a small RO/exec set * needed by /bin/sh. Empty @p workspace skips Landlock (returns 0). * - * @param workspace Absolute workspace directory, or NULL/empty to skip. + * Use a private read-only mount guard for commands on Landlock ABI 1 or 2. + * @param workspace Workspace directory, or NULL/empty to skip. * @return 0 on success or skip; -1 if the ruleset cannot apply. * * Example: sandbox_landlock_restrict_to_workspace("/home/user/.shellclaw"); @@ -32,6 +33,14 @@ int sandbox_landlock_restrict_to_workspace(const char *workspace); */ int sandbox_landlock_prepare(const char *workspace); +#ifdef __linux__ +/** + * Check whether the kernel needs a mount guard to restrict file truncation. + * @return 1 for ABI 1 or 2, 0 for ABI 3 or later, -1 if Landlock is unavailable. + */ +int sandbox_landlock_needs_mount_guard(void); +#endif + #ifdef __cplusplus } #endif diff --git a/src/tools/cron.c b/src/tools/cron.c index bf40b15a..806276cb 100644 --- a/src/tools/cron.c +++ b/src/tools/cron.c @@ -9,6 +9,7 @@ #include "core/agent.h" #include "core/memory.h" #include "channels/channel.h" +#include "channels/heartbeat.h" #include "core/config.h" #include "cJSON.h" #include @@ -181,13 +182,124 @@ int cron_is_one_shot(const char *schedule) return strncmp(schedule, CRON_PREFIX_AT, strlen(CRON_PREFIX_AT)) == 0; } +static const char *cron_default(const char *value, const char *fallback) +{ + return value && value[0] ? value : fallback; +} + +static const char *cron_skip_prefix(const char *value, const char *prefix) +{ + size_t len = strlen(prefix); + return strncmp(value, prefix, len) == 0 ? value + len : value; +} + +static int cron_decimal_id(const char *id, unsigned long long max) +{ + unsigned long long value; + if (!id[0] || id[strspn(id, "0123456789")] != '\0') + return 0; + errno = 0; + value = strtoull(id, NULL, 10); + return errno != ERANGE && value > 0 && value <= max; +} + +typedef enum { + CRON_TARGET_INVALID, + CRON_TARGET_DEFERRED, + CRON_TARGET_READY, +} cron_target_status_t; + +typedef enum { + CRON_TARGET_NEW, + CRON_TARGET_STORED, +} cron_target_origin_t; + +typedef struct { + const channel_t *channel; + char recipient[128]; +} cron_delivery_t; + +static cron_target_status_t cron_resolve_target(const char *channel, const char *recipient, + cron_target_origin_t origin, cron_delivery_t *delivery) +{ + const channel_t *dest; + const char *id; + const char *prefix = ""; + + channel = cron_default(channel, "cli"); + recipient = cron_default(recipient, "default"); + if (strlen(channel) >= sizeof(((cron_job_row_t *)0)->channel) || + strlen(recipient) >= sizeof(((cron_job_row_t *)0)->recipient) || + strchr(channel, ':') || strcmp(channel, "cron") == 0 || strcmp(channel, "webchat") == 0) + return CRON_TARGET_INVALID; + + dest = channel_get_by_name(channel); + if (dest == channel_cron_get() || (dest && dest->name && strcmp(dest->name, "webchat") == 0)) + return CRON_TARGET_INVALID; + if (strcmp(channel, "heartbeat") == 0 || dest == channel_heartbeat_get()) { + dest = dest == channel_heartbeat_get() ? heartbeat_local_delivery() : NULL; + if (origin == CRON_TARGET_NEW && (!dest || !dest->send)) + return CRON_TARGET_INVALID; + id = "default"; + } else if (strcmp(channel, "discord") == 0) { + prefix = "discord:c:"; + id = cron_skip_prefix(cron_skip_prefix(recipient, "discord:"), "c:"); + if (!cron_decimal_id(id, ULLONG_MAX)) + return CRON_TARGET_INVALID; + } else if (strcmp(channel, "telegram") == 0) { + id = cron_skip_prefix(recipient, "telegram:"); + if (id[0] == '@') { + const char *valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; + if (!id[1] || id[1 + strspn(id + 1, valid)] != '\0') + return CRON_TARGET_INVALID; + } else if (!cron_decimal_id(id + (id[0] == '-'), LLONG_MAX)) { + return CRON_TARGET_INVALID; + } + } else { + if (origin == CRON_TARGET_NEW && strcmp(channel, "cli") != 0 && (!dest || !dest->send)) + return CRON_TARGET_INVALID; + id = recipient; + } + if (!dest || !dest->send) + return CRON_TARGET_DEFERRED; + if (delivery) { + int n = snprintf(delivery->recipient, sizeof(delivery->recipient), "%s%s", prefix, id); + if (n < 0 || (size_t)n >= sizeof(delivery->recipient)) + return CRON_TARGET_INVALID; + delivery->channel = dest; + } + return CRON_TARGET_READY; +} + +static cron_target_status_t cron_stored_target(const char *channel, const char *recipient, + int channel_truncated, int recipient_truncated) +{ + if (channel_truncated) + return CRON_TARGET_INVALID; + if (recipient_truncated) { + /* Only the native local channels ignore a legacy recipient. */ + const char *name = cron_default(channel, "cli"); + const channel_t *dest = channel_get_by_name(name); + const channel_t *local = NULL; + if (strcmp(name, "cli") == 0) + local = channel_cli_get(); + else if (strcmp(name, "heartbeat") == 0) + local = channel_heartbeat_get(); + if (!local || (dest && dest != local)) + return CRON_TARGET_INVALID; + } + return cron_resolve_target(channel, recipient, CRON_TARGET_STORED, NULL); +} + int cron_create_job(const char *schedule, const char *message, const char *channel, const char *recipient, char *id_out, size_t id_size) { if (!schedule || !message || !id_out || id_size == 0) return -1; - const char *ch = channel ? channel : "cli"; - const char *rec = recipient ? recipient : "default"; + const char *ch = cron_default(channel, "cli"); + const char *rec = cron_default(recipient, "default"); + if (cron_resolve_target(ch, rec, CRON_TARGET_NEW, NULL) == CRON_TARGET_INVALID) + return CRON_INVALID_DESTINATION; if (id_out[0] == '\0') { unsigned char rnd[2]; if (crypto_read_urandom(rnd, sizeof(rnd)) != 0) return -1; @@ -342,22 +454,42 @@ static void cron_sleep_ms(long wait_ms) nanosleep(&remain, NULL); } -/** Prefer a due job outside its re-offer window so one stuck job cannot hide the rest. */ +/** Find a ready job, even when earlier jobs wait for a channel. */ static int cron_pick_due_row(long long now, int timeout_ms, cron_job_row_t *row) { cron_due_key_t keys[CRON_DUE_SCAN_MAX]; + cron_due_key_t cursor; + const cron_due_key_t *after = NULL; + char first[sizeof(keys[0].id)] = {0}; struct timespec mono; int n; - int wait_for_first = 0; + int deferred = 0; + int found; if (clock_gettime(CLOCK_MONOTONIC, &mono) != 0) memset(&mono, 0, sizeof(mono)); /* HTTP dashboard routes use this same connection (SQLITE_THREADSAFE=0). * Drop the lock before the re-offer sleep so that thread is not stalled. */ agent_lock(); - n = cron_job_list_due(now, keys, CRON_DUE_SCAN_MAX); - if (n > 0) { + do { + n = cron_job_list_due(now, after, keys, CRON_DUE_SCAN_MAX); for (int i = 0; i < n; i++) { + cron_target_status_t target = cron_stored_target(keys[i].channel, keys[i].recipient, + keys[i].channel_truncated, keys[i].recipient_truncated); + if (target == CRON_TARGET_INVALID) { + if (cron_job_disable(keys[i].id) == 0) + fprintf(stderr, "shellclaw: cron: disabled job '%s' with an invalid destination\n", + keys[i].id); + else + deferred = 1; + continue; + } + if (target == CRON_TARGET_DEFERRED) { + deferred = 1; + continue; + } + if (!first[0]) + memcpy(first, keys[i].id, sizeof(first)); if (!cron_due_is_returnable(keys[i].id, timeout_ms, &mono)) continue; if (cron_job_get_by_id(keys[i].id, row) == 1) { @@ -365,21 +497,31 @@ static int cron_pick_due_row(long long now, int timeout_ms, cron_job_row_t *row) return 1; } } - if (cron_job_get_by_id(keys[0].id, row) == 1) - wait_for_first = 1; - } + if (n == CRON_DUE_SCAN_MAX) { + cursor = keys[n - 1]; + after = &cursor; + } + } while (n == CRON_DUE_SCAN_MAX); agent_unlock(); - if (!wait_for_first) - return 0; - /* An id that never fit in the table has no age, so wait_remaining would return immediately. */ - { - long age = 0; - if (cron_offer_age_ms(row->id, &mono, &age)) - cron_wait_remaining(row->id, timeout_ms); - else + if (!first[0]) { + if (deferred) cron_sleep_ms((long)timeout_ms); + return 0; } - return 1; + long age = 0; + if (cron_offer_age_ms(first, &mono, &age)) + cron_wait_remaining(first, timeout_ms); + else + cron_sleep_ms((long)timeout_ms); + agent_lock(); + found = cron_job_get_by_id(first, row) == 1 && row->enabled && row->next_run <= now && + cron_stored_target(row->channel, row->recipient, row->channel_truncated, + row->recipient_truncated) == CRON_TARGET_READY; + agent_unlock(); + if (found) + return 1; + cron_job_row_free(row); + return 0; } static int cron_poll(channel_incoming_msg_t *out, int timeout_ms) @@ -448,6 +590,8 @@ int cron_ack_delivery(const char *job_id) static int cron_send(const char *recipient, const char *text, const channel_attachment_t *attachments, size_t att_count) { + cron_delivery_t delivery; + cron_target_status_t target; if (!recipient || !text) return -1; const char *colon = strchr(recipient, ':'); if (!colon) return -1; @@ -456,9 +600,12 @@ static int cron_send(const char *recipient, const char *text, if (n >= sizeof(ch_name)) return -1; memcpy(ch_name, recipient, n); ch_name[n] = '\0'; - const channel_t *ch = channel_get_by_name(ch_name); - if (!ch || !ch->send) return -1; - return ch->send(colon + 1, text, attachments, att_count); + agent_lock(); + target = cron_resolve_target(ch_name, colon + 1, CRON_TARGET_STORED, &delivery); + agent_unlock(); + if (target != CRON_TARGET_READY) + return -1; + return delivery.channel->send(delivery.recipient, text, attachments, att_count); } static void cron_cleanup(void) @@ -553,9 +700,12 @@ static int cron_tool_execute(const char *args_json, char *result_buf, size_t max id[0] = '\0'; const char *ch = (channel && cJSON_IsString(channel)) ? channel->valuestring : NULL; const char *rec = (recipient && cJSON_IsString(recipient)) ? recipient->valuestring : NULL; - if (cron_create_job(schedule->valuestring, message->valuestring, ch, rec, id, sizeof(id)) != 0) { + int rc = cron_create_job(schedule->valuestring, message->valuestring, ch, rec, id, sizeof(id)); + if (rc != 0) { cJSON_Delete(root); - snprintf(result_buf, max_len, "{\"error\":\"failed to create job\"}"); + snprintf(result_buf, max_len, "%s", rc == CRON_INVALID_DESTINATION + ? "{\"error\":\"Invalid cron destination.\"}" + : "{\"error\":\"failed to create job\"}"); return -1; } snprintf(result_buf, max_len, "{\"ok\":true,\"id\":\"%s\"}", id); diff --git a/src/tools/cron.h b/src/tools/cron.h index 803196d3..a45caa14 100644 --- a/src/tools/cron.h +++ b/src/tools/cron.h @@ -52,17 +52,25 @@ const channel_t *channel_cron_get(void); /** Get the cron tool for agent (list, create, delete, toggle jobs). */ const tool_t *tool_cron_get(void); +#define CRON_INVALID_DESTINATION (-2) + /** * Create a cron job (shared by tool and HTTP handler). * If id_out[0] == '\0', a random ID is generated. + * Register an extension channel before creating a job for it. + * If a stored channel is unavailable, its job keeps its due time. + * Heartbeat jobs require a configured log or CLI destination. + * If a send fails, a later poll can run the agent and its tools again. + * WebChat IDs identify connections. A restart can reuse an ID for another client. + * The poller disables stored WebChat jobs and keeps their data. * * @param schedule Schedule string (interval:N, at:ts, or cron expression). * @param message Message to inject when job fires. - * @param channel Target channel name (e.g., "cli"). NULL defaults to "cli". - * @param recipient Recipient ID. NULL defaults to "default". + * @param channel Target channel name. NULL or empty selects "cli". WebChat is invalid. + * @param recipient Recipient ID for the target channel. CLI accepts "default". * @param id_out Buffer for job ID. If non-empty on entry, used as-is; else generated. * @param id_size Size of id_out buffer. - * @return 0 on success, -1 on error. + * @return 0 on success, CRON_INVALID_DESTINATION for an invalid target, or -1 on error. */ int cron_create_job(const char *schedule, const char *message, const char *channel, const char *recipient, diff --git a/src/tools/hardware_tools.c b/src/tools/hardware_tools.c index 9289be97..0000bd1f 100644 --- a/src/tools/hardware_tools.c +++ b/src/tools/hardware_tools.c @@ -32,12 +32,16 @@ static int camera_capture_exec(const char *args_json, char *result_buf, size_t m const char *output_path = NULL; const char *camera_type; const char *resolution; - char result_path[512]; + char result_path[PATH_MAX]; + const size_t json_overhead = sizeof("{\"path\":\"\"}") - 1; + size_t path_capacity; char errbuf[256]; board_id_t board; int quality; int rc; + if (!result_buf || max_len == 0) + return -1; path_buf[0] = '\0'; if (!hw_tools_enabled()) { snprintf(result_buf, max_len, "%s", HW_ERR_DISABLED); @@ -48,8 +52,15 @@ static int camera_capture_exec(const char *args_json, char *result_buf, size_t m if (hw_tools_parse_root(args_json, &root, result_buf, max_len) != 0) return -1; path_item = cJSON_GetObjectItem(root, "path"); - if (path_item && cJSON_IsString(path_item) && path_item->valuestring[0]) - snprintf(path_buf, sizeof(path_buf), "%s", path_item->valuestring); + if (cJSON_IsString(path_item) && path_item->valuestring[0]) { + size_t length = strlen(path_item->valuestring); + if (length >= sizeof(path_buf)) { + cJSON_Delete(root); + hw_tools_json_error(result_buf, max_len, "camera: output path too long"); + return -1; + } + memcpy(path_buf, path_item->valuestring, length + 1); + } cJSON_Delete(root); root = NULL; } @@ -67,8 +78,15 @@ static int camera_capture_exec(const char *args_json, char *result_buf, size_t m camera_type = config_hardware_camera_type(g_hw_cfg); resolution = config_hardware_camera_resolution(g_hw_cfg); quality = config_hardware_camera_quality(g_hw_cfg); + if (max_len <= json_overhead) { + hw_tools_json_error(result_buf, max_len, "camera: result buffer too small"); + return -1; + } + path_capacity = max_len - json_overhead; + if (path_capacity > sizeof(result_path)) + path_capacity = sizeof(result_path); rc = hardware_camera_capture(board, camera_type, resolution, quality, 0, 0, output_path, - result_path, sizeof(result_path), errbuf, sizeof(errbuf)); + result_path, path_capacity, errbuf, sizeof(errbuf)); if (rc != 0) { hw_tools_json_error(result_buf, max_len, errbuf); return -1; diff --git a/tests/test_agent.c b/tests/test_agent.c index 8be45d81..ba08ee72 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -139,6 +139,45 @@ static const provider_t always_tool_provider = { .cleanup = always_tool_cleanup, }; +/* Tool-only replies often have no text. The cap drops the tool calls and + * must not store that blank body: Anthropic rejects it on the next turn. */ +static int blank_cap_calls; +static const char *blank_cap_body; +static int blank_cap_init(const config_t *cfg) { (void)cfg; blank_cap_calls = 0; return 0; } +static int blank_cap_chat(const provider_message_t *messages, size_t message_count, + const provider_tool_def_t *tools, size_t tool_count, provider_response_t *response) +{ + (void)messages; + (void)message_count; + (void)tools; + (void)tool_count; + response->error = 0; + blank_cap_calls++; + response->content = blank_cap_body ? strdup(blank_cap_body) : NULL; + response->tool_calls = malloc(sizeof(provider_tool_call_t)); + if (!response->tool_calls || (blank_cap_body && !response->content)) { + free(response->content); + free(response->tool_calls); + response->content = NULL; + response->tool_calls = NULL; + response->tool_calls_count = 0; + response->error = 1; + return -1; + } + response->tool_calls[0].id = strdup("tid"); + response->tool_calls[0].name = strdup("echo"); + response->tool_calls[0].arguments = strdup("{}"); + response->tool_calls_count = 1; + return 0; +} +static void blank_cap_cleanup(void) {} +static const provider_t blank_cap_provider = { + .name = "blank_cap", + .init = blank_cap_init, + .chat = blank_cap_chat, + .cleanup = blank_cap_cleanup, +}; + static int mock_echo_execute(const char *args_json, char *result_buf, size_t max_len) { (void)args_json; @@ -307,6 +346,61 @@ static int test_react_loop_max_iterations(void) return failed; } +static int test_tool_cap_blank_reply_stays_replayable(void) +{ + int failed = 1; + const char *db_path = "build/test_agent_blankcap.db"; + const char *config_path = "build/test_agent_blankcap.toml"; + const char *kept = "Stopped: tool iteration limit reached."; + const char *bodies[] = { NULL, "", " \n\t" }; + config_t *cfg = NULL; + char errbuf[256]; + char response_buf[4096]; + char loaded[8192]; + char expected[256]; + FILE *cf; + memory_cleanup(); + if (memory_init(db_path) != 0) goto cleanup; + cf = fopen(config_path, "w"); + if (!cf) goto cleanup; + fprintf(cf, "[agent]\nmodel = \"anthropic/claude-sonnet-4-20250514\"\n" + "max_tool_iterations = 1\n[memory]\ndb_path = \"%s\"\n", db_path); + fclose(cf); + if (config_load(config_path, &cfg, errbuf, sizeof(errbuf)) != 0 || cfg == NULL) + goto cleanup; + snprintf(expected, sizeof(expected), "[{\"role\":\"user\",\"content\":\"keep going\"}," + "{\"role\":\"assistant\",\"content\":\"%s\"}]", kept); + for (size_t i = 0; i < sizeof(bodies) / sizeof(bodies[0]); i++) { + char session_id[32]; + snprintf(session_id, sizeof(session_id), "cli:blankcap:%zu", i); + blank_cap_body = bodies[i]; + blank_cap_calls = 0; + if (agent_run(cfg, session_id, "keep going", &blank_cap_provider, &mock_echo_tool, 1, + response_buf, sizeof(response_buf)) != 0 || + blank_cap_calls != 2 || strcmp(response_buf, kept) != 0 || + session_load(session_id, loaded, sizeof(loaded)) != 0 || + strcmp(loaded, expected) != 0) { + fprintf(stderr, "FAIL: tool limit case %zu did not return and save the notice\n", i); + goto cleanup; + } + if (agent_run(cfg, session_id, "continue", &spy_provider, &mock_echo_tool, 1, + response_buf, sizeof(response_buf)) != 0 || + spy_message_count < 4 || !spy_roles[2] || + strcmp(spy_roles[2], "assistant") != 0 || strcmp(spy_content[2], kept) != 0) { + fprintf(stderr, "FAIL: tool limit case %zu did not replay the notice\n", i); + goto cleanup; + } + } + failed = 0; +cleanup: + spy_provider.cleanup(); + config_free(cfg); + remove(config_path); + remove(db_path); + memory_cleanup(); + return failed; +} + static int persist_reply_init(const config_t *cfg) { (void)cfg; return 0; } static int persist_reply_chat(const provider_message_t *messages, size_t message_count, const provider_tool_def_t *tools, size_t tool_count, provider_response_t *response) @@ -1628,6 +1722,71 @@ static int test_compaction_failure_keeps_original_session(void) return failed; } +static const char *mock_summary_body; +static int blank_summary_chat(const provider_message_t *messages, size_t message_count, + const provider_tool_def_t *tools, size_t tool_count, provider_response_t *response) +{ + if (message_count == 2) { + response->content = mock_summary_body ? strdup(mock_summary_body) : NULL; + return mock_summary_body && !response->content ? -1 : 0; + } + return spy_chat(messages, message_count, tools, tool_count, response); +} + +static const provider_t blank_summary_provider = { + .name = "blank_summary", + .init = spy_init, + .chat = blank_summary_chat, + .cleanup = spy_cleanup, +}; + +static int test_blank_compaction_summary_keeps_history(void) +{ + const char *db_path = "build/test_blank_summary.db"; + const char *config_path = "build/test_blank_summary.toml"; + const char *session_id = "cli:blank-summary"; + const char *bodies[] = { "", " \t\r\n", NULL }; + config_t *cfg = NULL; + char before[4096]; + char after[4096]; + char response[32]; + char err[256]; + int failed = 1; + + memory_cleanup(); + FILE *cf = fopen(config_path, "w"); + if (!cf) goto cleanup; + fputs("[agent]\nmodel = \"test\"\nmax_context_messages = 4\n", cf); + fclose(cf); + if (memory_init(db_path) != 0 || + config_load(config_path, &cfg, err, sizeof(err)) != 0) + goto cleanup; + for (size_t i = 0; i < sizeof(bodies) / sizeof(bodies[0]); i++) { + mock_summary_body = bodies[i]; + if (save_alternating_session(session_id, 6) != 0 || + session_load(session_id, before, sizeof(before)) != 0 || + agent_run(cfg, session_id, "new prompt", &blank_summary_provider, NULL, 0, + response, sizeof(response)) != 0 || + session_load(session_id, after, sizeof(after)) != 0) + goto cleanup; + if (strcmp(response, "ok") != 0 || strlen(before) == 0 || + strncmp(before, after, strlen(before) - 1) != 0 || + strcmp(after + strlen(before) - 1, ",{\"role\":\"user\",\"content\":\"new prompt\"}," + "{\"role\":\"assistant\",\"content\":\"ok\"}]") != 0) { + fprintf(stderr, "FAIL: blank summary case %zu changed prior history or lost the new turn\n", i); + goto cleanup; + } + } + failed = 0; +cleanup: + spy_cleanup(); + config_free(cfg); + memory_cleanup(); + remove(config_path); + remove(db_path); + return failed; +} + /* Odd max_context_messages cuts the tail on a user turn. A separate summary * user message then makes every later Anthropic call a 400. */ static int test_compaction_merges_summary_when_tail_starts_with_user(void) @@ -1707,6 +1866,79 @@ static int test_compaction_merges_summary_when_tail_starts_with_user(void) } +static int test_history_replay_preserves_assistant_role(void) +{ + const char *db_path = "build/test_history_replay.db"; + const char *config_path = "build/test_history_replay.toml"; + const char *session_id = "cli:history-replay"; + const char *folded_head = "[{\"role\":\"assistant\",\"content\":\"Summary of earlier"; + enum { REPLY = 65500, CAP = 128 * 1024 }; + config_t *cfg = NULL; + char err[256]; + char response[32]; + char *json = malloc(CAP); + char *reply = malloc(REPLY + 1); + int failed = 1; + + memory_cleanup(); + if (!json || !reply || memory_init(db_path) != 0) goto cleanup; + FILE *cf = fopen(config_path, "w"); + if (!cf) goto cleanup; + fputs("[agent]\nmodel = \"test\"\nmax_context_messages = 5\n", cf); + fclose(cf); + if (config_load(config_path, &cfg, err, sizeof(err)) != 0) goto cleanup; + memset(reply, 'B', REPLY); + memcpy(reply + REPLY - 11, "BIGASST_END", 11); + reply[REPLY] = '\0'; + /* One folded history fits the window. The other needs a second cut. */ + for (int count = 6; count <= 8; count += 2) { + size_t off = (size_t)snprintf(json, CAP, + "[{\"role\":\"user\",\"content\":\"Please compare the options above.\"}," + "{\"role\":\"assistant\",\"content\":\"%s\"}", reply); + for (int i = 2; i < count; i++) { + off += (size_t)snprintf(json + off, CAP - off, + ",{\"role\":\"%s\",\"content\":\"msg_%d\"}", + i % 2 ? "assistant" : "user", i); + } + snprintf(json + off, CAP - off, "]"); + if (session_save(session_id, json) != 0 || + agent_run(cfg, session_id, "new prompt", &compaction_provider, NULL, 0, + response, sizeof(response)) != 0 || + session_load(session_id, json, CAP) != 0) + goto cleanup; + const char *expected = count == 6 ? "Summary of earlier" : "msg_3"; + if (!spy_roles[1] || strcmp(spy_roles[1], "user") != 0 || + !spy_roles[2] || strcmp(spy_roles[2], "assistant") != 0 || + strncmp(spy_content[2], expected, strlen(expected)) != 0 || + strncmp(json, folded_head, strlen(folded_head)) != 0 || + strstr(json, "BIGASST_END") == NULL) { + fprintf(stderr, "FAIL: replay changed the role or content of a folded turn (%d messages)\n", count); + goto cleanup; + } + } + /* Older rows can already start with an assistant message. */ + if (session_save(session_id, "[{\"role\":\"assistant\",\"content\":\"old reply\"}]") != 0 || + agent_run(cfg, session_id, "new prompt", &spy_provider, NULL, 0, + response, sizeof(response)) != 0) + goto cleanup; + if (!spy_roles[1] || strcmp(spy_roles[1], "user") != 0 || + !spy_roles[2] || strcmp(spy_roles[2], "assistant") != 0 || + strcmp(spy_content[2], "old reply") != 0) { + fprintf(stderr, "FAIL: replay changed the role or content of a stored assistant turn\n"); + goto cleanup; + } + failed = 0; +cleanup: + spy_cleanup(); + config_free(cfg); + free(reply); + free(json); + memory_cleanup(); + remove(config_path); + remove(db_path); + return failed; +} + static int test_local_offline_note_when_active_is_local(void) { const char *path = "build/test_agent_local_note.toml"; @@ -1985,6 +2217,7 @@ static int test_local_offline_note_skipped_for_non_local(void) /* SESSION_JSON_MAX in agent.c is 128 KiB. A reply this large plus a near-full * prior session forces append_exchange_to_session_json over the cap. */ #define OVERFLOW_REPLY_BYTES (16 * 1024) +static const char overflow_reply_suffix[] = "\xC3\xA9\xE6\x97\xA5"; static int overflow_reply_init(const config_t *cfg) { (void)cfg; return 0; } static int overflow_reply_chat(const provider_message_t *messages, size_t message_count, @@ -2000,8 +2233,9 @@ static int overflow_reply_chat(const provider_message_t *messages, size_t messag response->tool_calls_count = 0; big = malloc(OVERFLOW_REPLY_BYTES); if (!big) return -1; - memset(big, 'R', OVERFLOW_REPLY_BYTES - 1); - big[OVERFLOW_REPLY_BYTES - 1] = '\0'; + memset(big, 'R', OVERFLOW_REPLY_BYTES - sizeof(overflow_reply_suffix)); + memcpy(big + OVERFLOW_REPLY_BYTES - sizeof(overflow_reply_suffix), + overflow_reply_suffix, sizeof(overflow_reply_suffix)); response->content = big; return 0; } @@ -2013,6 +2247,8 @@ static const provider_t overflow_reply_provider = { .cleanup = overflow_reply_cleanup, }; +static const char *expected_history_reply; +static int replayed_history_reply; static int keep_history_init(const config_t *cfg) { (void)cfg; return 0; } static int keep_history_chat(const provider_message_t *messages, size_t message_count, const provider_tool_def_t *tools, size_t tool_count, provider_response_t *response) @@ -2029,6 +2265,9 @@ static int keep_history_chat(const provider_message_t *messages, size_t message_ spy_roles[i] = messages[i].role ? strdup(messages[i].role) : NULL; if (messages[i].content) { size_t n = strlen(messages[i].content); + if (expected_history_reply && spy_roles[i] && strcmp(spy_roles[i], "assistant") == 0 && + strcmp(messages[i].content, expected_history_reply) == 0) + replayed_history_reply = 1; if (n >= SPY_CONTENT_SIZE) n = SPY_CONTENT_SIZE - 1; memcpy(spy_content[i], messages[i].content, n); spy_content[i][n] = '\0'; @@ -2045,12 +2284,50 @@ static const provider_t keep_history_provider = { .cleanup = keep_history_cleanup, }; -/** - * Concrete trigger: near-cap session JSON + fat assistant reply. - * Before the fix, append truncated mid-JSON, session_save persisted corrupt - * payload, and the next agent_run parse wiped history. After the fix, overflow - * refuses to save and prior history remains parseable. - */ +static int oversized_exchange_keeps_shortened_history(const config_t *cfg) +{ + const char *session_id = "cli:large-exchange"; + const char *marker = "[truncated]"; + enum { REPEATS = 18 * 1024 + 3, CAP = 128 * 1024 }; + char *input = malloc(REPEATS * 3 + 3); + char *loaded = malloc(CAP); + char response[OVERFLOW_REPLY_BYTES + 64]; + cJSON *parsed = NULL; + int failed = 1; + + if (!input || !loaded) goto cleanup; + /* JSON escapes the control byte. The accented character uses two bytes. */ + for (size_t i = 0; i < REPEATS; i++) + memcpy(input + i * 3, "\x01\xC3\xA9", 3); + memcpy(input + REPEATS * 3, "xx", 3); + if (agent_run(cfg, session_id, input, &overflow_reply_provider, NULL, 0, + response, sizeof(response)) != 0 || + strlen(response) != OVERFLOW_REPLY_BYTES - 1 || + session_load(session_id, loaded, CAP) != 0) { + fprintf(stderr, "FAIL: the oversized exchange did not save both turns\n"); + goto cleanup; + } + parsed = cJSON_Parse(loaded); + const cJSON *user = cJSON_GetObjectItem(cJSON_GetArrayItem(parsed, 0), "content"); + const cJSON *assistant = cJSON_GetObjectItem(cJSON_GetArrayItem(parsed, 1), "content"); + const char *suffix = cJSON_IsString(user) ? strstr(user->valuestring, marker) : NULL; + if (!json_roles_alternate_from_user(loaded) || cJSON_GetArraySize(parsed) != 2 || + !suffix || strcmp(suffix, marker) != 0 || !cJSON_IsString(assistant) || + strcmp(assistant->valuestring, response) != 0) + goto cleanup; + size_t preserved = (size_t)(suffix - user->valuestring); + if (preserved == 0 || strncmp(input, user->valuestring, preserved) != 0 || + ((unsigned char)input[preserved] & 0xC0) == 0x80) + goto cleanup; + failed = 0; +cleanup: + cJSON_Delete(parsed); + free(loaded); + free(input); + return failed; +} + +/* A new reply can exceed the byte limit before the message count triggers compaction. */ static int test_session_overflow_does_not_corrupt_history(void) { int failed = 1; @@ -2059,7 +2336,7 @@ static int test_session_overflow_does_not_corrupt_history(void) const char *config_path = "build/test_agent_overflow.toml"; const char *session_id = "cli:overflow"; const char *marker = "UNIQUE_HISTORY_MARKER_xyz"; - /* Two large messages keep msg_count under max_context so compaction does not shrink first. */ + /* Both large messages belong to the oldest exchange. */ enum { PAD_A = 62 * 1024, PAD_B = 62 * 1024, LOAD_CAP = 130 * 1024 }; char *session_json = NULL; char *pad_a = NULL; @@ -2067,8 +2344,9 @@ static int test_session_overflow_does_not_corrupt_history(void) char *loaded = NULL; size_t need; size_t off = 0; - char response_buf[OVERFLOW_REPLY_BYTES + 64]; - cJSON *parsed; + /* The response buffer cuts inside the last character of the reply. */ + char response_buf[OVERFLOW_REPLY_BYTES - 2]; + cJSON *parsed = NULL; memory_cleanup(); if (memory_init(db_path) != 0) goto cleanup; @@ -2079,12 +2357,13 @@ static int test_session_overflow_does_not_corrupt_history(void) pad_a[PAD_A] = '\0'; memset(pad_b, 'B', PAD_B); pad_b[PAD_B] = '\0'; - need = strlen(marker) + PAD_A + PAD_B + 128; + need = strlen(marker) + PAD_A + PAD_B + 256; session_json = malloc(need); if (!session_json) goto cleanup; off = (size_t)snprintf(session_json, need, - "[{\"role\":\"user\",\"content\":\"%s%s\"},{\"role\":\"assistant\",\"content\":\"%s\"}]", - marker, pad_a, pad_b); + "[{\"role\":\"user\",\"content\":\"old prompt%s\"},{\"role\":\"assistant\",\"content\":\"old reply%s\"}," + "{\"role\":\"user\",\"content\":\"%s\"},{\"role\":\"assistant\",\"content\":\"recent reply\"}]", + pad_a, pad_b, marker); if (off == 0 || off >= need) goto cleanup; if (session_save(session_id, session_json) != 0) goto cleanup; @@ -2107,6 +2386,11 @@ static int test_session_overflow_does_not_corrupt_history(void) fprintf(stderr, "FAIL: tests/test_agent.c: overflow agent_run failed\n"); goto cleanup; } + if (strlen(response_buf) != OVERFLOW_REPLY_BYTES - 4 || + strcmp(response_buf + OVERFLOW_REPLY_BYTES - 6, "\xC3\xA9") != 0) { + fprintf(stderr, "FAIL: response ends inside a UTF-8 character\n"); + goto cleanup; + } loaded = malloc(LOAD_CAP); if (!loaded) goto cleanup; @@ -2114,31 +2398,35 @@ static int test_session_overflow_does_not_corrupt_history(void) if (session_load(session_id, loaded, LOAD_CAP) != 0) goto cleanup; parsed = cJSON_Parse(loaded); if (!parsed || !cJSON_IsArray(parsed)) { - if (parsed) cJSON_Delete(parsed); fprintf(stderr, "FAIL: tests/test_agent.c: overflow session JSON unparseable\n"); goto cleanup; } - cJSON_Delete(parsed); - if (strstr(loaded, marker) == NULL) goto cleanup; + const cJSON *stored_reply = cJSON_GetObjectItem(cJSON_GetArrayItem(parsed, 3), "content"); + if (!cJSON_IsString(stored_reply) || strcmp(stored_reply->valuestring, response_buf) != 0) + goto cleanup; + if (!json_roles_alternate_from_user(loaded) || count_session_messages(loaded) != 4 || + strstr(loaded, "old prompt") || strstr(loaded, "old reply") || + strstr(loaded, "recent reply") == NULL || strstr(loaded, "push over the limit") == NULL) { + fprintf(stderr, "FAIL: overflow did not retain the two newest complete exchanges\n"); + goto cleanup; + } - /* Next turn must still see prior history (not wiped to empty []). */ + /* The next request starts with the most recent retained prompt. */ spy_roles_clear(); + expected_history_reply = stored_reply->valuestring; + replayed_history_reply = 0; response_buf[0] = '\0'; if (agent_run(cfg, session_id, "still there?", &keep_history_provider, NULL, 0, response_buf, sizeof(response_buf)) != 0) goto cleanup; - { - int found = 0; - for (size_t j = 0; j < spy_message_count && j < SPY_SLOTS; j++) { - if (strstr(spy_content[j], marker) != NULL) { - found = 1; - break; - } - } - if (!found) goto cleanup; - } - failed = 0; + if (!spy_roles[1] || strcmp(spy_roles[1], "user") != 0 || + strcmp(spy_content[1], marker) != 0 || + strcmp(spy_content[3], "push over the limit") != 0 || !replayed_history_reply) + goto cleanup; + failed = oversized_exchange_keeps_shortened_history(cfg); cleanup: + expected_history_reply = NULL; + cJSON_Delete(parsed); config_free(cfg); free(session_json); free(pad_a); @@ -2438,6 +2726,7 @@ int main(void) RUN(test_context_assembly_system_prompt_history_memories()); RUN(test_react_loop_tool_then_text()); RUN(test_react_loop_max_iterations()); + RUN(test_tool_cap_blank_reply_stays_replayable()); RUN(test_react_loop_preserves_prior_tool_results()); RUN(test_session_persisted_after_exchange()); RUN(test_context_compaction_when_history_exceeds_max()); @@ -2450,7 +2739,9 @@ int main(void) RUN(test_compaction_folds_assistant_line_that_fits_a_fresh_source()); RUN(test_compaction_progresses_when_assistant_message_is_oversized()); RUN(test_compaction_failure_keeps_original_session()); + RUN(test_blank_compaction_summary_keeps_history()); RUN(test_compaction_merges_summary_when_tail_starts_with_user()); + RUN(test_history_replay_preserves_assistant_role()); RUN(test_local_offline_note_when_active_is_local()); RUN(test_local_offline_note_skipped_for_non_local()); RUN(test_session_overflow_does_not_corrupt_history()); diff --git a/tests/test_anthropic.c b/tests/test_anthropic.c index 3af1281c..a0cfacbd 100644 --- a/tests/test_anthropic.c +++ b/tests/test_anthropic.c @@ -130,6 +130,24 @@ static int test_parse_api_error_object_sets_error(void) return 0; } +static int test_parse_missing_or_invalid_content_returns_error(void) +{ + const char *bodies[] = { + "{}", "{\"content\":null}", "{\"content\":{}}", "{\"content\":[{}]}", + "{\"content\":[{\"type\":\"text\",\"text\":42}]}", + "{\"content\":[{\"type\":\"text\"}]}", + "{\"content\":[{\"type\":\"tool_use\",\"id\":\"x\",\"name\":\"echo\",\"input\":[]}]}", + "{\"content\":[{\"type\":\"tool_use\",\"id\":\"x\",\"input\":{}}]}", + }; + for (size_t i = 0; i < sizeof(bodies) / sizeof(bodies[0]); i++) { + provider_response_t response = {0}; + ASSERT(anthropic_parse_response_for_test(bodies[i], &response) == -1); + ASSERT(response.error != 0 && response.content && response.content[0]); + provider_response_clear(&response); + } + return 0; +} + static int test_parse_empty_content_array_returns_zero(void) { const char *body = "{\"content\":[]}"; @@ -142,12 +160,13 @@ static int test_parse_empty_content_array_returns_zero(void) static int test_parse_valid_text_block_returns_content(void) { - const char *body = "{\"content\":[{\"type\":\"text\",\"text\":\"Hello world\"}]}"; + const char *body = "{\"content\":[{\"type\":\"thinking\",\"thinking\":\"internal\"}," + "{\"type\":\"text\",\"text\":\"Hello world\"}]}"; provider_response_t response = {0}; ASSERT(anthropic_parse_response_for_test(body, &response) == 0); ASSERT(response.error == 0); ASSERT(response.content != NULL); - ASSERT(strstr(response.content, "Hello world") != NULL); + ASSERT(strcmp(response.content, "Hello world") == 0); provider_response_clear(&response); return 0; } @@ -519,6 +538,93 @@ static int test_parse_tool_realloc_failure_is_error(void) provider_response_clear(&response); return 0; } + +static size_t cjson_allocations; +static size_t cjson_fail_at; + +static void *fail_one_cjson_allocation(size_t size) +{ + return ++cjson_allocations == cjson_fail_at ? NULL : malloc(size); +} + +static int test_parse_tool_input_serialization_failure_is_error(void) +{ + const char *body = "{\"content\":[{\"type\":\"tool_use\",\"id\":\"t\",\"name\":\"echo\",\"input\":{}}]}"; + cJSON_Hooks hooks = { .malloc_fn = fail_one_cjson_allocation, .free_fn = free }; + provider_response_t response = {0}; + cjson_allocations = 0; + cjson_fail_at = 0; + cJSON_InitHooks(&hooks); + cJSON *parsed = cJSON_Parse(body); + int parsed_ok = parsed != NULL; + /* Fail the first allocation after parsing the response JSON. */ + cjson_fail_at = cjson_allocations + 1; + cjson_allocations = 0; + cJSON_Delete(parsed); + int rc = anthropic_parse_response_for_test(body, &response); + cJSON_InitHooks(NULL); + ASSERT(parsed_ok && rc == -1 && response.error && response.tool_calls_count == 0); + provider_response_clear(&response); + return 0; +} + +/** A stored assistant turn with no text must not be replayed as an empty block. */ +static int test_blank_assistant_string_is_nonempty(void) +{ + provider_message_t messages[2]; + char *json; + const char *kept = "The model returned no text."; + + memset(messages, 0, sizeof(messages)); + messages[0].role = "user"; + messages[0].content = "continue"; + messages[1].role = "assistant"; + messages[1].content = ""; + json = anthropic_messages_json_for_test(messages, 2); + ASSERT(json != NULL); + ASSERT(strstr(json, "\"content\":\"\"") == NULL); + ASSERT(strstr(json, kept) != NULL); + cJSON_free(json); + + messages[1].content = " \n\t"; + json = anthropic_messages_json_for_test(messages, 2); + ASSERT(json != NULL); + ASSERT(strstr(json, kept) != NULL); + ASSERT(strstr(json, "\\n\\t") == NULL); + cJSON_free(json); + + messages[1].content = "partial"; + json = anthropic_messages_json_for_test(messages, 2); + ASSERT(json != NULL); + ASSERT(strstr(json, "partial") != NULL); + ASSERT(strstr(json, kept) == NULL); + cJSON_free(json); + return 0; +} + +/** Whitespace next to tool_use must not be sent as a text block. */ +static int test_whitespace_tool_text_is_omitted(void) +{ + provider_tool_call_t calls[1] = { + {.id = "toolu_a", .name = "shell", .arguments = "{\"command\":\"pwd\"}"}, + }; + provider_message_t messages[2]; + char *json; + + memset(messages, 0, sizeof(messages)); + messages[0].role = "user"; + messages[0].content = "run"; + messages[1].role = "assistant"; + messages[1].content = " \n"; + messages[1].tool_calls = calls; + messages[1].tool_calls_count = 1; + json = anthropic_messages_json_for_test(messages, 2); + ASSERT(json != NULL); + ASSERT(strstr(json, "tool_use") != NULL); + ASSERT(strstr(json, "\"text\"") == NULL); + cJSON_free(json); + return 0; +} #endif int main(void) @@ -531,6 +637,7 @@ int main(void) #ifdef SHELLCLAW_TEST RUN(test_parse_malformed_json_sets_error()); RUN(test_parse_api_error_object_sets_error()); + RUN(test_parse_missing_or_invalid_content_returns_error()); RUN(test_parse_empty_content_array_returns_zero()); RUN(test_parse_valid_text_block_returns_content()); RUN(test_parse_null_json_returns_error()); @@ -542,6 +649,9 @@ int main(void) RUN(test_tool_results_do_not_merge_across_assistant_rounds()); RUN(test_parse_text_realloc_failure_is_error()); RUN(test_parse_tool_realloc_failure_is_error()); + RUN(test_parse_tool_input_serialization_failure_is_error()); + RUN(test_blank_assistant_string_is_nonempty()); + RUN(test_whitespace_tool_text_is_omitted()); RUN(test_example_model_prefix_is_stripped()); #endif printf("test_anthropic: all tests passed\n"); diff --git a/tests/test_cron.c b/tests/test_cron.c index 5770f68b..34c18176 100644 --- a/tests/test_cron.c +++ b/tests/test_cron.c @@ -6,8 +6,10 @@ #include "tools/cron.h" #include "core/agent.h" +#include "core/config.h" #include "core/memory.h" #include "channels/channel.h" +#include "channels/heartbeat.h" #include #include #include @@ -23,6 +25,22 @@ void provider_router_active_backend_snapshot(char *dst, size_t dst_sz) dst[0] = '\0'; } +static char g_cron_recipient[128]; + +static int capture_send(const char *recipient, const char *text, + const channel_attachment_t *attachments, size_t count) +{ + (void)text; + (void)attachments; + (void)count; + snprintf(g_cron_recipient, sizeof(g_cron_recipient), "%s", recipient); + return 0; +} + +static const channel_t test_delivery_channel = {.send = capture_send}; + +static const char long_target[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"; + static void cron_test_reset_offers(void) { const channel_t *cron_ch = channel_cron_get(); @@ -754,8 +772,160 @@ static int test_cron_poll_delivers_17th_after_ack(void) return 0; } +static int test_cron_unavailable_targets_do_not_block_ready_jobs(void) +{ + const channel_t *cron = channel_cron_get(); + channel_incoming_msg_t msg = {0}; + const long long due = (long long)time(NULL) - 1; + struct timespec start; + struct timespec end; + cron_job_row_t row = {0}; + char id[16]; + + cron_test_reset_offers(); + ASSERT(memory_init(":memory:") == 0); + ASSERT(cron_job_create("old-channel", "at:1", "old", long_target, "", due - 5, 1) == 0); + ASSERT(cron_job_create("old-remote", "at:1", "old", "extension", long_target, due - 4, 1) == 0); + ASSERT(cron_job_create("old-cli", "at:1", "old", "cli", long_target, due - 3, 1) == 0); + ASSERT(cron_job_create("old-chat", "at:1", "old", "webchat", "webchat:42", due - 2, 1) == 0); + for (int i = 0; i < 65; i++) { + const char *channel = i == 0 ? "extension" : "telegram"; + snprintf(id, sizeof(id), "waiting%02d", i); + ASSERT(cron_job_create(id, "at:1", "old", channel, "-42", due - 1, 1) == 0); + } + ASSERT(cron_job_create("ready", "at:1", "ready", "cli", "", due, 1) == 0); + ASSERT(cron->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.user_id, "old-cli") == 0); + ASSERT(cron->send(msg.session_id, "legacy CLI reply", NULL, 0) == 0); + ASSERT(cron_ack_delivery(msg.user_id) == 0); + channel_incoming_msg_clear(&msg); + ASSERT(cron->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.user_id, "ready") == 0); + ASSERT(cron_ack_delivery(msg.user_id) == 0); + channel_incoming_msg_clear(&msg); + ASSERT(cron_job_get_by_id("old-chat", &row) == 1 && row.enabled == 0); + ASSERT(strcmp(row.channel, "webchat") == 0 && strcmp(row.recipient, "webchat:42") == 0); + ASSERT(strcmp(row.message, "old") == 0 && strcmp(row.schedule, "at:1") == 0 && row.next_run == due - 2); + cron_job_row_free(&row); + ASSERT(cron_job_get_by_id("old-channel", &row) == 1 && row.enabled == 0); + cron_job_row_free(&row); + ASSERT(cron_job_get_by_id("old-remote", &row) == 1 && row.enabled == 0); + cron_job_row_free(&row); + ASSERT(cron_job_get_by_id("waiting00", &row) == 1 && row.enabled == 1); + ASSERT(row.next_run == due - 1); + cron_job_row_free(&row); + ASSERT(clock_gettime(CLOCK_MONOTONIC, &start) == 0); + ASSERT(cron->poll(&msg, 80) == 0); + ASSERT(clock_gettime(CLOCK_MONOTONIC, &end) == 0); + ASSERT((end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000000 >= 40); + channel_register("extension", &test_delivery_channel); + ASSERT(cron->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.user_id, "waiting00") == 0); + ASSERT(cron->send(msg.session_id, "reply", NULL, 0) == 0); + ASSERT(strcmp(g_cron_recipient, "-42") == 0); + ASSERT(cron_ack_delivery(msg.user_id) == 0); + channel_incoming_msg_clear(&msg); + channel_register("telegram", &test_delivery_channel); + ASSERT(cron->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.user_id, "waiting01") == 0); + channel_incoming_msg_clear(&msg); + memory_cleanup(); + return 0; +} + +static int test_cron_target_validation_and_routing(void) +{ + const channel_t *cron = channel_cron_get(); + char id[32] = "job"; + const char *bad_targets[][2] = { + {"cron", "cli:default"}, {"heartbeat", "default"}, {"unknown", "abc"}, + {"webchat", NULL}, {"webchat", "42"}, {"webchat", "webchat:42"}, + {"discord", "default"}, {"telegram", "default"}, + {"cli", long_target}, {long_target, "default"}, + }; + + ASSERT(memory_init(":memory:") == 0); + for (size_t i = 0; i < sizeof(bad_targets) / sizeof(bad_targets[0]); i++) + ASSERT(cron_create_job("at:1", "message", bad_targets[i][0], bad_targets[i][1], + id, sizeof(id)) == CRON_INVALID_DESTINATION); + ASSERT(cron_create_job("at:1", "message", "discord", "1234", id, sizeof(id)) == 0); + channel_register("discord", &test_delivery_channel); + channel_register("custom", &test_delivery_channel); + strcpy(id, "extension_job"); + ASSERT(cron_create_job("at:1", "message", "custom", "my-id", id, sizeof(id)) == 0); + ASSERT(cron->send("webchat:42", "message", NULL, 0) != 0); + const char *routes[][2] = {{"discord:discord:c:1234", "discord:c:1234"}, {"discord:1234", "discord:c:1234"}, + {"custom:my-id", "my-id"}}; + for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) { + ASSERT(cron->send(routes[i][0], "message", NULL, 0) == 0); + ASSERT(strcmp(g_cron_recipient, routes[i][1]) == 0); + } + memory_cleanup(); + return 0; +} + +static int test_cron_heartbeat_delivers_only_to_local_destinations(void) +{ + const channel_t *cron = channel_cron_get(); + const channel_t *heartbeat = channel_heartbeat_get(); + const char *targets[] = {"log", "webchat", "heartbeat", "cron", "cli"}; + const char *path = "build/test_cron_heartbeat.toml"; + channel_incoming_msg_t msg = {0}; + cron_job_row_t row = {0}; + long long now = (long long)time(NULL); + char error[256]; + + cron_test_reset_offers(); + ASSERT(memory_init(":memory:") == 0); + ASSERT(cron_job_create("legacy_heartbeat", "at:1", "reminder", "heartbeat", long_target, + now - 1, 1) == 0); + ASSERT(cron->poll(&msg, 0) == 0); + ASSERT(cron_job_get_by_id("legacy_heartbeat", &row) == 1 && row.enabled == 1); + cron_job_row_free(&row); + channel_register("heartbeat", heartbeat); + for (size_t i = 0; i < sizeof(targets) / sizeof(targets[0]); i++) { + config_t *cfg = NULL; + FILE *f = fopen(path, "w"); + char id[16]; + int is_log = strcmp(targets[i], "log") == 0; + int is_local = is_log || strcmp(targets[i], "cli") == 0; + ASSERT(f != NULL); + fprintf(f, "[agent]\nmodel = \"test\"\n" + "[heartbeat]\nenabled = true\ndefault_channel = \"%s\"\n", targets[i]); + ASSERT(fclose(f) == 0); + ASSERT(config_load(path, &cfg, error, sizeof(error)) == 0); + ASSERT(heartbeat->init(cfg) == 0); + snprintf(id, sizeof(id), "new_%zu", i); + ASSERT(cron_create_job("interval:600", "new", "heartbeat", long_target, + id, sizeof(id)) == CRON_INVALID_DESTINATION); + ASSERT(cron_create_job("interval:600", "new", "heartbeat", NULL, id, sizeof(id)) == + (is_local ? 0 : CRON_INVALID_DESTINATION)); + if (is_local) { + g_cron_recipient[0] = '\0'; + ASSERT(cron->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.user_id, "legacy_heartbeat") == 0); + ASSERT(cron->send(msg.session_id, "reminder reply", NULL, 0) == 0); + ASSERT(g_cron_recipient[0] == '\0'); + channel_incoming_msg_clear(&msg); + } else { + ASSERT(cron->poll(&msg, 0) == 0); + ASSERT(cron->send("heartbeat:old", "reminder reply", NULL, 0) == -1); + } + ASSERT(cron_job_get_by_id("legacy_heartbeat", &row) == 1 && row.enabled == 1); + ASSERT(row.next_run == now - 1); + cron_job_row_free(&row); + heartbeat->cleanup(); + config_free(cfg); + } + remove(path); + memory_cleanup(); + return 0; +} + int main(void) { + channel_register("cli", channel_cli_get()); + channel_register("webchat", &test_delivery_channel); RUN(test_interval_next_run()); RUN(test_at_one_shot()); RUN(test_cron_expr_next_run()); @@ -781,6 +951,9 @@ int main(void) RUN(test_cron_poll_waits_when_offer_table_is_full()); RUN(test_cron_poll_delivers_17th_after_ack()); RUN(test_cron_list_orders_ties_by_id()); + RUN(test_cron_unavailable_targets_do_not_block_ready_jobs()); + RUN(test_cron_target_validation_and_routing()); + RUN(test_cron_heartbeat_delivers_only_to_local_destinations()); printf("test_cron: all tests passed\n"); return 0; } diff --git a/tests/test_dispatch.c b/tests/test_dispatch.c index 4286bacc..a2f6d2c0 100644 --- a/tests/test_dispatch.c +++ b/tests/test_dispatch.c @@ -5,6 +5,7 @@ #define _POSIX_C_SOURCE 200809L #include "channels/channel.h" +#include "channels/heartbeat.h" #include "core/bootstrap.h" void bootstrap_set_provider_for_test(const provider_t *provider); @@ -16,6 +17,7 @@ void bootstrap_add_tool_for_test(const tool_t *tool); #include "core/memory.h" #include "core/version.h" #include "providers/provider.h" +#include "tools/cron.h" #include #include #include @@ -41,6 +43,10 @@ void bootstrap_add_tool_for_test(const tool_t *tool); static char g_last_session[SEND_BUF_SIZE]; static char g_last_text[SEND_BUF_SIZE]; static int g_send_calls; +static int g_send_error; +static const char *g_spy_reply; +static const char *g_spy_openai_body; +static const config_t *g_reload_during_send; static size_t g_last_provider_tool_count; static int g_agent_mutex_held_during_chat; static int g_agent_mutex_held_during_reset; @@ -55,7 +61,13 @@ static int mock_send(const char *session_id, const char *text, g_last_session[sizeof(g_last_session) - 1] = '\0'; strncpy(g_last_text, text ? text : "", sizeof(g_last_text) - 1); g_last_text[sizeof(g_last_text) - 1] = '\0'; - return 0; + if (g_reload_during_send) { + agent_lock(); + heartbeat_set_live_config(g_reload_during_send); + agent_unlock(); + g_reload_during_send = NULL; + } + return g_send_error; } static const channel_t mock_channel = { @@ -88,8 +100,10 @@ static int spy_chat(const provider_message_t *messages, size_t message_count, (void)message_count; (void)tools; g_last_provider_tool_count = tool_count; + if (g_spy_openai_body) + return provider_parse_chat_completions_json(g_spy_openai_body, response); response->error = 0; - response->content = strdup("agent-ok"); + response->content = g_spy_reply ? strdup(g_spy_reply) : NULL; response->tool_calls = NULL; response->tool_calls_count = 0; return 0; @@ -185,6 +199,8 @@ static int write_minimal_toml(const char *path) static void reset_send_spy(void) { g_send_calls = 0; + g_send_error = 0; + g_spy_reply = "agent-ok"; g_last_session[0] = '\0'; g_last_text[0] = '\0'; g_last_provider_tool_count = 0; @@ -439,6 +455,93 @@ static int test_cron_agent_failure_does_not_ack(void) return 0; } +static int test_cron_blank_reply_acks_without_sending(void) +{ + const channel_t *cron = channel_cron_get(); + const char *db_path = "build/test_dispatch_cron_blank.db"; + const char *replies[] = {NULL, "", " \t\r\n\v\f", "reminder"}; + const char *schedules[] = {"at:1", "interval:60", "interval:60", "interval:60"}; + char tmpl[] = "/tmp/shellclaw_test_dispatch_cron_blank_XXXXXX"; + long long due_at = (long long)time(NULL) - 1; + channel_incoming_msg_t msg = {.session_id = "cli:default", .text = "remind me"}; + config_t *cfg; + int fd = mkstemp(tmpl); + + ASSERT(fd >= 0); + close(fd); + ASSERT(write_minimal_toml(tmpl) == 0); + cfg = load_minimal_cfg(tmpl); + ASSERT(cfg != NULL); + memory_cleanup(); + remove(db_path); + ASSERT(memory_init(db_path) == 0); + bootstrap_set_cfg(cfg); + bootstrap_set_provider_for_test(&spy_provider); + bootstrap_reset_tools_for_test(); + channel_register("cli", &mock_channel); + for (size_t i = 0; i < sizeof(replies) / sizeof(replies[0]); i++) { + cron_job_row_t row = {0}; + char id[16]; + snprintf(id, sizeof(id), "job_%zu", i); + ASSERT(cron_job_create(id, schedules[i], msg.text, "cli", "default", due_at, 1) == 0); + msg.user_id = id; + reset_send_spy(); + g_spy_reply = replies[i]; + g_send_error = -3; + if (i < 3) { + ASSERT(handle_message(cron, &msg) == 0); + ASSERT(g_send_calls == 0); + ASSERT(cron_job_get_by_id(id, &row) == (i > 0 ? 1 : 0)); + if (i > 0) + ASSERT(row.next_run > due_at); + } else { + ASSERT(handle_message(cron, &msg) == -3); + ASSERT(g_send_calls == 1); + ASSERT(cron_job_get_by_id(id, &row) == 1); + ASSERT(row.next_run == due_at); + } + cron_job_row_free(&row); + } + const char *valid_blank = "{\"choices\":[{\"message\":{\"content\":null}}]}"; + const char *invalid_tools = "{\"choices\":[{\"message\":{\"content\":null,\"tool_calls\":{}}}]}"; + const char *bodies[] = { valid_blank, "{}", invalid_tools, valid_blank }; + const char *channels[] = { "telegram", "cli", "cli", "cli" }; + const char *recipients[] = { "42", "malformed", "invalid-tools", "silent" }; + const char *routes[] = { "telegram:42", "cli:malformed", "cli:invalid-tools", "cli:silent" }; + for (size_t i = 0; i < sizeof(bodies) / sizeof(bodies[0]); i++) { + cron_job_row_t row = {0}; + char history[512]; + char id[16]; + snprintf(id, sizeof(id), "parsed_%zu", i); + ASSERT(cron_job_create(id, "at:1", msg.text, channels[i], recipients[i], due_at, 1) == 0); + reset_send_spy(); + g_spy_openai_body = bodies[i]; + msg.user_id = id; + msg.session_id = (char *)routes[i]; + ASSERT(handle_message(cron, &msg) == (i == 0 ? -1 : 0)); + ASSERT(g_send_calls == (i == 1 || i == 2 ? 1 : 0)); + ASSERT(cron_job_get_by_id(id, &row) == (i < 3 ? 1 : 0)); + if (i < 3) + ASSERT(row.next_run == due_at && row.enabled); + if (i == 1 || i == 2) + ASSERT(session_load(routes[i], history, sizeof(history)) != 0); + cron_job_row_free(&row); + } + g_spy_openai_body = NULL; + reset_send_spy(); + msg.user_id = NULL; + g_spy_reply = ""; + g_send_error = -3; + ASSERT(handle_message(&mock_channel, &msg) == -3); + ASSERT(g_send_calls == 1); + reset_send_spy(); + config_free(cfg); + unlink(tmpl); + memory_cleanup(); + remove(db_path); + return 0; +} + static int test_handle_message_holds_agent_mutex(void) { channel_incoming_msg_t msg = {0}; @@ -468,6 +571,78 @@ static int test_handle_message_holds_agent_mutex(void) return 0; } +static config_t *load_heartbeat_cfg(const char *path, const char *destination) +{ + FILE *file = fopen(path, "w"); + if (!file) + return NULL; + int written = fprintf(file, "[agent]\nmodel = \"test\"\n[heartbeat]\n" + "enabled = true\ndefault_channel = \"%s\"\n", destination); + if (fclose(file) != 0 || written < 0) + return NULL; + return load_minimal_cfg(path); +} + +static int test_cron_rechecks_heartbeat_only_for_silent_delivery(void) +{ + const channel_t *heartbeat = channel_heartbeat_get(); + const channel_t *cron = channel_cron_get(); + char path[] = "/tmp/shellclaw_test_dispatch_heartbeat_XXXXXX"; + int fd = mkstemp(path); + ASSERT(fd >= 0); + close(fd); + config_t *ready = load_heartbeat_cfg(path, "cli"); + config_t *unavailable = load_heartbeat_cfg(path, "webchat"); + ASSERT(ready && unavailable); + ASSERT(memory_init(":memory:") == 0); + ASSERT(heartbeat->init(ready) == 0 && cron->init(ready) == 0); + channel_register("cli", &mock_channel); + channel_register("heartbeat", heartbeat); + bootstrap_set_cfg(ready); + bootstrap_set_provider_for_test(&spy_provider); + bootstrap_reset_tools_for_test(); + for (int silent = 1; silent >= 0; silent--) { + char id[32]; + channel_incoming_msg_t msg = {0}; + cron_job_row_t row = {0}; + long long due_at = (long long)time(NULL) - 1; + snprintf(id, sizeof(id), "heartbeat_%d", silent); + reset_send_spy(); + agent_lock(); + heartbeat_set_live_config(ready); + agent_unlock(); + ASSERT(cron_job_create(id, "at:1", "remind me", "heartbeat", "default", due_at, 1) == 0); + ASSERT(cron->poll(&msg, 0) == 1); + g_spy_reply = silent ? "" : "delivered"; + if (silent) { + agent_lock(); + heartbeat_set_live_config(unavailable); + agent_unlock(); + } else { + g_reload_during_send = unavailable; + } + ASSERT(handle_message(cron, &msg) == (silent ? -1 : 0)); + ASSERT(g_send_calls == (silent ? 0 : 1) && !g_reload_during_send); + ASSERT(cron_job_get_by_id(id, &row) == silent); + if (silent) { + ASSERT(row.enabled && row.next_run == due_at); + ASSERT(cron_job_delete(id) == 0); + } else { + ASSERT(strcmp(g_last_text, "delivered") == 0); + } + cron_job_row_free(&row); + channel_incoming_msg_clear(&msg); + } + reset_send_spy(); + cron->cleanup(); + heartbeat->cleanup(); + memory_cleanup(); + config_free(ready); + config_free(unavailable); + unlink(path); + return 0; +} + static int test_api_session_delete_holds_agent_mutex(void) { const char *db_path = "build/test_dispatch_api_delete.db"; @@ -502,6 +677,8 @@ int main(void) RUN(test_handle_message_holds_agent_mutex()); RUN(test_cron_slash_commands_ack_jobs()); RUN(test_cron_agent_failure_does_not_ack()); + RUN(test_cron_blank_reply_acks_without_sending()); + RUN(test_cron_rechecks_heartbeat_only_for_silent_delivery()); puts("test_dispatch OK"); return 0; } diff --git a/tests/test_gateway_db_lock.c b/tests/test_gateway_db_lock.c index ed4fb882..df5889e1 100644 --- a/tests/test_gateway_db_lock.c +++ b/tests/test_gateway_db_lock.c @@ -4,6 +4,8 @@ */ #define _POSIX_C_SOURCE 200809L +#include "channels/channel.h" +#include "channels/webchat.h" #include "core/agent.h" #include "core/memory.h" #include "gateway/http_lws.h" @@ -50,11 +52,17 @@ static int test_dashboard_sqlite_holds_agent_lock(void) const char *path = "/tmp/shellclaw_test_gateway_db_lock.db"; const char *create_body = "{\"id\":\"job_lock\",\"schedule\":\"interval:3600\",\"message\":\"ping\"}"; + const char *invalid_body = + "{\"schedule\":\"interval:3600\",\"message\":\"ping\"," + "\"channel\":\"webchat\",\"recipient\":\"42\"}"; + char response[128]; int status = 0; memset(&ctx, 0, sizeof(ctx)); remove(path); ASSERT(memory_init(path) == 0); + channel_register("cli", channel_cli_get()); + channel_register("webchat", channel_webchat_get()); g_sqlite_hits = 0; g_sqlite_unlocked = 0; memory_sqlite_entry_set_hook_for_test(sqlite_probe); @@ -69,6 +77,10 @@ static int test_dashboard_sqlite_holds_agent_lock(void) ASSERT(status == 200); ASSERT(call_route(&ctx, HTTP_POST, "/api/cron", create_body, &status) == 0); ASSERT(status == 201); + ASSERT(dispatch_route(&ctx, NULL, HTTP_POST, "/api/cron", 9, invalid_body, + strlen(invalid_body), response, sizeof(response), &status) == 0); + ASSERT(status == 400); + ASSERT(strstr(response, "Invalid cron destination") != NULL); ASSERT(call_route(&ctx, HTTP_POST, "/api/cron/job_lock/toggle", NULL, &status) == 0); ASSERT(status == 200); ASSERT(call_route(&ctx, HTTP_DELETE, "/api/cron/job_lock", NULL, &status) == 0); diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index f2b6aab9..a1e61bc1 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -285,6 +285,91 @@ static int http_get(const char *url, long *code_out, char **body_out) return (res == CURLE_OK) ? 0 : -1; } +struct http_raw_body { + unsigned char data[65536]; + size_t len; +}; + +static size_t write_raw_cb(char *ptr, size_t size, size_t nmemb, void *user) +{ + struct http_raw_body *body = user; + size_t total = size * nmemb; + + if (!body || body->len + total > sizeof(body->data)) + return 0; + memcpy(body->data + body->len, ptr, total); + body->len += total; + return total; +} + +static int http_get_raw(const char *url, long *code_out, struct http_raw_body *body, + curl_off_t *cl_out) +{ + CURL *curl; + CURLcode res; + long code = 0; + curl_off_t cl = -1; + + if (!body) + return -1; + curl = curl_easy_init(); + if (!curl) + return -1; + body->len = 0; + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_raw_cb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, body); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L); + curl_easy_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 0L); + res = curl_easy_perform(curl); + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code); + curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &cl); + curl_easy_cleanup(curl); + if (code_out) + *code_out = code; + if (cl_out) + *cl_out = cl; + return (res == CURLE_OK) ? 0 : -1; +} + +static int raw_body_is_full_gzip(const struct http_raw_body *body, long code, + curl_off_t cl) +{ + if (!body || code != 200 || cl <= 4096) + return 0; + if (body->len != (size_t)cl || body->len < 2) + return 0; + return body->data[0] == 0x1f && body->data[1] == 0x8b; +} + +/* Static HTTP sends at most 4096 bytes per writable callback. These scripts + * gzip larger than that, so a stalled callback returns a short body. */ +static int test_static_js_body_completes(void) +{ + static const char *paths[] = { "/js/app.js", "/js/hardware.js" }; + struct http_raw_body *body; + size_t i; + + body = calloc(1, sizeof(*body)); + if (!body) + return 1; + for (i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + long code = 0; + curl_off_t cl = -1; + int rc = http_get_raw(gw_url(paths[i]), &code, body, &cl); + + if (rc != 0 || !raw_body_is_full_gzip(body, code, cl)) { + fprintf(stderr, + "static %s incomplete rc=%d code=%ld cl=%lld len=%zu\n", + paths[i], rc, code, (long long)cl, body->len); + free(body); + return 1; + } + } + free(body); + return 0; +} + static int http_post(const char *url, const char *json, long *code_out, char **body_out) { return http_post_raw(url, json, json ? strlen(json) : 0, NULL, code_out, body_out); @@ -1713,6 +1798,10 @@ int main(int argc, char **argv) failed++; } if (test_health() != 0) { fprintf(stderr, "test_health failed\n"); failed++; } + if (test_static_js_body_completes() != 0) { + fprintf(stderr, "test_static_js_body_completes failed\n"); + failed++; + } if (test_pair(pairing_code, token, sizeof(token)) != 0) { fprintf(stderr, "test_pair failed\n"); failed++; diff --git a/tests/test_hardware_camera.c b/tests/test_hardware_camera.c index 46fb2c1a..5f85574e 100644 --- a/tests/test_hardware_camera.c +++ b/tests/test_hardware_camera.c @@ -5,12 +5,13 @@ #include "test_runner.h" #include "hardware/hardware_camera.h" +#include #include #include #include #include -static char s_spawn_out_path[256]; +static char s_spawn_out_path[PATH_MAX]; static int s_spawn_fail; static int s_spawn_called; static int s_spawn_bad_jpeg; @@ -585,7 +586,6 @@ static int test_temp_jpeg_unlinked_on_spawn_failure(void) { char result[256]; char err[128]; - char leaked_path[256]; RUN(setup_mock()); s_spawn_fail = 1; ASSERT(hardware_camera_capture(BOARD_JETSON_ORIN_NANO, "csi", "640x480", 75, 0, @@ -593,8 +593,7 @@ static int test_temp_jpeg_unlinked_on_spawn_failure(void) sizeof(err)) == -1); ASSERT(strstr(err, HARDWARE_CAMERA_ERR_UNAVAILABLE) != NULL); ASSERT(s_spawn_out_path[0] != '\0'); - snprintf(leaked_path, sizeof(leaked_path), "%s", s_spawn_out_path); - ASSERT(access(leaked_path, F_OK) != 0); + ASSERT(access(s_spawn_out_path, F_OK) != 0); teardown(); return 0; } @@ -603,7 +602,6 @@ static int test_temp_jpeg_unlinked_on_invalid_jpeg(void) { char result[256]; char err[128]; - char leaked_path[256]; RUN(setup_mock()); s_spawn_bad_jpeg = 1; ASSERT(hardware_camera_capture(BOARD_JETSON_ORIN_NANO, "csi", "640x480", 75, 0, @@ -611,8 +609,7 @@ static int test_temp_jpeg_unlinked_on_invalid_jpeg(void) sizeof(err)) == -1); ASSERT(strstr(err, HARDWARE_CAMERA_ERR_UNAVAILABLE) != NULL); ASSERT(s_spawn_out_path[0] != '\0'); - snprintf(leaked_path, sizeof(leaked_path), "%s", s_spawn_out_path); - ASSERT(access(leaked_path, F_OK) != 0); + ASSERT(access(s_spawn_out_path, F_OK) != 0); teardown(); return 0; } @@ -641,6 +638,39 @@ static int test_caller_supplied_output_not_unlinked_on_error(void) return 0; } +static int test_capture_uses_the_entire_path(void) +{ + char ws[128]; + char path[257]; + char result[sizeof(path)]; + char err[128]; + size_t prefix; + + ASSERT(test_runner_mkdtemp_path("shellclaw_cam_path", ws, sizeof(ws)) == 0); + snprintf(path, sizeof(path), "%s/", ws); + prefix = strlen(path); + memset(path + prefix, 'a', sizeof(path) - prefix - 1); + path[sizeof(path) - 1] = '\0'; + RUN(setup_mock()); + hardware_camera_set_workspace(ws); + ASSERT(hardware_camera_capture(BOARD_RPI_ZERO2W, "csi", "640x480", 75, 0, 0, + path, result, sizeof(result) - 1, err, sizeof(err)) < 0); + ASSERT(!s_spawn_called); + ASSERT(hardware_camera_capture(BOARD_RPI_ZERO2W, "csi", "640x480", 75, 0, 0, + path, result, sizeof(result), err, sizeof(err)) == 0); + ASSERT(strcmp(result, path) == 0 && strcmp(s_spawn_out_path, path) == 0); + ASSERT(unlink(path) == 0); + ASSERT(hardware_camera_capture(BOARD_JETSON_ORIN_NANO, "csi", "640x480", 75, 0, 0, + path, result, sizeof(result), err, sizeof(err)) == 0); + ASSERT(strcmp(result, path) == 0 && strcmp(s_spawn_out_path, path) == 0); + ASSERT(unlink(path) == 0); + path[255] = '\0'; + ASSERT(access(path, F_OK) != 0); + ASSERT(rmdir(ws) == 0); + teardown(); + return 0; +} + static int test_default_spawn_times_out(void) { char *argv[] = { "/bin/sleep", "5", NULL }; @@ -679,6 +709,7 @@ int main(void) RUN(test_temp_jpeg_unlinked_on_spawn_failure()); RUN(test_temp_jpeg_unlinked_on_invalid_jpeg()); RUN(test_caller_supplied_output_not_unlinked_on_error()); + RUN(test_capture_uses_the_entire_path()); RUN(test_default_spawn_times_out()); printf("All hardware_camera tests passed.\n"); return 0; diff --git a/tests/test_hardware_tools.c b/tests/test_hardware_tools.c index 29d3acd2..ea4e0826 100644 --- a/tests/test_hardware_tools.c +++ b/tests/test_hardware_tools.c @@ -10,6 +10,8 @@ #include "core/config.h" #include "hardware/hardware.h" #include +#include +#include #include #include #include @@ -314,6 +316,82 @@ static int test_camera_capture_rejects_path_outside_workspace(void) return 0; } +static int write_test_jpeg(char *const argv[], char *errbuf, size_t errbufsz) +{ + FILE *file; + (void)errbuf; + (void)errbufsz; + ASSERT(strcmp(argv[1], "--output") == 0); + file = fopen(argv[2], "wb"); + ASSERT(file != NULL); + ASSERT(fwrite("\xff\xd8\xff\xd9", 1, 4, file) == 4); + return fclose(file); +} + +static int test_camera_tool_reports_the_full_path(void) +{ + char ws[128]; + char path[700]; + char args[sizeof(path) + 16]; + char result[sizeof(args)]; + size_t length; + size_t ends[2]; + config_t *cfg = NULL; + + ASSERT(test_runner_mkdtemp_path("shellclaw_cam_tool", ws, sizeof(ws)) == 0); + snprintf(path, sizeof(path), "%s", ws); + length = strlen(path); + for (size_t i = 0; i < 3; i++) { + path[length++] = '/'; + memset(path + length, 'a', 175); + length += 175; + path[length] = '\0'; + if (i < 2) { + ASSERT(mkdir(path, 0700) == 0); + ends[i] = length; + } + } + snprintf(args, sizeof(args), "{\"path\":\"%s\"}", path); + RUN(load_cfg("[agent]\nmodel = \"test\"\n[hardware]\nenabled = true\nboard = \"rpi\"\n" + "[sandbox]\nworkspace_only = false\n", &cfg)); + ASSERT(hardware_init(cfg) == 0); + tool_hardware_set_config(cfg); + hardware_camera_set_spawn_for_test(write_test_jpeg); + ASSERT(HW_TOOLS_CAMERA_CAPTURE.execute(args, result, strlen(args)) < 0); + ASSERT(access(path, F_OK) != 0); + ASSERT(HW_TOOLS_CAMERA_CAPTURE.execute(args, result, strlen(args) + 1) == 0); + ASSERT(strcmp(args, result) == 0); + ASSERT(unlink(path) == 0); + path[ends[1]] = '\0'; + ASSERT(rmdir(path) == 0); + path[ends[0]] = '\0'; + ASSERT(rmdir(path) == 0); + ASSERT(rmdir(ws) == 0); + hardware_camera_shutdown(); + tool_hardware_set_config(NULL); + config_free(cfg); + return 0; +} + +static int test_camera_tool_rejects_oversized_path(void) +{ + char path[PATH_MAX + 1]; + char args[sizeof(path) + 16]; + char result[128]; + config_t *cfg = NULL; + + memset(path, 'a', sizeof(path) - 1); + path[sizeof(path) - 1] = '\0'; + snprintf(args, sizeof(args), "{\"path\":\"%s\"}", path); + RUN(load_cfg("[agent]\nmodel = \"test\"\n[hardware]\nenabled = true\n", &cfg)); + tool_hardware_set_config(cfg); + ASSERT(HW_TOOLS_CAMERA_CAPTURE.execute(args, result, sizeof(result)) < 0); + ASSERT(strstr(result, "path too long") != NULL); + tool_hardware_set_config(NULL); + config_free(cfg); + return 0; +} + int main(void) { RUN(test_disabled_returns_error()); @@ -323,6 +401,8 @@ int main(void) RUN(test_gpio_mode_executes_json()); RUN(test_gpio_write_rejects_non_binary_value()); RUN(test_camera_capture_rejects_path_outside_workspace()); + RUN(test_camera_tool_rejects_oversized_path()); + RUN(test_camera_tool_reports_the_full_path()); RUN(test_i2c_read_success_with_mock()); RUN(test_i2c_invalid_addr()); RUN(test_i2c_default_bus_from_board()); diff --git a/tests/test_openai.c b/tests/test_openai.c index 2ac3829f..b23bdab7 100644 --- a/tests/test_openai.c +++ b/tests/test_openai.c @@ -175,12 +175,46 @@ static int test_parse_api_error_object_sets_error(void) return 0; } -static int test_parse_empty_choices_returns_zero(void) +static int test_parse_invalid_completion_returns_error(void) { - const char *body = "{\"choices\":[]}"; + const char *bodies[] = { + "{}", "{\"choices\":{}}", "{\"choices\":[]}", + "{\"choices\":[{}]}", "{\"choices\":[{\"message\":{}}]}", + "{\"choices\":[{\"message\":{\"content\":42}}]}", + "{\"choices\":[{\"message\":{\"content\":null,\"tool_calls\":{}}}]}", + "{\"choices\":[{\"message\":{\"content\":null,\"tool_calls\":[null]}}]}", + "{\"choices\":[{\"message\":{\"tool_calls\":[{\"id\":3,\"function\":{\"name\":\"echo\",\"arguments\":\"{}\"}}]}}]}", + "{\"choices\":[{\"message\":{\"tool_calls\":[{\"id\":\"x\",\"function\":{\"name\":\"echo\",\"arguments\":{}}}]}}]}", + }; + for (size_t i = 0; i < sizeof(bodies) / sizeof(bodies[0]); i++) { + provider_response_t response = {0}; + ASSERT(openai_parse_response_for_test(bodies[i], &response) == -1); + ASSERT(response.error != 0 && response.content && response.content[0]); + provider_response_clear(&response); + } + return 0; +} + +static int test_parse_silent_and_tool_only_messages(void) +{ + const char *silent[] = { + "{\"choices\":[{\"message\":{\"content\":null}}]}", + "{\"choices\":[{\"message\":{\"content\":null,\"tool_calls\":null}}]}", + "{\"choices\":[{\"message\":{\"content\":null,\"tool_calls\":[]}}]}", + }; + const char *tool_only = "{\"choices\":[{\"message\":{\"tool_calls\":[{\"id\":\"call_1\"," + "\"function\":{\"name\":\"echo\",\"arguments\":\"{}\"}}]}}]}"; provider_response_t response = {0}; - ASSERT(openai_parse_response_for_test(body, &response) == 0); - ASSERT(response.error == 0); + for (size_t i = 0; i < sizeof(silent) / sizeof(silent[0]); i++) { + ASSERT(openai_parse_response_for_test(silent[i], &response) == 0); + ASSERT(response.error == 0 && provider_text_is_blank(response.content)); + ASSERT(response.tool_calls_count == 0); + provider_response_clear(&response); + } + ASSERT(openai_parse_response_for_test(tool_only, &response) == 0); + ASSERT(response.error == 0 && provider_text_is_blank(response.content)); + ASSERT(response.tool_calls_count == 1 && response.tool_calls[0].name && + strcmp(response.tool_calls[0].name, "echo") == 0); provider_response_clear(&response); return 0; } @@ -326,7 +360,8 @@ int main(void) #ifdef SHELLCLAW_TEST RUN(test_parse_malformed_json_sets_error()); RUN(test_parse_api_error_object_sets_error()); - RUN(test_parse_empty_choices_returns_zero()); + RUN(test_parse_invalid_completion_returns_error()); + RUN(test_parse_silent_and_tool_only_messages()); RUN(test_parse_valid_message_returns_content()); RUN(test_parse_null_json_returns_error()); RUN(test_build_chat_body_serializes_tool_calls()); diff --git a/tests/test_sandbox.c b/tests/test_sandbox.c index e0820594..0aa98ed0 100644 --- a/tests/test_sandbox.c +++ b/tests/test_sandbox.c @@ -31,9 +31,13 @@ #include #include #include +#include #include +#include #include #include +#include +#include #endif #define ASSERT(c) do { \ @@ -1039,6 +1043,89 @@ static int test_scrubbed_env_child_loses_secrets(void) return 0; } +#ifdef __linux__ +int sandbox_isolate_namespaces(void); +int sandbox_seal_workspace_mounts(const char *workspace); + +static int mount_admin_was_removed(void) +{ + struct __user_cap_header_struct header = {.version = _LINUX_CAPABILITY_VERSION_3}; + struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3]; + unsigned int index = CAP_TO_INDEX(CAP_SYS_ADMIN); + __u32 mask = CAP_TO_MASK(CAP_SYS_ADMIN); + + return prctl(PR_CAPBSET_READ, CAP_SYS_ADMIN, 0, 0, 0) == 0 && + syscall(__NR_capget, &header, caps) == 0 && + ((caps[index].effective | caps[index].permitted | caps[index].inheritable) & mask) == 0; +} + +static int test_legacy_workspace_mount_guard(void) +{ + char parent[] = "/tmp/sc_mount_guard_XXXXXX"; + char workspace[sizeof(parent) + sizeof("/workspace")]; + char nested[sizeof(workspace) + sizeof("/locked")]; + char output[sizeof(workspace) + sizeof("/result")]; + struct statvfs original; + struct statvfs after; + int status = 0; + pid_t child; + + ASSERT(mkdtemp(parent) != NULL); + snprintf(workspace, sizeof(workspace), "%s/workspace", parent); + snprintf(nested, sizeof(nested), "%s/locked", workspace); + snprintf(output, sizeof(output), "%s/result", workspace); + ASSERT(mkdir(workspace, 0700) == 0); + ASSERT(mkdir(nested, 0700) == 0); + ASSERT(statvfs(parent, &original) == 0); + child = fork(); + ASSERT(child >= 0); + if (child == 0) { + pid_t command; + int fd; + if (sandbox_isolate_namespaces() != 0) + _exit(77); + if (mount("tmpfs", nested, "tmpfs", MS_NOSUID | MS_NODEV, "size=4k") != 0) + _exit(77); + if (mount(NULL, nested, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV, + NULL) != 0 || + sandbox_seal_workspace_mounts(workspace) != 0) + _exit(1); + if (statvfs(parent, &after) != 0 || !(after.f_flag & ST_RDONLY) || + statvfs(".", &after) != 0 || (after.f_flag & ST_RDONLY) || + statvfs("locked", &after) != 0 || + (after.f_flag & (ST_RDONLY | ST_NOSUID)) != (ST_RDONLY | ST_NOSUID)) + _exit(2); + fd = open("result", O_CREAT | O_WRONLY, 0600); + if (fd < 0 || write(fd, "sample", 6) != 6 || close(fd) != 0) + _exit(3); + command = fork(); + if (command == 0) { + if (!mount_admin_was_removed()) + _exit(1); + _exit(truncate("result", 2) != 0); + } + if (command < 0 || waitpid(command, &status, 0) != command || + !WIFEXITED(status) || WEXITSTATUS(status) != 0) + _exit(4); + _exit(0); + } + ASSERT(waitpid(child, &status, 0) == child); + ASSERT(statvfs(parent, &after) == 0 && original.f_flag == after.f_flag); + unlink(output); + ASSERT(rmdir(nested) == 0); + ASSERT(rmdir(workspace) == 0); + ASSERT(rmdir(parent) == 0); + if (WIFEXITED(status) && WEXITSTATUS(status) == 77) { + fprintf(stderr, "test_sandbox: skip legacy mount guard (namespaces unavailable)\n"); + return 0; + } + if (WIFEXITED(status) && WEXITSTATUS(status) != 0) + fprintf(stderr, "test_sandbox: legacy mount guard child exit=%d\n", WEXITSTATUS(status)); + ASSERT(WIFEXITED(status) && WEXITSTATUS(status) == 0); + return 0; +} +#endif + int main(void) { RUN(test_isolation_denied_helper()); @@ -1063,6 +1150,7 @@ int main(void) RUN(test_timeout_kills_trickle_output()); RUN(test_timeout_kills_process()); #ifdef __linux__ + RUN(test_legacy_workspace_mount_guard()); RUN(test_landlock_probe_without_restrict()); RUN(test_command_inherits_cgroup()); RUN(test_inherited_fd_is_closed()); diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index d0f8451c..4723668c 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -5,6 +5,9 @@ */ 'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); const dash = require('../web/js/dashboardView.js'); const hw = require('../web/js/hardwareView.js'); const escapeHtml = dash.escapeHtml; @@ -19,6 +22,36 @@ function assert(cond, msg) { } } +function testPairedChatDisplaysRepliesAsText() { + let connection; + const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' }; + const log = { textContent: '' }; + const elements = { app: {}, 'chat-log': log, 'chat-input': {} }; + const token = '1234567890abcdef1234567890abcdef'; + const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8'); + vm.runInNewContext(script, { + location, + window: { location, addEventListener() {} }, + document: { getElementById: id => elements[id], querySelectorAll: () => [] }, + localStorage: { getItem: key => key === 'shellclaw_token' ? token : null }, + WebSocket: function (url, protocols) { + this.url = url; + this.protocols = protocols; + connection = this; + }, + }); + const replies = ['The card is blue.', '{"type":"provider_status","providers":[]}', + '"Café" azul']; + replies.forEach(text => connection.onmessage({ data: text })); + assert(log.textContent === replies.join('\n') + '\n', 'chat displays each reply as text'); + assert(log.innerHTML === undefined, 'chat does not insert reply markup'); + assert(connection.url === 'wss://localhost/ws?view=chat', 'chat requests the replies-only socket'); + assert(connection.protocols.length === 2 && connection.protocols[0] === 'ws' && + connection.protocols[1] === 'bearer.' + token, 'paired chat offers both WebSocket protocols'); +} + +testPairedChatDisplaysRepliesAsText(); + assert(escapeHtml(null) === '', 'null'); assert(escapeHtml(undefined) === '', 'undefined'); assert(escapeHtml('').indexOf('