From 317741c46e38f179f8cf9b7ff8eabe9edceae60d Mon Sep 17 00:00:00 2001 From: Alfred Date: Sun, 8 Nov 2026 16:17:22 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=8F=91=E5=B8=83=20v0.6.5=EF=BC=9AAPI=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E3=80=81=E8=BF=90=E8=A1=8C=E6=97=B6=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E4=B8=8E=20Web=20UI=20=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 52 +- CMakeLists.txt | 17 +- cmake/http_transport_polling.cmake | 80 + cmake/httpd_admission.cmake | 28 +- cmake/json_limits.cmake | 6 + cmake/security_profile.cmake | 25 + components/ts_api/CMakeLists.txt | 4 +- components/ts_api/include/ts_api.h | 16 +- components/ts_api/include/ts_api_params.h | 97 + components/ts_api/include/ts_api_policy.h | 30 + components/ts_api/src/ts_api.c | 274 ++- components/ts_api/src/ts_api_auth.c | 95 +- components/ts_api/src/ts_api_automation.c | 1027 +++++----- components/ts_api/src/ts_api_cert.c | 35 +- components/ts_api/src/ts_api_config.c | 34 +- components/ts_api/src/ts_api_config_pack.c | 112 +- components/ts_api/src/ts_api_device.c | 217 ++- components/ts_api/src/ts_api_dhcp.c | 12 +- components/ts_api/src/ts_api_fan.c | 114 +- components/ts_api/src/ts_api_gpio.c | 12 +- components/ts_api/src/ts_api_hosts.c | 32 +- components/ts_api/src/ts_api_key.c | 284 +-- components/ts_api/src/ts_api_led.c | 170 +- components/ts_api/src/ts_api_log.c | 14 +- components/ts_api/src/ts_api_lpmu_access.c | 12 +- components/ts_api/src/ts_api_monitor.c | 24 +- components/ts_api/src/ts_api_nat.c | 10 +- components/ts_api/src/ts_api_network.c | 23 +- components/ts_api/src/ts_api_ota.c | 392 ++-- components/ts_api/src/ts_api_pack.h | 1 + components/ts_api/src/ts_api_power.c | 30 +- components/ts_api/src/ts_api_service.c | 10 + components/ts_api/src/ts_api_sftp.c | 14 +- components/ts_api/src/ts_api_ssh.c | 123 +- components/ts_api/src/ts_api_storage.c | 89 +- components/ts_api/src/ts_api_system.c | 301 +-- components/ts_api/src/ts_api_temp.c | 58 +- components/ts_api/src/ts_api_time.c | 20 +- components/ts_api/src/ts_api_ui.c | 8 +- components/ts_api/src/ts_api_wifi.c | 10 +- .../ts_api/src/ts_api_ws_test_transport.c | 174 ++ .../ts_api/src/ts_api_ws_test_transport.h | 17 + components/ts_auth_layout/CMakeLists.txt | 6 +- .../ts_auth_layout/include/ts_auth_layout.h | 36 +- .../ts_auth_layout/src/ts_auth_credential.c | 83 + components/ts_automation/CMakeLists.txt | 1 + .../ts_automation/include/ts_source_manager.h | 5 +- .../ts_automation/src/ts_action_manager.c | 79 +- .../ts_automation/src/ts_automation_file.c | 101 +- .../ts_automation/src/ts_automation_legacy.c | 21 +- .../ts_automation/src/ts_source_manager.c | 230 +-- components/ts_cert/include/ts_cert.h | 5 + components/ts_cert/src/ts_cert.c | 106 +- components/ts_config_pack/CMakeLists.txt | 1 + .../ts_config_pack/include/ts_config_pack.h | 25 +- .../ts_config_pack/src/ts_config_pack.c | 1099 +++-------- .../ts_config_pack/src/ts_config_pack_trust.c | 24 +- .../ts_config_pack/src/ts_config_pack_trust.h | 6 + components/ts_console/commands/ts_cmd_fs.c | 2 +- components/ts_console/commands/ts_cmd_key.c | 4 +- components/ts_console/commands/ts_cmd_led.c | 37 +- components/ts_console/commands/ts_cmd_pki.c | 2 +- components/ts_console/commands/ts_cmd_sftp.c | 4 +- components/ts_console/commands/ts_cmd_ssh.c | 4 +- .../ts_console/src/ts_console_builtin.c | 1 + .../ts_config/include/ts_config_file.h | 15 +- .../ts_config/include/ts_config_partitions.h | 4 +- .../ts_core/ts_config/src/ts_config_file.c | 87 +- .../ts_core/ts_config/src/ts_config_migrate.c | 57 +- .../ts_core/ts_event/include/ts_event.h | 9 +- .../ts_core/ts_event/include/ts_ota_events.h | 17 + components/ts_dns/CMakeLists.txt | 6 + components/ts_dns/include/ts_dns.h | 12 + components/ts_dns/src/ts_dns.c | 120 ++ components/ts_drivers/CMakeLists.txt | 1 + .../ts_drivers/src/ts_compute_monitor.c | 123 +- components/ts_drivers/src/ts_device_ctrl.c | 50 +- components/ts_http_fetch/CMakeLists.txt | 6 + .../ts_http_fetch/include/ts_http_fetch.h | 42 + .../ts_http_fetch/include/ts_http_url.h | 10 + components/ts_http_fetch/src/ts_http_fetch.c | 196 ++ components/ts_http_fetch/src/ts_http_target.c | 48 + components/ts_http_fetch/src/ts_http_url.c | 42 + components/ts_https/include/ts_https.h | 2 +- components/ts_https/src/ts_https.c | 101 +- components/ts_https/src/ts_https_auth.c | 54 +- components/ts_https/src/ts_https_internal.h | 4 +- components/ts_net/CMakeLists.txt | 10 + components/ts_net/include/ts_http_server.h | 42 +- components/ts_net/include/ts_net.h | 1 + components/ts_net/include/ts_net_manager.h | 2 + components/ts_net/include/ts_time_sync.h | 2 + components/ts_net/src/ts_dhcp_server.c | 10 + components/ts_net/src/ts_eth.c | 19 + components/ts_net/src/ts_http_origin.c | 168 ++ components/ts_net/src/ts_http_server.c | 203 +- components/ts_net/src/ts_https_server.c | 34 +- components/ts_net/src/ts_net.c | 16 + components/ts_net/src/ts_net_manager.c | 19 +- components/ts_net/src/ts_time_sync.c | 6 + components/ts_ota/include/ts_ota.h | 15 +- components/ts_ota/src/ts_ota.c | 17 +- components/ts_ota/src/ts_ota_www.c | 4 +- components/ts_pki_client/CMakeLists.txt | 2 +- .../ts_pki_client/include/ts_pki_client.h | 3 +- components/ts_pki_client/src/ts_pki_client.c | 500 ++--- components/ts_security/CMakeLists.txt | 1 + components/ts_security/include/ts_keystore.h | 37 +- components/ts_security/include/ts_security.h | 10 +- components/ts_security/src/ts_auth.c | 317 ++-- components/ts_security/src/ts_keystore.c | 739 ++++---- components/ts_security/src/ts_security.c | 129 +- components/ts_storage/CMakeLists.txt | 3 +- components/ts_storage/include/ts_file_store.h | 29 + components/ts_storage/include/ts_storage.h | 17 +- components/ts_storage/src/ts_file_store.c | 131 ++ components/ts_storage/src/ts_storage.c | 58 + components/ts_storage/src/ts_storage_paths.c | 127 +- components/ts_storage/src/ts_storage_sd.c | 21 +- components/ts_webui/Kconfig | 5 - components/ts_webui/include/ts_webui.h | 7 + components/ts_webui/include/ts_ws_operation.h | 2 + components/ts_webui/include/ts_ws_transport.h | 4 + components/ts_webui/src/ts_webui_api.c | 509 ++--- components/ts_webui/src/ts_webui_ws.c | 191 +- components/ts_webui/src/ts_ws_operation.c | 21 +- components/ts_webui/src/ts_ws_subscriptions.c | 23 +- components/ts_webui/src/ts_ws_transport.c | 42 +- components/ts_webui/web/css/style.css | 14 +- components/ts_webui/web/index.html | 2 +- components/ts_webui/web/js/api.js | 369 ++-- components/ts_webui/web/js/app.js | 263 +-- components/ts_webui/web/js/lang/en-US.js | 9 +- components/ts_webui/web/js/lang/zh-CN.js | 9 +- components/ts_webui/web/js/terminal.js | 14 +- docs/API_REFERENCE.md | 7 + docs/releases/v0.6.5.md | 42 + docs/repair/xterm-local/requests-en-US.json | 35 +- docs/repair/xterm-local/requests-zh-CN.json | 33 +- docs/security/pki-bootstrap.md | 14 + main/main.c | 2 + main/root_password_reset_main.c | 71 +- main/ts_services.c | 42 +- sdkconfig | 10 +- sdkconfig.defaults | 9 +- tests/certificate/README.md | 8 +- tests/certificate/generate_fixtures.py | 24 +- tests/certificate/run_host.sh | 7 +- tests/certificate/stubs/esp_https_server.h | 2 +- tests/certificate/stubs/esp_timer.h | 2 + tests/certificate/stubs/ts_time_sync.h | 4 + tests/certificate/test_coordinator.c | 3 +- tests/certificate/test_https_auth.c | 128 ++ tests/certificate/test_https_auth.py | 75 + tests/certificate/test_time_cancel.c | 4 +- tests/ci/test_policy.py | 30 +- tests/exec_results/run_host.sh | 5 +- tests/fan_review/test_review.c | 1 + tests/fixtures/failure-texts/system.json | 4 +- .../failure-wire/wire-pack-unsupported.json | 1 + tests/macos27/ui-correction.browser.cjs | 2 +- tests/prompts/api-methods.browser.test.cjs | 47 + tests/prompts/api-methods.json | 289 +++ tests/prompts/api-methods.test.cjs | 73 + tests/prompts/failure-catalog.test.cjs | 8 +- tests/prompts/file-images.browser.test.cjs | 77 + tests/prompts/flows.browser.test.cjs | 25 +- tests/prompts/harness.cjs | 2 +- .../key-generation-cache.browser.test.cjs | 11 +- tests/prompts/key-generation.test.cjs | 2 +- tests/prompts/lpmu-lifecycle.browser.test.cjs | 2 +- tests/prompts/origin.browser.test.cjs | 61 + tests/prompts/ota.browser.test.cjs | 43 + tests/prompts/ownership.browser.test.cjs | 35 +- tests/prompts/package.json | 4 +- tests/prompts/pagekit.cjs | 59 +- tests/prompts/proxy-samples.browser.test.cjs | 22 + tests/prompts/rule-pack.browser.test.cjs | 209 --- tests/prompts/ws-input.browser.test.cjs | 60 + tests/release/test_release.py | 62 +- tests/release/test_security_profile.py | 121 ++ tests/release/test_serial_upgrade.py | 6 +- tests/runtime/api-policy-contract.json | 1664 +++++++++++++++++ tests/runtime/dhcp_bindings/test_bindings.c | 20 +- .../dhcp_bindings/test_eth_lifecycle.inc | 15 +- tests/runtime/host_env.sh | 7 + tests/runtime/host_paths.py | 29 + .../http_fetch_stubs/esp_http_client.h | 29 + tests/runtime/rule_pack/stubs/esp_err.h | 1 + tests/runtime/rule_pack/test_crypto.c | 158 +- tests/runtime/rule_pack/test_file_trust.c | 61 + tests/runtime/run_all.sh | 42 + tests/runtime/run_codec.sh | 3 +- tests/runtime/run_config_storage.sh | 18 +- tests/runtime/run_log.sh | 3 +- tests/runtime/run_rule_pack.sh | 2 + tests/runtime/run_service_runs.sh | 3 +- tests/runtime/run_ssh.sh | 3 +- tests/runtime/run_storage_paths.sh | 7 +- tests/runtime/storage_stubs/esp_random.h | 2 + tests/runtime/test_agx_reset.py | 192 ++ tests/runtime/test_api_access.py | 60 + tests/runtime/test_api_context.py | 66 + tests/runtime/test_api_diagnostic_privacy.py | 104 ++ tests/runtime/test_api_numeric_security.py | 223 +++ tests/runtime/test_api_prebody.py | 163 ++ tests/runtime/test_auth_persistence.py | 772 ++++++++ tests/runtime/test_automation_config.c | 48 +- tests/runtime/test_automation_file.c | 5 +- tests/runtime/test_automation_legacy.c | 10 +- tests/runtime/test_browser_origin.py | 239 +++ tests/runtime/test_cert_admission.py | 151 ++ tests/runtime/test_complete_api_inventory.py | 128 ++ tests/runtime/test_completion.py | 3 +- tests/runtime/test_compute_monitor.py | 65 +- tests/runtime/test_config_privacy.py | 269 +++ tests/runtime/test_console_lifecycle.py | 5 +- tests/runtime/test_default_deny_policy.py | 80 + tests/runtime/test_dhcp_bindings.py | 6 +- tests/runtime/test_dns_lifecycle.py | 141 ++ tests/runtime/test_exec_delivery.py | 26 + tests/runtime/test_expansion.py | 3 +- tests/runtime/test_external_storage_reads.py | 117 ++ tests/runtime/test_external_storage_writes.py | 86 + tests/runtime/test_failure_wire.py | 6 +- tests/runtime/test_http_body_integrity.py | 93 + tests/runtime/test_http_client_privacy.py | 172 ++ tests/runtime/test_http_fetch.py | 126 ++ tests/runtime/test_http_file_stream.py | 78 +- tests/runtime/test_http_transport_polling.py | 97 + tests/runtime/test_https_startup.py | 87 + tests/runtime/test_json_depth.py | 73 + tests/runtime/test_keystore.py | 185 +- tests/runtime/test_led_controls.py | 55 +- tests/runtime/test_led_file_reads.py | 67 + tests/runtime/test_log_delivery.py | 29 + tests/runtime/test_network_diagnostics.py | 182 ++ tests/runtime/test_ota_lifecycle.py | 13 +- tests/runtime/test_ota_upload_handlers.py | 84 + tests/runtime/test_pki_http.py | 152 ++ tests/runtime/test_power_settings.py | 3 +- tests/runtime/test_probe.py | 3 +- tests/runtime/test_proxy_ws_samples.py | 300 +++ tests/runtime/test_receive_budget.py | 114 ++ tests/runtime/test_registry_tables.py | 6 +- tests/runtime/test_request_params.py | 104 ++ tests/runtime/test_rule_pack_crypto.py | 69 +- tests/runtime/test_sdk_diagnostic_privacy.py | 144 ++ tests/runtime/test_sensitive_auth.py | 773 +++++--- tests/runtime/test_service_control.py | 3 +- tests/runtime/test_source_sampling.py | 140 +- tests/runtime/test_ssh_cli_controls.py | 17 +- tests/runtime/test_ssh_copyid.py | 4 +- tests/runtime/test_ssh_fingerprint_wire.py | 32 +- tests/runtime/test_storage_paths.c | 226 ++- tests/runtime/test_system_migration.c | 35 +- tests/runtime/test_system_reboot.py | 6 +- tests/runtime/test_unimplemented_results.py | 74 + tests/runtime/test_ws_diagnostic_transport.py | 138 ++ tests/runtime/test_ws_sdk_lifecycle.py | 135 ++ tests/ws_subscriptions/run_control.sh | 6 +- tests/ws_subscriptions/run_host.sh | 2 +- tests/ws_subscriptions/run_input_admission.py | 18 + .../ws_subscriptions/run_operation_adapter.sh | 3 + tests/ws_subscriptions/run_reviewer.sh | 6 +- .../ws_subscriptions/stubs/esp_https_server.h | 2 + tests/ws_subscriptions/stubs/platform.h | 6 +- tests/ws_subscriptions/stubs/ts_api_params.h | 3 + tests/ws_subscriptions/stubs/ts_ota.h | 1 + tests/ws_subscriptions/stubs/ts_ota_events.h | 1 + tests/ws_subscriptions/test_control.c | 29 +- tests/ws_subscriptions/test_exec_api.c | 25 + tests/ws_subscriptions/test_exec_ownership.c | 81 + tests/ws_subscriptions/test_exec_results.c | 2 +- tests/ws_subscriptions/test_f1_f2.c | 6 +- tests/ws_subscriptions/test_http_auth.c | 53 +- tests/ws_subscriptions/test_input_admission.c | 63 + tests/ws_subscriptions/test_manager.c | 12 + tests/ws_subscriptions/test_operation.c | 8 +- .../ws_subscriptions/test_operation_adapter.c | 70 +- tests/ws_subscriptions/test_reviewer_http.c | 9 +- tests/ws_subscriptions/test_terminal_auth.c | 68 +- tests/ws_subscriptions/test_terminal_jobs.c | 28 +- tests/ws_subscriptions/test_ws_log_privacy.c | 21 + tools/build_root_reset.sh | 4 +- tools/check_release.py | 64 +- tools/ci/check_profile.py | 2 +- tools/ci/check_release_state.py | 5 +- tools/gen_version.py | 46 +- tools/make_firmware_manifest.py | 2 +- tools/minify_web.py | 5 +- tools/prepare_http_transport_polling.py | 198 ++ tools/prepare_httpd_admission.py | 194 +- tools/serial_upgrade.py | 9 +- version.txt | 2 +- 295 files changed, 17549 insertions(+), 5309 deletions(-) create mode 100644 cmake/http_transport_polling.cmake create mode 100644 cmake/json_limits.cmake create mode 100644 cmake/security_profile.cmake create mode 100644 components/ts_api/include/ts_api_params.h create mode 100644 components/ts_api/include/ts_api_policy.h create mode 100644 components/ts_api/src/ts_api_ws_test_transport.c create mode 100644 components/ts_api/src/ts_api_ws_test_transport.h create mode 100644 components/ts_auth_layout/src/ts_auth_credential.c create mode 100644 components/ts_core/ts_event/include/ts_ota_events.h create mode 100644 components/ts_dns/CMakeLists.txt create mode 100644 components/ts_dns/include/ts_dns.h create mode 100644 components/ts_dns/src/ts_dns.c create mode 100644 components/ts_http_fetch/CMakeLists.txt create mode 100644 components/ts_http_fetch/include/ts_http_fetch.h create mode 100644 components/ts_http_fetch/include/ts_http_url.h create mode 100644 components/ts_http_fetch/src/ts_http_fetch.c create mode 100644 components/ts_http_fetch/src/ts_http_target.c create mode 100644 components/ts_http_fetch/src/ts_http_url.c create mode 100644 components/ts_net/src/ts_http_origin.c create mode 100644 components/ts_storage/include/ts_file_store.h create mode 100644 components/ts_storage/src/ts_file_store.c create mode 100644 docs/releases/v0.6.5.md create mode 100644 docs/security/pki-bootstrap.md create mode 100644 tests/certificate/stubs/esp_timer.h create mode 100644 tests/certificate/test_https_auth.c create mode 100644 tests/certificate/test_https_auth.py create mode 100644 tests/fixtures/failure-wire/wire-pack-unsupported.json create mode 100644 tests/prompts/api-methods.browser.test.cjs create mode 100644 tests/prompts/api-methods.json create mode 100644 tests/prompts/api-methods.test.cjs create mode 100644 tests/prompts/file-images.browser.test.cjs create mode 100644 tests/prompts/origin.browser.test.cjs create mode 100644 tests/prompts/proxy-samples.browser.test.cjs delete mode 100644 tests/prompts/rule-pack.browser.test.cjs create mode 100644 tests/prompts/ws-input.browser.test.cjs create mode 100644 tests/release/test_security_profile.py create mode 100644 tests/runtime/api-policy-contract.json create mode 100644 tests/runtime/host_env.sh create mode 100644 tests/runtime/host_paths.py create mode 100644 tests/runtime/http_fetch_stubs/esp_http_client.h create mode 100644 tests/runtime/rule_pack/test_file_trust.c create mode 100644 tests/runtime/test_agx_reset.py create mode 100644 tests/runtime/test_api_access.py create mode 100644 tests/runtime/test_api_context.py create mode 100644 tests/runtime/test_api_diagnostic_privacy.py create mode 100644 tests/runtime/test_api_numeric_security.py create mode 100644 tests/runtime/test_api_prebody.py create mode 100644 tests/runtime/test_auth_persistence.py create mode 100644 tests/runtime/test_browser_origin.py create mode 100644 tests/runtime/test_cert_admission.py create mode 100644 tests/runtime/test_complete_api_inventory.py create mode 100644 tests/runtime/test_config_privacy.py create mode 100644 tests/runtime/test_default_deny_policy.py create mode 100644 tests/runtime/test_dns_lifecycle.py create mode 100644 tests/runtime/test_exec_delivery.py create mode 100644 tests/runtime/test_external_storage_reads.py create mode 100644 tests/runtime/test_external_storage_writes.py create mode 100644 tests/runtime/test_http_body_integrity.py create mode 100644 tests/runtime/test_http_client_privacy.py create mode 100644 tests/runtime/test_http_fetch.py create mode 100644 tests/runtime/test_http_transport_polling.py create mode 100644 tests/runtime/test_https_startup.py create mode 100644 tests/runtime/test_json_depth.py create mode 100644 tests/runtime/test_led_file_reads.py create mode 100644 tests/runtime/test_log_delivery.py create mode 100644 tests/runtime/test_network_diagnostics.py create mode 100644 tests/runtime/test_ota_upload_handlers.py create mode 100644 tests/runtime/test_pki_http.py create mode 100644 tests/runtime/test_proxy_ws_samples.py create mode 100644 tests/runtime/test_receive_budget.py create mode 100644 tests/runtime/test_request_params.py create mode 100644 tests/runtime/test_sdk_diagnostic_privacy.py create mode 100644 tests/runtime/test_unimplemented_results.py create mode 100644 tests/runtime/test_ws_diagnostic_transport.py create mode 100644 tests/runtime/test_ws_sdk_lifecycle.py create mode 100644 tests/ws_subscriptions/run_input_admission.py create mode 100644 tests/ws_subscriptions/stubs/esp_https_server.h create mode 100644 tests/ws_subscriptions/stubs/ts_api_params.h create mode 100644 tests/ws_subscriptions/stubs/ts_ota.h create mode 100644 tests/ws_subscriptions/stubs/ts_ota_events.h create mode 100644 tests/ws_subscriptions/test_exec_ownership.c create mode 100644 tests/ws_subscriptions/test_input_admission.c create mode 100644 tests/ws_subscriptions/test_ws_log_privacy.c create mode 100644 tools/prepare_http_transport_polling.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 722ec0a4..a55ae931 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,4 @@ -name: TianShanOS Build +name: TianshanOS Build on: push: @@ -38,6 +38,7 @@ jobs: node-version: '22' - run: python3 -m unittest discover -s tests/ci -p 'test_*.py' - run: python3 tests/release/test_release.py + - run: python3 tests/release/test_security_profile.py - run: python3 tests/release/test_serial_upgrade.py - name: Select checks and release eligibility id: scope @@ -62,13 +63,16 @@ jobs: working-directory: tests/prompts run: npx playwright install --with-deps chrome - run: npm run test:browser --prefix tests/prompts + env: + TS_TEST_WEB_TLS: '1' + NODE_PATH: ${{ github.workspace }}/tests/prompts/node_modules - name: Offline xterm and vendor regressions run: npm run test:xterm --prefix tests/prompts env: OFFLINE_RESULTS: ${{ runner.temp }}/xterm-source runtime-tests: - needs: changes + needs: [changes, build] if: needs.changes.outputs.run_full == 'true' name: Runtime and fan regression tests runs-on: ubuntu-latest @@ -85,11 +89,16 @@ jobs: export IDF_PATH="$RUNNER_TEMP/runtime-idf" echo "IDF_PATH=$IDF_PATH" >> "$GITHUB_ENV" git clone --depth 1 --branch "$IDF_VERSION" --filter=blob:none --sparse https://github.com/espressif/esp-idf.git "$IDF_PATH" - git -C "$IDF_PATH" sparse-checkout set components/json components/mbedtls components/nvs_flash components/console components/soc components/bootloader_support components/esp_app_format components/esp_http_server components/lwip components/esp_netif + git -C "$IDF_PATH" sparse-checkout set components/json components/mbedtls components/nvs_flash components/console components/soc components/bootloader_support components/esp_app_format components/esp_http_server components/esp_https_server components/http_parser components/esp_http_client components/esp_system components/esp-tls components/tcp_transport components/spiffs components/vfs components/lwip components/esp_netif git -C "$IDF_PATH" submodule update --init --recursive --depth 1 components/json/cJSON components/mbedtls/mbedtls - uses: actions/setup-node@v4 with: node-version: '22' + - name: Fetch the managed WebSocket source from this exact build + uses: actions/download-artifact@v4 + with: + name: runtime-dependencies-${{ github.sha }} + path: managed_components/espressif__esp_websocket_client - run: bash tests/runtime/run_all.sh - run: bash tests/ws_subscriptions/run_operation_adapter.sh - name: Current WebSocket and lifecycle regressions @@ -185,6 +194,15 @@ jobs: rm -f build/CMakeCache.txt idf.py build + - name: Preserve the exact managed source used by runtime fixtures + uses: actions/upload-artifact@v4 + with: + name: runtime-dependencies-${{ github.sha }} + path: managed_components/espressif__esp_websocket_client/ + include-hidden-files: true + if-no-files-found: error + retention-days: 7 + - name: Get version info id: version run: | @@ -216,6 +234,9 @@ jobs: if-no-files-found: error retention-days: 7 + - name: Bind security build policy to this firmware + run: python3 tools/check_release.py --seal-build build + - name: Package USB / serial partition upgrade run: python3 tools/serial_upgrade.py package --build-dir build --output "build/tianshanos-serial-v$(cat version.txt)" @@ -229,6 +250,8 @@ jobs: build/partition_table/partition-table.bin build/flasher_args.json build/tianshanos-serial-*.zip + build/security-build.json + build/security-artifact.json retention-days: 30 - name: Upload full build (for debugging) @@ -313,26 +336,25 @@ jobs: GH_TOKEN: ${{ github.token }} BUILD_VERSION: ${{ needs.build.outputs.version }} BUILD_COMMIT: ${{ needs.build.outputs.commit }} - - name: Add build identity to the Chinese release notes + - name: Normalize public firmware filename run: | python3 - <<'PYTHON' - import os + import json from pathlib import Path - notes = Path('docs/releases') / (os.environ['RELEASE_TAG'] + '.md') - with notes.open('a') as output: - output.write('\n\n## 本次构建\n\n') - output.write('固件版本:`' + os.environ['BUILD_VERSION'] + '`\n\n') - output.write('源码提交:`' + os.environ['BUILD_COMMIT'] + '`\n') + root = Path('firmware') + (root / 'TianShanOS.bin').rename(root / 'TianshanOS.bin') + args = root / 'flasher_args.json' + data = json.loads(args.read_text()) + data['app']['file'] = 'TianshanOS.bin' + data['flash_files'] = {address: 'TianshanOS.bin' if name == 'TianShanOS.bin' else name for address, name in data['flash_files'].items()} + args.write_text(json.dumps(data, indent=2) + '\n') PYTHON - env: - RELEASE_TAG: ${{ steps.preflight.outputs.tag }} - BUILD_VERSION: ${{ needs.build.outputs.version }} - BUILD_COMMIT: ${{ needs.build.outputs.commit }} + - name: Create or upload the release assets uses: softprops/action-gh-release@v2 with: tag_name: ${{ steps.preflight.outputs.tag }} - name: ${{ steps.preflight.outputs.tag }} + name: TianshanOS ${{ steps.preflight.outputs.tag }} files: | firmware/**/*.bin firmware/**/flasher_args.json diff --git a/CMakeLists.txt b/CMakeLists.txt index d6cb476f..6feaf047 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,8 +8,8 @@ cmake_minimum_required(VERSION 3.16) # ============================================================================ # 版本管理 - 使用 Python 脚本生成版本号 -# 格式: MAJOR.MINOR.PATCH+HASH.TIMESTAMP -# 例如: 0.3.1+7fdcca4d.01311234 +# 格式: MAJOR.MINOR.PATCH+SOURCE_ID(不包含日期/时间) +# 例如: 0.6.5+7fdcca4d # # 配置阶段会生成版本号,每次 fullClean 或手动 reconfigure 会更新时间戳 # ============================================================================ @@ -69,7 +69,7 @@ if(ROOT_PASSWORD_RESET) set(TIANSHAN_VERSION_BUILD "") endif() if(NOT ROOT_PASSWORD_RESET_RUN_ID) - string(TIMESTAMP ROOT_PASSWORD_RESET_RUN_ID "%H%M%S") + string(SHA256 ROOT_PASSWORD_RESET_RUN_ID "${TIANSHAN_VERSION_DISPLAY}") endif() string(REGEX REPLACE "[^a-zA-Z0-9.]" "." ROOT_PASSWORD_RESET_RUN_ID "${ROOT_PASSWORD_RESET_RUN_ID}") string(SUBSTRING "${ROOT_PASSWORD_RESET_RUN_ID}" 0 13 ROOT_PASSWORD_RESET_RUN_ID) @@ -114,10 +114,19 @@ if(ROOT_PASSWORD_RESET) endif() # 项目定义 -project(TianShanOS VERSION ${TIANSHAN_VERSION_MAJOR}.${TIANSHAN_VERSION_MINOR}.${TIANSHAN_VERSION_PATCH}) +# Disabling application authorization is an explicit, separately named build. +option(TS_DEVELOPMENT_BUILD "Build development-only firmware (never release)" OFF) +if(TS_DEVELOPMENT_BUILD) + project(TianShanOS_Dev VERSION ${TIANSHAN_VERSION_MAJOR}.${TIANSHAN_VERSION_MINOR}.${TIANSHAN_VERSION_PATCH}) +else() + project(TianShanOS VERSION ${TIANSHAN_VERSION_MAJOR}.${TIANSHAN_VERSION_MINOR}.${TIANSHAN_VERSION_PATCH}) +endif() +include(cmake/security_profile.cmake) if(NOT ROOT_PASSWORD_RESET) + include(cmake/json_limits.cmake) include(cmake/httpd_admission.cmake) + include(cmake/http_transport_polling.cmake) include(cmake/dhcps_bindings.cmake) endif() diff --git a/cmake/http_transport_polling.cmake b/cmake/http_transport_polling.cmake new file mode 100644 index 00000000..d3d860c2 --- /dev/null +++ b/cmake/http_transport_polling.cmake @@ -0,0 +1,80 @@ +# Nonblocking HTTP/TLS uses SDK async connection support with zero-timeout polls. +# Keep the SDK checkout immutable and fail on an unreviewed polling implementation. +idf_component_get_property(transport_lib tcp_transport COMPONENT_LIB) +idf_component_get_property(transport_dir tcp_transport COMPONENT_DIR) +idf_component_get_property(websocket_lib espressif__esp_websocket_client COMPONENT_LIB) +idf_component_get_property(websocket_dir espressif__esp_websocket_client COMPONENT_DIR) +set(polling_dir "${CMAKE_BINARY_DIR}/http_transport_polling") +set(polling_tool "${CMAKE_SOURCE_DIR}/tools/prepare_http_transport_polling.py") +execute_process( + COMMAND "${Python3_EXECUTABLE}" "${polling_tool}" --idf-dir "$ENV{IDF_PATH}" --output "${polling_dir}" --websocket-source "${websocket_dir}/esp_websocket_client.c" + RESULT_VARIABLE polling_result + ERROR_VARIABLE polling_error +) +if(NOT polling_result EQUAL 0) + message(FATAL_ERROR "HTTP nonblocking transport unavailable: ${polling_error}") +endif() +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + "${polling_tool}" "${transport_dir}/transport_ssl.c" + "${transport_dir}/transport_ws.c" "${websocket_dir}/esp_websocket_client.c") +get_target_property(transport_sources ${transport_lib} SOURCES) +set(updated_sources "") +set(found_transport "") +foreach(source IN LISTS transport_sources) + get_filename_component(source_name "${source}" NAME) + if(source_name STREQUAL "transport_ssl.c" OR source_name STREQUAL "transport_ws.c") + list(APPEND updated_sources "${polling_dir}/${source_name}") + list(APPEND found_transport "${source_name}") + else() + list(APPEND updated_sources "${source}") + endif() +endforeach() +list(SORT found_transport) +if(NOT found_transport STREQUAL "transport_ssl.c;transport_ws.c") + message(FATAL_ERROR "Cannot replace SDK transport sources; SDK sources changed") +endif() +set_property(TARGET ${transport_lib} PROPERTY SOURCES ${updated_sources}) +target_include_directories(${transport_lib} PRIVATE "${transport_dir}") +# Bound complete HTTP response headers; binary bodies use each owner's own cap. +idf_component_get_property(parser_lib http_parser COMPONENT_LIB) +target_compile_definitions(${parser_lib} PRIVATE HTTP_MAX_HEADER_SIZE=16384) + +# Feed confirmed FIN to the existing HTTP parser. This preserves valid EOF +# framing while the same parser continues rejecting short CL/chunked bodies. +idf_component_get_property(client_lib esp_http_client COMPONENT_LIB) +idf_component_get_property(client_dir esp_http_client COMPONENT_DIR) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${client_dir}/esp_http_client.c") +get_target_property(client_sources ${client_lib} SOURCES) +set(updated_sources "") +set(found FALSE) +foreach(source IN LISTS client_sources) + if(source STREQUAL "${client_dir}/esp_http_client.c" OR source STREQUAL "esp_http_client.c") + list(APPEND updated_sources "${polling_dir}/esp_http_client.c") + set(found TRUE) + else() + list(APPEND updated_sources "${source}") + endif() +endforeach() +if(NOT found) + message(FATAL_ERROR "Cannot replace SDK esp_http_client.c; SDK sources changed") +endif() +set_property(TARGET ${client_lib} PROPERTY SOURCES ${updated_sources}) +target_include_directories(${client_lib} PRIVATE "${client_dir}") + +# Managed dependency stays immutable, just like the shared ESP-IDF checkout. +get_target_property(websocket_sources ${websocket_lib} SOURCES) +set(updated_sources "") +set(found FALSE) +foreach(source IN LISTS websocket_sources) + if(source STREQUAL "${websocket_dir}/esp_websocket_client.c" OR source STREQUAL "esp_websocket_client.c") + list(APPEND updated_sources "${polling_dir}/esp_websocket_client.c") + set(found TRUE) + else() + list(APPEND updated_sources "${source}") + endif() +endforeach() +if(NOT found) + message(FATAL_ERROR "Cannot replace managed WebSocket client; dependency sources changed") +endif() +set_property(TARGET ${websocket_lib} PROPERTY SOURCES ${updated_sources}) +target_include_directories(${websocket_lib} PRIVATE "${websocket_dir}") diff --git a/cmake/httpd_admission.cmake b/cmake/httpd_admission.cmake index 0ddbaf14..282d507b 100644 --- a/cmake/httpd_admission.cmake +++ b/cmake/httpd_admission.cmake @@ -6,6 +6,7 @@ set(admission_tool "${CMAKE_SOURCE_DIR}/tools/prepare_httpd_admission.py") execute_process( COMMAND "${Python3_EXECUTABLE}" "${admission_tool}" --idf-dir "$ENV{IDF_PATH}" --output "${admission_dir}" + --trusted-origins "${TS_HTTP_TRUSTED_ORIGINS}" --with-https RESULT_VARIABLE admission_result ERROR_VARIABLE admission_error ) @@ -13,9 +14,11 @@ if(NOT admission_result EQUAL 0) message(FATAL_ERROR "HTTPD connection protection unavailable: ${admission_error}") endif() set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS - "${admission_tool}" "${httpd_dir}/src/httpd_sess.c" "${httpd_dir}/src/httpd_main.c") + "${admission_tool}" "${httpd_dir}/src/httpd_sess.c" "${httpd_dir}/src/httpd_main.c" + "${httpd_dir}/src/httpd_uri.c" "${httpd_dir}/src/httpd_parse.c" + "${httpd_dir}/src/httpd_txrx.c" "${httpd_dir}/src/httpd_ws.c") get_target_property(httpd_sources ${httpd_lib} SOURCES) -foreach(name httpd_sess.c httpd_main.c) +foreach(name httpd_sess.c httpd_main.c httpd_uri.c httpd_parse.c httpd_txrx.c httpd_ws.c) set(found FALSE) set(updated_sources "") foreach(source IN LISTS httpd_sources) @@ -33,3 +36,24 @@ foreach(name httpd_sess.c httpd_main.c) endforeach() set_property(TARGET ${httpd_lib} PROPERTY SOURCES ${httpd_sources}) target_include_directories(${httpd_lib} PRIVATE "${httpd_dir}/src") + +# The same build-local server policy owns copied TLS startup material. +idf_component_get_property(https_lib esp_https_server COMPONENT_LIB) +idf_component_get_property(https_dir esp_https_server COMPONENT_DIR) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${https_dir}/src/https_server.c") +get_target_property(https_sources ${https_lib} SOURCES) +set(updated_https_sources "") +set(found_https FALSE) +foreach(source IN LISTS https_sources) + if(source STREQUAL "${https_dir}/src/https_server.c" OR source STREQUAL "src/https_server.c") + list(APPEND updated_https_sources "${admission_dir}/https_server.c") + set(found_https TRUE) + else() + list(APPEND updated_https_sources "${source}") + endif() +endforeach() +if(NOT found_https) + message(FATAL_ERROR "Cannot replace HTTPS startup owner; SDK component sources changed") +endif() +set_property(TARGET ${https_lib} PROPERTY SOURCES ${updated_https_sources}) +target_include_directories(${https_lib} PRIVATE "${https_dir}/src") diff --git a/cmake/json_limits.cmake b/cmake/json_limits.cmake new file mode 100644 index 00000000..6835780f --- /dev/null +++ b/cmake/json_limits.cmake @@ -0,0 +1,6 @@ +# Bound recursion inside the parser, before callers can inspect a JSON tree. +# Config packs already accept at most 32 nesting levels. Apply that same bound +# to the actual shared SDK cJSON target, including WS/HTTP/PKI consumers. +# The serial-only recovery build has no application JSON ingress. +idf_component_get_property(ts_json_target json COMPONENT_LIB) +target_compile_definitions(${ts_json_target} PUBLIC CJSON_NESTING_LIMIT=32) diff --git a/cmake/security_profile.cmake b/cmake/security_profile.cmake new file mode 100644 index 00000000..40fc35b6 --- /dev/null +++ b/cmake/security_profile.cmake @@ -0,0 +1,25 @@ +# Inspect the effective IDF configuration, not sdkconfig.defaults. +if(NOT TS_DEVELOPMENT_BUILD AND NOT ROOT_PASSWORD_RESET AND CONFIG_TS_WEBUI_ENABLE) + if(NOT CONFIG_TS_WEBUI_AUTH_REQUIRED OR NOT CONFIG_TS_SECURITY_ENABLE) + message(FATAL_ERROR "Standard WebUI firmware requires authentication and security. Use explicit TS_DEVELOPMENT_BUILD=ON only for development firmware.") + endif() +endif() +foreach(flag TS_DEVELOPMENT_BUILD ROOT_PASSWORD_RESET CONFIG_TS_WEBUI_ENABLE CONFIG_TS_WEBUI_AUTH_REQUIRED CONFIG_TS_SECURITY_ENABLE ) + if(${flag}) + set(profile_${flag} true) + else() + set(profile_${flag} false) + endif() +endforeach() +set(profile_json [=[{ + "schema": 2, + "development": @profile_TS_DEVELOPMENT_BUILD@, + "recovery": @profile_ROOT_PASSWORD_RESET@, + "webui_enabled": @profile_CONFIG_TS_WEBUI_ENABLE@, + "auth_required": @profile_CONFIG_TS_WEBUI_AUTH_REQUIRED@, + "security_enabled": @profile_CONFIG_TS_SECURITY_ENABLE@, + "webui_tls": false +} +]=]) +string(CONFIGURE "${profile_json}" configured_profile @ONLY) +file(WRITE "${CMAKE_BINARY_DIR}/security-build.json" "${configured_profile}") diff --git a/components/ts_api/CMakeLists.txt b/components/ts_api/CMakeLists.txt index 96f06bd2..c3bffc5c 100644 --- a/components/ts_api/CMakeLists.txt +++ b/components/ts_api/CMakeLists.txt @@ -27,6 +27,7 @@ set(TS_API_SRCS "src/ts_api_ota.c" "src/ts_api_log.c" "src/ts_api_automation.c" + "src/ts_api_ws_test_transport.c" "src/ts_api_auto_config.c" "src/ts_api_cert.c" "src/ts_api_auth.c" @@ -42,5 +43,6 @@ idf_component_register( INCLUDE_DIRS "include" EMBED_FILES ${TS_API_EMBED_FILES} REQUIRES ts_core ts_drivers ts_led ts_net json ts_storage ts_security ts_ota ts_automation ts_cert ts_webui ts_config_pack - PRIV_REQUIRES ts_https ts_hal esp_timer esp_app_format spi_flash bootloader_support esp_wifi app_update esp_https_ota esp_http_client espressif__esp_websocket_client + PRIV_REQUIRES + ts_http_fetch ts_dns tcp_transport mbedtls ts_https ts_hal esp_timer esp_app_format spi_flash bootloader_support esp_wifi app_update esp_https_ota esp_http_client espressif__esp_websocket_client ) diff --git a/components/ts_api/include/ts_api.h b/components/ts_api/include/ts_api.h index 00eaa4aa..35314043 100644 --- a/components/ts_api/include/ts_api.h +++ b/components/ts_api/include/ts_api.h @@ -16,6 +16,8 @@ #include "esp_err.h" #include "cJSON.h" +#include "ts_api_params.h" +#include "ts_api_policy.h" #include #include @@ -89,6 +91,9 @@ typedef struct { */ typedef esp_err_t (*ts_api_handler_t)(const cJSON *params, ts_api_result_t *result); +/** Optional external dispatch: identity is a verified C value, never a JSON field. */ +typedef esp_err_t (*ts_api_session_handler_t)(const cJSON *params, uint32_t caller_session_id, ts_api_result_t *result); + /** * @brief API endpoint definition */ @@ -97,8 +102,11 @@ typedef struct { const char *description; /**< API description */ ts_api_category_t category; /**< API category */ ts_api_handler_t handler; /**< Handler function */ - bool requires_auth; /**< Requires authentication */ - const char *permission; /**< Required permission (optional) */ + bool requires_auth; /**< Compatibility metadata; external_access is authoritative. */ + const char *permission; /**< Capability metadata/invariants (optional), not role inference. */ + ts_api_external_access_t external_access; /**< Explicit role; zero means internal only. */ + uint8_t allowed_methods; /**< Nonzero for external roles, zero for internal only. */ + ts_api_session_handler_t session_handler; /**< External session-aware path; internal call uses handler. */ } ts_api_endpoint_t; /*===========================================================================*/ @@ -157,6 +165,10 @@ void ts_api_parse_query(cJSON *params, char *query); */ esp_err_t ts_api_call(const char *name, const cJSON *params, ts_api_result_t *result); +/* Coarse external admission from the live registry. Body-dependent resource + * checks remain in call_for_session after parsing; this lookup never allocates. */ +esp_err_t ts_api_get_access(const char *name, ts_api_access_t *access); + /* Browser/session boundary. Trusted internal callers continue to use ts_api_call. */ esp_err_t ts_api_call_for_session(const char *name, const cJSON *params, uint32_t session_id, ts_api_result_t *result); diff --git a/components/ts_api/include/ts_api_params.h b/components/ts_api/include/ts_api_params.h new file mode 100644 index 00000000..beb14d5f --- /dev/null +++ b/components/ts_api/include/ts_api_params.h @@ -0,0 +1,97 @@ +#pragma once +/* External parameter admission. Internal ts_api_call keeps its existing contract. */ +#include "cJSON.h" +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void ts_api_parse_query(cJSON *params, char *query); + +typedef enum { + TS_API_PARAMS_OK, + TS_API_PARAMS_INVALID, + TS_API_PARAMS_NO_MEM +} ts_api_params_status_t; + +/* Top-level parameter names are case-insensitive in existing handlers. Nested + * application data retains case-sensitive names, but exact duplicates are invalid. */ +static inline bool ts_api_params_unique(const cJSON *value, unsigned depth) +{ + if (depth > 32 || (cJSON_IsNumber(value) && !isfinite(value->valuedouble))) return false; + for (const cJSON *a = value->child; a; a = a->next) { + if (cJSON_IsObject(value)) { + for (const cJSON *b = a->next; b; b = b->next) { + if (a->string && b->string && + (depth == 0 ? !strcasecmp(a->string, b->string) : !strcmp(a->string, b->string))) + return false; + } + } + if (!ts_api_params_unique(a, depth + 1)) return false; + } + return true; +} + +static inline cJSON *ts_api_params_parse_object(const char *text, size_t length) +{ + if (!text || !length || memchr(text, 0, length)) return NULL; + /* Bound parser recursion before cJSON enters it; the existing configuration + * transport uses the same depth 32. Escaped backslashes stay literal text. */ + bool string = false; + unsigned depth = 0; + for (size_t i = 0; i < length; ++i) { + unsigned char c = text[i]; + if (c < 0x20 && (string || (c != '\t' && c != '\r' && c != '\n'))) return NULL; + if (string && c == '\\') { + if (i + 5 < length && text[i+1] == 'u' && !memcmp(text+i+2, "0000", 4)) return NULL; + ++i; + } else if (c == '"') string = !string; + else if (!string && (c == '{' || c == '[')) { if (++depth > 32) return NULL; } + else if (!string && (c == '}' || c == ']')) { if (!depth) return NULL; --depth; } + } + const char *end = NULL; + cJSON *value = cJSON_ParseWithLengthOpts(text, length, &end, false); + if (!value) return NULL; + while (end < text + length && isspace((unsigned char)*end)) ++end; + if (end != text + length || !cJSON_IsObject(value) || !ts_api_params_unique(value, 0)) { + cJSON_Delete(value); + return NULL; + } + return value; +} + +/* Keep the existing once-only value decoding and numeric/bool coercion. Reject + * malformed encodings and ambiguous keys before the legacy parser can lose them. */ +static inline ts_api_params_status_t ts_api_params_add_query(cJSON *params, char *query) +{ + char *state = NULL; + for (char *pair = strtok_r(query, "&", &state); pair; pair = strtok_r(NULL, "&", &state)) { + char *eq = strchr(pair, '='); + if (!eq || eq == pair) return TS_API_PARAMS_INVALID; + for (char *p = pair; *p; ++p) { + if (*p != '%') continue; + if (!p[1] || !p[2] || !isxdigit((unsigned char)p[1]) || !isxdigit((unsigned char)p[2]) || + (p[1] == '0' && p[2] == '0')) return TS_API_PARAMS_INVALID; + p += 2; + } + *eq = 0; + bool duplicate = cJSON_GetObjectItem(params, pair) != NULL; + *eq = '='; + if (duplicate) return TS_API_PARAMS_INVALID; + ts_api_parse_query(params, pair); + /* The parser replaces '=' with NUL. A missing item now means allocation + * failed; never dispatch a partially populated request. */ + if (!cJSON_GetObjectItemCaseSensitive(params, pair)) return TS_API_PARAMS_NO_MEM; + } + return TS_API_PARAMS_OK; +} + +#ifdef __cplusplus +} +#endif diff --git a/components/ts_api/include/ts_api_policy.h b/components/ts_api/include/ts_api_policy.h new file mode 100644 index 00000000..efb51d2d --- /dev/null +++ b/components/ts_api/include/ts_api_policy.h @@ -0,0 +1,30 @@ +#pragma once +#include +#include +/* Zero-initialized entries are trusted internal operations only. External + * exposure always needs an explicit role and nonzero method declaration. */ +typedef enum { + TS_API_ACCESS_INTERNAL = 0, + TS_API_ACCESS_LEGACY = TS_API_ACCESS_INTERNAL, /* Source alias for old snapshots; no external fallback. */ + TS_API_ACCESS_PUBLIC, + TS_API_ACCESS_READ, + TS_API_ACCESS_WRITE, + TS_API_ACCESS_ADMIN, + TS_API_ACCESS_ROOT, + TS_API_ACCESS_TOKEN +} ts_api_external_access_t; +enum { + TS_API_METHOD_GET = 1, + TS_API_METHOD_POST = 2, + TS_API_METHOD_PUT = 4, + TS_API_METHOD_DELETE = 8, + TS_API_METHOD_READ = TS_API_METHOD_GET | TS_API_METHOD_POST, + TS_API_METHOD_WRITE = TS_API_METHOD_POST | TS_API_METHOD_PUT | TS_API_METHOD_DELETE, + TS_API_METHOD_ALL = TS_API_METHOD_READ | TS_API_METHOD_WRITE +}; +typedef struct { + bool requires_auth; + uint8_t minimum_level; + uint8_t allowed_methods; + ts_api_external_access_t external_access; +} ts_api_access_t; diff --git a/components/ts_api/src/ts_api.c b/components/ts_api/src/ts_api.c index a65c47f7..43d94a58 100644 --- a/components/ts_api/src/ts_api.c +++ b/components/ts_api/src/ts_api.c @@ -19,6 +19,10 @@ #include #define TAG "ts_api" +_Static_assert(TS_API_ACCESS_READ - TS_API_ACCESS_PUBLIC == TS_PERM_READ && + TS_API_ACCESS_WRITE - TS_API_ACCESS_PUBLIC == TS_PERM_WRITE && + TS_API_ACCESS_ADMIN - TS_API_ACCESS_PUBLIC == TS_PERM_ADMIN && + TS_API_ACCESS_ROOT - TS_API_ACCESS_PUBLIC == TS_PERM_ROOT, "API/security role mapping changed"); /*===========================================================================*/ /* Name Tables */ @@ -69,8 +73,11 @@ typedef struct { char *description; ts_api_category_t category; ts_api_handler_t handler; + ts_api_session_handler_t session_handler; bool requires_auth; char *permission; + ts_api_external_access_t external_access; + uint8_t allowed_methods; bool used; } api_entry_t; @@ -191,6 +198,19 @@ esp_err_t ts_api_register(const ts_api_endpoint_t *endpoint) return ESP_ERR_INVALID_ARG; } + if (endpoint->external_access > TS_API_ACCESS_TOKEN || + (endpoint->allowed_methods & ~TS_API_METHOD_ALL) || + (endpoint->external_access == TS_API_ACCESS_INTERNAL ? endpoint->allowed_methods != 0 : !endpoint->allowed_methods)) + return ESP_ERR_INVALID_ARG; + /* Reject a contradictory management declaration at registration; never + * rewrite an admitted operation's role from a name or permission string. */ + if (endpoint->external_access != TS_API_ACCESS_INTERNAL && endpoint->permission && + !strcmp(endpoint->permission, "cert.manage") && + ((endpoint->external_access != TS_API_ACCESS_ADMIN && + endpoint->external_access != TS_API_ACCESS_ROOT) || + (endpoint->allowed_methods & ~TS_API_METHOD_WRITE))) + return ESP_ERR_INVALID_ARG; + xSemaphoreTake(s_api.mutex, portMAX_DELAY); /* Check for duplicate */ @@ -215,8 +235,19 @@ esp_err_t ts_api_register(const ts_api_endpoint_t *endpoint) entry->description = endpoint->description ? TS_STRDUP_PSRAM(endpoint->description) : NULL; entry->category = endpoint->category; entry->handler = endpoint->handler; + entry->session_handler = endpoint->session_handler; entry->requires_auth = endpoint->requires_auth; + entry->external_access = endpoint->external_access; + entry->allowed_methods = endpoint->allowed_methods; entry->permission = endpoint->permission ? TS_STRDUP_PSRAM(endpoint->permission) : NULL; + if ((endpoint->description && !entry->description) || + (endpoint->permission && !entry->permission)) { + free(entry->description); + free(entry->permission); + memset(entry, 0, sizeof(*entry)); + xSemaphoreGive(s_api.mutex); + return ESP_ERR_NO_MEM; + } entry->used = true; s_api.endpoint_count++; @@ -331,7 +362,8 @@ void ts_api_parse_query(cJSON *params, char *query) } -esp_err_t ts_api_call(const char *name, const cJSON *params, ts_api_result_t *result) +static esp_err_t api_call_dispatch(const char *name, const cJSON *params, uint32_t caller_session_id, + bool external, ts_api_result_t *result) { if (!s_api.initialized) { if (result) { @@ -358,12 +390,13 @@ esp_err_t ts_api_call(const char *name, const cJSON *params, ts_api_result_t *re /* Copy handler to call outside mutex */ ts_api_handler_t handler = entry->handler; + ts_api_session_handler_t session_handler = entry->session_handler; xSemaphoreGive(s_api.mutex); /* Call handler */ TS_LOGD(TAG, "Calling API: %s", name); - esp_err_t ret = handler(params, result); + esp_err_t ret = external && session_handler ? session_handler(params, caller_session_id, result) : handler(params, result); if (ret != ESP_OK && result->code == TS_API_OK) { ts_api_result_error(result, TS_API_ERR_INTERNAL, "Handler error"); @@ -372,56 +405,218 @@ esp_err_t ts_api_call(const char *name, const cJSON *params, ts_api_result_t *re return ret; } +esp_err_t ts_api_call(const char *name, const cJSON *params, ts_api_result_t *result) +{ + return api_call_dispatch(name, params, 0, false, result); +} + +static void classify_external_access(ts_api_external_access_t mode, uint8_t methods, + ts_api_access_t *access) +{ + access->external_access = mode; + access->allowed_methods = mode == TS_API_ACCESS_INTERNAL ? 0 : methods; + access->requires_auth = mode >= TS_API_ACCESS_READ && mode <= TS_API_ACCESS_ROOT; + access->minimum_level = access->requires_auth ? (uint8_t)(mode - TS_API_ACCESS_PUBLIC) : TS_PERM_NONE; +} + +esp_err_t ts_api_get_access(const char *name, ts_api_access_t *access) +{ + if (!name || !access) return ESP_ERR_INVALID_ARG; + if (!s_api.initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_api.mutex, portMAX_DELAY); + api_entry_t *entry = find_endpoint(name); + if (entry) classify_external_access(entry->external_access, entry->allowed_methods, access); + esp_err_t ret = entry ? ESP_OK : ESP_ERR_NOT_FOUND; + xSemaphoreGive(s_api.mutex); + return ret; +} + +/* Authorization and dispatch share one registry snapshot. */ +static esp_err_t copy_external_call(const char *name, ts_api_access_t *access, + ts_api_handler_t *handler, + ts_api_session_handler_t *session_handler) +{ + if (!s_api.initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_api.mutex, portMAX_DELAY); + api_entry_t *entry = find_endpoint(name); + if (entry) { + classify_external_access(entry->external_access, entry->allowed_methods, access); + *handler = entry->handler; + *session_handler = entry->session_handler; + } + esp_err_t ret = entry ? ESP_OK : ESP_ERR_NOT_FOUND; + xSemaphoreGive(s_api.mutex); + return ret; +} + +/* External private results have an explicit metadata contract. New saved + * fields are private until a field is deliberately added to this projection. */ +static bool project_result_fields(cJSON *object, const char *fields, const cJSON *preserved) +{ + if (!cJSON_IsObject(object)) return false; + cJSON *item = object->child; + while (item) { + cJSON *next = item->next; + if (item == preserved) { item = next; continue; } + bool allowed = false; + for (const char *p = fields; *p;) { + const char *end = strchr(p, '|'); + size_t length = end ? (size_t)(end - p) : strlen(p); + if (item->string && strlen(item->string) == length && !memcmp(item->string, p, length)) + allowed = true; + if (!end) break; + p = end + 1; + } + if (allowed && !strcmp(item->string, "automatic_start")) { + allowed = project_result_fields(item, "state|reason|retry_after_ms|", NULL); + } else if (allowed && !strcmp(item->string, "ssh_commands")) { + allowed = cJSON_IsArray(item); + for (cJSON *command = item->child; command;) { + cJSON *following = command->next; + if (!cJSON_IsString(command)) cJSON_Delete(cJSON_DetachItemViaPointer(item, command)); + command = following; + } + } else allowed = allowed && (cJSON_IsString(item) || cJSON_IsNumber(item) || cJSON_IsBool(item) || cJSON_IsNull(item)); + if (!allowed) cJSON_Delete(cJSON_DetachItemViaPointer(object, item)); + item = next; + } + return true; +} + +/* A NULL result probes the same policy, including effect/acknowledgement semantics. */ +static esp_err_t private_result_projection(const char *name, ts_api_result_t *result, bool root, bool *effect_result) +{ + static const struct { const char *name, *collection, *fields; bool effect; } views[] = { +#define VIEW_FIELDS "id|name|label|type|enabled|active_version|" + {"ssh.hosts.list", "hosts", VIEW_FIELDS "host|port|created|created_time|last_used|", false}, + {"ssh.hosts.get", NULL, VIEW_FIELDS "host|port|created|created_time|last_used|", false}, + {"ssh.commands.list", "commands", VIEW_FIELDS "host_id|icon|nohup|orphan|runtime_instance|lastExec|created|created_time|serviceMode|service_mode|varName|var_name|", false}, + {"ssh.commands.get", NULL, VIEW_FIELDS "host_id|icon|nohup|orphan|runtime_instance|lastExec|created|created_time|serviceMode|service_mode|varName|var_name|", false}, + {"automation.sources.list", "sources", VIEW_FIELDS "connected|last_update_ms|poll_interval_ms|reconnect_ms|mapping_count|update_mode|invalid|", false}, + {"automation.rules.list", "rules", VIEW_FIELDS "revision|runtime_active|manual_trigger|conditions_count|actions_count|trigger_count|last_trigger_ms|automatic_start|ssh_commands|", false}, + {"automation.rules.get", NULL, VIEW_FIELDS "revision|runtime_active|manual_trigger|conditions_count|actions_count|trigger_count|last_trigger_ms|", false}, + {"automation.actions.list", "templates", VIEW_FIELDS "async|use_count|last_used_at|created_at|", false}, + {"automation.actions.get", NULL, VIEW_FIELDS "async|use_count|last_used_at|created_at|", false}, + /* These two handlers already project their allowed public fields. */ + {"config.get", NULL, NULL, false}, + {"config.module.show", NULL, NULL, false}, + {"ota.server.get", NULL, "configured|", false}, + {"ota.progress", NULL, NULL, false}, + {"ota.www.progress", NULL, NULL, false}, + {"automation.actions.execute", NULL, "async|status|duration_ms|", true}, +#undef VIEW_FIELDS + }; + for (unsigned i = 0; i < sizeof(views) / sizeof(views[0]); ++i) { + if (strcmp(name, views[i].name)) continue; + if (effect_result) *effect_result = views[i].effect; + if (!result || !result->data || root || !views[i].fields) return ESP_OK; + if (views[i].effect) { + /* The effect already happened. Redaction must not allocate, fail, + * or turn its real acknowledgement into a retryable write error. */ + if (!project_result_fields(result->data, views[i].fields, NULL)) { + cJSON_Delete(result->data); + result->data = NULL; + } + return ESP_OK; + } + cJSON *rows = views[i].collection ? cJSON_GetObjectItemCaseSensitive(result->data, views[i].collection) : NULL; + bool valid = views[i].collection ? cJSON_IsArray(rows) : cJSON_IsObject(result->data); + if (views[i].collection && valid) { + valid = project_result_fields(result->data, + "count|total|active_version|load_error|paused|loaded|recovery_required|invalid_items|restart_required|", rows); + cJSON *row; + cJSON_ArrayForEach(row, rows) { + if (!project_result_fields(row, views[i].fields, NULL) || !cJSON_AddBoolToObject(row, "restricted", true)) { + valid = false; + break; + } + } + } else if (valid) valid = project_result_fields(result->data, views[i].fields, NULL); + if (!valid || !cJSON_AddBoolToObject(result->data, "restricted", true)) { + ts_api_result_error(result, TS_API_ERR_INTERNAL, "Configuration metadata unavailable"); + return ESP_FAIL; + } + return ESP_OK; + } + return ESP_ERR_NOT_FOUND; +} + esp_err_t ts_api_call_for_session(const char *name, const cJSON *params, uint32_t session_id, ts_api_result_t *result) { if (!name || !result) return ESP_ERR_INVALID_ARG; ts_api_result_init(result); - cJSON *info = ts_api_get_info(name); - if (!info) { - ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "API not found"); - return ESP_ERR_NOT_FOUND; - } - const cJSON *auth = cJSON_GetObjectItemCaseSensitive(info, "requires_auth"); - if (!cJSON_IsBool(auth)) { - cJSON_Delete(info); - ts_api_result_error(result, TS_API_ERR_INTERNAL, "API policy unavailable"); - return ESP_FAIL; + ts_api_access_t access; + ts_api_handler_t handler = NULL; + ts_api_session_handler_t session_handler = NULL; + esp_err_t policy_ret = copy_external_call(name, &access, &handler, &session_handler); + if (policy_ret != ESP_OK) { + ts_api_result_error(result, policy_ret == ESP_ERR_NOT_FOUND ? TS_API_ERR_NOT_FOUND : TS_API_ERR_INTERNAL, + policy_ret == ESP_ERR_NOT_FOUND ? "API not found" : "API policy unavailable"); + return policy_ret; + } + if (access.external_access == TS_API_ACCESS_INTERNAL) { + ts_api_result_error(result, TS_API_ERR_NOT_SUPPORTED, "API not exposed externally"); + return ESP_ERR_NOT_SUPPORTED; } - bool needs_auth = cJSON_IsTrue(auth); - cJSON_Delete(info); bool source_secrets = true; #ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED ts_session_t session; ts_perm_level_t level = TS_PERM_NONE; if (session_id && ts_security_validate_session(session_id, &session) == ESP_OK) level = session.level; - source_secrets = level >= TS_PERM_ROOT; - bool root_only = needs_auth && !strncmp(name, "automation.", 11) && - strcmp(name, "automation.actions.execute") && - strcmp(name, "automation.rules.trigger") && - strcmp(name, "automation.services.list") && - strcmp(name, "automation.services.status") && - strcmp(name, "automation.services.stop"); - ts_perm_level_t required = root_only ? TS_PERM_ROOT : - !strcmp(name, "ui.widgets.set") ? TS_PERM_ADMIN : TS_PERM_READ; - const cJSON *path = !strcmp(name, "storage.read") ? cJSON_GetObjectItem(params, "path") : NULL; - if ((needs_auth && level < required) || - (cJSON_IsString(path) && ts_storage_check_write_path(path->valuestring, false) != ESP_OK && !source_secrets)) { + /* Preserve the pre-existing sources credential projection. Other restored + * configuration/security pages retain their original Admin data contract. */ + ts_perm_level_t private_level = !strcmp(name, "automation.sources.list") ? TS_PERM_ROOT : TS_PERM_ADMIN; + source_secrets = level >= private_level; + /* The generic store can contain arbitrary credentials. Only the language + * preference is a public WebUI bootstrap value; raw reads require a logged-in administrator. */ + const cJSON *config_key = !strcmp(name, "config.get") ? cJSON_GetObjectItem(params, "key") : NULL; + bool private_config = !strcmp(name, "config.get") && + !(cJSON_IsString(config_key) && !strcmp(config_key->valuestring, "system.language")); + if ((access.requires_auth && level < access.minimum_level) || + (private_config && !source_secrets)) { ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); return ESP_ERR_NOT_ALLOWED; } #else - (void)needs_auth; + (void)access; (void)session_id; #endif - esp_err_t ret = ts_api_call(name, params, result); - if (!strcmp(name, "automation.sources.list") && !source_secrets && result->data) { - cJSON *source; - cJSON_ArrayForEach(source, cJSON_GetObjectItemCaseSensitive(result->data, "sources")) { - cJSON_DeleteItemFromObjectCaseSensitive(source, "rest_auth"); - cJSON_DeleteItemFromObjectCaseSensitive(source, "auth_header"); + /* Invoke the handler copied with this policy, never a second name lookup + * that could select a concurrently replaced operation. */ + esp_err_t ret = session_handler ? session_handler(params, session_id, result) : handler(params, result); + if (ret != ESP_OK && result->code == TS_API_OK) + ts_api_result_error(result, TS_API_ERR_INTERNAL, "Handler error"); + if (!strcmp(name, "config.module.show") && !source_secrets && result->data) { + /* Both single-module and "all" responses are emitted by this API. + * Omit secrets instead of returning a mask that a client might save. */ + cJSON *configs[] = { + cJSON_GetObjectItemCaseSensitive(result->data, "config"), + cJSON_GetObjectItemCaseSensitive(result->data, "wifi") + }; + for (unsigned i = 0; i < sizeof(configs) / sizeof(configs[0]); ++i) { + cJSON_DeleteItemFromObjectCaseSensitive(configs[i], "ap.password"); + cJSON_DeleteItemFromObjectCaseSensitive(configs[i], "sta.password"); + } + } + bool effect_result = false; + if (private_result_projection(name, NULL, true, &effect_result) == ESP_OK) { +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + ts_session_t current; + bool live = ts_security_validate_session(session_id, ¤t) == ESP_OK; + if (effect_result) { + /* Keep the actual write outcome, but never its private output if + * the initiating administrator is no longer authorized at delivery. */ + source_secrets = source_secrets && live && current.level >= private_level; + } else if ((access.requires_auth && (!live || current.level < access.minimum_level)) || + (source_secrets && (!live || current.level < private_level))) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; } +#endif + esp_err_t projected = private_result_projection(name, result, source_secrets, NULL); + if (projected != ESP_OK) return projected; } return ret; } @@ -500,9 +695,16 @@ cJSON *ts_api_get_info(const char *name) } cJSON_AddStringToObject(info, "category", ts_api_category_name(entry->category)); - cJSON_AddBoolToObject(info, "requires_auth", entry->requires_auth); - if (entry->permission) { - cJSON_AddStringToObject(info, "permission", entry->permission); + ts_api_access_t access; + classify_external_access(entry->external_access, entry->allowed_methods, &access); + /* Partial metadata must never weaken the dispatch policy. */ + if (!cJSON_AddBoolToObject(info, "requires_auth", access.requires_auth) || + !cJSON_AddNumberToObject(info, "minimum_level", access.minimum_level) || + !cJSON_AddNumberToObject(info, "external_access", access.external_access) || + !cJSON_AddNumberToObject(info, "allowed_methods", access.allowed_methods) || + (entry->permission && !cJSON_AddStringToObject(info, "permission", entry->permission))) { + cJSON_Delete(info); + info = NULL; } } diff --git a/components/ts_api/src/ts_api_auth.c b/components/ts_api/src/ts_api_auth.c index d9eae287..995f1cc5 100644 --- a/components/ts_api/src/ts_api_auth.c +++ b/components/ts_api/src/ts_api_auth.c @@ -61,6 +61,19 @@ static esp_err_t validate_root_token(const cJSON *token_item, ts_api_result_t *r return ESP_OK; } +/* Prepare the required client re-login contract before changing credentials. */ +static cJSON *password_update_response(bool reauth_required) +{ + cJSON *data = cJSON_CreateObject(); + if (!data || !cJSON_AddBoolToObject(data, "success", true) || + !cJSON_AddBoolToObject(data, "sessions_revoked", true) || + !cJSON_AddBoolToObject(data, "reauth_required", reauth_required)) { + cJSON_Delete(data); + return NULL; + } + return data; +} + /*===========================================================================*/ /* API Handlers */ /*===========================================================================*/ @@ -102,8 +115,13 @@ static esp_err_t api_auth_login(const cJSON *params, ts_api_result_t *result) } /* 获取权限级别 */ - ts_perm_level_t level; - ts_auth_verify_password(username, password, &level); + ts_session_t session; + ret = ts_security_validate_session(session_id, &session); + if (ret != ESP_OK) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Session expired"); + return ret; + } + ts_perm_level_t level = session.level; /* 检查是否需要修改密码 */ bool password_changed = ts_auth_password_changed(username); @@ -152,7 +170,7 @@ static esp_err_t api_auth_logout(const cJSON *params, ts_api_result_t *result) cJSON_AddBoolToObject(data, "success", ret == ESP_OK); ts_api_result_ok(result, data); - TS_LOGI(TAG, "Session %08lx logged out", (unsigned long)session_id); + TS_LOGI(TAG, "Session logged out"); return ESP_OK; } @@ -219,6 +237,13 @@ static esp_err_t api_auth_status(const cJSON *params, ts_api_result_t *result) * Params: { "token": "...", "old_password": "...", "new_password": "..." } * Returns: { "success": true } */ +static const char *password_update_failure(esp_err_t ret, const char *fallback) +{ + if (ret == ESP_ERR_NOT_FINISHED) return "credential_write_uncertain"; + if (ret == ESP_ERR_NOT_ALLOWED) return "auth_firmware_confirmation_required"; + return fallback; +} + static esp_err_t api_auth_change_password(const cJSON *params, ts_api_result_t *result) { const cJSON *token_item = cJSON_GetObjectItem(params, "token"); @@ -261,22 +286,27 @@ static esp_err_t api_auth_change_password(const cJSON *params, ts_api_result_t * return ESP_ERR_INVALID_ARG; } + cJSON *data = password_update_response(true); + if (!data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; + } + /* 修改密码 */ ret = ts_auth_change_password(session.client_id, old_pwd_item->valuestring, new_password); if (ret != ESP_OK) { + cJSON_Delete(data); if (ret == ESP_ERR_INVALID_ARG) { ts_api_result_error(result, TS_API_ERR_AUTH, "Old password is incorrect"); } else { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to change password"); + ts_api_result_error(result, TS_API_ERR_INTERNAL, password_update_failure(ret, "Failed to change password")); } return ret; } - cJSON *data = cJSON_CreateObject(); - cJSON_AddBoolToObject(data, "success", true); cJSON_AddStringToObject(data, "message", "Password changed successfully"); ts_api_result_ok(result, data); @@ -312,14 +342,19 @@ static esp_err_t api_auth_admin_set_password(const cJSON *params, ts_api_result_ return ESP_ERR_INVALID_ARG; } + cJSON *data = password_update_response(false); + if (!data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; + } + ret = ts_auth_set_admin_password(new_password); if (ret != ESP_OK) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to set admin password"); + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_INTERNAL, password_update_failure(ret, "Failed to set admin password")); return ret; } - cJSON *data = cJSON_CreateObject(); - cJSON_AddBoolToObject(data, "success", true); cJSON_AddStringToObject(data, "username", "admin"); cJSON_AddBoolToObject(data, "password_changed", true); @@ -356,14 +391,19 @@ static esp_err_t api_auth_root_set_password(const cJSON *params, ts_api_result_t return ESP_ERR_INVALID_ARG; } + cJSON *data = password_update_response(true); + if (!data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; + } + ret = ts_auth_set_root_password(new_password); if (ret != ESP_OK) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to set root password"); + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_INTERNAL, password_update_failure(ret, "Failed to set root password")); return ret; } - cJSON *data = cJSON_CreateObject(); - cJSON_AddBoolToObject(data, "success", true); cJSON_AddStringToObject(data, "username", "root"); cJSON_AddBoolToObject(data, "password_changed", true); @@ -385,14 +425,19 @@ static esp_err_t api_auth_admin_reset_password(const cJSON *params, ts_api_resul esp_err_t ret = validate_root_token(token_item, result); if (ret != ESP_OK) return ret; + cJSON *data = password_update_response(false); + if (!data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; + } + ret = ts_auth_reset_password("admin"); if (ret != ESP_OK) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to reset admin password"); + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_INTERNAL, password_update_failure(ret, "Failed to reset admin password")); return ret; } - cJSON *data = cJSON_CreateObject(); - cJSON_AddBoolToObject(data, "success", true); cJSON_AddStringToObject(data, "username", "admin"); cJSON_AddBoolToObject(data, "password_changed", false); @@ -411,6 +456,8 @@ static const ts_api_endpoint_t s_auth_endpoints[] = { .description = "User login", .category = TS_API_CAT_SECURITY, .handler = api_auth_login, + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_POST, .requires_auth = false, /* 登录本身不需要认证 */ }, { @@ -418,6 +465,8 @@ static const ts_api_endpoint_t s_auth_endpoints[] = { .description = "User logout", .category = TS_API_CAT_SECURITY, .handler = api_auth_logout, + .external_access = TS_API_ACCESS_TOKEN, + .allowed_methods = TS_API_METHOD_POST, .requires_auth = false, /* 登出使用 token 验证 */ }, { @@ -425,6 +474,8 @@ static const ts_api_endpoint_t s_auth_endpoints[] = { .description = "Check auth status", .category = TS_API_CAT_SECURITY, .handler = api_auth_status, + .external_access = TS_API_ACCESS_TOKEN, + .allowed_methods = TS_API_METHOD_POST, .requires_auth = false, /* 状态检查使用 token 验证 */ }, { @@ -432,6 +483,8 @@ static const ts_api_endpoint_t s_auth_endpoints[] = { .description = "Change password", .category = TS_API_CAT_SECURITY, .handler = api_auth_change_password, + .external_access = TS_API_ACCESS_TOKEN, + .allowed_methods = TS_API_METHOD_POST, .requires_auth = false, /* 密码修改使用 token 验证 */ }, { @@ -439,21 +492,27 @@ static const ts_api_endpoint_t s_auth_endpoints[] = { .description = "Root sets admin password", .category = TS_API_CAT_SECURITY, .handler = api_auth_admin_set_password, - .requires_auth = false, /* Handler validates root token */ + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_POST, + .requires_auth = true, /* Handler validates root token */ }, { .name = "auth.root.set_password", .description = "Root sets root password", .category = TS_API_CAT_SECURITY, .handler = api_auth_root_set_password, - .requires_auth = false, /* Handler validates root token */ + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_POST, + .requires_auth = true, /* Handler validates root token */ }, { .name = "auth.admin.reset_password", .description = "Root resets admin password to default", .category = TS_API_CAT_SECURITY, .handler = api_auth_admin_reset_password, - .requires_auth = false, /* Handler validates root token */ + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_POST, + .requires_auth = true, /* Handler validates root token */ }, }; diff --git a/components/ts_api/src/ts_api_automation.c b/components/ts_api/src/ts_api_automation.c index 36d818a0..a86ef748 100644 --- a/components/ts_api/src/ts_api_automation.c +++ b/components/ts_api/src/ts_api_automation.c @@ -1,3 +1,6 @@ +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#include "ts_api_ws_test_transport.h" #include "ts_api_auto_config.h" #include "ts_action_codec.h" #include "ts_rule_codec.h" @@ -22,6 +25,7 @@ */ #include "ts_api.h" +#include "ts_security.h" #include "ts_action_filter.h" #include "ts_api_service.h" #include "ts_automation.h" @@ -1082,8 +1086,7 @@ static esp_err_t api_automation_actions_execute(const cJSON *params, ts_api_resu esp_err_t ret = ts_action_template_execute_versioned(id->valuestring,version->valuestring,&exec_result,&reason); if(reason){ts_api_result_error(result,TS_API_ERR_BUSY,reason);return ESP_OK;} - TS_LOGI(TAG, "Execute result: ret=%s, status=%d, output=%s", - esp_err_to_name(ret), exec_result.status, exec_result.output); + TS_LOGI(TAG, "Execute result: ret=%s, status=%d", esp_err_to_name(ret), exec_result.status); result->data = cJSON_CreateObject(); @@ -1158,7 +1161,6 @@ static esp_err_t api_automation_action_stats_reset(const cJSON *params, ts_api_r /* Proxy APIs for External Connection Test */ /*===========================================================================*/ -#include "esp_http_client.h" #include "esp_websocket_client.h" /** @@ -1169,6 +1171,20 @@ static esp_err_t api_automation_action_stats_reset(const cJSON *params, ts_api_r * * Special handling for local API calls (127.0.0.1 or self IP) - calls API directly. */ +static bool proxy_fetch_current(void *context) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + uint32_t session_id = (uint32_t)(uintptr_t)context; + if (session_id) { + ts_session_t caller; + return ts_security_validate_session(session_id, &caller) == ESP_OK && caller.level >= TS_PERM_ROOT; + } +#else + (void)context; +#endif + return true; +} + static esp_err_t api_automation_proxy_fetch(const cJSON *params, ts_api_result_t *result) { return ts_api_automation_proxy_fetch_for_session(params, 0, result); @@ -1190,173 +1206,181 @@ esp_err_t ts_api_automation_proxy_fetch_for_session(const cJSON *params, uint32_ const char *url = url_json->valuestring; const char *method_str = (method_json && cJSON_IsString(method_json)) ? method_json->valuestring : "GET"; cJSON *timeout_json = cJSON_GetObjectItem(params, "timeout"); - int timeout_ms = (timeout_json && cJSON_IsNumber(timeout_json)) ? timeout_json->valueint : 15000; - - TS_LOGI(TAG, "Proxy fetch: %s %s (timeout=%dms)", method_str, url, timeout_ms); - - // 检测是否是本地 API 调用 (127.0.0.1 或 localhost) - // 格式: http://127.0.0.1/api/v1/xxx 或 http://localhost/api/v1/xxx - bool is_local = (strstr(url, "://127.0.0.1") != NULL || - strstr(url, "://localhost") != NULL); + int timeout_ms = 15000; + struct http_parser_url parsed; + if (!ts_http_url_parse(url, &parsed) || + (method_json && !cJSON_IsNull(method_json) && !cJSON_IsString(method_json)) || + (headers_json && !cJSON_IsNull(headers_json) && !cJSON_IsObject(headers_json)) || + (timeout_json && (!cJSON_IsNumber(timeout_json) || !isfinite(timeout_json->valuedouble) || + timeout_json->valuedouble < 1 || timeout_json->valuedouble > 30000 || + timeout_json->valuedouble != (int)timeout_json->valuedouble))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid HTTP target, headers or timeout"); + return ESP_ERR_INVALID_ARG; + } + if (timeout_json) timeout_ms = (int)timeout_json->valuedouble; + if (headers_json && cJSON_IsNull(headers_json)) headers_json = NULL; + bool is_local = ts_http_url_is_local_api(url, &parsed); if (is_local) { // 提取 API 路径: /api/v1/system/memory -> system.memory - const char *api_path = strstr(url, "/api/v1/"); - if (api_path) { - api_path += 8; // 跳过 "/api/v1/" - - // 将路径转换为 API 名称: system/memory -> system.memory - char api_name[64] = {0}; - size_t i = 0, j = 0; - while (api_path[i] && j < sizeof(api_name) - 1) { - if (api_path[i] == '/') { - api_name[j++] = '.'; - } else if (api_path[i] == '?') { - break; // 停止于查询参数 - } else { - api_name[j++] = api_path[i]; - } - i++; + const char *api_path = url + parsed.field_data[UF_PATH].off; + api_path += 8; // 跳过 "/api/v1/" + + // 将路径转换为 API 名称: system/memory -> system.memory + char api_name[64] = {0}; + size_t i = 0, j = 0; + size_t path_length = parsed.field_data[UF_PATH].len - 8; + while (i < path_length && j < sizeof(api_name) - 1) { + api_name[j++] = api_path[i] == '/' ? '.' : api_path[i]; + i++; + } + if (i != path_length) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "API name is too long"); + return ESP_ERR_INVALID_ARG; + } + api_name[j] = '\0'; + + TS_LOGI(TAG, "Local API dispatch requested"); + + ts_api_access_t access; + esp_err_t policy_ret = ts_api_get_access(api_name, &access); + uint8_t method_bit = !strcasecmp(method_str, "GET") ? TS_API_METHOD_GET : + !strcasecmp(method_str, "POST") ? TS_API_METHOD_POST : !strcasecmp(method_str, "PUT") ? TS_API_METHOD_PUT : + !strcasecmp(method_str, "DELETE") ? TS_API_METHOD_DELETE : 0; + if (policy_ret != ESP_OK || !method_bit || !(access.allowed_methods & method_bit)) { + ts_api_result_error(result, policy_ret == ESP_ERR_NOT_FOUND ? TS_API_ERR_NOT_FOUND : TS_API_ERR_NOT_SUPPORTED, + policy_ret != ESP_OK ? "API policy unavailable" : "Method not allowed"); + return policy_ret != ESP_OK ? policy_ret : ESP_ERR_NOT_SUPPORTED; + } + // 直接调用本地 API + ts_api_result_t local_result = {0}; + cJSON *api_params = cJSON_CreateObject(); + if (!api_params) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Parameter allocation failed"); + return ESP_ERR_NO_MEM; + } + const char *query = (parsed.field_set & (1U << UF_QUERY)) ? url + parsed.field_data[UF_QUERY].off : NULL; + if (query) { + char *copy = strndup(query, parsed.field_data[UF_QUERY].len); + if (!copy) { + cJSON_Delete(api_params); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Query allocation failed"); + return ESP_ERR_NO_MEM; } - api_name[j] = '\0'; - - TS_LOGI(TAG, "Local API call detected, calling directly: %s", api_name); - - // 直接调用本地 API - ts_api_result_t local_result = {0}; - cJSON *api_params = cJSON_CreateObject(); - const char *query = strchr(api_path, '?'); - if (query) { - char *copy = strdup(query + 1); - if (!copy) { - cJSON_Delete(api_params); - ts_api_result_error(result, TS_API_ERR_NO_MEM, "Query allocation failed"); - return ESP_ERR_NO_MEM; - } - ts_api_parse_query(api_params, copy); - free(copy); + ts_api_params_status_t parsed = ts_api_params_add_query(api_params, copy); + free(copy); + if (parsed != TS_API_PARAMS_OK) { + cJSON_Delete(api_params); + ts_api_result_error(result, parsed == TS_API_PARAMS_NO_MEM ? TS_API_ERR_NO_MEM : TS_API_ERR_INVALID_ARG, + "Invalid or unavailable query"); + return parsed == TS_API_PARAMS_NO_MEM ? ESP_ERR_NO_MEM : ESP_ERR_INVALID_ARG; } + } - esp_err_t ret = ts_api_call_for_session(api_name, api_params, session_id, &local_result); - cJSON_Delete(api_params); - - if (ret == ESP_OK && local_result.code == TS_API_OK) { - cJSON *data = cJSON_CreateObject(); - cJSON_AddNumberToObject(data, "status", 200); - cJSON_AddNumberToObject(data, "content_length", 0); - - // 包装本地 API 响应 - cJSON *body = cJSON_CreateObject(); - cJSON_AddNumberToObject(body, "code", local_result.code); - if (local_result.message) { - cJSON_AddStringToObject(body, "message", local_result.message); - } - if (local_result.data) { - cJSON_AddItemToObject(body, "data", cJSON_Duplicate(local_result.data, true)); - } - cJSON_AddItemToObject(data, "body", body); - - result->code = TS_API_OK; - result->message = strdup("Local API call successful"); - result->data = data; - } else { - result->code = local_result.code ? local_result.code : TS_API_ERR_INTERNAL; - result->message = local_result.message ? strdup(local_result.message) : strdup("Local API call failed"); + cJSON *data = cJSON_CreateObject(), *body = cJSON_CreateObject(); + char *success = strdup("Local API call successful"); + bool prepared = data && body && success && cJSON_AddNumberToObject(data, "status", 200) && + cJSON_AddNumberToObject(data, "content_length", 0) && cJSON_AddNumberToObject(body, "code", 0); + if (!prepared || !cJSON_AddItemToObjectCS(data, "body", body)) { + cJSON_Delete(data); cJSON_Delete(body); cJSON_Delete(api_params); free(success); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Response allocation failed"); + return ESP_ERR_NO_MEM; + } + esp_err_t ret = ts_api_call_for_session(api_name, api_params, session_id, &local_result); + cJSON_Delete(api_params); + if (ret == ESP_OK && local_result.code == TS_API_OK) { + bool complete = !local_result.message || cJSON_AddStringToObject(body, "message", local_result.message); + if (complete && local_result.data) { + complete = cJSON_AddItemToObjectCS(body, "data", local_result.data); + if (complete) local_result.data = NULL; } - - // 清理本地结果 - if (local_result.message) free(local_result.message); - if (local_result.data) cJSON_Delete(local_result.data); - - return ESP_OK; + if (complete) { + result->code = TS_API_OK; result->message = success; success = NULL; + result->data = data; data = NULL; + } else ts_api_result_error(result, TS_API_ERR_INTERNAL, "result_unknown"); + } else { + result->code = local_result.code ? local_result.code : TS_API_ERR_INTERNAL; + result->message = local_result.message; local_result.message = NULL; + result->data = local_result.data; local_result.data = NULL; } - } + free(success); cJSON_Delete(data); ts_api_result_free(&local_result); - // 外部 HTTP 请求 - esp_http_client_method_t method = HTTP_METHOD_GET; - if (strcasecmp(method_str, "POST") == 0) method = HTTP_METHOD_POST; - else if (strcasecmp(method_str, "PUT") == 0) method = HTTP_METHOD_PUT; - - // 配置 HTTP 客户端(支持 HTTP 和 HTTPS) - esp_http_client_config_t config = { - .url = url, - .method = method, - .timeout_ms = timeout_ms, - .buffer_size = 4096, - .buffer_size_tx = 1024, - .skip_cert_common_name_check = true, // 跳过 CN 检查(测试用) - .crt_bundle_attach = esp_crt_bundle_attach, // 使用证书包验证 HTTPS - }; - - esp_http_client_handle_t client = esp_http_client_init(&config); - if (!client) { - ts_api_result_reason(result, TS_API_ERR_INTERNAL, "proxy_init_failed", NULL); return ESP_OK; } - // 添加自定义头 - if (headers_json && cJSON_IsObject(headers_json)) { - cJSON *header = NULL; - cJSON_ArrayForEach(header, headers_json) { - if (cJSON_IsString(header)) { - esp_http_client_set_header(client, header->string, header->valuestring); - } + // 外部 HTTP 请求 + /* C session 0 is the existing trusted internal handler contract. Every + * external entry declares READ and supplies a verified nonzero session. + * Local proxy calls above inherit that session and the destination policy. */ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (session_id) { + ts_session_t caller; + if (ts_security_validate_session(session_id, &caller) != ESP_OK) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } + if (caller.level < TS_PERM_ROOT) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Root permission required"); + return ESP_ERR_NOT_ALLOWED; } } +#endif - // 执行请求 - esp_err_t err = esp_http_client_open(client, 0); - if (err != ESP_OK) { - esp_http_client_cleanup(client); - ts_api_result_reason(result, TS_API_ERR_CONNECTION, "proxy_connect_failed", esp_err_to_name(err)); - return ESP_OK; - } - - int content_length = esp_http_client_fetch_headers(client); - int status_code = esp_http_client_get_status_code(client); - - // 读取响应体(限制大小防止内存溢出) - int max_len = 8192; - char *body = heap_caps_malloc(max_len + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!body) { - body = malloc(max_len + 1); + esp_http_client_method_t method; + if (!strcasecmp(method_str, "GET")) method = HTTP_METHOD_GET; + else if (!strcasecmp(method_str, "POST")) method = HTTP_METHOD_POST; + else if (!strcasecmp(method_str, "PUT")) method = HTTP_METHOD_PUT; + else if (!strcasecmp(method_str, "DELETE")) method = HTTP_METHOD_DELETE; + else { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Unsupported HTTP method"); + return ESP_ERR_INVALID_ARG; + } + cJSON *ca = cJSON_GetObjectItem(params, "cert_pem"); + cJSON *skip = cJSON_GetObjectItem(params, "skip_verify"); + if ((ca && !cJSON_IsString(ca)) || (skip && !cJSON_IsFalse(skip))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Certificate verification is required"); + return ESP_ERR_INVALID_ARG; + } + char *success = strdup("Request successful"); + if (!success) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Response allocation failed"); + return ESP_ERR_NO_MEM; } - - int read_len = 0; - if (body) { - read_len = esp_http_client_read(client, body, max_len); - if (read_len >= 0) { - body[read_len] = '\0'; - } else { - body[0] = '\0'; + ts_http_fetch_config_t request = {.url = url, .method = method, .headers = headers_json, + .cert_pem = ca ? ca->valuestring : NULL, .timeout_ms = (unsigned)timeout_ms, .maximum_body = 8192, + .current = proxy_fetch_current, .context = (void *)(uintptr_t)session_id}; + ts_http_fetch_result_t reply = {0}; + esp_err_t error = ts_http_fetch(&request, &reply); + if (error != ESP_OK) { + free(success); + if (!proxy_fetch_current((void *)(uintptr_t)session_id)) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Root permission required"); + return ESP_ERR_NOT_ALLOWED; } + ts_api_result_reason(result, error == ESP_ERR_INVALID_ARG ? TS_API_ERR_INVALID_ARG : TS_API_ERR_CONNECTION, + "proxy_connect_failed", esp_err_to_name(error)); + return ESP_OK; } - - esp_http_client_close(client); - esp_http_client_cleanup(client); - - // 构建响应 - if (status_code >= 200 && status_code < 400) { + if (!proxy_fetch_current((void *)(uintptr_t)session_id)) { + free(reply.body); free(success); + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Root permission required"); + return ESP_ERR_NOT_ALLOWED; + } + if (reply.status >= 200 && reply.status < 400) { cJSON *data = cJSON_CreateObject(); - cJSON_AddNumberToObject(data, "status", status_code); - cJSON_AddNumberToObject(data, "content_length", content_length); - - // 尝试解析为 JSON,如果失败则作为字符串返回 - cJSON *body_json = cJSON_Parse(body); - if (body_json) { - cJSON_AddItemToObject(data, "body", body_json); + cJSON *body = cJSON_Parse(reply.body); + if (!body) body = cJSON_CreateString(reply.body ? reply.body : ""); + if (!data || !body || !cJSON_AddNumberToObject(data, "status", reply.status) || + !cJSON_AddNumberToObject(data, "content_length", (double)reply.content_length) || + !cJSON_AddItemToObjectCS(data, "body", body)) { + cJSON_Delete(data); cJSON_Delete(body); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "result_unknown"); } else { - cJSON_AddStringToObject(data, "body", body ? body : ""); + result->code = TS_API_OK; result->data = data; + result->message = success; success = NULL; } - - result->code = TS_API_OK; - result->message = strdup("Request successful"); - result->data = data; - } else { - proxy_http_error(result, status_code, body); - } - - if (body) free(body); + } else proxy_http_error(result, reply.status, reply.body); + free(reply.body); free(success); return ESP_OK; } @@ -1510,10 +1534,73 @@ static cJSON *extract_json_value(cJSON *json, const char *path) return current; } +/* A diagnostic sample is one complete WS message, not an SDK read fragment. + * Keep frame offsets independent from RFC continuation frames. The 64 KiB cap + * includes all continuation frames and is checked before allocating. */ +#define PROXY_WS_SAMPLE_MAX (64U * 1024U) +typedef struct { + char *data; + size_t length, capacity, frame_length, frame_offset; + uint8_t frame_opcode; + bool started, frame_open, frame_fin; +} proxy_ws_sample_t; + +/* 0: incomplete/control, 1: complete; failure returns a stable reason. */ +static int proxy_ws_sample_append(proxy_ws_sample_t *sample, + const esp_websocket_event_data_t *event, + const char **reason) +{ + if (event->op_code >= 8) return 0; + if (event->data_len < 0 || event->payload_len < 0 || event->payload_offset < 0 || + (event->data_len && !event->data_ptr)) goto invalid; + size_t length=(size_t)event->data_len, offset=(size_t)event->payload_offset; + size_t total=(size_t)event->payload_len; + if (offset>total || length>total-offset) goto invalid; + if (!offset) { + if (sample->frame_open) goto invalid; + if (event->op_code==1 || event->op_code==2) { + if (sample->started) goto invalid; + sample->length=0;sample->started=true; + } else if (event->op_code!=0 || !sample->started) goto invalid; + if (total>PROXY_WS_SAMPLE_MAX-sample->length) goto too_large; + sample->frame_length=total;sample->frame_offset=0; + sample->frame_opcode=event->op_code;sample->frame_fin=event->fin; + sample->frame_open=true; + } else if (!sample->frame_open || total!=sample->frame_length || + event->op_code!=sample->frame_opcode || event->fin!=sample->frame_fin) goto invalid; + if (offset!=sample->frame_offset) goto invalid; + if (length>PROXY_WS_SAMPLE_MAX-sample->length) goto too_large; + size_t needed=sample->length+length+1; + if (needed>sample->capacity) { + size_t capacity=(needed+4095U)&~(size_t)4095U; + if (capacity>PROXY_WS_SAMPLE_MAX+1U) capacity=PROXY_WS_SAMPLE_MAX+1U; + char *next=heap_caps_realloc(sample->data,capacity,MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT); + if (!next) next=heap_caps_realloc(sample->data,capacity,MALLOC_CAP_8BIT); + if (!next) { *reason="no_memory";return -1; } + sample->data=next;sample->capacity=capacity; + } + if (length) memcpy(sample->data+sample->length,event->data_ptr,length); + sample->length+=length;sample->frame_offset+=length; + sample->data[sample->length]='\0'; + if (sample->frame_offset==sample->frame_length) { + sample->frame_open=false; + if (sample->frame_fin) { + sample->started=false; + if (memchr(sample->data,'\0',sample->length)) goto invalid; + return 1; + } + } + return 0; +too_large: + *reason="ws_message_too_large";return -1; +invalid: + *reason="ws_invalid_frame";return -1; +} + // WebSocket 测试状态 typedef struct { - char *message; // 接收到的消息 - size_t message_len; + proxy_ws_sample_t sample; // Complete bounded message + bool failed; char *error; // 错误信息 bool connected; // 已连接标志 bool received; // 已收到数据标志 @@ -1544,27 +1631,14 @@ static void ws_test_handler(void *handler_args, esp_event_base_t base, int32_t e break; case WEBSOCKET_EVENT_DATA: - if (data->op_code < 8 && !ctx->received) { - if (data->data_len > 0 && data->data_ptr) { - TS_LOGI(TAG, "WS test: received %d bytes", data->data_len); - if (!ctx->message) { - ctx->message = heap_caps_malloc(8192, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!ctx->message) ctx->message = malloc(8192); - } - if (!ctx->message) { - ctx->error = strdup("no_memory"); - if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); - break; - } - size_t space = 8191 - ctx->message_len; - size_t copied = (size_t)data->data_len < space ? (size_t)data->data_len : space; - memcpy(ctx->message + ctx->message_len, data->data_ptr, copied); - ctx->message_len += copied; - ctx->message[ctx->message_len] = '\0'; - } - if (ctx->message_len > 0 && data->fin && (data->payload_len == 0 || - data->payload_offset + data->data_len >= data->payload_len)) { - ctx->received = true; + if (!ctx->received && !ctx->failed) { + const char *reason=NULL; + int state=proxy_ws_sample_append(&ctx->sample,data,&reason); + if (state<0) { + ctx->failed=true;ctx->error=strdup(reason); + if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); + } else if (state>0) { + ctx->received=true; if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); } } @@ -1572,7 +1646,8 @@ static void ws_test_handler(void *handler_args, esp_event_base_t base, int32_t e case WEBSOCKET_EVENT_ERROR: TS_LOGE(TAG, "WS test: error"); - ctx->error = strdup("ws_connect_failed"); + ctx->failed=true; + if (!ctx->error) ctx->error = strdup("ws_connect_failed"); // 释放所有信号量 if (ctx->connect_sem) xSemaphoreGive(ctx->connect_sem); if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); @@ -1599,6 +1674,33 @@ static void ws_test_handler(void *handler_args, esp_event_base_t base, int32_t e * - message: Raw message or extracted value * - raw: Full raw message (if json_path is specified) */ +/* One operation budget across diagnostic connect, send, probe and sample waits. + * SDK stop/destroy still joins the transport task before freeing callback state. */ +static bool proxy_test_timeout(const cJSON *value, unsigned fallback, unsigned *out) +{ + if (!value) { *out = fallback; return true; } + if (!cJSON_IsNumber(value) || !isfinite(value->valuedouble) || + value->valuedouble < 1 || value->valuedouble > 30000 || + value->valuedouble != (unsigned)value->valuedouble) return false; + *out = (unsigned)value->valuedouble; + return true; +} + +static unsigned proxy_test_remaining_ms(int64_t deadline) +{ + int64_t remaining = deadline - esp_timer_get_time(); + return remaining > 0 ? (unsigned)(remaining / 1000) : 0; +} + +static bool proxy_test_send(esp_websocket_client_handle_t client, const char *text, + int64_t deadline) +{ + unsigned remaining = proxy_test_remaining_ms(deadline); + size_t length = strlen(text); + return remaining && esp_websocket_client_send_text(client, text, length, + pdMS_TO_TICKS(remaining)) == (int)length; +} + static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result_t *result) { cJSON *uri_json = cJSON_GetObjectItem(params, "uri"); @@ -1613,14 +1715,27 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result } const char *uri = uri_json->valuestring; - int timeout_ms = (timeout_json && cJSON_IsNumber(timeout_json)) ? timeout_json->valueint : 10000; + struct http_parser_url parsed; + if (!ts_ws_url_parse(uri, &parsed)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid WebSocket URL"); + return ESP_OK; + } + unsigned timeout_ms; + if (!proxy_test_timeout(timeout_json, 10000, &timeout_ms) || + (subscribe_json && !cJSON_IsNull(subscribe_json) && (!cJSON_IsString(subscribe_json) || + strnlen(subscribe_json->valuestring, 4097) > 4096)) || + (json_path_json && !cJSON_IsNull(json_path_json) && (!cJSON_IsString(json_path_json) || + strnlen(json_path_json->valuestring, 256) > 255))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid diagnostic timeout or message"); + return ESP_OK; + } + int64_t deadline = esp_timer_get_time() + (int64_t)timeout_ms * 1000; const char *subscribe_msg = (subscribe_json && cJSON_IsString(subscribe_json)) ? subscribe_json->valuestring : NULL; const char *json_path = (json_path_json && cJSON_IsString(json_path_json)) ? json_path_json->valuestring : NULL; - TS_LOGI(TAG, "WS test: uri=%s timeout=%d", uri, timeout_ms); + TS_LOGI(TAG, "WS test timeout=%u", timeout_ms); ws_test_ctx_t ctx = { - .message = NULL, .error = NULL, .connected = false, .received = false, @@ -1636,17 +1751,39 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result return ESP_OK; } + cJSON *data = cJSON_CreateObject(); + if (!data) { + vSemaphoreDelete(ctx.connect_sem); + vSemaphoreDelete(ctx.data_sem); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "no_memory"); + return ESP_OK; + } + result->data = data; + + ts_api_ws_test_transport_t transport; + esp_err_t setup = ts_api_ws_test_transport_init(&transport, uri, deadline); + if (setup != ESP_OK) { + vSemaphoreDelete(ctx.connect_sem); + vSemaphoreDelete(ctx.data_sem); + ts_api_result_reason(result, setup == ESP_ERR_NO_MEM ? TS_API_ERR_NO_MEM : TS_API_ERR_CONNECTION, + "proxy_init_failed", esp_err_to_name(setup)); + return ESP_OK; + } + // 配置 WebSocket 客户端 esp_websocket_client_config_t ws_cfg = { .uri = uri, + .port = transport.port, + .ext_transport = transport.websocket, .buffer_size = 4096, .network_timeout_ms = timeout_ms, - .reconnect_timeout_ms = timeout_ms, // 禁用自动重连(使用大超时) + .disable_auto_reconnect = true, .crt_bundle_attach = esp_crt_bundle_attach, }; esp_websocket_client_handle_t client = esp_websocket_client_init(&ws_cfg); if (!client) { + ts_api_ws_test_transport_destroy(&transport); vSemaphoreDelete(ctx.connect_sem); vSemaphoreDelete(ctx.data_sem); result->code = TS_API_ERR_INTERNAL; @@ -1654,12 +1791,13 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result return ESP_OK; } - esp_websocket_register_events(client, WEBSOCKET_EVENT_ANY, ws_test_handler, &ctx); + esp_err_t err = esp_websocket_register_events(client, WEBSOCKET_EVENT_ANY, ws_test_handler, &ctx); // 启动连接 - esp_err_t err = esp_websocket_client_start(client); + if (err == ESP_OK) err = esp_websocket_client_start(client); if (err != ESP_OK) { esp_websocket_client_destroy(client); + ts_api_ws_test_transport_destroy(&transport); vSemaphoreDelete(ctx.connect_sem); vSemaphoreDelete(ctx.data_sem); ts_api_result_reason(result, TS_API_ERR_CONNECTION, "ws_start_failed", esp_err_to_name(err)); @@ -1667,12 +1805,14 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result } // 等待连接建立 - bool connect_ok = (xSemaphoreTake(ctx.connect_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) && ctx.connected && !ctx.error; + bool connect_ok = proxy_test_remaining_ms(deadline) && (xSemaphoreTake(ctx.connect_sem, pdMS_TO_TICKS(proxy_test_remaining_ms(deadline))) == pdTRUE) && ctx.connected && !ctx.failed && proxy_test_remaining_ms(deadline); - cJSON *data = cJSON_CreateObject(); cJSON_AddBoolToObject(data, "connected", connect_ok); if (!connect_ok) { + esp_websocket_client_stop(client); + esp_websocket_client_destroy(client); + ts_api_ws_test_transport_destroy(&transport); // 连接失败 result->code = TS_API_ERR_INTERNAL; if (ctx.error) { @@ -1684,28 +1824,34 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result cJSON_AddStringToObject(data, "error", result->message); result->data = data; - esp_websocket_client_stop(client); - esp_websocket_client_destroy(client); vSemaphoreDelete(ctx.connect_sem); vSemaphoreDelete(ctx.data_sem); - free(ctx.message); + free(ctx.sample.data); return ESP_OK; } // 连接成功,发送订阅消息(如果有) + bool subscribe_ok = true; if (subscribe_msg) { TS_LOGI(TAG, "WS test: sending subscribe message"); - esp_websocket_client_send_text(client, subscribe_msg, strlen(subscribe_msg), pdMS_TO_TICKS(5000)); + subscribe_ok = proxy_test_send(client, subscribe_msg, deadline); } // 等待数据消息 - bool data_ok = (xSemaphoreTake(ctx.data_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) && ctx.received && ctx.message; + bool data_ok = subscribe_ok && proxy_test_remaining_ms(deadline) && (xSemaphoreTake(ctx.data_sem, + pdMS_TO_TICKS(proxy_test_remaining_ms(deadline))) == pdTRUE) && + ctx.received && !ctx.failed && ctx.sample.data && proxy_test_remaining_ms(deadline); - if (data_ok && ctx.message) { - TS_LOGI(TAG, "WS test: message received, len=%d", (int)strlen(ctx.message)); + esp_websocket_client_stop(client); + esp_websocket_client_destroy(client); + ts_api_ws_test_transport_destroy(&transport); + if (!subscribe_ok && !ctx.error) ctx.error = strdup("ws_send_failed"); + + if (data_ok && ctx.sample.data) { + TS_LOGI(TAG, "WS test: message received, len=%d", (int)strlen(ctx.sample.data)); // 尝试解析为 JSON - cJSON *msg_json = cJSON_Parse(ctx.message); + cJSON *msg_json = cJSON_Parse(ctx.sample.data); if (msg_json) { // 如果指定了 json_path,提取值 @@ -1725,7 +1871,7 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result } } else { // 非 JSON 消息,返回原始文本 - cJSON_AddStringToObject(data, "message", ctx.message); + cJSON_AddStringToObject(data, "message", ctx.sample.data); } result->code = TS_API_OK; @@ -1740,10 +1886,8 @@ static esp_err_t api_automation_proxy_ws_test(const cJSON *params, ts_api_result result->data = data; - // 清理 - esp_websocket_client_stop(client); - esp_websocket_client_destroy(client); - free(ctx.message); + // Callback state is stable after the SDK task has joined. + free(ctx.sample.data); vSemaphoreDelete(ctx.connect_sem); vSemaphoreDelete(ctx.data_sem); if (ctx.error) free(ctx.error); @@ -1768,10 +1912,8 @@ typedef struct { SemaphoreHandle_t upgrade_sem; // 升级完成信号量 SemaphoreHandle_t data_sem; // 数据接收信号量 const char *target_event; // 目标事件名(可选过滤) - // 消息分片缓冲区(大消息可能分多个帧发送) - char *fragment_buf; // 分片缓冲区 - size_t fragment_len; // 当前分片长度 - size_t fragment_cap; // 缓冲区容量 + proxy_ws_sample_t sample; // Complete bounded WS message + bool failed; } sio_test_ctx_t; /** @@ -1791,6 +1933,7 @@ typedef struct { */ static bool sio_try_parse_event(sio_test_ctx_t *ctx, const char *data, size_t len) { + if (!data || len<3) return false; // 查找 JSON 数组开始 const char *json_start = NULL; for (size_t i = 0; i < len - 1; i++) { @@ -1818,20 +1961,18 @@ static bool sio_try_parse_event(sio_test_ctx_t *ctx, const char *data, size_t le strcmp(ctx->target_event, event_str) == 0); if (match && !ctx->received) { - TS_LOGI(TAG, "Socket.IO event matched: %s", event_str); - - if (ctx->event_name) free(ctx->event_name); - ctx->event_name = strdup(event_str); - - if (payload) { - char *payload_str = cJSON_PrintUnformatted(payload); - if (payload_str) { - if (ctx->message) free(ctx->message); - ctx->message = payload_str; - TS_LOGI(TAG, "Socket.IO payload size: %zu bytes", strlen(payload_str)); - } + TS_LOGI(TAG, "Socket.IO event matched"); + + char *name=strdup(event_str); + char *message=payload ? cJSON_PrintUnformatted(payload) : strdup("null"); + if (!name || !message) { + free(name);free(message);ctx->failed=true; + if (!ctx->error) ctx->error=strdup("no_memory"); + if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); + cJSON_Delete(arr);return false; } - + free(ctx->event_name);free(ctx->message); + ctx->event_name=name;ctx->message=message; ctx->received = true; if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); } @@ -1847,36 +1988,6 @@ static void sio_parse_message(sio_test_ctx_t *ctx, const char *data, int len) char type = data[0]; - // 检查是否是分片续传(不以协议类型数字开头) - bool is_continuation = (type < '0' || type > '9') && ctx->fragment_len > 0; - - if (is_continuation) { - // 追加到分片缓冲区 - size_t new_len = ctx->fragment_len + len; - if (new_len + 1 > ctx->fragment_cap) { - size_t new_cap = new_len + 1024; - char *new_buf = heap_caps_realloc(ctx->fragment_buf, new_cap, MALLOC_CAP_SPIRAM); - if (!new_buf) { - TS_LOGE(TAG, "Fragment buffer realloc failed"); - return; - } - ctx->fragment_buf = new_buf; - ctx->fragment_cap = new_cap; - } - memcpy(ctx->fragment_buf + ctx->fragment_len, data, len); - ctx->fragment_len = new_len; - ctx->fragment_buf[new_len] = '\0'; - - // 尝试解析完整消息 - if (ctx->fragment_buf[0] == '4' && ctx->fragment_buf[1] == '2') { - if (sio_try_parse_event(ctx, ctx->fragment_buf, ctx->fragment_len)) { - // 解析成功,清空缓冲区 - ctx->fragment_len = 0; - } - } - return; - } - switch (type) { case '0': { // Engine.IO open - 解析 sid @@ -1888,7 +1999,7 @@ static void sio_parse_message(sio_test_ctx_t *ctx, const char *data, int len) if (sid && cJSON_IsString(sid)) { if (ctx->sid) free(ctx->sid); ctx->sid = strdup(sid->valuestring); - TS_LOGI(TAG, "Socket.IO sid: %s", ctx->sid); + TS_LOGI(TAG, "Socket.IO session received"); } cJSON_Delete(json); } @@ -1916,30 +2027,14 @@ static void sio_parse_message(sio_test_ctx_t *ctx, const char *data, int len) } else if (sio_type == '2') { // Socket.IO event: 42["event_name", data] - // 先尝试直接解析 - if (!sio_try_parse_event(ctx, data, len)) { - // 解析失败,可能是分片消息,存入缓冲区 - if (ctx->fragment_cap < (size_t)len + 1) { - size_t new_cap = len + 4096; - char *new_buf = heap_caps_realloc(ctx->fragment_buf, new_cap, MALLOC_CAP_SPIRAM); - if (new_buf) { - ctx->fragment_buf = new_buf; - ctx->fragment_cap = new_cap; - } - } - if (ctx->fragment_buf && ctx->fragment_cap >= (size_t)len + 1) { - memcpy(ctx->fragment_buf, data, len); - ctx->fragment_len = len; - ctx->fragment_buf[len] = '\0'; - TS_LOGI(TAG, "Socket.IO event fragmented, buffering %d bytes", len); - } - } + // SDK chunks and RFC continuations are assembled by the caller. + sio_try_parse_event(ctx, data, (size_t)len); } break; } default: - TS_LOGD(TAG, "Socket.IO unknown message type: %c", type); + TS_LOGD(TAG, "Socket.IO unknown message type"); break; } } @@ -1965,22 +2060,24 @@ static void sio_ws_handler(void *handler_args, esp_event_base_t base, int32_t ev break; case WEBSOCKET_EVENT_DATA: - if (data->data_len > 0) { - // 临时 null 终止以便解析 - char *buf = strndup(data->data_ptr, data->data_len); - if (buf) { - // 打印接收到的所有消息(调试用) - TS_LOGI(TAG, "Socket.IO recv [%d]: %.100s%s", data->data_len, buf, - data->data_len > 100 ? "..." : ""); - sio_parse_message(ctx, buf, data->data_len); - free(buf); + if (!ctx->received && !ctx->failed) { + const char *reason=NULL; + int state=proxy_ws_sample_append(&ctx->sample,data,&reason); + if (state<0) { + ctx->failed=true;ctx->error=strdup(reason); + if (ctx->upgrade_sem) xSemaphoreGive(ctx->upgrade_sem); + if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); + } else if (state>0) { + TS_LOGI(TAG, "Socket.IO received %zu bytes", ctx->sample.length); + sio_parse_message(ctx,ctx->sample.data,(int)ctx->sample.length); } } break; case WEBSOCKET_EVENT_ERROR: TS_LOGE(TAG, "Socket.IO WS error"); - ctx->error = strdup("Socket.IO WebSocket error"); + ctx->failed=true; + if (!ctx->error) ctx->error = strdup("Socket.IO WebSocket error"); if (ctx->connect_sem) xSemaphoreGive(ctx->connect_sem); if (ctx->upgrade_sem) xSemaphoreGive(ctx->upgrade_sem); if (ctx->data_sem) xSemaphoreGive(ctx->data_sem); @@ -2025,11 +2122,28 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ const char *base_url = url_json->valuestring; const char *target_event = (event_json && cJSON_IsString(event_json)) ? event_json->valuestring : NULL; - int timeout_ms = (timeout_json && cJSON_IsNumber(timeout_json)) ? timeout_json->valueint : 15000; + unsigned timeout_ms; + if (!proxy_test_timeout(timeout_json, 15000, &timeout_ms) || + (event_json && !cJSON_IsNull(event_json) && (!cJSON_IsString(event_json) || + strnlen(event_json->valuestring, 256) > 255)) || + (json_path_json && !cJSON_IsNull(json_path_json) && (!cJSON_IsString(json_path_json) || + strnlen(json_path_json->valuestring, 256) > 255))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid diagnostic timeout or event"); + return ESP_OK; + } + int64_t deadline = esp_timer_get_time() + (int64_t)timeout_ms * 1000; const char *json_path = (json_path_json && cJSON_IsString(json_path_json)) ? json_path_json->valuestring : NULL; - TS_LOGI(TAG, "Socket.IO test: url=%s event=%s timeout=%d", - base_url, target_event ? target_event : "(any)", timeout_ms); + TS_LOGI(TAG, "Socket.IO test timeout=%u", timeout_ms); + + // Polling and upgrade use exactly the same validated base and path. + char polling_url[512]; + if (!ts_source_sio_url(base_url, NULL, polling_url, sizeof(polling_url))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid Socket.IO URL"); + return ESP_OK; + } + + ts_api_ws_test_transport_t transport = {0}; // 初始化上下文 sio_test_ctx_t ctx = { @@ -2056,70 +2170,36 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ } cJSON *result_data = cJSON_CreateObject(); - - // ========== Step 1: HTTP 轮询获取 session ========== - char polling_url[256]; - snprintf(polling_url, sizeof(polling_url), "%s/socket.io/?EIO=4&transport=polling", base_url); - - esp_http_client_config_t http_config = { - .url = polling_url, - .method = HTTP_METHOD_GET, - .timeout_ms = 10000, - .buffer_size = 2048, - .crt_bundle_attach = esp_crt_bundle_attach, - }; - - esp_http_client_handle_t http_client = esp_http_client_init(&http_config); - if (!http_client) { - result->code = TS_API_ERR_INTERNAL; - result->message = strdup("proxy_init_failed"); + if (!result_data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "no_memory"); goto cleanup; } + result->data = result_data; - esp_err_t err = esp_http_client_open(http_client, 0); - if (err != ESP_OK) { - esp_http_client_cleanup(http_client); - result->code = TS_API_ERR_INTERNAL; - result->message = strdup("proxy_connect_failed"); + unsigned remaining = proxy_test_remaining_ms(deadline); + if (!remaining) { + ts_api_result_error(result, TS_API_ERR_TIMEOUT, "sio_event_timeout"); + goto cleanup; + } + ts_http_fetch_config_t polling_request = {.url = polling_url, .method = HTTP_METHOD_GET, + .timeout_ms = remaining, .maximum_body = 2047}; + ts_http_fetch_result_t polling = {0}; + esp_err_t err = ts_http_fetch(&polling_request, &polling); + if (err != ESP_OK || polling.status != 200) { + result->code = err == ESP_ERR_NO_MEM ? TS_API_ERR_NO_MEM : TS_API_ERR_CONNECTION; + result->message = strdup(err == ESP_ERR_NO_MEM ? "proxy_init_failed" : "proxy_connect_failed"); cJSON_AddBoolToObject(result_data, "connected", false); cJSON_AddStringToObject(result_data, "error", "HTTP polling failed"); result->data = result_data; + free(polling.body); goto cleanup; } - - esp_http_client_fetch_headers(http_client); - - // 读取响应 - char *poll_response = heap_caps_malloc(2048, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!poll_response) poll_response = malloc(2048); - - int read_len = 0; - if (poll_response) { - read_len = esp_http_client_read(http_client, poll_response, 2047); - if (read_len > 0) { - poll_response[read_len] = '\0'; - TS_LOGD(TAG, "Socket.IO polling response: %s", poll_response); - - // 解析响应获取 sid - // 响应格式可能是: 0{"sid":"xxx",...} 或带长度前缀 - const char *json_start = strchr(poll_response, '{'); - if (json_start) { - cJSON *json = cJSON_Parse(json_start); - if (json) { - cJSON *sid = cJSON_GetObjectItem(json, "sid"); - if (sid && cJSON_IsString(sid)) { - ctx.sid = strdup(sid->valuestring); - TS_LOGI(TAG, "Socket.IO session: %s", ctx.sid); - } - cJSON_Delete(json); - } - } - } - free(poll_response); - } - - esp_http_client_cleanup(http_client); - + const char *json_start = polling.body ? strchr(polling.body, '{') : NULL; + cJSON *poll_json = json_start ? cJSON_Parse(json_start) : NULL; + const cJSON *sid = poll_json ? cJSON_GetObjectItemCaseSensitive(poll_json, "sid") : NULL; + if (cJSON_IsString(sid) && sid->valuestring[0]) ctx.sid = strdup(sid->valuestring); + cJSON_Delete(poll_json); + free(polling.body); if (!ctx.sid) { result->code = TS_API_ERR_INTERNAL; result->message = strdup("sio_no_session"); @@ -2129,17 +2209,35 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ goto cleanup; } + remaining = proxy_test_remaining_ms(deadline); + if (!remaining) { + ts_api_result_error(result, TS_API_ERR_TIMEOUT, "sio_event_timeout"); + goto cleanup; + } // ========== Step 2: WebSocket 连接 ========== - char ws_url[384]; - ts_source_sio_websocket_url(base_url, ctx.sid, ws_url, sizeof(ws_url)); + char ws_url[512]; + if (!ts_source_sio_url(base_url, ctx.sid, ws_url, sizeof(ws_url))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid Socket.IO session or target"); + goto cleanup; + } - TS_LOGI(TAG, "Socket.IO WS URL: %s", ws_url); + TS_LOGI(TAG, "Socket.IO WS connection prepared"); + + esp_err_t setup = ts_api_ws_test_transport_init(&transport, ws_url, deadline); + if (setup != ESP_OK) { + result->code = setup == ESP_ERR_NO_MEM ? TS_API_ERR_NO_MEM : TS_API_ERR_CONNECTION; + result->message = strdup("proxy_init_failed"); + cJSON_AddBoolToObject(result_data, "connected", false); + goto cleanup; + } esp_websocket_client_config_t ws_cfg = { .uri = ws_url, + .port = transport.port, + .ext_transport = transport.websocket, .buffer_size = 4096, - .network_timeout_ms = timeout_ms, - .reconnect_timeout_ms = timeout_ms * 2, // 禁用自动重连 + .network_timeout_ms = remaining, + .disable_auto_reconnect = true, .crt_bundle_attach = esp_crt_bundle_attach, }; @@ -2152,9 +2250,9 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ goto cleanup; } - esp_websocket_register_events(ws_client, WEBSOCKET_EVENT_ANY, sio_ws_handler, &ctx); + err = esp_websocket_register_events(ws_client, WEBSOCKET_EVENT_ANY, sio_ws_handler, &ctx); - err = esp_websocket_client_start(ws_client); + if (err == ESP_OK) err = esp_websocket_client_start(ws_client); if (err != ESP_OK) { esp_websocket_client_destroy(ws_client); result->code = TS_API_ERR_INTERNAL; @@ -2165,7 +2263,7 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ } // 等待 WebSocket 连接 - bool ws_connected = (xSemaphoreTake(ctx.connect_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) && ctx.connected; + bool ws_connected = proxy_test_remaining_ms(deadline) && (xSemaphoreTake(ctx.connect_sem, pdMS_TO_TICKS(proxy_test_remaining_ms(deadline))) == pdTRUE) && ctx.connected && !ctx.failed && proxy_test_remaining_ms(deadline); if (!ws_connected) { esp_websocket_client_stop(ws_client); @@ -2180,10 +2278,13 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ // ========== Step 3: 发送升级探针 ========== TS_LOGI(TAG, "Socket.IO sending probe"); - esp_websocket_client_send_text(ws_client, "2probe", 6, pdMS_TO_TICKS(5000)); + if (!proxy_test_send(ws_client, "2probe", deadline)) { + ts_api_result_error(result, TS_API_ERR_CONNECTION, "ws_send_failed"); + goto cleanup_ws; + } // 等待 probe 响应 - bool probe_ok = (xSemaphoreTake(ctx.upgrade_sem, pdMS_TO_TICKS(5000)) == pdTRUE) && ctx.upgraded; + bool probe_ok = proxy_test_remaining_ms(deadline) && (xSemaphoreTake(ctx.upgrade_sem, pdMS_TO_TICKS(proxy_test_remaining_ms(deadline) < 5000 ? proxy_test_remaining_ms(deadline) : 5000)) == pdTRUE) && ctx.upgraded && proxy_test_remaining_ms(deadline); if (!probe_ok) { TS_LOGW(TAG, "Socket.IO probe timeout, continuing anyway"); @@ -2192,28 +2293,38 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ // ========== Step 4: 发送升级确认 ========== TS_LOGI(TAG, "Socket.IO sending upgrade"); - esp_websocket_client_send_text(ws_client, "5", 1, pdMS_TO_TICKS(5000)); + if (!proxy_test_send(ws_client, "5", deadline)) { + ts_api_result_error(result, TS_API_ERR_CONNECTION, "ws_send_failed"); + goto cleanup_ws; + } // 短暂等待让服务器处理升级 - vTaskDelay(pdMS_TO_TICKS(100)); + vTaskDelay(pdMS_TO_TICKS(proxy_test_remaining_ms(deadline) < 100 ? proxy_test_remaining_ms(deadline) : 100)); // ========== Step 5: 发送 Socket.IO CONNECT 到默认 namespace ========== // Socket.IO 协议要求发送 40 (Engine.IO message + Socket.IO CONNECT) 来连接 namespace TS_LOGI(TAG, "Socket.IO sending CONNECT to default namespace"); - esp_websocket_client_send_text(ws_client, "40", 2, pdMS_TO_TICKS(5000)); + if (!proxy_test_send(ws_client, "40", deadline)) { + ts_api_result_error(result, TS_API_ERR_CONNECTION, "ws_send_failed"); + goto cleanup_ws; + } // 短暂等待连接确认 - vTaskDelay(pdMS_TO_TICKS(200)); + vTaskDelay(pdMS_TO_TICKS(proxy_test_remaining_ms(deadline) < 200 ? proxy_test_remaining_ms(deadline) : 200)); // ========== Step 6: 等待事件数据 ========== TS_LOGI(TAG, "Socket.IO waiting for event data..."); - bool data_ok = (xSemaphoreTake(ctx.data_sem, pdMS_TO_TICKS(timeout_ms)) == pdTRUE) && ctx.received; + bool data_ok = proxy_test_remaining_ms(deadline) && (xSemaphoreTake(ctx.data_sem, pdMS_TO_TICKS(proxy_test_remaining_ms(deadline))) == pdTRUE) && ctx.received && !ctx.failed && proxy_test_remaining_ms(deadline); + + esp_websocket_client_stop(ws_client); + esp_websocket_client_destroy(ws_client); + ws_client = NULL; cJSON_AddBoolToObject(result_data, "connected", true); cJSON_AddStringToObject(result_data, "sid", ctx.sid); if (data_ok && ctx.message) { - TS_LOGI(TAG, "Socket.IO received event: %s", ctx.event_name ? ctx.event_name : "(unknown)"); + TS_LOGI(TAG, "Socket.IO event received"); if (ctx.event_name) { cJSON_AddStringToObject(result_data, "event", ctx.event_name); @@ -2250,24 +2361,27 @@ static esp_err_t api_automation_proxy_socketio_test(const cJSON *params, ts_api_ result->code = TS_API_OK; result->message = strdup("Socket.IO test successful"); } else { - result->code = TS_API_ERR_TIMEOUT; - result->message = strdup("sio_event_timeout"); + result->code = ctx.failed ? TS_API_ERR_INTERNAL : TS_API_ERR_TIMEOUT; + result->message = strdup(ctx.error ? ctx.error : "sio_event_timeout"); cJSON_AddStringToObject(result_data, "error", - target_event ? "Target event not received" : "No event received"); + ctx.error ? ctx.error : (target_event ? "Target event not received" : "No event received")); } result->data = result_data; - // 清理 WebSocket - esp_websocket_client_stop(ws_client); - esp_websocket_client_destroy(ws_client); +cleanup_ws: + if (ws_client) { + esp_websocket_client_stop(ws_client); + esp_websocket_client_destroy(ws_client); + } cleanup: + ts_api_ws_test_transport_destroy(&transport); if (ctx.sid) free(ctx.sid); if (ctx.message) free(ctx.message); if (ctx.event_name) free(ctx.event_name); if (ctx.error) free(ctx.error); - if (ctx.fragment_buf) free(ctx.fragment_buf); + free(ctx.sample.data); if (ctx.connect_sem) vSemaphoreDelete(ctx.connect_sem); if (ctx.upgrade_sem) vSemaphoreDelete(ctx.upgrade_sem); if (ctx.data_sem) vSemaphoreDelete(ctx.data_sem); @@ -2688,449 +2802,464 @@ esp_err_t ts_api_automation_register(void) TS_LOGI(TAG, "Registering automation APIs"); const ts_api_endpoint_t configuration[]={ - {.name="automation.config.status",.description="Current automation storage and backup status",.category=TS_API_CAT_CONFIG,.handler=api_config_status,.requires_auth=false}, - {.name="automation.config.refresh",.description="Check SD card once without changing the user choice",.category=TS_API_CAT_CONFIG,.handler=api_config_refresh,.requires_auth=true}, - {.name="automation.config.backup",.description="Save the complete emergency configuration",.category=TS_API_CAT_CONFIG,.handler=api_config_backup,.requires_auth=true}, - {.name="automation.config.preview",.description="Preview a configuration restore or source choice",.category=TS_API_CAT_CONFIG,.handler=api_config_preview,.requires_auth=true}, - {.name="automation.config.apply",.description="Apply the confirmed restore or source choice",.category=TS_API_CAT_CONFIG,.handler=api_config_apply,.requires_auth=true}, - {.name="automation.config.enable",.description="Explicitly enable or pause the current configuration",.category=TS_API_CAT_CONFIG,.handler=api_config_enable,.requires_auth=true}, + {.name="automation.config.status", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ,.description="Current automation storage and backup status",.category=TS_API_CAT_CONFIG,.handler=api_config_status,.requires_auth=true}, + {.name="automation.config.refresh", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE,.description="Check SD card once without changing the user choice",.category=TS_API_CAT_CONFIG,.handler=api_config_refresh,.requires_auth=true}, + {.name="automation.config.backup", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE,.description="Save the complete emergency configuration",.category=TS_API_CAT_CONFIG,.handler=api_config_backup,.requires_auth=true}, + {.name="automation.config.preview", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST,.description="Preview a configuration restore or source choice",.category=TS_API_CAT_CONFIG,.handler=api_config_preview,.requires_auth=true}, + {.name="automation.config.apply", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST,.description="Apply the confirmed restore or source choice",.category=TS_API_CAT_CONFIG,.handler=api_config_apply,.requires_auth=true}, + {.name="automation.config.enable", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE,.description="Explicitly enable or pause the current configuration",.category=TS_API_CAT_CONFIG,.handler=api_config_enable,.requires_auth=true}, }; esp_err_t ret=ts_api_register_multiple(configuration,sizeof(configuration)/sizeof(configuration[0])); if(ret!=ESP_OK)return ret; // Status ts_api_endpoint_t ep_status = { - .name = "automation.status", + .name = "automation.status", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get automation engine status", .category = TS_API_CAT_SYSTEM, .handler = api_automation_status, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_status); // Control APIs ts_api_endpoint_t ep_start = { - .name = "automation.start", + .name = "automation.start", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Start automation engine", .category = TS_API_CAT_SYSTEM, .handler = api_automation_start, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_start); ts_api_endpoint_t ep_stop = { - .name = "automation.stop", + .name = "automation.stop", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Stop automation engine", .category = TS_API_CAT_SYSTEM, .handler = api_automation_stop, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_stop); ts_api_endpoint_t ep_pause = { - .name = "automation.pause", + .name = "automation.pause", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Pause automation engine", .category = TS_API_CAT_SYSTEM, .handler = api_automation_pause, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_pause); ts_api_endpoint_t ep_resume = { - .name = "automation.resume", + .name = "automation.resume", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Resume automation engine", .category = TS_API_CAT_SYSTEM, .handler = api_automation_resume, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_resume); ts_api_endpoint_t ep_reload = { - .name = "automation.reload", + .name = "automation.reload", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Reload configuration", .category = TS_API_CAT_SYSTEM, .handler = api_automation_reload, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_reload); // Variables APIs ts_api_endpoint_t ep_vars_list = { - .name = "automation.variables.list", + .name = "automation.variables.list", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "List all variables", .category = TS_API_CAT_SYSTEM, .handler = api_automation_variables_list, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_vars_list); ts_api_endpoint_t ep_vars_get = { - .name = "automation.variables.get", + .name = "automation.variables.get", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get variable value", .category = TS_API_CAT_SYSTEM, .handler = api_automation_variables_get, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_vars_get); ts_api_endpoint_t ep_vars_set = { - .name = "automation.variables.set", + .name = "automation.variables.set", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Set variable value", .category = TS_API_CAT_SYSTEM, .handler = api_automation_variables_set, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_vars_set); ts_api_endpoint_t ep_vars_delete = ep_vars_set; ep_vars_delete.name = "automation.variables.delete"; + ep_vars_delete.external_access=TS_API_ACCESS_ROOT; + ep_vars_delete.allowed_methods=TS_API_METHOD_WRITE; + ep_vars_delete.requires_auth=true; ep_vars_delete.description = "Delete a saved user variable"; ep_vars_delete.handler = api_automation_variables_delete; ts_api_register(&ep_vars_delete); // Rules APIs ts_api_endpoint_t ep_rules_list = { - .name = "automation.rules.list", + .name = "automation.rules.list", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "List all rules", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_list, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_rules_list); ts_api_endpoint_t ep_rules_enable = { - .name = "automation.rules.enable", + .name = "automation.rules.enable", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Enable a rule", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_enable, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_enable); ts_api_endpoint_t ep_rules_disable = { - .name = "automation.rules.disable", + .name = "automation.rules.disable", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Disable a rule", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_disable, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_disable); ts_api_endpoint_t ep_rules_get = { - .name = "automation.rules.get", + .name = "automation.rules.get", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get rule details by ID", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_get, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_rules_get); - ts_api_endpoint_t ep_service = {.name = "automation.services.status", + ts_api_endpoint_t ep_service = {.name = "automation.services.status", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Confirm managed remote process state", .category = TS_API_CAT_SYSTEM, .handler = api_service_status, - .requires_auth = true}; + .requires_auth=true}; ts_api_register(&ep_service); ep_service.name = "automation.services.stop"; + ep_service.external_access=TS_API_ACCESS_ADMIN; + ep_service.allowed_methods=TS_API_METHOD_WRITE; + ep_service.requires_auth=true; ep_service.handler = api_service_stop; ep_service.description = "Stop verified managed remote process"; ts_api_register(&ep_service); ep_service.name = "automation.services.list"; + ep_service.external_access=TS_API_ACCESS_READ; + ep_service.allowed_methods=TS_API_METHOD_READ; + ep_service.requires_auth=true; ep_service.description = "List independent remote service controls"; ep_service.handler = api_service_list; ts_api_register(&ep_service); ts_api_endpoint_t ep_rules_trigger = { - .name = "automation.rules.trigger", + .name = "automation.rules.trigger", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Manually trigger a rule", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_trigger, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_trigger); ts_api_endpoint_t ep_rules_add = { - .name = "automation.rules.add", + .name = "automation.rules.add", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Add a new rule", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_add, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_add); ts_api_endpoint_t ep_rules_update = ep_rules_add; ep_rules_update.name = "automation.rules.update"; + ep_rules_update.external_access=TS_API_ACCESS_ROOT; + ep_rules_update.allowed_methods=TS_API_METHOD_WRITE; + ep_rules_update.requires_auth=true; ep_rules_update.description = "Update rule with expected revision"; ep_rules_update.handler = api_automation_rules_update; ts_api_register(&ep_rules_update); ts_api_endpoint_t ep_rules_delete = { - .name = "automation.rules.delete", + .name = "automation.rules.delete", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Delete a rule", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_delete, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_delete); // Sources API ts_api_endpoint_t ep_sources_list = { - .name = "automation.sources.list", + .name = "automation.sources.list", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "List all data sources", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_list, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_sources_list); ts_api_endpoint_t ep_sources_add = { - .name = "automation.sources.add", + .name = "automation.sources.add", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Add a new data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_add, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_add); ts_api_endpoint_t ep_sources_update = ep_sources_add; ep_sources_update.name = "automation.sources.update"; + ep_sources_update.external_access=TS_API_ACCESS_ROOT; + ep_sources_update.allowed_methods=TS_API_METHOD_WRITE; + ep_sources_update.requires_auth=true; ep_sources_update.description = "Update an existing data source"; ep_sources_update.handler = api_automation_sources_update; ts_api_register(&ep_sources_update); ts_api_endpoint_t ep_sources_delete = { - .name = "automation.sources.delete", + .name = "automation.sources.delete", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Delete a data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_delete, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_delete); ts_api_endpoint_t ep_sources_add_mapping = { - .name = "automation.sources.add_mapping", + .name = "automation.sources.add_mapping", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Add a field mapping to an existing data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_add_mapping, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_add_mapping); ts_api_endpoint_t ep_sources_remove_mapping = { - .name = "automation.sources.remove_mapping", + .name = "automation.sources.remove_mapping", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Remove a field mapping from a data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_remove_mapping, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_remove_mapping); ts_api_endpoint_t ep_sources_enable = { - .name = "automation.sources.enable", + .name = "automation.sources.enable", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Enable a data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_enable, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_enable); ts_api_endpoint_t ep_sources_disable = { - .name = "automation.sources.disable", + .name = "automation.sources.disable", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Disable a data source", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_disable, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_disable); // Test action APIs ts_api_endpoint_t ep_test_led = { - .name = "automation.test.led", + .name = "automation.test.led", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Test LED action", .category = TS_API_CAT_SYSTEM, .handler = api_automation_test_led, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_test_led); ts_api_endpoint_t ep_test_gpio = { - .name = "automation.test.gpio", + .name = "automation.test.gpio", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Test GPIO action", .category = TS_API_CAT_SYSTEM, .handler = api_automation_test_gpio, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_test_gpio); ts_api_endpoint_t ep_test_device = { - .name = "automation.test.device", + .name = "automation.test.device", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Test device control action", .category = TS_API_CAT_SYSTEM, .handler = api_automation_test_device, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_test_device); ts_api_endpoint_t ep_test_ssh = { - .name = "automation.test.ssh", + .name = "automation.test.ssh", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Test SSH command execution", .category = TS_API_CAT_SYSTEM, .handler = api_automation_test_ssh, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_test_ssh); // Action Template APIs ts_api_endpoint_t ep_actions_list = { - .name = "automation.actions.list", + .name = "automation.actions.list", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "List all action templates", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_list, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_actions_list); ts_api_endpoint_t ep_actions_get = { - .name = "automation.actions.get", + .name = "automation.actions.get", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get action template by ID", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_get, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_actions_get); ts_api_endpoint_t ep_actions_add = { - .name = "automation.actions.add", + .name = "automation.actions.add", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Create a new action template", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_add, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_add); ts_api_endpoint_t ep_actions_update = { - .name = "automation.actions.update", + .name = "automation.actions.update", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Update an existing action template", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_update, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_update); ts_api_endpoint_t ep_actions_delete = { - .name = "automation.actions.delete", + .name = "automation.actions.delete", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_WRITE, .description = "Delete an action template", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_delete, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_delete); ts_api_endpoint_t ep_actions_execute = { - .name = "automation.actions.execute", + .name = "automation.actions.execute", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Execute an action template", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_execute, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_execute); // Action Statistics APIs ts_api_endpoint_t ep_action_stats = { - .name = "automation.action.stats", + .name = "automation.action.stats", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get action execution statistics", .category = TS_API_CAT_SYSTEM, .handler = api_automation_action_stats, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_action_stats); ts_api_endpoint_t ep_action_stats_reset = { - .name = "automation.action.stats.reset", + .name = "automation.action.stats.reset", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Reset action statistics", .category = TS_API_CAT_SYSTEM, .handler = api_automation_action_stats_reset, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_action_stats_reset); // Proxy APIs for external connection test ts_api_endpoint_t ep_proxy_fetch = { - .name = "automation.proxy.fetch", + .name = "automation.proxy.fetch", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_POST, .session_handler=ts_api_automation_proxy_fetch_for_session, .description = "Proxy fetch from external REST API", .category = TS_API_CAT_SYSTEM, .handler = api_automation_proxy_fetch, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_proxy_fetch); ts_api_endpoint_t ep_proxy_ws = { - .name = "automation.proxy.websocket_test", + .name = "automation.proxy.websocket_test", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Test WebSocket connection", .category = TS_API_CAT_SYSTEM, .handler = api_automation_proxy_ws_test, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_proxy_ws); ts_api_endpoint_t ep_proxy_sio = { - .name = "automation.proxy.socketio_test", + .name = "automation.proxy.socketio_test", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Test Socket.IO connection (v4 protocol)", .category = TS_API_CAT_SYSTEM, .handler = api_automation_proxy_socketio_test, - .requires_auth = false, + .requires_auth=true, }; ts_api_register(&ep_proxy_sio); // Export/Import APIs - Sources ts_api_endpoint_t ep_sources_export = { - .name = "automation.sources.export", + .name = "automation.sources.export", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Export data source as config pack (.tscfg)", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_export, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_export); ts_api_endpoint_t ep_sources_import = { - .name = "automation.sources.import", + .name = "automation.sources.import", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Import data source from config pack", .category = TS_API_CAT_SYSTEM, .handler = api_automation_sources_import, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_sources_import); // Export/Import APIs - Rules ts_api_endpoint_t ep_rules_export = { - .name = "automation.rules.export", + .name = "automation.rules.export", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Export rule as config pack (.tscfg)", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_export, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_export); ts_api_endpoint_t ep_rules_import = { - .name = "automation.rules.import", + .name = "automation.rules.import", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Import rule from config pack", .category = TS_API_CAT_SYSTEM, .handler = api_automation_rules_import, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_rules_import); // Export/Import APIs - Action Templates ts_api_endpoint_t ep_actions_export = { - .name = "automation.actions.export", + .name = "automation.actions.export", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Export action template as config pack (.tscfg)", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_export, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_export); ts_api_endpoint_t ep_actions_import = { - .name = "automation.actions.import", + .name = "automation.actions.import", .external_access=TS_API_ACCESS_ROOT, .allowed_methods=TS_API_METHOD_POST, .description = "Import action template from config pack", .category = TS_API_CAT_SYSTEM, .handler = api_automation_actions_import, - .requires_auth = true, + .requires_auth=true, }; ts_api_register(&ep_actions_import); diff --git a/components/ts_api/src/ts_api_cert.c b/components/ts_api/src/ts_api_cert.c index 595e68de..8cd2e659 100644 --- a/components/ts_api/src/ts_api_cert.c +++ b/components/ts_api/src/ts_api_cert.c @@ -105,6 +105,7 @@ static void add_runtime(cJSON *data, const ts_cert_pki_status_t *s) } else { cJSON_AddNullToObject(https, "last_error_stage"); cJSON_AddNullToObject(https, "last_error"); } + } static esp_err_t install_error(ts_api_result_t *result, esp_err_t err, ts_cert_op_error_t detail) @@ -488,6 +489,8 @@ esp_err_t ts_api_cert_register(void) static const ts_api_endpoint_t cert_apis[] = { { .name = "cert.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get PKI certificate status", .category = TS_API_CAT_SECURITY, .handler = api_cert_status, @@ -496,46 +499,58 @@ esp_err_t ts_api_cert_register(void) }, { .name = "cert.generate_keypair", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Generate ECDSA P-256 key pair", .category = TS_API_CAT_SECURITY, .handler = api_cert_generate_keypair, - .requires_auth = false, - .permission = NULL + .requires_auth = true, + .permission = "cert.manage" }, { .name = "cert.generate_csr", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Generate Certificate Signing Request", .category = TS_API_CAT_SECURITY, .handler = api_cert_generate_csr, - .requires_auth = false, - .permission = NULL + .requires_auth = true, + .permission = "cert.manage" }, { .name = "cert.install", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Install signed certificate", .category = TS_API_CAT_SECURITY, .handler = api_cert_install, - .requires_auth = false, - .permission = NULL + .requires_auth = true, + .permission = "cert.manage" }, { .name = "cert.install_ca", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Install CA certificate chain", .category = TS_API_CAT_SECURITY, .handler = api_cert_install_ca, - .requires_auth = false, - .permission = NULL + .requires_auth = true, + .permission = "cert.manage" }, { .name = "cert.delete", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Delete all PKI credentials", .category = TS_API_CAT_SECURITY, .handler = api_cert_delete, - .requires_auth = false, - .permission = NULL + .requires_auth = true, + .permission = "cert.manage" }, { .name = "cert.get_certificate", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get device certificate PEM", .category = TS_API_CAT_SECURITY, .handler = api_cert_get_certificate, diff --git a/components/ts_api/src/ts_api_config.c b/components/ts_api/src/ts_api_config.c index 48def849..0eb1f638 100644 --- a/components/ts_api/src/ts_api_config.c +++ b/components/ts_api/src/ts_api_config.c @@ -13,6 +13,7 @@ #include "ts_config_meta.h" #include "ts_log.h" #include +#include #define TAG "api_config" @@ -129,7 +130,11 @@ static esp_err_t api_config_set(const cJSON *params, ts_api_result_t *result) } else if (cJSON_IsNumber(value)) { /* Check if it's an integer or float */ double d = value->valuedouble; - if (d == (int64_t)d) { + if (!isfinite(d)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid numeric config value"); + return ESP_ERR_INVALID_ARG; + } + if (d >= -0x1p63 && d < 0x1p63 && floor(d) == d) { ret = ts_config_set_int64(key->valuestring, (int64_t)d); } else { ret = ts_config_set_double(key->valuestring, d); @@ -613,6 +618,9 @@ esp_err_t ts_api_config_register(void) .description = "Get configuration value", .category = TS_API_CAT_CONFIG, .handler = api_config_get, + /* Only system.language is public; other keys keep the dispatcher Root gate. */ + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .requires_auth = false, .permission = NULL }, @@ -621,6 +629,8 @@ esp_err_t ts_api_config_register(void) .description = "Set configuration value", .category = TS_API_CAT_CONFIG, .handler = api_config_set, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.write" }, @@ -629,6 +639,8 @@ esp_err_t ts_api_config_register(void) .description = "Delete configuration value", .category = TS_API_CAT_CONFIG, .handler = api_config_delete, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.admin" }, @@ -637,7 +649,9 @@ esp_err_t ts_api_config_register(void) .description = "List configuration keys", .category = TS_API_CAT_CONFIG, .handler = api_config_list, - .requires_auth = false, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, .permission = NULL }, { @@ -645,6 +659,8 @@ esp_err_t ts_api_config_register(void) .description = "Save configuration to storage", .category = TS_API_CAT_CONFIG, .handler = api_config_save, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.write" }, @@ -654,7 +670,9 @@ esp_err_t ts_api_config_register(void) .description = "List all config modules", .category = TS_API_CAT_CONFIG, .handler = api_config_module_list, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, .permission = NULL }, { @@ -662,7 +680,9 @@ esp_err_t ts_api_config_register(void) .description = "Show module configuration", .category = TS_API_CAT_CONFIG, .handler = api_config_module_show, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, .permission = NULL }, { @@ -670,6 +690,8 @@ esp_err_t ts_api_config_register(void) .description = "Set module configuration", .category = TS_API_CAT_CONFIG, .handler = api_config_module_set, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.write" }, @@ -678,6 +700,8 @@ esp_err_t ts_api_config_register(void) .description = "Save module configuration to NVS", .category = TS_API_CAT_CONFIG, .handler = api_config_module_save, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.write" }, @@ -686,6 +710,8 @@ esp_err_t ts_api_config_register(void) .description = "Reset module configuration", .category = TS_API_CAT_CONFIG, .handler = api_config_module_reset, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "config.admin" }, diff --git a/components/ts_api/src/ts_api_config_pack.c b/components/ts_api/src/ts_api_config_pack.c index 2dd5efb5..e28f49f1 100644 --- a/components/ts_api/src/ts_api_config_pack.c +++ b/components/ts_api/src/ts_api_config_pack.c @@ -193,10 +193,11 @@ static esp_err_t api_config_pack_verify(const cJSON *params, ts_api_result_t *re } /** - * @brief config.pack.import - Validate a .tscfg file in place + * @brief config.pack.import - Admit an encrypted pack from text or uploaded path * * Parameters: - * - path: Path to already uploaded .tscfg file + * - content: Raw .tscfg JSON from the existing paste/file-picker flow + * - path: Alternative already uploaded file; validated in place * * Validates the file without copying. Use this after file upload via * storage API to get metadata and validation status. @@ -210,64 +211,71 @@ static esp_err_t api_config_pack_import(const cJSON *params, ts_api_result_t *re ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing parameters"); return ESP_ERR_INVALID_ARG; } - - const cJSON *path = cJSON_GetObjectItem(params, "path"); - if (!path || !cJSON_IsString(path)) { - ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing 'path' parameter"); + + const cJSON *content = cJSON_GetObjectItemCaseSensitive(params, "content"); + const cJSON *path = cJSON_GetObjectItemCaseSensitive(params, "path"); + if ((!cJSON_IsString(content) || !content->valuestring[0]) && + (!cJSON_IsString(path) || !path->valuestring[0])) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing 'content' or 'path' parameter"); return ESP_ERR_INVALID_ARG; } - - /* 验证配置包(不复制) */ + /* The existing paste/file picker and in-place path flows share the same + * full recipient/publisher/decrypt admission. No generic apply is implied. */ ts_config_pack_metadata_t metadata = {0}; - ts_config_pack_result_t pack_result = ts_config_pack_validate_file( - path->valuestring, - &metadata - ); - + char saved_path[128] = {0}; + ts_config_pack_result_t pack_result = cJSON_IsString(content) ? + ts_config_pack_import(content->valuestring, strlen(content->valuestring), + &metadata, saved_path, sizeof(saved_path)) : + ts_config_pack_validate_file(path->valuestring, &metadata); + if (pack_result != TS_CONFIG_PACK_OK) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, ts_config_pack_reason(pack_result)); + return ESP_FAIL; + } + const char *validated_path = cJSON_IsString(content) ? saved_path : path->valuestring; + /* 构建响应 */ cJSON *data = cJSON_CreateObject(); if (!data) { ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + cJSON_AddBoolToObject(data, "valid", pack_result == TS_CONFIG_PACK_OK); cJSON_AddNumberToObject(data, "result_code", pack_result); cJSON_AddStringToObject(data, "result_message", ts_config_pack_strerror(pack_result)); cJSON_AddStringToObject(data, "reason", ts_config_pack_reason(pack_result)); - cJSON_AddStringToObject(data, "path", path->valuestring); - - if (pack_result == TS_CONFIG_PACK_OK) { - /* 元数据 */ - cJSON_AddStringToObject(data, "name", metadata.name); - cJSON_AddStringToObject(data, "description", metadata.description); - cJSON_AddStringToObject(data, "source_file", metadata.source_file); - cJSON_AddStringToObject(data, "target_device", metadata.target_device); - cJSON_AddNumberToObject(data, "created_at", (double)metadata.created_at); - - /* 签名信息 */ - cJSON *sig = cJSON_CreateObject(); - cJSON_AddBoolToObject(sig, "valid", metadata.sig_info.valid); - cJSON_AddBoolToObject(sig, "is_official", metadata.sig_info.is_official); - cJSON_AddStringToObject(sig, "signer_cn", metadata.sig_info.signer_cn); - cJSON_AddStringToObject(sig, "signer_ou", metadata.sig_info.signer_ou); - cJSON_AddNumberToObject(sig, "signed_at", (double)metadata.sig_info.signed_at); - cJSON_AddItemToObject(data, "signature", sig); - - TS_LOGI(TAG, "Config pack validated: %s (%s)", metadata.name, path->valuestring); - } - + cJSON_AddStringToObject(data, "path", validated_path); + cJSON_AddStringToObject(data, "saved_path", validated_path); + + /* 元数据 */ + cJSON_AddStringToObject(data, "name", metadata.name); + cJSON_AddStringToObject(data, "description", metadata.description); + cJSON_AddStringToObject(data, "source_file", metadata.source_file); + cJSON_AddStringToObject(data, "target_device", metadata.target_device); + cJSON_AddNumberToObject(data, "created_at", (double)metadata.created_at); + + /* 签名信息 */ + cJSON *sig = cJSON_CreateObject(); + cJSON_AddBoolToObject(sig, "valid", metadata.sig_info.valid); + cJSON_AddBoolToObject(sig, "is_official", metadata.sig_info.is_official); + cJSON_AddStringToObject(sig, "signer_cn", metadata.sig_info.signer_cn); + cJSON_AddStringToObject(sig, "signer_ou", metadata.sig_info.signer_ou); + cJSON_AddNumberToObject(sig, "signed_at", (double)metadata.sig_info.signed_at); + cJSON_AddItemToObject(data, "signature", sig); + + TS_LOGI(TAG, "Config pack validated: %s (%s)", metadata.name, validated_path); + ts_api_result_ok(result, data); return ESP_OK; } /** - * @brief config.pack.apply - Apply configuration from a validated .tscfg file + * @brief config.pack.apply - Unsupported legacy generic application * * Parameters: * - path: Path to .tscfg file * - * Decrypts and applies the configuration to the system. + * Generic application is unsupported; use the relevant configuration owner import. */ static esp_err_t api_config_pack_apply(const cJSON *params, ts_api_result_t *result) { @@ -289,6 +297,11 @@ static esp_err_t api_config_pack_apply(const cJSON *params, ts_api_result_t *res &applied_modules ); + if (pack_result == TS_CONFIG_PACK_ERR_UNSUPPORTED) { + pack_failure(result, pack_result); + return ESP_ERR_NOT_SUPPORTED; + } + /* 构建响应 */ cJSON *data = cJSON_CreateObject(); if (!data) { @@ -367,16 +380,15 @@ static esp_err_t api_config_pack_export(const cJSON *params, ts_api_result_t *re if (cJSON_IsString(content)) { json_content = strdup(content->valuestring); - json_len = strlen(json_content); } else { json_content = cJSON_PrintUnformatted(content); - json_len = strlen(json_content); } if (!json_content) { ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } + json_len = strlen(json_content); /* 准备导出选项 */ ts_config_pack_export_opts_t opts = { @@ -427,7 +439,7 @@ static esp_err_t api_config_pack_export(const cJSON *params, ts_api_result_t *re if (save_path && cJSON_IsString(save_path) && strlen(save_path->valuestring) > 0) { const char *path = save_path->valuestring; - esp_err_t ret = ts_storage_check_write_path(path, false); + esp_err_t ret = ts_storage_check_external_write_path(path, false); char dir_path[TS_STORAGE_MAX_PATH]; if (ret == ESP_OK) { snprintf(dir_path, sizeof(dir_path), "%s", path); @@ -611,6 +623,8 @@ esp_err_t ts_api_config_pack_register(void) static const ts_api_endpoint_t pack_apis[] = { { .name = "config.pack.info", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get config pack system information", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_info, @@ -619,6 +633,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.export_cert", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Export device certificate for encryption", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_export_cert, @@ -627,6 +643,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.verify", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Verify a .tscfg package signature", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_verify, @@ -635,6 +653,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.import", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Validate an uploaded .tscfg file in place", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_import, @@ -643,7 +663,9 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.apply", - .description = "Apply configuration from a validated .tscfg file", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, + .description = "Legacy generic configuration application (unsupported)", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_apply, .requires_auth = true, @@ -651,6 +673,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.export", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Export configuration as encrypted .tscfg", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_export, @@ -659,6 +683,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List .tscfg files in directory", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_list, @@ -667,6 +693,8 @@ esp_err_t ts_api_config_pack_register(void) }, { .name = "config.pack.content", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Decrypt and get content of imported config pack", .category = TS_API_CAT_CONFIG, .handler = api_config_pack_content, diff --git a/components/ts_api/src/ts_api_device.c b/components/ts_api/src/ts_api_device.c index dd6708d2..187f67e2 100644 --- a/components/ts_api/src/ts_api_device.c +++ b/components/ts_api/src/ts_api_device.c @@ -14,15 +14,17 @@ #include "ts_power.h" #include "ts_usb_mux.h" #include +#include +#include +#include "esp_timer.h" #include +#include #include #include #include #include #include #include "lwip/inet_chksum.h" -#include "lwip/ip.h" -#include "lwip/icmp.h" #define TAG "api_device" @@ -429,119 +431,110 @@ static esp_err_t api_device_usb_set(const cJSON *params, ts_api_result_t *result * @param host: IP address (default: "10.10.99.99" for LPMU) * @param timeout: timeout in ms (default: 1000) */ -static esp_err_t api_device_ping(const cJSON *params, ts_api_result_t *result) +static atomic_flag s_ping_busy = ATOMIC_FLAG_INIT; + +static bool ping_wait(int fd, bool writing, int64_t deadline) { - const char *host = "10.10.99.99"; - int timeout_ms = 1000; - - cJSON *host_json = cJSON_GetObjectItem(params, "host"); - if (host_json && cJSON_IsString(host_json)) { - host = host_json->valuestring; - } - - cJSON *timeout_json = cJSON_GetObjectItem(params, "timeout"); - if (timeout_json && cJSON_IsNumber(timeout_json)) { - timeout_ms = timeout_json->valueint; - } - - // 创建 ICMP raw socket - int sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - if (sock < 0) { - cJSON *data = cJSON_CreateObject(); - cJSON_AddStringToObject(data, "host", host); - cJSON_AddBoolToObject(data, "reachable", false); - cJSON_AddStringToObject(data, "error", "socket creation failed"); - ts_api_result_ok(result, data); - return ESP_OK; - } - - // 设置接收超时 - struct timeval tv; - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - - struct sockaddr_in addr; - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - inet_pton(AF_INET, host, &addr.sin_addr); - - // 构建 ICMP echo request - struct { - uint8_t type; - uint8_t code; - uint16_t checksum; - uint16_t id; - uint16_t seq; - uint8_t data[32]; - } icmp_pkt; - - memset(&icmp_pkt, 0, sizeof(icmp_pkt)); - icmp_pkt.type = 8; // ICMP_ECHO - icmp_pkt.code = 0; - icmp_pkt.id = htons(0x1234); - icmp_pkt.seq = htons(1); - memset(icmp_pkt.data, 0xAB, sizeof(icmp_pkt.data)); - - // 计算校验和 - icmp_pkt.checksum = 0; - icmp_pkt.checksum = inet_chksum(&icmp_pkt, sizeof(icmp_pkt)); - - int64_t start_time = esp_timer_get_time(); - - // 发送 ICMP echo request - int sent = sendto(sock, &icmp_pkt, sizeof(icmp_pkt), 0, - (struct sockaddr *)&addr, sizeof(addr)); - + for (;;) { + int64_t remaining = deadline - esp_timer_get_time(); + if (remaining <= 0) return false; + struct timeval timeout = {.tv_sec = remaining / 1000000, + .tv_usec = remaining % 1000000}; + fd_set ready; + FD_ZERO(&ready); + FD_SET(fd, &ready); + int ret = select(fd + 1, writing ? NULL : &ready, + writing ? &ready : NULL, NULL, &timeout); + if (ret > 0) return esp_timer_get_time() < deadline; + if (ret == 0 || errno != EINTR) return false; + } +} + +static esp_err_t device_ping_impl(const cJSON *params, ts_api_result_t *result) +{ + const cJSON *host_item = cJSON_GetObjectItemCaseSensitive(params, "host"); + const cJSON *timeout_item = cJSON_GetObjectItemCaseSensitive(params, "timeout"); + const char *host = host_item && cJSON_IsString(host_item) ? host_item->valuestring : "10.10.99.99"; + unsigned timeout_ms = 1000; + struct sockaddr_in address = {.sin_family = AF_INET}; + if ((host_item && !cJSON_IsString(host_item)) || inet_pton(AF_INET, host, &address.sin_addr) != 1 || + (timeout_item && (!cJSON_IsNumber(timeout_item) || !isfinite(timeout_item->valuedouble) || + timeout_item->valuedouble < 1 || timeout_item->valuedouble > 30000 || + floor(timeout_item->valuedouble) != timeout_item->valuedouble))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid IPv4 address or timeout (1-30000 ms)"); + return ESP_ERR_INVALID_ARG; + } + if (timeout_item) timeout_ms = (unsigned)timeout_item->valuedouble; + int64_t started = esp_timer_get_time(); + int64_t deadline = started + (int64_t)timeout_ms * 1000; bool reachable = false; - int latency_ms = 0; - const char *error_msg = NULL; - - if (sent > 0) { - // 等待 ICMP echo reply - char recv_buf[64]; - struct sockaddr_in from; - socklen_t from_len = sizeof(from); - - int recv_len = recvfrom(sock, recv_buf, sizeof(recv_buf), 0, - (struct sockaddr *)&from, &from_len); - - if (recv_len > 0) { - // IP 头部通常是 20 字节,ICMP 回复在其后 - // 检查是否是 ICMP echo reply (type = 0) - if (recv_len >= 28) { // 20 (IP) + 8 (ICMP header) - uint8_t icmp_type = recv_buf[20]; - if (icmp_type == 0) { // ICMP_ECHOREPLY + const char *error = "socket creation failed"; + int fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (fd >= 0) { + int flags = fcntl(fd, F_GETFL, 0); + error = "socket setup failed"; + if (flags >= 0 && fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0) { + struct { + uint8_t type, code; + uint16_t checksum, id, sequence; + uint8_t payload[32]; + } packet = {.type = 8, .id = (uint16_t)started, .sequence = 1}; + packet.checksum = inet_chksum(&packet, sizeof(packet)); + ssize_t sent; + do { + sent = sendto(fd, &packet, sizeof(packet), 0, + (struct sockaddr *)&address, sizeof(address)); + } while (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) && + ping_wait(fd, true, deadline)); + error = sent == (ssize_t)sizeof(packet) ? "timeout" : "send failed"; + while (sent == (ssize_t)sizeof(packet) && ping_wait(fd, false, deadline)) { + uint8_t reply[128]; + struct sockaddr_in from = {0}; + socklen_t length = sizeof(from); + ssize_t received = recvfrom(fd, reply, sizeof(reply), 0, + (struct sockaddr *)&from, &length); + if (received < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; + error = "receive failed"; + break; + } + /* Ignore unrelated packets without extending the operation deadline. */ + unsigned header = received > 0 ? (reply[0] & 15U) * 4U : 0; + if (header >= 20 && received >= header + 8 && (reply[0] >> 4) == 4 && + from.sin_addr.s_addr == address.sin_addr.s_addr && reply[header] == 0 && + reply[header + 1] == 0 && !memcmp(reply + header + 4, &packet.id, 4)) { reachable = true; - latency_ms = (int)((esp_timer_get_time() - start_time) / 1000); - } else { - error_msg = "unexpected icmp type"; + break; } - } else { - error_msg = "short packet"; } - } else { - error_msg = "timeout"; } - } else { - error_msg = "send failed"; + close(fd); } - - close(sock); - cJSON *data = cJSON_CreateObject(); - cJSON_AddStringToObject(data, "host", host); - cJSON_AddBoolToObject(data, "reachable", reachable); - if (reachable) { - cJSON_AddNumberToObject(data, "latency_ms", latency_ms); - } else if (error_msg) { - cJSON_AddStringToObject(data, "error", error_msg); + bool complete = data && cJSON_AddStringToObject(data, "host", host) && + cJSON_AddBoolToObject(data, "reachable", reachable); + complete = complete && (reachable ? cJSON_AddNumberToObject(data, "latency_ms", + (double)(esp_timer_get_time() - started) / 1000) : cJSON_AddStringToObject(data, "error", error)); + if (!complete) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Insufficient device memory"); + return ESP_ERR_NO_MEM; } - ts_api_result_ok(result, data); return ESP_OK; } +static esp_err_t api_device_ping(const cJSON *params, ts_api_result_t *result) +{ + if (atomic_flag_test_and_set(&s_ping_busy)) { + ts_api_result_error(result, TS_API_ERR_BUSY, "Network diagnostic busy"); + return ESP_ERR_INVALID_STATE; + } + esp_err_t ret = device_ping_impl(params, result); + atomic_flag_clear(&s_ping_busy); + return ret; +} + /*===========================================================================*/ /* Registration */ /*===========================================================================*/ @@ -549,6 +542,8 @@ static esp_err_t api_device_ping(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t device_endpoints[] = { { .name = "device.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get device power status", .category = TS_API_CAT_DEVICE, .handler = api_device_status, @@ -556,6 +551,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.power", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Control device power (on/off/force_off)", .category = TS_API_CAT_DEVICE, .handler = api_device_power, @@ -564,6 +561,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.reset", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Reset device", .category = TS_API_CAT_DEVICE, .handler = api_device_reset, @@ -572,6 +571,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.fan.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get fan status", .category = TS_API_CAT_FAN, .handler = api_device_fan_status, @@ -579,6 +580,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.fan.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set fan mode and duty", .category = TS_API_CAT_FAN, .handler = api_device_fan_set, @@ -587,6 +590,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.power.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get power measurements", .category = TS_API_CAT_POWER, .handler = api_device_power_status, @@ -594,6 +599,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.usb.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get USB MUX status", .category = TS_API_CAT_DEVICE, .handler = api_device_usb_status, @@ -601,6 +608,8 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.usb.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set USB MUX target", .category = TS_API_CAT_DEVICE, .handler = api_device_usb_set, @@ -609,10 +618,12 @@ static const ts_api_endpoint_t device_endpoints[] = { }, { .name = "device.ping", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Test network connectivity (TCP port check)", .category = TS_API_CAT_DEVICE, .handler = api_device_ping, - .requires_auth = false, + .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_dhcp.c b/components/ts_api/src/ts_api_dhcp.c index a0dd5974..3c2299f1 100644 --- a/components/ts_api/src/ts_api_dhcp.c +++ b/components/ts_api/src/ts_api_dhcp.c @@ -255,20 +255,26 @@ esp_err_t ts_api_dhcp_register(void) static const ts_api_endpoint_t endpoints[] = { { .name = "dhcp.status", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get DHCP server status", .category = TS_API_CAT_NETWORK, .handler = api_dhcp_status, - .requires_auth = false, + .requires_auth = true, }, { .name = "dhcp.clients", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List DHCP clients", .category = TS_API_CAT_NETWORK, .handler = api_dhcp_clients, - .requires_auth = false, + .requires_auth = true, }, { .name = "dhcp.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Start DHCP server", .category = TS_API_CAT_NETWORK, .handler = api_dhcp_start, @@ -276,6 +282,8 @@ esp_err_t ts_api_dhcp_register(void) }, { .name = "dhcp.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop DHCP server", .category = TS_API_CAT_NETWORK, .handler = api_dhcp_stop, diff --git a/components/ts_api/src/ts_api_fan.c b/components/ts_api/src/ts_api_fan.c index fe0fd4e1..ee610296 100644 --- a/components/ts_api/src/ts_api_fan.c +++ b/components/ts_api/src/ts_api_fan.c @@ -13,6 +13,8 @@ #include "ts_config_module.h" #include "ts_log.h" #include +#include +#include #define TAG "api_fan" @@ -296,15 +298,30 @@ static esp_err_t api_fan_limits(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } - int fan_id = id_item->valueint; - if (fan_id < 0 || fan_id >= TS_FAN_MAX) { + double id = id_item->valuedouble; + if (!isfinite(id) || id < 0 || id >= TS_FAN_MAX || floor(id) != id) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid fan ID"); return ESP_ERR_INVALID_ARG; } + int fan_id = (int)id; + const cJSON *limits[] = { min_item, max_item }; + for (unsigned i = 0; i < 2; ++i) { + const cJSON *item = limits[i]; + if (item && (!cJSON_IsNumber(item) || !isfinite(item->valuedouble) || + item->valuedouble < 0 || item->valuedouble > 100 || + floor(item->valuedouble) != item->valuedouble)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid duty limits (0-100, min <= max)"); + return ESP_ERR_INVALID_ARG; + } + } // 获取当前配置作为默认值 ts_fan_config_t cfg; - ts_fan_get_config(fan_id, &cfg); + esp_err_t ret = ts_fan_get_config(fan_id, &cfg); + if (ret != ESP_OK) { + ts_api_result_error(result, TS_API_ERR_HARDWARE, "Failed to get fan config"); + return ret; + } uint8_t min_duty = cfg.min_duty; uint8_t max_duty = cfg.max_duty; @@ -321,7 +338,7 @@ static esp_err_t api_fan_limits(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } - esp_err_t ret = ts_fan_set_limits(fan_id, min_duty, max_duty); + ret = ts_fan_set_limits(fan_id, min_duty, max_duty); if (ret != ESP_OK) { ts_api_result_error(result, TS_API_ERR_HARDWARE, "Failed to set fan limits"); return ret; @@ -371,11 +388,12 @@ static esp_err_t api_fan_curve(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } - int fan_id = id_item->valueint; - if (fan_id < 0 || fan_id >= TS_FAN_MAX) { + double id = id_item->valuedouble; + if (!isfinite(id) || id < 0 || id >= TS_FAN_MAX || floor(id) != id) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid fan ID"); return ESP_ERR_INVALID_ARG; } + int fan_id = (int)id; int count = cJSON_GetArraySize(curve_item); if (count > TS_FAN_MAX_CURVE_POINTS) { @@ -393,11 +411,46 @@ static esp_err_t api_fan_curve(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid curve point format"); return ESP_ERR_INVALID_ARG; } + if (!isfinite(temp->valuedouble) || temp->valuedouble < INT16_MIN / 10.0 || + temp->valuedouble > INT16_MAX / 10.0 || + !isfinite(duty->valuedouble) || duty->valuedouble < 0 || + duty->valuedouble > 100 || floor(duty->valuedouble) != duty->valuedouble) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid curve point format"); + return ESP_ERR_INVALID_ARG; + } curve[i].temp = (int16_t)(temp->valuedouble * 10); /* Convert to 0.1°C */ curve[i].duty = (uint8_t)duty->valueint; } + bool set_hysteresis = hysteresis_item || interval_item; + int16_t hysteresis = 0; + uint32_t min_interval = 0; + if (set_hysteresis) { + if ((hysteresis_item && (!cJSON_IsNumber(hysteresis_item) || + !isfinite(hysteresis_item->valuedouble) || hysteresis_item->valuedouble < 0 || + hysteresis_item->valuedouble > 20)) || + (interval_item && (!cJSON_IsNumber(interval_item) || + !isfinite(interval_item->valuedouble) || interval_item->valuedouble < 100 || + interval_item->valuedouble > 60000 || + floor(interval_item->valuedouble) != interval_item->valuedouble))) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid fan hysteresis or interval"); + return ESP_ERR_INVALID_ARG; + } + ts_fan_config_t cfg; + esp_err_t ret = ts_fan_get_config(fan_id, &cfg); + if (ret != ESP_OK) { + ts_api_result_error(result, TS_API_ERR_HARDWARE, "Failed to get fan config"); + return ret; + } + hysteresis = hysteresis_item ? (int16_t)(hysteresis_item->valuedouble * 10) : cfg.hysteresis; + min_interval = interval_item ? (uint32_t)interval_item->valuedouble : cfg.min_interval; + if (hysteresis < 0 || hysteresis > 200 || min_interval < 100 || min_interval > 60000) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid fan hysteresis or interval"); + return ESP_ERR_INVALID_ARG; + } + } + esp_err_t ret = ts_fan_set_curve(fan_id, curve, count); if (ret != ESP_OK) { ts_api_result_error(result, TS_API_ERR_HARDWARE, "Failed to set fan curve"); @@ -405,24 +458,11 @@ static esp_err_t api_fan_curve(const cJSON *params, ts_api_result_t *result) } // 如果提供了 hysteresis 或 min_interval,也一并设置 - if (cJSON_IsNumber(hysteresis_item) || cJSON_IsNumber(interval_item)) { - // 获取当前配置作为默认值 - ts_fan_config_t cfg; - ts_fan_get_config(fan_id, &cfg); - - int16_t hysteresis = cfg.hysteresis; - uint32_t min_interval = cfg.min_interval; - - if (cJSON_IsNumber(hysteresis_item)) { - hysteresis = (int16_t)(hysteresis_item->valuedouble * 10); /* Convert to 0.1°C */ - } - if (cJSON_IsNumber(interval_item)) { - min_interval = (uint32_t)interval_item->valueint; - } - + if (set_hysteresis) { ret = ts_fan_set_hysteresis(fan_id, hysteresis, min_interval); if (ret != ESP_OK) { - TS_LOGW(TAG, "Failed to set hysteresis: %s", esp_err_to_name(ret)); + ts_api_result_error(result, TS_API_ERR_HARDWARE, "Failed to set fan hysteresis"); + return ret; } } @@ -545,6 +585,8 @@ static esp_err_t api_fan_config(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t s_fan_endpoints[] = { { .name = "fan.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get fan status", .category = TS_API_CAT_FAN, .handler = api_fan_status, @@ -552,52 +594,66 @@ static const ts_api_endpoint_t s_fan_endpoints[] = { }, { .name = "fan.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set fan speed (manual mode)", .category = TS_API_CAT_FAN, .handler = api_fan_set, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.mode", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set fan operating mode", .category = TS_API_CAT_FAN, .handler = api_fan_mode, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.enable", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Enable or disable a fan", .category = TS_API_CAT_FAN, .handler = api_fan_enable, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.limits", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set duty cycle limits (min/max)", .category = TS_API_CAT_FAN, .handler = api_fan_limits, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.curve", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set temperature curve for fan", .category = TS_API_CAT_FAN, .handler = api_fan_curve, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.save", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Save fan configuration to NVS", .category = TS_API_CAT_FAN, .handler = api_fan_save, - .requires_auth = false, + .requires_auth = true, }, { .name = "fan.config", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get fan configuration including curve", .category = TS_API_CAT_FAN, .handler = api_fan_config, - .requires_auth = false, + .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_gpio.c b/components/ts_api/src/ts_api_gpio.c index 40b0ada7..fb184cc0 100644 --- a/components/ts_api/src/ts_api_gpio.c +++ b/components/ts_api/src/ts_api_gpio.c @@ -269,20 +269,26 @@ static esp_err_t api_gpio_toggle(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t s_gpio_endpoints[] = { { .name = "gpio.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List all controllable GPIO pins", .category = TS_API_CAT_HAL, .handler = api_gpio_list, - .requires_auth = false + .requires_auth = true }, { .name = "gpio.info", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get GPIO pin info", .category = TS_API_CAT_HAL, .handler = api_gpio_info, - .requires_auth = false + .requires_auth = true }, { .name = "gpio.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set GPIO level", .category = TS_API_CAT_HAL, .handler = api_gpio_set, @@ -290,6 +296,8 @@ static const ts_api_endpoint_t s_gpio_endpoints[] = { }, { .name = "gpio.toggle", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Toggle GPIO level", .category = TS_API_CAT_HAL, .handler = api_gpio_toggle, diff --git a/components/ts_api/src/ts_api_hosts.c b/components/ts_api/src/ts_api_hosts.c index e81c372b..248320af 100644 --- a/components/ts_api/src/ts_api_hosts.c +++ b/components/ts_api/src/ts_api_hosts.c @@ -10,6 +10,7 @@ #include "ts_known_hosts.h" #include "ts_log.h" #include +#include #define TAG "api_hosts" @@ -26,7 +27,12 @@ static esp_err_t api_hosts_list(const cJSON *params, ts_api_result_t *result) TS_LOGI(TAG, "API: hosts.list called"); - ts_known_host_t hosts[32]; + /* Keep the bounded snapshot off the shared 8 KB HTTP task stack. */ + ts_known_host_t *hosts = malloc(32 * sizeof(*hosts)); + if (!hosts) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); + return ESP_ERR_NO_MEM; + } size_t count = 0; esp_err_t ret = ts_known_hosts_list(hosts, 32, &count); @@ -35,6 +41,7 @@ static esp_err_t api_hosts_list(const cJSON *params, ts_api_result_t *result) // 如果模块未初始化,返回空列表而不是错误 if (ret == ESP_ERR_INVALID_STATE) { + free(hosts); cJSON *data = cJSON_CreateObject(); cJSON_AddNumberToObject(data, "count", 0); cJSON_AddArrayToObject(data, "hosts"); @@ -43,12 +50,14 @@ static esp_err_t api_hosts_list(const cJSON *params, ts_api_result_t *result) } if (ret != ESP_OK) { + free(hosts); ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to list known hosts"); return ret; } cJSON *data = cJSON_CreateObject(); if (!data) { + free(hosts); ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } @@ -66,6 +75,7 @@ static esp_err_t api_hosts_list(const cJSON *params, ts_api_result_t *result) cJSON_AddItemToArray(hosts_array, item); } + free(hosts); ts_api_result_ok(result, data); return ESP_OK; } @@ -231,39 +241,39 @@ esp_err_t ts_api_hosts_register(void) { static const ts_api_endpoint_t endpoints[] = { { - .name = "hosts.list", + .name = "hosts.list", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "List all known SSH hosts", .category = TS_API_CAT_NETWORK, .handler = api_hosts_list, - .requires_auth = false, + .requires_auth=true, }, { - .name = "hosts.info", + .name = "hosts.info", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get known host info", .category = TS_API_CAT_NETWORK, .handler = api_hosts_info, - .requires_auth = false, + .requires_auth=true, }, { - .name = "hosts.remove", + .name = "hosts.remove", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Remove a known host", .category = TS_API_CAT_NETWORK, .handler = api_hosts_remove, - .requires_auth = true, + .requires_auth=true, }, { - .name = "hosts.update", + .name = "hosts.update", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Force update a host fingerprint", .category = TS_API_CAT_NETWORK, .handler = api_hosts_update, - .requires_auth = true, + .requires_auth=true, }, { - .name = "hosts.clear", + .name = "hosts.clear", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Clear all known hosts", .category = TS_API_CAT_NETWORK, .handler = api_hosts_clear, - .requires_auth = true, + .requires_auth=true, }, }; diff --git a/components/ts_api/src/ts_api_key.c b/components/ts_api/src/ts_api_key.c index a1838711..063f849e 100644 --- a/components/ts_api/src/ts_api_key.c +++ b/components/ts_api/src/ts_api_key.c @@ -8,6 +8,7 @@ #include "ts_api.h" #include "ts_keystore.h" +#include "ts_security.h" #include "ts_automation_config.h" #include "ts_ssh_service.h" #include "ts_log.h" @@ -39,15 +40,31 @@ static const char *key_type_desc(ts_keystore_key_type_t type) /** * @brief key.list - List all stored keys */ -static esp_err_t api_key_list(const cJSON *params, ts_api_result_t *result) +static cJSON *key_info_json(const ts_keystore_key_info_t *info, bool list_row) +{ + cJSON *data = cJSON_CreateObject(); + if (!data || !cJSON_AddStringToObject(data, "id", info->id) || + !cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info->type)) || + !cJSON_AddStringToObject(data, "type_desc", key_type_desc(info->type)) || + !cJSON_AddStringToObject(data, "comment", info->comment) || + !cJSON_AddStringToObject(data, "alias", info->alias) || + !cJSON_AddNumberToObject(data, "created", info->created_at) || + !cJSON_AddNumberToObject(data, "last_used", info->last_used) || + !cJSON_AddBoolToObject(data, list_row ? "has_pubkey" : "has_public_key", info->has_public_key) || + !cJSON_AddBoolToObject(data, "exportable", info->exportable) || + !cJSON_AddBoolToObject(data, "hidden", info->hidden)) { + cJSON_Delete(data); + return NULL; + } + return data; +} + +static esp_err_t api_key_list_impl(const cJSON *params, bool show_hidden, ts_api_result_t *result) { (void)params; TS_LOGI(TAG, "API: key.list called"); - /* 检查是否显示隐藏密钥(TODO: 从认证状态判断) */ - bool show_hidden = true; // 暂时默认显示全部,后续接入认证系统 - /* 使用 PSRAM 分配避免栈溢出 */ ts_keystore_key_info_t *keys = heap_caps_malloc( sizeof(ts_keystore_key_info_t) * TS_KEYSTORE_MAX_KEYS, @@ -65,17 +82,9 @@ static esp_err_t api_key_list(const cJSON *params, ts_api_result_t *result) TS_LOGI(TAG, "API: ts_keystore_list_keys_ex returned %s, count=%zu", esp_err_to_name(ret), count); - // 如果模块未初始化,返回空列表而不是错误 - if (ret == ESP_ERR_INVALID_STATE) { - free(keys); - cJSON *data = cJSON_CreateObject(); - cJSON_AddNumberToObject(data, "count", 0); - cJSON_AddNumberToObject(data, "max_keys", TS_KEYSTORE_MAX_KEYS); - cJSON_AddArrayToObject(data, "keys"); - ts_api_result_ok(result, data); - return ESP_OK; - } - + /* Preserve the empty view before the keystore service starts. */ + if (ret == ESP_ERR_INVALID_STATE) { ret = ESP_OK; count = 0; } + if (ret != ESP_OK) { free(keys); ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to list keys"); @@ -83,43 +92,22 @@ static esp_err_t api_key_list(const cJSON *params, ts_api_result_t *result) } cJSON *data = cJSON_CreateObject(); - if (!data) { - free(keys); - ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); - return ESP_ERR_NO_MEM; - } - - cJSON_AddNumberToObject(data, "count", count); - cJSON_AddNumberToObject(data, "max_keys", TS_KEYSTORE_MAX_KEYS); - - cJSON *keys_array = cJSON_AddArrayToObject(data, "keys"); - for (size_t i = 0; i < count; i++) { - cJSON *item = cJSON_CreateObject(); - - /* 如果是隐藏密钥且未授权,则掩码 ID */ - if (keys[i].hidden && !show_hidden) { - /* 掩码格式:🔒 或 🔒 Hidden Key */ - const char *display_id = (strlen(keys[i].alias) > 0) ? keys[i].alias : "Hidden Key"; - char masked_id[TS_KEYSTORE_ALIAS_MAX_LEN + 8]; - snprintf(masked_id, sizeof(masked_id), "🔒 %s", display_id); - cJSON_AddStringToObject(item, "id", masked_id); - } else { - cJSON_AddStringToObject(item, "id", keys[i].id); + cJSON *keys_array = data ? cJSON_AddArrayToObject(data, "keys") : NULL; + bool complete = keys_array && cJSON_AddNumberToObject(data, "count", count) && + cJSON_AddNumberToObject(data, "max_keys", TS_KEYSTORE_MAX_KEYS); + for (size_t i = 0; complete && i < count; ++i) { + cJSON *item = key_info_json(&keys[i], true); + if (!item || !cJSON_AddItemToArray(keys_array, item)) { + cJSON_Delete(item); + complete = false; } - - cJSON_AddStringToObject(item, "type", ts_keystore_type_to_string(keys[i].type)); - cJSON_AddStringToObject(item, "type_desc", key_type_desc(keys[i].type)); - cJSON_AddStringToObject(item, "comment", keys[i].comment); - cJSON_AddStringToObject(item, "alias", keys[i].alias); - cJSON_AddNumberToObject(item, "created", keys[i].created_at); - cJSON_AddNumberToObject(item, "last_used", keys[i].last_used); - cJSON_AddBoolToObject(item, "has_pubkey", keys[i].has_public_key); - cJSON_AddBoolToObject(item, "exportable", keys[i].exportable); - cJSON_AddBoolToObject(item, "hidden", keys[i].hidden); - cJSON_AddItemToArray(keys_array, item); } - free(keys); + if (!complete) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); + return ESP_ERR_NO_MEM; + } ts_api_result_ok(result, data); return ESP_OK; } @@ -129,7 +117,7 @@ static esp_err_t api_key_list(const cJSON *params, ts_api_result_t *result) * * @param params { "id": "key_id" } */ -static esp_err_t api_key_info(const cJSON *params, ts_api_result_t *result) +static esp_err_t api_key_info_impl(const cJSON *params, bool show_hidden, ts_api_result_t *result) { if (!params) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing parameters"); @@ -143,7 +131,7 @@ static esp_err_t api_key_info(const cJSON *params, ts_api_result_t *result) } ts_keystore_key_info_t info; - esp_err_t ret = ts_keystore_get_key_info(id->valuestring, &info); + esp_err_t ret = ts_keystore_read_public_record(id->valuestring, show_hidden, &info, NULL, NULL); if (ret == ESP_ERR_NOT_FOUND) { ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "Key not found"); @@ -153,23 +141,11 @@ static esp_err_t api_key_info(const cJSON *params, ts_api_result_t *result) return ret; } - cJSON *data = cJSON_CreateObject(); + cJSON *data = key_info_json(&info, false); if (!data) { ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - - cJSON_AddStringToObject(data, "id", info.id); - cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info.type)); - cJSON_AddStringToObject(data, "type_desc", key_type_desc(info.type)); - cJSON_AddStringToObject(data, "comment", info.comment); - cJSON_AddStringToObject(data, "alias", info.alias); - cJSON_AddNumberToObject(data, "created", info.created_at); - cJSON_AddNumberToObject(data, "last_used", info.last_used); - cJSON_AddBoolToObject(data, "has_public_key", info.has_public_key); - cJSON_AddBoolToObject(data, "exportable", info.exportable); - cJSON_AddBoolToObject(data, "hidden", info.hidden); - ts_api_result_ok(result, data); return ESP_OK; } @@ -254,7 +230,7 @@ static esp_err_t api_key_generate(const cJSON *params, ts_api_result_t *result) } ts_keystore_generate_result_t detail; esp_err_t ret = ts_keystore_generate_key_with_result(id->valuestring, type, &opts, &detail); - TS_LOGI(TAG, "key.generate request=%s storage id=%s ret=%s stage=%s stored=%d cleanup=%s", request_id, id->valuestring, + TS_LOGI(TAG, "key.generate request=%s storage ret=%s stage=%s stored=%d cleanup=%s", request_id, esp_err_to_name(ret), detail.failed_stage ? detail.failed_stage : "saved", detail.stored, esp_err_to_name(detail.cleanup_error)); if (ret != ESP_OK) { @@ -284,7 +260,7 @@ static esp_err_t api_key_generate(const cJSON *params, ts_api_result_t *result) !cJSON_AddStringToObject(data, "id", id->valuestring) || !cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(type))) { cJSON_Delete(data); - TS_LOGE(TAG, "key.generate request=%s saved id=%s but response allocation failed", request_id, id->valuestring); + TS_LOGE(TAG, "key.generate request=%s saved but response allocation failed", request_id); ts_api_result_error(result, TS_API_ERR_NO_MEM, "key_response_failed"); return ESP_ERR_NO_MEM; } @@ -376,7 +352,7 @@ static esp_err_t api_key_delete(const cJSON *params, ts_api_result_t *result) * @param params { "id": "key_id" } * @return Public key in OpenSSH format */ -static esp_err_t api_key_export(const cJSON *params, ts_api_result_t *result) +static esp_err_t api_key_export_impl(const cJSON *params, bool show_hidden, ts_api_result_t *result) { if (!params) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing parameters"); @@ -392,7 +368,8 @@ static esp_err_t api_key_export(const cJSON *params, ts_api_result_t *result) /* 加载公钥 */ char *pubkey = NULL; size_t pubkey_len = 0; - esp_err_t ret = ts_keystore_load_public_key(id->valuestring, &pubkey, &pubkey_len); + ts_keystore_key_info_t info; + esp_err_t ret = ts_keystore_read_public_record(id->valuestring, show_hidden, &info, &pubkey, &pubkey_len); if (ret == ESP_ERR_NOT_FOUND) { ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "Key not found"); @@ -402,18 +379,17 @@ static esp_err_t api_key_export(const cJSON *params, ts_api_result_t *result) return ret; } - /* 获取密钥信息 */ - ts_keystore_key_info_t info; - ts_keystore_get_key_info(id->valuestring, &info); - cJSON *data = cJSON_CreateObject(); - cJSON_AddStringToObject(data, "id", id->valuestring); - cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info.type)); - cJSON_AddStringToObject(data, "public_key", pubkey); - cJSON_AddStringToObject(data, "comment", info.comment); - + bool complete = data && cJSON_AddStringToObject(data, "id", info.id) && + cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info.type)) && + cJSON_AddStringToObject(data, "public_key", pubkey) && + cJSON_AddStringToObject(data, "comment", info.comment); free(pubkey); - + if (!complete) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); + return ESP_ERR_NO_MEM; + } ts_api_result_ok(result, data); return ESP_OK; } @@ -437,48 +413,34 @@ static esp_err_t api_key_export_private(const cJSON *params, ts_api_result_t *re return ESP_ERR_INVALID_ARG; } - /* 获取密钥信息,检查是否可导出 */ ts_keystore_key_info_t info; - esp_err_t ret = ts_keystore_get_key_info(id->valuestring, &info); - if (ret == ESP_ERR_NOT_FOUND) { - ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "Key not found"); - return ESP_ERR_NOT_FOUND; - } else if (ret != ESP_OK) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to get key info"); - return ret; - } - - /* 安全检查:只有 exportable=true 的密钥才能导出私钥 */ - if (!info.exportable) { - ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, - "Private key is not exportable. Generate key with --exportable flag to allow export."); - return ESP_ERR_NOT_ALLOWED; - } - - /* 加载私钥 */ char *privkey = NULL; size_t privkey_len = 0; - ret = ts_keystore_load_private_key(id->valuestring, &privkey, &privkey_len); - - if (ret == ESP_ERR_NOT_FOUND) { - ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "Private key not found"); - return ESP_ERR_NOT_FOUND; - } else if (ret != ESP_OK || !privkey) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "Failed to export private key"); + esp_err_t ret = ts_keystore_read_exportable_private_record(id->valuestring, &info, &privkey, &privkey_len); + if (ret == ESP_ERR_NOT_ALLOWED) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Private key is not exportable"); return ret; } - + if (ret != ESP_OK || !privkey) { + ts_api_result_error(result, ret == ESP_ERR_NOT_FOUND ? TS_API_ERR_NOT_FOUND : TS_API_ERR_INTERNAL, + ret == ESP_ERR_NOT_FOUND ? "Key not found" : "Failed to export private key"); + return ret == ESP_OK ? ESP_FAIL : ret; + } + cJSON *data = cJSON_CreateObject(); - cJSON_AddStringToObject(data, "id", id->valuestring); - cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info.type)); - cJSON_AddStringToObject(data, "private_key", privkey); - cJSON_AddStringToObject(data, "comment", info.comment); - - /* 安全警告 */ - cJSON_AddStringToObject(data, "warning", "Keep this private key secure! Never share it publicly."); - + bool complete = data && cJSON_AddStringToObject(data, "id", info.id) && + cJSON_AddStringToObject(data, "type", ts_keystore_type_to_string(info.type)) && + cJSON_AddStringToObject(data, "private_key", privkey) && + cJSON_AddStringToObject(data, "comment", info.comment) && + cJSON_AddStringToObject(data, "warning", "Keep this private key secure! Never share it publicly."); + volatile char *wipe = privkey; + for (size_t i = 0; i < privkey_len; ++i) wipe[i] = 0; free(privkey); - + if (!complete) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); + return ESP_ERR_NO_MEM; + } ts_api_result_ok(result, data); return ESP_OK; } @@ -487,25 +449,113 @@ static esp_err_t api_key_export_private(const cJSON *params, ts_api_result_t *re /* Registration */ /*===========================================================================*/ +static esp_err_t key_read_visibility(uint32_t session_id, bool *show_hidden, + ts_api_result_t *result) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + ts_session_t caller; + if (ts_security_validate_session(session_id, &caller) != ESP_OK || caller.level < TS_PERM_READ) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } + *show_hidden = caller.level >= TS_PERM_ADMIN; +#else + (void)session_id; (void)result; + *show_hidden = true; +#endif + return ESP_OK; +} + +static esp_err_t api_key_list(const cJSON *params, ts_api_result_t *result) +{ + return api_key_list_impl(params, true, result); +} + +typedef esp_err_t (*key_read_handler_t)(const cJSON *, bool, ts_api_result_t *); +static esp_err_t key_read_for_session(const cJSON *params, uint32_t session_id, + bool administrator_only, key_read_handler_t handler, ts_api_result_t *result) +{ + bool show_hidden; + esp_err_t ret = key_read_visibility(session_id, &show_hidden, result); + if (ret != ESP_OK) return ret; + if (administrator_only && !show_hidden) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Administrator permission required"); + return ESP_ERR_NOT_ALLOWED; + } + ret = handler(params, show_hidden, result); + if (ret != ESP_OK || result->code != TS_API_OK) return ret; + bool still_hidden; + ret = key_read_visibility(session_id, &still_hidden, result); + if (ret == ESP_OK && still_hidden != show_hidden) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Key read permission changed"); + ret = ESP_ERR_NOT_ALLOWED; + } + return ret; +} + +static esp_err_t private_export_read(const cJSON *params, bool show_hidden, ts_api_result_t *result) +{ + (void)show_hidden; + return api_key_export_private(params, result); +} + +static esp_err_t api_key_info(const cJSON *params, ts_api_result_t *result) +{ + return api_key_info_impl(params, true, result); +} + +static esp_err_t api_key_export(const cJSON *params, ts_api_result_t *result) +{ + return api_key_export_impl(params, true, result); +} + +static esp_err_t api_key_list_for_session(const cJSON *params, uint32_t session_id, ts_api_result_t *result) +{ + return key_read_for_session(params, session_id, false, api_key_list_impl, result); +} + +static esp_err_t api_key_info_for_session(const cJSON *params, uint32_t session_id, ts_api_result_t *result) +{ + return key_read_for_session(params, session_id, false, api_key_info_impl, result); +} + +static esp_err_t api_key_export_for_session(const cJSON *params, uint32_t session_id, ts_api_result_t *result) +{ + return key_read_for_session(params, session_id, false, api_key_export_impl, result); +} + +static esp_err_t api_key_export_private_for_session(const cJSON *params, uint32_t session_id, ts_api_result_t *result) +{ + return key_read_for_session(params, session_id, true, private_export_read, result); +} + esp_err_t ts_api_key_register(void) { static const ts_api_endpoint_t endpoints[] = { { .name = "key.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List all stored keys", .category = TS_API_CAT_SYSTEM, .handler = api_key_list, + .session_handler = api_key_list_for_session, .requires_auth = false, }, { .name = "key.info", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get key info", .category = TS_API_CAT_SYSTEM, .handler = api_key_info, + .session_handler = api_key_info_for_session, .requires_auth = false, }, { .name = "key.generate", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Generate a new key", .category = TS_API_CAT_SYSTEM, .handler = api_key_generate, @@ -513,6 +563,8 @@ esp_err_t ts_api_key_register(void) }, { .name = "key.delete", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Delete a key", .category = TS_API_CAT_SYSTEM, .handler = api_key_delete, @@ -520,16 +572,22 @@ esp_err_t ts_api_key_register(void) }, { .name = "key.export", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Export public key", .category = TS_API_CAT_SYSTEM, .handler = api_key_export, + .session_handler = api_key_export_for_session, .requires_auth = false, }, { .name = "key.exportPrivate", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Export private key (only for exportable keys)", .category = TS_API_CAT_SYSTEM, .handler = api_key_export_private, + .session_handler = api_key_export_private_for_session, .requires_auth = true, /* 导出私钥需要认证 */ }, }; diff --git a/components/ts_api/src/ts_api_led.c b/components/ts_api/src/ts_api_led.c index 44313123..fd00ef85 100644 --- a/components/ts_api/src/ts_api_led.c +++ b/components/ts_api/src/ts_api_led.c @@ -17,7 +17,10 @@ #include "ts_led_font.h" #include "ts_led_effect.h" #include "ts_led_color_correction.h" +#include "ts_storage.h" +#include "ts_security.h" #include +#include #define TAG "api_led" @@ -168,7 +171,13 @@ static esp_err_t api_led_brightness(const cJSON *params, ts_api_result_t *result } // If brightness is provided, set it; otherwise return current value - if (brightness_param && cJSON_IsNumber(brightness_param)) { + if (brightness_param) { + if (!cJSON_IsNumber(brightness_param) || !isfinite(brightness_param->valuedouble) || + brightness_param->valuedouble < 0 || brightness_param->valuedouble > 255 || + floor(brightness_param->valuedouble) != brightness_param->valuedouble) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid brightness (integer 0-255)"); + return ESP_ERR_INVALID_ARG; + } uint8_t brightness = (uint8_t)cJSON_GetNumberValue(brightness_param); esp_err_t ret = ts_led_device_set_brightness(dev, brightness); if (ret != ESP_OK) { @@ -232,7 +241,7 @@ static esp_err_t api_led_clear(const cJSON *params, ts_api_result_t *result) } /** - * @brief led.set - Set LED(s) color + * @brief led.set - Set a validated LED pixel range * @param device: device name * @param index: LED index or start index * @param count: number of LEDs (optional, default 1) @@ -1526,7 +1535,13 @@ static esp_err_t api_led_cc_export(const cJSON *params, ts_api_result_t *result) path = path_param->valuestring; } - esp_err_t ret = ts_led_cc_save_to_sdcard(path); + esp_err_t ret = ts_storage_check_external_write_path(path ? path : TS_LED_CC_SDCARD_JSON_PATH, false); + if (ret != ESP_OK) { + ts_api_result_error(result, ret == ESP_ERR_NOT_ALLOWED ? TS_API_ERR_NO_PERMISSION : TS_API_ERR_INVALID_ARG, + ret == ESP_ERR_NOT_ALLOWED ? "automation_configuration_managed" : "storage_path_invalid"); + return ret; + } + ret = ts_led_cc_save_to_sdcard(path); if (ret != ESP_OK) { ts_api_result_error(result, ret == ESP_ERR_NOT_ALLOWED ? TS_API_ERR_NO_PERMISSION : TS_API_ERR_INTERNAL, ret == ESP_ERR_NOT_ALLOWED ? "automation_configuration_managed" : "Failed to export configuration"); @@ -1571,6 +1586,56 @@ static esp_err_t api_led_cc_import(const cJSON *params, ts_api_result_t *result) return ESP_OK; } +/* File consumers use the same private path classification as generic reads. + * Check before touching LED state; never infer identity from request JSON. */ +static esp_err_t led_read_for_session(const cJSON *params, uint32_t session_id, + ts_api_handler_t handler, const char *key, + const char *fallback, ts_api_result_t *result) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + ts_session_t session; + if (ts_security_validate_session(session_id, &session) != ESP_OK || session.level < TS_PERM_ADMIN) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } +#else + (void)session_id; +#endif + const cJSON *item = cJSON_GetObjectItem(params, key); + const char *path = cJSON_IsString(item) ? item->valuestring : fallback; + if (!path || !path[0]) return handler(params, result); + bool needs_admin; + esp_err_t ret = ts_storage_external_read_requires_admin(path, &needs_admin); + if (ret != ESP_OK) { + ts_api_result_error(result, ret == ESP_ERR_INVALID_ARG ? TS_API_ERR_INVALID_ARG : TS_API_ERR_INTERNAL, + ret == ESP_ERR_INVALID_ARG ? "storage_path_invalid" : "storage_read_failed"); + return ret; + } +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (ts_security_validate_session(session_id, &session) != ESP_OK || session.level < TS_PERM_ADMIN) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } + if (needs_admin && session.level < TS_PERM_ADMIN) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Administrator permission required"); + return ESP_ERR_NOT_ALLOWED; + } +#endif + return handler(params, result); +} +static esp_err_t led_image_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return led_read_for_session(params, session, api_led_image, "path", NULL, result); +} +static esp_err_t led_qrcode_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return led_read_for_session(params, session, api_led_qrcode, "bg_image", NULL, result); +} +static esp_err_t led_cc_import_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return led_read_for_session(params, session, api_led_cc_import, "path", TS_LED_CC_SDCARD_JSON_PATH, result); +} + /*===========================================================================*/ /* Registration */ /*===========================================================================*/ @@ -1578,6 +1643,8 @@ static esp_err_t api_led_cc_import(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t led_endpoints[] = { { .name = "led.list", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "List LED devices", .category = TS_API_CAT_LED, .handler = api_led_list, @@ -1585,181 +1652,230 @@ static const ts_api_endpoint_t led_endpoints[] = { }, { .name = "led.brightness", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Get/set device brightness", .category = TS_API_CAT_LED, .handler = api_led_brightness, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.clear", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Clear all LEDs on device", .category = TS_API_CAT_LED, .handler = api_led_clear, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.set", - .description = "Set LED(s) color", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, + .description = "Legacy individual pixel setting (unsupported)", .category = TS_API_CAT_LED, .handler = api_led_set, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.fill", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Fill all LEDs with color", .category = TS_API_CAT_LED, .handler = api_led_fill, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.effect.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List available effects", .category = TS_API_CAT_LED, .handler = api_led_effect_list, - .requires_auth = false, + .requires_auth = true, }, { .name = "led.effect.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Start effect on device", .category = TS_API_CAT_LED, .handler = api_led_effect_start, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.effect.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop effect on device", .category = TS_API_CAT_LED, .handler = api_led_effect_stop, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.control", }, { .name = "led.color.parse", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Parse color string to RGB", .category = TS_API_CAT_LED, .handler = api_led_color_parse, - .requires_auth = false, + .requires_auth = true, }, { .name = "led.color.hsv", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Convert HSV to RGB", .category = TS_API_CAT_LED, .handler = api_led_color_hsv, - .requires_auth = false, + .requires_auth = true, }, { .name = "led.filter.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List available post-processing filters", .category = TS_API_CAT_LED, .handler = api_led_filter_list, - .requires_auth = false, + .requires_auth = true, }, { .name = "led.filter.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Apply post-processing filter", .category = TS_API_CAT_LED, .handler = api_led_filter_start, - .requires_auth = false, + .requires_auth = true, .permission = "led.control", }, { .name = "led.filter.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop post-processing filter", .category = TS_API_CAT_LED, .handler = api_led_filter_stop, - .requires_auth = false, + .requires_auth = true, .permission = "led.control", }, { .name = "led.image", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Display image on matrix", .category = TS_API_CAT_LED, .handler = api_led_image, - .requires_auth = false, + .session_handler = led_image_for_session, + .requires_auth = true, .permission = "led.control", }, { .name = "led.qrcode", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Generate and display QR code", .category = TS_API_CAT_LED, .handler = api_led_qrcode, - .requires_auth = false, + .session_handler = led_qrcode_for_session, + .requires_auth = true, .permission = "led.control", }, { .name = "led.text", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Display text on matrix", .category = TS_API_CAT_LED, .handler = api_led_text, - .requires_auth = false, + .requires_auth = true, .permission = "led.control", }, { .name = "led.text.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop text overlay", .category = TS_API_CAT_LED, .handler = api_led_text_stop, - .requires_auth = false, + .requires_auth = true, .permission = "led.control", }, { .name = "led.save", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Save current state as boot configuration", .category = TS_API_CAT_LED, .handler = api_led_save, - .requires_auth = false, // TODO: 测试完成后改为 true + .requires_auth = true, // TODO: 测试完成后改为 true .permission = "led.config", }, { .name = "led.boot.config", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get LED boot configuration", .category = TS_API_CAT_LED, .handler = api_led_boot_config, - .requires_auth = false, + .requires_auth = true, }, /* Color Correction APIs */ { .name = "led.color_correction.get", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get color correction configuration", .category = TS_API_CAT_LED, .handler = api_led_cc_get, - .requires_auth = false, + .requires_auth = true, }, { .name = "led.color_correction.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set color correction configuration", .category = TS_API_CAT_LED, .handler = api_led_cc_set, - .requires_auth = false, + .requires_auth = true, .permission = "led.config", }, { .name = "led.color_correction.reset", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Reset color correction to defaults", .category = TS_API_CAT_LED, .handler = api_led_cc_reset, - .requires_auth = false, + .requires_auth = true, .permission = "led.config", }, { .name = "led.color_correction.export", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Export color correction config to SD card", .category = TS_API_CAT_LED, .handler = api_led_cc_export, - .requires_auth = false, + .requires_auth = true, .permission = "led.config", }, { .name = "led.color_correction.import", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Import color correction config from SD card", .category = TS_API_CAT_LED, .handler = api_led_cc_import, - .requires_auth = false, + .session_handler = led_cc_import_for_session, + .requires_auth = true, .permission = "led.config", }, }; diff --git a/components/ts_api/src/ts_api_log.c b/components/ts_api/src/ts_api_log.c index 2812edbb..574308e1 100644 --- a/components/ts_api/src/ts_api_log.c +++ b/components/ts_api/src/ts_api_log.c @@ -282,20 +282,26 @@ void ts_api_log_register(void) static const ts_api_endpoint_t endpoints[] = { { .name = "log.list", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_log_list, .description = "Get log entries with filtering", - .requires_auth = false, + .requires_auth = true, }, { .name = "log.stats", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_log_stats, .description = "Get log system statistics", - .requires_auth = false, + .requires_auth = true, }, { .name = "log.clear", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_log_clear, .description = "Clear log buffer", @@ -303,6 +309,8 @@ void ts_api_log_register(void) }, { .name = "log.setLevel", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_log_set_level, .description = "Set log level", @@ -310,6 +318,8 @@ void ts_api_log_register(void) }, { .name = "log.capture", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_log_capture, .description = "Enable/disable ESP_LOG capture", diff --git a/components/ts_api/src/ts_api_lpmu_access.c b/components/ts_api/src/ts_api_lpmu_access.c index 21b785d7..33847e3c 100644 --- a/components/ts_api/src/ts_api_lpmu_access.c +++ b/components/ts_api/src/ts_api_lpmu_access.c @@ -748,27 +748,27 @@ static esp_err_t api_lpmu_access_log(const cJSON *params, ts_api_result_t *resul static const ts_api_endpoint_t lpmu_access_endpoints[] = { { - .name = "network.lpmu_access.start", + .name = "network.lpmu_access.start", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Start application computer upstream-network access setup", .category = TS_API_CAT_NETWORK, .handler = api_lpmu_access_start, - .requires_auth = true, + .requires_auth=true, .permission = "network.config", }, { - .name = "network.lpmu_access.status", + .name = "network.lpmu_access.status", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_READ, .description = "Get application computer upstream-network access setup status", .category = TS_API_CAT_NETWORK, .handler = api_lpmu_access_status, - .requires_auth = true, + .requires_auth=true, .permission = "network.view", }, { - .name = "network.lpmu_access.log", + .name = "network.lpmu_access.log", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_READ, .description = "Get the execution log for an application computer network access run", .category = TS_API_CAT_NETWORK, .handler = api_lpmu_access_log, - .requires_auth = true, + .requires_auth=true, .permission = "network.view", }, }; diff --git a/components/ts_api/src/ts_api_monitor.c b/components/ts_api/src/ts_api_monitor.c index 048c0d45..8743432b 100644 --- a/components/ts_api/src/ts_api_monitor.c +++ b/components/ts_api/src/ts_api_monitor.c @@ -266,46 +266,46 @@ esp_err_t ts_api_monitor_register(void) static const ts_api_endpoint_t endpoints[] = { { - .name = "monitor.status", + .name = "monitor.status", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get Compute monitor status", .category = TS_API_CAT_DEVICE, .handler = api_monitor_status, - .requires_auth = false, + .requires_auth=true, }, { - .name = "monitor.data", + .name = "monitor.data", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get latest Compute telemetry data", .category = TS_API_CAT_DEVICE, .handler = api_monitor_data, - .requires_auth = false, + .requires_auth=true, }, { - .name = "monitor.config", + .name = "monitor.config", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get Compute monitor configuration", .category = TS_API_CAT_DEVICE, .handler = api_monitor_config, - .requires_auth = false, + .requires_auth=true, }, { - .name = "monitor.set_server", + .name = "monitor.set_server", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Set compute monitoring server IP and port", .category = TS_API_CAT_DEVICE, .handler = api_monitor_set_server, - .requires_auth = true, + .requires_auth=true, }, { - .name = "monitor.start", + .name = "monitor.start", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Start Compute monitoring", .category = TS_API_CAT_DEVICE, .handler = api_monitor_start, - .requires_auth = true, + .requires_auth=true, }, { - .name = "monitor.stop", + .name = "monitor.stop", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Stop Compute monitoring", .category = TS_API_CAT_DEVICE, .handler = api_monitor_stop, - .requires_auth = true, + .requires_auth=true, }, }; diff --git a/components/ts_api/src/ts_api_nat.c b/components/ts_api/src/ts_api_nat.c index db47466d..f571e650 100644 --- a/components/ts_api/src/ts_api_nat.c +++ b/components/ts_api/src/ts_api_nat.c @@ -124,13 +124,17 @@ esp_err_t ts_api_nat_register(void) static const ts_api_endpoint_t endpoints[] = { { .name = "nat.status", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get NAT gateway status", .category = TS_API_CAT_NETWORK, .handler = api_nat_status, - .requires_auth = false, + .requires_auth = true, }, { .name = "nat.enable", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Enable NAT gateway", .category = TS_API_CAT_NETWORK, .handler = api_nat_enable, @@ -138,6 +142,8 @@ esp_err_t ts_api_nat_register(void) }, { .name = "nat.disable", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Disable NAT gateway", .category = TS_API_CAT_NETWORK, .handler = api_nat_disable, @@ -145,6 +151,8 @@ esp_err_t ts_api_nat_register(void) }, { .name = "nat.save", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Save NAT configuration", .category = TS_API_CAT_NETWORK, .handler = api_nat_save, diff --git a/components/ts_api/src/ts_api_network.c b/components/ts_api/src/ts_api_network.c index 2aa080a3..257e4aff 100644 --- a/components/ts_api/src/ts_api_network.c +++ b/components/ts_api/src/ts_api_network.c @@ -99,6 +99,7 @@ static esp_err_t api_network_status(const cJSON *params, ts_api_result_t *result cJSON *data = cJSON_CreateObject(); cJSON_AddStringToObject(data, "hostname", ts_net_get_hostname()); + cJSON_AddStringToObject(data, "wifi_mode", wifi_mode_to_str(ts_wifi_get_mode())); // Ethernet status cJSON *eth = cJSON_AddObjectToObject(data, "ethernet"); @@ -484,6 +485,8 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Get overall network status", .category = TS_API_CAT_NETWORK, .handler = api_network_status, + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .requires_auth = false, }, { @@ -491,6 +494,8 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Get/set WiFi mode", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_mode, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "network.config", }, @@ -499,13 +504,17 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Scan for WiFi networks", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_scan, - .requires_auth = false, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, + .requires_auth = true, }, { .name = "network.wifi.connect", .description = "Connect to WiFi network", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_connect, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "network.config", }, @@ -514,6 +523,8 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Disconnect from WiFi", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_disconnect, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "network.config", }, @@ -522,6 +533,8 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Configure WiFi AP", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_ap_config, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "network.config", }, @@ -530,13 +543,17 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Get connected AP stations", .category = TS_API_CAT_NETWORK, .handler = api_network_wifi_ap_stations, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, }, { .name = "network.eth.status", .description = "Get Ethernet status", .category = TS_API_CAT_NETWORK, .handler = api_network_eth_status, + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .requires_auth = false, }, { @@ -544,6 +561,8 @@ static const ts_api_endpoint_t network_endpoints[] = { .description = "Get/set hostname", .category = TS_API_CAT_NETWORK, .handler = api_network_hostname, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, .permission = "network.config", }, diff --git a/components/ts_api/src/ts_api_ota.c b/components/ts_api/src/ts_api_ota.c index e5920a08..46f14571 100644 --- a/components/ts_api/src/ts_api_ota.c +++ b/components/ts_api/src/ts_api_ota.c @@ -7,17 +7,21 @@ */ #include +#include +#include +#include "ts_http_fetch.h" +#include "ts_http_url.h" #include "esp_log.h" #include "esp_timer.h" #include "cJSON.h" #include "ts_api.h" #include "ts_ota.h" +#include "ts_security.h" #include "nvs_flash.h" #include "nvs.h" -#include "lwip/netdb.h" -#include "lwip/sockets.h" static const char *TAG = "ts_api_ota"; +static atomic_flag s_ota_probe_busy = ATOMIC_FLAG_INIT; // NVS 存储键 #define NVS_NAMESPACE_OTA "ota_config" @@ -93,15 +97,16 @@ static esp_err_t save_ota_server_config(void) static esp_err_t api_ota_server_get(const cJSON *params, ts_api_result_t *result) { (void)params; - + cJSON *json = cJSON_CreateObject(); - if (!json) { + if (!json || !cJSON_AddStringToObject(json, "url", s_ota_server_url) || + !cJSON_AddBoolToObject(json, "configured", s_ota_server_url[0] != '\0')) { + cJSON_Delete(json); ts_api_result_error(result, TS_API_ERR_NO_MEM, "内存不足"); return ESP_ERR_NO_MEM; } - cJSON_AddStringToObject(json, "url", s_ota_server_url); - + ts_api_result_ok(result, json); return ESP_OK; } @@ -125,7 +130,7 @@ static esp_err_t api_ota_server_set(const cJSON *params, ts_api_result_t *result // URL 可以是空字符串(表示清除) const char *url = cJSON_IsString(url_item) ? url_item->valuestring : ""; - + // 验证 URL 长度 if (strlen(url) >= sizeof(s_ota_server_url)) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "URL 过长"); @@ -136,7 +141,7 @@ static esp_err_t api_ota_server_set(const cJSON *params, ts_api_result_t *result strncpy(s_ota_server_url, url, sizeof(s_ota_server_url) - 1); s_ota_server_url[sizeof(s_ota_server_url) - 1] = '\0'; - ESP_LOGI(TAG, "OTA server URL set to: %s", s_ota_server_url[0] ? s_ota_server_url : "(empty)"); + ESP_LOGI(TAG, "OTA server configuration updated (configured=%d)", s_ota_server_url[0] != 0); // 检查是否需要持久化 cJSON *save_item = cJSON_GetObjectItem(params, "save"); @@ -154,7 +159,7 @@ static esp_err_t api_ota_server_set(const cJSON *params, ts_api_result_t *result cJSON *json = cJSON_CreateObject(); cJSON_AddStringToObject(json, "url", s_ota_server_url); cJSON_AddBoolToObject(json, "saved", do_save); - + ts_api_result_ok(result, json); return ESP_OK; } @@ -265,7 +270,7 @@ static esp_err_t api_ota_progress(const cJSON *params, ts_api_result_t *result) cJSON_AddNumberToObject(json, "percent", progress.progress_percent); cJSON_AddNumberToObject(json, "total_size", progress.total_size); cJSON_AddNumberToObject(json, "received_size", progress.received_size); - cJSON_AddStringToObject(json, "message", progress.status_msg ? progress.status_msg : ""); + cJSON_AddStringToObject(json, "message", progress.status_msg); ts_api_result_ok(result, json); return ESP_OK; @@ -306,51 +311,73 @@ static esp_err_t api_ota_version(const cJSON *params, ts_api_result_t *result) * @brief Get partition information * API: ota.partitions */ +static bool ota_partition_json(cJSON *json, const char *name, const ts_ota_partition_info_t *info) +{ + cJSON *node = cJSON_AddObjectToObject(json, name); + bool complete = node && cJSON_AddStringToObject(node, "label", info->label) && + cJSON_AddNumberToObject(node, "address", info->address) && + cJSON_AddNumberToObject(node, "size", info->size) && + cJSON_AddBoolToObject(node, "is_bootable", info->is_bootable); + if (complete && info->is_bootable) complete = + cJSON_AddStringToObject(node, "version", info->version.version) && + cJSON_AddStringToObject(node, "project", info->version.project_name); + return complete; +} + + static esp_err_t api_ota_partitions(const cJSON *params, ts_api_result_t *result) { - ts_ota_partition_info_t running, next; - + (void)params; + ts_ota_partition_info_t running = {0}, next = {0}; esp_err_t ret = ts_ota_get_running_partition_info(&running); + if (ret == ESP_OK) ret = ts_ota_get_next_partition_info(&next); if (ret != ESP_OK) { - ts_api_result_error(result, TS_API_ERR_INTERNAL, "获取分区信息失败"); + ts_api_result_error(result, TS_API_ERR_INTERNAL, "Partition information unavailable"); return ret; } - - ts_ota_get_next_partition_info(&next); - cJSON *json = cJSON_CreateObject(); - if (!json) { - ts_api_result_error(result, TS_API_ERR_NO_MEM, "内存不足"); + bool complete = json && ota_partition_json(json, "running", &running) && + ota_partition_json(json, "next", &next) && + cJSON_AddBoolToObject(json, "can_rollback", ts_ota_can_rollback()); + if (!complete) { + cJSON_Delete(json); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); return ESP_ERR_NO_MEM; } + ts_api_result_ok(result, json); + return ESP_OK; +} - // Running partition - cJSON *running_json = cJSON_AddObjectToObject(json, "running"); - cJSON_AddStringToObject(running_json, "label", running.label); - cJSON_AddNumberToObject(running_json, "address", running.address); - cJSON_AddNumberToObject(running_json, "size", running.size); - cJSON_AddBoolToObject(running_json, "is_bootable", running.is_bootable); - if (running.is_bootable) { - cJSON_AddStringToObject(running_json, "version", running.version.version); - cJSON_AddStringToObject(running_json, "project", running.version.project_name); - } +/* Reboot confirmation must survive the RAM session it is confirming. Keep + * complete partition management data behind READ; only running identity is public. */ +static esp_err_t api_ota_partitions_for_session(const cJSON *params, uint32_t session_id, + ts_api_result_t *result) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (ts_security_check_permission(session_id, TS_PERM_READ)) + return api_ota_partitions(params, result); - // Next partition - cJSON *next_json = cJSON_AddObjectToObject(json, "next"); - cJSON_AddStringToObject(next_json, "label", next.label); - cJSON_AddNumberToObject(next_json, "address", next.address); - cJSON_AddNumberToObject(next_json, "size", next.size); - cJSON_AddBoolToObject(next_json, "is_bootable", next.is_bootable); - if (next.is_bootable) { - cJSON_AddStringToObject(next_json, "version", next.version.version); - cJSON_AddStringToObject(next_json, "project", next.version.project_name); + ts_ota_partition_info_t running = {0}; + esp_err_t ret = ts_ota_get_running_partition_info(&running); + if (ret != ESP_OK) { + ts_api_result_error(result, TS_API_ERR_INTERNAL, "Partition information unavailable"); + return ret; + } + cJSON *json = cJSON_CreateObject(); + cJSON *identity = json ? cJSON_AddObjectToObject(json, "running") : NULL; + if (!identity || !cJSON_AddStringToObject(identity, "label", running.label) || + !cJSON_AddStringToObject(identity, "version", running.version.version) || + !cJSON_AddStringToObject(identity, "project", running.version.project_name)) { + cJSON_Delete(json); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; } - - // Check if rollback is possible - cJSON_AddBoolToObject(json, "can_rollback", ts_ota_can_rollback()); - ts_api_result_ok(result, json); return ESP_OK; +#else + (void)session_id; + return api_ota_partitions(params, result); +#endif } /** @@ -371,6 +398,12 @@ static esp_err_t api_ota_start_url(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } + struct http_parser_url parsed; + if (strnlen(url_item->valuestring, 2049) > 2048 || !ts_http_url_parse(url_item->valuestring, &parsed)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid HTTP or HTTPS URL"); + return ESP_ERR_INVALID_ARG; + } + ts_ota_config_t config = { .source = TS_OTA_SOURCE_HTTPS, .url = url_item->valuestring, @@ -558,7 +591,9 @@ static esp_err_t api_ota_upload_begin(const cJSON *params, ts_api_result_t *resu } cJSON *size_item = cJSON_GetObjectItem(params, "size"); - if (!size_item || !cJSON_IsNumber(size_item)) { + if (!cJSON_IsNumber(size_item) || !isfinite(size_item->valuedouble) || + size_item->valuedouble <= 0 || size_item->valuedouble > UINT32_MAX || + floor(size_item->valuedouble) != size_item->valuedouble) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "缺少 size 参数"); return ESP_ERR_INVALID_ARG; } @@ -654,6 +689,10 @@ static esp_err_t api_ota_www_start(const cJSON *params, ts_api_result_t *result) cJSON *url_item = cJSON_GetObjectItem(params, "url"); char url[300] = {0}; + if (url_item && cJSON_IsString(url_item) && strlen(url_item->valuestring) >= sizeof(url)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "URL too long"); + return ESP_ERR_INVALID_ARG; + } if (url_item && cJSON_IsString(url_item) && url_item->valuestring[0]) { strncpy(url, url_item->valuestring, sizeof(url) - 1); } else if (s_ota_server_url[0]) { @@ -741,7 +780,7 @@ static esp_err_t api_ota_www_progress(const cJSON *params, ts_api_result_t *resu cJSON_AddNumberToObject(json, "received", progress.received_size); cJSON_AddNumberToObject(json, "total", progress.total_size); cJSON_AddNumberToObject(json, "percent", progress.progress_percent); - cJSON_AddStringToObject(json, "message", progress.status_msg ? progress.status_msg : ""); + cJSON_AddStringToObject(json, "message", progress.status_msg); cJSON_AddBoolToObject(json, "running", ts_ota_www_is_running()); ts_api_result_ok(result, json); @@ -817,172 +856,66 @@ static esp_err_t api_ota_www_start_sdcard(const cJSON *params, ts_api_result_t * * * 此 API 从 ESP32 设备测试到 OTA 服务器的连接 */ -static esp_err_t api_ota_test_connection(const cJSON *params, ts_api_result_t *result) +static esp_err_t ota_test_connection_impl(const cJSON *params, ts_api_result_t *result) { - if (!params) { - ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "缺少参数"); + const cJSON *item = cJSON_GetObjectItemCaseSensitive(params, "url"); + struct http_parser_url parsed; + if (!cJSON_IsString(item) || !ts_http_url_parse(item->valuestring, &parsed) || + parsed.field_data[UF_HOST].len >= 256) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid HTTP or HTTPS URL"); return ESP_ERR_INVALID_ARG; } - - cJSON *url_item = cJSON_GetObjectItem(params, "url"); - if (!url_item || !cJSON_IsString(url_item) || !url_item->valuestring[0]) { - ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "缺少 url 参数"); - return ESP_ERR_INVALID_ARG; - } - - const char *url = url_item->valuestring; - ESP_LOGI(TAG, "Testing connection to: %s", url); - - cJSON *json = cJSON_CreateObject(); - cJSON_AddStringToObject(json, "url", url); - - // 解析 URL 获取主机名 - const char *host_start = strstr(url, "://"); - if (!host_start) { - ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "URL 格式无效"); - cJSON_Delete(json); - return ESP_ERR_INVALID_ARG; - } - host_start += 3; - - char host[128] = {0}; - char port_str[8] = "80"; - const char *port_pos = strchr(host_start, ':'); - const char *path_pos = strchr(host_start, '/'); - - if (port_pos && (!path_pos || port_pos < path_pos)) { - // 有端口号 - size_t host_len = port_pos - host_start; - if (host_len >= sizeof(host)) host_len = sizeof(host) - 1; - strncpy(host, host_start, host_len); - - const char *port_end = path_pos ? path_pos : port_pos + strlen(port_pos); - size_t port_len = port_end - (port_pos + 1); - if (port_len >= sizeof(port_str)) port_len = sizeof(port_str) - 1; - strncpy(port_str, port_pos + 1, port_len); - } else if (path_pos) { - size_t host_len = path_pos - host_start; - if (host_len >= sizeof(host)) host_len = sizeof(host) - 1; - strncpy(host, host_start, host_len); - } else { - strncpy(host, host_start, sizeof(host) - 1); - } - - cJSON_AddStringToObject(json, "host", host); - cJSON_AddStringToObject(json, "port", port_str); - - // DNS 解析测试 - struct addrinfo hints = { - .ai_family = AF_INET, - .ai_socktype = SOCK_STREAM, - }; - struct addrinfo *res = NULL; - - int64_t dns_start = esp_timer_get_time(); - int dns_err = getaddrinfo(host, port_str, &hints, &res); - int64_t dns_time = (esp_timer_get_time() - dns_start) / 1000; // ms - - cJSON_AddNumberToObject(json, "dns_time_ms", dns_time); - - if (dns_err != 0 || res == NULL) { - cJSON_AddBoolToObject(json, "dns_ok", false); - cJSON_AddStringToObject(json, "dns_error", "DNS 解析失败"); - ESP_LOGE(TAG, "DNS lookup failed for %s: %d", host, dns_err); - ts_api_result_ok(result, json); - return ESP_OK; - } - - struct sockaddr_in *addr = (struct sockaddr_in *)res->ai_addr; - char ip_str[16]; - inet_ntoa_r(addr->sin_addr, ip_str, sizeof(ip_str)); - cJSON_AddBoolToObject(json, "dns_ok", true); - cJSON_AddStringToObject(json, "resolved_ip", ip_str); - ESP_LOGI(TAG, "DNS resolved %s -> %s", host, ip_str); - - // TCP 连接测试 - int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (sock < 0) { - freeaddrinfo(res); - cJSON_AddBoolToObject(json, "tcp_ok", false); - cJSON_AddStringToObject(json, "tcp_error", "创建 socket 失败"); - ts_api_result_ok(result, json); - return ESP_OK; - } - - // 设置超时 - struct timeval tv = { - .tv_sec = 5, - .tv_usec = 0, - }; - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); - - int64_t tcp_start = esp_timer_get_time(); - int conn_err = connect(sock, res->ai_addr, res->ai_addrlen); - int64_t tcp_time = (esp_timer_get_time() - tcp_start) / 1000; // ms - - freeaddrinfo(res); - cJSON_AddNumberToObject(json, "tcp_time_ms", tcp_time); - - if (conn_err != 0) { - close(sock); - cJSON_AddBoolToObject(json, "tcp_ok", false); - cJSON_AddStringToObject(json, "tcp_error", "TCP 连接失败"); - ESP_LOGE(TAG, "TCP connect failed to %s:%s", host, port_str); - ts_api_result_ok(result, json); - return ESP_OK; + cJSON *data = cJSON_CreateObject(); + if (!data) { + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Insufficient device memory"); + return ESP_ERR_NO_MEM; } - - cJSON_AddBoolToObject(json, "tcp_ok", true); - ESP_LOGI(TAG, "TCP connection successful to %s:%s in %lld ms", host, port_str, tcp_time); - - // HTTP 请求测试 - char request[512]; - snprintf(request, sizeof(request), - "GET / HTTP/1.1\r\n" - "Host: %s:%s\r\n" - "Connection: close\r\n" - "\r\n", - host, port_str); - - int64_t http_start = esp_timer_get_time(); - int sent = send(sock, request, strlen(request), 0); - if (sent <= 0) { - close(sock); - cJSON_AddBoolToObject(json, "http_ok", false); - cJSON_AddStringToObject(json, "http_error", "HTTP 发送失败"); - ts_api_result_ok(result, json); - return ESP_OK; + char host[256], port[8]; + size_t length = parsed.field_data[UF_HOST].len; + memcpy(host, item->valuestring + parsed.field_data[UF_HOST].off, length); + host[length] = 0; + snprintf(port, sizeof(port), "%u", parsed.field_set & (1U << UF_PORT) ? parsed.port : + parsed.field_data[UF_SCHEMA].len == 5 ? 443U : 80U); + int64_t started = esp_timer_get_time(); + ts_http_fetch_config_t config = {.url = item->valuestring, .method = HTTP_METHOD_GET, + .timeout_ms = 5000, .headers_only = true, .maximum_body = 4096}; + ts_http_fetch_result_t reply; + esp_err_t ret = ts_http_fetch(&config, &reply); + bool http_ok = ret == ESP_OK && reply.connected && reply.status >= 100 && reply.status < 600; + int64_t http_ms = (esp_timer_get_time() - started) / 1000 - reply.dns_time_ms - reply.connect_time_ms; + bool complete = cJSON_AddStringToObject(data, "url", item->valuestring) && + cJSON_AddStringToObject(data, "host", host) && cJSON_AddStringToObject(data, "port", port) && + cJSON_AddBoolToObject(data, "dns_ok", reply.dns_ok) && + cJSON_AddNumberToObject(data, "dns_time_ms", (double)reply.dns_time_ms) && + cJSON_AddStringToObject(data, "resolved_ip", reply.resolved_ip) && + cJSON_AddBoolToObject(data, "tcp_ok", reply.connected) && + cJSON_AddNumberToObject(data, "tcp_time_ms", (double)reply.connect_time_ms) && + cJSON_AddBoolToObject(data, "http_ok", http_ok) && + cJSON_AddNumberToObject(data, "http_time_ms", (double)(http_ms > 0 ? http_ms : 0)) && + cJSON_AddNumberToObject(data, "http_status", reply.status); + if (!reply.dns_ok) complete = complete && cJSON_AddStringToObject(data, "dns_error", esp_err_to_name(ret)); + else if (!reply.connected) complete = complete && cJSON_AddStringToObject(data, "tcp_error", esp_err_to_name(ret)); + else if (!http_ok) complete = complete && cJSON_AddStringToObject(data, "http_error", esp_err_to_name(ret)); + free(reply.body); + if (!complete) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Insufficient device memory"); + return ESP_ERR_NO_MEM; } + ts_api_result_ok(result, data); + return ESP_OK; +} - char response[1024]; - int received = recv(sock, response, sizeof(response) - 1, 0); - int64_t http_time = (esp_timer_get_time() - http_start) / 1000; // ms - close(sock); - - cJSON_AddNumberToObject(json, "http_time_ms", http_time); - if (received <= 0) { - cJSON_AddBoolToObject(json, "http_ok", false); - cJSON_AddStringToObject(json, "http_error", "HTTP 无响应"); - ts_api_result_ok(result, json); - return ESP_OK; - } - - response[received] = '\0'; - - // 解析 HTTP 状态码 - int http_status = 0; - if (strncmp(response, "HTTP/", 5) == 0) { - sscanf(response + 9, "%d", &http_status); +static esp_err_t api_ota_test_connection(const cJSON *params, ts_api_result_t *result) +{ + if (atomic_flag_test_and_set(&s_ota_probe_busy)) { + ts_api_result_error(result, TS_API_ERR_BUSY, "Network diagnostic busy"); + return ESP_ERR_INVALID_STATE; } - - cJSON_AddBoolToObject(json, "http_ok", true); - cJSON_AddNumberToObject(json, "http_status", http_status); - ESP_LOGI(TAG, "HTTP response: status=%d, time=%lld ms", http_status, http_time); - - ts_api_result_ok(result, json); - return ESP_OK; + esp_err_t ret = ota_test_connection_impl(params, result); + atomic_flag_clear(&s_ota_probe_busy); + return ret; } // ============================================================================ @@ -1003,20 +936,26 @@ esp_err_t ts_api_ota_register(void) ts_api_endpoint_t endpoints[] = { { .name = "ota.status", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_status, - .requires_auth = false, + .requires_auth = true, .description = "获取 OTA 状态", }, { .name = "ota.progress", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_progress, - .requires_auth = false, + .requires_auth = true, .description = "获取 OTA 进度", }, { .name = "ota.version", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_version, .requires_auth = false, @@ -1024,20 +963,27 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.partitions", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_partitions, .requires_auth = false, + .session_handler = api_ota_partitions_for_session, .description = "获取分区信息", }, { .name = "ota.start_url", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_start_url, .requires_auth = true, .description = "从 URL 启动 OTA", }, { - .name = "ota.upgrade_url", // Alias for start_url + .name = "ota.upgrade_url", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, // Alias for start_url .category = TS_API_CAT_SYSTEM, .handler = api_ota_start_url, .requires_auth = true, @@ -1045,13 +991,17 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.start_file", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_start_file, .requires_auth = true, .description = "从 SD 卡启动 OTA", }, { - .name = "ota.upgrade_file", // Alias for start_file + .name = "ota.upgrade_file", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, // Alias for start_file .category = TS_API_CAT_SYSTEM, .handler = api_ota_start_file, .requires_auth = true, @@ -1059,6 +1009,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.abort", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_abort, .requires_auth = true, @@ -1066,6 +1018,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.validate", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_validate, .requires_auth = true, @@ -1073,6 +1027,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.rollback", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_rollback, .requires_auth = true, @@ -1080,6 +1036,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.upload_begin", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_upload_begin, .requires_auth = true, @@ -1087,6 +1045,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.upload_end", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_upload_end, .requires_auth = true, @@ -1094,6 +1054,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.upload_abort", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_upload_abort, .requires_auth = true, @@ -1101,13 +1063,17 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.server.get", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_server_get, - .requires_auth = false, + .requires_auth = true, .description = "获取 OTA 服务器地址", }, { .name = "ota.server.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_server_set, .requires_auth = true, @@ -1116,6 +1082,8 @@ esp_err_t ts_api_ota_register(void) // WWW Partition OTA { .name = "ota.www.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_www_start, .requires_auth = true, @@ -1123,6 +1091,8 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.www.start_sdcard", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_www_start_sdcard, .requires_auth = true, @@ -1130,13 +1100,17 @@ esp_err_t ts_api_ota_register(void) }, { .name = "ota.www.progress", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .category = TS_API_CAT_SYSTEM, .handler = api_ota_www_progress, - .requires_auth = false, + .requires_auth = true, .description = "获取 WWW OTA 进度", }, { .name = "ota.www.abort", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_www_abort, .requires_auth = true, @@ -1145,9 +1119,11 @@ esp_err_t ts_api_ota_register(void) // Network diagnostics { .name = "ota.test_connection", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .category = TS_API_CAT_SYSTEM, .handler = api_ota_test_connection, - .requires_auth = false, + .requires_auth = true, .description = "测试 OTA 服务器连接", }, }; diff --git a/components/ts_api/src/ts_api_pack.h b/components/ts_api/src/ts_api_pack.h index ea961ad8..cc50a3ec 100644 --- a/components/ts_api/src/ts_api_pack.h +++ b/components/ts_api/src/ts_api_pack.h @@ -12,6 +12,7 @@ static inline void pack_failure(ts_api_result_t *result, ts_config_pack_result_t pack_result) { ts_api_result_code_t code = pack_result == TS_CONFIG_PACK_ERR_NO_MEM ? TS_API_ERR_NO_MEM + : pack_result == TS_CONFIG_PACK_ERR_UNSUPPORTED ? TS_API_ERR_NOT_SUPPORTED : pack_result == TS_CONFIG_PACK_ERR_PERMISSION ? TS_API_ERR_NO_PERMISSION : (pack_result == TS_CONFIG_PACK_ERR_IO || pack_result == TS_CONFIG_PACK_ERR_NOT_INIT) ? TS_API_ERR_INTERNAL : TS_API_ERR_INVALID_ARG; diff --git a/components/ts_api/src/ts_api_power.c b/components/ts_api/src/ts_api_power.c index eee2a57f..3547b59d 100644 --- a/components/ts_api/src/ts_api_power.c +++ b/components/ts_api/src/ts_api_power.c @@ -532,6 +532,8 @@ static esp_err_t api_power_debug(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t s_power_endpoints[] = { { .name = "power.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get power monitoring status", .category = TS_API_CAT_POWER, .handler = api_power_status, @@ -539,6 +541,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.voltage", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Read current voltage", .category = TS_API_CAT_POWER, .handler = api_power_voltage, @@ -546,6 +550,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.chip", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get power chip data", .category = TS_API_CAT_POWER, .handler = api_power_chip, @@ -553,13 +559,17 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.stats", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get monitoring statistics", .category = TS_API_CAT_POWER, .handler = api_power_stats, - .requires_auth = false, + .requires_auth = true, }, { .name = "power.stats.reset", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Reset monitoring statistics", .category = TS_API_CAT_POWER, .handler = api_power_stats_reset, @@ -567,6 +577,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.threshold.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set voltage thresholds", .category = TS_API_CAT_POWER, .handler = api_power_threshold_set, @@ -574,6 +586,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.interval.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set sampling interval", .category = TS_API_CAT_POWER, .handler = api_power_interval_set, @@ -581,6 +595,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.debug", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Set debug mode", .category = TS_API_CAT_POWER, .handler = api_power_debug, @@ -588,6 +604,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.protection.set", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Configure voltage protection", .category = TS_API_CAT_POWER, .handler = api_power_protection_set, @@ -595,13 +613,17 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.protection.config", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get voltage protection configuration", .category = TS_API_CAT_POWER, .handler = api_power_protection_config, - .requires_auth = false, + .requires_auth = true, }, { .name = "power.protection.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get voltage protection status", .category = TS_API_CAT_POWER, .handler = api_power_protection_status, @@ -609,6 +631,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.monitor.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Start power monitoring", .category = TS_API_CAT_POWER, .handler = api_power_monitor_start, @@ -616,6 +640,8 @@ static const ts_api_endpoint_t s_power_endpoints[] = { }, { .name = "power.monitor.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop power monitoring", .category = TS_API_CAT_POWER, .handler = api_power_monitor_stop, diff --git a/components/ts_api/src/ts_api_service.c b/components/ts_api/src/ts_api_service.c index 7a6f743a..5afb2793 100644 --- a/components/ts_api/src/ts_api_service.c +++ b/components/ts_api/src/ts_api_service.c @@ -290,6 +290,8 @@ static esp_err_t api_service_restart(const cJSON *params, ts_api_result_t *resul static const ts_api_endpoint_t s_service_endpoints[] = { { .name = "service.list", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "List all services", .category = TS_API_CAT_SYSTEM, .handler = api_service_list, @@ -297,6 +299,8 @@ static const ts_api_endpoint_t s_service_endpoints[] = { }, { .name = "service.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get service status", .category = TS_API_CAT_SYSTEM, .handler = api_service_status, @@ -304,6 +308,8 @@ static const ts_api_endpoint_t s_service_endpoints[] = { }, { .name = "service.start", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Start a service", .category = TS_API_CAT_SYSTEM, .handler = api_service_start, @@ -311,6 +317,8 @@ static const ts_api_endpoint_t s_service_endpoints[] = { }, { .name = "service.stop", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Stop a service", .category = TS_API_CAT_SYSTEM, .handler = api_service_stop, @@ -318,6 +326,8 @@ static const ts_api_endpoint_t s_service_endpoints[] = { }, { .name = "service.restart", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Restart a service", .category = TS_API_CAT_SYSTEM, .handler = api_service_restart, diff --git a/components/ts_api/src/ts_api_sftp.c b/components/ts_api/src/ts_api_sftp.c index 78a52dea..74dacf34 100644 --- a/components/ts_api/src/ts_api_sftp.c +++ b/components/ts_api/src/ts_api_sftp.c @@ -231,7 +231,7 @@ static esp_err_t api_sftp_get(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } - esp_err_t ret = ts_storage_check_write_path(local->valuestring, false); + esp_err_t ret = ts_storage_check_external_write_path(local->valuestring, false); if (ret != ESP_OK) { ts_api_result_error(result, ret == ESP_ERR_NOT_ALLOWED ? TS_API_ERR_NO_PERMISSION : TS_API_ERR_INVALID_ARG, ret == ESP_ERR_NOT_ALLOWED ? "automation_configuration_managed" : "storage_path_invalid"); @@ -482,6 +482,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "List remote directory via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_ls, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -489,6 +491,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "Download file via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_get, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -496,6 +500,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "Upload file via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_put, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -503,6 +509,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "Delete remote file via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_rm, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -510,6 +518,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "Create remote directory via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_mkdir, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -517,6 +527,8 @@ static const ts_api_endpoint_t sftp_endpoints[] = { .description = "Get remote file information via SFTP", .category = TS_API_CAT_SECURITY, .handler = api_sftp_stat, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_ssh.c b/components/ts_api/src/ts_api_ssh.c index 0b5df786..989e4c82 100644 --- a/components/ts_api/src/ts_api_ssh.c +++ b/components/ts_api/src/ts_api_ssh.c @@ -117,7 +117,7 @@ static esp_err_t configure_ssh_from_params(const cJSON *params, ts_ssh_config_t esp_err_t ret = ts_keystore_load_private_key(keyid->valuestring, &request_key->data, &request_key->len); if (ret != ESP_OK) { - TS_LOGE(TAG, "Failed to load key '%s': %s", keyid->valuestring, esp_err_to_name(ret)); + TS_LOGE(TAG, "Failed to load SSH key: %s", esp_err_to_name(ret)); return ret; } config->auth_method = TS_SSH_AUTH_PUBLICKEY; @@ -439,7 +439,7 @@ static esp_err_t api_ssh_exec(const cJSON *params, ts_api_result_t *result) * - collect_output: Whether to collect output (default true) * - max_output_size: Maximum output to collect (default 65536) */ -static esp_err_t api_ssh_exec_stream(const cJSON *params, ts_api_result_t *result) +static esp_err_t api_ssh_exec_stream_impl(const cJSON *params, uint32_t caller_session_id, ts_api_result_t *result) { if (!params) { ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Missing parameters"); @@ -520,7 +520,7 @@ static esp_err_t api_ssh_exec_stream(const cJSON *params, ts_api_result_t *resul ts_webui_ssh_receipt_t receipt={0}; { /* Use one admission path, including the private recovery receipt. */ - ts_webui_ssh_options_t options = {.receipt=&receipt}; + ts_webui_ssh_options_t options = {.receipt=&receipt,.owner_session_id=caller_session_id}; options.expect_pattern = (expect_pattern && cJSON_IsString(expect_pattern)) ? expect_pattern->valuestring : NULL; options.fail_pattern = (fail_pattern && cJSON_IsString(fail_pattern)) ? @@ -540,9 +540,7 @@ static esp_err_t api_ssh_exec_stream(const cJSON *params, ts_api_result_t *resul options.stop_on_match = (stop_on_match && cJSON_IsBool(stop_on_match)) ? cJSON_IsTrue(stop_on_match) : false; - TS_LOGW(TAG, "api_ssh_exec_stream: var_name param=%p, is_string=%d, value='%s'", - (void*)var_name, var_name ? cJSON_IsString(var_name) : 0, - options.var_name ? options.var_name : "(null)"); + TS_LOGD(TAG, "SSH stream options accepted"); ret = ts_webui_ssh_exec_start_ex( host->valuestring, ssh_port, @@ -570,31 +568,46 @@ static esp_err_t api_ssh_exec_stream(const cJSON *params, ts_api_result_t *resul return ESP_OK; } +static esp_err_t api_ssh_exec_stream(const cJSON *p,ts_api_result_t *r){ + return api_ssh_exec_stream_impl(p,0,r); +} +static esp_err_t api_ssh_exec_stream_for_session(const cJSON *p,uint32_t sid,ts_api_result_t *r){ + return api_ssh_exec_stream_impl(p,sid,r); +} + /* Exact boot identity and the private initiation receipt, in addition to the * same authentication gate as ssh.exec_stream. IDs alone reveal no results. */ -static esp_err_t api_ssh_exec_status(const cJSON *params,ts_api_result_t *result) { +static esp_err_t api_ssh_exec_status_impl(const cJSON *params,const uint32_t *caller_session_id,ts_api_result_t *result) { const cJSON *id=cJSON_GetObjectItem(params,"session_id"); const cJSON *boot=cJSON_GetObjectItem(params,"boot_id"),*key=cJSON_GetObjectItem(params,"result_key"); char *json=NULL;esp_err_t lookup=ESP_ERR_NOT_FOUND; if(cJSON_IsNumber(id) && id->valuedouble>=1 && id->valuedouble<=UINT32_MAX && id->valuedouble==(double)(uint32_t)id->valuedouble && cJSON_IsString(boot) && cJSON_IsString(key)) - json=ts_webui_ssh_exec_status((uint32_t)id->valuedouble,boot->valuestring,key->valuestring,&lookup); + json=caller_session_id ? ts_webui_ssh_exec_status_for_session((uint32_t)id->valuedouble,boot->valuestring,key->valuestring,*caller_session_id,&lookup) : + ts_webui_ssh_exec_status((uint32_t)id->valuedouble,boot->valuestring,key->valuestring,&lookup); if(!json){ts_api_result_error(result,lookup==ESP_ERR_NO_MEM?TS_API_ERR_INTERNAL:TS_API_ERR_NOT_FOUND, lookup==ESP_ERR_NO_MEM?"ssh_result_unknown":"ssh_result_unavailable");return lookup;} cJSON *data=cJSON_Parse(json);free(json); if(!data){ts_api_result_error(result,TS_API_ERR_INTERNAL,"ssh_result_unknown");return ESP_FAIL;} ts_api_result_ok(result,data);return ESP_OK; } +static esp_err_t api_ssh_exec_status(const cJSON *p,ts_api_result_t *r){ + return api_ssh_exec_status_impl(p,NULL,r); +} +static esp_err_t api_ssh_exec_status_for_session(const cJSON *p,uint32_t sid,ts_api_result_t *r){ + return api_ssh_exec_status_impl(p,&sid,r); +} + /** * @brief ssh.cancel - Cancel running SSH exec session * - * Params: { "session_id": 12345 } + * Params: { "session_id": 12345, "boot_id": "", "result_key": "" } * * Response: { "cancelled": true } */ -static esp_err_t api_ssh_cancel(const cJSON *params, ts_api_result_t *result) +static esp_err_t api_ssh_cancel_impl(const cJSON *params,const uint32_t *caller_session_id,ts_api_result_t *result) { const cJSON *sid = cJSON_GetObjectItem(params, "session_id"); @@ -604,7 +617,20 @@ static esp_err_t api_ssh_cancel(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "ssh_no_session"); return ESP_ERR_NOT_FOUND; } - esp_err_t ret = ts_webui_ssh_exec_cancel((uint32_t)sid->valuedouble); + const cJSON *boot = cJSON_GetObjectItem(params, "boot_id"); + const cJSON *key = cJSON_GetObjectItem(params, "result_key"); + bool has_receipt = cJSON_IsString(boot) && cJSON_IsString(key); + esp_err_t ret = ESP_ERR_INVALID_STATE; + /* The original UI sends only the job ID. Its validated initiating login + * already identifies the owner; supplied receipt fields must still match. */ + if (caller_session_id && ((!boot && !key) || has_receipt)) { + ret = ts_webui_ssh_exec_cancel_for_session((uint32_t)sid->valuedouble, + has_receipt ? boot->valuestring : NULL, + has_receipt ? key->valuestring : NULL, *caller_session_id); + } else if (!caller_session_id && has_receipt) { + ret = ts_webui_ssh_exec_cancel_with_receipt((uint32_t)sid->valuedouble, + boot->valuestring, key->valuestring); + } if (ret != ESP_OK) { ts_api_result_error(result, ret == ESP_ERR_INVALID_STATE ? TS_API_ERR_NOT_FOUND : TS_API_ERR_INTERNAL, ret == ESP_ERR_INVALID_STATE ? "ssh_no_session" : "ssh_cancel_failed"); @@ -617,6 +643,13 @@ static esp_err_t api_ssh_cancel(const cJSON *params, ts_api_result_t *result) return ESP_OK; } +static esp_err_t api_ssh_cancel(const cJSON *p,ts_api_result_t *r){ + return api_ssh_cancel_impl(p,NULL,r); +} +static esp_err_t api_ssh_cancel_for_session(const cJSON *p,uint32_t sid,ts_api_result_t *r){ + return api_ssh_cancel_impl(p,&sid,r); +} + /** * @brief ssh.test - Test SSH connection @@ -1760,15 +1793,27 @@ static esp_err_t api_ssh_service_start(const cJSON *params, ts_api_result_t *res } static const ts_api_endpoint_t ssh_endpoints[] = { - {.name="ssh.exec_status",.description="Read owned current or latest SSH result", - .category=TS_API_CAT_SECURITY,.handler=api_ssh_exec_status,.requires_auth=true}, + { + .name = "ssh.exec_status", + .description = "Read owned current or latest SSH result", + .category = TS_API_CAT_SECURITY, + .handler = api_ssh_exec_status, + .session_handler = api_ssh_exec_status_for_session, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, + }, {.name = "ssh.services.start", .description = "Start a stored managed service", - .category = TS_API_CAT_SECURITY, .handler = api_ssh_service_start, .requires_auth = true}, + .category = TS_API_CAT_SECURITY, .handler = api_ssh_service_start, + .external_access = TS_API_ACCESS_ADMIN, .allowed_methods = TS_API_METHOD_WRITE, + .requires_auth = true}, { .name = "ssh.exec", .description = "Execute remote command via SSH", .category = TS_API_CAT_SECURITY, .handler = api_ssh_exec, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1776,6 +1821,9 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Execute remote command with streaming output via WebSocket", .category = TS_API_CAT_SECURITY, .handler = api_ssh_exec_stream, + .session_handler = api_ssh_exec_stream_for_session, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1783,6 +1831,9 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Cancel running SSH exec session", .category = TS_API_CAT_SECURITY, .handler = api_ssh_cancel, + .session_handler = api_ssh_cancel_for_session, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1790,6 +1841,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Test SSH connection", .category = TS_API_CAT_SECURITY, .handler = api_ssh_test, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1797,6 +1850,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Deploy public key to remote server", .category = TS_API_CAT_SECURITY, .handler = api_ssh_copyid, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1804,6 +1859,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Revoke (remove) deployed public key from remote server", .category = TS_API_CAT_SECURITY, .handler = api_ssh_revoke, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1811,6 +1868,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Generate SSH key pair", .category = TS_API_CAT_SECURITY, .handler = api_ssh_keygen, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, /* SSH Host Config APIs */ @@ -1819,13 +1878,17 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "List all SSH host configurations", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_list, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, }, { .name = "ssh.hosts.add", .description = "Add SSH host configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_add, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1833,6 +1896,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Update an existing SSH hosts configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_update, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1840,6 +1905,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Remove SSH host configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_remove, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1847,13 +1914,17 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Get SSH host configuration by ID", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_get, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, }, { .name = "ssh.hosts.export", .description = "Export SSH host configuration as .tscfg", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_export, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1861,6 +1932,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Import SSH host configuration from .tscfg", .category = TS_API_CAT_SECURITY, .handler = api_ssh_hosts_import, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, /* SSH Command Config APIs */ @@ -1869,13 +1942,17 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "List all SSH command configurations", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_list, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, }, { .name = "ssh.commands.add", .description = "Add or update SSH command configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_add, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1883,6 +1960,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Update an existing SSH commands configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_update, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1890,6 +1969,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Remove SSH command configuration", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_remove, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1897,13 +1978,17 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Get SSH command configuration by ID", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_get, - .requires_auth = false, + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, + .requires_auth = true, }, { .name = "ssh.commands.export", .description = "Export SSH command configuration as .tscfg", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_export, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -1911,6 +1996,8 @@ static const ts_api_endpoint_t ssh_endpoints[] = { .description = "Import SSH command configuration from .tscfg", .category = TS_API_CAT_SECURITY, .handler = api_ssh_commands_import, + .external_access = TS_API_ACCESS_ROOT, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_storage.c b/components/ts_api/src/ts_api_storage.c index 0f9738d6..ce506a2d 100644 --- a/components/ts_api/src/ts_api_storage.c +++ b/components/ts_api/src/ts_api_storage.c @@ -8,6 +8,7 @@ #include "ts_api.h" #include "ts_storage.h" +#include "ts_security.h" #include "ts_log.h" #include #include @@ -205,7 +206,7 @@ static esp_err_t api_storage_delete(const cJSON *params, ts_api_result_t *result return ESP_ERR_INVALID_ARG; } - esp_err_t ret = ts_storage_check_write_path(path, true); + esp_err_t ret = ts_storage_check_external_write_path(path, true); if (ret != ESP_OK) return storage_mutation_failure(result, ret, "Failed to delete"); if (!ts_storage_exists(path)) { ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "File not found"); @@ -248,7 +249,9 @@ static esp_err_t api_storage_mkdir(const cJSON *params, ts_api_result_t *result) const char *path = path_param->valuestring; - esp_err_t ret = ts_storage_mkdir_p(path); + esp_err_t ret = ts_storage_check_external_write_path(path, false); + if (ret != ESP_OK) return storage_mutation_failure(result, ret, "Failed to create directory"); + ret = ts_storage_mkdir_p(path); if (ret != ESP_OK) { return storage_mutation_failure(result, ret, "Failed to create directory"); } @@ -282,8 +285,8 @@ static esp_err_t api_storage_rename(const cJSON *params, ts_api_result_t *result const char *from = from_param->valuestring; const char *to = to_param->valuestring; - esp_err_t ret = ts_storage_check_write_path(from, true); - if (ret == ESP_OK) ret = ts_storage_check_write_path(to, true); + esp_err_t ret = ts_storage_check_external_write_path(from, true); + if (ret == ESP_OK) ret = ts_storage_check_external_write_path(to, true); if (ret != ESP_OK) return storage_mutation_failure(result, ret, "Failed to rename"); if (!ts_storage_exists(from)) { ts_api_result_error(result, TS_API_ERR_NOT_FOUND, "Source file not found"); @@ -429,6 +432,57 @@ static esp_err_t api_storage_read(const cJSON *params, ts_api_result_t *result) return ESP_OK; } +/* Only external calls carry an authenticated C session; internal reads keep + * their original handler and do not inherit untrusted JSON identity fields. */ +static esp_err_t storage_read_for_session(const cJSON *params, uint32_t session_id, + ts_api_handler_t handler, bool default_sd, + ts_api_result_t *result) +{ + const cJSON *item = cJSON_GetObjectItem(params, "path"); + const char *path = cJSON_IsString(item) ? item->valuestring : default_sd ? "/sdcard" : NULL; + if (!path) return handler(params, result); +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + ts_session_t session; + if (ts_security_validate_session(session_id, &session) != ESP_OK || session.level < TS_PERM_READ) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } +#else + (void)session_id; +#endif + bool needs_admin; + esp_err_t ret = ts_storage_external_read_requires_admin(path, &needs_admin); + if (ret != ESP_OK) { + ts_api_result_error(result, ret == ESP_ERR_INVALID_ARG ? TS_API_ERR_INVALID_ARG : TS_API_ERR_INTERNAL, + ret == ESP_ERR_INVALID_ARG ? "storage_path_invalid" : "storage_read_failed"); + return ret; + } +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (ts_security_validate_session(session_id, &session) != ESP_OK || session.level < TS_PERM_READ) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } + if (needs_admin && session.level < TS_PERM_ADMIN) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Administrator permission required"); + return ESP_ERR_NOT_ALLOWED; + } +#endif + return handler(params, result); +} + +static esp_err_t storage_list_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return storage_read_for_session(params, session, api_storage_list, true, result); +} +static esp_err_t storage_info_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return storage_read_for_session(params, session, api_storage_info, false, result); +} +static esp_err_t storage_file_for_session(const cJSON *params, uint32_t session, ts_api_result_t *result) +{ + return storage_read_for_session(params, session, api_storage_read, false, result); +} + /*===========================================================================*/ /* Registration */ /*===========================================================================*/ @@ -436,6 +490,8 @@ static esp_err_t api_storage_read(const cJSON *params, ts_api_result_t *result) static const ts_api_endpoint_t s_storage_endpoints[] = { { .name = "storage.status", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get storage status", .category = TS_API_CAT_STORAGE, .handler = api_storage_status, @@ -443,6 +499,8 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.mount", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Mount SD card", .category = TS_API_CAT_STORAGE, .handler = api_storage_mount, @@ -450,6 +508,8 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.unmount", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Unmount SD card", .category = TS_API_CAT_STORAGE, .handler = api_storage_unmount, @@ -457,13 +517,18 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.list", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List directory contents", .category = TS_API_CAT_STORAGE, .handler = api_storage_list, - .requires_auth = false + .session_handler = storage_list_for_session, + .requires_auth = true }, { .name = "storage.delete", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Delete file or directory", .category = TS_API_CAT_STORAGE, .handler = api_storage_delete, @@ -471,6 +536,8 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.mkdir", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Create directory", .category = TS_API_CAT_STORAGE, .handler = api_storage_mkdir, @@ -478,6 +545,8 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.rename", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Rename/move file", .category = TS_API_CAT_STORAGE, .handler = api_storage_rename, @@ -485,17 +554,23 @@ static const ts_api_endpoint_t s_storage_endpoints[] = { }, { .name = "storage.info", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Get file info", .category = TS_API_CAT_STORAGE, .handler = api_storage_info, - .requires_auth = false + .session_handler = storage_info_for_session, + .requires_auth = true }, { .name = "storage.read", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "Read file content", .category = TS_API_CAT_STORAGE, .handler = api_storage_read, - .requires_auth = false + .session_handler = storage_file_for_session, + .requires_auth = true } }; diff --git a/components/ts_api/src/ts_api_system.c b/components/ts_api/src/ts_api_system.c index 5f99de3c..ea982167 100644 --- a/components/ts_api/src/ts_api_system.c +++ b/components/ts_api/src/ts_api_system.c @@ -1,15 +1,17 @@ /** * @file ts_api_system.c * @brief System API Handlers - * + * * 任务列表等大缓冲区优先分配到 PSRAM - * + * * @author TianShanOS Team * @version 1.0.0 * @date 2026-01-15 */ #include "ts_api.h" +#include "ts_ota.h" +#include #include "ts_core.h" /* TS_MALLOC_PSRAM */ #include "ts_log.h" #include "esp_system.h" @@ -41,19 +43,7 @@ extern uint32_t _rtc_bss_start, _rtc_bss_end; /* Delayed Reboot Task */ /*===========================================================================*/ -static void reboot_task(void *arg) -{ - int delay_ms = (int)(intptr_t)arg; - - /* Wait for response to be sent */ - vTaskDelay(pdMS_TO_TICKS(delay_ms)); - - TS_LOGI(TAG, "Rebooting system..."); - esp_restart(); - - /* Should not reach here */ - vTaskDelete(NULL); -} + /*===========================================================================*/ /* API Handlers */ @@ -69,7 +59,7 @@ static esp_err_t api_system_info(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + /* App info */ const esp_app_desc_t *app_desc = esp_app_get_description(); cJSON *app = cJSON_AddObjectToObject(data, "app"); @@ -78,13 +68,13 @@ static esp_err_t api_system_info(const cJSON *params, ts_api_result_t *result) cJSON_AddStringToObject(app, "idf_version", app_desc->idf_ver); cJSON_AddStringToObject(app, "compile_time", app_desc->time); cJSON_AddStringToObject(app, "compile_date", app_desc->date); - + /* Chip info */ esp_chip_info_t chip_info; esp_chip_info(&chip_info); - + cJSON *chip = cJSON_AddObjectToObject(data, "chip"); - + const char *model_name = "unknown"; switch (chip_info.model) { case CHIP_ESP32: model_name = "ESP32"; break; @@ -99,29 +89,29 @@ static esp_err_t api_system_info(const cJSON *params, ts_api_result_t *result) cJSON_AddStringToObject(chip, "model", model_name); cJSON_AddNumberToObject(chip, "cores", chip_info.cores); cJSON_AddNumberToObject(chip, "revision", chip_info.revision); - + cJSON *features = cJSON_AddArrayToObject(chip, "features"); - if (chip_info.features & CHIP_FEATURE_WIFI_BGN) + if (chip_info.features & CHIP_FEATURE_WIFI_BGN) cJSON_AddItemToArray(features, cJSON_CreateString("WiFi")); - if (chip_info.features & CHIP_FEATURE_BT) + if (chip_info.features & CHIP_FEATURE_BT) cJSON_AddItemToArray(features, cJSON_CreateString("BT")); - if (chip_info.features & CHIP_FEATURE_BLE) + if (chip_info.features & CHIP_FEATURE_BLE) cJSON_AddItemToArray(features, cJSON_CreateString("BLE")); - if (chip_info.features & CHIP_FEATURE_EMB_FLASH) + if (chip_info.features & CHIP_FEATURE_EMB_FLASH) cJSON_AddItemToArray(features, cJSON_CreateString("Embedded Flash")); - if (chip_info.features & CHIP_FEATURE_EMB_PSRAM) + if (chip_info.features & CHIP_FEATURE_EMB_PSRAM) cJSON_AddItemToArray(features, cJSON_CreateString("Embedded PSRAM")); - + /* Flash */ uint32_t flash_size; if (esp_flash_get_size(NULL, &flash_size) == ESP_OK) { cJSON_AddNumberToObject(data, "flash_size", flash_size); } - + /* Uptime */ int64_t uptime_us = esp_timer_get_time(); cJSON_AddNumberToObject(data, "uptime_ms", uptime_us / 1000); - + ts_api_result_ok(result, data); return ESP_OK; } @@ -136,33 +126,33 @@ static esp_err_t api_system_memory(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + /* Heap info */ cJSON_AddNumberToObject(data, "free_heap", esp_get_free_heap_size()); cJSON_AddNumberToObject(data, "min_free_heap", esp_get_minimum_free_heap_size()); - + /* Internal memory */ multi_heap_info_t heap_info; heap_caps_get_info(&heap_info, MALLOC_CAP_INTERNAL); - + cJSON *internal = cJSON_AddObjectToObject(data, "internal"); - cJSON_AddNumberToObject(internal, "total", + cJSON_AddNumberToObject(internal, "total", heap_info.total_free_bytes + heap_info.total_allocated_bytes); cJSON_AddNumberToObject(internal, "free", heap_info.total_free_bytes); cJSON_AddNumberToObject(internal, "allocated", heap_info.total_allocated_bytes); cJSON_AddNumberToObject(internal, "largest_block", heap_info.largest_free_block); - + /* PSRAM */ heap_caps_get_info(&heap_info, MALLOC_CAP_SPIRAM); if (heap_info.total_free_bytes > 0 || heap_info.total_allocated_bytes > 0) { cJSON *psram = cJSON_AddObjectToObject(data, "psram"); - cJSON_AddNumberToObject(psram, "total", + cJSON_AddNumberToObject(psram, "total", heap_info.total_free_bytes + heap_info.total_allocated_bytes); cJSON_AddNumberToObject(psram, "free", heap_info.total_free_bytes); cJSON_AddNumberToObject(psram, "allocated", heap_info.total_allocated_bytes); cJSON_AddNumberToObject(psram, "largest_block", heap_info.largest_free_block); } - + ts_api_result_ok(result, data); return ESP_OK; } @@ -177,22 +167,22 @@ static esp_err_t api_system_tasks(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + #if configUSE_TRACE_FACILITY UBaseType_t task_count = uxTaskGetNumberOfTasks(); TaskStatus_t *task_array = TS_MALLOC_PSRAM(task_count * sizeof(TaskStatus_t)); - + if (task_array == NULL) { cJSON_Delete(data); ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + uint32_t total_runtime; task_count = uxTaskGetSystemState(task_array, task_count, &total_runtime); - + cJSON *tasks = cJSON_AddArrayToObject(data, "tasks"); - + for (int i = 0; i < task_count; i++) { cJSON *task = cJSON_CreateObject(); cJSON_AddStringToObject(task, "name", task_array[i].pcTaskName); @@ -203,7 +193,7 @@ static esp_err_t api_system_tasks(const cJSON *params, ts_api_result_t *result) #else cJSON_AddNumberToObject(task, "core", -1); #endif - + const char *state = "unknown"; switch (task_array[i].eCurrentState) { case eRunning: state = "running"; break; @@ -214,16 +204,16 @@ static esp_err_t api_system_tasks(const cJSON *params, ts_api_result_t *result) default: break; } cJSON_AddStringToObject(task, "state", state); - + cJSON_AddItemToArray(tasks, task); } - + free(task_array); cJSON_AddNumberToObject(data, "count", task_count); #else cJSON_AddStringToObject(data, "error", "Task trace not enabled"); #endif - + ts_api_result_ok(result, data); return ESP_OK; } @@ -248,28 +238,28 @@ static esp_err_t api_system_cpu(const cJSON *params, ts_api_result_t *result) ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + /* Get chip info for core count */ esp_chip_info_t chip_info; esp_chip_info(&chip_info); uint8_t num_cores = chip_info.cores; - + #if configUSE_TRACE_FACILITY && configGENERATE_RUN_TIME_STATS UBaseType_t task_count = uxTaskGetNumberOfTasks(); TaskStatus_t *task_array = TS_MALLOC_PSRAM(task_count * sizeof(TaskStatus_t)); - + if (task_array == NULL) { cJSON_Delete(data); ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + uint32_t total_runtime; UBaseType_t actual_count = uxTaskGetSystemState(task_array, task_count, &total_runtime); - + /* 只需要每个核心的 IDLE 任务运行时间 */ uint32_t idle_runtime[2] = {0, 0}; - + for (UBaseType_t i = 0; i < actual_count; i++) { if (strncmp(task_array[i].pcTaskName, "IDLE", 4) == 0) { BaseType_t core_id = task_array[i].xCoreID; @@ -278,23 +268,23 @@ static esp_err_t api_system_cpu(const cJSON *params, ts_api_result_t *result) } } } - + cJSON *cores = cJSON_AddArrayToObject(data, "cores"); uint32_t total_usage_sum = 0; - + /* 增量计算:使用两次采样的差值 */ uint32_t delta_total = total_runtime - s_prev_total_runtime; - + for (int i = 0; i < num_cores; i++) { cJSON *core = cJSON_CreateObject(); cJSON_AddNumberToObject(core, "id", i); - + uint32_t cpu_percent = 0; - + if (s_cpu_prev_valid && delta_total > 0) { /* 每个核心可用时间 = 总时间增量(timer 对所有核心公用) */ uint32_t delta_idle = idle_runtime[i] - s_prev_idle_runtime[i]; - + /* 使用率 = 100% - 空闲率 */ if (delta_idle < delta_total) { cpu_percent = ((delta_total - delta_idle) * 100) / delta_total; @@ -302,24 +292,24 @@ static esp_err_t api_system_cpu(const cJSON *params, ts_api_result_t *result) /* 限幅保护(避免计数器回绕时出错) */ if (cpu_percent > 100) cpu_percent = 100; } - + cJSON_AddNumberToObject(core, "usage", cpu_percent); cJSON_AddItemToArray(cores, core); total_usage_sum += cpu_percent; } - + /* 保存本次采样数据,供下次增量计算使用 */ s_prev_total_runtime = total_runtime; for (int i = 0; i < num_cores && i < 2; i++) { s_prev_idle_runtime[i] = idle_runtime[i]; } s_cpu_prev_valid = true; - + /* Overall CPU usage (average across cores) */ cJSON_AddNumberToObject(data, "total_usage", num_cores > 0 ? total_usage_sum / num_cores : 0); cJSON_AddNumberToObject(data, "total_runtime", total_runtime); cJSON_AddNumberToObject(data, "task_count", actual_count); - + free(task_array); #else /* Fallback when runtime stats not available */ @@ -334,7 +324,7 @@ static esp_err_t api_system_cpu(const cJSON *params, ts_api_result_t *result) cJSON_AddNumberToObject(data, "total_usage", 0); cJSON_AddStringToObject(data, "error", "CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS not enabled"); #endif - + ts_api_result_ok(result, data); return ESP_OK; } @@ -342,28 +332,47 @@ static esp_err_t api_system_cpu(const cJSON *params, ts_api_result_t *result) /** * @brief system.reboot - Reboot the system */ +static void reboot_task(void *arg) +{ + int delay_ms = (int)(intptr_t)arg; + + /* Wait for response to be sent */ + vTaskDelay(pdMS_TO_TICKS(delay_ms)); + + TS_LOGI(TAG, "Rebooting system..."); + esp_restart(); + + /* Should not reach here */ + vTaskDelete(NULL); +} + + static esp_err_t api_system_reboot(const cJSON *params, ts_api_result_t *result) { - int delay_ms = 500; /* Default 500ms to allow response to be sent */ - - if (params) { - cJSON *delay = cJSON_GetObjectItem(params, "delay"); - if (delay && cJSON_IsNumber(delay)) { - delay_ms = delay->valueint; - if (delay_ms < 100) delay_ms = 100; /* Minimum 100ms to send response */ - if (delay_ms > 10000) delay_ms = 10000; + int delay_ms = 500; + const cJSON *delay = params ? cJSON_GetObjectItem(params, "delay") : NULL; + if (delay) { + if (!cJSON_IsNumber(delay) || !isfinite(delay->valuedouble) || + floor(delay->valuedouble) != delay->valuedouble) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "delay must be an integer in milliseconds"); + return ESP_ERR_INVALID_ARG; } + delay_ms = delay->valuedouble < 100 ? 100 : delay->valuedouble > 10000 ? 10000 : (int)delay->valuedouble; } - cJSON *data = cJSON_CreateObject(); - cJSON_AddStringToObject(data, "status", "rebooting"); - cJSON_AddNumberToObject(data, "delay_ms", delay_ms); - + cJSON *waiting = data ? cJSON_AddBoolToObject(data, "waiting_for_maintenance", false) : NULL; + if (!data || !waiting || !cJSON_AddStringToObject(data, "status", "rebooting") || + !cJSON_AddNumberToObject(data, "delay_ms", delay_ms)) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Out of memory"); + return ESP_ERR_NO_MEM; + } + if (xTaskCreate(reboot_task, "reboot", 2048, (void *)(intptr_t)delay_ms, 1, NULL) != pdPASS) { + cJSON_Delete(data); + ts_api_result_error(result, TS_API_ERR_NO_MEM, "Cannot schedule reboot"); + return ESP_ERR_NO_MEM; + } ts_api_result_ok(result, data); - - /* Schedule reboot in a separate task to allow HTTP response to be sent first */ - xTaskCreate(reboot_task, "reboot", 2048, (void *)(intptr_t)delay_ms, 1, NULL); - return ESP_OK; } @@ -373,11 +382,11 @@ static esp_err_t api_system_reboot(const cJSON *params, ts_api_result_t *result) static esp_err_t api_system_log_level(const cJSON *params, ts_api_result_t *result) { cJSON *data = cJSON_CreateObject(); - + if (params) { cJSON *level = cJSON_GetObjectItem(params, "level"); cJSON *tag = cJSON_GetObjectItem(params, "tag"); - + if (level && cJSON_IsNumber(level)) { int lvl = level->valueint; if (lvl >= TS_LOG_NONE && lvl <= TS_LOG_VERBOSE) { @@ -399,7 +408,7 @@ static esp_err_t api_system_log_level(const cJSON *params, ts_api_result_t *resu cJSON_AddNumberToObject(data, "level", ts_log_get_level()); cJSON_AddStringToObject(data, "status", "get"); } - + ts_api_result_ok(result, data); return ESP_OK; } @@ -414,7 +423,7 @@ static void add_heap_regions(cJSON *regions_array, uint32_t caps) /* Use heap_caps_walk to get detailed region info */ multi_heap_info_t info; heap_caps_get_info(&info, caps); - + /* Since we can't easily enumerate all regions, we provide aggregate info */ cJSON *region = cJSON_CreateObject(); cJSON_AddNumberToObject(region, "total_free", info.total_free_bytes); @@ -429,10 +438,10 @@ static void add_heap_regions(cJSON *regions_array, uint32_t caps) /** * @brief system.memory_detail - Get detailed memory analysis - * + * * Returns comprehensive heap information including: * - DRAM (Internal RAM) statistics - * - PSRAM (External RAM) statistics + * - PSRAM (External RAM) statistics * - DMA capable memory statistics * - IRAM (Instruction RAM) statistics * - Static memory sections (.data, .bss, .rodata) @@ -450,36 +459,36 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * return ESP_ERR_NO_MEM; } cJSON_AddBoolToObject(data, "stack_allocation_estimated", true); - + /* === Static Memory Sections === */ cJSON *static_mem = cJSON_AddObjectToObject(data, "static"); - + /* .data section (initialized data) */ size_t data_size = (size_t)(&_data_end - &_data_start) * sizeof(uint32_t); cJSON_AddNumberToObject(static_mem, "data_size", data_size); - + /* .bss section (uninitialized data) */ size_t bss_size = (size_t)(&_bss_end - &_bss_start) * sizeof(uint32_t); cJSON_AddNumberToObject(static_mem, "bss_size", bss_size); - + /* .rodata section (read-only data, in flash) */ size_t rodata_size = (size_t)(&_rodata_end - &_rodata_start) * sizeof(uint32_t); cJSON_AddNumberToObject(static_mem, "rodata_size", rodata_size); - + /* Total static DRAM usage */ cJSON_AddNumberToObject(static_mem, "total_dram_static", data_size + bss_size); - + /* === IRAM (Instruction RAM) === */ cJSON *iram = cJSON_AddObjectToObject(data, "iram"); size_t iram_text_size = (size_t)(&_iram_text_end - &_iram_text_start) * sizeof(uint32_t); cJSON_AddNumberToObject(iram, "text_size", iram_text_size); - + /* IRAM heap (8-bit capable internal) */ size_t iram_free = heap_caps_get_free_size(MALLOC_CAP_32BIT | MALLOC_CAP_EXEC); size_t iram_total = heap_caps_get_total_size(MALLOC_CAP_32BIT | MALLOC_CAP_EXEC); cJSON_AddNumberToObject(iram, "heap_total", iram_total); cJSON_AddNumberToObject(iram, "heap_free", iram_free); - + /* === RTC Memory === */ cJSON *rtc = cJSON_AddObjectToObject(data, "rtc"); size_t rtc_data_size = (size_t)(&_rtc_data_end - &_rtc_data_start) * sizeof(uint32_t); @@ -488,16 +497,16 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(rtc, "bss_size", rtc_bss_size); cJSON_AddNumberToObject(rtc, "total_used", rtc_data_size + rtc_bss_size); cJSON_AddNumberToObject(rtc, "total_available", 8192); /* RTC slow memory is 8KB */ - + /* === DRAM (Internal RAM) === */ size_t dram_free = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); size_t dram_total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL); size_t dram_largest = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL); size_t dram_min_free = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL); - + multi_heap_info_t dram_info; heap_caps_get_info(&dram_info, MALLOC_CAP_INTERNAL); - + cJSON *dram = cJSON_AddObjectToObject(data, "dram"); cJSON_AddNumberToObject(dram, "total", dram_total); cJSON_AddNumberToObject(dram, "free", dram_free); @@ -507,7 +516,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(dram, "min_free_ever", dram_min_free); cJSON_AddNumberToObject(dram, "alloc_blocks", dram_info.allocated_blocks); cJSON_AddNumberToObject(dram, "free_blocks", dram_info.free_blocks); - + /* Fragmentation: (1 - largest_free / total_free) * 100 */ if (dram_free > 0) { float frag = 100.0f * (1.0f - (float)dram_largest / (float)dram_free); @@ -515,17 +524,17 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * } else { cJSON_AddNumberToObject(dram, "fragmentation", 0); } - + /* === PSRAM (External RAM) === */ size_t psram_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM); size_t psram_total = heap_caps_get_total_size(MALLOC_CAP_SPIRAM); size_t psram_largest = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM); size_t psram_min_free = heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM); - + if (psram_total > 0) { multi_heap_info_t psram_info; heap_caps_get_info(&psram_info, MALLOC_CAP_SPIRAM); - + cJSON *psram = cJSON_AddObjectToObject(data, "psram"); cJSON_AddNumberToObject(psram, "total", psram_total); cJSON_AddNumberToObject(psram, "free", psram_free); @@ -535,7 +544,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(psram, "min_free_ever", psram_min_free); cJSON_AddNumberToObject(psram, "alloc_blocks", psram_info.allocated_blocks); cJSON_AddNumberToObject(psram, "free_blocks", psram_info.free_blocks); - + if (psram_free > 0) { float frag = 100.0f * (1.0f - (float)psram_largest / (float)psram_free); cJSON_AddNumberToObject(psram, "fragmentation", (int)(frag * 10) / 10.0); @@ -543,12 +552,12 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(psram, "fragmentation", 0); } } - + /* === DMA Capable Memory === */ size_t dma_free = heap_caps_get_free_size(MALLOC_CAP_DMA); size_t dma_total = heap_caps_get_total_size(MALLOC_CAP_DMA); size_t dma_largest = heap_caps_get_largest_free_block(MALLOC_CAP_DMA); - + if (dma_total > 0) { cJSON *dma = cJSON_AddObjectToObject(data, "dma"); cJSON_AddNumberToObject(dma, "total", dma_total); @@ -557,11 +566,11 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(dma, "used_percent", 100 * (dma_total - dma_free) / dma_total); cJSON_AddNumberToObject(dma, "largest_block", dma_largest); } - + /* === Historical Data === */ cJSON *history = cJSON_AddObjectToObject(data, "history"); cJSON_AddNumberToObject(history, "min_free_heap_ever", esp_get_minimum_free_heap_size()); - + /* === Task Memory Usage (Top consumers) === */ UBaseType_t task_count = uxTaskGetNumberOfTasks(); if (task_count > 0) { @@ -569,11 +578,11 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * if (task_array) { uint32_t total_runtime; UBaseType_t actual_count = uxTaskGetSystemState(task_array, task_count, &total_runtime); - + /* Sort by stack high water mark (lower = more stack used) */ /* We'll calculate stack usage = stack size - high water mark */ /* Since we don't have stack size, we use high water mark directly (lower is worse) */ - + /* Simple bubble sort for top tasks - sort by stack usage (ascending high water = more used) */ for (UBaseType_t i = 0; i + 1 < actual_count; i++) { for (UBaseType_t j = 0; j < actual_count - i - 1; j++) { @@ -584,21 +593,21 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * } } } - + cJSON *tasks = cJSON_AddArrayToObject(data, "tasks"); - + /* Calculate total stack memory used by all tasks */ uint32_t total_stack_allocated = 0; - + /* Report ALL tasks sorted by stack high water mark (lowest first = most used) */ for (UBaseType_t i = 0; i < actual_count; i++) { cJSON *task = cJSON_CreateObject(); cJSON_AddStringToObject(task, "name", task_array[i].pcTaskName); - + /* Stack high water mark in bytes */ uint32_t hwm_bytes = task_array[i].usStackHighWaterMark * sizeof(StackType_t); cJSON_AddNumberToObject(task, "stack_hwm", hwm_bytes); - + /* Try to get stack allocation size from task handle */ TaskHandle_t task_handle = task_array[i].xHandle; if (task_handle != NULL) { @@ -609,7 +618,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * /* Estimate stack size based on known task configurations */ uint32_t stack_size = 0; const char *name = task_array[i].pcTaskName; - + /* Known task stack sizes from sdkconfig and code */ if (strcmp(name, "main") == 0) stack_size = CONFIG_ESP_MAIN_TASK_STACK_SIZE; else if (strcmp(name, "esp_timer") == 0) stack_size = CONFIG_ESP_TIMER_TASK_STACK_SIZE; @@ -620,7 +629,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * else if (strcmp(name, "httpd") == 0 || strncmp(name, "http", 4) == 0) stack_size = 4096; else if (strcmp(name, "console") == 0) stack_size = 4096; else stack_size = 2048; /* Default assumption */ - + /* hwm_bytes is the REMAINING stack (high water mark = minimum free ever) * If hwm > stack_size, our estimate is wrong - use hwm as minimum size */ if (hwm_bytes > stack_size) { @@ -628,17 +637,17 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * } uint32_t stack_used = stack_size - hwm_bytes; uint32_t usage_pct = stack_size > 0 ? (100 * stack_used / stack_size) : 0; - + cJSON_AddNumberToObject(task, "stack_alloc", stack_size); cJSON_AddNumberToObject(task, "stack_used", stack_used); cJSON_AddNumberToObject(task, "stack_usage_pct", usage_pct); total_stack_allocated += stack_size; } } - + cJSON_AddNumberToObject(task, "priority", task_array[i].uxCurrentPriority); cJSON_AddNumberToObject(task, "core", task_array[i].xCoreID); - + /* State string */ const char *state_str = "Unknown"; switch (task_array[i].eCurrentState) { @@ -650,7 +659,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * default: break; } cJSON_AddStringToObject(task, "state", state_str); - + #if configGENERATE_RUN_TIME_STATS /* CPU usage percentage */ if (total_runtime > 0) { @@ -660,13 +669,13 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * #endif cJSON_AddItemToArray(tasks, task); } - + cJSON_AddNumberToObject(data, "task_count", actual_count); cJSON_AddNumberToObject(data, "total_stack_allocated", total_stack_allocated); free(task_array); } } - + /* === NVS Usage Statistics === */ nvs_stats_t nvs_stats; if (nvs_get_stats(NULL, &nvs_stats) == ESP_OK) { @@ -678,31 +687,31 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * cJSON_AddNumberToObject(nvs, "used_percent", nvs_stats.total_entries > 0 ? 100 * nvs_stats.used_entries / nvs_stats.total_entries : 0); } - + /* === Memory Capability Summary === */ cJSON *caps = cJSON_AddObjectToObject(data, "caps"); - + /* 8-bit accessible memory */ size_t d8_free = heap_caps_get_free_size(MALLOC_CAP_8BIT); size_t d8_total = heap_caps_get_total_size(MALLOC_CAP_8BIT); cJSON_AddNumberToObject(caps, "d8_free", d8_free); cJSON_AddNumberToObject(caps, "d8_total", d8_total); - + /* 32-bit accessible memory */ size_t d32_free = heap_caps_get_free_size(MALLOC_CAP_32BIT); size_t d32_total = heap_caps_get_total_size(MALLOC_CAP_32BIT); cJSON_AddNumberToObject(caps, "d32_free", d32_free); cJSON_AddNumberToObject(caps, "d32_total", d32_total); - + /* Default caps (what malloc uses) */ size_t default_free = heap_caps_get_free_size(MALLOC_CAP_DEFAULT); size_t default_total = heap_caps_get_total_size(MALLOC_CAP_DEFAULT); cJSON_AddNumberToObject(caps, "default_free", default_free); cJSON_AddNumberToObject(caps, "default_total", default_total); - + /* === Optimization Tips === */ cJSON *tips = cJSON_AddArrayToObject(data, "tips"); - + if (dram_total > 0) { int dram_used_pct = 100 * (dram_total - dram_free) / dram_total; if (dram_used_pct > 85) { @@ -710,7 +719,7 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * } else if (dram_used_pct > 80) { cJSON_AddItemToArray(tips, cJSON_CreateString("warning:DRAM 使用率超过 80%,建议将缓冲区迁移到 PSRAM")); } - + if (dram_free > 0) { float frag = 100.0f * (1.0f - (float)dram_largest / (float)dram_free); if (frag > 60) { @@ -718,14 +727,14 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * } } } - + if (psram_total > 0) { int psram_used_pct = 100 * (psram_total - psram_free) / psram_total; if (psram_used_pct < 50) { cJSON_AddItemToArray(tips, cJSON_CreateString("info:psram_sufficient")); } } - + ts_api_result_ok(result, data); return ESP_OK; } @@ -736,13 +745,13 @@ static esp_err_t api_system_memory_detail(const cJSON *params, ts_api_result_t * static esp_err_t api_system_apis(const cJSON *params, ts_api_result_t *result) { (void)params; - + cJSON *data = cJSON_CreateObject(); if (!data) { ts_api_result_error(result, TS_API_ERR_NO_MEM, "Memory allocation failed"); return ESP_ERR_NO_MEM; } - + // 获取所有 API 列表 cJSON *apis = ts_api_list(TS_API_CAT_MAX); // TS_API_CAT_MAX = 所有类别 if (apis) { @@ -750,14 +759,14 @@ static esp_err_t api_system_apis(const cJSON *params, ts_api_result_t *result) } else { cJSON_AddArrayToObject(data, "apis"); } - + // 添加一些统计信息 int total = 0; if (apis) { total = cJSON_GetArraySize(apis); } cJSON_AddNumberToObject(data, "total", total); - + // 检查 monitor.* API 是否存在 bool has_monitor_status = false; bool has_monitor_data = false; @@ -773,7 +782,7 @@ static esp_err_t api_system_apis(const cJSON *params, ts_api_result_t *result) } cJSON_AddBoolToObject(data, "has_monitor_status", has_monitor_status); cJSON_AddBoolToObject(data, "has_monitor_data", has_monitor_data); - + ts_api_result_ok(result, data); return ESP_OK; } @@ -787,6 +796,8 @@ esp_err_t ts_api_system_register(void) static const ts_api_endpoint_t system_apis[] = { { .name = "system.info", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get system information", .category = TS_API_CAT_SYSTEM, .handler = api_system_info, @@ -795,6 +806,8 @@ esp_err_t ts_api_system_register(void) }, { .name = "system.memory", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get memory information", .category = TS_API_CAT_SYSTEM, .handler = api_system_memory, @@ -803,14 +816,18 @@ esp_err_t ts_api_system_register(void) }, { .name = "system.memory_detail", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_READ, .description = "Get detailed memory analysis", .category = TS_API_CAT_SYSTEM, .handler = api_system_memory_detail, - .requires_auth = false, + .requires_auth = true, .permission = NULL }, { .name = "system.cpu", + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .description = "Get CPU core statistics", .category = TS_API_CAT_SYSTEM, .handler = api_system_cpu, @@ -819,22 +836,28 @@ esp_err_t ts_api_system_register(void) }, { .name = "system.tasks", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_READ, .description = "Get task list", .category = TS_API_CAT_SYSTEM, .handler = api_system_tasks, - .requires_auth = false, + .requires_auth = true, .permission = NULL }, { .name = "system.reboot", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Reboot the system", .category = TS_API_CAT_SYSTEM, .handler = api_system_reboot, - .requires_auth = false, /* TODO: Enable auth in production */ + .requires_auth = true, .permission = NULL }, { .name = "system.log.level", + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .description = "Get/set log level", .category = TS_API_CAT_SYSTEM, .handler = api_system_log_level, @@ -843,14 +866,16 @@ esp_err_t ts_api_system_register(void) }, { .name = "system.apis", + .external_access = TS_API_ACCESS_READ, + .allowed_methods = TS_API_METHOD_READ, .description = "List all registered APIs", .category = TS_API_CAT_SYSTEM, .handler = api_system_apis, - .requires_auth = false, + .requires_auth = true, .permission = NULL } }; - - return ts_api_register_multiple(system_apis, + + return ts_api_register_multiple(system_apis, sizeof(system_apis) / sizeof(system_apis[0])); } diff --git a/components/ts_api/src/ts_api_temp.c b/components/ts_api/src/ts_api_temp.c index 3fb1d88e..c5f77d58 100644 --- a/components/ts_api/src/ts_api_temp.c +++ b/components/ts_api/src/ts_api_temp.c @@ -8,11 +8,13 @@ */ #include "ts_api.h" +#include "ts_security.h" #include "ts_temp_source.h" #include "ts_variable.h" #include "ts_log.h" #include "esp_timer.h" #include +#include #define TAG "api_temp" @@ -194,6 +196,17 @@ static esp_err_t api_temp_manual(const cJSON *params, ts_api_result_t *result) esp_err_t ret = ESP_OK; /* Set manual temperature if provided */ + const cJSON *temperature = cJSON_IsNumber(temp_item) ? temp_item : temp_01c_item; + if (temperature) { + double value = temperature->valuedouble; + double scale = temperature == temp_01c_item ? 1.0 : 10.0; + if (!cJSON_IsNumber(temperature) || !isfinite(value) || + value < TS_TEMP_MIN_VALID / scale || value > TS_TEMP_MAX_VALID / scale || + (scale == 1.0 && floor(value) != value)) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid manual temperature"); + return ESP_ERR_INVALID_ARG; + } + } if (cJSON_IsNumber(temp_item)) { int16_t temp_01c = (int16_t)(temp_item->valuedouble * 10.0); ret = ts_temp_set_manual(temp_01c); @@ -541,48 +554,69 @@ static esp_err_t api_temp_bind(const cJSON *params, ts_api_result_t *result) /* Registration */ /*===========================================================================*/ +static esp_err_t api_temp_bind_for_session(const cJSON *params, uint32_t session_id, ts_api_result_t *result) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + ts_session_t caller; + if (ts_security_validate_session(session_id, &caller) != ESP_OK || caller.level < TS_PERM_ADMIN) { + ts_api_result_error(result, TS_API_ERR_AUTH, "Unauthorized"); + return ESP_ERR_NOT_ALLOWED; + } + /* Match the handler's case-insensitive legacy names, including unbind and + * malformed requests: a non-Root caller cannot enter any setter branch. */ + if ((cJSON_GetObjectItem(params, "variables") || cJSON_GetObjectItem(params, "variable")) && caller.level < TS_PERM_ROOT) { + ts_api_result_error(result, TS_API_ERR_NO_PERMISSION, "Root permission required"); + return ESP_ERR_NOT_ALLOWED; + } +#else + (void)session_id; +#endif + return api_temp_bind(params, result); +} + static const ts_api_endpoint_t s_temp_endpoints[] = { { - .name = "temp.sources", + .name = "temp.sources", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get all temperature sources info", .category = TS_API_CAT_DEVICE, // Use DEVICE category .handler = api_temp_sources, - .requires_auth = false, + .requires_auth=true, }, { - .name = "temp.read", + .name = "temp.read", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Read current temperature", .category = TS_API_CAT_DEVICE, .handler = api_temp_read, - .requires_auth = false, + .requires_auth=true, }, { - .name = "temp.manual", + .name = "temp.manual", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Set/get manual temperature mode", .category = TS_API_CAT_DEVICE, .handler = api_temp_manual, - .requires_auth = true, + .requires_auth=true, }, { - .name = "temp.status", + .name = "temp.status", .external_access=TS_API_ACCESS_PUBLIC, .allowed_methods=TS_API_METHOD_READ, .description = "Get temperature system status", .category = TS_API_CAT_DEVICE, .handler = api_temp_status, - .requires_auth = false, + .requires_auth=false, }, { - .name = "temp.select", + .name = "temp.select", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Set/get preferred temperature source", .category = TS_API_CAT_DEVICE, .handler = api_temp_select, - .requires_auth = true, + .requires_auth=true, }, { - .name = "temp.bind", + .name = "temp.bind", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Bind/unbind temperature to a system variable", .category = TS_API_CAT_DEVICE, .handler = api_temp_bind, - .requires_auth = true, + .session_handler = api_temp_bind_for_session, + .requires_auth=true, }, }; diff --git a/components/ts_api/src/ts_api_time.c b/components/ts_api/src/ts_api_time.c index d3c96d70..5c955cdd 100644 --- a/components/ts_api/src/ts_api_time.c +++ b/components/ts_api/src/ts_api_time.c @@ -14,6 +14,7 @@ #include "esp_log.h" #include #include +#include static const char *TAG = "ts_api_time"; @@ -111,7 +112,12 @@ static esp_err_t api_time_sync(const cJSON *params, ts_api_result_t *result) return ESP_ERR_INVALID_ARG; } - int64_t timestamp_ms = (int64_t)ts_json->valuedouble; + double value = ts_json->valuedouble; + if (!isfinite(value) || value < 0 || value >= 0x1p63 || floor(value) != value) { + ts_api_result_error(result, TS_API_ERR_INVALID_ARG, "Invalid timestamp_ms"); + return ESP_ERR_INVALID_ARG; + } + int64_t timestamp_ms = (int64_t)value; ESP_LOGI(TAG, "Syncing time from browser: %lld ms", (long long)timestamp_ms); @@ -255,6 +261,8 @@ esp_err_t ts_api_time_register(void) .description = "Get time sync info", .category = TS_API_CAT_SYSTEM, .handler = api_time_info, + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .requires_auth = false, }, { @@ -262,13 +270,17 @@ esp_err_t ts_api_time_register(void) .description = "Sync time from browser", .category = TS_API_CAT_SYSTEM, .handler = api_time_sync, - .requires_auth = false, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, + .requires_auth = true, }, { .name = "time.set_ntp", .description = "Set NTP server", .category = TS_API_CAT_SYSTEM, .handler = api_time_set_ntp, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -276,6 +288,8 @@ esp_err_t ts_api_time_register(void) .description = "Set timezone", .category = TS_API_CAT_SYSTEM, .handler = api_time_set_timezone, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -283,6 +297,8 @@ esp_err_t ts_api_time_register(void) .description = "Force NTP sync", .category = TS_API_CAT_SYSTEM, .handler = api_time_force_sync, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_ui.c b/components/ts_api/src/ts_api_ui.c index 1545b28e..2567555a 100644 --- a/components/ts_api/src/ts_api_ui.c +++ b/components/ts_api/src/ts_api_ui.c @@ -254,18 +254,18 @@ static esp_err_t api_ui_widgets_set(const cJSON *params, ts_api_result_t *result static const ts_api_endpoint_t ui_endpoints[] = { { - .name = "ui.widgets.get", + .name = "ui.widgets.get", .external_access=TS_API_ACCESS_READ, .allowed_methods=TS_API_METHOD_READ, .description = "Get data widgets configuration", .category = TS_API_CAT_SYSTEM, .handler = api_ui_widgets_get, - .requires_auth = false, + .requires_auth=true, }, { - .name = "ui.widgets.set", + .name = "ui.widgets.set", .external_access=TS_API_ACCESS_ADMIN, .allowed_methods=TS_API_METHOD_WRITE, .description = "Save data widgets configuration", .category = TS_API_CAT_SYSTEM, .handler = api_ui_widgets_set, - .requires_auth = true, + .requires_auth=true, }, }; diff --git a/components/ts_api/src/ts_api_wifi.c b/components/ts_api/src/ts_api_wifi.c index 0d3ad753..56924361 100644 --- a/components/ts_api/src/ts_api_wifi.c +++ b/components/ts_api/src/ts_api_wifi.c @@ -217,6 +217,8 @@ esp_err_t ts_api_wifi_register(void) .description = "Get WiFi status", .category = TS_API_CAT_NETWORK, .handler = api_wifi_status, + .external_access = TS_API_ACCESS_PUBLIC, + .allowed_methods = TS_API_METHOD_READ, .requires_auth = false, }, { @@ -224,13 +226,17 @@ esp_err_t ts_api_wifi_register(void) .description = "Scan for WiFi networks", .category = TS_API_CAT_NETWORK, .handler = api_wifi_scan, - .requires_auth = false, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, + .requires_auth = true, }, { .name = "wifi.connect", .description = "Connect to WiFi network", .category = TS_API_CAT_NETWORK, .handler = api_wifi_connect, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, { @@ -238,6 +244,8 @@ esp_err_t ts_api_wifi_register(void) .description = "Disconnect from WiFi", .category = TS_API_CAT_NETWORK, .handler = api_wifi_disconnect, + .external_access = TS_API_ACCESS_ADMIN, + .allowed_methods = TS_API_METHOD_WRITE, .requires_auth = true, }, }; diff --git a/components/ts_api/src/ts_api_ws_test_transport.c b/components/ts_api/src/ts_api_ws_test_transport.c new file mode 100644 index 00000000..75244dfe --- /dev/null +++ b/components/ts_api/src/ts_api_ws_test_transport.c @@ -0,0 +1,174 @@ +#include "ts_api_ws_test_transport.h" +#include "ts_http_url.h" +#include "ts_dns.h" +#include "esp_transport_tcp.h" +#include "esp_transport_ssl.h" +#include "esp_transport_ws.h" +#include "esp_crt_bundle.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "mbedtls/base64.h" +#include +#include +#include + +/* Use the same nonblocking SDK primitives as the existing HTTP owner. Neither + * a stalled DNS lookup nor another partial frame may renew the operation. */ +static int64_t call_deadline(ts_api_ws_test_transport_t *owner, int timeout_ms) +{ + if (timeout_ms < 0) return owner->deadline; + int64_t requested = esp_timer_get_time() + (int64_t)timeout_ms * 1000; + return requested < owner->deadline ? requested : owner->deadline; +} + +static int wait_ready(ts_api_ws_test_transport_t *owner, bool writing, int64_t until) +{ + for (;;) { + if (esp_timer_get_time() >= owner->deadline) { errno = ETIMEDOUT; return -1; } + int ready = writing ? esp_transport_poll_write(owner->socket, 0) : + esp_transport_poll_read(owner->socket, 0); + if (ready != 0) return ready; + if (esp_timer_get_time() >= until) return 0; + vTaskDelay(1); + } +} + +static int bounded_connect(esp_transport_handle_t transport, const char *host, int port, int timeout_ms) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + int64_t until = call_deadline(owner, timeout_ms); + ip_addr_t address; + if (ts_dns_resolve(host, until, NULL, NULL, &address) != ESP_OK) return -1; + char numeric[64]; + if (!ipaddr_ntoa_r(&address, numeric, sizeof(numeric))) return -1; + while (esp_timer_get_time() < until) { + int ret = esp_transport_connect_async(owner->socket, numeric, port, 0); + if (ret != 0) return ret > 0 && esp_timer_get_time() < until ? 0 : -1; + vTaskDelay(1); + } + errno = ETIMEDOUT; + return -1; +} + +static int bounded_read(esp_transport_handle_t transport, char *buffer, int length, int timeout_ms) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + int64_t until = call_deadline(owner, timeout_ms); + for (;;) { + int ready = wait_ready(owner, false, until); + if (ready <= 0) { if (!ready) errno = EAGAIN; return -1; } + int ret = esp_transport_read(owner->socket, buffer, length, 0); + if (ret >= 0) return esp_timer_get_time() < owner->deadline ? ret : -1; + if ((errno != EAGAIN && errno != EWOULDBLOCK) || esp_timer_get_time() >= until) return -1; + } +} + +static int bounded_write(esp_transport_handle_t transport, const char *buffer, int length, int timeout_ms) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + int64_t until = call_deadline(owner, timeout_ms); + for (;;) { + int ready = wait_ready(owner, true, until); + if (ready <= 0) { if (!ready) errno = EAGAIN; return -1; } + int ret = esp_transport_write(owner->socket, buffer, length, 0); + if (ret >= 0) return esp_timer_get_time() < owner->deadline ? ret : -1; + if ((errno != EAGAIN && errno != EWOULDBLOCK) || esp_timer_get_time() >= until) return -1; + } +} + +static int bounded_poll_read(esp_transport_handle_t transport, int timeout_ms) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + return wait_ready(owner, false, call_deadline(owner, timeout_ms)); +} + +static int bounded_poll_write(esp_transport_handle_t transport, int timeout_ms) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + return wait_ready(owner, true, call_deadline(owner, timeout_ms)); +} + +static int bounded_close(esp_transport_handle_t transport) +{ + ts_api_ws_test_transport_t *owner = esp_transport_get_context_data(transport); + return esp_transport_close(owner->socket); +} + +static int bounded_destroy(esp_transport_handle_t transport) +{ + (void)transport; /* The diagnostic owner releases each handle once. */ + return 0; +} + +void ts_api_ws_test_transport_destroy(ts_api_ws_test_transport_t *owner) +{ + if (owner->websocket) esp_transport_destroy(owner->websocket); + if (owner->bounded) esp_transport_destroy(owner->bounded); + if (owner->socket) esp_transport_destroy(owner->socket); + memset(owner, 0, sizeof(*owner)); +} + +esp_err_t ts_api_ws_test_transport_init(ts_api_ws_test_transport_t *owner, + const char *uri, int64_t deadline) +{ + memset(owner, 0, sizeof(*owner)); + struct http_parser_url parsed; + if (!ts_ws_url_parse(uri, &parsed) || parsed.field_data[UF_HOST].len >= sizeof(owner->hostname)) + return ESP_ERR_INVALID_ARG; + if (esp_timer_get_time() >= deadline) return ESP_ERR_TIMEOUT; + memcpy(owner->hostname, uri + parsed.field_data[UF_HOST].off, parsed.field_data[UF_HOST].len); + bool secure = parsed.field_data[UF_SCHEMA].len == 3; + owner->port = parsed.field_set & (1U << UF_PORT) ? parsed.port : secure ? 443 : 80; + owner->deadline = deadline; + owner->socket = secure ? esp_transport_ssl_init() : esp_transport_tcp_init(); + owner->bounded = esp_transport_init(); + esp_err_t result = ESP_ERR_NO_MEM; + char *path = NULL, *credentials = NULL, *auth = NULL; + if (!owner->socket || !owner->bounded) goto done; + if (secure) { + /* SDK borrows this name; the owner survives the joined client worker. */ + esp_transport_ssl_set_common_name(owner->socket, owner->hostname); + esp_transport_ssl_crt_bundle_attach(owner->socket, esp_crt_bundle_attach); + } + esp_transport_set_context_data(owner->bounded, owner); + esp_transport_set_func(owner->bounded, bounded_connect, bounded_read, bounded_write, + bounded_close, bounded_poll_read, bounded_poll_write, bounded_destroy); + owner->websocket = esp_transport_ws_init(owner->bounded); + if (!owner->websocket) goto done; + size_t path_len = parsed.field_data[UF_PATH].len; + size_t query_len = parsed.field_data[UF_QUERY].len; + path = malloc(path_len + query_len + 3); + if (!path) goto done; + size_t used = 0; + if (path_len) { memcpy(path, uri + parsed.field_data[UF_PATH].off, path_len); used = path_len; } + else path[used++] = '/'; + if (query_len) { + path[used++] = '?'; + memcpy(path + used, uri + parsed.field_data[UF_QUERY].off, query_len); used += query_len; + } + path[used] = 0; + size_t user_len = parsed.field_data[UF_USERINFO].len; + if (user_len) { + credentials = malloc(user_len + 2); + if (!credentials) goto done; + memcpy(credentials, uri + parsed.field_data[UF_USERINFO].off, user_len); + if (!memchr(credentials, ':', user_len)) credentials[user_len++] = ':'; + credentials[user_len] = 0; + size_t capacity = 4 * ((user_len + 2) / 3) + 1, written; + auth = malloc(capacity + 6); + if (!auth) goto done; + memcpy(auth, "Basic ", 6); + if (mbedtls_base64_encode((unsigned char *)auth + 6, capacity, &written, + (const unsigned char *)credentials, user_len) != 0) { + result = ESP_FAIL; goto done; + } + auth[6 + written] = 0; + } + const esp_transport_ws_config_t config = {.ws_path = path, .auth = auth, .propagate_control_frames = true}; + result = esp_transport_ws_set_config(owner->websocket, &config); +done: + free(auth); free(credentials); free(path); + if (result != ESP_OK) ts_api_ws_test_transport_destroy(owner); + return result; +} diff --git a/components/ts_api/src/ts_api_ws_test_transport.h b/components/ts_api/src/ts_api_ws_test_transport.h new file mode 100644 index 00000000..52597b46 --- /dev/null +++ b/components/ts_api/src/ts_api_ws_test_transport.h @@ -0,0 +1,17 @@ +#pragma once +#include +#include "esp_err.h" +#include "esp_transport.h" + +/* Private to the two one-shot API diagnostics. The SDK client borrows websocket; + * stop/destroy the client before releasing this stack-owned transport context. */ +typedef struct { + esp_transport_handle_t socket, bounded, websocket; + int64_t deadline; + int port; + char hostname[256]; +} ts_api_ws_test_transport_t; + +esp_err_t ts_api_ws_test_transport_init(ts_api_ws_test_transport_t *owner, + const char *uri, int64_t deadline); +void ts_api_ws_test_transport_destroy(ts_api_ws_test_transport_t *owner); diff --git a/components/ts_auth_layout/CMakeLists.txt b/components/ts_auth_layout/CMakeLists.txt index f0f73a8c..232af23e 100644 --- a/components/ts_auth_layout/CMakeLists.txt +++ b/components/ts_auth_layout/CMakeLists.txt @@ -1,4 +1,6 @@ idf_component_register( - INCLUDE_DIRS - "include" + SRCS "src/ts_auth_credential.c" + INCLUDE_DIRS "include" + REQUIRES esp_common + PRIV_REQUIRES mbedtls esp_hw_support ) diff --git a/components/ts_auth_layout/include/ts_auth_layout.h b/components/ts_auth_layout/include/ts_auth_layout.h index 0364c3a5..c4845041 100644 --- a/components/ts_auth_layout/include/ts_auth_layout.h +++ b/components/ts_auth_layout/include/ts_auth_layout.h @@ -9,6 +9,7 @@ #include #include #include +#include "esp_err.h" #define TS_AUTH_NVS_NAMESPACE "ts_auth" #define TS_AUTH_ROOT_CRED_KEY "cred_root" @@ -17,6 +18,11 @@ #define TS_AUTH_DEFAULT_ROOT_PASSWORD "rm01" #define TS_AUTH_DEFAULT_ADMIN_PASSWORD "rm01" #define TS_AUTH_CONFIG_VERSION 3 +#define TS_AUTH_PROTOTYPE_CONFIG_VERSION 4 +#define TS_AUTH_LEGACY_CONFIG_VERSION 3 +#define TS_AUTH_CREDENTIAL_MAGIC 0x34464b50U +#define TS_AUTH_KDF_MIN_ROUNDS 10000U +#define TS_AUTH_KDF_MAX_ROUNDS 200000U #define TS_AUTH_SALT_LEN 16 #define TS_AUTH_HASH_LEN 32 @@ -27,9 +33,14 @@ typedef struct { bool password_changed; uint32_t failed_attempts; uint32_t lockout_until; + uint32_t format; + uint32_t rounds; } ts_auth_user_credential_t; +#define TS_AUTH_LEGACY_CREDENTIAL_SIZE 60 #define TS_AUTH_USER_CREDENTIAL_SIZE 60 +/* Read bridge for the unreleased API prototype; never written by this firmware. */ +#define TS_AUTH_MAX_CREDENTIAL_SIZE 68 #if defined(__cplusplus) static_assert(offsetof(ts_auth_user_credential_t, salt) == 0, "auth salt offset changed"); @@ -37,14 +48,35 @@ static_assert(offsetof(ts_auth_user_credential_t, hash) == 16, "auth hash offset static_assert(offsetof(ts_auth_user_credential_t, password_changed) == 48, "auth password_changed offset changed"); static_assert(offsetof(ts_auth_user_credential_t, failed_attempts) == 52, "auth failed_attempts offset changed"); static_assert(offsetof(ts_auth_user_credential_t, lockout_until) == 56, "auth lockout_until offset changed"); -static_assert(sizeof(ts_auth_user_credential_t) == TS_AUTH_USER_CREDENTIAL_SIZE, "auth credential size changed"); +static_assert(offsetof(ts_auth_user_credential_t, format) == 60, "auth format offset changed"); +static_assert(offsetof(ts_auth_user_credential_t, rounds) == 64, "auth rounds offset changed"); +static_assert(sizeof(ts_auth_user_credential_t) == TS_AUTH_MAX_CREDENTIAL_SIZE, "auth credential size changed"); #else _Static_assert(offsetof(ts_auth_user_credential_t, salt) == 0, "auth salt offset changed"); _Static_assert(offsetof(ts_auth_user_credential_t, hash) == 16, "auth hash offset changed"); _Static_assert(offsetof(ts_auth_user_credential_t, password_changed) == 48, "auth password_changed offset changed"); _Static_assert(offsetof(ts_auth_user_credential_t, failed_attempts) == 52, "auth failed_attempts offset changed"); _Static_assert(offsetof(ts_auth_user_credential_t, lockout_until) == 56, "auth lockout_until offset changed"); -_Static_assert(sizeof(ts_auth_user_credential_t) == TS_AUTH_USER_CREDENTIAL_SIZE, "auth credential size changed"); +_Static_assert(offsetof(ts_auth_user_credential_t, format) == 60, "auth format offset changed"); +_Static_assert(offsetof(ts_auth_user_credential_t, rounds) == 64, "auth rounds offset changed"); +_Static_assert(sizeof(ts_auth_user_credential_t) == TS_AUTH_MAX_CREDENTIAL_SIZE, "auth credential size changed"); +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Writes use the original 60-byte v3 format. The internal view can also read + * the old prototype for conversion after correct password verification. */ +esp_err_t ts_auth_credential_decode(const void *bytes, size_t length, + ts_auth_user_credential_t *credential); +esp_err_t ts_auth_credential_create(const char *password, bool changed, + ts_auth_user_credential_t *credential); +esp_err_t ts_auth_credential_verify(const ts_auth_user_credential_t *credential, + const char *password, bool *matches); + +#ifdef __cplusplus +} #endif #endif /* TS_AUTH_LAYOUT_H */ diff --git a/components/ts_auth_layout/src/ts_auth_credential.c b/components/ts_auth_layout/src/ts_auth_credential.c new file mode 100644 index 00000000..2fe0ab37 --- /dev/null +++ b/components/ts_auth_layout/src/ts_auth_credential.c @@ -0,0 +1,83 @@ +#include "ts_auth_layout.h" +#include "esp_random.h" +#include "mbedtls/pkcs5.h" +#include "mbedtls/sha256.h" +#include "mbedtls/platform_util.h" +#include + +/* Stored parameters bound both verification cost and accepted formats. */ +static bool credential_format_valid(const ts_auth_user_credential_t *credential) +{ + return credential->format == TS_AUTH_CREDENTIAL_MAGIC && + credential->rounds >= TS_AUTH_KDF_MIN_ROUNDS && + credential->rounds <= TS_AUTH_KDF_MAX_ROUNDS; +} + +esp_err_t ts_auth_credential_decode(const void *bytes, size_t length, + ts_auth_user_credential_t *credential) +{ + if (!bytes || !credential) return ESP_ERR_INVALID_ARG; + if (length != TS_AUTH_LEGACY_CREDENTIAL_SIZE && length != sizeof(*credential)) + return ESP_ERR_INVALID_SIZE; + /* Validate the persisted bool representation before accessing it as bool. */ + if (((const uint8_t *)bytes)[offsetof(ts_auth_user_credential_t, password_changed)] > 1) + return ESP_ERR_INVALID_STATE; + memmove(credential, bytes, length); + if (length == TS_AUTH_LEGACY_CREDENTIAL_SIZE) + memset((unsigned char *)credential + length, 0, sizeof(*credential) - length); + if (length == TS_AUTH_LEGACY_CREDENTIAL_SIZE || credential_format_valid(credential)) + return ESP_OK; + mbedtls_platform_zeroize(credential, sizeof(*credential)); + return ESP_ERR_INVALID_STATE; +} + +static esp_err_t credential_hash(const ts_auth_user_credential_t *credential, + const char *password, uint8_t hash[TS_AUTH_HASH_LEN]) +{ + size_t length = strlen(password); + if (length > 64) return ESP_ERR_INVALID_ARG; + if (credential_format_valid(credential)) + return mbedtls_pkcs5_pbkdf2_hmac_ext(MBEDTLS_MD_SHA256, + (const unsigned char *)password, length, credential->salt, TS_AUTH_SALT_LEN, + credential->rounds, TS_AUTH_HASH_LEN, hash) == 0 ? ESP_OK : ESP_FAIL; + if (credential->format || credential->rounds) return ESP_ERR_INVALID_STATE; + /* Original v3 password scheme; no new storage format is emitted. */ + unsigned char material[TS_AUTH_SALT_LEN + 64]; + memcpy(material, credential->salt, TS_AUTH_SALT_LEN); + memcpy(material + TS_AUTH_SALT_LEN, password, length); + int result = mbedtls_sha256(material, TS_AUTH_SALT_LEN + length, hash, 0); + mbedtls_platform_zeroize(material, sizeof(material)); + return result == 0 ? ESP_OK : ESP_FAIL; +} + + +esp_err_t ts_auth_credential_create(const char *password, bool changed, + ts_auth_user_credential_t *credential) +{ + if (!password || !credential || strlen(password) < 4 || strlen(password) > 64) + return ESP_ERR_INVALID_ARG; + memset(credential, 0, sizeof(*credential)); + /* Original v3 salt + SHA-256 layout, also readable by stock 0.6.4. */ + esp_fill_random(credential->salt, TS_AUTH_SALT_LEN); + esp_err_t ret = credential_hash(credential, password, credential->hash); + if (ret != ESP_OK) mbedtls_platform_zeroize(credential, sizeof(*credential)); + else credential->password_changed = changed; + return ret; +} + +esp_err_t ts_auth_credential_verify(const ts_auth_user_credential_t *credential, + const char *password, bool *matches) +{ + if (!credential || !password || !matches) return ESP_ERR_INVALID_ARG; + *matches = false; + uint8_t computed[TS_AUTH_HASH_LEN]; + esp_err_t ret = credential_hash(credential, password, computed); + if (ret == ESP_OK) { + unsigned char difference = 0; + for (size_t i = 0; i < sizeof(computed); ++i) + difference |= computed[i] ^ credential->hash[i]; + *matches = difference == 0; + } + mbedtls_platform_zeroize(computed, sizeof(computed)); + return ret; +} diff --git a/components/ts_automation/CMakeLists.txt b/components/ts_automation/CMakeLists.txt index 4ffcad26..711aa424 100644 --- a/components/ts_automation/CMakeLists.txt +++ b/components/ts_automation/CMakeLists.txt @@ -26,6 +26,7 @@ idf_component_register( ts_storage json PRIV_REQUIRES + ts_http_fetch ts_api ts_led ts_hal diff --git a/components/ts_automation/include/ts_source_manager.h b/components/ts_automation/include/ts_source_manager.h index 19efa944..0cadcf82 100644 --- a/components/ts_automation/include/ts_source_manager.h +++ b/components/ts_automation/include/ts_source_manager.h @@ -171,8 +171,9 @@ bool ts_source_ws_is_connected(const char *id); /* Socket.IO Sources */ /*===========================================================================*/ -/* Both the test and the runtime upgrade the same polling URL. */ -void ts_source_sio_websocket_url(const char *base_url, const char *sid, char *out, size_t size); +/* Shared by runtime and diagnostics: NULL sid builds polling; otherwise WS + * upgrade. Validates the base, escapes the opaque sid, never truncates output. */ +bool ts_source_sio_url(const char *base_url, const char *sid, char *out, size_t size); /** * @brief Connect Socket.IO source diff --git a/components/ts_automation/src/ts_action_manager.c b/components/ts_automation/src/ts_action_manager.c index dd96a45b..fee96503 100644 --- a/components/ts_automation/src/ts_action_manager.c +++ b/components/ts_automation/src/ts_action_manager.c @@ -1,3 +1,4 @@ +#include "ts_http_fetch.h" #include "ts_action_codec.h" #include "ts_action_filter.h" #include "ts_automation_config.h" @@ -34,7 +35,6 @@ #include "ts_led_animation.h" #include "ts_hal.h" #include "ts_device_ctrl.h" -#include "esp_http_client.h" #include "ts_core.h" #include "ts_console.h" #include "ts_storage.h" @@ -705,13 +705,13 @@ static esp_err_t exec_ssh_bound(const ts_auto_action_ssh_t *ssh,const ts_action_ config.auth.key.private_key = (const uint8_t *)key_data; config.auth.key.private_key_len = key_len; config.auth.key.private_key_path = NULL; - ESP_LOGI(TAG, "Loaded SSH key '%s' from keystore (%zu bytes)", keyid, key_len); + ESP_LOGI(TAG, "Loaded SSH key from keystore (%zu bytes)", key_len); } else { free(key_data); free(expanded_cmd); result->reason="ssh_key_unavailable"; result->status=TS_ACTION_STATUS_FAILED; - snprintf(result->output,sizeof(result->output),"SSH key unavailable: %s",keyid); + snprintf(result->output,sizeof(result->output),"SSH key unavailable"); return ret==ESP_OK?ESP_ERR_INVALID_STATE:ret; } } else { @@ -1385,54 +1385,21 @@ static esp_err_t execute_webhook(const ts_auto_action_t *action) return ESP_ERR_INVALID_ARG; } - ESP_LOGI(TAG, "Webhook action: url=%s, method=%s", - action->webhook.url, action->webhook.method); - - esp_http_client_config_t config = { - .url = action->webhook.url, - .timeout_ms = 5000, // 默认 5 秒超时 - }; - - esp_http_client_handle_t client = esp_http_client_init(&config); - if (!client) { - ESP_LOGE(TAG, "Failed to create HTTP client"); - return ESP_ERR_NO_MEM; - } - - // 设置方法 - if (strcasecmp(action->webhook.method, "POST") == 0) { - esp_http_client_set_method(client, HTTP_METHOD_POST); - } else if (strcasecmp(action->webhook.method, "PUT") == 0) { - esp_http_client_set_method(client, HTTP_METHOD_PUT); - } else { - esp_http_client_set_method(client, HTTP_METHOD_GET); - } - - // 设置 Content-Type (对于 POST/PUT) - if (strcasecmp(action->webhook.method, "POST") == 0 || - strcasecmp(action->webhook.method, "PUT") == 0) { - esp_http_client_set_header(client, "Content-Type", "application/json"); - } - - // 设置 body(使用 body_template) - if (action->webhook.body_template[0] != '\0') { - esp_http_client_set_post_field(client, action->webhook.body_template, - strlen(action->webhook.body_template)); - } - - esp_err_t ret = esp_http_client_perform(client); - if (ret == ESP_OK) { - int status = esp_http_client_get_status_code(client); - ESP_LOGI(TAG, "Webhook response: %d", status); - - if (status < 200 || status >= 300) { - ret = ESP_FAIL; // 非 2xx 视为失败 - } - } else { - ESP_LOGE(TAG, "Webhook request failed: %s", esp_err_to_name(ret)); - } - - esp_http_client_cleanup(client); + ESP_LOGI(TAG, "Webhook action started"); + + esp_http_client_method_t method; + if (!strcasecmp(action->webhook.method, "POST")) method = HTTP_METHOD_POST; + else if (!strcasecmp(action->webhook.method, "PUT")) method = HTTP_METHOD_PUT; + else if (!strcasecmp(action->webhook.method, "GET")) method = HTTP_METHOD_GET; + else return ESP_ERR_INVALID_ARG; + ts_http_fetch_config_t request = {.url = action->webhook.url, .method = method, + .content_type = method == HTTP_METHOD_POST || method == HTTP_METHOD_PUT ? "application/json" : NULL, + .body = action->webhook.body_template[0] ? action->webhook.body_template : NULL, + .timeout_ms = 5000, .maximum_body = 8192, .headers_only = true}; + ts_http_fetch_result_t reply = {0}; + esp_err_t ret = ts_http_fetch(&request, &reply); + if (ret == ESP_OK && (reply.status < 200 || reply.status >= 300)) ret = ESP_FAIL; + free(reply.body); return ret; } @@ -1632,8 +1599,7 @@ static esp_err_t exec_ssh_ref_bound(const ts_auto_action_ssh_ref_t *ssh_ref, ESP_LOGI(TAG, "SSH ref [%s]: host=%s, command_bytes=%u", ssh_ref->cmd_id, cmd_config.host_id, (unsigned)strlen(cmd_config.command)); - ESP_LOGI(TAG, "SSH ref config: var_name='%s', nohup=%d, service_mode=%d, ready_pattern='%s'", - cmd_config.var_name, cmd_config.nohup, cmd_config.service_mode, cmd_config.ready_pattern); + ESP_LOGI(TAG, "SSH service options: nohup=%d, service_mode=%d, has_ready_pattern=%d", cmd_config.nohup, cmd_config.service_mode, cmd_config.ready_pattern[0] != 0); const ts_action_ssh_host_t host=binding->host; @@ -1703,12 +1669,12 @@ static esp_err_t exec_ssh_ref_bound(const ts_auto_action_ssh_ref_t *ssh_ref, config.auth.key.private_key = (const uint8_t *)key_data; config.auth.key.private_key_len = key_len; config.auth.key.private_key_path = NULL; - ESP_LOGI(TAG, "Loaded SSH key '%s' from keystore (%zu bytes)", keyid, key_len); + ESP_LOGI(TAG, "Loaded SSH key from keystore (%zu bytes)", key_len); } else { if(cmd_config.nohup)ts_ssh_service_set_operation_reason(run_id,launch_id,"ssh_key_unavailable"); free(key_data);free(expanded_cmd);free(nohup_cmd); result->reason="ssh_key_unavailable";result->status=TS_ACTION_STATUS_FAILED; - snprintf(result->output,sizeof(result->output),"SSH key unavailable: %s",keyid); + snprintf(result->output,sizeof(result->output),"SSH key unavailable"); return ret==ESP_OK?ESP_ERR_INVALID_STATE:ret; } } else { @@ -1837,8 +1803,7 @@ static esp_err_t exec_ssh_ref_bound(const ts_auto_action_ssh_ref_t *ssh_ref, if (watch_ret != ESP_OK) ts_ssh_service_observe(run_id, run_generation, "unknown"); if (watch_ret == ESP_OK) { - ESP_LOGI(TAG, "🔍 Service mode: watching log for '%s' (fail='%s', timeout: %us)", - cmd_config.ready_pattern, cmd_config.service_fail_pattern, watch_config.timeout_sec); + ESP_LOGI(TAG, "Service log watch started (timeout=%u s)", watch_config.timeout_sec); } else { ESP_LOGW(TAG, "Failed to start log watch: %s", esp_err_to_name(watch_ret)); } diff --git a/components/ts_automation/src/ts_automation_file.c b/components/ts_automation/src/ts_automation_file.c index 2a950f4c..ae294920 100644 --- a/components/ts_automation/src/ts_automation_file.c +++ b/components/ts_automation/src/ts_automation_file.c @@ -1,9 +1,9 @@ #include "ts_automation_file.h" +#include "ts_file_store.h" #include "ts_config_partitions.h" #include "ts_crypto.h" #include "cJSON.h" #include "esp_heap_caps.h" -#include "esp_log.h" #include #include #include @@ -12,11 +12,8 @@ #include #define MAX_BYTES 0x200000U -static const char *TAG = "automation_file"; -typedef struct { - const char *current, *pending, *previous; -} paths_t; +typedef ts_file_store_paths_t paths_t; static const paths_t s_paths[] = { {TS_CONFIG_AUTO_SD_DIR "/state.json", TS_CONFIG_AUTO_SD_DIR "/state.pending", @@ -30,18 +27,6 @@ static esp_err_t io_error(void) return errno == ENOSPC ? ESP_ERR_INVALID_SIZE : ESP_FAIL; } -static int exists(const char *path) -{ - struct stat st; - if (stat(path, &st) == 0) return 1; - return errno == ENOENT ? 0 : -1; -} - -static bool remove_file(const char *path) -{ - return unlink(path) == 0 || errno == ENOENT; -} - static bool valid_document(const char *text, size_t size) { cJSON *json = cJSON_ParseWithLengthOpts(text, size + 1, NULL, true); @@ -88,50 +73,15 @@ static esp_err_t read_file(const char *path, char **out) return ret; } -static esp_err_t write_pending(const char *path, const char *json) +static esp_err_t validate_file(const char *path, void *context) { - FILE *file = fopen(path, "wb"); - if (!file) return io_error(); - size_t size = strlen(json); - esp_err_t ret = fwrite(json, 1, size, file) == size ? ESP_OK : io_error(); - if (fflush(file) != 0 && ret == ESP_OK) ret = io_error(); - if (fsync(fileno(file)) != 0 && ret == ESP_OK) ret = io_error(); - if (fclose(file) != 0 && ret == ESP_OK) ret = io_error(); - if (ret != ESP_OK) return ret; - char *readback = NULL; - ret = read_file(path, &readback); - if (ret == ESP_OK && strcmp(readback, json)) ret = ESP_FAIL; - free(readback); + (void)context; + char *text = NULL; + esp_err_t ret = read_file(path, &text); + free(text); return ret; } -/* Complete just one interrupted replacement. No search of legacy stores, - * source switching, or persistent history is performed here. */ -static esp_err_t recover(const paths_t *p, bool writing) -{ - int current = exists(p->current), pending = exists(p->pending), previous = exists(p->previous); - if (current < 0 || pending < 0 || previous < 0) return ESP_ERR_NOT_FINISHED; - if (pending) { - if (previous) { - if (current) return ESP_ERR_NOT_FINISHED; - if (rename(p->previous, p->current) != 0) return ESP_ERR_NOT_FINISHED; - } - return remove_file(p->pending) ? ESP_OK : ESP_FAIL; - } - if (!previous) return ESP_OK; - if (!current) - return rename(p->previous, p->current) == 0 ? ESP_OK : ESP_ERR_NOT_FINISHED; - char *committed = NULL; - esp_err_t ret = read_file(p->current, &committed); - free(committed); - if (ret != ESP_OK) return ESP_ERR_NOT_FINISHED; - if (!remove_file(p->previous)) { - ESP_LOGW(TAG, "Configuration saved; previous-file cleanup is pending"); - return writing ? ESP_FAIL : ESP_OK; - } - return ESP_OK; -} - static esp_err_t ensure_sd_directory(void) { const char *paths[] = {TS_CONFIG_AUTO_SD_PARENT, TS_CONFIG_AUTO_SD_DIR}; @@ -150,7 +100,7 @@ esp_err_t ts_auto_file_load(ts_auto_file_location_t location, char **json) return ESP_ERR_INVALID_ARG; *json = NULL; const paths_t *p = &s_paths[location]; - esp_err_t ret = recover(p, false); + esp_err_t ret = ts_file_store_recover(p, false, validate_file, NULL); return ret == ESP_OK ? read_file(p->current, json) : ret; } @@ -159,7 +109,7 @@ esp_err_t ts_auto_file_fingerprint(ts_auto_file_location_t location,char digest[ if(!digest || (unsigned)location>=sizeof(s_paths)/sizeof(s_paths[0]))return ESP_ERR_INVALID_ARG; digest[0]=0; const paths_t *paths=&s_paths[location]; - esp_err_t ret=recover(paths,false); + esp_err_t ret=ts_file_store_recover(paths, false, validate_file, NULL); char *bytes=NULL;size_t length=0;unsigned char hash[32]; if(ret==ESP_OK)ret=read_bytes(paths->current,&bytes,&length); if(ret==ESP_OK)ret=ts_crypto_hash(TS_HASH_SHA256,bytes,length,hash,sizeof(hash)); @@ -176,37 +126,6 @@ esp_err_t ts_auto_file_save(ts_auto_file_location_t location, const char *json) if (!valid_document(json, size)) return ESP_ERR_INVALID_ARG; esp_err_t ret = location == TS_AUTO_FILE_SD ? ensure_sd_directory() : ESP_OK; const paths_t *p = &s_paths[location]; - if (ret == ESP_OK) ret = recover(p, true); if (ret != ESP_OK) return ret; - ret = write_pending(p->pending, json); - if (ret != ESP_OK) goto uncommitted; - int current = exists(p->current); - if (current < 0) { ret = ESP_FAIL; goto uncommitted; } - if (current && rename(p->current, p->previous) != 0) { - ret = io_error(); - goto uncommitted; - } - if (rename(p->pending, p->current) != 0) { - ret = io_error(); - /* Some drivers report an error after rename took effect. Check the - * actual installed bytes before saying the save failed. */ - char *installed = NULL; - int pending = exists(p->pending); - esp_err_t observed = read_file(p->current, &installed); - bool committed = pending == 0 && observed == ESP_OK && !strcmp(installed, json); - free(installed); - if (!committed) { - if (pending != 1 || (observed != ESP_ERR_NOT_FOUND && observed != ESP_OK)) - return ESP_ERR_NOT_FINISHED; - goto uncommitted; - } - } - /* The new complete document now has the target name: commit succeeded. - * Cleanup failure cannot turn it into a reported failed save. */ - if (!remove_file(p->previous)) - ESP_LOGW(TAG, "Configuration saved; previous-file cleanup is pending"); - return ESP_OK; - -uncommitted: - return recover(p, false) == ESP_OK ? ret : ESP_ERR_NOT_FINISHED; + return ts_file_store_replace(p, json, size, TS_FILE_STORE_FIXED, validate_file, NULL); } diff --git a/components/ts_automation/src/ts_automation_legacy.c b/components/ts_automation/src/ts_automation_legacy.c index 85412867..1d7d90b7 100644 --- a/components/ts_automation/src/ts_automation_legacy.c +++ b/components/ts_automation/src/ts_automation_legacy.c @@ -135,7 +135,7 @@ static esp_err_t file_bytes(const char *path, char **out, size_t *length) } static esp_err_t load_json(const char *path, bool encrypted, ts_auto_config_kind_t kind, - const ts_config_pack_acceptance_t *accepted, cJSON **out, + cJSON **out, ts_auto_config_error_t *error) { *out = NULL; @@ -146,14 +146,12 @@ static esp_err_t load_json(const char *path, bool encrypted, ts_auto_config_kind if (encrypted) { ts_config_pack_t *pack = NULL; ts_config_pack_acceptance_t proof = {0}; - /* Preserve each installed manager's original verification policy. - * Guarded rule packages retain their explicit signer acceptance; the - * other installed files use the same signature/recipient loader as - * their former SD-priority managers. This is not a failed-check retry. */ - ts_config_pack_result_t got = kind == TS_AUTO_CONFIG_RULE - ? ts_config_pack_load_verified_mem(text, length, accepted, &pack, &proof, NULL) - : ts_config_pack_load_mem(text, length, &pack); + /* All legacy SD files use the same pinned-publisher owner and exact + * internal acceptance. The existing selected-rule journal below keeps + * its explicit provenance verification; it is not reinterpreted here. */ + ts_config_pack_result_t got = ts_config_pack_load_rule_mem(text, length, &pack); if (got == TS_CONFIG_PACK_OK) { + proof = pack->acceptance; *out = ts_config_pack_parse_json(pack->content, pack->content_len); ts_config_pack_free(pack); const cJSON *type = cJSON_GetObjectItemCaseSensitive(*out, "type"); @@ -176,6 +174,7 @@ static esp_err_t load_json(const char *path, bool encrypted, ts_auto_config_kind } } else *out = ts_config_pack_parse_json(text, length); free(text); + if (ret != ESP_OK) { cJSON_Delete(*out); *out = NULL; } return ret != ESP_OK ? ret : *out ? ESP_OK : ESP_ERR_INVALID_ARG; } @@ -185,10 +184,10 @@ static esp_err_t priority_json(const char *base, ts_auto_config_kind_t kind, cJS char path[256]; if (snprintf(path, sizeof(path), "%s.tscfg", base) >= sizeof(path)) return ESP_ERR_INVALID_SIZE; struct stat st; - if (stat(path, &st) == 0) return load_json(path, true, kind, NULL, out, error); + if (stat(path, &st) == 0) return load_json(path, true, kind, out, error); if (errno != ENOENT) return ESP_FAIL; if (snprintf(path, sizeof(path), "%s.json", base) >= sizeof(path)) return ESP_ERR_INVALID_SIZE; - return load_json(path, false, kind, NULL, out, error); + return load_json(path, false, kind, out, error); } static const cJSON *unwrap(const cJSON *json, ts_auto_config_kind_t kind) @@ -270,7 +269,7 @@ static esp_err_t directory(cJSON *array, ts_auto_config_kind_t kind, const char } snprintf(path, sizeof(path), LEGACY_CONFIG_DIR "/%s/%s%s", name, id, encrypted ? ".tscfg" : ".json"); cJSON *json = NULL; - ret = load_json(path, encrypted, kind, NULL, &json, error); + ret = load_json(path, encrypted, kind, &json, error); if (ret == ESP_OK && encrypted && kind == TS_AUTO_CONFIG_RULE) { const char *type = string(json, "type"); if (!type || strcmp(type, "automation_rule")) ret = ESP_ERR_INVALID_ARG; diff --git a/components/ts_automation/src/ts_source_manager.c b/components/ts_automation/src/ts_source_manager.c index 0d81b712..2dd6b5d0 100644 --- a/components/ts_automation/src/ts_source_manager.c +++ b/components/ts_automation/src/ts_source_manager.c @@ -1,3 +1,5 @@ +#include "ts_http_fetch.h" +#include "ts_http_url.h" #include "ts_action_codec.h" /** * @file ts_source_manager.c @@ -29,7 +31,6 @@ #include "freertos/idf_additions.h" // HTTP 客户端(用于 REST 源) -#include "esp_http_client.h" #include "esp_crt_bundle.h" #include "esp_websocket_client.h" #include "cJSON.h" @@ -84,6 +85,7 @@ typedef struct { atomic_uint last_message_ms; // 最近消息毫秒值,按无符号差计算超时 TaskHandle_t task_handle; // 连接任务句柄 atomic_bool should_stop; // 停止标志 + atomic_bool reconnect_requested; // Socket.IO task must obtain a new SID atomic_bool allocated; ts_auto_source_type_t type; uint64_t source_instance; @@ -369,7 +371,7 @@ static int auto_discover_json_fields(ts_auto_source_t *src, cJSON *json_data, ret = ts_variable_upsert(&new_var); if (ret == ESP_OK) { - ESP_LOGD(TAG, "Auto-discovered variable: %s", var_name); + ESP_LOGD(TAG, "Source variable discovered"); count++; } // 存储满时不再尝试创建,继续更新已有变量 @@ -479,11 +481,10 @@ static int process_source_mappings(ts_auto_source_t *src, cJSON *json_data) ret = ts_variable_upsert(&new_var); if (ret == ESP_OK) { - ESP_LOGD(TAG, "Auto-created variable '%s' from mapping", mapping->var_name); + ESP_LOGD(TAG, "Mapped source variable created"); processed++; } else { - ESP_LOGW(TAG, "Failed to create variable '%s': %s", - mapping->var_name, esp_err_to_name(ret)); + ESP_LOGW(TAG, "Source variable creation failed: %s", esp_err_to_name(ret)); } } else if (ret == ESP_OK) { processed++; @@ -549,11 +550,12 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) const char *url = src->rest.url; const char *path = src->rest.path; - ESP_LOGD(TAG, "Reading REST source: %s, path: %s", url, path); + ESP_LOGD(TAG, "Reading REST source"); // 检测是否是本地 API 调用 - bool is_local = (strstr(url, "://127.0.0.1") != NULL || - strstr(url, "://localhost") != NULL); + struct http_parser_url parsed; + if (!ts_http_url_parse(url, &parsed)) return ESP_ERR_INVALID_ARG; + bool is_local = ts_http_url_is_local_api(url, &parsed); cJSON *response_json = NULL; esp_err_t ret = ESP_OK; @@ -562,7 +564,7 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) // 本地 API 调用 - 解析路径并直接调用 const char *api_path = strstr(url, "/api/v1/"); if (!api_path) { - ESP_LOGW(TAG, "Invalid local API URL: %s", url); + ESP_LOGW(TAG, "Invalid local API URL"); return ESP_ERR_INVALID_ARG; } api_path += 8; // 跳过 "/api/v1/" @@ -582,7 +584,7 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) } api_name[j] = '\0'; - ESP_LOGD(TAG, "Local API call: %s", api_name); + ESP_LOGD(TAG, "Calling local source API"); // 调用本地 API ts_api_result_t api_result = {0}; @@ -601,8 +603,7 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) if (ret == ESP_OK && api_result.code == TS_API_OK && api_result.data) { response_json = cJSON_Duplicate(api_result.data, true); } else { - ESP_LOGW(TAG, "Local API call failed: %s, code=%d", - api_result.message ? api_result.message : "unknown", api_result.code); + ESP_LOGW(TAG, "Local source API failed (code=%d)", api_result.code); ret = ESP_FAIL; } @@ -612,64 +613,17 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) } else { // 外部 HTTP 请求 - char *response_buf = heap_caps_malloc(4096, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!response_buf) { - response_buf = malloc(4096); - } - if (!response_buf) { - return ESP_ERR_NO_MEM; - } - - int response_len = 0; - - esp_http_client_config_t config = { - .url = url, + ts_http_fetch_config_t request = {.url = url, .method = !strcmp(src->rest.method, "POST") ? HTTP_METHOD_POST : HTTP_METHOD_GET, - .timeout_ms = 10000, - .buffer_size = 2048, - .skip_cert_common_name_check = true, - .crt_bundle_attach = esp_crt_bundle_attach, - }; - - esp_http_client_handle_t client = esp_http_client_init(&config); - if (!client) { - free(response_buf); - return ESP_ERR_NO_MEM; - } - - // 添加认证头 - if (src->rest.auth_header[0] != '\0') { - esp_http_client_set_header(client, "Authorization", src->rest.auth_header); - } - - ret = esp_http_client_open(client, 0); + .authorization = src->rest.auth_header[0] ? src->rest.auth_header : NULL, + .timeout_ms = 10000, .maximum_body = 4095}; + ts_http_fetch_result_t reply = {0}; + ret = ts_http_fetch(&request, &reply); if (ret == ESP_OK) { - esp_http_client_fetch_headers(client); // 获取头部(返回值未使用,chunked 模式下可能为负数) - int status_code = esp_http_client_get_status_code(client); - - if (status_code == 200) { - response_len = esp_http_client_read(client, response_buf, 4095); - if (response_len > 0) { - response_buf[response_len] = '\0'; - response_json = cJSON_Parse(response_buf); - if (!response_json) { - ESP_LOGW(TAG, "Failed to parse JSON response"); - ret = ESP_ERR_INVALID_RESPONSE; - } - } else { - ret = ESP_ERR_INVALID_RESPONSE; - } - } else { - ESP_LOGW(TAG, "HTTP request failed with status: %d, URL: %s", status_code, url); - ret = ESP_FAIL; - } - } else { - ESP_LOGW(TAG, "HTTP connection failed: %s", esp_err_to_name(ret)); + if (reply.status != 200) ret = ESP_FAIL; + else if (!reply.length || !(response_json = cJSON_Parse(reply.body))) ret = ESP_ERR_INVALID_RESPONSE; } - - esp_http_client_close(client); - esp_http_client_cleanup(client); - free(response_buf); + free(reply.body); } // 处理 JSON 响应 @@ -713,7 +667,7 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) // 对于本地 API,response_json 已经是 data 对象 if (is_local && strncmp(path, "data.", 5) == 0) { actual_path = path + 5; - ESP_LOGD(TAG, "Local API: stripped 'data.' prefix, using path: %s", actual_path); + ESP_LOGD(TAG, "Using local source data path"); } // 使用 JSONPath 提取 @@ -725,7 +679,7 @@ static esp_err_t read_rest_source(ts_auto_source_t *src, ts_auto_value_t *value) // Fallback 到旧方法 ret = extract_json_value(response_json, actual_path, value); if (ret != ESP_OK) { - ESP_LOGW(TAG, "Failed to extract path '%s' from response", actual_path); + ESP_LOGW(TAG, "Source response path was not available"); } } } else if (value && src->mapping_count == 0 && !src->auto_discover) { @@ -797,8 +751,7 @@ static esp_err_t read_variable_source(ts_auto_source_t *src, ts_auto_value_t *va } } - ESP_LOGD(TAG, "Variable source '%s': read %d variables from prefix '%s'", - src->id, count, alias); + ESP_LOGD(TAG, "Variable source read (count=%d)", count); if (count > 0) { // 返回主要状态变量 @@ -815,8 +768,7 @@ static esp_err_t read_variable_source(ts_auto_source_t *src, ts_auto_value_t *va } // 变量不存在(指令可能尚未执行) - ESP_LOGD(TAG, "Variable source '%s': no variables found for prefix '%s' (command may not have been executed yet)", - src->id, alias); + ESP_LOGD(TAG, "Variable source not populated"); return ESP_ERR_NOT_FOUND; } @@ -860,8 +812,7 @@ static esp_err_t read_variable_source(ts_auto_source_t *src, ts_auto_value_t *va } } - ESP_LOGD(TAG, "Variable source '%s': synced %d variables from prefix '%s'", - src->id, count, var_prefix); + ESP_LOGD(TAG, "Variable source synchronized (count=%d)", count); if (count > 0) { value->type = TS_AUTO_VAL_INT; @@ -1048,12 +999,41 @@ bool ts_source_ws_is_connected(const char *id) /** * 查找 Socket.IO 连接 */ -void ts_source_sio_websocket_url(const char *base_url, const char *sid, char *out, size_t size) +bool ts_source_sio_url(const char *base_url, const char *sid, char *out, size_t size) { - const char *host = strstr(base_url, "://"); - host = host ? host + 3 : base_url; - snprintf(out, size, "%s://%s/socket.io/?EIO=4&transport=websocket&sid=%s", - !strncmp(base_url, "https://", 8) ? "wss" : "ws", host, sid); + if (!out || !size) return false; + out[0] = 0; + struct http_parser_url parsed; + if (!ts_http_url_parse(base_url, &parsed) || + (parsed.field_set & ((1U << UF_QUERY) | (1U << UF_FRAGMENT)))) return false; + size_t scheme = parsed.field_data[UF_SCHEMA].len; + const char *authority = base_url + parsed.field_data[UF_SCHEMA].off + scheme + 3; + size_t base_length = strlen(authority); + while (base_length && authority[base_length - 1] == '/') --base_length; + const char *prefix = sid ? (scheme == 5 ? "wss://" : "ws://") : (scheme == 5 ? "https://" : "http://"); + const char *suffix = sid ? "/socket.io/?EIO=4&transport=websocket&sid=" : "/socket.io/?EIO=4&transport=polling"; + size_t encoded = 0, sid_length = sid ? strnlen(sid, 64) : 0; + if (sid && (!sid_length || sid_length >= 64)) return false; + for (size_t i = 0; i < sid_length; ++i) { + unsigned char c = (unsigned char)sid[i]; + if (c <= 0x20 || c == 0x7f) return false; + bool unreserved = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~'; + encoded += unreserved ? 1 : 3; + } + size_t length = strlen(prefix) + base_length + strlen(suffix); + if (length + encoded >= size) return false; + snprintf(out, size, "%s%.*s%s", prefix, (int)base_length, authority, suffix); + static const char hex[] = "0123456789ABCDEF"; + for (size_t i = 0; i < sid_length; ++i) { + unsigned char c = (unsigned char)sid[i]; + bool unreserved = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~'; + if (unreserved) out[length++] = (char)c; + else { out[length++] = '%'; out[length++] = hex[c >> 4]; out[length++] = hex[c & 15]; } + } + out[length] = 0; + return true; } /* Caller owns the connection mutex; slots never move while a task uses them. */ @@ -1140,7 +1120,7 @@ static void sio_handle_event_message(sio_connection_t *conn, const char *msg) return; } - ESP_LOGD(TAG, "SIO event: %s from source %s", event_name->valuestring, conn->source_id); + ESP_LOGD(TAG, "SIO event received"); // 查找关联的数据源 xSemaphoreTake(ts_source_runtime.mutex, portMAX_DELAY); @@ -1150,7 +1130,7 @@ static void sio_handle_event_message(sio_connection_t *conn, const char *msg) // 检查是否是我们订阅的事件 if (strcmp(event_name->valuestring, src->socketio.event) == 0 && event_data) { - ESP_LOGD(TAG, "Matched subscribed event '%s', updating source value...", event_name->valuestring); + ESP_LOGD(TAG, "Subscribed event received; updating source"); // 更新源的 last_value // 由于 str_val 只有 64 字节,存储摘要而非完整 JSON @@ -1167,7 +1147,7 @@ static void sio_handle_event_message(sio_connection_t *conn, const char *msg) strncpy(src->last_value.str_val, json_str, sizeof(src->last_value.str_val) - 1); src->last_value.str_val[sizeof(src->last_value.str_val) - 1] = '\0'; } - ESP_LOGD(TAG, "Source '%s' last_value: %s", src->id, src->last_value.str_val); + ESP_LOGD(TAG, "SIO source value updated (bytes=%zu)", json_len); // 处理数据到变量 - 所有处理都在主任务中执行,避免栈溢出 // (mapping 可能需要递归展开数组/对象,auto_discover 也是递归的) @@ -1249,7 +1229,6 @@ static void sio_websocket_event_handler(void *arg, esp_event_base_t event_base, break; case WEBSOCKET_EVENT_CLOSED: - if (conn->type != TS_AUTO_SRC_WEBSOCKET) break; /* A clean server close has a distinct event in esp-websocket. */ /* fall through */ case WEBSOCKET_EVENT_DISCONNECTED: @@ -1257,6 +1236,10 @@ static void sio_websocket_event_handler(void *arg, esp_event_base_t event_base, conn->connected = false; conn->upgraded = false; if (conn->type == TS_AUTO_SRC_WEBSOCKET) conn->msg_buf_len = 0; + else { + conn->reconnect_requested = true; + if (conn->task_handle) xTaskNotifyGive(conn->task_handle); + } // 更新源状态 xSemaphoreTake(ts_source_runtime.mutex, portMAX_DELAY); int idx = current_connection_index(conn); @@ -1325,8 +1308,7 @@ static void sio_websocket_event_handler(void *arg, esp_event_base_t event_base, // 完整的单帧消息 char *msg = strndup(data->data_ptr, data->data_len); if (msg) { - ESP_LOGD(TAG, "SIO [%s] recv: %.100s%s", conn->source_id, msg, - strlen(msg) > 100 ? "..." : ""); + ESP_LOGD(TAG, "SIO frame received (bytes=%zu)", strlen(msg)); // 处理 Socket.IO 协议消息 if (conn->type == TS_AUTO_SRC_WEBSOCKET) { @@ -1375,52 +1357,29 @@ static void sio_websocket_event_handler(void *arg, esp_event_base_t event_base, */ static esp_err_t sio_http_handshake(const char *base_url, char *sid_out, size_t sid_len) { - char handshake_url[256]; - snprintf(handshake_url, sizeof(handshake_url), - "%s/socket.io/?EIO=4&transport=polling", base_url); - - char *response_buf = heap_caps_malloc(1024, MALLOC_CAP_SPIRAM); - if (!response_buf) response_buf = malloc(1024); - if (!response_buf) return ESP_ERR_NO_MEM; - - esp_http_client_config_t config = { - .url = handshake_url, - .method = HTTP_METHOD_GET, - .timeout_ms = 10000, - .crt_bundle_attach = esp_crt_bundle_attach, - }; - - esp_http_client_handle_t client = esp_http_client_init(&config); - esp_err_t ret = ESP_FAIL; - - if (esp_http_client_open(client, 0) == ESP_OK) { - esp_http_client_fetch_headers(client); - int len = esp_http_client_read(client, response_buf, 1023); - if (len > 0) { - response_buf[len] = '\0'; - ESP_LOGD(TAG, "SIO handshake response: %s", response_buf); - - // 响应格式:0{"sid":"xxx","upgrades":["websocket"],...} - char *json_start = strchr(response_buf, '{'); - if (json_start) { - cJSON *root = cJSON_Parse(json_start); - if (root) { - cJSON *sid = cJSON_GetObjectItem(root, "sid"); - if (sid && cJSON_IsString(sid)) { - strncpy(sid_out, sid->valuestring, sid_len - 1); - ret = ESP_OK; - ESP_LOGD(TAG, "SIO got session ID: %s", sid_out); - } - cJSON_Delete(root); - } + if (!base_url || !sid_out || sid_len < 2) return ESP_ERR_INVALID_ARG; + sid_out[0] = 0; + char handshake_url[512]; + if (!ts_source_sio_url(base_url, NULL, handshake_url, sizeof(handshake_url))) return ESP_ERR_INVALID_ARG; + ts_http_fetch_config_t request = {.url = handshake_url, .method = HTTP_METHOD_GET, + .timeout_ms = 10000, .maximum_body = 1023}; + ts_http_fetch_result_t reply = {0}; + esp_err_t ret = ts_http_fetch(&request, &reply); + if (ret == ESP_OK) { + ret = ESP_ERR_INVALID_RESPONSE; + const char *start = reply.status == 200 && reply.body ? strchr(reply.body, '{') : NULL; + cJSON *json = start ? cJSON_Parse(start) : NULL; + const cJSON *sid = json ? cJSON_GetObjectItemCaseSensitive(json, "sid") : NULL; + if (cJSON_IsString(sid)) { + size_t length = strlen(sid->valuestring); + if (length && length < sid_len) { + memcpy(sid_out, sid->valuestring, length + 1); + ret = ESP_OK; } } + cJSON_Delete(json); } - - esp_http_client_close(client); - esp_http_client_cleanup(client); - free(response_buf); - + free(reply.body); return ret; } @@ -1487,7 +1446,7 @@ static void sio_connection_task(void *arg) : retry_delay_ms * 2; } - ESP_LOGD(TAG, "SIO [%s] attempting connection to %s", conn->source_id, base_url); + ESP_LOGD(TAG, "SIO connection attempt"); if (conn->type == TS_AUTO_SRC_WEBSOCKET) break; @@ -1525,14 +1484,16 @@ static void sio_connection_task(void *arg) xSemaphoreGive(ts_source_runtime.mutex); // 2. 构建 WebSocket URL - char ws_url[256]; + char ws_url[512]; if (conn->type == TS_AUTO_SRC_WEBSOCKET) { + struct http_parser_url parsed; + if (!ts_ws_url_parse(ws_base_url, &parsed)) goto task_exit; snprintf(ws_url, sizeof(ws_url), "%s", ws_base_url); } else { - ts_source_sio_websocket_url(ws_base_url, conn->session_id, ws_url, sizeof(ws_url)); + if (!ts_source_sio_url(ws_base_url, conn->session_id, ws_url, sizeof(ws_url))) goto task_exit; } - ESP_LOGD(TAG, "SIO [%s] WebSocket URL: %s", conn->source_id, ws_url); + ESP_LOGD(TAG, "SIO WebSocket target prepared"); // 3. 创建 WebSocket 连接 esp_websocket_client_config_t ws_cfg = { @@ -1540,11 +1501,13 @@ static void sio_connection_task(void *arg) .buffer_size = 2048, .reconnect_timeout_ms = conn->type == TS_AUTO_SRC_WEBSOCKET && ws_reconnect_ms ? ws_reconnect_ms : 10000, .enable_close_reconnect = conn->type == TS_AUTO_SRC_WEBSOCKET, + .disable_auto_reconnect = conn->type == TS_AUTO_SRC_SOCKETIO, .network_timeout_ms = 10000, /* 网络超时 10s */ .ping_interval_sec = 0, /* 禁用 WebSocket ping,使用 Socket.IO ping */ .crt_bundle_attach = esp_crt_bundle_attach, }; + conn->reconnect_requested = false; conn->client = esp_websocket_client_init(&ws_cfg); if (!conn->client) { ESP_LOGE(TAG, "SIO [%s] failed to init WebSocket client", conn->source_id); @@ -1565,6 +1528,7 @@ static void sio_connection_task(void *arg) while (!conn->should_stop) { ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(200)); if (conn->should_stop) break; + if (conn->type == TS_AUTO_SRC_SOCKETIO && conn->reconnect_requested) break; // 处理待处理的自动发现数据(在此任务中执行,有足够栈空间) if (xSemaphoreTake(conn->pending_mutex, 0) == pdTRUE) { diff --git a/components/ts_cert/include/ts_cert.h b/components/ts_cert/include/ts_cert.h index 16fc606c..a76fa7b3 100644 --- a/components/ts_cert/include/ts_cert.h +++ b/components/ts_cert/include/ts_cert.h @@ -150,6 +150,11 @@ void ts_cert_free_snapshot(ts_cert_snapshot_t *snapshot); bool ts_cert_prerequisites(const ts_cert_pki_status_t *status, bool require_ca); const char *ts_cert_validity_to_str(ts_cert_validity_t validity); esp_err_t ts_cert_install_certificate_ex(const char *pem, size_t len, ts_cert_op_error_t *detail); +/* Auto-enrollment only: local key pair + TLS leaf + owner-installed issuer + * chain, before the single existing certificate write. Never installs a CA + * from a peer. Offline storage does not authorize TLS clients or config packs. */ +esp_err_t ts_cert_install_issued_certificate_ex(const char *pem, size_t len, ts_cert_op_error_t *detail); + esp_err_t ts_cert_install_ca_chain_ex(const char *pem, size_t len, ts_cert_op_error_t *detail); const char *ts_cert_op_error_to_str(ts_cert_op_error_t detail); diff --git a/components/ts_cert/src/ts_cert.c b/components/ts_cert/src/ts_cert.c index bb7f4855..ab3512cb 100644 --- a/components/ts_cert/src/ts_cert.c +++ b/components/ts_cert/src/ts_cert.c @@ -198,6 +198,7 @@ static esp_err_t nvs_write_string(const char *key, const char *str) return err; } + static void set_status(const ts_cert_info_t *current) { ts_cert_info_t info = *current; @@ -643,14 +644,40 @@ static void save_ca_copy(const char *pem) if (written != len || closed != 0) ESP_LOGW(TAG, "CA saved in NVS; SD copy write failed"); } -static esp_err_t install_material(const char *pem, size_t len, bool ca, ts_cert_op_error_t *detail) +/* CA installation accepts an owner-selected trust bundle, not a leaf + * certificate. Validate every member, including on reload. A CA without KU + * retains X.509's unrestricted-usage meaning; present KU must allow signing. + * Selection of a new trust anchor does not require the previous CA's signature. */ +static bool ca_bundle_constraints_valid(const mbedtls_x509_crt *bundle) +{ + if (!bundle || !bundle->raw.len) return false; + for (const mbedtls_x509_crt *crt = bundle; crt; crt = crt->next) { + if (!crt->raw.len || mbedtls_x509_crt_get_ca_istrue(crt) != 1 || + mbedtls_x509_crt_check_key_usage(crt, MBEDTLS_X509_KU_KEY_CERT_SIGN) != 0) + return false; + } + return true; +} + +/* Automatic enrollment authenticates the signed device identity against the + * owner's existing issuer bundle. A peer response never supplies trust roots. + * With no usable UTC, time flags may be deferred only for storing this identity; + * remote-client authentication and config-package admission keep their own gates. */ +static int issued_validity(void *context, mbedtls_x509_crt *crt, int depth, uint32_t *flags) +{ + (void)crt; (void)depth; + if (*(bool *)context) *flags &= ~(MBEDTLS_X509_BADCERT_FUTURE | MBEDTLS_X509_BADCERT_EXPIRED); + return 0; +} + +static esp_err_t install_material(const char *pem, size_t len, bool ca, bool issued, ts_cert_op_error_t *detail) { ts_cert_op_error_t why = TS_CERT_OP_OK; esp_err_t err = ESP_ERR_INVALID_ARG; char *replacement = NULL; - mbedtls_x509_crt crt; + mbedtls_x509_crt crt, trust; mbedtls_pk_context pk; - mbedtls_x509_crt_init(&crt); mbedtls_pk_init(&pk); + mbedtls_x509_crt_init(&crt); mbedtls_x509_crt_init(&trust); mbedtls_pk_init(&pk); if (!s_initialized) { why = TS_CERT_OP_NOT_INITIALIZED; err = ESP_ERR_INVALID_STATE; goto done; } if (!pem || len <= 1) { why = TS_CERT_OP_INVALID_INPUT; goto done; } size_t cap = ca ? TS_CERT_CA_CHAIN_MAX_LEN : TS_CERT_PEM_MAX_LEN; @@ -664,6 +691,7 @@ static esp_err_t install_material(const char *pem, size_t len, bool ca, ts_cert_ why = TS_CERT_OP_PRIVATE_KEY_MISSING; err = ESP_ERR_INVALID_STATE; goto done; } if (s_storage_error) { why = TS_CERT_OP_STORAGE_FAILED; err = ESP_FAIL; goto done; } + if (issued && (!s_ca_chain_pem || !s_ca_valid)) { why = TS_CERT_OP_INVALID_INPUT; err = ESP_ERR_INVALID_STATE; goto done; } char *old = ca ? s_ca_chain_pem : s_certificate_pem; replacement = copy_pem(pem, len); if (!replacement) { why = TS_CERT_OP_NO_MEMORY; err = ESP_ERR_NO_MEM; goto done; } @@ -674,6 +702,10 @@ static esp_err_t install_material(const char *pem, size_t len, bool ca, ts_cert_ err = why == TS_CERT_OP_NO_MEMORY ? ESP_ERR_NO_MEM : ESP_ERR_INVALID_ARG; goto done; } + if (ca && !ca_bundle_constraints_valid(&crt)) { + why = TS_CERT_OP_INVALID_INPUT; + goto done; + } if (!ca) { err = init_rng(); if (err != ESP_OK) { why = err == ESP_ERR_NO_MEM ? TS_CERT_OP_NO_MEMORY : TS_CERT_OP_CRYPTO_FAILED; goto done; } @@ -691,6 +723,26 @@ static esp_err_t install_material(const char *pem, size_t len, bool ca, ts_cert_ goto done; } } + if (issued) { + if (mbedtls_x509_crt_get_ca_istrue(&crt) != 0 || + mbedtls_x509_crt_check_key_usage(&crt, MBEDTLS_X509_KU_DIGITAL_SIGNATURE) || + (mbedtls_x509_crt_check_extended_key_usage(&crt, MBEDTLS_OID_CLIENT_AUTH, MBEDTLS_OID_SIZE(MBEDTLS_OID_CLIENT_AUTH)) && + mbedtls_x509_crt_check_extended_key_usage(&crt, MBEDTLS_OID_SERVER_AUTH, MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH)))) { + why = TS_CERT_OP_INVALID_INPUT; err = ESP_ERR_INVALID_ARG; goto done; + } + ret = mbedtls_x509_crt_parse(&trust, (const unsigned char *)s_ca_chain_pem, strlen(s_ca_chain_pem) + 1); + if (ret != 0) { + why = allocation_error(ret) ? TS_CERT_OP_NO_MEMORY : TS_CERT_OP_PEM_PARSE_FAILED; + err = why == TS_CERT_OP_NO_MEMORY ? ESP_ERR_NO_MEM : ESP_ERR_INVALID_ARG; goto done; + } + uint32_t flags = 0; + bool offline = !ts_cert_time_ready((int64_t)time(NULL), TS_TIME_MIN_VALID_YEAR); + ret = mbedtls_x509_crt_verify(&crt, &trust, NULL, NULL, &flags, issued_validity, &offline); + if (ret != 0 || flags) { + why = allocation_error(ret) ? TS_CERT_OP_NO_MEMORY : TS_CERT_OP_INVALID_INPUT; + err = why == TS_CERT_OP_NO_MEMORY ? ESP_ERR_NO_MEM : ESP_ERR_INVALID_ARG; goto done; + } + } /* Reuse the candidate parser for metadata: no second parse or allocation after persistence. */ ts_cert_info_t info = {0}; unsigned char hash[32]; @@ -720,15 +772,15 @@ static esp_err_t install_material(const char *pem, size_t len, bool ca, ts_cert_ err = ESP_OK; done: free(replacement); - mbedtls_pk_free(&pk); mbedtls_x509_crt_free(&crt); + mbedtls_pk_free(&pk); mbedtls_x509_crt_free(&crt); mbedtls_x509_crt_free(&trust); if (detail) *detail = why; return err; } static esp_err_t ts_cert_install_certificate_ex_locked(const char *pem, size_t len, ts_cert_op_error_t *detail) -{ return install_material(pem, len, false, detail); } +{ return install_material(pem, len, false, false, detail); } static esp_err_t ts_cert_install_ca_chain_ex_locked(const char *pem, size_t len, ts_cert_op_error_t *detail) -{ return install_material(pem, len, true, detail); } +{ return install_material(pem, len, true, false, detail); } static esp_err_t ts_cert_install_certificate_locked(const char *pem, size_t len) { return ts_cert_install_certificate_ex_locked(pem, len, NULL); } static esp_err_t ts_cert_install_ca_chain_locked(const char *pem, size_t len) @@ -1053,7 +1105,8 @@ static void refresh_metadata(void) } } if (s_ca_chain_pem) - s_ca_valid = mbedtls_x509_crt_parse(&ca, (const unsigned char *)s_ca_chain_pem, strlen(s_ca_chain_pem)+1) == 0; + s_ca_valid = mbedtls_x509_crt_parse(&ca, (const unsigned char *)s_ca_chain_pem, strlen(s_ca_chain_pem)+1) == 0 && + ca_bundle_constraints_valid(&ca); mbedtls_pk_free(&key); mbedtls_x509_crt_free(&crt); mbedtls_x509_crt_free(&ca); s_metadata_generation = s_generation; } @@ -1087,14 +1140,8 @@ void ts_cert_free_snapshot(ts_cert_snapshot_t *s) memset(s, 0, sizeof(*s)); } -static esp_err_t ts_cert_get_snapshot_locked(bool require_ca, ts_cert_snapshot_t *snapshot) +static esp_err_t copy_snapshot_locked(bool require_ca, ts_cert_snapshot_t *snapshot) { - if (!snapshot) return ESP_ERR_INVALID_ARG; - memset(snapshot, 0, sizeof(*snapshot)); - ts_cert_pki_status_t status; - esp_err_t err = ts_cert_get_status_locked(&status); - if (err != ESP_OK) return err; - if (!ts_cert_prerequisites(&status, require_ca)) return ESP_ERR_INVALID_STATE; snapshot->key = copy_pem(s_private_key_pem, strlen(s_private_key_pem)+1); snapshot->certificate = copy_pem(s_certificate_pem, strlen(s_certificate_pem)+1); if (s_ca_chain_pem && s_ca_valid) snapshot->ca = copy_pem(s_ca_chain_pem, strlen(s_ca_chain_pem)+1); @@ -1106,6 +1153,17 @@ static esp_err_t ts_cert_get_snapshot_locked(bool require_ca, ts_cert_snapshot_t return ESP_OK; } +static esp_err_t ts_cert_get_snapshot_locked(bool require_ca, ts_cert_snapshot_t *snapshot) +{ + if (!snapshot) return ESP_ERR_INVALID_ARG; + memset(snapshot, 0, sizeof(*snapshot)); + ts_cert_pki_status_t status; + esp_err_t err = ts_cert_get_status_locked(&status); + if (err != ESP_OK) return err; + if (!ts_cert_prerequisites(&status, require_ca)) return ESP_ERR_INVALID_STATE; + return copy_snapshot_locked(require_ca, snapshot); +} + /* All public cache/RNG operations take the same lock; events are posted after release. * Lock order: material only -> unlock -> event; never material -> TLS/service manager. */ @@ -1192,6 +1250,15 @@ esp_err_t ts_cert_install_certificate_ex(const char *pem, size_t len, ts_cert_op return result; } +esp_err_t ts_cert_install_issued_certificate_ex(const char *pem, size_t len, ts_cert_op_error_t *detail) +{ + material_lock(); + uint32_t previous = s_generation; + esp_err_t result = install_material(pem, len, false, true, detail); + material_unlock(previous, 1); + return result; +} + esp_err_t ts_cert_install_ca_chain_ex(const char *pem, size_t len, ts_cert_op_error_t *detail) { material_lock(); @@ -1319,18 +1386,13 @@ esp_err_t ts_cert_get_pack_snapshot(ts_cert_snapshot_t *snapshot) if (ret == ESP_OK && (status.storage_error || !status.key_valid || !status.key_matches || !status.has_certificate || !status.ca_valid)) ret = ESP_ERR_INVALID_STATE; if (ret == ESP_OK) { - snapshot->key = copy_pem(s_private_key_pem, strlen(s_private_key_pem) + 1); - snapshot->certificate = copy_pem(s_certificate_pem, strlen(s_certificate_pem) + 1); - snapshot->ca = copy_pem(s_ca_chain_pem, strlen(s_ca_chain_pem) + 1); - snapshot->generation = s_generation; - memcpy(snapshot->certificate_sha256, s_fingerprint, sizeof(s_fingerprint)); - if (!snapshot->key || !snapshot->certificate || !snapshot->ca) { - ts_cert_free_snapshot(snapshot); ret = ESP_ERR_NO_MEM; - } + ret = copy_snapshot_locked(true, snapshot); } xSemaphoreGive(s_mutex); return ret; } + + /* Short configuration admission lease: acquire after certificate/crypto work. * Never call TLS/material parsing while holding it. */ bool ts_cert_material_begin(uint32_t expected_generation) diff --git a/components/ts_config_pack/CMakeLists.txt b/components/ts_config_pack/CMakeLists.txt index db7c4cf2..c1f6f45d 100644 --- a/components/ts_config_pack/CMakeLists.txt +++ b/components/ts_config_pack/CMakeLists.txt @@ -12,4 +12,5 @@ idf_component_register( PRIV_REQUIRES ts_storage mbedtls + nvs_flash ) diff --git a/components/ts_config_pack/include/ts_config_pack.h b/components/ts_config_pack/include/ts_config_pack.h index 0ffeae06..3fde2a9d 100644 --- a/components/ts_config_pack/include/ts_config_pack.h +++ b/components/ts_config_pack/include/ts_config_pack.h @@ -65,6 +65,7 @@ typedef enum { TS_CONFIG_PACK_ERR_TRUST_NOT_CONFIGURED, TS_CONFIG_PACK_ERR_SIGNER_ROLE, TS_CONFIG_PACK_ERR_CREDENTIAL_CHANGED, + TS_CONFIG_PACK_ERR_UNSUPPORTED, } ts_config_pack_result_t; /** Local acceptance of exact v1 package bytes; never constructed from package metadata. */ @@ -99,6 +100,7 @@ typedef struct { char *content; /**< Decrypted JSON content */ size_t content_len; /**< Content length */ ts_config_pack_sig_info_t sig_info; /**< Signature info */ + ts_config_pack_acceptance_t acceptance; /**< Verified local proof, never SD metadata */ int64_t created_at; /**< Creation timestamp (Unix epoch) */ char *source_file; /**< Original source filename */ char *target_device; /**< Target device CN */ @@ -149,8 +151,14 @@ bool ts_config_pack_can_export(void); * @param pack Output: loaded configuration (caller must free with ts_config_pack_free) * @return TS_CONFIG_PACK_OK on success, error code otherwise */ +/* Ordinary data retains its original Developer certificate usage and pinned CA + * chain verification. Existing local data can load before NTP; new imports need + * current time. No SD metadata grants trust or creates a trusted timestamp. */ ts_config_pack_result_t ts_config_pack_load(const char *path, ts_config_pack_t **pack); +/* Command-bearing automation additionally requires code-signing usage. */ +ts_config_pack_result_t ts_config_pack_load_rule_mem(const char *bytes, size_t length, ts_config_pack_t **pack); + /** * @brief Load and decrypt from memory buffer * @@ -323,14 +331,15 @@ ts_config_pack_result_t ts_config_pack_validate_file( ); /** - * @brief Apply configuration from a validated .tscfg file - * - * Decrypts and applies the configuration from a .tscfg file. - * The file should have been validated first. - * - * @param path Full path to .tscfg file - * @param applied_modules Output: JSON array of applied module names (optional) - * @return TS_CONFIG_PACK_OK on success + * @brief Legacy generic configuration application (not supported) + * + * Generic module application is not implemented. This legacy entry point + * returns TS_CONFIG_PACK_ERR_UNSUPPORTED without opening or decrypting the file. + * Use the configuration owner's supported import operation instead. + * + * @param path Full path to .tscfg file (not opened) + * @param applied_modules Output: always NULL, including errors (optional) + * @return Unsupported, invalid argument, or uninitialized subsystem */ ts_config_pack_result_t ts_config_pack_apply_file( const char *path, diff --git a/components/ts_config_pack/src/ts_config_pack.c b/components/ts_config_pack/src/ts_config_pack.c index 9f9c1cfa..daa126d1 100644 --- a/components/ts_config_pack/src/ts_config_pack.c +++ b/components/ts_config_pack/src/ts_config_pack.c @@ -26,6 +26,8 @@ #include "ts_cert.h" #include "ts_crypto.h" #include "ts_config_pack_trust.h" +#include "ts_time_sync.h" +#include "nvs.h" #include "cJSON.h" #include "esp_log.h" #include @@ -131,6 +133,9 @@ typedef struct { static bool s_initialized = false; +static ts_config_pack_result_t load_cached_mem(const char *bytes, size_t length, + ts_config_pack_t **pack, bool require_code_signing, bool existing_file); + /*===========================================================================*/ /* Forward Declarations */ /*===========================================================================*/ @@ -147,11 +152,12 @@ static ts_config_pack_result_t verify_signature(const char *signer_cert_pem, size_t data_len, const uint8_t *signature, size_t sig_len); -static ts_config_pack_result_t decrypt_payload(const ts_config_pack_crypto_params_t *params, - const uint8_t *ciphertext, - size_t ciphertext_len, - char **plaintext, - size_t *plaintext_len); + + +static ts_config_pack_result_t verify_pack_mem(const char *text, size_t length, bool require_code_signing, bool existing_file, + const ts_config_pack_acceptance_t *accepted, ts_config_pack_t **pack, + ts_config_pack_acceptance_t *acceptance, uint32_t *credential_generation, + ts_config_pack_sig_info_t *signature_info); /*===========================================================================*/ /* Error Messages */ @@ -176,6 +182,7 @@ static const char *s_error_messages[] = { [TS_CONFIG_PACK_ERR_TRUST_NOT_CONFIGURED] = "Configuration signing root is not configured", [TS_CONFIG_PACK_ERR_SIGNER_ROLE] = "Certificate is not authorized for configuration signing", [TS_CONFIG_PACK_ERR_CREDENTIAL_CHANGED] = "Credentials changed during validation", + [TS_CONFIG_PACK_ERR_UNSUPPORTED] = "Generic configuration pack application is not supported", }; const char *ts_config_pack_strerror(ts_config_pack_result_t result) @@ -190,6 +197,8 @@ const char *ts_config_pack_strerror(ts_config_pack_result_t result) const char *ts_config_pack_reason(ts_config_pack_result_t result) { switch (result) { + case TS_CONFIG_PACK_OK: return "ok"; + case TS_CONFIG_PACK_ERR_UNSUPPORTED: return "pack_apply_unsupported"; case TS_CONFIG_PACK_ERR_PARSE: return "pack_parse_failed"; case TS_CONFIG_PACK_ERR_VERSION: return "pack_version_unsupported"; case TS_CONFIG_PACK_ERR_RECIPIENT: return "pack_wrong_device"; @@ -246,195 +255,134 @@ bool ts_config_pack_can_export(void) /* Load Functions */ /*===========================================================================*/ -ts_config_pack_result_t ts_config_pack_load(const char *path, ts_config_pack_t **pack) +/* One bounded immutable read is used by both encrypted and plain configuration + * paths. A selected encrypted file never falls back after an I/O/trust error. */ +static ts_config_pack_result_t read_config_bytes(const char *path, char **out, size_t *length) { - if (!path || !pack) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - if (!s_initialized) { - return TS_CONFIG_PACK_ERR_NOT_INIT; - } - - /* 读取文件 */ - FILE *f = fopen(path, "r"); - if (!f) { - ESP_LOGE(TAG, "Failed to open file: %s", path); - return TS_CONFIG_PACK_ERR_IO; - } - - /* 获取文件大小 */ - fseek(f, 0, SEEK_END); - long file_size = ftell(f); - fseek(f, 0, SEEK_SET); - - if (file_size <= 0 || file_size > CONFIG_TS_CONFIG_PACK_MAX_SIZE) { - ESP_LOGE(TAG, "Invalid file size: %ld", file_size); - fclose(f); - return TS_CONFIG_PACK_ERR_PARSE; - } - - char *json_buf = TS_MALLOC_PSRAM(file_size + 1); - if (!json_buf) { - fclose(f); - return TS_CONFIG_PACK_ERR_NO_MEM; + *out = NULL; *length = 0; + FILE *file = fopen(path, "rb"); + if (!file) return TS_CONFIG_PACK_ERR_IO; + bool ok = fseek(file, 0, SEEK_END) == 0; + long size = ok ? ftell(file) : -1; + ts_config_pack_result_t result = TS_CONFIG_PACK_ERR_IO; + if (size <= 0 || size > CONFIG_TS_CONFIG_PACK_MAX_SIZE) { + result = TS_CONFIG_PACK_ERR_PARSE; + } else if (fseek(file, 0, SEEK_SET) == 0) { + char *bytes = TS_MALLOC_PSRAM((size_t)size + 1); + if (!bytes) result = TS_CONFIG_PACK_ERR_NO_MEM; + else { + if (fread(bytes, 1, size, file) == (size_t)size && !ferror(file)) { + bytes[size] = 0; *out = bytes; *length = size; + result = TS_CONFIG_PACK_OK; + } else free(bytes); + } } - - size_t read_len = fread(json_buf, 1, file_size, f); - fclose(f); - - if (read_len != (size_t)file_size) { - free(json_buf); - return TS_CONFIG_PACK_ERR_IO; + if (fclose(file) && result == TS_CONFIG_PACK_OK) { + free(*out); *out = NULL; *length = 0; result = TS_CONFIG_PACK_ERR_IO; } - json_buf[file_size] = '\0'; - - ts_config_pack_result_t result = ts_config_pack_load_mem(json_buf, file_size, pack); - free(json_buf); - return result; } -ts_config_pack_result_t ts_config_pack_load_mem( - const char *tscfg_json, - size_t tscfg_len, - ts_config_pack_t **pack) +/* Public acceptance metadata is held in internal NVS, never read from package + * fields or an SD sidecar. The short index cannot authorize a hash collision: + * the full package digest, issuer, signer and recipient are rechecked below. */ +static bool acceptance_matches(const ts_config_pack_acceptance_t *record, const char *hash) { - if (!tscfg_json || !pack) { + return record->policy == TS_CONFIG_PACK_ACCEPT_POLICY && record->accepted_at > 0 && + record->package_sha256[64] == 0 && record->signer_sha256[64] == 0 && + record->root_sha256[64] == 0 && record->recipient[64] == 0 && + !strcmp(record->package_sha256, hash) && + !strcmp(record->root_sha256, CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256); +} + +static esp_err_t read_acceptance(const char *index, ts_config_pack_acceptance_t *record) +{ + memset(record, 0, sizeof(*record)); + nvs_handle_t handle; + esp_err_t ret = nvs_open("ts_pack_accept", NVS_READONLY, &handle); + if (ret == ESP_ERR_NVS_NOT_FOUND) return ESP_OK; + if (ret != ESP_OK) return ret; + size_t length = 0; + ret = nvs_get_blob(handle, index, NULL, &length); + if (ret == ESP_OK && length == sizeof(*record)) + ret = nvs_get_blob(handle, index, record, &length); + nvs_close(handle); + return ret == ESP_ERR_NVS_NOT_FOUND ? ESP_OK : ret; +} + +static esp_err_t write_acceptance(const char *index, const ts_config_pack_acceptance_t *record) +{ + nvs_handle_t handle; + esp_err_t ret = nvs_open("ts_pack_accept", NVS_READWRITE, &handle); + if (ret != ESP_OK) return ret; + ret = nvs_set_blob(handle, index, record, sizeof(*record)); + if (ret == ESP_OK) ret = nvs_commit(handle); + nvs_close(handle); + return ret; +} + +ts_config_pack_result_t ts_config_pack_load(const char *path, ts_config_pack_t **pack) +{ + if (!pack) return TS_CONFIG_PACK_ERR_INVALID_ARG; + *pack = NULL; + if (!path) return TS_CONFIG_PACK_ERR_INVALID_ARG; + if (!s_initialized) return TS_CONFIG_PACK_ERR_NOT_INIT; + char *bytes = NULL; size_t length = 0; + ts_config_pack_result_t result = read_config_bytes(path, &bytes, &length); + if (result == TS_CONFIG_PACK_OK) result = load_cached_mem(bytes, length, pack, false, true); + free(bytes); + return result; +} + +static ts_config_pack_result_t lookup_acceptance(const char *bytes, size_t length, + ts_config_pack_acceptance_t *accepted, char index[16], bool *reload) +{ + if (!bytes || !length || length > CONFIG_TS_CONFIG_PACK_MAX_SIZE) return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - if (!s_initialized) { - return TS_CONFIG_PACK_ERR_NOT_INIT; - } - - char device_fingerprint[CERT_FINGERPRINT_LEN + 1]; - esp_err_t identity_ret = ts_config_pack_get_cert_fingerprint(device_fingerprint, sizeof(device_fingerprint)); - if (identity_ret != ESP_OK) { - return identity_ret == ESP_ERR_NO_MEM ? TS_CONFIG_PACK_ERR_NO_MEM : TS_CONFIG_PACK_ERR_RECIPIENT; - } + if (!s_initialized) return TS_CONFIG_PACK_ERR_NOT_INIT; + unsigned char digest[32]; char hash[65]; + if (ts_crypto_hash(TS_HASH_SHA256, bytes, length, digest, sizeof digest) != ESP_OK || + ts_crypto_hex_encode(digest, sizeof digest, hash, sizeof hash) != ESP_OK) + return TS_CONFIG_PACK_ERR_INVALID_ARG; + memcpy(index, hash, 15); index[15] = 0; + if (read_acceptance(index, accepted) != ESP_OK) return TS_CONFIG_PACK_ERR_IO; + *reload = acceptance_matches(accepted, hash); + return TS_CONFIG_PACK_OK; +} - cJSON *root = NULL; - ts_config_pack_crypto_params_t params = {0}; - char *payload_b64 = NULL; - char *signer_cert_pem = NULL; - char *signature_b64 = NULL; - ts_config_pack_sig_info_t sig_info = {0}; - - /* 解析 JSON */ - ts_config_pack_result_t result = parse_tscfg_json( - tscfg_json, tscfg_len, - &root, ¶ms, &payload_b64, &signer_cert_pem, &signature_b64, &sig_info); - - if (result != TS_CONFIG_PACK_OK) { - goto cleanup; - } - - /* 验证接收方指纹 */ - if (strcmp(params.recipient_fingerprint, device_fingerprint) != 0) { - ESP_LOGE(TAG, "Config pack not intended for this device"); - ESP_LOGE(TAG, "Device fingerprint: %s", device_fingerprint); - ESP_LOGE(TAG, "Pack fingerprint: %s", params.recipient_fingerprint); - result = TS_CONFIG_PACK_ERR_RECIPIENT; - goto cleanup; - } - - /* Base64 解码 payload */ - size_t payload_b64_len = strlen(payload_b64); - size_t ciphertext_max_len = (payload_b64_len * 3) / 4 + 4; - uint8_t *ciphertext = TS_MALLOC_PSRAM(ciphertext_max_len); - if (!ciphertext) { - result = TS_CONFIG_PACK_ERR_NO_MEM; - goto cleanup; - } - - size_t ciphertext_len = ciphertext_max_len; - if (ts_crypto_base64_decode(payload_b64, payload_b64_len, - ciphertext, &ciphertext_len) != ESP_OK) { - ESP_LOGE(TAG, "Failed to decode payload"); - free(ciphertext); - result = TS_CONFIG_PACK_ERR_PARSE; - goto cleanup; - } - - /* Base64 解码签名 */ - size_t sig_b64_len = strlen(signature_b64); - uint8_t signature[MAX_SIGNATURE_LEN]; - size_t sig_len = sizeof(signature); - if (ts_crypto_base64_decode(signature_b64, sig_b64_len, - signature, &sig_len) != ESP_OK) { - ESP_LOGE(TAG, "Failed to decode signature"); - free(ciphertext); - result = TS_CONFIG_PACK_ERR_PARSE; - goto cleanup; - } - - /* 构建待签名数据并验证签名 */ - /* TODO: 完整的签名数据应包含 ciphertext + ephemeral_pub + fingerprint + timestamp + version */ - /* 这里简化为只对 ciphertext 签名 */ - result = verify_signature(signer_cert_pem, ciphertext, ciphertext_len, - signature, sig_len); - if (result != TS_CONFIG_PACK_OK) { - free(ciphertext); - goto cleanup; - } - - sig_info.valid = true; - - /* 解密 payload */ - char *plaintext = NULL; - size_t plaintext_len = 0; - result = decrypt_payload(¶ms, ciphertext, ciphertext_len, - &plaintext, &plaintext_len); - free(ciphertext); - - if (result != TS_CONFIG_PACK_OK) { - goto cleanup; - } - - /* 构建返回结构 */ - ts_config_pack_t *p = TS_CALLOC_PSRAM(1, sizeof(ts_config_pack_t)); - if (!p) { - free(plaintext); - result = TS_CONFIG_PACK_ERR_NO_MEM; - goto cleanup; - } - - /* 从 JSON 提取元数据 */ - cJSON *metadata = cJSON_GetObjectItem(root, "metadata"); - if (metadata) { - cJSON *name = cJSON_GetObjectItem(metadata, "name"); - cJSON *desc = cJSON_GetObjectItem(metadata, "description"); - cJSON *source = cJSON_GetObjectItem(metadata, "source_file"); - cJSON *target = cJSON_GetObjectItem(metadata, "target_device"); - - if (name && cJSON_IsString(name)) { - p->name = strdup(cJSON_GetStringValue(name)); - } - if (desc && cJSON_IsString(desc)) { - p->description = strdup(cJSON_GetStringValue(desc)); - } - if (source && cJSON_IsString(source)) { - p->source_file = strdup(cJSON_GetStringValue(source)); - } - if (target && cJSON_IsString(target)) { - p->target_device = strdup(cJSON_GetStringValue(target)); +static ts_config_pack_result_t load_cached_mem(const char *bytes, size_t length, + ts_config_pack_t **pack, bool require_code_signing, bool existing_file) +{ + if (!pack) return TS_CONFIG_PACK_ERR_INVALID_ARG; + *pack = NULL; + char index[16]; bool reload = false; + ts_config_pack_acceptance_t accepted = {0}, verified = {0}; + ts_config_pack_result_t result = lookup_acceptance(bytes, length, &accepted, index, &reload); + if (result != TS_CONFIG_PACK_OK) return result; + result = verify_pack_mem(bytes, length, require_code_signing, existing_file, + reload ? &accepted : NULL, pack, &verified, NULL, NULL); + if (result == TS_CONFIG_PACK_OK && !reload && verified.accepted_at > 0) { + ts_config_pack_acceptance_t readback; + if (write_acceptance(index, &verified) != ESP_OK || + read_acceptance(index, &readback) != ESP_OK || memcmp(&readback, &verified, sizeof verified)) { + ts_config_pack_free(*pack); *pack = NULL; result = TS_CONFIG_PACK_ERR_IO; } - /* TODO: 解析 ISO 8601 时间戳 */ } - - p->content = plaintext; - p->content_len = plaintext_len; - p->sig_info = sig_info; - - *pack = p; - result = TS_CONFIG_PACK_OK; - -cleanup: - if (root) cJSON_Delete(root); return result; } +ts_config_pack_result_t ts_config_pack_load_mem(const char *bytes, size_t length, ts_config_pack_t **pack) +{ + return load_cached_mem(bytes, length, pack, false, false); +} + +/* Command-bearing legacy automation keeps strict code-signing usage while + * reusing the same exact-byte acceptance cache. The payload cannot choose it. */ +ts_config_pack_result_t ts_config_pack_load_rule_mem(const char *bytes, size_t length, ts_config_pack_t **pack) +{ + return load_cached_mem(bytes, length, pack, true, false); +} + void ts_config_pack_free(ts_config_pack_t *pack) { if (!pack) return; @@ -788,110 +736,28 @@ esp_err_t ts_config_pack_save(const char *path, const char *tscfg_json, size_t t /* Verify Functions */ /*===========================================================================*/ -ts_config_pack_result_t ts_config_pack_verify( - const char *path, - ts_config_pack_sig_info_t *info) +ts_config_pack_result_t ts_config_pack_verify(const char *path, ts_config_pack_sig_info_t *info) { - if (!path) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - /* 读取文件 */ - FILE *f = fopen(path, "r"); - if (!f) { - return TS_CONFIG_PACK_ERR_IO; - } - - fseek(f, 0, SEEK_END); - long file_size = ftell(f); - fseek(f, 0, SEEK_SET); - - if (file_size <= 0 || file_size > CONFIG_TS_CONFIG_PACK_MAX_SIZE) { - fclose(f); - return TS_CONFIG_PACK_ERR_PARSE; - } - - char *json_buf = TS_MALLOC_PSRAM(file_size + 1); - if (!json_buf) { - fclose(f); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - fread(json_buf, 1, file_size, f); - fclose(f); - json_buf[file_size] = '\0'; - - ts_config_pack_result_t result = ts_config_pack_verify_mem(json_buf, file_size, info); - free(json_buf); - + if (info) memset(info, 0, sizeof(*info)); + if (!path) return TS_CONFIG_PACK_ERR_INVALID_ARG; + char *bytes = NULL; size_t length = 0; + ts_config_pack_result_t result = read_config_bytes(path, &bytes, &length); + if (result == TS_CONFIG_PACK_OK) result = ts_config_pack_verify_mem(bytes, length, info); + free(bytes); return result; } -ts_config_pack_result_t ts_config_pack_verify_mem( - const char *tscfg_json, - size_t tscfg_len, - ts_config_pack_sig_info_t *info) +ts_config_pack_result_t ts_config_pack_verify_mem(const char *bytes, size_t length, + ts_config_pack_sig_info_t *info) { - if (!tscfg_json) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - cJSON *root = NULL; - ts_config_pack_crypto_params_t params = {0}; - char *payload_b64 = NULL; - char *signer_cert_pem = NULL; - char *signature_b64 = NULL; - ts_config_pack_sig_info_t sig_info = {0}; - - ts_config_pack_result_t result = parse_tscfg_json( - tscfg_json, tscfg_len, - &root, ¶ms, &payload_b64, &signer_cert_pem, &signature_b64, &sig_info); - - if (result != TS_CONFIG_PACK_OK) { - if (root) cJSON_Delete(root); - return result; - } - - /* Base64 解码 payload */ - size_t payload_b64_len = strlen(payload_b64); - size_t ciphertext_max_len = (payload_b64_len * 3) / 4 + 4; - uint8_t *ciphertext = TS_MALLOC_PSRAM(ciphertext_max_len); - if (!ciphertext) { - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - size_t ciphertext_len = ciphertext_max_len; - if (ts_crypto_base64_decode(payload_b64, payload_b64_len, - ciphertext, &ciphertext_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* Base64 解码签名 */ - size_t sig_b64_len = strlen(signature_b64); - uint8_t signature[MAX_SIGNATURE_LEN]; - size_t sig_len = sizeof(signature); - if (ts_crypto_base64_decode(signature_b64, sig_b64_len, - signature, &sig_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* 验证签名 */ - result = verify_signature(signer_cert_pem, ciphertext, ciphertext_len, - signature, sig_len); - free(ciphertext); - cJSON_Delete(root); - - if (result == TS_CONFIG_PACK_OK && info) { - sig_info.valid = true; - *info = sig_info; - } - - return result; + if (info) memset(info, 0, sizeof(*info)); + char index[16]; bool reload = false; + ts_config_pack_acceptance_t accepted = {0}; + ts_config_pack_result_t result = lookup_acceptance(bytes, length, &accepted, index, &reload); + if (result != TS_CONFIG_PACK_OK) return result; + /* Inspection may verify an outbound package for another recipient. It + * never grants offline acceptance; import/load also authenticate GCM. */ + return verify_pack_mem(bytes, length, false, false, reload ? &accepted : NULL, NULL, NULL, NULL, info); } /*===========================================================================*/ @@ -904,496 +770,86 @@ ts_config_pack_result_t ts_config_pack_verify_mem( /** * @brief 确保目录存在 */ -static esp_err_t ensure_dir_exists(const char *dir) +/* Unauthenticated display time is never used for admission or expiry. */ +static int64_t display_created_at(const cJSON *metadata) { - struct stat st; - if (stat(dir, &st) == 0) { - return ESP_OK; - } - - /* 递归创建父目录 */ - char *parent = strdup(dir); - if (!parent) return ESP_ERR_NO_MEM; - - char *slash = strrchr(parent, '/'); - if (slash && slash != parent) { - *slash = '\0'; - ensure_dir_exists(parent); - } - free(parent); - - if (mkdir(dir, 0755) != 0 && errno != EEXIST) { - ESP_LOGE(TAG, "Failed to create directory: %s", dir); - return ESP_FAIL; - } - - return ESP_OK; + const cJSON *value = cJSON_GetObjectItemCaseSensitive(metadata, "created_at"); + int y, m, d, h, minute, second, end = 0; + if (!cJSON_IsString(value) || sscanf(value->valuestring, "%4d-%2d-%2dT%2d:%2d:%2dZ%n", + &y, &m, &d, &h, &minute, &second, &end) != 6 || value->valuestring[end] || + y < 1970 || y > 9999 || m < 1 || m > 12 || d < 1 || d > 31 || + h < 0 || h > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) return 0; + y -= m <= 2; + int era = y / 400, year = y - era * 400; + int day = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; + int64_t days = era * 146097 + year * 365 + year / 4 - year / 100 + day - 719468; + return days * 86400 + h * 3600 + minute * 60 + second; } -ts_config_pack_result_t ts_config_pack_import( - const char *tscfg_json, - size_t tscfg_len, - ts_config_pack_metadata_t *metadata, - char *saved_path, - size_t saved_path_len) +static void pack_metadata(const ts_config_pack_t *pack, ts_config_pack_metadata_t *metadata) { - if (!tscfg_json || tscfg_len == 0) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - if (!s_initialized) { - return TS_CONFIG_PACK_ERR_NOT_INIT; - } - - /* 解析 JSON 获取元数据和加密参数 */ - cJSON *root = NULL; - ts_config_pack_crypto_params_t params = {0}; - char *payload_b64 = NULL; - char *signer_cert_pem = NULL; - char *signature_b64 = NULL; - ts_config_pack_sig_info_t sig_info = {0}; - - ts_config_pack_result_t result = parse_tscfg_json( - tscfg_json, tscfg_len, - &root, ¶ms, &payload_b64, &signer_cert_pem, &signature_b64, &sig_info); - - if (result != TS_CONFIG_PACK_OK) { - if (root) cJSON_Delete(root); - return result; - } - - char device_fingerprint[CERT_FINGERPRINT_LEN + 1]; - esp_err_t identity_ret = ts_config_pack_get_cert_fingerprint(device_fingerprint, sizeof(device_fingerprint)); - if (identity_ret != ESP_OK) { - cJSON_Delete(root); - return identity_ret == ESP_ERR_NO_MEM ? TS_CONFIG_PACK_ERR_NO_MEM : TS_CONFIG_PACK_ERR_RECIPIENT; - } + if (!metadata) return; + memset(metadata, 0, sizeof(*metadata)); + snprintf(metadata->name, sizeof(metadata->name), "%s", pack->name ? pack->name : "unnamed"); + snprintf(metadata->description, sizeof(metadata->description), "%s", pack->description ? pack->description : ""); + snprintf(metadata->source_file, sizeof(metadata->source_file), "%s", pack->source_file ? pack->source_file : ""); + snprintf(metadata->target_device, sizeof(metadata->target_device), "%s", pack->target_device ? pack->target_device : ""); + metadata->created_at = pack->created_at; + metadata->sig_info = pack->sig_info; +} - /* 验证接收方指纹 - 必须是本设备 */ - if (strcmp(params.recipient_fingerprint, device_fingerprint) != 0) { - ESP_LOGE(TAG, "Config pack not intended for this device"); - ESP_LOGE(TAG, "Device fingerprint: %s", device_fingerprint); - ESP_LOGE(TAG, "Pack fingerprint: %s", params.recipient_fingerprint); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_RECIPIENT; - } - - /* Base64 解码 payload 用于签名验证 */ - size_t payload_b64_len = strlen(payload_b64); - size_t ciphertext_max_len = (payload_b64_len * 3) / 4 + 4; - uint8_t *ciphertext = TS_MALLOC_PSRAM(ciphertext_max_len); - if (!ciphertext) { - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - size_t ciphertext_len = ciphertext_max_len; - if (ts_crypto_base64_decode(payload_b64, payload_b64_len, - ciphertext, &ciphertext_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* Base64 解码签名 */ - size_t sig_b64_len = strlen(signature_b64); - uint8_t signature[MAX_SIGNATURE_LEN]; - size_t sig_len = sizeof(signature); - if (ts_crypto_base64_decode(signature_b64, sig_b64_len, - signature, &sig_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* 验证签名 */ - result = verify_signature(signer_cert_pem, ciphertext, ciphertext_len, - signature, sig_len); - free(ciphertext); - - if (result != TS_CONFIG_PACK_OK) { - cJSON_Delete(root); - return result; - } - - sig_info.valid = true; - - /* 提取元数据(不解密) */ - char name[64] = "unnamed"; - char description[128] = ""; - char source_file[64] = ""; - char target_device[64] = ""; - int64_t created_at = 0; - - cJSON *meta = cJSON_GetObjectItem(root, "metadata"); - if (meta) { - cJSON *j_name = cJSON_GetObjectItem(meta, "name"); - cJSON *j_desc = cJSON_GetObjectItem(meta, "description"); - cJSON *j_src = cJSON_GetObjectItem(meta, "source_file"); - cJSON *j_target = cJSON_GetObjectItem(meta, "target_device"); - cJSON *j_created = cJSON_GetObjectItem(meta, "created_at"); - - if (j_name && cJSON_IsString(j_name)) { - strncpy(name, j_name->valuestring, sizeof(name) - 1); - } - if (j_desc && cJSON_IsString(j_desc)) { - strncpy(description, j_desc->valuestring, sizeof(description) - 1); - } - if (j_src && cJSON_IsString(j_src)) { - strncpy(source_file, j_src->valuestring, sizeof(source_file) - 1); - } - if (j_target && cJSON_IsString(j_target)) { - strncpy(target_device, j_target->valuestring, sizeof(target_device) - 1); - } - if (j_created && cJSON_IsString(j_created)) { - /* ISO 8601 时间戳解析 */ - int year, month, day, hour, min, sec; - if (sscanf(j_created->valuestring, "%d-%d-%dT%d:%d:%dZ", - &year, &month, &day, &hour, &min, &sec) == 6) { - struct tm tm_info = { - .tm_year = year - 1900, - .tm_mon = month - 1, - .tm_mday = day, - .tm_hour = hour, - .tm_min = min, - .tm_sec = sec, - .tm_isdst = 0 - }; - char *old_tz = getenv("TZ"); - setenv("TZ", "UTC0", 1); - tzset(); - created_at = mktime(&tm_info); - if (old_tz) { - setenv("TZ", old_tz, 1); - } else { - unsetenv("TZ"); - } - tzset(); - } - } - } - - cJSON_Delete(root); - - /* 确保目录存在 */ - if (ensure_dir_exists(CONFIG_PACK_DIR) != ESP_OK) { - return TS_CONFIG_PACK_ERR_IO; - } - - /* 构建保存路径 */ +ts_config_pack_result_t ts_config_pack_import(const char *bytes, size_t length, + ts_config_pack_metadata_t *metadata, char *saved_path, size_t saved_path_len) +{ + if (saved_path && saved_path_len) saved_path[0] = 0; + if (metadata) memset(metadata, 0, sizeof(*metadata)); + ts_config_pack_t *pack = NULL; + ts_config_pack_result_t result = ts_config_pack_load_mem(bytes, length, &pack); + if (result != TS_CONFIG_PACK_OK) return result; + /* v1 display metadata cannot escape the fixed import directory. */ + const char *name = pack->name ? pack->name : "unnamed"; + size_t count = strlen(name); + bool safe = count > 0 && count < 64; + for (size_t i = 0; safe && i < count; ++i) + safe = (unsigned char)name[i] >= 0x20 && (unsigned char)name[i] != 0x7f && + name[i] != '/' && name[i] != '\\'; + safe = safe && strcmp(name, ".") && strcmp(name, ".."); char path[128]; - snprintf(path, sizeof(path), "%s/%s.tscfg", CONFIG_PACK_DIR, name); - - /* 保存加密的配置包文件(原样保存,不解密) */ - if (ts_config_pack_save(path, tscfg_json, tscfg_len) != ESP_OK) { - return TS_CONFIG_PACK_ERR_IO; - } - - ESP_LOGI(TAG, "Config pack imported: %s -> %s", name, path); - - /* 填充返回的元数据 */ - if (metadata) { - strncpy(metadata->name, name, sizeof(metadata->name) - 1); - strncpy(metadata->description, description, sizeof(metadata->description) - 1); - strncpy(metadata->source_file, source_file, sizeof(metadata->source_file) - 1); - strncpy(metadata->target_device, target_device, sizeof(metadata->target_device) - 1); - metadata->created_at = created_at; - metadata->sig_info = sig_info; - } - - if (saved_path && saved_path_len > 0) { - strncpy(saved_path, path, saved_path_len - 1); - saved_path[saved_path_len - 1] = '\0'; + if (!safe) result = TS_CONFIG_PACK_ERR_INVALID_ARG; + else if (ts_storage_mkdir_p(CONFIG_PACK_DIR) != ESP_OK) result = TS_CONFIG_PACK_ERR_IO; + else { + snprintf(path, sizeof(path), "%s/%s.tscfg", CONFIG_PACK_DIR, name); + if (ts_storage_replace_file(path, bytes, length) != ESP_OK) result = TS_CONFIG_PACK_ERR_IO; + else { + pack_metadata(pack, metadata); + if (saved_path && saved_path_len) snprintf(saved_path, saved_path_len, "%s", path); + } } - - return TS_CONFIG_PACK_OK; + ts_config_pack_free(pack); + return result; } -ts_config_pack_result_t ts_config_pack_validate_file( - const char *path, - ts_config_pack_metadata_t *metadata) +ts_config_pack_result_t ts_config_pack_validate_file(const char *path, + ts_config_pack_metadata_t *metadata) { - if (!path) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - if (!s_initialized) { - return TS_CONFIG_PACK_ERR_NOT_INIT; - } - - /* 读取文件内容 */ - FILE *f = fopen(path, "r"); - if (!f) { - ESP_LOGE(TAG, "Failed to open file: %s", path); - return TS_CONFIG_PACK_ERR_IO; - } - - fseek(f, 0, SEEK_END); - long file_size = ftell(f); - fseek(f, 0, SEEK_SET); - - if (file_size <= 0 || file_size > 65536) { - fclose(f); - ESP_LOGE(TAG, "Invalid file size: %ld", file_size); - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - char *file_buf = TS_MALLOC_PSRAM(file_size + 1); - if (!file_buf) { - fclose(f); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - size_t read_len = fread(file_buf, 1, file_size, f); - fclose(f); - - if (read_len != (size_t)file_size) { - free(file_buf); - return TS_CONFIG_PACK_ERR_IO; - } - file_buf[file_size] = '\0'; - - /* 解析 JSON 获取元数据和加密参数 */ - cJSON *root = NULL; - ts_config_pack_crypto_params_t params = {0}; - char *payload_b64 = NULL; - char *signer_cert_pem = NULL; - char *signature_b64 = NULL; - ts_config_pack_sig_info_t sig_info = {0}; - - ts_config_pack_result_t result = parse_tscfg_json( - file_buf, file_size, - &root, ¶ms, &payload_b64, &signer_cert_pem, &signature_b64, &sig_info); - - free(file_buf); - - if (result != TS_CONFIG_PACK_OK) { - if (root) cJSON_Delete(root); - return result; - } - - char device_fingerprint[CERT_FINGERPRINT_LEN + 1]; - esp_err_t identity_ret = ts_config_pack_get_cert_fingerprint(device_fingerprint, sizeof(device_fingerprint)); - if (identity_ret != ESP_OK) { - cJSON_Delete(root); - return identity_ret == ESP_ERR_NO_MEM ? TS_CONFIG_PACK_ERR_NO_MEM : TS_CONFIG_PACK_ERR_RECIPIENT; - } - - /* 验证接收方指纹 - 必须是本设备 */ - if (strcmp(params.recipient_fingerprint, device_fingerprint) != 0) { - ESP_LOGE(TAG, "Config pack not intended for this device"); - ESP_LOGE(TAG, "Device fingerprint: %s", device_fingerprint); - ESP_LOGE(TAG, "Pack fingerprint: %s", params.recipient_fingerprint); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_RECIPIENT; - } - - /* Base64 解码 payload 用于签名验证 */ - size_t payload_b64_len = strlen(payload_b64); - size_t ciphertext_max_len = (payload_b64_len * 3) / 4 + 4; - uint8_t *ciphertext = TS_MALLOC_PSRAM(ciphertext_max_len); - if (!ciphertext) { - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - size_t ciphertext_len = ciphertext_max_len; - if (ts_crypto_base64_decode(payload_b64, payload_b64_len, - ciphertext, &ciphertext_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* Base64 解码签名 */ - size_t sig_b64_len = strlen(signature_b64); - uint8_t signature[MAX_SIGNATURE_LEN]; - size_t sig_len = sizeof(signature); - if (ts_crypto_base64_decode(signature_b64, sig_b64_len, - signature, &sig_len) != ESP_OK) { - free(ciphertext); - cJSON_Delete(root); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* 验证签名 */ - result = verify_signature(signer_cert_pem, ciphertext, ciphertext_len, - signature, sig_len); - free(ciphertext); - - if (result != TS_CONFIG_PACK_OK) { - cJSON_Delete(root); - return result; - } - - sig_info.valid = true; - - /* 提取元数据(不解密) */ - char name[64] = "unnamed"; - char description[128] = ""; - char source_file[64] = ""; - char target_device[64] = ""; - int64_t created_at = 0; - - cJSON *meta = cJSON_GetObjectItem(root, "metadata"); - if (meta) { - cJSON *j_name = cJSON_GetObjectItem(meta, "name"); - cJSON *j_desc = cJSON_GetObjectItem(meta, "description"); - cJSON *j_src = cJSON_GetObjectItem(meta, "source_file"); - cJSON *j_target = cJSON_GetObjectItem(meta, "target_device"); - cJSON *j_created = cJSON_GetObjectItem(meta, "created_at"); - - if (j_name && cJSON_IsString(j_name)) { - strncpy(name, j_name->valuestring, sizeof(name) - 1); - } - if (j_desc && cJSON_IsString(j_desc)) { - strncpy(description, j_desc->valuestring, sizeof(description) - 1); - } - if (j_src && cJSON_IsString(j_src)) { - strncpy(source_file, j_src->valuestring, sizeof(source_file) - 1); - } - if (j_target && cJSON_IsString(j_target)) { - strncpy(target_device, j_target->valuestring, sizeof(target_device) - 1); - } - if (j_created && cJSON_IsString(j_created)) { - /* ISO 8601 时间戳解析 */ - int year, month, day, hour, min, sec; - if (sscanf(j_created->valuestring, "%d-%d-%dT%d:%d:%dZ", - &year, &month, &day, &hour, &min, &sec) == 6) { - struct tm tm_info = { - .tm_year = year - 1900, - .tm_mon = month - 1, - .tm_mday = day, - .tm_hour = hour, - .tm_min = min, - .tm_sec = sec, - .tm_isdst = 0 - }; - char *old_tz = getenv("TZ"); - setenv("TZ", "UTC0", 1); - tzset(); - created_at = mktime(&tm_info); - if (old_tz) { - setenv("TZ", old_tz, 1); - } else { - unsetenv("TZ"); - } - tzset(); - } - } - } - - cJSON_Delete(root); - - /* 填充返回的元数据 */ - if (metadata) { - strncpy(metadata->name, name, sizeof(metadata->name) - 1); - strncpy(metadata->description, description, sizeof(metadata->description) - 1); - strncpy(metadata->source_file, source_file, sizeof(metadata->source_file) - 1); - strncpy(metadata->target_device, target_device, sizeof(metadata->target_device) - 1); - metadata->created_at = created_at; - metadata->sig_info = sig_info; - } - - ESP_LOGI(TAG, "Config pack validated: %s at %s", name, path); - return TS_CONFIG_PACK_OK; + if (metadata) memset(metadata, 0, sizeof(*metadata)); + ts_config_pack_t *pack = NULL; + ts_config_pack_result_t result = ts_config_pack_load(path, &pack); + if (result == TS_CONFIG_PACK_OK) pack_metadata(pack, metadata); + ts_config_pack_free(pack); + return result; } ts_config_pack_result_t ts_config_pack_apply_file( const char *path, cJSON **applied_modules) { - if (!path) { - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - if (!s_initialized) { - return TS_CONFIG_PACK_ERR_NOT_INIT; - } - - /* 读取并解密配置包 */ - FILE *f = fopen(path, "r"); - if (!f) { - ESP_LOGE(TAG, "Failed to open file: %s", path); - return TS_CONFIG_PACK_ERR_IO; - } - - fseek(f, 0, SEEK_END); - long file_size = ftell(f); - fseek(f, 0, SEEK_SET); - - if (file_size <= 0 || file_size > 65536) { - fclose(f); - return TS_CONFIG_PACK_ERR_INVALID_ARG; - } - - char *file_buf = TS_MALLOC_PSRAM(file_size + 1); - if (!file_buf) { - fclose(f); - return TS_CONFIG_PACK_ERR_NO_MEM; - } - - size_t read_len = fread(file_buf, 1, file_size, f); - fclose(f); - - if (read_len != (size_t)file_size) { - free(file_buf); - return TS_CONFIG_PACK_ERR_IO; - } - file_buf[file_size] = '\0'; - - /* 解析并解密 */ - ts_config_pack_t *pack = NULL; - ts_config_pack_result_t result = ts_config_pack_load_mem(file_buf, file_size, &pack); - free(file_buf); - - if (result != TS_CONFIG_PACK_OK) { - ESP_LOGE(TAG, "Failed to load config pack: %s", ts_config_pack_strerror(result)); - return result; - } - - if (!pack || !pack->content) { - ESP_LOGE(TAG, "No content in config pack"); - if (pack) ts_config_pack_free(pack); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* 解析解密后的配置内容 */ - cJSON *config = cJSON_Parse(pack->content); - if (!config) { - ESP_LOGE(TAG, "Failed to parse decrypted config content"); - ts_config_pack_free(pack); - return TS_CONFIG_PACK_ERR_PARSE; - } - - /* 应用配置模块 */ - cJSON *modules = cJSON_CreateArray(); - - /* TODO: 遍历配置模块并应用 */ - /* 示例模块: network, led, fan, security 等 */ - cJSON *item = NULL; - cJSON_ArrayForEach(item, config) { - const char *key = item->string; - if (key) { - cJSON_AddItemToArray(modules, cJSON_CreateString(key)); - ESP_LOGI(TAG, "Applied config module: %s", key); - - /* TODO: 调用各模块的配置应用函数 */ - /* 例如: ts_net_apply_config(item), ts_led_apply_config(item) 等 */ - } - } - - cJSON_Delete(config); - ts_config_pack_free(pack); - - if (applied_modules) { - *applied_modules = modules; - } else { - cJSON_Delete(modules); - } - - ESP_LOGI(TAG, "Config pack applied: %s", path); - return TS_CONFIG_PACK_OK; + if (applied_modules) *applied_modules = NULL; + if (!path) return TS_CONFIG_PACK_ERR_INVALID_ARG; + if (!s_initialized) return TS_CONFIG_PACK_ERR_NOT_INIT; + /* The former path only enumerated names. Application belongs to each + * configuration owner; this legacy API has no module apply implementation. */ + return TS_CONFIG_PACK_ERR_UNSUPPORTED; } esp_err_t ts_config_pack_list( @@ -1796,25 +1252,12 @@ static ts_config_pack_result_t decrypt_payload_key( return TS_CONFIG_PACK_OK; } -static ts_config_pack_result_t decrypt_payload(const ts_config_pack_crypto_params_t *params, - const uint8_t *ciphertext, size_t ciphertext_len, char **plaintext, size_t *plaintext_len) -{ - char *key = TS_MALLOC_PSRAM(TS_CERT_KEY_MAX_LEN); - if (!key) return TS_CONFIG_PACK_ERR_NO_MEM; - size_t len = TS_CERT_KEY_MAX_LEN; - ts_config_pack_result_t ret = TS_CONFIG_PACK_ERR_RECIPIENT; - if (ts_cert_get_private_key(key, &len) == ESP_OK) - ret = decrypt_payload_key(params, key, ciphertext, ciphertext_len, plaintext, plaintext_len); - memset(key, 0, TS_CERT_KEY_MAX_LEN); free(key); - return ret; -} - -ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text, size_t length, +static ts_config_pack_result_t verify_pack_mem(const char *text, size_t length, bool require_code_signing, bool existing_file, const ts_config_pack_acceptance_t *accepted, ts_config_pack_t **pack, - ts_config_pack_acceptance_t *acceptance, uint32_t *credential_generation) + ts_config_pack_acceptance_t *acceptance, uint32_t *credential_generation, ts_config_pack_sig_info_t *signature_info) { - if (!pack) return TS_CONFIG_PACK_ERR_INVALID_ARG; - *pack = NULL; + if (pack) *pack = NULL; + uint32_t time_generation = ts_time_sync_security_generation(); cJSON *root = NULL; ts_config_pack_crypto_params_t params = {0}; char *payload = NULL, *signer = NULL, *signature_text = NULL; @@ -1838,8 +1281,8 @@ ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text, size_ ts_crypto_hex_encode(digest, sizeof digest, hash, sizeof hash) != ESP_OK) { ret = TS_CONFIG_PACK_ERR_INVALID_ARG; goto done; } - if (strcmp(recipient, params.recipient_fingerprint)) { ret = TS_CONFIG_PACK_ERR_RECIPIENT; goto done; } - ret = ts_config_pack_signer_trust(signer, &snapshot, hash, recipient, accepted, &local); + if (pack && strcmp(recipient, params.recipient_fingerprint)) { ret = TS_CONFIG_PACK_ERR_RECIPIENT; goto done; } + ret = ts_config_pack_signer_trust(signer, &snapshot, hash, params.recipient_fingerprint, require_code_signing, existing_file, accepted, &local); if (ret != TS_CONFIG_PACK_OK) goto done; size_t cipher_len = strlen(payload) * 3 / 4 + 4; ciphertext = TS_MALLOC_PSRAM(cipher_len); @@ -1852,18 +1295,38 @@ ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text, size_ ret = verify_signature(signer, ciphertext, cipher_len, signature, sig_len); if (ret != TS_CONFIG_PACK_OK) goto done; size_t plain_len = 0; - ret = decrypt_payload_key(¶ms, snapshot.key, ciphertext, cipher_len, &plaintext, &plain_len); - if (ret != TS_CONFIG_PACK_OK) goto done; - cJSON *content = ts_config_pack_parse_json(plaintext, plain_len); - if (!content) { ret = TS_CONFIG_PACK_ERR_PARSE; goto done; } - cJSON_Delete(content); + if (pack) { + ret = decrypt_payload_key(¶ms, snapshot.key, ciphertext, cipher_len, &plaintext, &plain_len); + if (ret != TS_CONFIG_PACK_OK) goto done; + cJSON *content = ts_config_pack_parse_json(plaintext, plain_len); + if (!content) { ret = TS_CONFIG_PACK_ERR_PARSE; goto done; } + cJSON_Delete(content); + } ts_cert_pki_status_t status = {0}; - if (ts_cert_get_status(&status) != ESP_OK || status.generation != snapshot.generation) { + if (ts_cert_get_status(&status) != ESP_OK || status.generation != snapshot.generation || + (!accepted && time_generation != ts_time_sync_security_generation())) { ret = TS_CONFIG_PACK_ERR_CREDENTIAL_CHANGED; goto done; } + if (!pack) { + info.valid = info.is_official = true; + if (signature_info) *signature_info = info; + goto done; + } ts_config_pack_t *loaded = TS_CALLOC_PSRAM(1, sizeof(*loaded)); if (!loaded) { ret = TS_CONFIG_PACK_ERR_NO_MEM; goto done; } loaded->content = plaintext; plaintext = NULL; loaded->content_len = plain_len; + cJSON *metadata = cJSON_GetObjectItemCaseSensitive(root, "metadata"); + const char *fields[] = {"name", "description", "source_file", "target_device"}; + char **outputs[] = {&loaded->name, &loaded->description, &loaded->source_file, &loaded->target_device}; + for (size_t i = 0; i < sizeof(fields) / sizeof(fields[0]); ++i) { + const cJSON *value = cJSON_GetObjectItemCaseSensitive(metadata, fields[i]); + if (cJSON_IsString(value)) { + *outputs[i] = strdup(value->valuestring); + if (!*outputs[i]) { ts_config_pack_free(loaded); ret = TS_CONFIG_PACK_ERR_NO_MEM; goto done; } + } + } + loaded->acceptance = local; + loaded->created_at = display_created_at(metadata); info.valid = info.is_official = true; loaded->sig_info = info; if (acceptance) *acceptance = local; if (credential_generation) *credential_generation = snapshot.generation; @@ -1873,6 +1336,14 @@ ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text, size_ return ret; } +ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text, size_t length, + const ts_config_pack_acceptance_t *accepted, ts_config_pack_t **pack, + ts_config_pack_acceptance_t *acceptance, uint32_t *credential_generation) +{ + if (!pack) return TS_CONFIG_PACK_ERR_INVALID_ARG; + return verify_pack_mem(text, length, true, false, accepted, pack, acceptance, credential_generation, NULL); +} + // ============================================================================ // 通用配置加载辅助函数 (Generic Config Loading Helpers) // ============================================================================ @@ -1956,65 +1427,27 @@ esp_err_t ts_config_pack_load_with_priority( // 检查 .tscfg 是否存在 struct stat st; if (stat(tscfg_path, &st) == 0) { - // .tscfg 存在,使用 ts_config_pack_load 解密 - ESP_LOGI(TAG, "Loading encrypted config: %s", tscfg_path); - ts_config_pack_t *pack = NULL; ts_config_pack_result_t result = ts_config_pack_load(tscfg_path, &pack); - - if (result == TS_CONFIG_PACK_OK && pack != NULL) { - // 成功解密,移交内容所有权 - *content = pack->content; - if (content_len) *content_len = pack->content_len; - if (used_tscfg) *used_tscfg = true; - - pack->content = NULL; // 防止 free 释放 + if (result != TS_CONFIG_PACK_OK) { ts_config_pack_free(pack); - - ESP_LOGI(TAG, "Successfully loaded encrypted config: %s", tscfg_path); - return ESP_OK; + return result == TS_CONFIG_PACK_ERR_NO_MEM ? ESP_ERR_NO_MEM : ESP_FAIL; } - - // 解密失败,回退到 .json - if (pack) ts_config_pack_free(pack); - ESP_LOGW(TAG, "Failed to decrypt %s (err=%d), falling back to .json", - tscfg_path, result); - } - - // 加载普通 .json 文件 - if (stat(json_path, &st) != 0) { - ESP_LOGD(TAG, "Config file not found: %s", json_path); - return ESP_ERR_NOT_FOUND; - } - - FILE *f = fopen(json_path, "r"); - if (!f) { - ESP_LOGE(TAG, "Failed to open: %s", json_path); - return ESP_FAIL; - } - - size_t file_size = st.st_size; - char *json_content = heap_caps_malloc(file_size + 1, MALLOC_CAP_SPIRAM); - if (!json_content) { - fclose(f); - ESP_LOGE(TAG, "Failed to allocate memory for %s", json_path); - return ESP_ERR_NO_MEM; - } - - size_t read_size = fread(json_content, 1, file_size, f); - fclose(f); - - if (read_size != file_size) { - free(json_content); - ESP_LOGE(TAG, "Failed to read: %s", json_path); - return ESP_FAIL; + *content = pack->content; + if (content_len) *content_len = pack->content_len; + if (used_tscfg) *used_tscfg = true; + pack->content = NULL; + ts_config_pack_free(pack); + return ESP_OK; } - - json_content[file_size] = '\0'; - *content = json_content; - if (content_len) *content_len = file_size; - if (used_tscfg) *used_tscfg = false; - - ESP_LOGI(TAG, "Loaded plain config: %s (%zu bytes)", json_path, file_size); + if (errno != ENOENT) return ESP_FAIL; + + if (stat(json_path, &st) != 0) + return errno == ENOENT ? ESP_ERR_NOT_FOUND : ESP_FAIL; + size_t length = 0; + ts_config_pack_result_t result = read_config_bytes(json_path, content, &length); + if (result != TS_CONFIG_PACK_OK) + return result == TS_CONFIG_PACK_ERR_NO_MEM ? ESP_ERR_NO_MEM : ESP_FAIL; + if (content_len) *content_len = length; return ESP_OK; } diff --git a/components/ts_config_pack/src/ts_config_pack_trust.c b/components/ts_config_pack/src/ts_config_pack_trust.c index e2138f30..f5063f4a 100644 --- a/components/ts_config_pack/src/ts_config_pack_trust.c +++ b/components/ts_config_pack/src/ts_config_pack_trust.c @@ -1,16 +1,12 @@ #include "ts_config_pack_trust.h" #include "ts_crypto.h" #include "ts_core.h" +#include "ts_time_sync.h" #include "mbedtls/x509_crt.h" #include "mbedtls/oid.h" #include #include -#ifndef CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256 -#define CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256 "" -#endif -#define ACCEPT_POLICY 1 - static bool cert_hash(const mbedtls_x509_crt *crt, char out[65]) { unsigned char digest[32]; return ts_crypto_hash(TS_HASH_SHA256, crt->raw.p, crt->raw.len, digest, sizeof digest) == ESP_OK && @@ -36,6 +32,7 @@ static int accepted_time(void *context, mbedtls_x509_crt *crt, int depth, uint32 } ts_config_pack_result_t ts_config_pack_signer_trust(const char *signer, const ts_cert_snapshot_t *snapshot, const char *package_hash, const char *recipient, + bool require_code_signing, bool existing_file, const ts_config_pack_acceptance_t *accepted, ts_config_pack_acceptance_t *out) { if (strlen(CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256) != 64) return TS_CONFIG_PACK_ERR_TRUST_NOT_CONFIGURED; @@ -67,17 +64,22 @@ ts_config_pack_result_t ts_config_pack_signer_trust(const char *signer, if (!cert_hash(c, hash)) goto done; if (strcmp(hash, root_hash) && mbedtls_x509_crt_parse_der(&certs->leaf, c->raw.p, c->raw.len)) goto done; } - bool reload = accepted && accepted->policy == ACCEPT_POLICY && accepted->accepted_at > 0 && + bool reload = accepted && accepted->policy == TS_CONFIG_PACK_ACCEPT_POLICY && accepted->accepted_at > 0 && !strcmp(accepted->package_sha256, package_hash) && !strcmp(accepted->recipient, recipient) && !strcmp(accepted->signer_sha256, signer_hash) && !strcmp(accepted->root_sha256, root_hash); if (accepted && !reload) goto done; ts_cert_pki_status_t status = {0}; - if (!reload && (ts_cert_get_status(&status) != ESP_OK || !status.time_ready)) { + if (ts_cert_get_status(&status) != ESP_OK) goto done; + /* Existing ordinary data must load before network/NTP starts. The chain, + * Developer role, signature, recipient and GCM checks still apply. Display + * timestamps never grant trust or manufacture fresh acceptance. */ + bool defer_time = reload || (existing_file && !require_code_signing && !status.time_ready); + if (!reload && !status.time_ready && !defer_time) { result = TS_CONFIG_PACK_ERR_TIME_UNVERIFIED; goto done; } uint32_t flags = 0; if (mbedtls_x509_crt_verify(&certs->leaf, &certs->root, NULL, NULL, &flags, - accepted_time, &reload) != 0 || flags) goto done; + accepted_time, &defer_time) != 0 || flags) goto done; result = TS_CONFIG_PACK_ERR_SIGNER_ROLE; if(!mbedtls_pk_can_do(&certs->leaf.pk,MBEDTLS_PK_ECDSA) || mbedtls_pk_ec(certs->leaf.pk)->MBEDTLS_PRIVATE(grp).id!=MBEDTLS_ECP_DP_SECP256R1)goto done; @@ -85,7 +87,7 @@ ts_config_pack_result_t ts_config_pack_signer_trust(const char *signer, mbedtls_x509_crt_check_key_usage(&certs->leaf, MBEDTLS_X509_KU_DIGITAL_SIGNATURE)) goto done; /* No invented mandatory EKU. If a signer carries EKU restrictions, it must * permit code signing or any usage; a TLS-only certificate is not a signing credential. */ - if (certs->leaf.MBEDTLS_PRIVATE(ext_types) & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE) { + if (require_code_signing && (certs->leaf.MBEDTLS_PRIVATE(ext_types) & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE)) { bool allowed = false; for (const mbedtls_x509_sequence *s = &certs->leaf.ext_key_usage; s; s = s->next) allowed |= (s->buf.len == MBEDTLS_OID_SIZE(MBEDTLS_OID_CODE_SIGNING) && @@ -95,8 +97,8 @@ ts_config_pack_result_t ts_config_pack_signer_trust(const char *signer, if (!allowed) goto done; } if (out) { - memset(out, 0, sizeof(*out)); out->policy = ACCEPT_POLICY; - out->accepted_at = reload ? accepted->accepted_at : (int64_t)time(NULL); + memset(out, 0, sizeof(*out)); out->policy = TS_CONFIG_PACK_ACCEPT_POLICY; + out->accepted_at = reload ? accepted->accepted_at : status.time_ready ? (int64_t)time(NULL) : 0; strcpy(out->package_sha256, package_hash); strcpy(out->recipient, recipient); strcpy(out->signer_sha256, signer_hash); strcpy(out->root_sha256, root_hash); } diff --git a/components/ts_config_pack/src/ts_config_pack_trust.h b/components/ts_config_pack/src/ts_config_pack_trust.h index f1679854..4a273ebe 100644 --- a/components/ts_config_pack/src/ts_config_pack_trust.h +++ b/components/ts_config_pack/src/ts_config_pack_trust.h @@ -3,4 +3,10 @@ #include "ts_cert.h" ts_config_pack_result_t ts_config_pack_signer_trust(const char *signer, const ts_cert_snapshot_t *snapshot, const char *package_hash, const char *recipient, + bool require_code_signing, bool existing_file, const ts_config_pack_acceptance_t *accepted, ts_config_pack_acceptance_t *out); + +#ifndef CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256 +#define CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256 "" +#endif +#define TS_CONFIG_PACK_ACCEPT_POLICY 1 diff --git a/components/ts_console/commands/ts_cmd_fs.c b/components/ts_console/commands/ts_cmd_fs.c index a6186cb3..d601a2b9 100644 --- a/components/ts_console/commands/ts_cmd_fs.c +++ b/components/ts_console/commands/ts_cmd_fs.c @@ -351,7 +351,7 @@ static struct { static int fs_mutation_error(const char *command, const char *path, esp_err_t ret) { if (ret == ESP_ERR_NOT_ALLOWED) { - ts_console_error("%s: '%s' belongs to Automation. Use Automation > Configuration & backup, or edit items in their lists.\n", command, path); + ts_console_error("%s: '%s' is protected. Use its dedicated configuration or update workflow.\n", command, path); } else if (ret == ESP_ERR_INVALID_ARG) { ts_console_error("%s: invalid path '%s'.\n", command, path); } else { diff --git a/components/ts_console/commands/ts_cmd_key.c b/components/ts_console/commands/ts_cmd_key.c index 1f3397fc..188fd413 100644 --- a/components/ts_console/commands/ts_cmd_key.c +++ b/components/ts_console/commands/ts_cmd_key.c @@ -481,7 +481,7 @@ static int do_key_export(const char *key_id, const char *output_path) if (ret != ESP_OK) { ts_console_printf("FAILED\n"); ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? " This file belongs to Automation. Choose another export path.\n" + ? " This path is protected. Choose another export path.\n" : " Could not save the public key. Check the path and storage.\n"); return 1; } @@ -514,7 +514,7 @@ static int do_key_export_private(const char *key_id, const char *output_path) esp_err_t ret = ts_storage_check_write_path(output_path, false); if (ret != ESP_OK) { ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? "This file belongs to Automation. Choose another export path.\n" : "Invalid export path.\n"); + ? "This path is protected. Choose another export path.\n" : "Invalid export path.\n"); return 1; } diff --git a/components/ts_console/commands/ts_cmd_led.c b/components/ts_console/commands/ts_cmd_led.c index 55223f26..d8493404 100644 --- a/components/ts_console/commands/ts_cmd_led.c +++ b/components/ts_console/commands/ts_cmd_led.c @@ -1531,14 +1531,14 @@ static int do_led_draw_text(const char *device_name, const char *text, char raw_text[256] = {0}; const char *cmdline = ts_console_get_raw_cmdline(); if (cmdline && extract_text_from_cmdline(cmdline, raw_text, sizeof(raw_text))) { - TS_LOGI(TAG, "Extracted text from raw cmdline: %s", raw_text); + TS_LOGI(TAG, "Extracted text from raw cmdline (%zu bytes)", strlen(raw_text)); text = raw_text; // 使用从原始命令行提取的文本 // 同时尝试从原始命令行提取其他参数(因为 argtable3 可能解析失败) static char raw_font[32], raw_color[32], raw_align[16]; if (!font_name && extract_param_from_cmdline(cmdline, "--font", raw_font, sizeof(raw_font))) { font_name = raw_font; - TS_LOGI(TAG, "Extracted font from raw cmdline: %s", font_name); + TS_LOGI(TAG, "Extracted font option from raw cmdline"); } if (!color_str && extract_param_from_cmdline(cmdline, "--color", raw_color, sizeof(raw_color))) { color_str = raw_color; @@ -1548,16 +1548,6 @@ static int do_led_draw_text(const char *device_name, const char *text, } } - // 调试:显示 text 的原始字节 - if (text) { - char hex_buf[256] = {0}; - int pos = 0; - for (size_t i = 0; i < strlen(text) && pos < 250; i++) { - pos += snprintf(hex_buf + pos, sizeof(hex_buf) - pos, "%02X ", (uint8_t)text[i]); - } - TS_LOGI(TAG, "text bytes: %s", hex_buf); - } - // 文本内容:优先使用文件,其次使用 --text 参数 char text_buf[256] = {0}; const char *display_text = text; @@ -1577,7 +1567,7 @@ static int do_led_draw_text(const char *device_name, const char *text, text_buf[--n] = '\0'; } display_text = text_buf; - TS_LOGI(TAG, "Read text from file: %s (%zu bytes)", text_file, n); + TS_LOGI(TAG, "Read text from file (%zu bytes)", n); } if (!display_text || strlen(display_text) == 0) { @@ -1639,8 +1629,8 @@ static int do_led_draw_text(const char *device_name, const char *text, } strncpy(s_current_font_name, font_name, sizeof(s_current_font_name) - 1); - TS_LOGI(TAG, "Font loaded: %s (%ux%u, %lu glyphs)", - font_path, s_current_font->header.width, + TS_LOGI(TAG, "Font loaded (%ux%u, %lu glyphs)", + s_current_font->header.width, s_current_font->header.height, (unsigned long)s_current_font->header.glyph_count); } @@ -2106,18 +2096,9 @@ static int cmd_led(int argc, char **argv) bool is_draw_text_from_cmdline = false; const char *cmdline = ts_console_get_raw_cmdline(); - // 调试:打印原始命令行 - TS_LOGI(TAG, "nerrors=%d, cmdline=%s", nerrors, cmdline ? cmdline : "(null)"); - if (cmdline) { - // 打印原始字节 - char hex_buf[128] = {0}; - int pos = 0; - for (size_t i = 0; i < strlen(cmdline) && i < 40 && pos < 120; i++) { - pos += snprintf(hex_buf + pos, sizeof(hex_buf) - pos, "%02X ", (uint8_t)cmdline[i]); - } - TS_LOGI(TAG, "cmdline bytes: %s", hex_buf); - } - + // Shared diagnostics retain parser state, never command contents. + TS_LOGI(TAG, "LED argument parse errors=%d, raw command present=%d", nerrors, cmdline != NULL); + if (nerrors != 0 && cmdline) { // 直接从原始命令行检查是否包含 --draw-text if (strstr(cmdline, "--draw-text")) { @@ -2132,7 +2113,7 @@ static int cmd_led(int argc, char **argv) char test_buf[64]; if (extract_text_from_cmdline(cmdline, test_buf, sizeof(test_buf))) { can_recover_from_raw_cmdline = true; - TS_LOGI(TAG, "Recovering from UTF-8 parse error, extracted: %s", test_buf); + TS_LOGI(TAG, "Recovering from UTF-8 parse error (%zu text bytes)", strlen(test_buf)); break; } else { TS_LOGW(TAG, "extract_text_from_cmdline failed"); diff --git a/components/ts_console/commands/ts_cmd_pki.c b/components/ts_console/commands/ts_cmd_pki.c index aaea11de..816d7a72 100644 --- a/components/ts_console/commands/ts_cmd_pki.c +++ b/components/ts_console/commands/ts_cmd_pki.c @@ -326,7 +326,7 @@ static int cmd_pki_export_csr(const char *filepath) free(csr_buf); if (err != ESP_OK) { ts_console_printf(err == ESP_ERR_NOT_ALLOWED - ? "This file belongs to Automation. Choose another export path.\n" + ? "This path is protected. Choose another export path.\n" : "Could not save the CSR. Check the path and storage.\n"); return 1; } diff --git a/components/ts_console/commands/ts_cmd_sftp.c b/components/ts_console/commands/ts_cmd_sftp.c index afe412c9..ce2ba256 100644 --- a/components/ts_console/commands/ts_cmd_sftp.c +++ b/components/ts_console/commands/ts_cmd_sftp.c @@ -260,7 +260,7 @@ static int do_file_get(const char *host, int port, const char *user, esp_err_t ret = ts_storage_check_write_path(local_path, false); if (ret != ESP_OK) { ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? "This file belongs to Automation. Choose another download path.\n" + ? "This path is protected. Choose another download path.\n" : "Invalid local download path.\n"); return 1; } @@ -314,7 +314,7 @@ static int do_file_get(const char *host, int port, const char *user, return 0; } else { ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? "This file belongs to Automation. Choose another download path.\n" : "✗ Download failed\n"); + ? "This path is protected. Choose another download path.\n" : "✗ Download failed\n"); return 1; } } diff --git a/components/ts_console/commands/ts_cmd_ssh.c b/components/ts_console/commands/ts_cmd_ssh.c index 31536a0e..76f041d2 100644 --- a/components/ts_console/commands/ts_cmd_ssh.c +++ b/components/ts_console/commands/ts_cmd_ssh.c @@ -1481,7 +1481,7 @@ static int do_ssh_keygen(const char *type_str, const char *output_path, const ch free(private_pem); if (ret != ESP_OK) { ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? "FAILED: This file belongs to Automation. Choose another output path.\n" + ? "FAILED: This path is protected. Choose another output path.\n" : "FAILED: Could not save the private key. Check the path and storage.\n"); ts_crypto_keypair_free(keypair); return 1; @@ -1515,7 +1515,7 @@ static int do_ssh_keygen(const char *type_str, const char *output_path, const ch ret = ts_storage_write_file(pub_path, openssh_pub, strlen(openssh_pub)); if (ret != ESP_OK) { ts_console_printf(ret == ESP_ERR_NOT_ALLOWED - ? "FAILED: This file belongs to Automation. Choose another output path.\n" + ? "FAILED: This path is protected. Choose another output path.\n" : "FAILED: Could not save the public key. Check the path and storage.\n"); free(openssh_pub); ts_crypto_keypair_free(keypair); diff --git a/components/ts_console/src/ts_console_builtin.c b/components/ts_console/src/ts_console_builtin.c index debb5b0e..3d0bb8ec 100644 --- a/components/ts_console/src/ts_console_builtin.c +++ b/components/ts_console/src/ts_console_builtin.c @@ -8,6 +8,7 @@ */ #include "ts_console.h" +#include "ts_ota.h" #include "ts_console_args.h" #include "ts_i18n.h" #include "ts_log.h" diff --git a/components/ts_core/ts_config/include/ts_config_file.h b/components/ts_core/ts_config/include/ts_config_file.h index 53a8f3a7..924bc359 100644 --- a/components/ts_core/ts_config/include/ts_config_file.h +++ b/components/ts_core/ts_config/include/ts_config_file.h @@ -69,20 +69,7 @@ esp_err_t ts_config_file_save_all(void); */ const ts_config_backend_ops_t *ts_config_file_get_ops(void); -/** - * @brief 加载加密配置文件 (.tscfg) - * - * 在证书系统初始化后调用,加载 SD 卡上的加密配置包。 - * 此函数应在 ts_cert_init() 之后、security 服务启动后调用。 - * - * 加载逻辑: - * - 遍历配置目录中的 .tscfg 文件 - * - 验证签名并解密 - * - 解密后的 JSON 内容会覆盖之前从 .json 加载的同名配置 - * - * @return ESP_OK 成功(即使部分文件加载失败) - */ -esp_err_t ts_config_file_load_encrypted(void); + #ifdef __cplusplus } diff --git a/components/ts_core/ts_config/include/ts_config_partitions.h b/components/ts_core/ts_config/include/ts_config_partitions.h index ba820e8e..1fc4ec9e 100644 --- a/components/ts_core/ts_config/include/ts_config_partitions.h +++ b/components/ts_core/ts_config/include/ts_config_partitions.h @@ -18,7 +18,9 @@ extern "C" { esp_err_t ts_config_partitions_init(void); /* Before configuration schemas, authentication, networking or drivers start. - * SD must already have been checked. Completion is recorded before cleanup. */ + * SD must already have been checked. Completion is recorded before cleanup. + * NOT_FINISHED: encrypted SD data awaits trusted publisher/time admission. + * Continue boot with the already copied internal settings; retry on reboot. */ esp_err_t ts_config_migrate_system(bool sd_available); #ifdef __cplusplus diff --git a/components/ts_core/ts_config/src/ts_config_file.c b/components/ts_core/ts_config/src/ts_config_file.c index 52ea533b..1d734653 100644 --- a/components/ts_core/ts_config/src/ts_config_file.c +++ b/components/ts_core/ts_config/src/ts_config_file.c @@ -22,7 +22,6 @@ #include "ts_config.h" #include "ts_config_file.h" #include "ts_config_module.h" -#include "ts_config_pack.h" #include "esp_log.h" #include "esp_vfs.h" #include "esp_heap_caps.h" @@ -234,7 +233,7 @@ esp_err_t ts_config_file_load_all(void) } // 遍历目录,加载 JSON 配置文件 - // 注意: .tscfg 加密配置在 security 服务启动后由 ts_config_file_load_encrypted() 加载 + // Encrypted files belong to the one-time migration/configuration owner. DIR *dir = opendir(s_config_path); if (dir == NULL) { ESP_LOGE(TAG, "Failed to open configuration directory"); @@ -285,7 +284,7 @@ esp_err_t ts_config_file_load_all(void) const char *ext = strrchr(entry->d_name, '.'); if (ext == NULL) continue; - // 只处理 .json 明文配置(.tscfg 由 ts_config_file_load_encrypted() 在 security 服务启动后加载) + // This generic backend never replays encrypted system/automation files. if (strcmp(ext, ".json") != 0) continue; snprintf(filepath, MAX_PATH_LEN, "%.127s/%.127s", s_config_path, entry->d_name); @@ -340,88 +339,6 @@ esp_err_t ts_config_file_load_all(void) return ESP_OK; } -esp_err_t ts_config_file_load_encrypted(void) -{ - if (!s_file_initialized) { - return ESP_ERR_INVALID_STATE; - } - - // 首先初始化 config pack 子系统(需要证书已加载) - esp_err_t init_ret = ts_config_pack_init(); - if (init_ret != ESP_OK) { - ESP_LOGW(TAG, "Config pack init failed: %s, skipping encrypted configs", - esp_err_to_name(init_ret)); - return ESP_OK; // 不是致命错误 - } - - ESP_LOGI(TAG, "Loading encrypted configuration files from: %s", s_config_path); - - // 检查目录是否存在 - if (!path_exists(s_config_path)) { - ESP_LOGD(TAG, "Configuration path does not exist"); - return ESP_OK; - } - - DIR *dir = opendir(s_config_path); - if (dir == NULL) { - ESP_LOGE(TAG, "Failed to open configuration directory"); - return ESP_FAIL; - } - - int loaded_count = 0; - int failed_count = 0; - struct dirent *entry; - - // 堆分配避免栈溢出 - #define TSCFG_MAX_PATH_LEN 256 - char *filepath = heap_caps_malloc(TSCFG_MAX_PATH_LEN, MALLOC_CAP_SPIRAM); - if (filepath == NULL) { - closedir(dir); - return ESP_ERR_NO_MEM; - } - - while ((entry = readdir(dir)) != NULL) { - const char *ext = strrchr(entry->d_name, '.'); - if (ext == NULL || strcmp(ext, ".tscfg") != 0) { - continue; - } - - snprintf(filepath, TSCFG_MAX_PATH_LEN, "%.127s/%.127s", s_config_path, entry->d_name); - - ESP_LOGI(TAG, "Loading encrypted: %s", entry->d_name); - - // 解密并加载配置 - ts_config_pack_t *pack = NULL; - ts_config_pack_result_t pack_ret = ts_config_pack_load(filepath, &pack); - - if (pack_ret == TS_CONFIG_PACK_OK && pack && pack->content) { - // 解密成功,解析 JSON 并应用配置 - esp_err_t ret = ts_config_load_json_string(pack->content); - if (ret == ESP_OK) { - ESP_LOGI(TAG, "Loaded encrypted config: %s (signer: %s)", - entry->d_name, pack->sig_info.signer_cn); - loaded_count++; - } else { - ESP_LOGW(TAG, "Failed to parse decrypted content: %s", entry->d_name); - failed_count++; - } - ts_config_pack_free(pack); - } else { - ESP_LOGW(TAG, "Failed to decrypt %s: %s", entry->d_name, - ts_config_pack_strerror(pack_ret)); - failed_count++; - } - } - - free(filepath); - closedir(dir); - - if (loaded_count > 0 || failed_count > 0) { - ESP_LOGI(TAG, "Encrypted configs: %d loaded, %d failed", loaded_count, failed_count); - } - return ESP_OK; -} - esp_err_t ts_config_file_save_all(void) { if (!s_file_initialized) { diff --git a/components/ts_core/ts_config/src/ts_config_migrate.c b/components/ts_core/ts_config/src/ts_config_migrate.c index c77dddff..c40b845a 100644 --- a/components/ts_core/ts_config/src/ts_config_migrate.c +++ b/components/ts_core/ts_config/src/ts_config_migrate.c @@ -116,12 +116,14 @@ static esp_err_t visit_system_entries(bool remove) /* Encrypted legacy files keep precedence. A selected but unreadable pack must * not silently import a different plaintext configuration or finish migration. */ -static esp_err_t read_system_file(const char *path, char **raw, size_t *length) +static esp_err_t read_system_file(const char *path, char **raw, size_t *length, bool *encrypted_source) { + *encrypted_source = false; char encrypted[80]; snprintf(encrypted, sizeof(encrypted), "%.*s.tscfg", (int)strlen(path) - 5, path); struct stat st; if (stat(encrypted, &st) == 0) { + *encrypted_source = true; esp_err_t ret = ts_cert_init(); if (ret == ESP_OK) ret = ts_config_pack_init(); if (ret != ESP_OK) return ret; @@ -129,7 +131,9 @@ static esp_err_t read_system_file(const char *path, char **raw, size_t *length) ts_config_pack_result_t packed = ts_config_pack_load(encrypted, &pack); if (packed != TS_CONFIG_PACK_OK || !pack || !pack->content) { ts_config_pack_free(pack); - return ESP_FAIL; + ESP_LOGW(TAG, "Encrypted system config deferred (%s): %s", encrypted, + ts_config_pack_strerror(packed)); + return ESP_ERR_NOT_FINISHED; } *raw = pack->content; *length = pack->content_len; @@ -175,34 +179,42 @@ static esp_err_t import_system_files(void) nvs_close(old); } if (ret != ESP_OK && ret != ESP_ERR_NVS_NOT_FOUND) return ret; - for (size_t i = 0; i < sizeof(modules) / sizeof(modules[0]); ++i) { + enum { MODULE_COUNT = sizeof(modules) / sizeof(modules[0]) }; + char *contents[MODULE_COUNT] = {0}; + size_t lengths[MODULE_COUNT] = {0}; + /* Verify every selected source before writing any SD-derived system value. + * This avoids partially applying earlier files when a later signer fails. */ + for (size_t i = 0; i < MODULE_COUNT; ++i) { if (i < 9 && (pending & (1U << i))) continue; char path[80]; snprintf(path, sizeof(path), "/sdcard/config/%s.json", modules[i].file); - char *raw = NULL; - size_t length = 0; - ret = read_system_file(path, &raw, &length); - if (ret == ESP_ERR_NOT_FOUND) continue; - if (ret != ESP_OK) return ret; - cJSON *json = cJSON_ParseWithLengthOpts(raw, length + 1, NULL, true); + bool encrypted = false; + ret = read_system_file(path, &contents[i], &lengths[i], &encrypted); + if (ret == ESP_ERR_NOT_FOUND) { ret = ESP_OK; continue; } + if (ret != ESP_OK) goto done; + cJSON *json = cJSON_ParseWithLengthOpts(contents[i], lengths[i] + 1, NULL, true); bool valid = cJSON_IsObject(json); cJSON_Delete(json); if (!valid) { - ESP_LOGW(TAG, "Ignoring invalid legacy system file: %s", path); - free(raw); - continue; + ESP_LOGW(TAG, "Invalid legacy system file: %s", path); + free(contents[i]); contents[i] = NULL; + if (encrypted) { ret = ESP_ERR_NOT_FINISHED; goto done; } } + } + for (size_t i = 0; i < MODULE_COUNT; ++i) { + if (!contents[i]) continue; nvs_handle_t to; ret = nvs_open(modules[i].ns, NVS_READWRITE, &to); if (ret == ESP_OK) { - ret = nvs_set_blob(to, modules[i].key, raw, length); + ret = nvs_set_blob(to, modules[i].key, contents[i], lengths[i]); if (ret == ESP_OK) ret = nvs_commit(to); nvs_close(to); } - free(raw); - if (ret != ESP_OK) return ret; + if (ret != ESP_OK) break; } - return ESP_OK; +done: + for (size_t i = 0; i < MODULE_COUNT; ++i) free(contents[i]); + return ret; } esp_err_t ts_config_migrate_system(bool sd_available) @@ -213,8 +225,19 @@ esp_err_t ts_config_migrate_system(bool sd_available) uint8_t version = 0; ret = nvs_get_u8(state, "system_v", &version); if (ret == ESP_ERR_NVS_NOT_FOUND) ret = ESP_OK; + if (ret == ESP_OK && version > 1) ret = ESP_ERR_NOT_SUPPORTED; if (ret == ESP_OK && version != 1) { - ret = visit_system_entries(false); + uint8_t base = 0; + ret = nvs_get_u8(state, "system_base_v", &base); + if (ret == ESP_ERR_NVS_NOT_FOUND) ret = ESP_OK; + if (ret == ESP_OK && base > 1) ret = ESP_ERR_NOT_SUPPORTED; + if (ret == ESP_OK && base != 1) { + ret = visit_system_entries(false); + if (ret == ESP_OK) ret = nvs_set_u8(state, "system_base_v", 1); + if (ret == ESP_OK) ret = nvs_commit(state); + } + /* A clock/trust-deferred SD import must never replay old credentials + * over Root changes made through the reachable Web UI in the meantime. */ if (ret == ESP_OK && sd_available) ret = import_system_files(); if (ret == ESP_OK) ret = nvs_set_u8(state, "system_v", 1); if (ret == ESP_OK) ret = nvs_commit(state); diff --git a/components/ts_core/ts_event/include/ts_event.h b/components/ts_core/ts_event/include/ts_event.h index 10f15052..604bb831 100644 --- a/components/ts_core/ts_event/include/ts_event.h +++ b/components/ts_core/ts_event/include/ts_event.h @@ -280,14 +280,7 @@ typedef struct { * OTA 事件 ID * ========================================================================== */ -/** OTA 进度更新 */ -#define TS_EVENT_OTA_PROGRESS_UPDATE 0x0601 -/** OTA 开始 */ -#define TS_EVENT_OTA_STARTED 0x0602 -/** OTA 完成 */ -#define TS_EVENT_OTA_FINISHED 0x0603 -/** OTA 失败 */ -#define TS_EVENT_OTA_FAILED 0x0604 +#include "ts_ota_events.h" /* ============================================================================ * 事件基础别名(兼容旧代码) diff --git a/components/ts_core/ts_event/include/ts_ota_events.h b/components/ts_core/ts_event/include/ts_ota_events.h new file mode 100644 index 00000000..d177ce61 --- /dev/null +++ b/components/ts_core/ts_event/include/ts_ota_events.h @@ -0,0 +1,17 @@ +#pragma once + +/* One OTA event contract for publishers and subscribers, independent of SDK + * headers and include order. Existing event-bus IDs remain unchanged. */ +typedef enum { + TS_EVENT_OTA_PROGRESS_UPDATE = 0x0601, + TS_EVENT_OTA_PROGRESS = TS_EVENT_OTA_PROGRESS_UPDATE, + TS_EVENT_OTA_STARTED = 0x0602, + TS_EVENT_OTA_FINISHED = 0x0603, + TS_EVENT_OTA_COMPLETED = TS_EVENT_OTA_FINISHED, + TS_EVENT_OTA_FAILED = 0x0604, + TS_EVENT_OTA_ABORTED = 0x0605, + TS_EVENT_OTA_PENDING_REBOOT = 0x0606, + TS_EVENT_OTA_ROLLBACK_PENDING = 0x0607, + TS_EVENT_OTA_ROLLBACK_EXECUTED = 0x0608, + TS_EVENT_OTA_VALIDATED = 0x0609 +} ts_event_ota_id_t; diff --git a/components/ts_dns/CMakeLists.txt b/components/ts_dns/CMakeLists.txt new file mode 100644 index 00000000..83c1c700 --- /dev/null +++ b/components/ts_dns/CMakeLists.txt @@ -0,0 +1,6 @@ +idf_component_register( + SRCS "src/ts_dns.c" + INCLUDE_DIRS "include" + REQUIRES esp_common lwip + PRIV_REQUIRES esp_timer freertos +) diff --git a/components/ts_dns/include/ts_dns.h b/components/ts_dns/include/ts_dns.h new file mode 100644 index 00000000..1fdba043 --- /dev/null +++ b/components/ts_dns/include/ts_dns.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include +#include "esp_err.h" +#include "lwip/ip_addr.h" + +/* Worker tasks only, never the TCP/IP thread. No additional resolver task is + * created. At most one unresolved callback is allocated, even after its caller + * times out/cancels. Callers still own their worker/request admission budget. + * DNS supplies an address, not server identity or permission to contact it. */ +esp_err_t ts_dns_resolve(const char *hostname, int64_t deadline_us, + bool (*still_current)(void *), void *context, ip_addr_t *address); diff --git a/components/ts_dns/src/ts_dns.c b/components/ts_dns/src/ts_dns.c new file mode 100644 index 00000000..582db9b2 --- /dev/null +++ b/components/ts_dns/src/ts_dns.c @@ -0,0 +1,120 @@ +#include "ts_dns.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "esp_timer.h" +#include "lwip/dns.h" +#include "lwip/tcpip.h" +#include +#include +#include + +typedef struct { + atomic_uint references; + atomic_bool wanted; + int64_t deadline; + SemaphoreHandle_t completed; + ip_addr_t address; + esp_err_t result; + char hostname[DNS_MAX_NAME_LENGTH]; +} resolve_request_t; + +static atomic_bool s_query_active; + +static void release_request(resolve_request_t *request) +{ + if (atomic_fetch_sub(&request->references, 1) == 1) { + vSemaphoreDelete(request->completed); + free(request); + } +} + +static void resolved(const char *name, const ip_addr_t *address, void *context) +{ + (void)name; + resolve_request_t *request = context; + request->result = address ? ESP_OK : ESP_ERR_NOT_FOUND; + if (address) ip_addr_copy(request->address, *address); + /* The old callback never touches this admission flag after waking a caller + * that may immediately finish its job and start another resolution. */ + atomic_store(&s_query_active, false); + xSemaphoreGive(request->completed); + release_request(request); +} + +static void start_query(void *context) +{ + resolve_request_t *request = context; + if (!atomic_load(&request->wanted) || esp_timer_get_time() >= request->deadline) { + resolved(NULL, NULL, request); + return; + } + err_t result = dns_gethostbyname_addrtype(request->hostname, &request->address, + resolved, request, LWIP_DNS_ADDRTYPE_DEFAULT); + if (result == ERR_OK) resolved(NULL, &request->address, request); + else if (result != ERR_INPROGRESS) resolved(NULL, NULL, request); +} + +static esp_err_t allowed(int64_t deadline, bool (*still_current)(void *), void *context) +{ + if (still_current && !still_current(context)) return ESP_ERR_INVALID_STATE; + return esp_timer_get_time() < deadline ? ESP_OK : ESP_ERR_TIMEOUT; +} + +esp_err_t ts_dns_resolve(const char *hostname, int64_t deadline, + bool (*still_current)(void *), void *context, ip_addr_t *address) +{ + if (!address) return ESP_ERR_INVALID_ARG; + ip_addr_set_zero(address); + if (!hostname) return ESP_ERR_INVALID_ARG; + size_t length = strnlen(hostname, DNS_MAX_NAME_LENGTH); + if (!length || length == DNS_MAX_NAME_LENGTH) return ESP_ERR_INVALID_ARG; + esp_err_t result = allowed(deadline, still_current, context); + if (result != ESP_OK) return result; + ip_addr_t literal; + if (ipaddr_aton(hostname, &literal)) { ip_addr_copy(*address, literal); return ESP_OK; } + for (;;) { + result = allowed(deadline, still_current, context); + if (result != ESP_OK) return result; + bool available = false; + if (atomic_compare_exchange_strong(&s_query_active, &available, true)) break; + vTaskDelay(1); + } + resolve_request_t *request = calloc(1, sizeof(*request)); + if (!request) { atomic_store(&s_query_active, false); return ESP_ERR_NO_MEM; } + request->completed = xSemaphoreCreateBinary(); + if (!request->completed) { free(request); atomic_store(&s_query_active, false); return ESP_ERR_NO_MEM; } + atomic_init(&request->references, 2); /* caller plus queued/DNS callback */ + atomic_init(&request->wanted, true); + request->deadline = deadline; + memcpy(request->hostname, hostname, length); + request->hostname[length] = 0; + if (tcpip_try_callback(start_query, request) != ERR_OK) { + atomic_store(&s_query_active, false); + release_request(request); + release_request(request); + return ESP_ERR_NO_MEM; + } + for (;;) { + result = allowed(deadline, still_current, context); + if (result != ESP_OK) break; + int64_t milliseconds = (deadline - esp_timer_get_time() + 999) / 1000; + if (milliseconds <= 0) { result = ESP_ERR_TIMEOUT; break; } + if (milliseconds > 20) milliseconds = 20; + TickType_t ticks = pdMS_TO_TICKS((uint32_t)milliseconds); + if (!ticks) ticks = 1; + if (xSemaphoreTake(request->completed, ticks) == pdTRUE) { + result = allowed(deadline, still_current, context); + if (result == ESP_OK) { + result = request->result; + if (result == ESP_OK) ip_addr_copy(*address, request->address); + } + break; + } + } + /* Timeout/cancel relinquishes only the caller's reference. The callback's + * semaphore/input stay alive, and it releases the sole query slot later. */ + atomic_store(&request->wanted, false); + release_request(request); + return result; +} diff --git a/components/ts_drivers/CMakeLists.txt b/components/ts_drivers/CMakeLists.txt index 71607edc..23effde8 100644 --- a/components/ts_drivers/CMakeLists.txt +++ b/components/ts_drivers/CMakeLists.txt @@ -15,6 +15,7 @@ idf_component_register( ts_core ts_hal PRIV_REQUIRES + ts_http_fetch driver esp_adc esp_timer diff --git a/components/ts_drivers/src/ts_compute_monitor.c b/components/ts_drivers/src/ts_compute_monitor.c index 09a5a243..cfee63f0 100644 --- a/components/ts_drivers/src/ts_compute_monitor.c +++ b/components/ts_drivers/src/ts_compute_monitor.c @@ -1,3 +1,4 @@ +#include "ts_http_fetch.h" /** * @file ts_compute_monitor.c * @brief Compute Device Monitor Implementation for TianShanOS @@ -25,7 +26,6 @@ #include "esp_log.h" #include "esp_timer.h" #include "esp_websocket_client.h" -#include "esp_http_client.h" #include "nvs_flash.h" #include "nvs.h" #include "cJSON.h" @@ -121,7 +121,7 @@ static void compute_monitor_task(void *arg); static esp_err_t socketio_handshake(void); static void websocket_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data); -static esp_err_t parse_tegrastats_data(const char *json_str, ts_compute_data_t *data); +static esp_err_t parse_tegrastats_data(const cJSON *root, ts_compute_data_t *data); static void update_temp_source(const ts_compute_data_t *data); static void publish_status_event(ts_compute_status_t status); static void publish_data_event(const ts_compute_data_t *data); @@ -700,80 +700,38 @@ static void update_temp_source(const ts_compute_data_t *data) * * 获取 session id 和配置 */ +static bool compute_http_current(void *context) +{ + return !atomic_load(&((compute_monitor_ctx_t *)context)->should_stop); +} + static esp_err_t socketio_handshake(void) { + compute_monitor_ctx_t *ctx = s_ctx; char url[256]; - snprintf(url, sizeof(url), - "http://%s:%d/socket.io/?EIO=4&transport=polling", - s_ctx->config.server_ip, s_ctx->config.server_port); - - ESP_LOGI(TAG, "Socket.IO handshake: %s", url); - - esp_http_client_config_t http_cfg = { - .url = url, - .timeout_ms = 5000, - }; - - esp_http_client_handle_t client = esp_http_client_init(&http_cfg); - if (client == NULL) { - set_error("HTTP client init failed"); - return ESP_FAIL; - } - - esp_err_t err = esp_http_client_open(client, 0); - if (err != ESP_OK) { - set_error("HTTP open failed"); - esp_http_client_cleanup(client); - return err; - } - - int content_length = esp_http_client_fetch_headers(client); - if (content_length < 0) { - set_error("HTTP fetch headers failed"); - esp_http_client_close(client); - esp_http_client_cleanup(client); - return ESP_FAIL; - } - - char buffer[HTTP_BUFFER_SIZE]; - int read_len = esp_http_client_read(client, buffer, sizeof(buffer) - 1); - - esp_http_client_close(client); - esp_http_client_cleanup(client); - - if (read_len <= 0) { - set_error("HTTP read failed"); - return ESP_FAIL; - } - - buffer[read_len] = '\0'; - ESP_LOGD(TAG, "Handshake response: %s", buffer); - - /* 解析响应:格式为 "0{\"sid\":\"xxxxx\",...}" */ - char *json_start = strchr(buffer, '{'); - if (json_start == NULL) { - set_error("Invalid handshake response"); - return ESP_FAIL; - } - - cJSON *root = cJSON_Parse(json_start); - if (root == NULL) { - set_error("JSON parse failed"); - return ESP_FAIL; - } - - cJSON *sid = cJSON_GetObjectItem(root, "sid"); - if (sid == NULL || !cJSON_IsString(sid)) { - set_error("SID not found"); - cJSON_Delete(root); - return ESP_FAIL; + int size = snprintf(url, sizeof(url), "http://%s:%d/socket.io/?EIO=4&transport=polling", + ctx->config.server_ip, ctx->config.server_port); + if (size < 0 || (size_t)size >= sizeof(url)) return ESP_ERR_INVALID_SIZE; + ts_http_fetch_config_t request = {.url = url, .method = HTTP_METHOD_GET, + .timeout_ms = 5000, .maximum_body = HTTP_BUFFER_SIZE - 1, + .current = compute_http_current, .context = ctx}; + ts_http_fetch_result_t reply = {0}; + esp_err_t ret = ts_http_fetch(&request, &reply); + if (ret != ESP_OK) { set_error("HTTP handshake failed"); return ret; } + const char *start = reply.status == 200 && reply.body ? strchr(reply.body, '{') : NULL; + cJSON *json = start ? cJSON_Parse(start) : NULL; + const cJSON *sid = json ? cJSON_GetObjectItemCaseSensitive(json, "sid") : NULL; + ret = ESP_ERR_INVALID_RESPONSE; + if (cJSON_IsString(sid)) { + size_t length = strlen(sid->valuestring); + if (length && length < sizeof(ctx->session_id)) { + memcpy(ctx->session_id, sid->valuestring, length + 1); + ret = ESP_OK; + } } - - strncpy(s_ctx->session_id, sid->valuestring, sizeof(s_ctx->session_id) - 1); - cJSON_Delete(root); - - ESP_LOGI(TAG, "Got session ID: %s", s_ctx->session_id); - return ESP_OK; + cJSON_Delete(json); free(reply.body); + if (ret != ESP_OK) set_error("Invalid handshake response"); + return ret; } /** @@ -809,7 +767,7 @@ static void websocket_event_handler(void *arg, esp_event_base_t event_base, if (data->data_len > 0 && data->data_ptr != NULL) { char *msg = strndup(data->data_ptr, data->data_len); if (msg != NULL) { - ESP_LOGD(TAG, "WS recv: %s", msg); + ESP_LOGD(TAG, "WebSocket frame received (bytes=%d)", data->data_len); /* 处理 Socket.IO 消息 */ if (strcmp(msg, "3probe") == 0) { @@ -852,7 +810,7 @@ static void websocket_event_handler(void *arg, esp_event_base_t event_base, memset(&agx_data, 0, sizeof(agx_data)); if (parse_tegrastats_data( - cJSON_Print(event_data_json), + event_data_json, &agx_data) == ESP_OK) { /* 更新数据 */ @@ -906,18 +864,10 @@ static void websocket_event_handler(void *arg, esp_event_base_t event_base, /** * @brief 解析 tegrastats 数据 */ -static esp_err_t parse_tegrastats_data(const char *json_str, ts_compute_data_t *data) +static esp_err_t parse_tegrastats_data(const cJSON *root, ts_compute_data_t *data) { - if (json_str == NULL || data == NULL) { - return ESP_ERR_INVALID_ARG; - } - - cJSON *root = cJSON_Parse(json_str); - if (root == NULL) { - ESP_LOGE(TAG, "Failed to parse tegrastats JSON"); - return ESP_FAIL; - } - + if (!cJSON_IsObject(root) || !data) return ESP_ERR_INVALID_ARG; + /* 时间戳 */ cJSON *timestamp = cJSON_GetObjectItem(root, "timestamp"); if (timestamp != NULL && cJSON_IsString(timestamp)) { @@ -1021,7 +971,6 @@ static esp_err_t parse_tegrastats_data(const char *json_str, ts_compute_data_t * } } - cJSON_Delete(root); return ESP_OK; } @@ -1065,7 +1014,7 @@ static void compute_monitor_task(void *arg) ctx->config.server_ip, ctx->config.server_port, ctx->session_id); - ESP_LOGI(TAG, "Connecting WebSocket: %s", ws_url); + ESP_LOGI(TAG, "Connecting monitor WebSocket"); esp_websocket_client_config_t ws_cfg = { .uri = ws_url, diff --git a/components/ts_drivers/src/ts_device_ctrl.c b/components/ts_drivers/src/ts_device_ctrl.c index 78d5ee72..81fb03da 100644 --- a/components/ts_drivers/src/ts_device_ctrl.c +++ b/components/ts_drivers/src/ts_device_ctrl.c @@ -11,6 +11,7 @@ #include "ts_log.h" #include "ts_event.h" #include "esp_timer.h" +#include "esp_system.h" #include "esp_heap_caps.h" #include "driver/gpio.h" #include "freertos/FreeRTOS.h" @@ -78,6 +79,8 @@ typedef struct { /*===========================================================================*/ static agx_instance_t s_agx = {0}; +/* Serialize reset GPIO/state commits with a completed shutdown, never delays. */ +static portMUX_TYPE s_agx_power_lock = portMUX_INITIALIZER_UNLOCKED; static lpmu_instance_t s_lpmu = {0}; static bool s_initialized = false; @@ -236,10 +239,12 @@ static esp_err_t agx_power_off(void) // 设置 RESET = HIGH(断电/关机) // 注意:不要调用 gpio_reset_pin,会导致电平毛刺 + portENTER_CRITICAL(&s_agx_power_lock); gpio_set_level(pin_reset, 1); // HIGH = 断电(持续) + s_agx.state = TS_DEVICE_STATE_OFF; + portEXIT_CRITICAL(&s_agx_power_lock); TS_LOGI(TAG, "RESET set to HIGH (GPIO%d), AGX powered off", pin_reset); - s_agx.state = TS_DEVICE_STATE_OFF; TS_LOGI(TAG, "AGX powered off"); // 发送设备状态变更事件 (WebSocket) @@ -271,29 +276,48 @@ static esp_err_t agx_reset(void) return ESP_ERR_INVALID_STATE; } + if (!GPIO_IS_VALID_OUTPUT_GPIO(pin_reset)) { + return ESP_ERR_INVALID_ARG; + } + // 重启脉冲:LOW → HIGH → LOW(断电后重新通电) // 注意:不要调用 gpio_reset_pin(),避免电平毛刺(robOS 经验) TS_LOGI(TAG, "Sending RESET pulse (GPIO%d: LOW->HIGH->LOW, HIGH for %dms)...", pin_reset, TS_AGX_RESET_PULSE_MS); + portENTER_CRITICAL(&s_agx_power_lock); gpio_set_level(pin_reset, 0); // LOW = 确保通电状态 + s_agx.state = TS_DEVICE_STATE_ON; // ON means supplied, not OS-ready. + portEXIT_CRITICAL(&s_agx_power_lock); vTaskDelay(pdMS_TO_TICKS(50)); // 短暂延时 + portENTER_CRITICAL(&s_agx_power_lock); + if (s_agx.state == TS_DEVICE_STATE_OFF) { + portEXIT_CRITICAL(&s_agx_power_lock); + return ESP_ERR_INVALID_STATE; + } gpio_set_level(pin_reset, 1); // HIGH = 断电 + portEXIT_CRITICAL(&s_agx_power_lock); vTaskDelay(pdMS_TO_TICKS(TS_AGX_RESET_PULSE_MS)); + portENTER_CRITICAL(&s_agx_power_lock); + if (s_agx.state == TS_DEVICE_STATE_OFF) { + portEXIT_CRITICAL(&s_agx_power_lock); + return ESP_ERR_INVALID_STATE; + } gpio_set_level(pin_reset, 0); // LOW = 重新通电 + s_agx.power_on_time = esp_timer_get_time() / 1000; + uint32_t boot_count = ++s_agx.boot_count; + s_agx.state = TS_DEVICE_STATE_ON; + portEXIT_CRITICAL(&s_agx_power_lock); TS_LOGI(TAG, "RESET pulse complete, GPIO%d back to LOW (powered on)", pin_reset); - s_agx.boot_count++; - s_agx.state = TS_DEVICE_STATE_BOOTING; - - TS_LOGI(TAG, "AGX reset complete (boot #%lu)", s_agx.boot_count); + TS_LOGI(TAG, "AGX reset complete (boot #%lu)", boot_count); // 发送设备状态变更事件 (WebSocket) cJSON *status = cJSON_CreateObject(); if (status) { cJSON_AddStringToObject(status, "device", "agx"); cJSON_AddBoolToObject(status, "power", true); - cJSON_AddStringToObject(status, "state", "resetting"); - cJSON_AddNumberToObject(status, "boot_count", s_agx.boot_count); + cJSON_AddStringToObject(status, "state", "on"); + cJSON_AddNumberToObject(status, "boot_count", boot_count); char *json_str = cJSON_PrintUnformatted(status); if (json_str) { ts_event_post(TS_EVENT_BASE_DEVICE_MON, TS_EVENT_DEVICE_STATUS_CHANGED, @@ -896,18 +920,22 @@ static void lpmu_startup_detect_task(void *arg) s_lpmu.power_on_time = esp_timer_get_time() / 1000; } else { // LPMU 不在线,尝试开机 - TS_LOGI(TAG, "LPMU not detected, attempting power on..."); + TS_LOGI(TAG, "LPMU not detected, checking automatic power-on..."); s_lpmu.state = TS_DEVICE_STATE_BOOTING; - // 发送开机脉冲 - if (s_lpmu.gpio.power_btn) { + // Only cold controller power-on may automatically press the power button. + esp_reset_reason_t reset_reason = esp_reset_reason(); + if (s_lpmu.gpio.power_btn && reset_reason == ESP_RST_POWERON) { ts_gpio_set_level(s_lpmu.gpio.power_btn, 1); vTaskDelay(pdMS_TO_TICKS(TS_LPMU_POWER_PULSE_MS)); ts_gpio_set_level(s_lpmu.gpio.power_btn, 0); + TS_LOGI(TAG, "LPMU power pulse sent"); + } else { + TS_LOGI(TAG, "LPMU automatic power pulse skipped (reset reason %d)", reset_reason); } // 等待 LPMU 启动(最多 80 秒) - TS_LOGI(TAG, "LPMU power pulse sent, waiting for boot (max 80s)..."); + TS_LOGI(TAG, "Waiting for LPMU boot (max 80s)..."); bool booted = false; for (int i = 0; i < 16; i++) { // 16 * 5s = 80s vTaskDelay(pdMS_TO_TICKS(5000)); diff --git a/components/ts_http_fetch/CMakeLists.txt b/components/ts_http_fetch/CMakeLists.txt new file mode 100644 index 00000000..dbc74a8c --- /dev/null +++ b/components/ts_http_fetch/CMakeLists.txt @@ -0,0 +1,6 @@ +idf_component_register( + SRCS "src/ts_http_url.c" "src/ts_http_target.c" "src/ts_http_fetch.c" + INCLUDE_DIRS "include" + REQUIRES esp_common esp_http_client json http_parser + PRIV_REQUIRES ts_dns esp_timer freertos mbedtls +) diff --git a/components/ts_http_fetch/include/ts_http_fetch.h b/components/ts_http_fetch/include/ts_http_fetch.h new file mode 100644 index 00000000..cfa4017c --- /dev/null +++ b/components/ts_http_fetch/include/ts_http_fetch.h @@ -0,0 +1,42 @@ +#pragma once +#include +#include +#include "esp_err.h" +#include "esp_http_client.h" +#include "cJSON.h" + +/* One resolved hop. Address pinning does not replace Host/SNI verification. */ +typedef struct { + char *url, *hostname, *authority, *user_info; + bool secure; +} ts_http_target_t; +esp_err_t ts_http_target_resolve(const char *url, int64_t deadline_us, + bool (*current)(void *), void *context, ts_http_target_t *target); +void ts_http_target_free(ts_http_target_t *target); + +typedef struct { + const char *url, *cert_pem, *authorization, *content_type, *body; + const cJSON *headers; + esp_http_client_method_t method; + unsigned timeout_ms; + size_t maximum_body; + /* Webhooks need only a complete HTTP status/header acknowledgment. */ + bool headers_only; + bool (*current)(void *); + void *context; +} ts_http_fetch_config_t; +typedef struct { + int status; + int64_t content_length; + /* Actual connectivity phases, consumed by ota.test_connection. */ + bool dns_ok, connected; + int64_t dns_time_ms, connect_time_ms; + char resolved_ip[64]; + char *body; + size_t length; +} ts_http_fetch_result_t; +/* Worker entry; callers enforce permission/configuration authority. + * Nonblocking SDK polls; no new task or global job. + * DNS, connect, headers and body share one deadline. Redirects are never followed. + * On success the caller owns body; failure clears it. Release with free(). */ +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_result_t *result); diff --git a/components/ts_http_fetch/include/ts_http_url.h b/components/ts_http_fetch/include/ts_http_url.h new file mode 100644 index 00000000..f9215e14 --- /dev/null +++ b/components/ts_http_fetch/include/ts_http_url.h @@ -0,0 +1,10 @@ +#pragma once +#include +#include "http_parser.h" + +#define TS_HTTP_URL_LIMIT 2048U +bool ts_http_url_parse(const char *url, struct http_parser_url *parsed); +/* WS/WSS use the same bounded SDK parser; fragments are not a WS target. */ +bool ts_ws_url_parse(const char *url, struct http_parser_url *parsed); +/* parsed must be a successful parse of this same URL. */ +bool ts_http_url_is_local_api(const char *url, const struct http_parser_url *parsed); diff --git a/components/ts_http_fetch/src/ts_http_fetch.c b/components/ts_http_fetch/src/ts_http_fetch.c new file mode 100644 index 00000000..2fb80d84 --- /dev/null +++ b/components/ts_http_fetch/src/ts_http_fetch.c @@ -0,0 +1,196 @@ +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#include "esp_crt_bundle.h" +#include "esp_heap_caps.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include +#include +#include + +#define FETCH_BODY_LIMIT (64U * 1024U) +#define FETCH_HEADER_LIMIT 4096U + +typedef struct { + const ts_http_fetch_config_t *request; + ts_http_fetch_result_t *result; + int64_t deadline, started; + size_t received; + bool acknowledged; + esp_err_t error; +} fetch_t; + +static esp_err_t current(fetch_t *owner) +{ + if (owner->request->current && !owner->request->current(owner->request->context)) return ESP_ERR_INVALID_STATE; + return esp_timer_get_time() < owner->deadline ? ESP_OK : ESP_ERR_TIMEOUT; +} + +static void stop(fetch_t *owner, esp_http_client_handle_t client, esp_err_t error) +{ + if (owner->error == ESP_OK) owner->error = error; + esp_http_client_close(client); +} + +static esp_err_t receive(esp_http_client_event_t *event) +{ + fetch_t *owner = event->user_data; + if (event->event_id == HTTP_EVENT_DISCONNECTED || event->event_id == HTTP_EVENT_ERROR) return ESP_OK; + if (owner->error != ESP_OK) return owner->error; + esp_err_t allowed = current(owner); + if (allowed != ESP_OK) { stop(owner, event->client, allowed); return allowed; } + if (event->event_id == HTTP_EVENT_ON_CONNECTED) { + owner->result->connected = true; + owner->result->connect_time_ms = (esp_timer_get_time() - owner->started) / 1000 - owner->result->dns_time_ms; + } else if (event->event_id == HTTP_EVENT_HEADERS_SENT) { + /* Basic authentication may retry on this handle. Only the final body is + * returned; the cumulative wire budget and deadline never reset. */ + owner->result->length = 0; + if (owner->result->body) owner->result->body[0] = 0; + owner->acknowledged = false; + } else if (event->event_id == HTTP_EVENT_ON_DATA && event->data_len > 0) { + owner->result->status = esp_http_client_get_status_code(event->client); + if (owner->request->headers_only && owner->result->status >= 200 && owner->result->status < 300) { + owner->acknowledged = true; + esp_http_client_close(event->client); + return ESP_OK; + } + if ((size_t)event->data_len > owner->request->maximum_body - owner->received) { + stop(owner, event->client, ESP_ERR_INVALID_SIZE); + return owner->error; + } + owner->received += (size_t)event->data_len; + if (esp_http_client_get_content_length(event->client) > (int64_t)owner->request->maximum_body) { + stop(owner, event->client, ESP_ERR_INVALID_SIZE); + return owner->error; + } + if (owner->result->body) { + memcpy(owner->result->body + owner->result->length, event->data, (size_t)event->data_len); + owner->result->length += (size_t)event->data_len; + owner->result->body[owner->result->length] = 0; + } + } else if (event->event_id == HTTP_EVENT_ON_FINISH) { + owner->result->status = esp_http_client_get_status_code(event->client); + owner->acknowledged = owner->result->status >= 200 && owner->result->status < 300; + } + return ESP_OK; +} + +static bool header_text(const char *text, bool name, size_t *bytes) +{ + if (!text) return false; + size_t length = strnlen(text, FETCH_HEADER_LIMIT + 1); + if ((name && !length) || length > FETCH_HEADER_LIMIT || length > FETCH_HEADER_LIMIT - *bytes) return false; + for (size_t i = 0; i < length; ++i) { + unsigned char c = (unsigned char)text[i]; + bool token = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || strchr("!#$%&'*+-.^_`|~", c); + if (c < 0x20 || c == 0x7f || (name && !token)) return false; + } + *bytes += length; + return true; +} + +static bool headers_valid(const ts_http_fetch_config_t *request) +{ + size_t bytes = 0, count = 0; + if (request->authorization && !header_text(request->authorization, false, &bytes)) return false; + if (request->content_type && !header_text(request->content_type, false, &bytes)) return false; + if (!request->headers) return true; + if (!cJSON_IsObject(request->headers)) return false; + const cJSON *header; + cJSON_ArrayForEach(header, request->headers) { + if (++count > 16 || !cJSON_IsString(header) || !header_text(header->string, true, &bytes) || + !header_text(header->valuestring, false, &bytes) || + !strcasecmp(header->string, "Host") || !strcasecmp(header->string, "Content-Length") || + !strcasecmp(header->string, "Transfer-Encoding") || !strcasecmp(header->string, "Connection")) return false; + } + return true; +} + +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_result_t *result) +{ + if (!result) return ESP_ERR_INVALID_ARG; + memset(result, 0, sizeof(*result)); + if (!request || !request->timeout_ms || request->timeout_ms > 30000 || + !request->maximum_body || request->maximum_body > FETCH_BODY_LIMIT || + (request->method != HTTP_METHOD_GET && request->method != HTTP_METHOD_POST && + request->method != HTTP_METHOD_PUT && request->method != HTTP_METHOD_DELETE) || + (request->body && strnlen(request->body, FETCH_HEADER_LIMIT + 1) > FETCH_HEADER_LIMIT) || + !headers_valid(request)) return ESP_ERR_INVALID_ARG; + struct http_parser_url parsed; + if (!ts_http_url_parse(request->url, &parsed) || + (request->cert_pem && (parsed.field_data[UF_SCHEMA].len != 5 || + strnlen(request->cert_pem, 16385) > 16384))) return ESP_ERR_INVALID_ARG; + int64_t started = esp_timer_get_time(); + fetch_t owner = {.request = request, .result = result, .started = started, + .deadline = started + (int64_t)request->timeout_ms * 1000}; + esp_err_t error = current(&owner); + if (error != ESP_OK) return error; + if (!request->headers_only) { + result->body = heap_caps_malloc(request->maximum_body + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!result->body) result->body = malloc(request->maximum_body + 1); + if (!result->body) return ESP_ERR_NO_MEM; + result->body[0] = 0; + } + ts_http_target_t target = {0}; + error = ts_http_target_resolve(request->url, owner.deadline, request->current, request->context, &target); + esp_http_client_handle_t client = NULL; + result->dns_time_ms = (esp_timer_get_time() - started) / 1000; + if (error != ESP_OK) goto done; + result->dns_ok = true; + struct http_parser_url numeric; + if (!ts_http_url_parse(target.url, &numeric) || numeric.field_data[UF_HOST].len >= sizeof(result->resolved_ip)) { + error = ESP_ERR_INVALID_ARG; + goto done; + } + memcpy(result->resolved_ip, target.url + numeric.field_data[UF_HOST].off, numeric.field_data[UF_HOST].len); + result->resolved_ip[numeric.field_data[UF_HOST].len] = 0; + char *password = target.user_info ? strchr(target.user_info, ':') : NULL; + if (password) *password++ = 0; + esp_http_client_config_t config = {.url = target.url, .method = request->method, + .is_async = true, .timeout_ms = 1, .disable_auto_redirect = true, + .buffer_size = 2048, .buffer_size_tx = 1024, + .event_handler = receive, .user_data = &owner, + .cert_pem = request->cert_pem, .common_name = target.secure ? target.hostname : NULL, + .crt_bundle_attach = request->cert_pem ? NULL : esp_crt_bundle_attach, + .username = target.user_info, .password = password}; + client = esp_http_client_init(&config); + if (!client) { error = ESP_ERR_NO_MEM; goto done; } + error = esp_http_client_set_header(client, "Host", target.authority); + if (error == ESP_OK) error = esp_http_client_set_timeout_ms(client, 0); + if (error == ESP_OK && request->authorization) + error = esp_http_client_set_header(client, "Authorization", request->authorization); + if (error == ESP_OK && request->content_type) + error = esp_http_client_set_header(client, "Content-Type", request->content_type); + const cJSON *header; + cJSON_ArrayForEach(header, request->headers) { + if (error != ESP_OK) break; + error = esp_http_client_set_header(client, header->string, header->valuestring); + } + if (error == ESP_OK && request->body) + error = esp_http_client_set_post_field(client, request->body, (int)strlen(request->body)); + if (error == ESP_OK) { + do { + error = current(&owner); + if (error != ESP_OK) break; + error = esp_http_client_perform(client); + if (owner.error != ESP_OK) { error = owner.error; break; } + if (request->headers_only && owner.acknowledged) { error = ESP_OK; break; } + if (error == ESP_ERR_HTTP_EAGAIN) vTaskDelay(1); + } while (error == ESP_ERR_HTTP_EAGAIN); + } + if (error == ESP_OK) error = current(&owner); + result->status = esp_http_client_get_status_code(client); + result->content_length = esp_http_client_get_content_length(client); + if (error == ESP_OK && !request->headers_only && !esp_http_client_is_complete_data_received(client)) + error = ESP_ERR_INVALID_RESPONSE; +done: + if (client) esp_http_client_cleanup(client); + ts_http_target_free(&target); + if (error != ESP_OK) { + free(result->body); result->body = NULL; result->length = 0; + } + return error; +} diff --git a/components/ts_http_fetch/src/ts_http_target.c b/components/ts_http_fetch/src/ts_http_target.c new file mode 100644 index 00000000..7a4f23c7 --- /dev/null +++ b/components/ts_http_fetch/src/ts_http_target.c @@ -0,0 +1,48 @@ +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#include "ts_dns.h" +#include +#include +#include + +void ts_http_target_free(ts_http_target_t *target) +{ + if (!target) return; + free(target->url); free(target->hostname); free(target->authority); free(target->user_info); + memset(target, 0, sizeof(*target)); +} + +esp_err_t ts_http_target_resolve(const char *url, int64_t deadline, + bool (*current)(void *), void *context, ts_http_target_t *target) +{ + if (!target) return ESP_ERR_INVALID_ARG; + memset(target, 0, sizeof(*target)); + struct http_parser_url parsed; + if (!ts_http_url_parse(url, &parsed)) return ESP_ERR_INVALID_ARG; + target->secure = parsed.field_data[UF_SCHEMA].len == 5; + unsigned start = parsed.field_data[UF_HOST].off, length = parsed.field_data[UF_HOST].len; + target->hostname = strndup(url + start, length); + if (!target->hostname) return ESP_ERR_NO_MEM; + ip_addr_t address; + esp_err_t result = ts_dns_resolve(target->hostname, deadline, current, context, &address); + if (result != ESP_OK) return result; + char numeric[64]; + if (!ipaddr_ntoa_r(&address, numeric, sizeof(numeric))) return ESP_FAIL; + unsigned port = parsed.field_set & (1U << UF_PORT) ? parsed.port : target->secure ? 443 : 80; + target->authority = malloc(length + 16); + target->url = malloc(TS_HTTP_URL_LIMIT + 96); + if (!target->authority || !target->url) return ESP_ERR_NO_MEM; + bool original_ipv6 = memchr(target->hostname, ':', length) != NULL; + if (parsed.field_set & (1U << UF_PORT)) + snprintf(target->authority, length + 16, original_ipv6 ? "[%s]:%u" : "%s:%u", target->hostname, port); + else snprintf(target->authority, length + 16, original_ipv6 ? "[%s]" : "%s", target->hostname); + const char *origin = strstr(url, "://") + 3; + const char *suffix = origin + strcspn(origin, "/?#"); + snprintf(target->url, TS_HTTP_URL_LIMIT + 96, IP_IS_V6(&address) ? "%s://[%s]:%u%s%s" : "%s://%s:%u%s%s", + target->secure ? "https" : "http", numeric, port, *suffix == '/' ? "" : "/", suffix); + if (parsed.field_set & (1U << UF_USERINFO)) { + target->user_info = strndup(url + parsed.field_data[UF_USERINFO].off, parsed.field_data[UF_USERINFO].len); + if (!target->user_info) return ESP_ERR_NO_MEM; + } + return ESP_OK; +} diff --git a/components/ts_http_fetch/src/ts_http_url.c b/components/ts_http_fetch/src/ts_http_url.c new file mode 100644 index 00000000..4aa3c310 --- /dev/null +++ b/components/ts_http_fetch/src/ts_http_url.c @@ -0,0 +1,42 @@ +#include "ts_http_url.h" +#include +#include + +static bool parse_url(const char *url, struct http_parser_url *parsed, bool websocket) +{ + if (!url || !parsed) return false; + size_t length = strnlen(url, TS_HTTP_URL_LIMIT + 1); + if (!length || length > TS_HTTP_URL_LIMIT) return false; + for (size_t i = 0; i < length; ++i) + if ((unsigned char)url[i] <= 0x20 || (unsigned char)url[i] == 0x7f || url[i] == '\\') return false; + http_parser_url_init(parsed); + if (http_parser_parse_url(url, length, 0, parsed) || + !(parsed->field_set & (1U << UF_SCHEMA)) || !(parsed->field_set & (1U << UF_HOST)) || + ((parsed->field_set & (1U << UF_PORT)) && !parsed->port)) return false; + unsigned start = parsed->field_data[UF_SCHEMA].off, size = parsed->field_data[UF_SCHEMA].len; + if (websocket) return !(parsed->field_set & (1U << UF_FRAGMENT)) && + ((size == 2 && !strncasecmp(url + start, "ws", 2)) || + (size == 3 && !strncasecmp(url + start, "wss", 3))); + return (size == 4 && !strncasecmp(url + start, "http", 4)) || + (size == 5 && !strncasecmp(url + start, "https", 5)); +} + +bool ts_http_url_parse(const char *url, struct http_parser_url *parsed) +{ + return parse_url(url, parsed, false); +} + +bool ts_ws_url_parse(const char *url, struct http_parser_url *parsed) +{ + return parse_url(url, parsed, true); +} + +bool ts_http_url_is_local_api(const char *url, const struct http_parser_url *parsed) +{ + unsigned start = parsed->field_data[UF_HOST].off, length = parsed->field_data[UF_HOST].len; + bool local = (length == 9 && !strncasecmp(url + start, "localhost", 9)) || + (length == 9 && !memcmp(url + start, "127.0.0.1", 9)) || + (length == 3 && !memcmp(url + start, "::1", 3)); + unsigned path = parsed->field_data[UF_PATH].off, size = parsed->field_data[UF_PATH].len; + return local && size >= 8 && !memcmp(url + path, "/api/v1/", 8); +} diff --git a/components/ts_https/include/ts_https.h b/components/ts_https/include/ts_https.h index 9c23063c..82a346c8 100644 --- a/components/ts_https/include/ts_https.h +++ b/components/ts_https/include/ts_https.h @@ -58,7 +58,7 @@ typedef enum { TS_HTTPS_ROLE_VIEWER, /**< Read-only access (OU=viewer) */ TS_HTTPS_ROLE_OPERATOR, /**< Operation access (OU=operator) */ TS_HTTPS_ROLE_ADMIN, /**< Full access (OU=admin) */ - TS_HTTPS_ROLE_DEVICE /**< Device identity (OU=device) */ + TS_HTTPS_ROLE_DEVICE /**< Device identity and viewer reads; no management rank */ } ts_https_role_t; /** diff --git a/components/ts_https/src/ts_https.c b/components/ts_https/src/ts_https.c index 86fc1dd5..1e100eda 100644 --- a/components/ts_https/src/ts_https.c +++ b/components/ts_https/src/ts_https.c @@ -179,6 +179,7 @@ esp_err_t ts_https_start(void) // Configure HTTPS server httpd_ssl_config_t config = HTTPD_SSL_CONFIG_DEFAULT(); + config.httpd.ctrl_port = 32769; /* Independent from business and redirect listeners. */ config.httpd.server_port = 0; // HTTPS uses its own port config.port_secure = s_config.port; config.httpd.max_open_sockets = s_config.max_clients; @@ -411,65 +412,6 @@ static const mbedtls_x509_crt *get_client_cert(httpd_req_t *req) return peer_cert; } -/** - * @brief 从 X.509 证书 DN 中提取指定 OID 的值 - */ -static int extract_dn_field(const mbedtls_x509_name *dn, const char *oid, char *buf, size_t buf_len) -{ - const mbedtls_x509_name *name = dn; - while (name != NULL) { - // 检查 OID 是否匹配 - if (name->oid.len == strlen(oid) && memcmp(name->oid.p, oid, name->oid.len) == 0) { - size_t copy_len = (name->val.len < buf_len - 1) ? name->val.len : buf_len - 1; - memcpy(buf, name->val.p, copy_len); - buf[copy_len] = '\0'; - return 0; - } - name = name->next; - } - return -1; -} - -// X.509 OID 常量 -#define OID_CN "\x55\x04\x03" // 2.5.4.3 - Common Name -#define OID_O "\x55\x04\x0a" // 2.5.4.10 - Organization -#define OID_OU "\x55\x04\x0b" // 2.5.4.11 - Organizational Unit - -/** - * @brief 从证书 Subject 中提取认证信息 - */ -static void extract_auth_from_cert(const mbedtls_x509_crt *cert, ts_https_auth_t *auth) -{ - char buf[64]; - - // 提取 CN (Common Name) -> username - if (extract_dn_field(&cert->subject, OID_CN, buf, sizeof(buf)) == 0) { - strncpy(auth->username, buf, sizeof(auth->username) - 1); - auth->username[sizeof(auth->username) - 1] = '\0'; - } - - // 提取 O (Organization) -> organization - if (extract_dn_field(&cert->subject, OID_O, buf, sizeof(buf)) == 0) { - strncpy(auth->organization, buf, sizeof(auth->organization) - 1); - auth->organization[sizeof(auth->organization) - 1] = '\0'; - } - - // 提取 OU (Organizational Unit) -> role - if (extract_dn_field(&cert->subject, OID_OU, buf, sizeof(buf)) == 0) { - auth->role = ts_https_str_to_role(buf); - ESP_LOGI(TAG, "Client cert OU='%s' -> role=%s", buf, ts_https_role_to_str(auth->role)); - } - - int64_t expiry; - time_t now = time(NULL); - auth->cert_days_remaining = 0; - if (now != (time_t)-1 && ts_cert_time_utc(cert->valid_to.year, cert->valid_to.mon, - cert->valid_to.day, cert->valid_to.hour, cert->valid_to.min, cert->valid_to.sec, &expiry)) - auth->cert_days_remaining = ts_cert_time_days(expiry - (int64_t)now); - - auth->authenticated = true; -} - static esp_err_t generic_handler(httpd_req_t *req) { ts_https_endpoint_t *endpoint = (ts_https_endpoint_t *)req->user_ctx; @@ -490,23 +432,36 @@ static esp_err_t generic_handler(httpd_req_t *req) } }; - // Try to get client authentication from certificate + /* A retained TLS context authenticates against its loaded CA. Recheck the + * material lease before granting permissions, so material loss, rotation or + * an unavailable credential store cannot keep authorizing old sessions. + * Explicit public health remains anonymous until admission is restored. */ + bool client_auth_current = false; if (s_config.require_client_cert) { + ts_cert_pki_status_t current; + client_auth_current = ts_cert_get_status(¤t) == ESP_OK && + ts_cert_prerequisites(¤t, true) && current.generation == s_material.generation; + if (!client_auth_current && endpoint->min_role != TS_HTTPS_ROLE_ANONYMOUS) + return ts_https_send_error(&https_req, 503, "Client authentication materials changed or are not ready"); + } + + // Try to get client authentication from certificate + if (client_auth_current) { const mbedtls_x509_crt *client_cert = get_client_cert(req); if (client_cert) { - // 从证书中提取认证信息 - extract_auth_from_cert(client_cert, &https_req.auth); - ESP_LOGI(TAG, "mTLS auth: user='%s', org='%s', role=%s", - https_req.auth.username, - https_req.auth.organization, - ts_https_role_to_str(https_req.auth.role)); + /* Use the same complete OU policy as the SSL-context auth path. */ + esp_err_t auth_result = ts_https_auth_from_cert(client_cert, &https_req.auth); + if (auth_result != ESP_OK) { + ESP_LOGW(TAG, "Client certificate identity is invalid"); + } else { + ESP_LOGI(TAG, "mTLS auth: user='%s', org='%s', role=%s", + https_req.auth.username, + https_req.auth.organization, + ts_https_role_to_str(https_req.auth.role)); + } } else { - // 客户端证书不可用,但 TLS 握手成功,说明证书已被验证 - // 这种情况不应该发生,记录警告并使用默认值 - ESP_LOGW(TAG, "mTLS required but client cert not accessible, using fallback"); - https_req.auth.authenticated = true; - https_req.auth.role = TS_HTTPS_ROLE_VIEWER; // 降级到最低权限 - strncpy(https_req.auth.username, "unknown-mTLS-user", sizeof(https_req.auth.username) - 1); + /* Configuration is not evidence of a caller's authenticated identity. */ + ESP_LOGW(TAG, "mTLS required but client certificate is not accessible"); } } @@ -535,6 +490,8 @@ esp_err_t ts_https_send_json(ts_https_req_t *req, int status, const char *json_s return ESP_ERR_INVALID_ARG; } + esp_err_t ret = httpd_resp_set_hdr(req->req, "Cache-Control", "no-store"); + if (ret != ESP_OK) return ret; httpd_resp_set_type(req->req, "application/json"); // Set status code diff --git a/components/ts_https/src/ts_https_auth.c b/components/ts_https/src/ts_https_auth.c index 18cb0934..e448e4c9 100644 --- a/components/ts_https/src/ts_https_auth.c +++ b/components/ts_https/src/ts_https_auth.c @@ -12,6 +12,7 @@ #include "mbedtls/x509_crt.h" #include "mbedtls/ssl.h" #include +#include static const char *TAG = "ts_https_auth"; @@ -45,14 +46,24 @@ ts_https_role_t ts_https_str_to_role(const char *str) bool ts_https_role_has_permission(ts_https_role_t user_role, ts_https_role_t required_role) { - // Admin > Operator > Viewer > Anonymous - // Device is special - only equals Device - if (required_role == TS_HTTPS_ROLE_DEVICE) { - return user_role == TS_HTTPS_ROLE_DEVICE; + /* Device is an identity for device endpoints, not a management rank. */ + switch (required_role) { + case TS_HTTPS_ROLE_ANONYMOUS: + return user_role == TS_HTTPS_ROLE_ANONYMOUS || + user_role == TS_HTTPS_ROLE_VIEWER || user_role == TS_HTTPS_ROLE_OPERATOR || + user_role == TS_HTTPS_ROLE_ADMIN || user_role == TS_HTTPS_ROLE_DEVICE; + case TS_HTTPS_ROLE_VIEWER: + return user_role == TS_HTTPS_ROLE_VIEWER || user_role == TS_HTTPS_ROLE_OPERATOR || + user_role == TS_HTTPS_ROLE_ADMIN || user_role == TS_HTTPS_ROLE_DEVICE; + case TS_HTTPS_ROLE_OPERATOR: + return user_role == TS_HTTPS_ROLE_OPERATOR || user_role == TS_HTTPS_ROLE_ADMIN; + case TS_HTTPS_ROLE_ADMIN: + return user_role == TS_HTTPS_ROLE_ADMIN; + case TS_HTTPS_ROLE_DEVICE: + return user_role == TS_HTTPS_ROLE_DEVICE; + default: + return false; } - - // For other roles, higher numeric value = more permission - return (int)user_role >= (int)required_role; } /*===========================================================================*/ @@ -99,12 +110,12 @@ static esp_err_t extract_rdn(const mbedtls_x509_name *name, */ esp_err_t ts_https_auth_from_cert(const mbedtls_x509_crt *cert, ts_https_auth_t *auth) { - if (!cert || !auth) { + if (!auth) { return ESP_ERR_INVALID_ARG; } memset(auth, 0, sizeof(*auth)); - auth->authenticated = true; + if (!cert) return ESP_ERR_INVALID_ARG; // Extract Common Name (CN) → username // OID for CN: 2.5.4.3 @@ -124,16 +135,20 @@ esp_err_t ts_https_auth_from_cert(const mbedtls_x509_crt *cert, ts_https_auth_t // OID for OU: 2.5.4.11 static const char oid_ou[] = { 0x55, 0x04, 0x0B }; char ou_value[32] = {0}; - if (extract_rdn(&cert->subject, oid_ou, sizeof(oid_ou), - ou_value, sizeof(ou_value)) == ESP_OK) { - auth->role = ts_https_str_to_role(ou_value); - ESP_LOGI(TAG, "Client role from OU: %s → %s", - ou_value, ts_https_role_to_str(auth->role)); - } else { - // No OU field - default to viewer - auth->role = TS_HTTPS_ROLE_VIEWER; - ESP_LOGW(TAG, "No OU field in certificate, defaulting to viewer"); + bool found_role = false; + for (const mbedtls_x509_name *n = &cert->subject; n; n = n->next) { + if (n->oid.len != sizeof(oid_ou) || memcmp(n->oid.p, oid_ou, sizeof(oid_ou))) continue; + /* A role is exactly one complete OU value, never a truncated C string. */ + if (found_role || !n->val.len || n->val.len >= sizeof(ou_value) || + memchr(n->val.p, '\0', n->val.len)) { + memset(auth, 0, sizeof(*auth)); + return ESP_ERR_INVALID_ARG; + } + memcpy(ou_value, n->val.p, n->val.len); + found_role = true; } + auth->role = ts_https_str_to_role(ou_value); /* Missing/unknown OU stays anonymous. */ + auth->authenticated = true; int64_t expiry; time_t now = time(NULL); @@ -161,11 +176,12 @@ esp_err_t ts_https_auth_from_cert(const mbedtls_x509_crt *cert, ts_https_auth_t */ esp_err_t ts_https_get_client_auth(void *ssl_ctx, ts_https_auth_t *auth) { - if (!ssl_ctx || !auth) { + if (!auth) { return ESP_ERR_INVALID_ARG; } memset(auth, 0, sizeof(*auth)); + if (!ssl_ctx) return ESP_ERR_INVALID_ARG; mbedtls_ssl_context *ssl = (mbedtls_ssl_context *)ssl_ctx; diff --git a/components/ts_https/src/ts_https_internal.h b/components/ts_https/src/ts_https_internal.h index 530877ce..252fe702 100644 --- a/components/ts_https/src/ts_https_internal.h +++ b/components/ts_https/src/ts_https_internal.h @@ -14,7 +14,9 @@ extern "C" { #endif /** - * @brief Extract authentication info from certificate + * @brief Extract identity from a peer certificate already validated by TLS. + * Missing/unknown OU has no protected role; duplicate or malformed role OU fails. + * A failure clears the output identity. This function does not verify the chain. */ esp_err_t ts_https_auth_from_cert(const mbedtls_x509_crt *cert, ts_https_auth_t *auth); diff --git a/components/ts_net/CMakeLists.txt b/components/ts_net/CMakeLists.txt index 7c393daa..655d56f1 100644 --- a/components/ts_net/CMakeLists.txt +++ b/components/ts_net/CMakeLists.txt @@ -7,6 +7,7 @@ idf_component_register( "src/ts_dhcp_server.c" "src/ts_nat.c" "src/ts_http_server.c" + "src/ts_http_origin.c" "src/ts_https_server.c" "src/ts_time_sync.c" INCLUDE_DIRS @@ -29,5 +30,14 @@ idf_component_register( PRIV_REQUIRES driver esp_event + esp_timer nvs_flash ) + +# Exact public origins/authorities for intentionally hosted dashboards or proxies. +# Empty means same-origin device UI only; never derive this from incoming headers. +set(TS_HTTP_TRUSTED_ORIGINS "" CACHE STRING "Comma-separated trusted http(s) origins, no wildcards") +if(TS_HTTP_TRUSTED_ORIGINS MATCHES "[;\"\\\r\n]") + message(FATAL_ERROR "TS_HTTP_TRUSTED_ORIGINS contains an unsafe configuration delimiter") +endif() +target_compile_definitions(${COMPONENT_LIB} PRIVATE TS_HTTP_TRUSTED_ORIGINS="${TS_HTTP_TRUSTED_ORIGINS}") diff --git a/components/ts_net/include/ts_http_server.h b/components/ts_net/include/ts_http_server.h index 7c69797b..7b9d4f10 100644 --- a/components/ts_net/include/ts_http_server.h +++ b/components/ts_net/include/ts_http_server.h @@ -8,12 +8,13 @@ #include "esp_err.h" #include "esp_http_server.h" #include +#include #ifdef __cplusplus extern "C" { #endif -/* Seven accepted clients share the existing 16-socket system budget. Reserve +/* Seven accepted clients share the system socket budget. Reserve * two non-upgraded sessions for page/API traffic; the HTTPD build policy keeps * upgraded WebSockets out of LRU selection. */ #define TS_HTTP_MAX_CLIENTS 7 @@ -32,6 +33,8 @@ typedef enum { TS_HTTP_PATCH = HTTP_PATCH } ts_http_method_t; +#define TS_HTTP_ORIGIN_MAX_BYTES 288 + /** HTTP request context */ typedef struct { httpd_req_t *req; @@ -39,11 +42,16 @@ typedef struct { ts_http_method_t method; char *body; size_t body_len; + char cors_origin[TS_HTTP_ORIGIN_MAX_BYTES]; /**< Response header lifetime is this request. */ } ts_http_request_t; /** HTTP handler callback */ typedef esp_err_t (*ts_http_handler_t)(ts_http_request_t *req, void *user_data); +/** Admission runs before body allocation/receive. A rejection must send its + * response and return false; transport closes the unread request. */ +typedef bool (*ts_http_admission_t)(ts_http_request_t *req, void *user_data); + /** Route registration */ typedef struct { const char *uri; @@ -51,8 +59,32 @@ typedef struct { ts_http_handler_t handler; void *user_data; bool requires_auth; + uint8_t required_level; /**< Nonzero also requires auth; 0 retains legacy READ minimum. */ + ts_http_admission_t admit; /**< Optional route-owned dynamic pre-body policy. */ + size_t max_body_bytes; /**< Zero selects 1 MiB; larger streams require explicit policy. */ + uint32_t body_timeout_ms; /**< Zero selects 30 seconds; SDK maximum is 300 seconds. */ } ts_http_route_t; +/** Shared Host/Origin policy. SDK dispatch invokes the strong admission hook + * before route lookup, WS upgrade, authorization or application body allocation. + * Optional origin output belongs to the caller and must survive response send. */ +esp_err_t ts_http_validate_browser_request(httpd_req_t *req, char *origin, size_t capacity); +esp_err_t ts_httpd_admit_request(httpd_req_t *req); + +/** Live route authorization before body allocation and again before dispatch. + * Sends rejection; caller frees a received body and closes on failure. */ +bool ts_http_authorize_route(ts_http_request_t *req, const ts_http_route_t *route); + +/** Receive the complete body into an initially empty context, or send an error. + * On failure the transport must close; on success the caller owns/free()s body. + */ +esp_err_t ts_http_receive_body(ts_http_request_t *req); +/* Validate declared bytes before allocation and select this request's one-time + * body budget. SDK header/frame reads have an independent 15 second budget. + * Bounds are checked before/after each recv; one socket read timeout may overrun. */ +esp_err_t ts_http_admit_body(ts_http_request_t *req, const ts_http_route_t *route); +void ts_httpd_set_body_receive_budget(uint32_t milliseconds); + /** * @brief Initialize HTTP server */ @@ -68,6 +100,8 @@ esp_err_t ts_http_server_deinit(void); */ esp_err_t ts_http_server_start(void); + + /** * @brief Stop HTTP server */ @@ -105,6 +139,12 @@ esp_err_t ts_http_send_json(ts_http_request_t *req, int status, const char *json */ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath); +/** + * @brief Send an API file download with Cache-Control: no-store. + * File bytes, content type, gzip and streaming behavior match ts_http_send_file. + */ +esp_err_t ts_http_send_private_file(ts_http_request_t *req, const char *filepath); + /** * @brief Send error response */ diff --git a/components/ts_net/include/ts_net.h b/components/ts_net/include/ts_net.h index 61a3cbf8..5aa63bf1 100644 --- a/components/ts_net/include/ts_net.h +++ b/components/ts_net/include/ts_net.h @@ -99,6 +99,7 @@ esp_err_t ts_net_set_hostname(const char *hostname); * @brief Get hostname */ const char *ts_net_get_hostname(void); +/* Coherent bounded snapshot for request authority policy. */ /** * @brief Convert IP to string diff --git a/components/ts_net/include/ts_net_manager.h b/components/ts_net/include/ts_net_manager.h index 1f60cb28..6023e352 100644 --- a/components/ts_net/include/ts_net_manager.h +++ b/components/ts_net/include/ts_net_manager.h @@ -291,6 +291,8 @@ esp_err_t ts_net_manager_set_hostname(const char *hostname); * @return 主机名字符串 */ const char *ts_net_manager_get_hostname(void); +/* Copy the published authority (configured name before first start). Pending + * hostname edits do not invalidate the currently published management origin. */ /* ============================================================================ * 配置持久化 diff --git a/components/ts_net/include/ts_time_sync.h b/components/ts_net/include/ts_time_sync.h index 41ea04c2..585fc839 100644 --- a/components/ts_net/include/ts_time_sync.h +++ b/components/ts_net/include/ts_time_sync.h @@ -21,6 +21,8 @@ extern "C" { #endif +uint32_t ts_time_sync_security_generation(void); + /** * @brief Time sync status */ diff --git a/components/ts_net/src/ts_dhcp_server.c b/components/ts_net/src/ts_dhcp_server.c index 5e13ca17..7cdfc6a1 100644 --- a/components/ts_net/src/ts_dhcp_server.c +++ b/components/ts_net/src/ts_dhcp_server.c @@ -25,6 +25,7 @@ #include "nvs.h" #include "lwip/ip4_addr.h" #include "lwip/ip_addr.h" +#include "lwip/dns.h" #include "ts_dhcps_bindings.h" #include "dhcpserver/dhcpserver.h" /* For dhcps_lease_t */ #include "freertos/FreeRTOS.h" @@ -392,6 +393,15 @@ static esp_err_t configure_stopped_netif(ts_dhcp_if_t iface, esp_netif_t *netif, ret = esp_netif_set_dns_info(netif, i ? ESP_NETIF_DNS_BACKUP : ESP_NETIF_DNS_MAIN, &dns); if (ret != ESP_OK) return ret; } + /* Already on TCP/IP. Host DNS is independent of the DHCP pool's offers; + * changing/reloading a pool alone must leave the resolver untouched. */ + if (host_dns) { + for (unsigned i = 0; i < 2; ++i) { + ip_addr_t address; + ip_addr_set_ip4_u32_val(address, host_dns[i]); + dns_setserver(i, &address); + } + } return ESP_OK; } diff --git a/components/ts_net/src/ts_eth.c b/components/ts_net/src/ts_eth.c index 1faad0e9..e271e63f 100644 --- a/components/ts_net/src/ts_eth.c +++ b/components/ts_net/src/ts_eth.c @@ -14,6 +14,7 @@ */ #include "ts_eth.h" +#include "lwip/dns.h" #include "ts_net.h" #include "ts_dhcp_server.h" #include "ts_pin_manager.h" @@ -149,6 +150,18 @@ static void ip_event_handler(void *arg, esp_event_base_t event_base, } } +/* DHCPS netif DNS entries belong to DHCP offers, not the host resolver. */ +static esp_err_t set_eth_host_dns(void *context) +{ + const uint32_t *servers = context; + for (unsigned i = 0; i < 2; ++i) { + ip_addr_t address; + ip_addr_set_ip4_u32_val(address, servers[i]); + dns_setserver(i, &address); + } + return ESP_OK; +} + /** * @brief 创建支持 DHCP 服务器的以太网 netif * @@ -202,6 +215,12 @@ static esp_err_t create_eth_netif_with_dhcps(const ts_eth_config_t *config, esp_ } } + esp_err_t ret = esp_netif_tcpip_exec(set_eth_host_dns, (void *)config->dns); + if (ret != ESP_OK) { + esp_netif_destroy(netif); + return ret; + } + TS_LOGI(TAG, "Created Ethernet netif with DHCP server mode"); *out = netif; diff --git a/components/ts_net/src/ts_http_origin.c b/components/ts_net/src/ts_http_origin.c new file mode 100644 index 00000000..6dacb3fc --- /dev/null +++ b/components/ts_net/src/ts_http_origin.c @@ -0,0 +1,168 @@ +/* Preserve the published device/proxy authority while rejecting foreign browser origins. */ +#include "ts_http_server.h" +#include "lwip/sockets.h" +#include "lwip/inet.h" +#include +#include +#include +#include + +#ifndef TS_HTTP_TRUSTED_ORIGINS +#define TS_HTTP_TRUSTED_ORIGINS "" +#endif + +/* Implemented in this project's generated HTTPD parse object, not the shared SDK. + * Distinguishes missing/empty values and refuses duplicate security headers. */ +extern esp_err_t ts_httpd_get_single_header(httpd_req_t *req, const char *field, + char *out, size_t capacity); + +typedef struct { + uint8_t address[16]; /* Keep inet_pton output naturally aligned. */ + char host[254]; + uint16_t port; + int family; + bool explicit_port; + bool secure; +} authority_t; + +static bool authority_parse(const char *text, bool secure, authority_t *out) +{ + memset(out, 0, sizeof(*out)); + out->secure = secure; out->port = secure ? 443 : 80; + if (!text || !text[0]) return false; + const char *host = text, *end = NULL, *port = NULL; + if (*host == '[') { + host++; end = strchr(host, ']'); + if (!end || (end[1] && end[1] != ':')) return false; + if (end[1]) port = end + 2; + out->family = AF_INET6; + } else { + end = strchr(host, ':'); + if (end) port = end + 1; else end = host + strlen(host); + out->family = AF_UNSPEC; + } + size_t length = (size_t)(end - host); + if (!length || length >= sizeof(out->host)) return false; + for (size_t i = 0; i < length; ++i) { + unsigned char c = host[i]; + if (c <= ' ' || c >= 0x7f) return false; + out->host[i] = c >= 'A' && c <= 'Z' ? (char)(c + 'a' - 'A') : (char)c; + } + if (out->family == AF_INET6) { + if (inet_pton(AF_INET6, out->host, out->address) != 1) return false; + } else if (inet_pton(AF_INET, out->host, out->address) == 1) out->family = AF_INET; + else { + /* Only DNS labels; no credentials, paths, percent escapes, lists or zones. */ + size_t label = 0; + for (size_t i = 0; i < length; ++i) { + unsigned char c = out->host[i]; + if (c == '.') { if (!label) return false; label = 0; } + else { + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_')) return false; + if (++label > 63) return false; + } + } + } + if (port) { + if (!*port) return false; + unsigned value = 0; + while (*port) { + if (*port < '0' || *port > '9') return false; + unsigned digit = (unsigned)(*port++ - '0'); + if (value > (65535u - digit) / 10u) return false; + value = value * 10u + digit; + } + if (!value) return false; + out->port = value; out->explicit_port = true; + } + return true; +} + +static bool origin_parse(const char *text, authority_t *out) +{ + if (!strncasecmp(text, "http://", 7)) return authority_parse(text + 7, false, out); + if (!strncasecmp(text, "https://", 8)) return authority_parse(text + 8, true, out); + return false; /* Includes opaque/null origins. */ +} + +static bool host_equal(const authority_t *a, const authority_t *b) +{ + if (a->family != b->family) return false; + if (a->family == AF_INET) return !memcmp(a->address, b->address, 4); + if (a->family == AF_INET6) return !memcmp(a->address, b->address, 16); + return !strcmp(a->host, b->host); +} +static bool origin_equal(const authority_t *a, const authority_t *b) +{ + return a->secure == b->secure && a->port == b->port && host_equal(a, b); +} + +static bool configured_matches(const authority_t *host, const authority_t *origin, + bool *host_match, bool *origin_match) +{ + const char *at = TS_HTTP_TRUSTED_ORIGINS; + *host_match = *origin_match = false; + unsigned count = 0; + if (!*at) return true; + do { + const char *comma = strchr(at, ','); + size_t length = comma ? (size_t)(comma - at) : strlen(at); + if (!length || length >= TS_HTTP_ORIGIN_MAX_BYTES || ++count > 4) return false; + char entry[TS_HTTP_ORIGIN_MAX_BYTES]; + memcpy(entry, at, length); entry[length] = 0; + authority_t allowed; + if (!origin_parse(entry, &allowed)) return false; + /* A proxy can preserve a default-port public Host without a port even + * when its backend listener has a different scheme/port. */ + if (host_equal(host, &allowed) && + (host->explicit_port ? host->port == allowed.port : allowed.port == (allowed.secure ? 443 : 80))) *host_match = true; + if (origin && origin_equal(origin, &allowed)) *origin_match = true; + if (!comma) break; + at = comma + 1; + } while (true); + return true; +} + + + + + +esp_err_t ts_http_validate_browser_request(httpd_req_t *req, char *origin_out, size_t capacity) +{ + if (!req || (origin_out && !capacity)) return ESP_ERR_INVALID_ARG; + if (origin_out) origin_out[0] = 0; + char host_text[TS_HTTP_ORIGIN_MAX_BYTES], origin_text[TS_HTTP_ORIGIN_MAX_BYTES]; + if (ts_httpd_get_single_header(req, "Host", host_text, sizeof(host_text)) != ESP_OK) return ESP_ERR_INVALID_ARG; + esp_err_t origin_ret = ts_httpd_get_single_header(req, "Origin", origin_text, sizeof(origin_text)); + if (origin_ret != ESP_OK && origin_ret != ESP_ERR_NOT_FOUND) return ESP_ERR_INVALID_ARG; + bool secure = httpd_get_global_transport_ctx(req->handle) != NULL; + bool has_origin = origin_ret == ESP_OK; + authority_t host, origin; + if (has_origin && !origin_parse(origin_text, &origin)) return ESP_ERR_INVALID_ARG; + /* A trusted forwarding service can terminate TLS before this HTTP listener. + * Host retains its public authority; compare a browser's complete authority. */ + if (!authority_parse(host_text, has_origin ? origin.secure : secure, &host)) return ESP_ERR_INVALID_ARG; + bool configured_host, configured_origin; + if (!configured_matches(&host, has_origin ? &origin : NULL, + &configured_host, &configured_origin)) return ESP_ERR_INVALID_STATE; + if (has_origin && !configured_origin && !origin_equal(&host, &origin)) return ESP_ERR_NOT_ALLOWED; + if (origin_out && has_origin) { + size_t size = strlen(origin_text) + 1; + if (size > capacity) return ESP_ERR_INVALID_SIZE; + memcpy(origin_out, origin_text, size); + } + return ESP_OK; +} + +/* Strong symbol called from every generated HTTPD URI dispatch, including the + * mTLS service and raw WebSocket routes. Failure closes unread request bodies. */ +esp_err_t ts_httpd_admit_request(httpd_req_t *req) +{ + esp_err_t ret = ts_http_validate_browser_request(req, NULL, 0); + if (ret == ESP_OK) return ESP_OK; + httpd_err_code_t status = ret == ESP_ERR_NOT_ALLOWED ? HTTPD_403_FORBIDDEN : + ret == ESP_ERR_INVALID_STATE ? HTTPD_500_INTERNAL_SERVER_ERROR : HTTPD_400_BAD_REQUEST; + httpd_resp_send_err(req, status, status == HTTPD_403_FORBIDDEN ? "Browser origin or host is not allowed" : + status == HTTPD_500_INTERNAL_SERVER_ERROR ? "Browser policy unavailable" : "Invalid browser request headers"); + return ESP_FAIL; +} diff --git a/components/ts_net/src/ts_http_server.c b/components/ts_net/src/ts_http_server.c index 22fcac38..bf2dc63a 100644 --- a/components/ts_net/src/ts_http_server.c +++ b/components/ts_net/src/ts_http_server.c @@ -13,6 +13,7 @@ #include "esp_log.h" #include "esp_heap_caps.h" #include +#include #include #include "freertos/task.h" @@ -82,6 +83,7 @@ esp_err_t ts_http_server_start(void) config.server_port = CONFIG_TS_NET_HTTP_PORT; #endif config.open_fn = session_open; + config.ctrl_port = 32768; config.max_uri_handlers = MAX_ROUTES; config.uri_match_fn = httpd_uri_match_wildcard; config.global_user_ctx = NULL; @@ -100,13 +102,16 @@ esp_err_t ts_http_server_start(void) // 注意:任务栈必须在内部 RAM,因为 flash 操作时 PSRAM 不可用 config.task_caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT; - esp_err_t ret = httpd_start(&s_server, &config); + httpd_handle_t started = NULL; + esp_err_t ret = httpd_start(&started, &config); if (ret == ESP_OK) { - TS_LOGI(TAG, "HTTP server started on port %d", config.server_port); + s_server = started; + TS_LOGI(TAG, "HTTP server started on port %u", config.server_port); } return ret; } + esp_err_t ts_http_server_admit_ws(httpd_req_t *req, unsigned client_limit) { int fds[TS_HTTP_MAX_CLIENTS]; @@ -154,6 +159,72 @@ esp_err_t ts_http_server_stop(void) return ret; } +bool ts_http_authorize_route(ts_http_request_t *req, const ts_http_route_t *route) +{ +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (route->requires_auth || route->required_level) { + char auth[128]; + uint32_t session_id; + ts_perm_level_t level = TS_PERM_NONE; + if (ts_http_get_header(req, "Authorization", auth, sizeof(auth)) != ESP_OK || + ts_auth_validate_request(auth, &session_id, &level) != ESP_OK) { + ts_http_send_error(req, 401, "Unauthorized"); + return false; + } + ts_perm_level_t required = route->required_level ? (ts_perm_level_t)route->required_level : TS_PERM_READ; + if (level < required) { + ts_http_send_error(req, 403, required == TS_PERM_ROOT ? "Root permission required" : "Permission denied"); + return false; + } + } +#else + (void)req; (void)route; +#endif + return true; +} + +esp_err_t ts_http_admit_body(ts_http_request_t *req, const ts_http_route_t *route) +{ + const size_t limit=route->max_body_bytes?route->max_body_bytes:1024U*1024U; + size_t length=req->req->content_len; + if (length==SIZE_MAX || length>limit) { + ts_http_send_error(req,413,"Request body too large"); + return ESP_FAIL; + } + ts_httpd_set_body_receive_budget(route->body_timeout_ms); + return ESP_OK; +} + +esp_err_t ts_http_receive_body(ts_http_request_t *req) +{ + size_t length = req->req->content_len; + if (!length) return ESP_OK; + if (length == SIZE_MAX) { + ts_http_send_error(req, 413, "Request body too large"); + return ESP_FAIL; + } + char *body = TS_MALLOC_PSRAM(length + 1); + if (!body) { + ts_http_send_error(req, 500, "Memory allocation failed"); + return ESP_FAIL; + } + size_t received = 0; + while (received < length) { + int ret = httpd_req_recv(req->req, body + received, length - received); + if (ret <= 0) { + free(body); + ts_http_send_error(req, ret == HTTPD_SOCK_ERR_TIMEOUT ? 408 : 400, + ret == HTTPD_SOCK_ERR_TIMEOUT ? "Request body timed out" : "Incomplete request body"); + return ESP_FAIL; /* Caller closes the connection with unread bytes. */ + } + received += ret; + } + body[length] = '\0'; + req->body = body; + req->body_len = length; + return ESP_OK; +} + static esp_err_t http_handler_wrapper(httpd_req_t *req) { if(s_stopping && req->method!=HTTP_GET) { @@ -175,48 +246,20 @@ static esp_err_t http_handler_wrapper(httpd_req_t *req) }; #ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED - if (route->requires_auth) { - char auth[128]; - uint32_t session_id; - ts_perm_level_t level; - if (ts_http_get_header(&ts_req, "Authorization", auth, sizeof(auth)) != ESP_OK || - ts_auth_validate_request(auth, &session_id, &level) != ESP_OK || level < TS_PERM_READ) - return ts_http_send_error(&ts_req, 401, "Unauthorized"); - } + if (!ts_http_authorize_route(&ts_req, route)) return ESP_FAIL; #endif - // Read body if present - must loop to receive all data - if (req->content_len > 0) { - ts_req.body = TS_MALLOC_PSRAM(req->content_len + 1); - if (ts_req.body) { - size_t total_received = 0; - while (total_received < req->content_len) { - int ret = httpd_req_recv(req, ts_req.body + total_received, - req->content_len - total_received); - if (ret <= 0) { - if (ret == HTTPD_SOCK_ERR_TIMEOUT) { - // Timeout, continue trying - continue; - } - // Error or connection closed - TS_LOGW(TAG, "Body recv error at %zu/%zu bytes: %d", - total_received, (size_t)req->content_len, ret); - break; - } - total_received += ret; - } - ts_req.body[total_received] = '\0'; - ts_req.body_len = total_received; - - if (total_received != req->content_len) { - TS_LOGW(TAG, "Incomplete body: got %zu of %zu bytes", - total_received, (size_t)req->content_len); - } - } else { - TS_LOGE(TAG, "Failed to allocate %zu bytes for body", (size_t)req->content_len); - } + if (route->admit && !route->admit(&ts_req, route->user_data)) return ESP_FAIL; + + if (ts_http_admit_body(&ts_req, route) != ESP_OK) return ESP_FAIL; + if (ts_http_receive_body(&ts_req) != ESP_OK) return ESP_FAIL; + + /* A large body may outlive the session or a role change. Route-owned + * authorization is live again at execution, before any business effect. */ + if (!ts_http_authorize_route(&ts_req, route)) { + free(ts_req.body); + return ESP_FAIL; } - esp_err_t result = route->handler(&ts_req, route->user_data); free(ts_req.body); @@ -280,14 +323,18 @@ esp_err_t ts_http_send_response(ts_http_request_t *req, int status, { if (!req || !req->req) return ESP_ERR_INVALID_ARG; - httpd_resp_set_status(req->req, status == 200 ? "200 OK" : - status == 201 ? "201 Created" : - status == 400 ? "400 Bad Request" : - status == 401 ? "401 Unauthorized" : - status == 403 ? "403 Forbidden" : - status == 404 ? "404 Not Found" : - status == 500 ? "500 Internal Server Error" : "200 OK"); - + if (status < 100 || status > 599) status = 500; + const char *reason = status == 200 ? "OK" : status == 201 ? "Created" : + status == 400 ? "Bad Request" : status == 401 ? "Unauthorized" : + status == 403 ? "Forbidden" : status == 404 ? "Not Found" : + status == 405 ? "Method Not Allowed" : status == 408 ? "Request Timeout" : + status == 409 ? "Conflict" : status == 413 ? "Content Too Large" : + status == 429 ? "Too Many Requests" : status == 500 ? "Internal Server Error" : + status == 503 ? "Service Unavailable" : "Response"; + char status_line[48]; + snprintf(status_line, sizeof(status_line), "%d %s", status, reason); + httpd_resp_set_status(req->req, status_line); + if (content_type) { httpd_resp_set_type(req->req, content_type); } @@ -297,6 +344,9 @@ esp_err_t ts_http_send_response(ts_http_request_t *req, int status, esp_err_t ts_http_send_json(ts_http_request_t *req, int status, const char *json) { + if (!req || !req->req) return ESP_ERR_INVALID_ARG; + esp_err_t ret = httpd_resp_set_hdr(req->req, "Cache-Control", "no-store"); + if (ret != ESP_OK) return ret; return ts_http_send_response(req, status, "application/json", json); } @@ -322,9 +372,34 @@ static bool is_compressible(const char *ext) strcmp(ext, ".html") == 0 || strcmp(ext, ".json") == 0); } -esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) +static esp_err_t send_file(ts_http_request_t *req, const char *filepath, bool private_response) { if (!req || !filepath) return ESP_ERR_INVALID_ARG; + /* SDK keeps header value pointers until the response is sent. */ + char disposition[3 * 256 + 80] = "attachment; filename=\"download\"; filename*=UTF-8''"; + /* API downloads must not inherit the public asset cache policy, including + * errors before the file is opened or its content type is known. */ + if (private_response) { + const char *filename = strrchr(filepath, '/'); + filename = filename ? filename + 1 : filepath; + size_t length = strnlen(filename, 256); + if (length == 256) return ESP_ERR_INVALID_SIZE; + /* Encode bytes, not a quoted user-controlled header value. UTF-8 names + * round-trip without allowing quotes, CR/LF or path delimiters. */ + size_t used = strlen(disposition); + static const char hex[] = "0123456789ABCDEF"; + for (size_t i = 0; i < length; ++i) { + unsigned char c = (unsigned char)filename[i]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_') disposition[used++] = c; + else { disposition[used++] = '%'; disposition[used++] = hex[c >> 4]; disposition[used++] = hex[c & 15]; } + } + disposition[used] = 0; + if (httpd_resp_set_hdr(req->req, "Cache-Control", "no-store") != ESP_OK || + httpd_resp_set_hdr(req->req, "Content-Disposition", disposition) != ESP_OK || + httpd_resp_set_hdr(req->req, "Content-Security-Policy", "sandbox; default-src 'none'; frame-ancestors 'none'") != ESP_OK || + httpd_resp_set_hdr(req->req, "X-Content-Type-Options", "nosniff") != ESP_OK) return ESP_FAIL; + } /* ===== Content-Type 检测 ===== */ const char *ext = strrchr(filepath, '.'); @@ -347,7 +422,7 @@ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) char gz_path[140]; bool use_gzip = false; - if (is_compressible(ext) && client_accepts_gzip(req->req)) { + if (!private_response && is_compressible(ext) && client_accepts_gzip(req->req)) { snprintf(gz_path, sizeof(gz_path), "%s.gz", filepath); if (ts_storage_exists(gz_path)) { actual_filepath = gz_path; @@ -367,7 +442,8 @@ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) } /* ===== 设置响应头 ===== */ - httpd_resp_set_type(req->req, content_type); + esp_err_t type_result = httpd_resp_set_type(req->req, content_type); + if (private_response && type_result != ESP_OK) return type_result; if (use_gzip) { httpd_resp_set_hdr(req->req, "Content-Encoding", "gzip"); @@ -378,15 +454,16 @@ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) * JS/CSS/字体等通过 index.html 中的 ?v= 版本参数实现缓存失效。 */ const char *basename = strrchr(filepath, '/'); - if (basename && strcmp(basename, "/index.html") == 0) { + if (!private_response && basename && strcmp(basename, "/index.html") == 0) { httpd_resp_set_hdr(req->req, "Cache-Control", "no-cache, no-store, must-revalidate"); - } else if (ext) { + } else if (!private_response && ext) { httpd_resp_set_hdr(req->req, "Cache-Control", "public, max-age=604800, immutable"); } /* ===== 发送文件内容 ===== */ /* 对于小文件(<32KB),直接发送 */ + if (!size) return httpd_resp_send(req->req, NULL, 0); if (size < 32 * 1024) { char *buf = TS_MALLOC_PSRAM(size); if (!buf) { @@ -406,6 +483,7 @@ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) /* 对于大文件,使用分块传输(chunked transfer) */ FILE *f = fopen(actual_filepath, "r"); if (!f) { + if (errno == EBUSY) return ts_http_send_error(req, 503, "WebUI update in progress"); return ts_http_send_error(req, 500, "Failed to open file"); } @@ -441,6 +519,16 @@ esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) return ret; } +esp_err_t ts_http_send_file(ts_http_request_t *req, const char *filepath) +{ + return send_file(req, filepath, false); +} + +esp_err_t ts_http_send_private_file(ts_http_request_t *req, const char *filepath) +{ + return send_file(req, filepath, true); +} + esp_err_t ts_http_send_error(ts_http_request_t *req, int status, const char *message) { char json[128]; @@ -525,7 +613,12 @@ esp_err_t ts_http_set_cors(ts_http_request_t *req, const char *origin) { if (!req || !req->req) return ESP_ERR_INVALID_ARG; - httpd_resp_set_hdr(req->req, "Access-Control-Allow-Origin", origin ? origin : "*"); + (void)origin; /* Legacy callers cannot select or widen the browser policy. */ + esp_err_t ret = ts_http_validate_browser_request(req->req, req->cors_origin, sizeof(req->cors_origin)); + if (ret != ESP_OK) return ret; + if (!req->cors_origin[0]) return ESP_OK; /* Non-browser clients need no ACAO. */ + httpd_resp_set_hdr(req->req, "Access-Control-Allow-Origin", req->cors_origin); + httpd_resp_set_hdr(req->req, "Vary", "Origin"); httpd_resp_set_hdr(req->req, "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); httpd_resp_set_hdr(req->req, "Access-Control-Allow-Headers", "Content-Type, Authorization"); diff --git a/components/ts_net/src/ts_https_server.c b/components/ts_net/src/ts_https_server.c index 2b934393..53483acf 100644 --- a/components/ts_net/src/ts_https_server.c +++ b/components/ts_net/src/ts_https_server.c @@ -143,29 +143,19 @@ static esp_err_t https_handler_wrapper(httpd_req_t *req) .body_len = 0 }; - // Read body if present - must loop to receive all data - if (req->content_len > 0) { - ts_req.body = TS_MALLOC_PSRAM(req->content_len + 1); - if (ts_req.body) { - size_t total_received = 0; - while (total_received < req->content_len) { - int ret = httpd_req_recv(req, ts_req.body + total_received, - req->content_len - total_received); - if (ret <= 0) { - if (ret == HTTPD_SOCK_ERR_TIMEOUT) { - // Timeout, continue trying - continue; - } - // Error or connection closed - break; - } - total_received += ret; - } - ts_req.body[total_received] = '\0'; - ts_req.body_len = total_received; - } + if (!ts_http_authorize_route(&ts_req, route)) return ESP_FAIL; + + if (route->admit && !route->admit(&ts_req, route->user_data)) return ESP_FAIL; + + if (ts_http_admit_body(&ts_req, route) != ESP_OK) return ESP_FAIL; + if (ts_http_receive_body(&ts_req) != ESP_OK) return ESP_FAIL; + + /* A large body may outlive the session or a role change. Route-owned + * authorization is live again at execution, before any business effect. */ + if (!ts_http_authorize_route(&ts_req, route)) { + free(ts_req.body); + return ESP_FAIL; } - esp_err_t result = route->handler(&ts_req, route->user_data); free(ts_req.body); diff --git a/components/ts_net/src/ts_net.c b/components/ts_net/src/ts_net.c index 77864d65..bea0a620 100644 --- a/components/ts_net/src/ts_net.c +++ b/components/ts_net/src/ts_net.c @@ -14,7 +14,9 @@ #include "mdns.h" #endif #include +#include "freertos/FreeRTOS.h" #include +#include "lwip/dns.h" #define TAG "ts_net" @@ -160,6 +162,15 @@ static esp_netif_t *get_netif(ts_net_if_t iface) } } +static esp_err_t read_eth_host_dns(void *context) +{ + ts_net_ip_info_t *info = context; + const ip_addr_t *main = dns_getserver(0), *backup = dns_getserver(1); + info->dns1 = IP_IS_V4(main) ? ip4_addr_get_u32(ip_2_ip4(main)) : 0; + info->dns2 = IP_IS_V4(backup) ? ip4_addr_get_u32(ip_2_ip4(backup)) : 0; + return ESP_OK; +} + esp_err_t ts_net_get_ip_info(ts_net_if_t iface, ts_net_ip_info_t *info) { if (!info) return ESP_ERR_INVALID_ARG; @@ -175,6 +186,9 @@ esp_err_t ts_net_get_ip_info(ts_net_if_t iface, ts_net_ip_info_t *info) info->netmask = ip_info.netmask.addr; info->gateway = ip_info.gw.addr; + /* esp-netif reads offered DNS for a DHCP server interface. Report the + * resolver actually used by this host instead of its clients' options. */ + if (iface == TS_NET_IF_ETH) return esp_netif_tcpip_exec(read_eth_host_dns, info); esp_netif_dns_info_t dns; if (esp_netif_get_dns_info(netif, ESP_NETIF_DNS_MAIN, &dns) == ESP_OK) { info->dns1 = dns.ip.u_addr.ip4.addr; @@ -292,6 +306,8 @@ esp_err_t ts_net_set_hostname(const char *hostname) return ESP_OK; } + + const char *ts_net_get_hostname(void) { return s_hostname; diff --git a/components/ts_net/src/ts_net_manager.c b/components/ts_net/src/ts_net_manager.c index cd452e32..044a19d3 100644 --- a/components/ts_net/src/ts_net_manager.c +++ b/components/ts_net/src/ts_net_manager.c @@ -109,6 +109,7 @@ typedef enum { ETH_OP_START, ETH_OP_STOP, ETH_OP_RESTART } eth_operation_t; static ts_net_manager_state_t s_state = {0}; + /* ============================================================================ * 前向声明 * ========================================================================== */ @@ -275,9 +276,9 @@ static void update_eth_ip_from_netif(void) TS_NET_IP_STR_MAX_LEN); /* 获取 DNS */ - esp_netif_dns_info_t dns; - if (esp_netif_get_dns_info(netif, ESP_NETIF_DNS_MAIN, &dns) == ESP_OK) { - ts_net_ip_u32_to_str(dns.ip.u_addr.ip4.addr, + ts_net_ip_info_t host; + if (ts_net_get_ip_info(TS_NET_IF_ETH, &host) == ESP_OK) { + ts_net_ip_u32_to_str(host.dns1, s_state.eth_status.ip_info.dns1, TS_NET_IP_STR_MAX_LEN); } @@ -428,7 +429,7 @@ esp_err_t ts_net_manager_init(void) } /* 初始化默认配置 */ - strncpy(s_state.hostname, TS_NET_DEFAULT_HOSTNAME, sizeof(s_state.hostname) - 1); + strlcpy(s_state.hostname, TS_NET_DEFAULT_HOSTNAME, sizeof(s_state.hostname)); /* 以太网默认配置 - 作为网关/DHCP服务器,默认使用静态IP */ s_state.eth_config.enabled = true; @@ -1132,8 +1133,7 @@ esp_err_t ts_net_manager_set_hostname(const char *hostname) if (!hostname) return ESP_ERR_INVALID_ARG; xSemaphoreTake(s_state.mutex, portMAX_DELAY); - strncpy(s_state.hostname, hostname, TS_NET_HOSTNAME_MAX_LEN - 1); - s_state.hostname[TS_NET_HOSTNAME_MAX_LEN - 1] = '\0'; + strlcpy(s_state.hostname, hostname, sizeof(s_state.hostname)); xSemaphoreGive(s_state.mutex); TS_LOGI(TAG, "Hostname set to %s", hostname); @@ -1263,8 +1263,9 @@ esp_err_t ts_net_manager_load_config(void) } s_state.eth_status.config_error = eth_result; - str_len = TS_NET_HOSTNAME_MAX_LEN; - nvs_get_str(handle, NVS_KEY_HOSTNAME, s_state.hostname, &str_len); + char hostname[TS_NET_HOSTNAME_MAX_LEN] = {0}; + str_len = sizeof(hostname); + if (nvs_get_str(handle, NVS_KEY_HOSTNAME, hostname, &str_len) == ESP_OK) strlcpy(s_state.hostname, hostname, sizeof(s_state.hostname)); /* 加载 WiFi AP 配置 */ #ifdef CONFIG_TS_NET_WIFI_ENABLE @@ -1321,7 +1322,7 @@ esp_err_t ts_net_manager_reset_config(void) s_state.eth_config.static_ip.dns2[0] = '\0'; s_state.eth_status.config_error = ESP_OK; - strncpy(s_state.hostname, TS_NET_DEFAULT_HOSTNAME, TS_NET_HOSTNAME_MAX_LEN); + strlcpy(s_state.hostname, TS_NET_DEFAULT_HOSTNAME, sizeof(s_state.hostname)); xSemaphoreGive(s_state.mutex); diff --git a/components/ts_net/src/ts_time_sync.c b/components/ts_net/src/ts_time_sync.c index df65c9bd..ab8837bc 100644 --- a/components/ts_net/src/ts_time_sync.c +++ b/components/ts_net/src/ts_time_sync.c @@ -318,3 +318,9 @@ bool ts_time_sync_needs_sync(void) /* 如果年份 < 2025,说明系统时间无效(ESP32 默认 1970) */ return (timeinfo.tm_year + 1900) < TS_TIME_MIN_VALID_YEAR; } + +/* Existing time owner revision used by in-flight certificate/config checks. */ +uint32_t ts_time_sync_security_generation(void) +{ + return s_time_sync.info.sync_count; +} diff --git a/components/ts_ota/include/ts_ota.h b/components/ts_ota/include/ts_ota.h index 30f142c6..a1d1d85b 100644 --- a/components/ts_ota/include/ts_ota.h +++ b/components/ts_ota/include/ts_ota.h @@ -24,7 +24,6 @@ #include #include #include "esp_err.h" -#include "esp_partition.h" #ifdef __cplusplus extern "C" { @@ -83,7 +82,7 @@ typedef struct { size_t total_size; ///< Total firmware size (0 if unknown) size_t received_size; ///< Bytes received so far uint8_t progress_percent; ///< Progress percentage (0-100) - const char *status_msg; ///< Human-readable status message + char status_msg[64]; ///< Human-readable status message } ts_ota_progress_t; /** @@ -641,17 +640,7 @@ bool ts_ota_download_is_running(void); /** * @brief OTA event IDs */ -typedef enum { - TS_EVENT_OTA_STARTED, ///< OTA update started - TS_EVENT_OTA_PROGRESS, ///< Progress update - TS_EVENT_OTA_COMPLETED, ///< Update completed successfully - TS_EVENT_OTA_FAILED, ///< Update failed - TS_EVENT_OTA_ABORTED, ///< Update aborted by user - TS_EVENT_OTA_PENDING_REBOOT, ///< Waiting for reboot - TS_EVENT_OTA_ROLLBACK_PENDING, ///< Rollback is pending - TS_EVENT_OTA_ROLLBACK_EXECUTED, ///< Rollback was executed - TS_EVENT_OTA_VALIDATED, ///< Firmware validated -} ts_event_ota_id_t; +#include "ts_ota_events.h" #ifdef __cplusplus } diff --git a/components/ts_ota/src/ts_ota.c b/components/ts_ota/src/ts_ota.c index 19bbb040..324c2089 100644 --- a/components/ts_ota/src/ts_ota.c +++ b/components/ts_ota/src/ts_ota.c @@ -189,7 +189,7 @@ esp_err_t ts_ota_get_progress(ts_ota_progress_t *progress) progress->progress_percent = 0; } - progress->status_msg = s_status_msg; + memcpy(progress->status_msg, s_status_msg, sizeof(progress->status_msg)); xSemaphoreGive(s_ota_mutex); @@ -379,6 +379,11 @@ esp_err_t ts_ota_upload_begin(size_t total_size) ESP_LOGI(TAG, "OTA upload starting, target partition: %s (size: %lu KB)", s_upload_partition->label, s_upload_partition->size / 1024); + if (!total_size || total_size > s_upload_partition->size) { + xSemaphoreGive(s_ota_mutex); + return ESP_ERR_INVALID_SIZE; + } + // Begin OTA ret = esp_ota_begin(s_upload_partition, OTA_WITH_SEQUENTIAL_WRITES, &s_upload_handle); if (ret != ESP_OK) { @@ -417,6 +422,11 @@ esp_err_t ts_ota_upload_write(const void *data, size_t len) return ESP_ERR_INVALID_STATE; } + if (len > s_total_size - s_received_size) { + xSemaphoreGive(s_ota_mutex); + return ESP_ERR_INVALID_SIZE; + } + ret = esp_ota_write(s_upload_handle, data, len); if (ret != ESP_OK) { xSemaphoreGive(s_ota_mutex); @@ -455,6 +465,11 @@ esp_err_t ts_ota_upload_end(bool auto_reboot) return ESP_ERR_INVALID_STATE; } + if (s_received_size != s_total_size) { + xSemaphoreGive(s_ota_mutex); + return ESP_ERR_INVALID_SIZE; + } + // End OTA ret = esp_ota_end(s_upload_handle); if (ret != ESP_OK) { diff --git a/components/ts_ota/src/ts_ota_www.c b/components/ts_ota/src/ts_ota_www.c index 8c86b6e1..3cde8b8b 100644 --- a/components/ts_ota/src/ts_ota_www.c +++ b/components/ts_ota/src/ts_ota_www.c @@ -80,7 +80,7 @@ static void www_ota_update_progress(ts_ota_state_t state, size_t received, size_ } else { s_www_progress.progress_percent = 0; } - s_www_progress.status_msg = msg; + snprintf(s_www_progress.status_msg, sizeof(s_www_progress.status_msg), "%s", msg ? msg : ""); xSemaphoreGive(s_www_progress_mutex); } @@ -91,8 +91,8 @@ static void www_ota_update_progress(ts_ota_state_t state, size_t received, size_ .received_size = received, .total_size = total, .progress_percent = (total > 0) ? (received * 100 / total) : 0, - .status_msg = msg }; + snprintf(progress.status_msg, sizeof(progress.status_msg), "%s", msg ? msg : ""); s_www_config.progress_cb(&progress, s_www_config.user_data); } } diff --git a/components/ts_pki_client/CMakeLists.txt b/components/ts_pki_client/CMakeLists.txt index 3cde49c7..5f88c1bb 100644 --- a/components/ts_pki_client/CMakeLists.txt +++ b/components/ts_pki_client/CMakeLists.txt @@ -4,7 +4,7 @@ idf_component_register( INCLUDE_DIRS "include" REQUIRES - esp_http_client + ts_http_fetch json ts_cert PRIV_REQUIRES diff --git a/components/ts_pki_client/include/ts_pki_client.h b/components/ts_pki_client/include/ts_pki_client.h index a9ed5343..b4550cde 100644 --- a/components/ts_pki_client/include/ts_pki_client.h +++ b/components/ts_pki_client/include/ts_pki_client.h @@ -104,7 +104,8 @@ esp_err_t ts_pki_client_init_with_config(const ts_pki_client_config_t *config); /** * @brief Deinitialize PKI client */ -void ts_pki_client_deinit(void); +/* Busy retains all resources; retry before deinitializing certificate services. */ +esp_err_t ts_pki_client_deinit(void); /** * @brief Get default configuration diff --git a/components/ts_pki_client/src/ts_pki_client.c b/components/ts_pki_client/src/ts_pki_client.c index 38583d57..afd68a53 100644 --- a/components/ts_pki_client/src/ts_pki_client.c +++ b/components/ts_pki_client/src/ts_pki_client.c @@ -12,6 +12,10 @@ */ #include +#include +#include +#include "ts_http_url.h" +#include "esp_timer.h" #include #include #include "freertos/FreeRTOS.h" @@ -19,8 +23,7 @@ #include "freertos/semphr.h" #include "esp_log.h" #include "esp_mac.h" -#include "esp_http_client.h" -#include "esp_crt_bundle.h" +#include "ts_http_fetch.h" #include "esp_heap_caps.h" #include "cJSON.h" @@ -39,27 +42,76 @@ static struct { ts_pki_client_config_t config; char device_id[TS_CERT_DEVICE_ID_MAX_LEN]; int request_id; // CSR 提交后返回的请求 ID - TaskHandle_t enroll_task; + _Atomic(TaskHandle_t) enroll_task; _Atomic bool enroll_running; - SemaphoreHandle_t mutex; _Atomic bool stop_requested; ts_pki_enroll_callback_t callback; void *callback_data; } s_client = {0}; +/* One operation owner, retained across deinit so late callers cannot take a + * freed mutex. Recursive only for the existing blocking enrollment composition. + * Contending control/HTTP requests return busy rather than waiting behind I/O. */ +static StaticSemaphore_t s_operation_storage; +static SemaphoreHandle_t s_operation; +static portMUX_TYPE s_operation_init_lock = portMUX_INITIALIZER_UNLOCKED; +static atomic_bool s_deinitializing; +static int64_t s_request_deadline; /* Held by the operation owner; zero for individual requests. */ +static bool operation_take(void) +{ + portENTER_CRITICAL(&s_operation_init_lock); + if (!s_operation) s_operation = xSemaphoreCreateRecursiveMutexStatic(&s_operation_storage); + portEXIT_CRITICAL(&s_operation_init_lock); + return xSemaphoreTakeRecursive(s_operation, 0) == pdTRUE; +} +static bool operation_enter(void) +{ + if (!operation_take()) return false; + if (s_deinitializing) { xSemaphoreGiveRecursive(s_operation); return false; } + return true; +} +static bool enrollment_owner(void) +{ + return !s_client.enroll_running || xTaskGetCurrentTaskHandle() == s_client.enroll_task; +} +static bool request_current(void *task) +{ + return !s_deinitializing && (!s_request_deadline || esp_timer_get_time() < s_request_deadline) && !(s_client.enroll_running && + task == s_client.enroll_task && s_client.stop_requested); +} + +/* Only a host, never a URL/path/header; accept DNS and IPv4/IPv6 without + * inventing a separate authority parser or changing the configured target. */ +static bool valid_server(const char *host, uint16_t port) +{ + if (!host || !port || !host[0] || strnlen(host, sizeof(s_client.config.server_host)) >= sizeof(s_client.config.server_host)) return false; + char url[96]; + bool brackets = strchr(host, ':') && host[0] != '['; + int n = snprintf(url, sizeof(url), brackets ? "http://[%s]:%u/" : "http://%s:%u/", host, (unsigned)port); + struct http_parser_url parsed; + return n > 0 && (size_t)n < sizeof(url) && ts_http_url_parse(url, &parsed) && + !(parsed.field_set & ((1U << UF_USERINFO) | (1U << UF_QUERY) | (1U << UF_FRAGMENT))) && + parsed.field_data[UF_PATH].len == 1; +} +static void server_url(char *out, size_t size, const char *path) +{ + const char *host = s_client.config.server_host; + bool brackets = strchr(host, ':') && host[0] != '['; + snprintf(out, size, brackets ? "http%s://[%s]:%u%s" : "http%s://%s:%u%s", + s_client.config.use_https ? "s" : "", host, (unsigned)s_client.config.server_port, path); +} + /** HTTP response buffer */ #define HTTP_RESP_BUF_SIZE 8192 -static char *s_http_resp_buf = NULL; -static size_t s_http_resp_len = 0; /*===========================================================================*/ /* Forward Declarations */ /*===========================================================================*/ -static esp_err_t http_event_handler(esp_http_client_event_t *evt); static esp_err_t do_http_request(const char *url, esp_http_client_method_t method, - const char *post_data, int *http_code); + const char *post_data, int *http_code, cJSON **response); static void auto_enroll_task(void *arg); +static void enroll_wait(uint32_t ms); static esp_err_t get_device_id(void); /*===========================================================================*/ @@ -87,35 +139,15 @@ esp_err_t ts_pki_client_init(void) return ts_pki_client_init_with_config(&config); } -esp_err_t ts_pki_client_init_with_config(const ts_pki_client_config_t *config) +static esp_err_t ts_pki_client_init_with_config_locked(const ts_pki_client_config_t *config) { if (s_client.initialized) { ESP_LOGW(TAG, "Already initialized"); return ESP_OK; } - if (!config) { - return ESP_ERR_INVALID_ARG; - } - - // 分配 HTTP 响应缓冲区 - s_http_resp_buf = heap_caps_malloc(HTTP_RESP_BUF_SIZE, MALLOC_CAP_SPIRAM); - if (!s_http_resp_buf) { - s_http_resp_buf = malloc(HTTP_RESP_BUF_SIZE); - if (!s_http_resp_buf) { - ESP_LOGE(TAG, "Failed to allocate HTTP buffer"); - return ESP_ERR_NO_MEM; - } - } - - // 创建互斥锁 - s_client.mutex = xSemaphoreCreateMutex(); - if (!s_client.mutex) { - free(s_http_resp_buf); - s_http_resp_buf = NULL; - return ESP_ERR_NO_MEM; - } - + if (!config || !valid_server(config->server_host, config->server_port) || !config->poll_interval_sec) return ESP_ERR_INVALID_ARG; + // 复制配置 memcpy(&s_client.config, config, sizeof(ts_pki_client_config_t)); s_client.initialized = true; @@ -139,59 +171,59 @@ esp_err_t ts_pki_client_init_with_config(const ts_pki_client_config_t *config) return ESP_OK; } -void ts_pki_client_deinit(void) +esp_err_t ts_pki_client_deinit(void) { - if (!s_client.initialized) return; - - // 停止后台任务 + s_deinitializing = true; ts_pki_client_stop_auto_enroll(); - - if (s_client.enroll_running) { ESP_LOGW(TAG, "Enrollment still exiting; retaining resources"); return; } - - // 释放资源 - if (s_client.mutex) { - vSemaphoreDelete(s_client.mutex); - s_client.mutex = NULL; - } - - if (s_http_resp_buf) { - free(s_http_resp_buf); - s_http_resp_buf = NULL; + if (!operation_take()) return ESP_ERR_INVALID_STATE; + if (s_client.enroll_running) { + xSemaphoreGiveRecursive(s_operation); + return ESP_ERR_INVALID_STATE; } - - memset(&s_client, 0, sizeof(s_client)); + s_client.initialized = false; + memset(&s_client.config, 0, sizeof(s_client.config)); + memset(s_client.device_id, 0, sizeof(s_client.device_id)); + s_client.request_id = 0; + s_client.enroll_task = NULL; + s_client.callback = NULL; + s_client.callback_data = NULL; + s_client.stop_requested = false; + s_deinitializing = false; + xSemaphoreGiveRecursive(s_operation); ESP_LOGI(TAG, "PKI client deinitialized"); + return ESP_OK; } /*===========================================================================*/ /* Server Configuration */ /*===========================================================================*/ -esp_err_t ts_pki_client_set_server(const char *host, uint16_t port) +static esp_err_t ts_pki_client_set_server_locked(const char *host, uint16_t port) { if (!s_client.initialized || !host) { return ESP_ERR_INVALID_STATE; } - xSemaphoreTake(s_client.mutex, portMAX_DELAY); - strncpy(s_client.config.server_host, host, sizeof(s_client.config.server_host) - 1); - s_client.config.server_port = port; - xSemaphoreGive(s_client.mutex); - + if (!valid_server(host, port)) return ESP_ERR_INVALID_ARG; + if (s_client.enroll_running) return ESP_ERR_INVALID_STATE; + if (strcmp(s_client.config.server_host, host) || s_client.config.server_port != port) { + snprintf(s_client.config.server_host, sizeof(s_client.config.server_host), "%s", host); + s_client.config.server_port = port; + s_client.request_id = 0; /* Request IDs are scoped to their issuing server. */ + } + ESP_LOGI(TAG, "PKI server set to %s:%d", host, port); return ESP_OK; } -esp_err_t ts_pki_client_get_server(char *host, uint16_t *port) +static esp_err_t ts_pki_client_get_server_locked(char *host, uint16_t *port) { if (!s_client.initialized || !host || !port) { return ESP_ERR_INVALID_STATE; } - xSemaphoreTake(s_client.mutex, portMAX_DELAY); strcpy(host, s_client.config.server_host); *port = s_client.config.server_port; - xSemaphoreGive(s_client.mutex); return ESP_OK; } @@ -200,7 +232,7 @@ esp_err_t ts_pki_client_get_server(char *host, uint16_t *port) /* Manual Enrollment Operations */ /*===========================================================================*/ -esp_err_t ts_pki_client_submit_csr(void) +static esp_err_t ts_pki_client_submit_csr_locked(void) { if (!s_client.initialized) { return ESP_ERR_INVALID_STATE; @@ -248,16 +280,20 @@ esp_err_t ts_pki_client_submit_csr(void) // 构建 JSON 请求体 cJSON *root = cJSON_CreateObject(); - cJSON_AddStringToObject(root, "device_id", s_client.device_id); - cJSON_AddStringToObject(root, "csr_pem", csr_pem); - cJSON_AddStringToObject(root, "device_type", "ESP32-S3"); - cJSON_AddStringToObject(root, "device_ip", "10.10.99.97"); // 设备静态 IP - cJSON_AddStringToObject(root, "description", "TianShanOS Rack Manager"); - // 建议的 SAN IP,管理员可在审批时修改 - cJSON *san_ips = cJSON_CreateArray(); - cJSON_AddItemToArray(san_ips, cJSON_CreateString("10.10.99.97")); - cJSON_AddItemToObject(root, "suggested_san_ips", san_ips); - + bool complete = root && cJSON_AddStringToObject(root, "device_id", s_client.device_id) && + cJSON_AddStringToObject(root, "csr_pem", csr_pem) && + cJSON_AddStringToObject(root, "device_type", "ESP32-S3") && + cJSON_AddStringToObject(root, "device_ip", "10.10.99.97") && + cJSON_AddStringToObject(root, "description", "TianShanOS Rack Manager"); + cJSON *san_ips = complete ? cJSON_AddArrayToObject(root, "suggested_san_ips") : NULL; + cJSON *ip = san_ips ? cJSON_CreateString("10.10.99.97") : NULL; + if (!ip || !cJSON_AddItemToArray(san_ips, ip)) { + cJSON_Delete(ip); + cJSON_Delete(root); + free(csr_pem); + return ESP_ERR_NO_MEM; + } + char *json_str = cJSON_PrintUnformatted(root); cJSON_Delete(root); free(csr_pem); @@ -268,13 +304,12 @@ esp_err_t ts_pki_client_submit_csr(void) // 发送 HTTP 请求到 /api/csr/submit char url[256]; - snprintf(url, sizeof(url), "http%s://%s:%d/api/csr/submit", - s_client.config.use_https ? "s" : "", - s_client.config.server_host, - s_client.config.server_port); + server_url(url, sizeof(url), "/api/csr/submit"); int http_code = 0; - ret = do_http_request(url, HTTP_METHOD_POST, json_str, &http_code); + cJSON *resp = NULL; + s_client.request_id = 0; + ret = do_http_request(url, HTTP_METHOD_POST, json_str, &http_code, &resp); free(json_str); if (ret != ESP_OK) { @@ -284,10 +319,14 @@ esp_err_t ts_pki_client_submit_csr(void) if (http_code == 200 || http_code == 201) { // 解析响应获取 request_id - cJSON *resp = cJSON_Parse(s_http_resp_buf); if (resp) { cJSON *req_id = cJSON_GetObjectItem(resp, "request_id"); - if (req_id && cJSON_IsNumber(req_id)) { + if (!cJSON_IsNumber(req_id) || !isfinite(req_id->valuedouble) || req_id->valuedouble < 1 || + req_id->valuedouble > INT_MAX || req_id->valuedouble != (int)req_id->valuedouble) { + cJSON_Delete(resp); + return ESP_ERR_INVALID_RESPONSE; + } + if (req_id) { s_client.request_id = req_id->valueint; ESP_LOGI(TAG, "CSR submitted successfully, request_id=%d", s_client.request_id); } @@ -298,18 +337,7 @@ esp_err_t ts_pki_client_submit_csr(void) strcmp(status->valuestring, "approved") == 0 && cert && cJSON_IsString(cert)) { ESP_LOGI(TAG, "Certificate auto-issued!"); - cJSON *ca_chain = cJSON_GetObjectItem(resp, "ca_chain"); - // 安装证书 (mbedtls 需要包含 null 终止符) - ret = ts_cert_install_certificate(cert->valuestring, strlen(cert->valuestring) + 1); - // 安装 CA 链 - if (ret == ESP_OK && ca_chain && cJSON_IsString(ca_chain)) { - ret = ts_cert_install_ca_chain(ca_chain->valuestring, strlen(ca_chain->valuestring) + 1); - } - if (ret == ESP_OK) { - ts_cert_pki_status_t installed; - ret = ts_cert_get_status(&installed); - if (ret == ESP_OK && (!installed.has_ca_chain || !installed.ca_valid)) ret = ESP_ERR_INVALID_STATE; - } + ret = ts_cert_install_issued_certificate_ex(cert->valuestring, strlen(cert->valuestring) + 1, NULL); if (ret != ESP_OK) { cJSON_Delete(resp); return ret; } } cJSON_Delete(resp); @@ -317,14 +345,14 @@ esp_err_t ts_pki_client_submit_csr(void) return ESP_OK; } else if (http_code == 409) { ESP_LOGW(TAG, "CSR already exists for this device"); - return ESP_OK; // 已存在也算成功 + return ESP_ERR_INVALID_STATE; /* Conflict without a bound request ID is not success. */ } else { ESP_LOGE(TAG, "Server returned error: %d", http_code); return ESP_FAIL; } } -esp_err_t ts_pki_client_check_status(ts_pki_enroll_status_t *status) +static esp_err_t ts_pki_client_check_status_locked(ts_pki_enroll_status_t *status) { if (!s_client.initialized || !status) { return ESP_ERR_INVALID_STATE; @@ -336,14 +364,13 @@ esp_err_t ts_pki_client_check_status(ts_pki_enroll_status_t *status) } char url[256]; - snprintf(url, sizeof(url), "http%s://%s:%d/api/csr/status/%d", - s_client.config.use_https ? "s" : "", - s_client.config.server_host, - s_client.config.server_port, - s_client.request_id); + char path[64]; + snprintf(path, sizeof(path), "/api/csr/status/%d", s_client.request_id); + server_url(url, sizeof(url), path); int http_code = 0; - esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code); + cJSON *root = NULL; + esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code, &root); if (ret != ESP_OK) { *status = TS_PKI_ENROLL_ERROR; @@ -356,12 +383,12 @@ esp_err_t ts_pki_client_check_status(ts_pki_enroll_status_t *status) } if (http_code != 200) { + cJSON_Delete(root); *status = TS_PKI_ENROLL_ERROR; return ESP_OK; } // 解析 JSON 响应 - cJSON *root = cJSON_Parse(s_http_resp_buf); if (!root) { *status = TS_PKI_ENROLL_ERROR; return ESP_OK; @@ -387,7 +414,7 @@ esp_err_t ts_pki_client_check_status(ts_pki_enroll_status_t *status) return ESP_OK; } -esp_err_t ts_pki_client_install_certificate(void) +static esp_err_t ts_pki_client_install_certificate_locked(void) { if (!s_client.initialized) { return ESP_ERR_INVALID_STATE; @@ -402,22 +429,21 @@ esp_err_t ts_pki_client_install_certificate(void) // 从 /api/csr/status/{request_id} 获取证书 char url[256]; - snprintf(url, sizeof(url), "http%s://%s:%d/api/csr/status/%d", - s_client.config.use_https ? "s" : "", - s_client.config.server_host, - s_client.config.server_port, - s_client.request_id); + char path[64]; + snprintf(path, sizeof(path), "/api/csr/status/%d", s_client.request_id); + server_url(url, sizeof(url), path); int http_code = 0; - esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code); + cJSON *root = NULL; + esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code, &root); if (ret != ESP_OK || http_code != 200) { + cJSON_Delete(root); ESP_LOGE(TAG, "Failed to get certificate: http_code=%d", http_code); return ESP_FAIL; } // 解析 JSON 响应 - cJSON *root = cJSON_Parse(s_http_resp_buf); if (!root) { ESP_LOGE(TAG, "Failed to parse certificate response"); return ESP_FAIL; @@ -438,30 +464,10 @@ esp_err_t ts_pki_client_install_certificate(void) return ESP_FAIL; } - // 获取 CA 链(如果有) - cJSON *ca_chain = cJSON_GetObjectItem(root, "ca_chain"); - const char *ca_chain_str = (ca_chain && cJSON_IsString(ca_chain)) ? ca_chain->valuestring : NULL; - - // 安装证书 (mbedtls 需要包含 null 终止符) - ret = ts_cert_install_certificate(cert_pem->valuestring, strlen(cert_pem->valuestring) + 1); - - if (ret != ESP_OK) { - cJSON_Delete(root); - ESP_LOGE(TAG, "Failed to install certificate: %s", esp_err_to_name(ret)); - return ret; - } - - // 安装 CA 链 - if (ca_chain_str) { - ret = ts_cert_install_ca_chain(ca_chain_str, strlen(ca_chain_str) + 1); - if (ret != ESP_OK) { cJSON_Delete(root); return ret; } - } else { - ts_cert_pki_status_t installed; - ret = ts_cert_get_status(&installed); - if (ret != ESP_OK || (!installed.has_ca_chain || !installed.ca_valid)) { - cJSON_Delete(root); return ESP_ERR_INVALID_STATE; - } - } + /* The response is untrusted transport data. Its ca_chain is not a trust + * decision; the material owner verifies against Root's existing bundle. */ + ret = ts_cert_install_issued_certificate_ex(cert_pem->valuestring, strlen(cert_pem->valuestring) + 1, NULL); + if (ret != ESP_OK) { cJSON_Delete(root); return ret; } cJSON_Delete(root); @@ -470,7 +476,7 @@ esp_err_t ts_pki_client_install_certificate(void) return ESP_OK; } -esp_err_t ts_pki_client_enroll_blocking(uint32_t timeout_sec) +static esp_err_t ts_pki_client_enroll_blocking_locked(uint32_t timeout_sec) { if (!s_client.initialized) { return ESP_ERR_INVALID_STATE; @@ -482,17 +488,22 @@ esp_err_t ts_pki_client_enroll_blocking(uint32_t timeout_sec) return ret; } - // 计算超时 - uint32_t max_attempts = timeout_sec ? - (timeout_sec / s_client.config.poll_interval_sec) : - s_client.config.max_poll_attempts; - + uint32_t max_attempts = timeout_sec ? 0 : s_client.config.max_poll_attempts; + // 轮询等待批准 uint32_t attempts = 0; ts_pki_enroll_status_t status; - while (attempts < max_attempts) { - vTaskDelay(pdMS_TO_TICKS(s_client.config.poll_interval_sec * 1000)); + while (!max_attempts || attempts < max_attempts) { + uint32_t wait_ms = (uint32_t)s_client.config.poll_interval_sec * 1000; + if (s_request_deadline) { + int64_t remaining = (s_request_deadline - esp_timer_get_time()) / 1000; + if (remaining <= 0) return ESP_ERR_TIMEOUT; + if (remaining < wait_ms) wait_ms = (uint32_t)remaining; + } + enroll_wait(wait_ms); + if (s_deinitializing) return ESP_ERR_INVALID_STATE; + if (!request_current(xTaskGetCurrentTaskHandle())) return ESP_ERR_TIMEOUT; ret = ts_pki_client_check_status(&status); if (ret != ESP_OK) { @@ -530,34 +541,38 @@ esp_err_t ts_pki_client_enroll_blocking(uint32_t timeout_sec) /* Background Enrollment Service */ /*===========================================================================*/ -esp_err_t ts_pki_client_start_auto_enroll(ts_pki_enroll_callback_t callback, +static esp_err_t ts_pki_client_start_auto_enroll_locked(ts_pki_enroll_callback_t callback, void *user_data) { if (!s_client.initialized) { return ESP_ERR_INVALID_STATE; } - bool expected = false; - if (!atomic_compare_exchange_strong(&s_client.enroll_running, &expected, true)) { - ESP_LOGW(TAG, "Auto-enroll already running"); - return ESP_OK; + portENTER_CRITICAL(&s_operation_init_lock); + bool already_running = s_client.enroll_running; + if (!already_running) { + s_client.stop_requested = false; + s_client.enroll_task = NULL; + s_client.enroll_running = true; } - + portEXIT_CRITICAL(&s_operation_init_lock); + if (already_running) return ESP_OK; s_client.callback = callback; s_client.callback_data = user_data; - s_client.stop_requested = false; - + /* MUST use DRAM stack - PKI operations access NVS (SPI Flash). * SPI Flash operations disable cache, and PSRAM access requires cache. */ + TaskHandle_t task = NULL; BaseType_t ret = xTaskCreate(auto_enroll_task, "pki_enroll", 8192, - NULL, 5, &s_client.enroll_task); + NULL, 5, &task); if (ret != pdPASS) { s_client.enroll_running = false; ESP_LOGE(TAG, "Failed to create enroll task"); return ESP_ERR_NO_MEM; } + s_client.enroll_task = task; ESP_LOGI(TAG, "Auto-enrollment started"); return ESP_OK; } @@ -567,6 +582,7 @@ void ts_pki_client_stop_auto_enroll(void) if (!s_client.enroll_running) return; s_client.stop_requested = true; + if (s_client.enroll_task == xTaskGetCurrentTaskHandle()) return; // 等待任务退出 for (int i = 0; i < 50; i++) { @@ -603,18 +619,15 @@ const char *ts_pki_enroll_status_to_str(ts_pki_enroll_status_t status) } } -bool ts_pki_client_is_server_reachable(void) +static bool ts_pki_client_is_server_reachable_locked(void) { if (!s_client.initialized) return false; char url[128]; - snprintf(url, sizeof(url), "http%s://%s:%d/api/health", - s_client.config.use_https ? "s" : "", - s_client.config.server_host, - s_client.config.server_port); + server_url(url, sizeof(url), "/api/health"); int http_code = 0; - esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code); + esp_err_t ret = do_http_request(url, HTTP_METHOD_GET, NULL, &http_code, NULL); return (ret == ESP_OK && http_code == 200); } @@ -644,75 +657,46 @@ static esp_err_t get_device_id(void) return ESP_OK; } -static esp_err_t http_event_handler(esp_http_client_event_t *evt) -{ - switch (evt->event_id) { - case HTTP_EVENT_ON_DATA: - if (!esp_http_client_is_chunked_response(evt->client)) { - if (s_http_resp_len + evt->data_len < HTTP_RESP_BUF_SIZE - 1) { - memcpy(s_http_resp_buf + s_http_resp_len, evt->data, evt->data_len); - s_http_resp_len += evt->data_len; - s_http_resp_buf[s_http_resp_len] = '\0'; - } - } - break; - default: - break; - } - return ESP_OK; -} - static esp_err_t do_http_request(const char *url, esp_http_client_method_t method, - const char *post_data, int *http_code) -{ - esp_http_client_config_t config = { - .url = url, - .method = method, - .event_handler = http_event_handler, - .timeout_ms = TS_PKI_HTTP_TIMEOUT_MS, - .buffer_size = 2048, - .buffer_size_tx = 2048, + const char *post_data, int *http_code, cJSON **response) +{ + if (!http_code) return ESP_ERR_INVALID_ARG; + *http_code = 0; + if (response) *response = NULL; + unsigned timeout_ms = TS_PKI_HTTP_TIMEOUT_MS; + if (s_request_deadline) { + int64_t remaining = (s_request_deadline - esp_timer_get_time()) / 1000; + if (remaining <= 0) return ESP_ERR_TIMEOUT; + if (remaining < timeout_ms) timeout_ms = (unsigned)remaining; + } + ts_http_fetch_config_t request = { + .url = url, .method = method, .body = post_data, + .content_type = post_data ? "application/json" : NULL, + .timeout_ms = timeout_ms, .maximum_body = HTTP_RESP_BUF_SIZE - 1, + .current = request_current, .context = xTaskGetCurrentTaskHandle(), }; - - // 如果使用 HTTPS,配置证书验证 - if (s_client.config.use_https) { - config.crt_bundle_attach = esp_crt_bundle_attach; - } - - esp_http_client_handle_t client = esp_http_client_init(&config); - if (!client) { - return ESP_ERR_NO_MEM; - } - - // 设置 Content-Type - if (post_data) { - esp_http_client_set_header(client, "Content-Type", "application/json"); - esp_http_client_set_post_field(client, post_data, strlen(post_data)); - } - - // 清空响应缓冲区 - s_http_resp_len = 0; - s_http_resp_buf[0] = '\0'; - - // 执行请求 - esp_err_t ret = esp_http_client_perform(client); - + ts_http_fetch_result_t reply = {0}; + esp_err_t ret = ts_http_fetch(&request, &reply); + if (ret == ESP_OK && !request_current(request.context)) ret = ESP_ERR_INVALID_STATE; if (ret == ESP_OK) { - *http_code = esp_http_client_get_status_code(client); - ESP_LOGD(TAG, "HTTP %s %s => %d", - method == HTTP_METHOD_POST ? "POST" : "GET", - url, *http_code); - } else { - ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(ret)); - } - - esp_http_client_cleanup(client); + *http_code = reply.status; + if (response && (reply.status == 200 || reply.status == 201)) { + const char *end = NULL; + cJSON *json = reply.body ? cJSON_ParseWithLengthOpts(reply.body, reply.length + 1, &end, true) : NULL; + if (!cJSON_IsObject(json) || end != reply.body + reply.length) { + cJSON_Delete(json); + ret = ESP_ERR_INVALID_RESPONSE; + } else *response = json; + } + ESP_LOGD(TAG, "PKI HTTP status=%d", *http_code); + } else ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(ret)); + free(reply.body); return ret; } static void enroll_wait(uint32_t ms) { - while (ms && !s_client.stop_requested) { + while (ms && request_current(xTaskGetCurrentTaskHandle())) { uint32_t step = ms < 100 ? ms : 100; vTaskDelay(pdMS_TO_TICKS(step)); ms -= step; } @@ -725,7 +709,7 @@ static void auto_enroll_task(void *arg) // 等待网络就绪 enroll_wait(5000); - if (s_client.stop_requested) goto done; + if (!request_current(xTaskGetCurrentTaskHandle())) goto done; // 检查是否已有有效证书 ts_cert_pki_status_t cert_status; @@ -745,7 +729,7 @@ static void auto_enroll_task(void *arg) // 等待 PKI 服务器可达 int retry = 0; - while (!s_client.stop_requested && retry < 30) { + while (request_current(xTaskGetCurrentTaskHandle()) && retry < 30) { if (ts_pki_client_is_server_reachable()) { ESP_LOGI(TAG, "PKI server is reachable"); break; @@ -755,7 +739,7 @@ static void auto_enroll_task(void *arg) retry++; } - if (s_client.stop_requested) { + if (!request_current(xTaskGetCurrentTaskHandle())) { s_client.enroll_running = false; vTaskDelete(NULL); return; @@ -782,7 +766,7 @@ static void auto_enroll_task(void *arg) uint32_t attempts = 0; ts_pki_enroll_status_t status; - while (!s_client.stop_requested) { + while (request_current(xTaskGetCurrentTaskHandle())) { if (s_client.config.max_poll_attempts > 0 && attempts >= s_client.config.max_poll_attempts) { ESP_LOGE(TAG, "Max poll attempts reached"); @@ -795,7 +779,7 @@ static void auto_enroll_task(void *arg) enroll_wait(s_client.config.poll_interval_sec * 1000); - if (s_client.stop_requested) break; + if (!request_current(xTaskGetCurrentTaskHandle())) break; ret = ts_pki_client_check_status(&status); if (ret != ESP_OK) { ESP_LOGW(TAG, "Failed to check status, retrying..."); @@ -855,3 +839,83 @@ static void auto_enroll_task(void *arg) s_client.enroll_running = false; vTaskDelete(NULL); } + +/* Public entry points; busy never starts a second request or changes its target. */ +esp_err_t ts_pki_client_init_with_config(const ts_pki_client_config_t *config) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + esp_err_t result = ts_pki_client_init_with_config_locked(config); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_set_server(const char *host, uint16_t port) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + esp_err_t result = ts_pki_client_set_server_locked(host, port); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_get_server(char *host, uint16_t *port) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + esp_err_t result = ts_pki_client_get_server_locked(host, port); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_submit_csr(void) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + if (!enrollment_owner()) { xSemaphoreGiveRecursive(s_operation); return ESP_ERR_INVALID_STATE; } + esp_err_t result = ts_pki_client_submit_csr_locked(); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_check_status(ts_pki_enroll_status_t *status) +{ + if (status) *status = TS_PKI_ENROLL_ERROR; + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + esp_err_t result = ts_pki_client_check_status_locked(status); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_install_certificate(void) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + if (!enrollment_owner()) { xSemaphoreGiveRecursive(s_operation); return ESP_ERR_INVALID_STATE; } + esp_err_t result = ts_pki_client_install_certificate_locked(); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_enroll_blocking(uint32_t timeout_sec) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + if (!enrollment_owner()) { xSemaphoreGiveRecursive(s_operation); return ESP_ERR_INVALID_STATE; } + s_request_deadline = timeout_sec ? esp_timer_get_time() + (int64_t)timeout_sec * 1000000 : 0; + esp_err_t result = ts_pki_client_enroll_blocking_locked(timeout_sec); + s_request_deadline = 0; + xSemaphoreGiveRecursive(s_operation); + return result; +} + +esp_err_t ts_pki_client_start_auto_enroll(ts_pki_enroll_callback_t callback, + void *user_data) +{ + if (!operation_enter()) return ESP_ERR_INVALID_STATE; + esp_err_t result = ts_pki_client_start_auto_enroll_locked(callback, user_data); + xSemaphoreGiveRecursive(s_operation); + return result; +} + +bool ts_pki_client_is_server_reachable(void) +{ + if (!operation_enter()) return false; + bool result = ts_pki_client_is_server_reachable_locked(); + xSemaphoreGiveRecursive(s_operation); + return result; +} diff --git a/components/ts_security/CMakeLists.txt b/components/ts_security/CMakeLists.txt index 4943d7c2..9e99818c 100644 --- a/components/ts_security/CMakeLists.txt +++ b/components/ts_security/CMakeLists.txt @@ -30,6 +30,7 @@ idf_component_register( ch405labs_esp_libssh2 json PRIV_REQUIRES + app_update ts_storage esp_timer ts_config_pack diff --git a/components/ts_security/include/ts_keystore.h b/components/ts_security/include/ts_keystore.h index 3a433010..c93cd1d4 100644 --- a/components/ts_security/include/ts_keystore.h +++ b/components/ts_security/include/ts_keystore.h @@ -8,9 +8,9 @@ * * SECURITY PRINCIPLES: * ==================== - * 1. Private keys NEVER leave secure storage (no export API) - * 2. Memory is securely zeroed after use (prevents RAM dump attacks) - * 3. Only public keys can be exported to files + * 1. Private export requires an explicit exportable flag and authorized caller + * 2. Temporary private-key buffers are cleared before release + * 3. Ordinary internal SSH use can load non-exportable private keys * 4. NVS encryption protects keys at rest (when enabled) * * STORAGE CAPACITY: @@ -19,7 +19,7 @@ * - Max keys: 8 (TS_KEYSTORE_MAX_KEYS) * - RSA-4096: ~4.2KB per key (private + public + metadata) * - ECDSA P-256: ~0.6KB per key - * - Total capacity: 8x RSA-4096 or 50+ ECDSA keys + * - At most 8 keys; actual capacity depends on serialized sizes and NVS overhead * * CONFIGURATION: * ============== @@ -104,7 +104,7 @@ typedef struct { uint32_t last_used; /**< Last used timestamp */ bool has_public_key; /**< Whether public key is stored */ bool exportable; /**< Whether private key can be exported */ - bool hidden; /**< Whether key ID is hidden from unauthenticated users */ + bool hidden; /**< Whether key ID is hidden from non-Root external readers */ } ts_keystore_key_info_t; /** @@ -114,7 +114,7 @@ typedef struct { bool exportable; /**< Allow private key export (default: false) */ const char *comment; /**< Key comment (optional) */ const char *alias; /**< Display alias (optional, recommended for hidden keys) */ - bool hidden; /**< Hide key ID from unauthenticated users (default: false) */ + bool hidden; /**< Hide key ID from non-Root external readers (default: false) */ } ts_keystore_gen_opts_t; /** Per-call generation outcome. Storage success is independent of HTTP delivery. */ @@ -181,17 +181,21 @@ bool ts_keystore_is_initialized(void); * Stores a private key (and optionally public key) in the secure storage. * The private key is encrypted at rest using NVS encryption. * - * @param[in] id Unique key identifier (max TS_KEYSTORE_ID_MAX_LEN chars) + * @param[in] id New unique key ID (up to 10 bytes with current NVS suffixes) * @param[in] keypair Key pair to store * @param[in] type Key type * @param[in] comment Optional comment (can be NULL) * + * Existing IDs and any unlisted fragments are rejected without writes. + * Finish explicit deletion before reusing an ID; there is no overwrite mode. + * * @return * - ESP_OK on success * - ESP_ERR_INVALID_ARG if id or keypair is invalid * - ESP_ERR_NO_MEM if out of memory * - ESP_ERR_NVS_NOT_ENOUGH_SPACE if storage is full - * - ESP_ERR_INVALID_STATE if keystore not initialized + * - ESP_ERR_INVALID_STATE if keystore not initialized or ID occupied + * - ESP_ERR_NOT_FINISHED if failed creation cleanup could not be confirmed */ esp_err_t ts_keystore_store_key(const char *id, const ts_keystore_keypair_t *keypair, @@ -281,8 +285,8 @@ esp_err_t ts_keystore_get_key_info(const char *id, ts_keystore_key_info_t *info) * * Retrieves a list of all stored key IDs and their metadata. * - * @param[out] keys Array to receive key info (must be at least TS_KEYSTORE_MAX_KEYS) - * @param[out] count Pointer to receive actual number of keys + * @param[out] keys Array to receive key info + * @param[in,out] count Input capacity; output count (zero on read failure) * * @return * - ESP_OK on success @@ -297,7 +301,7 @@ esp_err_t ts_keystore_list_keys(ts_keystore_key_info_t *keys, size_t *count); * Extended version of ts_keystore_list_keys with filtering support. * * @param[out] keys Array to receive key info - * @param[out] count Pointer to receive actual number of keys + * @param[in,out] count Input capacity; output count (zero on read failure) * @param[in] show_hidden If true, include hidden keys; if false, exclude them * * @return @@ -307,6 +311,17 @@ esp_err_t ts_keystore_list_keys(ts_keystore_key_info_t *keys, size_t *count); */ esp_err_t ts_keystore_list_keys_ex(ts_keystore_key_info_t *keys, size_t *count, bool show_hidden); +/** Read one visibility-checked metadata/public-key snapshot under the existing + * writer lock. Both public-key outputs may be NULL for metadata only. + * Hidden and absent records return NOT_FOUND when show_hidden is false. + * No private key bytes are returned. */ +esp_err_t ts_keystore_read_public_record(const char *id, bool show_hidden, + ts_keystore_key_info_t *info, char **public_key, size_t *public_key_len); +/* Explicit export only: checks immutable exportability and reads the same key + * under the store owner. Ordinary internal private-key use remains supported. */ +esp_err_t ts_keystore_read_exportable_private_record(const char *id, + ts_keystore_key_info_t *info, char **private_key, size_t *private_key_len); + /** * @brief Update last used timestamp * diff --git a/components/ts_security/include/ts_security.h b/components/ts_security/include/ts_security.h index a2f839e4..3fded786 100644 --- a/components/ts_security/include/ts_security.h +++ b/components/ts_security/include/ts_security.h @@ -112,18 +112,24 @@ esp_err_t ts_security_validate_session(uint32_t session_id, ts_session_t *sessio */ esp_err_t ts_security_destroy_session(uint32_t session_id); +/** + * @brief Revoke every session belonging to a trusted client identity. + * @note Caller must derive client_id from trusted C state, never request JSON. + */ +void ts_security_destroy_sessions_by_client(const char *client_id); + /** * @brief Check permission */ bool ts_security_check_permission(uint32_t session_id, ts_perm_level_t required); /** - * @brief Generate auth token + * @brief Generate opaque 16-random-byte Base64 auth token */ esp_err_t ts_security_generate_token(uint32_t session_id, char *token, size_t max_len); /** - * @brief Validate auth token + * @brief Match the complete issued credential, then validate its session */ esp_err_t ts_security_validate_token(const char *token, uint32_t *session_id); diff --git a/components/ts_security/src/ts_auth.c b/components/ts_security/src/ts_auth.c index 7366d588..02e6fb73 100644 --- a/components/ts_security/src/ts_auth.c +++ b/components/ts_security/src/ts_auth.c @@ -2,7 +2,7 @@ * @file ts_auth.c * @brief Authentication Helpers - 用户认证与会话管理 * - * 支持 admin 和 root 两个用户,密码使用 SHA256+salt 哈希存储于 NVS + * 支持 admin 和 root 两个用户,密码使用原有加盐 SHA-256 存储于 NVS * * 安全设计: * - 密码哈希仅存储在 NVS,不导出到 SD 卡 @@ -17,6 +17,8 @@ #include "nvs.h" #include "esp_random.h" #include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" #include #define TAG "ts_auth" @@ -28,35 +30,19 @@ typedef ts_auth_user_credential_t user_credential_t; static nvs_handle_t s_auth_nvs; static bool s_auth_initialized = false; +static uint8_t s_auth_format_version; +/* Serialize password verification + session issuance with credential updates. + * Otherwise a login verified before a change can issue a session after revocation. */ +static StaticSemaphore_t s_auth_gate_storage; +static SemaphoreHandle_t s_auth_gate; +/* Per-boot monotonic deadlines; on-flash nonzero lockout_until is only a marker. + * Never compare a previous boot's uptime to this boot's clock. */ +static uint32_t s_lockout_deadlines[2]; /* admin, root */ /*===========================================================================*/ /* 内部函数 */ /*===========================================================================*/ -/** - * @brief 计算密码哈希 (SHA256(salt + password)) - */ -static esp_err_t compute_password_hash(const uint8_t *salt, const char *password, - uint8_t *hash_out) -{ - /* 拼接 salt + password */ - size_t pwd_len = strlen(password); - size_t total_len = TS_AUTH_SALT_LEN + pwd_len; - uint8_t *buf = malloc(total_len); - if (!buf) return ESP_ERR_NO_MEM; - - memcpy(buf, salt, TS_AUTH_SALT_LEN); - memcpy(buf + TS_AUTH_SALT_LEN, password, pwd_len); - - esp_err_t ret = ts_crypto_hash(TS_HASH_SHA256, buf, total_len, hash_out, TS_AUTH_HASH_LEN); - - /* 清除敏感数据 */ - memset(buf, 0, total_len); - free(buf); - - return ret; -} - /** * @brief 获取用户凭据 */ @@ -65,27 +51,60 @@ static esp_err_t load_user_credential(const char *username, user_credential_t *c char key[32]; snprintf(key, sizeof(key), "cred_%s", username); - size_t len = sizeof(user_credential_t); - esp_err_t ret = nvs_get_blob(s_auth_nvs, key, cred, &len); - + unsigned char bytes[TS_AUTH_MAX_CREDENTIAL_SIZE]; + size_t len = sizeof(bytes); + esp_err_t ret = nvs_get_blob(s_auth_nvs, key, bytes, &len); + if (ret == ESP_OK) ret = ts_auth_credential_decode(bytes, len, cred); + memset(bytes, 0, sizeof(bytes)); return ret; } /** * @brief 保存用户凭据 */ -static esp_err_t save_user_credential(const char *username, const user_credential_t *cred) +static esp_err_t save_user_credential(const char *username, const user_credential_t *cred, bool revoke_sessions) { char key[32]; snprintf(key, sizeof(key), "cred_%s", username); - esp_err_t ret = nvs_set_blob(s_auth_nvs, key, cred, sizeof(user_credential_t)); + size_t length = cred->format ? sizeof(*cred) : TS_AUTH_LEGACY_CREDENTIAL_SIZE; + esp_err_t ret = nvs_set_blob(s_auth_nvs, key, cred, length); + if (ret != ESP_OK) return ret; + /* A failed commit may already expose the new credential. Never let an old + * session survive a password replacement accepted by the storage owner. */ + if (revoke_sessions) ts_security_destroy_sessions_by_client(username); + ret = nvs_commit(s_auth_nvs); if (ret == ESP_OK) { - nvs_commit(s_auth_nvs); + user_credential_t readback; + ret = load_user_credential(username, &readback); + if (ret == ESP_OK && memcmp(cred, &readback, sizeof(readback))) ret = ESP_FAIL; + memset(&readback, 0, sizeof(readback)); } - return ret; + return ret != ESP_OK && revoke_sessions ? ESP_ERR_NOT_FINISHED : ret; } +/* Only retire the unreleased prototype marker after both stored records are + * actually readable by stock 0.6.4. Never relabel an unreadable credential. */ +static esp_err_t finish_credential_migration(void) +{ + if (s_auth_format_version == TS_AUTH_CONFIG_VERSION) return ESP_OK; + const char *users[] = {"admin", "root"}; + for (unsigned i = 0; i < 2; ++i) { + user_credential_t credential; + esp_err_t ret = load_user_credential(users[i], &credential); + bool original = ret == ESP_OK && credential.format == 0; + memset(&credential, 0, sizeof(credential)); + if (ret != ESP_OK) return ret; + if (!original) return ESP_ERR_NOT_FINISHED; + } + esp_err_t ret = nvs_set_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, TS_AUTH_CONFIG_VERSION); + if (ret == ESP_OK) ret = nvs_commit(s_auth_nvs); + uint8_t readback = 0; + if (ret == ESP_OK) ret = nvs_get_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, &readback); + if (ret == ESP_OK && readback != TS_AUTH_CONFIG_VERSION) ret = ESP_FAIL; + if (ret == ESP_OK) s_auth_format_version = TS_AUTH_CONFIG_VERSION; + return ret; +} /** * @brief 写入用户密码凭据,并清除失败计数/锁定状态 */ @@ -100,18 +119,18 @@ static esp_err_t write_user_password_credential(const char *username, const char return ESP_ERR_INVALID_ARG; } - user_credential_t cred = {0}; - - esp_fill_random(cred.salt, TS_AUTH_SALT_LEN); - - esp_err_t ret = compute_password_hash(cred.salt, password, cred.hash); + user_credential_t cred; + esp_err_t ret = ts_auth_credential_create(password, password_changed, &cred); if (ret != ESP_OK) return ret; - - cred.password_changed = password_changed; - cred.failed_attempts = 0; - cred.lockout_until = 0; - - return save_user_credential(username, &cred); + ret = save_user_credential(username, &cred, true); + if (ret == ESP_OK) { + esp_err_t migrated = finish_credential_migration(); + if (migrated != ESP_OK && migrated != ESP_ERR_NOT_FINISHED) ret = ESP_ERR_NOT_FINISHED; + } + memset(&cred, 0, sizeof(cred)); + if (ret == ESP_OK) + s_lockout_deadlines[strcmp(username, "root") == 0 ? 1 : 0] = 0; + return ret; } /** @@ -129,31 +148,47 @@ static esp_err_t force_create_user(const char *username, ts_perm_level_t level) } /** - * @brief 初始化用户(如果不存在则创建默认密码) + * @brief 获取当前时间(秒) */ -static esp_err_t init_user_if_needed(const char *username, ts_perm_level_t level) +static uint32_t get_current_time_sec(void) { - user_credential_t cred; - - if (load_user_credential(username, &cred) == ESP_OK) { - /* 开机计时相关的临时锁定不能沿用到本次启动。 */ - if (cred.failed_attempts || cred.lockout_until) { - cred.failed_attempts = 0; - cred.lockout_until = 0; - return save_user_credential(username, &cred); - } - return ESP_OK; - } - - return force_create_user(username, level); + return (uint32_t)(esp_timer_get_time() / 1000000); +} + +static bool credential_is_locked(const user_credential_t *cred) +{ + return cred->lockout_until != 0 || cred->failed_attempts >= MAX_LOGIN_ATTEMPTS; } /** - * @brief 获取当前时间(秒) + * @brief 准备已有用户;读取失败不能当作恢复默认口令的授权 */ -static uint32_t get_current_time_sec(void) +static esp_err_t init_existing_user(const char *username) { - return (uint32_t)(esp_timer_get_time() / 1000000); + user_credential_t cred; + esp_err_t ret = load_user_credential(username, &cred); + if (ret == ESP_OK && credential_is_locked(&cred)) { + unsigned index = strcmp(username, "root") == 0 ? 1 : 0; + s_lockout_deadlines[index] = get_current_time_sec() + LOGIN_LOCKOUT_SEC; + } + if (ret == ESP_OK && cred.format == TS_AUTH_CREDENTIAL_MAGIC) { + const char *password = !strcmp(username, "root") ? TS_AUTH_DEFAULT_ROOT_PASSWORD : TS_AUTH_DEFAULT_ADMIN_PASSWORD; + bool matches = false; + ret = ts_auth_credential_verify(&cred, password, &matches); + if (ret == ESP_OK && matches) { + user_credential_t original; + ret = ts_auth_credential_create(password, cred.password_changed, &original); + if (ret == ESP_OK) { + original.failed_attempts = cred.failed_attempts; + original.lockout_until = cred.lockout_until; + ret = save_user_credential(username, &original, false); + } + memset(&original, 0, sizeof(original)); + } + } + memset(&cred, 0, sizeof(cred)); + /* Preserve the retry budget; prototype conversion never resets a password. */ + return ret; } /*===========================================================================*/ @@ -166,6 +201,8 @@ static uint32_t get_current_time_sec(void) esp_err_t ts_auth_init(void) { if (s_auth_initialized) return ESP_OK; + if (!s_auth_gate) s_auth_gate = xSemaphoreCreateMutexStatic(&s_auth_gate_storage); + if (!s_auth_gate) return ESP_ERR_NO_MEM; esp_err_t ret = nvs_open(TS_AUTH_NVS_NAMESPACE, NVS_READWRITE, &s_auth_nvs); if (ret != ESP_OK) { @@ -173,38 +210,61 @@ esp_err_t ts_auth_init(void) return ret; } - /* 检查配置版本,版本变化时强制重置所有用户 */ + memset(s_lockout_deadlines, 0, sizeof(s_lockout_deadlines)); + + /* Only an empty, unversioned namespace is a new device. Errors or unknown + * layouts are not permission to overwrite an existing credential. */ uint8_t stored_version = 0; - nvs_get_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, &stored_version); - - if (stored_version != TS_AUTH_CONFIG_VERSION) { - TS_LOGW(TAG, "Auth config version changed (%d -> %d), resetting all users", - stored_version, TS_AUTH_CONFIG_VERSION); - /* 强制重新创建所有用户 */ - force_create_user("admin", TS_PERM_ADMIN); - force_create_user("root", TS_PERM_ROOT); - /* 保存新版本号 */ - nvs_set_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, TS_AUTH_CONFIG_VERSION); - nvs_commit(s_auth_nvs); + ret = nvs_get_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, &stored_version); + if (ret == ESP_ERR_NVS_NOT_FOUND) { + user_credential_t existing; + ret = load_user_credential("admin", &existing); + if (ret != ESP_ERR_NVS_NOT_FOUND) { + if (ret == ESP_OK) ret = ESP_ERR_INVALID_STATE; + goto failed; + } + ret = load_user_credential("root", &existing); + if (ret != ESP_ERR_NVS_NOT_FOUND) { + if (ret == ESP_OK) ret = ESP_ERR_INVALID_STATE; + goto failed; + } + s_auth_format_version = TS_AUTH_CONFIG_VERSION; + ret = force_create_user("admin", TS_PERM_ADMIN); + if (ret == ESP_OK) ret = force_create_user("root", TS_PERM_ROOT); + if (ret == ESP_OK) + ret = nvs_set_u8(s_auth_nvs, TS_AUTH_CONFIG_VERSION_KEY, TS_AUTH_CONFIG_VERSION); + if (ret == ESP_OK) ret = nvs_commit(s_auth_nvs); + if (ret != ESP_OK) goto failed; + } else if (ret == ESP_OK && (stored_version == TS_AUTH_CONFIG_VERSION || + stored_version == TS_AUTH_PROTOTYPE_CONFIG_VERSION)) { + s_auth_format_version = stored_version; + ret = init_existing_user("admin"); + if (ret == ESP_OK) ret = init_existing_user("root"); + if (ret != ESP_OK) goto failed; + ret = finish_credential_migration(); + if (ret != ESP_OK && ret != ESP_ERR_NOT_FINISHED) goto failed; } else { - /* 初始化默认用户(如果不存在) */ - ret = init_user_if_needed("admin", TS_PERM_ADMIN); - if (ret == ESP_OK) ret = init_user_if_needed("root", TS_PERM_ROOT); - if (ret != ESP_OK) { - nvs_close(s_auth_nvs); - return ret; + if (ret == ESP_OK) { + TS_LOGE(TAG, "Unsupported auth config version %u; migration required", stored_version); + ret = ESP_ERR_INVALID_STATE; } + goto failed; } s_auth_initialized = true; TS_LOGI(TAG, "Auth module initialized (version %d)", TS_AUTH_CONFIG_VERSION); return ESP_OK; + +failed: + nvs_close(s_auth_nvs); + s_auth_nvs = 0; + return ret; } /** * @brief 验证用户密码 */ -esp_err_t ts_auth_verify_password(const char *username, const char *password, +static esp_err_t verify_password_locked(const char *username, const char *password, ts_perm_level_t *level) { if (!username || !password) return ESP_ERR_INVALID_ARG; @@ -229,49 +289,71 @@ esp_err_t ts_auth_verify_password(const char *username, const char *password, /* 检查是否被锁定 */ uint32_t now = get_current_time_sec(); - if (cred.lockout_until > now) { + unsigned index = user_level == TS_PERM_ROOT ? 1 : 0; + if (s_lockout_deadlines[index] > now) { TS_LOGW(TAG, "User %s is locked out for %lu more seconds", - username, (unsigned long)(cred.lockout_until - now)); + username, (unsigned long)(s_lockout_deadlines[index] - now)); return ESP_ERR_INVALID_STATE; } - - /* 计算输入密码的哈希 */ - uint8_t computed_hash[TS_AUTH_HASH_LEN]; - ret = compute_password_hash(cred.salt, password, computed_hash); - if (ret != ESP_OK) return ret; - - /* 比较哈希(恒定时间比较防止时序攻击) */ - uint8_t diff = 0; - for (int i = 0; i < TS_AUTH_HASH_LEN; i++) { - diff |= computed_hash[i] ^ cred.hash[i]; + bool expired_lock = credential_is_locked(&cred); + if (expired_lock) { + cred.lockout_until = 0; + cred.failed_attempts = 0; } - /* 清除敏感数据 */ - memset(computed_hash, 0, sizeof(computed_hash)); - - if (diff != 0) { + bool matches; + ret = ts_auth_credential_verify(&cred, password, &matches); + if (ret != ESP_OK) return ret; + + if (!matches) { /* 密码错误,增加失败计数 */ cred.failed_attempts++; if (cred.failed_attempts >= MAX_LOGIN_ATTEMPTS) { - cred.lockout_until = now + LOGIN_LOCKOUT_SEC; + cred.lockout_until = 1; /* persistent marker, not an uptime deadline */ + s_lockout_deadlines[index] = now + LOGIN_LOCKOUT_SEC; cred.failed_attempts = 0; TS_LOGW(TAG, "User %s locked out due to too many failed attempts", username); } - save_user_credential(username, &cred); - return ESP_ERR_INVALID_ARG; + ret = save_user_credential(username, &cred, false); + return ret == ESP_OK ? ESP_ERR_INVALID_ARG : ret; } - /* 密码正确,清除失败计数及已过期的锁定。 */ - if (cred.failed_attempts || cred.lockout_until) { + /* Restore the original verifier after a successful prototype verification. + * A crash leaves either the old or new complete blob under the same key. */ + bool migrated = cred.format == TS_AUTH_CREDENTIAL_MAGIC; + if (migrated) { + user_credential_t upgraded; + ret = ts_auth_credential_create(password, cred.password_changed, &upgraded); + if (ret != ESP_OK) return ret; + cred = upgraded; + memset(&upgraded, 0, sizeof(upgraded)); + } + if (migrated || expired_lock || cred.failed_attempts || cred.lockout_until) { cred.failed_attempts = 0; cred.lockout_until = 0; - save_user_credential(username, &cred); + ret = save_user_credential(username, &cred, false); + if (ret != ESP_OK) return ret; + if (migrated) { + ret = finish_credential_migration(); + if (ret != ESP_OK && ret != ESP_ERR_NOT_FINISHED) return ret; + } } + s_lockout_deadlines[index] = 0; if (level) *level = user_level; return ESP_OK; } +esp_err_t ts_auth_verify_password(const char *username, const char *password, + ts_perm_level_t *level) +{ + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); + esp_err_t ret = verify_password_locked(username, password, level); + xSemaphoreGive(s_auth_gate); + return ret; +} + /** * @brief 修改密码 */ @@ -287,14 +369,18 @@ esp_err_t ts_auth_change_password(const char *username, const char *old_password return ESP_ERR_INVALID_ARG; } - /* 验证旧密码 */ - esp_err_t ret = ts_auth_verify_password(username, old_password, NULL); + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); + /* Verify and replace under the same gate as login. */ + esp_err_t ret = verify_password_locked(username, old_password, NULL); if (ret != ESP_OK) { TS_LOGW(TAG, "Old password verification failed for %s", username); + xSemaphoreGive(s_auth_gate); return ret; } ret = write_user_password_credential(username, new_password, true); + xSemaphoreGive(s_auth_gate); if (ret == ESP_OK) { TS_LOGI(TAG, "Password changed for user %s", username); } @@ -307,7 +393,10 @@ esp_err_t ts_auth_change_password(const char *username, const char *old_password */ esp_err_t ts_auth_set_admin_password(const char *new_password) { + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); esp_err_t ret = write_user_password_credential("admin", new_password, true); + xSemaphoreGive(s_auth_gate); if (ret == ESP_OK) { TS_LOGI(TAG, "Password set for admin by root"); } @@ -320,7 +409,10 @@ esp_err_t ts_auth_set_admin_password(const char *new_password) */ esp_err_t ts_auth_set_root_password(const char *new_password) { + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); esp_err_t ret = write_user_password_credential("root", new_password, true); + xSemaphoreGive(s_auth_gate); if (ret == ESP_OK) { TS_LOGI(TAG, "Password set for root by root"); } @@ -349,17 +441,19 @@ bool ts_auth_password_changed(const char *username) esp_err_t ts_auth_login(const char *username, const char *password, uint32_t *session_id, char *token, size_t token_len) { + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); ts_perm_level_t level; - esp_err_t ret = ts_auth_verify_password(username, password, &level); + esp_err_t ret = verify_password_locked(username, password, &level); if (ret != ESP_OK) { TS_LOGW(TAG, "Login failed for user: %s", username); - return ret; + goto done; } ret = ts_security_create_session(username, level, session_id); if (ret != ESP_OK) { TS_LOGE(TAG, "Failed to create session for %s", username); - return ret; + goto done; } /* 生成 token */ @@ -367,12 +461,14 @@ esp_err_t ts_auth_login(const char *username, const char *password, ret = ts_security_generate_token(*session_id, token, token_len); if (ret != ESP_OK) { ts_security_destroy_session(*session_id); - return ret; + goto done; } } TS_LOGI(TAG, "User %s logged in (level %d)", username, level); - return ESP_OK; +done: + xSemaphoreGive(s_auth_gate); + return ret; } /** @@ -424,7 +520,10 @@ esp_err_t ts_auth_reset_password(const char *username) return ESP_ERR_NOT_FOUND; } + if (!s_auth_initialized) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_auth_gate, portMAX_DELAY); esp_err_t ret = write_user_password_credential(username, default_pwd, false); + xSemaphoreGive(s_auth_gate); if (ret == ESP_OK) { TS_LOGI(TAG, "Password reset to default for user %s", username); } diff --git a/components/ts_security/src/ts_keystore.c b/components/ts_security/src/ts_keystore.c index 30eab918..44c1a343 100644 --- a/components/ts_security/src/ts_keystore.c +++ b/components/ts_security/src/ts_keystore.c @@ -28,6 +28,7 @@ #include #include #include +#include #include static const char *TAG = "ts_keystore"; @@ -88,24 +89,19 @@ static void make_nvs_key(char *buf, size_t buf_len, const char *id, const char * */ static int parse_index(const char *index_str, char ids[][TS_KEYSTORE_ID_MAX_LEN], size_t max_ids) { - if (!index_str || !ids || max_ids == 0) { - return 0; - } - - int count = 0; - char *copy = TS_STRDUP_PSRAM(index_str); - if (!copy) return 0; - char *saveptr = NULL; - char *token = strtok_r(copy, ",", &saveptr); - while (token && count < max_ids) { - strncpy(ids[count], token, TS_KEYSTORE_ID_MAX_LEN - 1); - ids[count][TS_KEYSTORE_ID_MAX_LEN - 1] = '\0'; - count++; - token = strtok_r(NULL, ",", &saveptr); + size_t count = 0; + for (const char *p = index_str; *p;) { + const char *end = strchr(p, ','); + size_t len = end ? (size_t)(end - p) : strlen(p); + if (!len || len >= TS_KEYSTORE_ID_MAX_LEN || count == max_ids) + return -1; + memcpy(ids[count], p, len); + ids[count++][len] = 0; + if (!end) break; + p = end + 1; + if (!*p) return -1; } - - free(copy); - return count; + return (int)count; } /** @@ -172,6 +168,7 @@ static esp_err_t remove_from_index(const char *id) /* 重建索引,排除指定 ID */ char ids[TS_KEYSTORE_MAX_KEYS][TS_KEYSTORE_ID_MAX_LEN]; int count = parse_index(index_str, ids, TS_KEYSTORE_MAX_KEYS); + if (count < 0) return ESP_ERR_INVALID_RESPONSE; char new_index[MAX_INDEX_LEN] = {0}; for (int i = 0; i < count; i++) { @@ -227,94 +224,85 @@ static esp_err_t load_metadata(const char *id, ts_keystore_key_info_t *info) { char key[TS_KEYSTORE_ID_MAX_LEN + 8]; make_nvs_key(key, sizeof(key), id, "_meta"); - - /* 获取长度 */ size_t len = 0; esp_err_t ret = nvs_get_str(s_keystore.nvs_handle, key, NULL, &len); if (ret != ESP_OK) return ret; - + /* JSON escaping can use six bytes per stored comment/alias byte. */ + if (!len || len > 6 * (TS_KEYSTORE_COMMENT_MAX_LEN + TS_KEYSTORE_ALIAS_MAX_LEN) + 256) + return ESP_ERR_INVALID_SIZE; char *str = TS_MALLOC_PSRAM(len); if (!str) return ESP_ERR_NO_MEM; - - ret = nvs_get_str(s_keystore.nvs_handle, key, str, &len); - if (ret != ESP_OK) { + size_t actual = len; + ret = nvs_get_str(s_keystore.nvs_handle, key, str, &actual); + if (ret != ESP_OK || actual != len || str[len - 1] || strlen(str) + 1 != len) { free(str); - return ret; + return ret == ESP_OK ? ESP_ERR_INVALID_RESPONSE : ret; } - - /* 解析 JSON */ - cJSON *json = cJSON_Parse(str); - free(str); - - if (!json) return ESP_ERR_INVALID_RESPONSE; - - memset(info, 0, sizeof(*info)); - strncpy(info->id, id, sizeof(info->id) - 1); - - cJSON *item; - if ((item = cJSON_GetObjectItem(json, "type"))) { - info->type = ts_keystore_type_from_string(item->valuestring); - } - if ((item = cJSON_GetObjectItem(json, "comment"))) { - strncpy(info->comment, item->valuestring, sizeof(info->comment) - 1); - } - if ((item = cJSON_GetObjectItem(json, "alias"))) { - strncpy(info->alias, item->valuestring, sizeof(info->alias) - 1); - } - if ((item = cJSON_GetObjectItem(json, "created_at"))) { - info->created_at = (uint32_t)item->valuedouble; - } - if ((item = cJSON_GetObjectItem(json, "last_used"))) { - info->last_used = (uint32_t)item->valuedouble; - } - if ((item = cJSON_GetObjectItem(json, "has_pubkey"))) { - info->has_public_key = cJSON_IsTrue(item); - } - if ((item = cJSON_GetObjectItem(json, "exportable"))) { - info->exportable = cJSON_IsTrue(item); - } else { - info->exportable = false; /* 旧密钥默认不可导出 */ + for (size_t i = 0; i + 1 < len; ++i) { + if (str[i] != '\\') continue; + if (i + 5 < len && !memcmp(str + i, "\\u0000", 6)) { + free(str); + return ESP_ERR_INVALID_RESPONSE; + } + ++i; /* Skip the escaped byte; a literal backslash is not a Unicode escape. */ } - if ((item = cJSON_GetObjectItem(json, "hidden"))) { - info->hidden = cJSON_IsTrue(item); - } else { - info->hidden = false; /* 旧密钥默认不隐藏 */ + cJSON *json = cJSON_ParseWithLengthOpts(str, len, NULL, true); + free(str); + if (!cJSON_IsObject(json)) { cJSON_Delete(json); return ESP_ERR_INVALID_RESPONSE; } + ts_keystore_key_info_t decoded = {0}; + snprintf(decoded.id, sizeof(decoded.id), "%s", id); + bool has_type = false, valid = true; + const cJSON *item; + cJSON_ArrayForEach(item, json) { + /* Ambiguous metadata must never turn a private record into a public one. */ + for (const cJSON *prior = json->child; prior != item; prior = prior->next) + if (!strcmp(prior->string, item->string)) valid = false; + const char *name = item->string; + if (!strcmp(name, "type")) { + if (!cJSON_IsString(item)) { valid = false; continue; } + decoded.type = ts_keystore_type_from_string(item->valuestring); + has_type = decoded.type != TS_KEYSTORE_TYPE_UNKNOWN || !strcmp(item->valuestring, "unknown"); + } else if (!strcmp(name, "comment") || !strcmp(name, "alias")) { + char *dest = !strcmp(name, "comment") ? decoded.comment : decoded.alias; + size_t capacity = !strcmp(name, "comment") ? sizeof(decoded.comment) : sizeof(decoded.alias); + if (!cJSON_IsString(item) || strlen(item->valuestring) >= capacity) valid = false; + else strcpy(dest, item->valuestring); + } else if (!strcmp(name, "created_at") || !strcmp(name, "last_used")) { + double value = item->valuedouble; + if (!cJSON_IsNumber(item) || !(value >= 0 && value <= UINT32_MAX) || value != (uint32_t)value) + valid = false; + else if (!strcmp(name, "created_at")) decoded.created_at = (uint32_t)value; + else decoded.last_used = (uint32_t)value; + } else if (!strcmp(name, "has_pubkey") || !strcmp(name, "exportable") || !strcmp(name, "hidden")) { + if (!cJSON_IsBool(item)) valid = false; + else if (!strcmp(name, "has_pubkey")) decoded.has_public_key = cJSON_IsTrue(item); + else if (!strcmp(name, "exportable")) decoded.exportable = cJSON_IsTrue(item); + else decoded.hidden = cJSON_IsTrue(item); + } else valid = false; } - cJSON_Delete(json); + if (!valid || !has_type) return ESP_ERR_INVALID_RESPONSE; + /* Absent legacy flags retain their documented false defaults. */ + *info = decoded; return ESP_OK; } /* ========== 公开 API ========== */ /* 内部函数:带选项的密钥存储 */ -static esp_err_t store_key_locked(const char *id, +static esp_err_t write_new_key_locked(const char *id, const ts_keystore_keypair_t *keypair, ts_keystore_key_type_t type, const ts_keystore_gen_opts_t *opts, ts_keystore_generate_result_t *detail) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!id || strlen(id) == 0 || strlen(id) >= TS_KEYSTORE_ID_MAX_LEN) { - ESP_LOGE(TAG, "Invalid key ID"); - return ESP_ERR_INVALID_ARG; - } - - if (!keypair || !keypair->private_key || keypair->private_key_len == 0) { - ESP_LOGE(TAG, "Invalid keypair"); - return ESP_ERR_INVALID_ARG; - } - bool exportable = opts ? opts->exportable : false; const char *comment = opts ? opts->comment : NULL; const char *alias = opts ? opts->alias : NULL; bool hidden = opts ? opts->hidden : false; - ESP_LOGI(TAG, "Storing key '%s' (type=%s, privkey_len=%zu, exportable=%d, hidden=%d)", - id, ts_keystore_type_to_string(type), keypair->private_key_len, exportable, hidden); + ESP_LOGI(TAG, "Storing key (type=%s, privkey_len=%zu, exportable=%d, hidden=%d)", + ts_keystore_type_to_string(type), keypair->private_key_len, exportable, hidden); char nvs_key[TS_KEYSTORE_ID_MAX_LEN + 8]; esp_err_t ret; @@ -338,7 +326,7 @@ static esp_err_t store_key_locked(const char *id, keypair->public_key, keypair->public_key_len); if (ret != ESP_OK) { ESP_LOGW(TAG, "Failed to store public key: %s", esp_err_to_name(ret)); - if (detail) return ret; /* Generated keys require their public key. */ + return ret; } else { has_pubkey = true; } @@ -385,22 +373,10 @@ static esp_err_t store_key_locked(const char *id, } if (detail) { detail->stored = true; detail->failed_stage = NULL; } - ESP_LOGI(TAG, "Key '%s' stored successfully", id); + ESP_LOGI(TAG, "Key stored successfully"); return ESP_OK; } -static esp_err_t ts_keystore_store_key_ex(const char *id, - const ts_keystore_keypair_t *keypair, - ts_keystore_key_type_t type, - const ts_keystore_gen_opts_t *opts) -{ - if (!s_keystore.initialized) return ESP_ERR_INVALID_STATE; - xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); - esp_err_t ret = store_key_locked(id, keypair, type, opts, NULL); - xSemaphoreGive(s_keystore.write_lock); - return ret; -} - /* New generation cannot replace an indexed key or an unlisted fragment. */ static esp_err_t check_new_key(const char *id, char *index, bool *index_present, ts_keystore_generate_result_t *detail) @@ -454,6 +430,53 @@ static esp_err_t cleanup_new_key(const char *id, const char *old_index, return first_error != ESP_OK ? first_error : ret; } +static bool valid_key_id(const char *id) +{ + return id && *id && strlen(id) <= NVS_KEY_NAME_MAX_SIZE - 1 - 5 && !strchr(id, ','); +} + +/* PEM/OpenSSH text may include its final NUL in the stored length. */ +static bool key_text_length(const char *bytes, size_t size, size_t maximum, size_t *length) +{ + if (!bytes || !size || size > maximum + 1) return false; + size_t used = strnlen(bytes, size); + if (!used || used > maximum || (used != size && used + 1 != size)) return false; + *length = used; + return true; +} + +/* Every writer follows the product's existing create-only contract. Check all + * fragments under the same owner as bytes/flags/index and failure cleanup. */ +static esp_err_t create_key(const char *id, const ts_keystore_keypair_t *keypair, + ts_keystore_key_type_t type, const ts_keystore_gen_opts_t *opts, + ts_keystore_generate_result_t *detail) +{ + ts_keystore_generate_result_t local; + if (!detail) detail = &local; + *detail = (ts_keystore_generate_result_t){.failed_stage="validation", .cleanup_complete=true}; + size_t length; + if (!valid_key_id(id) || !keypair || + !key_text_length(keypair->private_key, keypair->private_key_len, TS_KEYSTORE_PRIVKEY_MAX_LEN, &length) || + (keypair->public_key_len && !key_text_length(keypair->public_key, keypair->public_key_len, TS_KEYSTORE_PUBKEY_MAX_LEN, &length))) + return ESP_ERR_INVALID_ARG; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + char old_index[MAX_INDEX_LEN]; + bool index_present; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = check_new_key(id, old_index, &index_present, detail); + if (ret == ESP_OK) { + ret = write_new_key_locked(id, keypair, type, opts, detail); + if (ret != ESP_OK) { + bool index_attempted = !strcmp(detail->failed_stage, "index_write") || + !strcmp(detail->failed_stage, "commit"); + detail->cleanup_error = cleanup_new_key(id, old_index, index_attempted, index_present); + detail->cleanup_complete = detail->cleanup_error == ESP_OK; + } + } + xSemaphoreGive(s_keystore.write_lock); + return ret; +} + esp_err_t ts_keystore_init(void) { /* Static lock remains valid for writers waiting while the service stops. */ @@ -499,101 +522,70 @@ esp_err_t ts_keystore_store_key(const char *id, .exportable = false, .comment = comment, }; - return ts_keystore_store_key_ex(id, keypair, type, &opts); + ts_keystore_generate_result_t detail; + esp_err_t ret = create_key(id, keypair, type, &opts, &detail); + return !detail.cleanup_complete ? ESP_ERR_NOT_FINISHED : ret; } -esp_err_t ts_keystore_load_private_key(const char *id, - char **private_key, - size_t *private_key_len) +static esp_err_t touch_key_locked(const char *id); + +/* Caller holds the stable keystore writer/read-snapshot owner. */ +static esp_err_t load_key_bytes_locked(const char *id, const char *suffix, + size_t maximum, char **bytes, size_t *length) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!id || !private_key || !private_key_len) { - return ESP_ERR_INVALID_ARG; - } - - char nvs_key[TS_KEYSTORE_ID_MAX_LEN + 8]; - make_nvs_key(nvs_key, sizeof(nvs_key), id, "_priv"); - - /* 获取长度 */ - size_t len = 0; - esp_err_t ret = nvs_get_blob(s_keystore.nvs_handle, nvs_key, NULL, &len); - if (ret != ESP_OK) { - return (ret == ESP_ERR_NVS_NOT_FOUND) ? ESP_ERR_NOT_FOUND : ret; - } - - /* 分配内存并读取 */ - char *buf = TS_MALLOC_PSRAM(len + 1); /* +1 for null terminator */ - if (!buf) { - return ESP_ERR_NO_MEM; - } - - ret = nvs_get_blob(s_keystore.nvs_handle, nvs_key, buf, &len); - if (ret != ESP_OK) { - free(buf); - return ret; - } - - buf[len] = '\0'; /* Ensure null termination for PEM string */ - *private_key = buf; - - /* - * 返回字符串长度(不含 null 终止符) - * libssh2_userauth_publickey_frommemory 期望的长度不包含 null - * 它内部会自己添加 null 并传递 len+1 给 mbedTLS - */ - *private_key_len = strlen(buf); - - /* 更新使用时间 */ - ts_keystore_touch_key(id); - - ESP_LOGI(TAG, "Loaded private key '%s' (%zu bytes)", id, *private_key_len); + *bytes = NULL; + *length = 0; + char key[TS_KEYSTORE_ID_MAX_LEN + 8]; + make_nvs_key(key, sizeof(key), id, suffix); + size_t size = 0; + esp_err_t ret = nvs_get_blob(s_keystore.nvs_handle, key, NULL, &size); + if (ret != ESP_OK) return ret == ESP_ERR_NVS_NOT_FOUND ? ESP_ERR_NOT_FOUND : ret; + if (!size || size > maximum + 1) return ESP_ERR_INVALID_SIZE; + char *buffer = TS_MALLOC_PSRAM(size + 1); + if (!buffer) return ESP_ERR_NO_MEM; + size_t actual = size; + ret = nvs_get_blob(s_keystore.nvs_handle, key, buffer, &actual); + if (ret != ESP_OK || actual != size) { + secure_free_key(buffer, size + 1); + return ret == ESP_OK ? ESP_ERR_INVALID_RESPONSE : ret; + } + buffer[size] = 0; + size_t used; + if (!key_text_length(buffer, size, maximum, &used)) { + secure_free_key(buffer, size + 1); + return ESP_ERR_INVALID_RESPONSE; + } + *bytes = buffer; + *length = used; return ESP_OK; } -esp_err_t ts_keystore_load_public_key(const char *id, - char **public_key, - size_t *public_key_len) +esp_err_t ts_keystore_load_private_key(const char *id, char **private_key, size_t *private_key_len) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!id || !public_key || !public_key_len) { - return ESP_ERR_INVALID_ARG; - } - - char nvs_key[TS_KEYSTORE_ID_MAX_LEN + 8]; - make_nvs_key(nvs_key, sizeof(nvs_key), id, "_pub"); - - /* 获取长度 */ - size_t len = 0; - esp_err_t ret = nvs_get_blob(s_keystore.nvs_handle, nvs_key, NULL, &len); - if (ret != ESP_OK) { - return (ret == ESP_ERR_NVS_NOT_FOUND) ? ESP_ERR_NOT_FOUND : ret; - } - - /* 分配内存并读取 */ - char *buf = TS_MALLOC_PSRAM(len + 1); - if (!buf) { - return ESP_ERR_NO_MEM; - } - - ret = nvs_get_blob(s_keystore.nvs_handle, nvs_key, buf, &len); - if (ret != ESP_OK) { - free(buf); - return ret; - } - - buf[len] = '\0'; - *public_key = buf; - /* 返回字符串长度(不含 null 终止符) */ - *public_key_len = strlen(buf); - - ESP_LOGI(TAG, "Loaded public key '%s' (%zu bytes)", id, *public_key_len); - return ESP_OK; + if (private_key) *private_key = NULL; + if (private_key_len) *private_key_len = 0; + if (!id || !private_key || !private_key_len) return ESP_ERR_INVALID_ARG; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = s_keystore.initialized ? load_key_bytes_locked(id, "_priv", + TS_KEYSTORE_PRIVKEY_MAX_LEN, private_key, private_key_len) : ESP_ERR_INVALID_STATE; + if (ret == ESP_OK && touch_key_locked(id) != ESP_OK) + ESP_LOGW(TAG, "Key loaded; usage timestamp was not persisted"); + xSemaphoreGive(s_keystore.write_lock); + return ret; +} + +esp_err_t ts_keystore_load_public_key(const char *id, char **public_key, size_t *public_key_len) +{ + if (public_key) *public_key = NULL; + if (public_key_len) *public_key_len = 0; + if (!id || !public_key || !public_key_len) return ESP_ERR_INVALID_ARG; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = s_keystore.initialized ? load_key_bytes_locked(id, "_pub", + TS_KEYSTORE_PUBKEY_MAX_LEN, public_key, public_key_len) : ESP_ERR_INVALID_STATE; + xSemaphoreGive(s_keystore.write_lock); + return ret; } esp_err_t ts_keystore_delete_key(const char *id) @@ -611,7 +603,7 @@ esp_err_t ts_keystore_delete_key(const char *id) xSemaphoreGive(s_keystore.write_lock); return ESP_ERR_INVALID_STATE; } - ESP_LOGI(TAG, "Deleting key '%s'", id); + ESP_LOGI(TAG, "Deleting key"); char nvs_key[TS_KEYSTORE_ID_MAX_LEN + 8]; @@ -647,230 +639,157 @@ bool ts_keystore_key_exists(const char *id) esp_err_t ts_keystore_get_key_info(const char *id, ts_keystore_key_info_t *info) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!id || !info) { - return ESP_ERR_INVALID_ARG; - } - - return load_metadata(id, info); + if (!id || !info) return ESP_ERR_INVALID_ARG; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = s_keystore.initialized ? load_metadata(id, info) : ESP_ERR_INVALID_STATE; + xSemaphoreGive(s_keystore.write_lock); + return ret; } esp_err_t ts_keystore_list_keys(ts_keystore_key_info_t *keys, size_t *count) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!keys || !count) { - return ESP_ERR_INVALID_ARG; - } - - ESP_LOGI(TAG, "Listing keys, max_count=%zu", *count); - - /* 读取索引 */ + return ts_keystore_list_keys_ex(keys, count, true); +} + +/* One complete index/metadata snapshot shares the existing writer owner. */ +static esp_err_t list_keys_locked(ts_keystore_key_info_t *keys, size_t capacity, + size_t *count, bool show_hidden) +{ + *count = 0; + if (!capacity) return ESP_OK; char index_str[MAX_INDEX_LEN] = {0}; - size_t len = sizeof(index_str); - - esp_err_t ret = nvs_get_str(s_keystore.nvs_handle, KEYSTORE_INDEX_KEY, index_str, &len); - - ESP_LOGI(TAG, "NVS read index: ret=%s, index='%s'", esp_err_to_name(ret), index_str); - if (ret == ESP_ERR_NVS_NOT_FOUND) { - *count = 0; - return ESP_OK; - } else if (ret != ESP_OK) { - return ret; - } - - /* 解析索引 */ + size_t length = sizeof(index_str); + esp_err_t result = nvs_get_str(s_keystore.nvs_handle, KEYSTORE_INDEX_KEY, index_str, &length); + if (result == ESP_ERR_NVS_NOT_FOUND) return ESP_OK; + if (result != ESP_OK) return result; char ids[TS_KEYSTORE_MAX_KEYS][TS_KEYSTORE_ID_MAX_LEN]; - int num_keys = parse_index(index_str, ids, TS_KEYSTORE_MAX_KEYS); - - ESP_LOGI(TAG, "Parsed %d keys from index", num_keys); - - /* 加载每个密钥的元数据 */ - size_t valid_count = 0; - for (int i = 0; i < num_keys && valid_count < TS_KEYSTORE_MAX_KEYS; i++) { - ESP_LOGI(TAG, "Loading metadata for key[%d]: '%s'", i, ids[i]); - if (load_metadata(ids[i], &keys[valid_count]) == ESP_OK) { - valid_count++; - } else { - ESP_LOGW(TAG, "Failed to load metadata for key '%s'", ids[i]); - } + int total = parse_index(index_str, ids, TS_KEYSTORE_MAX_KEYS); + if (total < 0) return ESP_ERR_INVALID_RESPONSE; + for (int i = 0; i < total && *count < capacity; ++i) { + ts_keystore_key_info_t item; + result = load_metadata(ids[i], &item); + if (result != ESP_OK) { *count = 0; return result; } + if (!show_hidden && item.hidden) continue; + keys[(*count)++] = item; } - - ESP_LOGI(TAG, "Returning %zu valid keys", valid_count); - *count = valid_count; return ESP_OK; } esp_err_t ts_keystore_list_keys_ex(ts_keystore_key_info_t *keys, size_t *count, bool show_hidden) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!keys || !count) { - return ESP_ERR_INVALID_ARG; - } - - ESP_LOGI(TAG, "Listing keys (show_hidden=%d), max_count=%zu", show_hidden, *count); - - /* 读取索引 */ - char index_str[MAX_INDEX_LEN] = {0}; - size_t len = sizeof(index_str); - - esp_err_t ret = nvs_get_str(s_keystore.nvs_handle, KEYSTORE_INDEX_KEY, index_str, &len); - - if (ret == ESP_ERR_NVS_NOT_FOUND) { - *count = 0; - return ESP_OK; - } else if (ret != ESP_OK) { - return ret; - } - - /* 解析索引 */ - char ids[TS_KEYSTORE_MAX_KEYS][TS_KEYSTORE_ID_MAX_LEN]; - int num_keys = parse_index(index_str, ids, TS_KEYSTORE_MAX_KEYS); - - ESP_LOGI(TAG, "Parsed %d keys from index", num_keys); - - /* 加载每个密钥的元数据,根据 show_hidden 过滤 */ - size_t valid_count = 0; - for (int i = 0; i < num_keys && valid_count < TS_KEYSTORE_MAX_KEYS; i++) { - ts_keystore_key_info_t temp_info; - if (load_metadata(ids[i], &temp_info) == ESP_OK) { - /* 如果不显示隐藏密钥,则跳过隐藏的密钥 */ - if (!show_hidden && temp_info.hidden) { - ESP_LOGD(TAG, "Skipping hidden key '%s'", ids[i]); - continue; - } - keys[valid_count] = temp_info; - valid_count++; - } else { - ESP_LOGW(TAG, "Failed to load metadata for key '%s'", ids[i]); - } - } - - ESP_LOGI(TAG, "Returning %zu valid keys (filtered)", valid_count); - *count = valid_count; - return ESP_OK; + if (!keys || !count) return ESP_ERR_INVALID_ARG; + size_t capacity = *count; + if (capacity > TS_KEYSTORE_MAX_KEYS) capacity = TS_KEYSTORE_MAX_KEYS; + *count = 0; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t result = s_keystore.initialized ? + list_keys_locked(keys, capacity, count, show_hidden) : ESP_ERR_INVALID_STATE; + xSemaphoreGive(s_keystore.write_lock); + return result; } -esp_err_t ts_keystore_touch_key(const char *id) +esp_err_t ts_keystore_read_public_record(const char *id, bool show_hidden, + ts_keystore_key_info_t *info, char **public_key, size_t *public_key_len) { - if (!s_keystore.initialized || !id) { - return ESP_ERR_INVALID_ARG; - } - + if (public_key) *public_key = NULL; + if (public_key_len) *public_key_len = 0; + if (!id || !info || (!!public_key != !!public_key_len)) return ESP_ERR_INVALID_ARG; + memset(info, 0, sizeof(*info)); + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t result = s_keystore.initialized ? load_metadata(id, info) : ESP_ERR_INVALID_STATE; + if (result == ESP_ERR_NVS_NOT_FOUND) result = ESP_ERR_NOT_FOUND; + if (result == ESP_OK && info->hidden && !show_hidden) result = ESP_ERR_NOT_FOUND; + if (result == ESP_OK && public_key) + result = load_key_bytes_locked(id, "_pub", TS_KEYSTORE_PUBKEY_MAX_LEN, public_key, public_key_len); + xSemaphoreGive(s_keystore.write_lock); + if (result != ESP_OK) memset(info, 0, sizeof(*info)); + return result; +} + +esp_err_t ts_keystore_read_exportable_private_record(const char *id, + ts_keystore_key_info_t *info, char **private_key, size_t *private_key_len) +{ + if (private_key) *private_key = NULL; + if (private_key_len) *private_key_len = 0; + if (!id || !info || !private_key || !private_key_len) return ESP_ERR_INVALID_ARG; + memset(info, 0, sizeof(*info)); + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = s_keystore.initialized ? load_metadata(id, info) : ESP_ERR_INVALID_STATE; + if (ret == ESP_ERR_NVS_NOT_FOUND) ret = ESP_ERR_NOT_FOUND; + if (ret == ESP_OK && !info->exportable) ret = ESP_ERR_NOT_ALLOWED; + if (ret == ESP_OK) + ret = load_key_bytes_locked(id, "_priv", TS_KEYSTORE_PRIVKEY_MAX_LEN, private_key, private_key_len); + xSemaphoreGive(s_keystore.write_lock); + if (ret != ESP_OK) memset(info, 0, sizeof(*info)); + return ret; +} + +static esp_err_t touch_key_locked(const char *id) +{ ts_keystore_key_info_t info; - esp_err_t ret = s_keystore.initialized ? load_metadata(id, &info) : ESP_ERR_INVALID_STATE; + esp_err_t ret = load_metadata(id, &info); if (ret == ESP_OK) { info.last_used = (uint32_t)time(NULL); ret = store_metadata(id, &info); } + return ret; +} + +esp_err_t ts_keystore_touch_key(const char *id) +{ + if (!id) return ESP_ERR_INVALID_ARG; + if (!s_keystore.write_lock) return ESP_ERR_INVALID_STATE; + xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); + esp_err_t ret = s_keystore.initialized ? touch_key_locked(id) : ESP_ERR_INVALID_STATE; xSemaphoreGive(s_keystore.write_lock); return ret; } -esp_err_t ts_keystore_import_from_file(const char *id, - const char *path, - const char *comment) +static esp_err_t read_key_file(const char *path, size_t maximum, bool optional, char **bytes, size_t *length) { - if (!s_keystore.initialized) { - return ESP_ERR_INVALID_STATE; - } - - if (!id || !path) { - return ESP_ERR_INVALID_ARG; - } - - ESP_LOGI(TAG, "Importing key from %s as '%s'", path, id); - - /* 读取私钥文件 */ - FILE *f = fopen(path, "r"); - if (!f) { - ESP_LOGE(TAG, "Cannot open private key file: %s", path); - return ESP_ERR_NOT_FOUND; - } - - fseek(f, 0, SEEK_END); - long priv_len = ftell(f); - fseek(f, 0, SEEK_SET); - - if (priv_len <= 0 || priv_len > TS_KEYSTORE_PRIVKEY_MAX_LEN) { - fclose(f); - return ESP_ERR_INVALID_SIZE; - } - - char *priv_key = TS_MALLOC_PSRAM(priv_len + 1); - if (!priv_key) { - fclose(f); - return ESP_ERR_NO_MEM; - } - - size_t read_len = fread(priv_key, 1, priv_len, f); - fclose(f); - priv_key[read_len] = '\0'; - - /* 尝试读取公钥文件 */ + *bytes = NULL; *length = 0; + FILE *file = fopen(path, "rb"); + if (!file) return optional && errno == ENOENT ? ESP_OK : errno == ENOENT ? ESP_ERR_NOT_FOUND : ESP_FAIL; + esp_err_t ret = ESP_OK; + long size = -1; + if (fseek(file, 0, SEEK_END) || (size = ftell(file)) < 0 || fseek(file, 0, SEEK_SET)) ret = ESP_FAIL; + else if ((size == 0 && !optional) || (size_t)size > maximum) ret = ESP_ERR_INVALID_SIZE; + char *buffer = ret == ESP_OK && size ? TS_MALLOC_PSRAM((size_t)size + 1) : NULL; + if (ret == ESP_OK && size && !buffer) ret = ESP_ERR_NO_MEM; + if (ret == ESP_OK && size) { + if (fread(buffer, 1, (size_t)size, file) != (size_t)size || ferror(file)) ret = ESP_FAIL; + buffer[size] = 0; + } + if (fclose(file) && ret == ESP_OK) ret = ESP_FAIL; + if (ret != ESP_OK) { secure_free_key(buffer, size > 0 ? (size_t)size + 1 : 0); return ret; } + *bytes = buffer; *length = (size_t)size; + return ESP_OK; +} + +esp_err_t ts_keystore_import_from_file(const char *id, const char *path, const char *comment) +{ + if (!s_keystore.initialized) return ESP_ERR_INVALID_STATE; + if (!valid_key_id(id) || !path) return ESP_ERR_INVALID_ARG; char pub_path[256]; - snprintf(pub_path, sizeof(pub_path), "%s.pub", path); - - char *pub_key = NULL; - size_t pub_len = 0; - - f = fopen(pub_path, "r"); - if (f) { - fseek(f, 0, SEEK_END); - pub_len = ftell(f); - fseek(f, 0, SEEK_SET); - - if (pub_len > 0 && pub_len < TS_KEYSTORE_PUBKEY_MAX_LEN) { - pub_key = TS_MALLOC_PSRAM(pub_len + 1); - if (pub_key) { - size_t read = fread(pub_key, 1, pub_len, f); - pub_key[read] = '\0'; - pub_len = read; - } - } - fclose(f); - } - - /* 检测密钥类型 */ + int path_length = snprintf(pub_path, sizeof(pub_path), "%s.pub", path); + if (path_length < 0 || (size_t)path_length >= sizeof(pub_path)) return ESP_ERR_INVALID_SIZE; + char *priv_key = NULL, *pub_key = NULL; + size_t priv_len = 0, pub_len = 0; + esp_err_t ret = read_key_file(path, TS_KEYSTORE_PRIVKEY_MAX_LEN, false, &priv_key, &priv_len); + if (ret == ESP_OK) ret = read_key_file(pub_path, TS_KEYSTORE_PUBKEY_MAX_LEN, true, &pub_key, &pub_len); + if (ret != ESP_OK) { secure_free_key(priv_key, priv_len); free(pub_key); return ret; } + /* Preserve the existing opaque import formats; no new crypto parser restriction. */ ts_keystore_key_type_t type = TS_KEYSTORE_TYPE_UNKNOWN; - if (strstr(priv_key, "BEGIN RSA PRIVATE KEY")) { - /* 需要进一步检测位数 */ - if (priv_len > 2500) { - type = TS_KEYSTORE_TYPE_RSA_4096; - } else { - type = TS_KEYSTORE_TYPE_RSA_2048; - } - } else if (strstr(priv_key, "BEGIN EC PRIVATE KEY")) { - if (priv_len > 300) { - type = TS_KEYSTORE_TYPE_ECDSA_P384; - } else { - type = TS_KEYSTORE_TYPE_ECDSA_P256; - } - } - - /* 存储密钥 */ - ts_keystore_keypair_t keypair = { - .private_key = priv_key, - .private_key_len = read_len, - .public_key = pub_key, - .public_key_len = pub_len, - }; - - esp_err_t ret = ts_keystore_store_key(id, &keypair, type, comment); - - /* 安全清零私钥内存 */ - secure_free_key(priv_key, read_len); - if (pub_key) free(pub_key); - + if (strstr(priv_key, "BEGIN RSA PRIVATE KEY")) type = priv_len > 2500 ? TS_KEYSTORE_TYPE_RSA_4096 : TS_KEYSTORE_TYPE_RSA_2048; + else if (strstr(priv_key, "BEGIN EC PRIVATE KEY")) type = priv_len > 300 ? TS_KEYSTORE_TYPE_ECDSA_P384 : TS_KEYSTORE_TYPE_ECDSA_P256; + ts_keystore_keypair_t keypair = {priv_key, priv_len, pub_key, pub_len}; + ret = ts_keystore_store_key(id, &keypair, type, comment); + secure_free_key(priv_key, priv_len); + free(pub_key); return ret; } @@ -884,7 +803,7 @@ esp_err_t ts_keystore_export_public_key_to_file(const char *id, const char *path return ESP_ERR_INVALID_ARG; } - ESP_LOGI(TAG, "Exporting public key '%s' to %s", id, path); + ESP_LOGI(TAG, "Exporting public key to file"); /* * 安全策略:只允许导出公钥,私钥永不离开安全存储 @@ -897,12 +816,12 @@ esp_err_t ts_keystore_export_public_key_to_file(const char *id, const char *path esp_err_t ret = ts_keystore_load_public_key(id, &pub_key, &pub_len); if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to load public key '%s': %s", id, esp_err_to_name(ret)); + ESP_LOGE(TAG, "Failed to load public key: %s", esp_err_to_name(ret)); return ret; } if (!pub_key || pub_len == 0) { - ESP_LOGE(TAG, "Key '%s' has no public key", id); + ESP_LOGE(TAG, "Key has no public key"); return ESP_ERR_NOT_FOUND; } @@ -911,7 +830,7 @@ esp_err_t ts_keystore_export_public_key_to_file(const char *id, const char *path free(pub_key); if (ret != ESP_OK) return ret; - ESP_LOGI(TAG, "Public key '%s' exported to %s", id, path); + ESP_LOGI(TAG, "Public key exported to file"); return ESP_OK; } @@ -936,33 +855,13 @@ esp_err_t ts_keystore_export_private_key_to_file(const char *id, const char *pat return ESP_ERR_INVALID_ARG; } - /* 检查密钥是否存在并获取元数据 */ + /* Metadata policy and private bytes are one version under the store owner. */ ts_keystore_key_info_t info; - esp_err_t ret = ts_keystore_get_key_info(id, &info); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Key '%s' not found", id); - return ESP_ERR_NOT_FOUND; - } - - /* 安全检查:只有 exportable=true 的密钥才能导出 */ - if (!info.exportable) { - ESP_LOGE(TAG, "Key '%s' is not exportable (security policy)", id); - ESP_LOGW(TAG, "To export private keys, generate with --exportable flag"); - return ESP_ERR_NOT_ALLOWED; - } - - ESP_LOGW(TAG, "Exporting private key '%s' to %s (exportable=true)", id, path); - - /* 加载私钥 */ char *priv_key = NULL; size_t priv_len = 0; - - ret = ts_keystore_load_private_key(id, &priv_key, &priv_len); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to load private key '%s': %s", id, esp_err_to_name(ret)); - return ret; - } - + esp_err_t ret = ts_keystore_read_exportable_private_record(id, &info, &priv_key, &priv_len); + if (ret != ESP_OK) return ret; + /* 写入私钥文件 */ FILE *file = NULL; ret = ts_storage_open_write(path, &file); @@ -978,7 +877,7 @@ esp_err_t ts_keystore_export_private_key_to_file(const char *id, const char *pat secure_free_key(priv_key, priv_len); if (written != priv_len || closed != 0) return ESP_FAIL; - ESP_LOGI(TAG, "Private key '%s' exported to %s", id, path); + ESP_LOGI(TAG, "Private key exported to file"); return ESP_OK; } @@ -994,7 +893,7 @@ esp_err_t ts_keystore_generate_key_with_result(const char *id, return ESP_ERR_INVALID_STATE; } - if (!id || !*id || strlen(id) > NVS_KEY_NAME_MAX_SIZE - 1 - 5 || strchr(id, ',') || type == TS_KEYSTORE_TYPE_UNKNOWN) { + if (!valid_key_id(id) || type == TS_KEYSTORE_TYPE_UNKNOWN) { return ESP_ERR_INVALID_ARG; } @@ -1004,8 +903,8 @@ esp_err_t ts_keystore_generate_key_with_result(const char *id, opts = &default_opts; } - ESP_LOGI(TAG, "Generating %s key as '%s' (exportable=%d)", - ts_keystore_type_to_string(type), id, opts->exportable); + ESP_LOGI(TAG, "Generating %s key (exportable=%d)", + ts_keystore_type_to_string(type), opts->exportable); /* 映射 keystore 类型到 crypto 类型 */ ts_crypto_key_type_t crypto_type; @@ -1026,10 +925,9 @@ esp_err_t ts_keystore_generate_key_with_result(const char *id, return ESP_ERR_INVALID_ARG; } - char old_index[MAX_INDEX_LEN]; - bool index_present; + char initial_index[MAX_INDEX_LEN]; xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); - esp_err_t ret = check_new_key(id, old_index, &index_present, detail); + esp_err_t ret = check_new_key(id, initial_index, NULL, detail); xSemaphoreGive(s_keystore.write_lock); if (ret != ESP_OK) return ret; detail->failed_stage = "generate"; @@ -1079,19 +977,8 @@ esp_err_t ts_keystore_generate_key_with_result(const char *id, .public_key_len = pub_len, }; - xSemaphoreTake(s_keystore.write_lock, portMAX_DELAY); - ret = check_new_key(id, old_index, &index_present, detail); - if (ret == ESP_OK) { - ret = store_key_locked(id, &kp, type, opts, detail); - if (ret != ESP_OK) { - bool index_attempted = strcmp(detail->failed_stage, "index_write") == 0 || - strcmp(detail->failed_stage, "commit") == 0; - detail->cleanup_error = cleanup_new_key(id, old_index, index_attempted, index_present); - detail->cleanup_complete = detail->cleanup_error == ESP_OK; - } - } - xSemaphoreGive(s_keystore.write_lock); - + ret = create_key(id, &kp, type, opts, detail); + /* 安全清零私钥内存 */ secure_free_key(priv_key, priv_len); if (pub_key) free(pub_key); diff --git a/components/ts_security/src/ts_security.c b/components/ts_security/src/ts_security.c index 40aed557..097b9230 100644 --- a/components/ts_security/src/ts_security.c +++ b/components/ts_security/src/ts_security.c @@ -17,6 +17,9 @@ #include "esp_random.h" #include "esp_timer.h" #include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" #define TAG "ts_security" #define NVS_NAMESPACE "ts_security" @@ -33,10 +36,30 @@ static nvs_handle_t s_nvs; static nvs_handle_t s_keys_nvs; static session_slot_t s_sessions[MAX_SESSIONS]; static bool s_initialized = false; +/* Volatile owners (jobs and WS clients) survive service reinitialization. Never + * recycle their identity within this boot; zero is reserved for internal work. */ +static atomic_uint_least32_t s_last_session_id = ATOMIC_VAR_INIT(0); +/* One owner for slot allocation, token issuance/comparison and revocation. + * Keep the gate across service restarts, just like the identity counter. */ +static StaticSemaphore_t s_session_gate_storage; +static SemaphoreHandle_t s_session_gate; +static bool session_lock(void) +{ + return s_session_gate && xSemaphoreTakeRecursive(s_session_gate, portMAX_DELAY) == pdTRUE; +} +static void session_unlock(void) +{ + xSemaphoreGiveRecursive(s_session_gate); +} + esp_err_t ts_security_init(void) { if (s_initialized) return ESP_OK; + if (!s_session_gate) { + s_session_gate = xSemaphoreCreateRecursiveMutexStatic(&s_session_gate_storage); + if (!s_session_gate) return ESP_ERR_NO_MEM; + } esp_err_t ret = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &s_nvs); if (ret != ESP_OK) { @@ -47,7 +70,9 @@ esp_err_t ts_security_init(void) ret = nvs_open_from_partition(TS_CONFIG_KEYS_PARTITION, NVS_NAMESPACE, NVS_READWRITE, &s_keys_nvs); if (ret != ESP_OK) { nvs_close(s_nvs); return ret; } + if (!session_lock()) { nvs_close(s_nvs); nvs_close(s_keys_nvs); return ESP_ERR_INVALID_STATE; } memset(s_sessions, 0, sizeof(s_sessions)); + session_unlock(); // 初始化 SSH 主机配置模块 ret = ts_ssh_hosts_config_init(); @@ -182,25 +207,30 @@ esp_err_t ts_security_store_cert(const char *name, ts_cert_type_t type, /** * @brief 驱逐指定 client_id 的所有会话(释放槽位) - * @note 仅内部使用,在 create_session 槽位满时按同用户驱逐 + * @note 密码成功更新时撤销目标账户,也用于槽位满时按同用户驱逐 */ -static void destroy_sessions_by_client(const char *client_id) +static void ts_security_destroy_sessions_by_client_locked(const char *client_id) { if (!client_id || client_id[0] == '\0') return; for (int i = 0; i < MAX_SESSIONS; i++) { if (s_sessions[i].active && strcmp(s_sessions[i].session.client_id, client_id) == 0) { s_sessions[i].active = false; - TS_LOGI(TAG, "Evicted session for client: %s", client_id); } } } -esp_err_t ts_security_create_session(const char *client_id, ts_perm_level_t level, +static esp_err_t ts_security_create_session_locked(const char *client_id, ts_perm_level_t level, uint32_t *session_id) { if (!session_id) return ESP_ERR_INVALID_ARG; + uint_least32_t previous = atomic_load(&s_last_session_id); + do { + if (previous >= UINT32_MAX) return ESP_ERR_INVALID_STATE; + } while (!atomic_compare_exchange_weak(&s_last_session_id, &previous, previous + 1)); + uint32_t sid = (uint32_t)previous + 1; + // Find free slot int slot = -1; for (int i = 0; i < MAX_SESSIONS; i++) { @@ -212,7 +242,7 @@ esp_err_t ts_security_create_session(const char *client_id, ts_perm_level_t leve if (slot < 0) { if (client_id && client_id[0] != '\0') { - destroy_sessions_by_client(client_id); + ts_security_destroy_sessions_by_client(client_id); for (int i = 0; i < MAX_SESSIONS; i++) { if (!s_sessions[i].active) { slot = i; @@ -221,15 +251,10 @@ esp_err_t ts_security_create_session(const char *client_id, ts_perm_level_t leve } } if (slot < 0) { - TS_LOGW(TAG, "No free session slots"); return ESP_ERR_NO_MEM; } } - // Generate session ID - uint32_t sid; - ts_security_random(&sid, sizeof(sid)); - uint32_t now = esp_timer_get_time() / 1000000; memset(&s_sessions[slot], 0, sizeof(s_sessions[slot])); @@ -249,11 +274,10 @@ esp_err_t ts_security_create_session(const char *client_id, ts_perm_level_t leve } *session_id = sid; - TS_LOGI(TAG, "Session created"); return ESP_OK; } -esp_err_t ts_security_validate_session(uint32_t session_id, ts_session_t *session) +static esp_err_t ts_security_validate_session_locked(uint32_t session_id, ts_session_t *session) { uint32_t now = esp_timer_get_time() / 1000000; @@ -273,12 +297,11 @@ esp_err_t ts_security_validate_session(uint32_t session_id, ts_session_t *sessio return ESP_ERR_NOT_FOUND; } -esp_err_t ts_security_destroy_session(uint32_t session_id) +static esp_err_t ts_security_destroy_session_locked(uint32_t session_id) { for (int i = 0; i < MAX_SESSIONS; i++) { if (s_sessions[i].active && s_sessions[i].session.session_id == session_id) { s_sessions[i].active = false; - TS_LOGI(TAG, "Session destroyed"); return ESP_OK; } } @@ -294,7 +317,7 @@ bool ts_security_check_permission(uint32_t session_id, ts_perm_level_t required) return session.level >= required; } -esp_err_t ts_security_generate_token(uint32_t session_id, char *token, size_t max_len) +static esp_err_t ts_security_generate_token_locked(uint32_t session_id, char *token, size_t max_len) { if (!token || max_len < 64) return ESP_ERR_INVALID_ARG; @@ -303,12 +326,11 @@ esp_err_t ts_security_generate_token(uint32_t session_id, char *token, size_t ma for (int i = 0; i < MAX_SESSIONS; i++) { if (s_sessions[i].active && s_sessions[i].session.session_id == session_id) { - // Keep the existing wire format and bind it to the issued credential. + // Keep the 16-byte Base64 wire length, with all bytes random. + // The session identity and uptime are metadata, never bearer entropy. uint8_t data[16]; - memcpy(data, &session_id, 4); - ts_security_random(data + 4, 8); - uint32_t ts = esp_timer_get_time() / 1000; - memcpy(data + 12, &ts, 4); + ret = ts_security_random(data, sizeof(data)); + if (ret != ESP_OK) return ret; size_t out_len = max_len; ret = ts_crypto_base64_encode(data, sizeof(data), token, &out_len); @@ -322,7 +344,7 @@ esp_err_t ts_security_generate_token(uint32_t session_id, char *token, size_t ma return ESP_ERR_NOT_FOUND; } -esp_err_t ts_security_validate_token(const char *token, uint32_t *session_id) +static esp_err_t ts_security_validate_token_locked(const char *token, uint32_t *session_id) { if (!token || !session_id) return ESP_ERR_INVALID_ARG; @@ -332,23 +354,70 @@ esp_err_t ts_security_validate_token(const char *token, uint32_t *session_id) esp_err_t ret = ts_crypto_base64_decode(token, strlen(token), data, &data_len); if (ret != ESP_OK || data_len != sizeof(data)) return ESP_ERR_INVALID_ARG; - uint32_t sid; - memcpy(&sid, data, 4); - - ret = ts_security_validate_session(sid, NULL); - if (ret != ESP_OK) return ret; - for (int i = 0; i < MAX_SESSIONS; i++) { - if (s_sessions[i].active && s_sessions[i].session.session_id == sid && - s_sessions[i].token_issued) { + if (s_sessions[i].active && s_sessions[i].token_issued) { uint8_t diff = 0; for (size_t j = 0; j < sizeof(data); j++) { diff |= data[j] ^ s_sessions[i].token_data[j]; } - if (diff != 0) return ESP_ERR_INVALID_ARG; + if (diff != 0) continue; + uint32_t sid = s_sessions[i].session.session_id; + ret = ts_security_validate_session(sid, NULL); + if (ret != ESP_OK) return ret; *session_id = sid; return ESP_OK; } } return ESP_ERR_NOT_FOUND; } + +/* Public entry points serialize every access to the shared session slots. */ +void ts_security_destroy_sessions_by_client(const char *client_id) +{ + if (!session_lock()) return; + ts_security_destroy_sessions_by_client_locked(client_id); + session_unlock(); +} + +esp_err_t ts_security_create_session(const char *client_id, ts_perm_level_t level, uint32_t *session_id) +{ + if (!session_lock()) return ESP_ERR_INVALID_STATE; + esp_err_t ret = ts_security_create_session_locked(client_id, level, session_id); + session_unlock(); + if (ret == ESP_OK) TS_LOGI(TAG, "Session created"); + if (ret == ESP_ERR_NO_MEM) TS_LOGW(TAG, "No free session slots"); + return ret; +} + +esp_err_t ts_security_validate_session(uint32_t session_id, ts_session_t *session) +{ + if (!session_lock()) return ESP_ERR_INVALID_STATE; + esp_err_t ret = ts_security_validate_session_locked(session_id, session); + session_unlock(); + return ret; +} + +esp_err_t ts_security_destroy_session(uint32_t session_id) +{ + if (!session_lock()) return ESP_ERR_INVALID_STATE; + esp_err_t ret = ts_security_destroy_session_locked(session_id); + session_unlock(); + if (ret == ESP_OK) TS_LOGI(TAG, "Session destroyed"); + return ret; +} + +esp_err_t ts_security_generate_token(uint32_t session_id, char *token, size_t max_len) +{ + if (!session_lock()) return ESP_ERR_INVALID_STATE; + esp_err_t ret = ts_security_generate_token_locked(session_id, token, max_len); + session_unlock(); + return ret; +} + +esp_err_t ts_security_validate_token(const char *token, uint32_t *session_id) +{ + if (!session_lock()) return ESP_ERR_INVALID_STATE; + esp_err_t ret = ts_security_validate_token_locked(token, session_id); + session_unlock(); + return ret; +} diff --git a/components/ts_storage/CMakeLists.txt b/components/ts_storage/CMakeLists.txt index 43bdb97a..4e0014b6 100644 --- a/components/ts_storage/CMakeLists.txt +++ b/components/ts_storage/CMakeLists.txt @@ -2,6 +2,7 @@ set(TS_STORAGE_SRCS "src/ts_storage.c" + "src/ts_file_store.c" "src/ts_storage_spiffs.c" "src/ts_storage_sd.c" "src/ts_storage_auto.c" @@ -12,5 +13,5 @@ idf_component_register( SRCS ${TS_STORAGE_SRCS} INCLUDE_DIRS "include" REQUIRES ts_core fatfs spiffs vfs - PRIV_REQUIRES driver sdmmc ts_event + PRIV_REQUIRES driver sdmmc ts_event esp_hw_support ) diff --git a/components/ts_storage/include/ts_file_store.h b/components/ts_storage/include/ts_file_store.h new file mode 100644 index 00000000..164f39e8 --- /dev/null +++ b/components/ts_storage/include/ts_file_store.h @@ -0,0 +1,29 @@ +#pragma once +#include "esp_err.h" +#include +#include + +/* Trusted C file owners only. Callers hold their writer/mount gate and own + * all three paths on the same filesystem. No JSON caller supplies these paths. + * FAT/SPIFFS rename does not overwrite an existing destination. */ +typedef struct { + const char *current, *pending, *previous; +} ts_file_store_paths_t; +typedef esp_err_t (*ts_file_store_validate_t)(const char *path, void *context); + +typedef enum { + TS_FILE_STORE_FIXED, /* Owner's fixed paths: recover an interrupted save. */ + TS_FILE_STORE_FRESH /* New unused sidecars: never delete preexisting data. */ +} ts_file_store_mode_t; + +/* Recovery restores an old file instead of publishing an uncommitted pending + * file. NOT_FINISHED preserves uncertain evidence. Filesystem power-loss + * atomicity is not promised by this protocol. */ +esp_err_t ts_file_store_recover(const ts_file_store_paths_t *paths, bool writing, + ts_file_store_validate_t validate, void *context); +/* Complete bytes are flushed, synced, closed and read back before promotion. + * OK means the new target was observed installed, even if old cleanup failed. + * NOT_FINISHED means inspect the retained paths before retrying. */ +esp_err_t ts_file_store_replace(const ts_file_store_paths_t *paths, + const void *bytes, size_t length, ts_file_store_mode_t mode, + ts_file_store_validate_t validate, void *context); diff --git a/components/ts_storage/include/ts_storage.h b/components/ts_storage/include/ts_storage.h index 09812496..7a7b3f2f 100644 --- a/components/ts_storage/include/ts_storage.h +++ b/components/ts_storage/include/ts_storage.h @@ -325,16 +325,31 @@ ssize_t ts_storage_read_file(const char *path, void *buf, size_t max_size); */ char *ts_storage_read_string(const char *path); -/* Generic file mutations cannot replace the automation owner's files or roots. +/* Generic file mutations cannot replace the WWW code volume or automation + * owner's files or roots. * include_children also checks directory moves/removals of their parents. */ esp_err_t ts_storage_check_write_path(const char *path, bool include_children); +/* External generic mutations are SD data operations, never WWW/SPIFFS/other + * VFS mounts. Compose this boundary with the managed configuration owner guard; + * trusted internal persistence continues to use check_write_path directly. */ +esp_err_t ts_storage_check_external_write_path(const char *path, bool include_children); + +/* Ordinary SD reads need a session; config/PKI and internal mounts need Root. + * Unknown mounts, malformed paths and unresolved FAT metadata errors refuse. */ +esp_err_t ts_storage_external_read_requires_admin(const char *path, bool *requires_admin); + /* Open a streamed download destination under the same ownership check. * The caller writes/closes the stream; network transfer does not hold the SD gate. */ esp_err_t ts_storage_open_write(const char *path, FILE **file); /** Write a complete buffer to a file. */ esp_err_t ts_storage_write_file(const char *path, const void *data, size_t size); +/* Replace ordinary SD data using fresh sibling sidecars. The old target is not + * truncated on preparation failure. An uncertain rename retains sidecars for + * explicit recovery; cleanup failure after commit still reports success. */ +esp_err_t ts_storage_replace_file(const char *path, const void *data, size_t size); + /** * @brief Write string to file diff --git a/components/ts_storage/src/ts_file_store.c b/components/ts_storage/src/ts_file_store.c new file mode 100644 index 00000000..6eb1d81b --- /dev/null +++ b/components/ts_storage/src/ts_file_store.c @@ -0,0 +1,131 @@ +#include "ts_file_store.h" +#include "esp_log.h" +#include +#include +#include +#include +#include + +static const char *store_tag = "file_store"; + +static esp_err_t store_io_error(void) +{ + return errno == ENOSPC ? ESP_ERR_INVALID_SIZE : ESP_FAIL; +} + +static int store_file_state(const char *path) +{ + struct stat st; + if (stat(path, &st) == 0) return S_ISREG(st.st_mode) ? 1 : -1; + return errno == ENOENT ? 0 : -1; +} + +static bool store_remove(const char *path) +{ + return unlink(path) == 0 || errno == ENOENT; +} + +static esp_err_t store_matches(const char *path, const void *bytes, size_t length) +{ + FILE *file = fopen(path, "rb"); + if (!file) return errno == ENOENT ? ESP_ERR_NOT_FOUND : store_io_error(); + unsigned char chunk[1024]; + size_t position = 0; + esp_err_t ret = ESP_OK; + while (position < length) { + size_t count = length - position; + if (count > sizeof(chunk)) count = sizeof(chunk); + size_t got = fread(chunk, 1, count, file); + if (got != count || memcmp(chunk, (const unsigned char *)bytes + position, count)) { + ret = ESP_FAIL; + break; + } + position += count; + } + if (ret == ESP_OK && (fgetc(file) != EOF || ferror(file))) ret = ESP_FAIL; + if (fclose(file) != 0 && ret == ESP_OK) ret = store_io_error(); + return ret; +} + +static esp_err_t store_prepare(const char *path, const void *bytes, size_t length, bool *created) +{ + /* Recovery/selection established that the pending name is unused. Never + * truncate a racing or unrelated file which acquired that name meanwhile. */ + *created = false; + FILE *file = fopen(path, "wbx"); + if (!file) return store_io_error(); + *created = true; + esp_err_t ret = !length || fwrite(bytes, 1, length, file) == length ? ESP_OK : store_io_error(); + if (fflush(file) != 0 && ret == ESP_OK) ret = store_io_error(); + if (fsync(fileno(file)) != 0 && ret == ESP_OK) ret = store_io_error(); + if (fclose(file) != 0 && ret == ESP_OK) ret = store_io_error(); + return ret == ESP_OK ? store_matches(path, bytes, length) : ret; +} + +esp_err_t ts_file_store_recover(const ts_file_store_paths_t *p, bool writing, + ts_file_store_validate_t validate, void *context) +{ + int current = store_file_state(p->current), pending = store_file_state(p->pending); + int previous = store_file_state(p->previous); + if (current < 0 || pending < 0 || previous < 0) return ESP_ERR_NOT_FINISHED; + if (pending) { + if (previous) { + if (current || rename(p->previous, p->current) != 0) return ESP_ERR_NOT_FINISHED; + } + return store_remove(p->pending) ? ESP_OK : ESP_FAIL; + } + if (!previous) return ESP_OK; + if (!current) + return rename(p->previous, p->current) == 0 ? ESP_OK : ESP_ERR_NOT_FINISHED; + if (validate && validate(p->current, context) != ESP_OK) return ESP_ERR_NOT_FINISHED; + if (!store_remove(p->previous)) { + ESP_LOGW(store_tag, "Committed file retained its previous copy"); + return writing ? ESP_FAIL : ESP_OK; + } + return ESP_OK; +} + +esp_err_t ts_file_store_replace(const ts_file_store_paths_t *p, + const void *bytes, size_t length, ts_file_store_mode_t mode, + ts_file_store_validate_t validate, void *context) +{ + if (!p || !p->current || !p->pending || !p->previous || (!bytes && length)) + return ESP_ERR_INVALID_ARG; + esp_err_t ret; + if (mode == TS_FILE_STORE_FIXED) { + ret = ts_file_store_recover(p, true, validate, context); + } else if (mode == TS_FILE_STORE_FRESH) { + ret = store_file_state(p->pending) == 0 && store_file_state(p->previous) == 0 + ? ESP_OK : ESP_ERR_NOT_FINISHED; + } else return ESP_ERR_INVALID_ARG; + if (ret != ESP_OK) return ret; + int current = store_file_state(p->current); + if (current < 0) return ESP_ERR_NOT_FINISHED; + bool created; + ret = store_prepare(p->pending, bytes, length, &created); + if (ret != ESP_OK) { + if (!created) return ret; /* Never clean up a failed exclusive open. */ + goto uncommitted; + } + if (current && rename(p->current, p->previous) != 0) { + ret = store_io_error(); + goto uncommitted; + } + if (rename(p->pending, p->current) != 0) { + ret = store_io_error(); + /* A driver may report an error after taking effect. Compare actual + * installed bytes before reporting failure or attempting rollback. */ + int pending = store_file_state(p->pending); + esp_err_t observed = store_matches(p->current, bytes, length); + if (!(pending == 0 && observed == ESP_OK)) { + if (pending != 1 || (observed != ESP_ERR_NOT_FOUND && observed != ESP_OK)) + return ESP_ERR_NOT_FINISHED; + goto uncommitted; + } + } + if (current && !store_remove(p->previous)) + ESP_LOGW(store_tag, "Committed file retained its previous copy"); + return ESP_OK; +uncommitted: + return ts_file_store_recover(p, false, validate, context) == ESP_OK ? ret : ESP_ERR_NOT_FINISHED; +} diff --git a/components/ts_storage/src/ts_storage.c b/components/ts_storage/src/ts_storage.c index 787698c7..f632bafc 100644 --- a/components/ts_storage/src/ts_storage.c +++ b/components/ts_storage/src/ts_storage.c @@ -8,6 +8,8 @@ */ #include "ts_storage.h" +#include "ts_file_store.h" +#include "esp_random.h" #include "ts_log.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" @@ -24,6 +26,8 @@ #define TAG "ts_storage" +extern esp_err_t ts_storage_sd_resolve_name(const char *path, char *name, size_t capacity); + /*===========================================================================*/ /* Private Data */ /*===========================================================================*/ @@ -241,6 +245,60 @@ esp_err_t ts_storage_write_file(const char *path, const void *data, size_t size) ts_storage_sd_unlock();return ret; } +esp_err_t ts_storage_replace_file(const char *path, const void *data, size_t size) +{ + if (!data && size) return ESP_ERR_INVALID_ARG; + /* SPIFFS has short object names; use its original direct writer instead of + * FAT staging suffixes, which can make valid SPIFFS names unusable. */ + if (path && (strncmp(path, "/spiffs/", 8) == 0 || strncmp(path, "/www/", 5) == 0)) { + esp_err_t checked = ts_storage_check_external_write_path(path, false); + return checked == ESP_OK ? ts_storage_write_file(path, data, size) : checked; + } + ts_storage_sd_lock(); + esp_err_t ret = ts_storage_check_external_write_path(path, false); + if (ret != ESP_OK) goto done; + /* Preserve the real long filename when a caller used a FAT short alias. + * Only the final component is renamed; parent aliases remain equivalent. */ + char current[2 * TS_STORAGE_MAX_PATH], leaf[TS_STORAGE_MAX_PATH]; + const char *target = path; + ret = !strncmp(path, "/sdcard/", 8) ? + ts_storage_sd_resolve_name(path, leaf, sizeof(leaf)) : ESP_ERR_NOT_FOUND; + if (ret == ESP_OK) { + const char *separator = strrchr(path, '/'), *backslash = strrchr(path, '\\'); + if (backslash && backslash > separator) separator = backslash; + size_t parent = (size_t)(separator + 1 - path); + int length = snprintf(current, sizeof(current), "%.*s%s", (int)parent, path, leaf); + if (length < 0 || (size_t)length >= sizeof(current)) { + ret = ESP_ERR_INVALID_SIZE; + goto done; + } + target = current; + } else if (ret != ESP_ERR_NOT_FOUND) goto done; + /* Eight ASCII suffix bytes still fit the 255-character FAT component + * limit for every target accepted by our 256-byte /sdcard path contract. + * The actual newlib/VFS path buffer is larger than this internal path. */ + char pending[TS_STORAGE_MAX_PATH + 8], previous[TS_STORAGE_MAX_PATH + 8]; + ret = ESP_ERR_NOT_FINISHED; + for (unsigned attempt = 0; attempt < 8; ++attempt) { + unsigned long nonce = esp_random() & 0xffffffU; + snprintf(pending, sizeof(pending), "%s.n%06lx", path, nonce); + snprintf(previous, sizeof(previous), "%s.o%06lx", path, nonce); + struct stat st; + if (stat(pending, &st) == 0) continue; + if (errno != ENOENT) goto done; + if (stat(previous, &st) == 0) continue; + if (errno != ENOENT) goto done; + ts_file_store_paths_t paths = {target, pending, previous}; + ret = ts_file_store_replace(&paths, data, size, TS_FILE_STORE_FRESH, NULL, NULL); + if (ret == ESP_ERR_NOT_FINISHED) + TS_LOGE(TAG, "File replacement requires recovery"); + break; + } +done: + ts_storage_sd_unlock(); + return ret; +} + esp_err_t ts_storage_write_string(const char *path, const char *str) { if (str == NULL) { diff --git a/components/ts_storage/src/ts_storage_paths.c b/components/ts_storage/src/ts_storage_paths.c index ffbc88c1..9cb4fb02 100644 --- a/components/ts_storage/src/ts_storage_paths.c +++ b/components/ts_storage/src/ts_storage_paths.c @@ -4,37 +4,27 @@ #include /* FatFs resolves its own short names and Unicode case equivalents. */ -extern bool ts_storage_sd_name_is(const char *path, const char *name); +extern esp_err_t ts_storage_sd_resolve_name(const char *path, char *name, size_t capacity); -static bool directory_is(const char *path, const char *expected) +static esp_err_t directory_is(const char *path, const char *expected, bool *matches) { const char *name = strrchr(expected, '/') + 1; const char *component = strrchr(path, '/') + 1; - return !strcasecmp(component, name) || ts_storage_sd_name_is(path, name); + if (!strcasecmp(component, name)) { *matches = true; return ESP_OK; } + char resolved[TS_STORAGE_MAX_PATH]; + esp_err_t ret = ts_storage_sd_resolve_name(path, resolved, sizeof(resolved)); + if (ret != ESP_OK && ret != ESP_ERR_NOT_FOUND) return ret; + *matches = ret == ESP_OK && !strcasecmp(resolved, name); + return ESP_OK; } -esp_err_t ts_storage_check_write_path(const char *path, bool include_children) +static esp_err_t normalize_sd_suffix(const char *at, char normalized[TS_STORAGE_MAX_PATH]) { - if (!path || path[0] != '/' || strlen(path) >= TS_STORAGE_MAX_PATH) return ESP_ERR_INVALID_ARG; - for (const unsigned char *p = (const unsigned char *)path; *p; ++p) { - /* FatFs treats a control character as the end of the path. */ - if (*p < ' ' || *p == 0x7f) return ESP_ERR_INVALID_ARG; - } - const char *at = path; - while (*at == '/') ++at; - const char *end = strchr(at, '/'); - size_t mount = end ? (size_t)(end - at) : strlen(at); - if (!mount) return include_children ? ESP_ERR_NOT_ALLOWED : ESP_OK; - if (mount == strlen(&TS_CONFIG_AUTO_MOUNT[1]) && !strncmp(at, &TS_CONFIG_AUTO_MOUNT[1], mount)) { - return ESP_ERR_NOT_ALLOWED; - } - if (mount != 6 || strncmp(at, "sdcard", 6)) return ESP_OK; - /* Normalize within the VFS mount. Both separators and trailing dots/spaces * have FAT semantics; '..' cannot change which VFS mount owns this path. */ - char normalized[TS_STORAGE_MAX_PATH] = "/sdcard"; + strcpy(normalized, "/sdcard"); size_t used = 7; - at = end ? end : at + mount; + const char *end; while (*at) { while (*at == '/' || *at == '\\') ++at; if (!*at) break; @@ -57,14 +47,93 @@ esp_err_t ts_storage_check_write_path(const char *path, bool include_children) } at = end; } + return ESP_OK; +} + +esp_err_t ts_storage_check_write_path(const char *path, bool include_children) +{ + if (!path || path[0] != '/' || strlen(path) >= TS_STORAGE_MAX_PATH) return ESP_ERR_INVALID_ARG; + for (const unsigned char *p = (const unsigned char *)path; *p; ++p) { + /* FatFs treats a control character as the end of the path. */ + if (*p < ' ' || *p == 0x7f) return ESP_ERR_INVALID_ARG; + } + const char *at = path; + while (*at == '/') ++at; + const char *end = strchr(at, '/'); + size_t mount = end ? (size_t)(end - at) : strlen(at); + if (!mount) return include_children ? ESP_ERR_NOT_ALLOWED : ESP_OK; + if (mount == strlen(&TS_CONFIG_AUTO_MOUNT[1]) && !strncmp(at, &TS_CONFIG_AUTO_MOUNT[1], mount)) { + return ESP_ERR_NOT_ALLOWED; + } + if (mount != 6 || strncmp(at, "sdcard", 6)) return ESP_OK; + + char normalized[TS_STORAGE_MAX_PATH]; + esp_err_t ret = normalize_sd_suffix(end ? end : at + mount, normalized); + if (ret != ESP_OK) return ret; + size_t used = strlen(normalized); if (used == 7) return include_children ? ESP_ERR_NOT_ALLOWED : ESP_OK; + /* Preserve the existing automation configuration owner through the + * same FAT case/short-name owner check, including recursive parent removal. */ + const char *owned[][2] = { + {TS_CONFIG_AUTO_SD_PARENT, TS_CONFIG_AUTO_SD_DIR}, + }; char *parent_end = strchr(normalized + 8, '/'); - if (parent_end) *parent_end = 0; - bool config_parent = directory_is(normalized, TS_CONFIG_AUTO_SD_PARENT); - if (parent_end) *parent_end = '/'; - if (!config_parent) return ESP_OK; - if (!parent_end) return include_children ? ESP_ERR_NOT_ALLOWED : ESP_OK; - char *directory_end = strchr(parent_end + 1, '/'); - if (directory_end) *directory_end = 0; - return directory_is(normalized, TS_CONFIG_AUTO_SD_DIR) ? ESP_ERR_NOT_ALLOWED : ESP_OK; + for (size_t i = 0; i < sizeof(owned) / sizeof(owned[0]); ++i) { + if (parent_end) *parent_end = 0; + bool parent_matches; + ret = directory_is(normalized, owned[i][0], &parent_matches); + if (parent_end) *parent_end = '/'; + if (ret != ESP_OK) return ret; + if (!parent_matches) continue; + if (!parent_end) return include_children ? ESP_ERR_NOT_ALLOWED : ESP_OK; + char *directory_end = strchr(parent_end + 1, '/'); + if (directory_end) *directory_end = 0; + bool directory_matches; + ret = directory_is(normalized, owned[i][1], &directory_matches); + if (directory_end) *directory_end = '/'; + if (ret != ESP_OK) return ret; + if (directory_matches) return ESP_ERR_NOT_ALLOWED; + } + return ESP_OK; +} + +/* VFS selects the mount before FAT interprets its path. Do not turn the + * internal owner guard into a global SD-only restriction. */ +esp_err_t ts_storage_check_external_write_path(const char *path, bool include_children) +{ + if (!path || !((!strncmp(path, "/sdcard/", 8) && path[8]) || + (!strncmp(path, "/spiffs/", 8) && path[8]) || + (!strncmp(path, "/www/", 5) && path[5]))) return ESP_ERR_INVALID_ARG; + return ts_storage_check_write_path(path, include_children); +} + +/* Private roots are checked after FAT normalization/resolution. Metadata errors + * fail closed: a failed alias lookup never turns a private path into SD data. */ +esp_err_t ts_storage_external_read_requires_admin(const char *path, bool *requires_admin) +{ + if (!requires_admin) return ESP_ERR_INVALID_ARG; + *requires_admin = true; + if (!path || path[0] != '/' || strlen(path) >= TS_STORAGE_MAX_PATH) return ESP_ERR_INVALID_ARG; + for (const unsigned char *p = (const unsigned char *)path; *p; ++p) { + if (*p < ' ' || *p == 0x7f) return ESP_ERR_INVALID_ARG; + } + const char *private_mounts[] = {"/spiffs", "/www", TS_CONFIG_AUTO_MOUNT}; + for (size_t i = 0; i < sizeof(private_mounts) / sizeof(private_mounts[0]); ++i) { + size_t length = strlen(private_mounts[i]); + if (!strncmp(path, private_mounts[i], length) && (!path[length] || path[length] == '/')) return ESP_OK; + } + if (strncmp(path, "/sdcard", 7) || (path[7] && path[7] != '/')) return ESP_ERR_INVALID_ARG; + char normalized[TS_STORAGE_MAX_PATH]; + esp_err_t ret = normalize_sd_suffix(path + 7, normalized); + if (ret != ESP_OK) return ret; + if (!strcmp(normalized, "/sdcard")) { *requires_admin = false; return ESP_OK; } + char *end = strchr(normalized + 8, '/'); + if (end) *end = 0; + const char *name = normalized + 8; + if (!strcasecmp(name, "config") || !strcasecmp(name, "pki")) return ESP_OK; + char resolved[TS_STORAGE_MAX_PATH]; + ret = ts_storage_sd_resolve_name(normalized, resolved, sizeof(resolved)); + if (ret != ESP_OK && ret != ESP_ERR_NOT_FOUND) return ret; + *requires_admin = ret == ESP_OK && (!strcasecmp(resolved, "config") || !strcasecmp(resolved, "pki")); + return ESP_OK; } diff --git a/components/ts_storage/src/ts_storage_sd.c b/components/ts_storage/src/ts_storage_sd.c index b7e55392..47baf99b 100644 --- a/components/ts_storage/src/ts_storage_sd.c +++ b/components/ts_storage/src/ts_storage_sd.c @@ -482,21 +482,30 @@ esp_err_t ts_storage_sd_refresh(void) ts_storage_sd_unlock();return ret; } -/* Compare the resolved directory name, including FAT aliases/case rules. */ -bool ts_storage_sd_name_is(const char *path, const char *name) +/* Resolve the actual FAT name; distinguish absence from I/O/driver failure. */ +esp_err_t ts_storage_sd_resolve_name(const char *path, char *name, size_t capacity) { + if (!path || !name || !capacity) return ESP_ERR_INVALID_ARG; ts_storage_sd_lock(); - bool matches = false; + esp_err_t ret = ESP_FAIL; size_t mount_length = strlen(s_mount_point); if (s_card && mount_length && !strncmp(path, s_mount_point, mount_length) && path[mount_length] == '/') { BYTE drive = ff_diskio_get_pdrv_card(s_card); FILINFO info; char fat_path[TS_STORAGE_MAX_PATH]; if (drive != 0xff) { - snprintf(fat_path, sizeof(fat_path), "%u:%s", drive, path + mount_length); - matches = f_stat(fat_path, &info) == FR_OK && !strcasecmp(info.fname, name); + int length = snprintf(fat_path, sizeof(fat_path), "%u:%s", drive, path + mount_length); + if (length >= 0 && (size_t)length < sizeof(fat_path)) { + FRESULT result = f_stat(fat_path, &info); + if (result == FR_OK && strlen(info.fname) < capacity) { + strcpy(name, info.fname); + ret = ESP_OK; + } else if (result == FR_NO_FILE || result == FR_NO_PATH) { + ret = ESP_ERR_NOT_FOUND; + } + } } } ts_storage_sd_unlock(); - return matches; + return ret; } diff --git a/components/ts_webui/Kconfig b/components/ts_webui/Kconfig index 4fc21a2a..66d2f797 100644 --- a/components/ts_webui/Kconfig +++ b/components/ts_webui/Kconfig @@ -38,9 +38,4 @@ menu "TianShanOS WebUI Configuration" default y depends on TS_WEBUI_ENABLE - config TS_WEBUI_STATIC_PATH - string "Static Files Path" - default "/www" - depends on TS_WEBUI_ENABLE - endmenu diff --git a/components/ts_webui/include/ts_webui.h b/components/ts_webui/include/ts_webui.h index db289c74..dc5b505e 100644 --- a/components/ts_webui/include/ts_webui.h +++ b/components/ts_webui/include/ts_webui.h @@ -71,6 +71,7 @@ typedef enum { typedef struct { char boot_id[33], result_key[33]; } ts_webui_ssh_receipt_t; typedef struct { ts_webui_ssh_receipt_t *receipt; /**< Private query capability, returned only to the initiating request. */ + uint32_t owner_session_id; /**< Trusted C caller identity; zero denotes internal work. */ const char *expect_pattern; /**< 期望匹配的模式(简单字符串包含检查)*/ const char *fail_pattern; /**< 失败模式(匹配则视为失败)*/ const char *extract_pattern; /**< 提取模式,格式: "prefix(capture)suffix" */ @@ -145,8 +146,14 @@ esp_err_t ts_webui_ssh_exec_start_ex(const char *host, uint16_t port, * @return esp_err_t ESP_OK on success */ esp_err_t ts_webui_ssh_exec_cancel(uint32_t session_id); + +/** Unbound control requires the private receipt. The authenticated initiating + * session may omit both receipt fields when cancelling its own active job. */ +esp_err_t ts_webui_ssh_exec_cancel_with_receipt(uint32_t session_id, const char *boot_id, const char *result_key); +esp_err_t ts_webui_ssh_exec_cancel_for_session(uint32_t session_id, const char *boot_id, const char *result_key, uint32_t caller_session_id); /* Authenticated API also requires the initiating request's unbroadcast capability. */ char *ts_webui_ssh_exec_status(uint32_t id, const char *boot_id, const char *result_key, esp_err_t *error); +char *ts_webui_ssh_exec_status_for_session(uint32_t session_id, const char *boot_id, const char *result_key, uint32_t caller_session_id, esp_err_t *error); /** * @brief Check if SSH exec session is running diff --git a/components/ts_webui/include/ts_ws_operation.h b/components/ts_webui/include/ts_ws_operation.h index 0becf5d8..80260df0 100644 --- a/components/ts_webui/include/ts_ws_operation.h +++ b/components/ts_webui/include/ts_ws_operation.h @@ -21,6 +21,8 @@ void ts_ws_op_enable(void); void ts_ws_op_stop_admission(void); bool ts_ws_op_busy(void); ts_ws_operation_t *ts_ws_op_create(ts_ws_op_kind_t kind, ts_ws_peer_t peer, esp_err_t *error); +/* Trusted creator, before open/task start. Zero means internal/no raw observers. */ +void ts_ws_op_set_exec_owner(ts_ws_operation_t *op, uint32_t session_id); void ts_ws_op_bind(ts_ws_operation_t *op, void *data, void (*destroy)(void *)); void *ts_ws_op_data(ts_ws_operation_t *op); /* caller owns a reference */ uint32_t ts_ws_op_id(ts_ws_operation_t *op); diff --git a/components/ts_webui/include/ts_ws_transport.h b/components/ts_webui/include/ts_ws_transport.h index 2baaae88..b0f44edb 100644 --- a/components/ts_webui/include/ts_ws_transport.h +++ b/components/ts_webui/include/ts_ws_transport.h @@ -44,11 +44,15 @@ bool ts_ws_peer_get(httpd_handle_t server, int fd, ts_ws_peer_t *peer); bool ts_ws_peer_equal(ts_ws_peer_t a, ts_ws_peer_t b); esp_err_t ts_ws_peer_bind_session(ts_ws_peer_t peer, uint32_t session_id); bool ts_ws_peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required); +bool ts_ws_peer_authorized_for_session(ts_ws_peer_t peer, ts_perm_level_t required, uint32_t session_id); +unsigned ts_ws_peer_snapshot_for_session(ts_ws_peer_t *peers, unsigned capacity, ts_perm_level_t required, uint32_t session_id); unsigned ts_ws_peer_snapshot_for_level(ts_ws_peer_t *peers, unsigned capacity, ts_perm_level_t required); unsigned ts_ws_transport_capacity(void); ts_ws_message_t *ts_ws_message_json(const char *topic, const cJSON *data, int64_t timestamp); ts_ws_message_t *ts_ws_message_text(const char *text, size_t len); void ts_ws_message_require(ts_ws_message_t *message, ts_perm_level_t required); +/* Immutable after publication; even session_id=0 is a restrictive requirement. */ +void ts_ws_message_require_session(ts_ws_message_t *message, uint32_t session_id); void ts_ws_message_release(ts_ws_message_t *message); /* ESP_OK means local acceptance. Each accepted target settles once via done, * including later queue failure, stale/canceled target and socket failure. diff --git a/components/ts_webui/src/ts_webui_api.c b/components/ts_webui/src/ts_webui_api.c index 468828ee..7cd50c02 100644 --- a/components/ts_webui/src/ts_webui_api.c +++ b/components/ts_webui/src/ts_webui_api.c @@ -17,6 +17,9 @@ #include "freertos/task.h" #include "esp_http_server.h" #include "esp_system.h" +#include "esp_ota_ops.h" +#include "esp_app_format.h" +#include #include "esp_timer.h" #include #include @@ -42,6 +45,8 @@ static bool is_binary_upload_complete(ts_http_request_t *req) return req && req->req && req->body_len == (size_t)req->req->content_len; } + + static void delayed_reboot_task(void *arg) { uint32_t delay_ms = (uint32_t)(uintptr_t)arg; @@ -49,6 +54,7 @@ static void delayed_reboot_task(void *arg) esp_restart(); } + static void schedule_reboot_after_response(uint32_t delay_ms) { BaseType_t ret = xTaskCreate( @@ -64,21 +70,9 @@ static void schedule_reboot_after_response(uint32_t delay_ms) } } -static void clear_recovery_manifest(const char *reason) -{ - if (unlink(TS_OTA_RECOVERY_MANIFEST_PATH) == 0) { - TS_LOGI(TAG, "Removed recovery manifest: %s", reason); - } -} -static void clean_recovery_after_browser_ota_failure(const char *reason) -{ - TS_LOGW(TAG, "Cleaning recovery cache after browser OTA failure: %s", reason); - esp_err_t ret = ts_ota_clean_recovery(); - if (ret != ESP_OK) { - TS_LOGW(TAG, "Recovery cleanup failed: %s", esp_err_to_name(ret)); - } -} + + static bool is_browser_ota_busy(void) { @@ -140,43 +134,87 @@ static esp_err_t send_key_generate_result(ts_http_request_t *req, ts_api_result_ return ret; } +/* One URI/policy owner for pre-body admission and execution-time recheck. + * TOKEN endpoints retain their existing bounded-parser/body-token contract; + * body fields never supply the C session identity for protected operations. */ +/* The role/session comes from the validated header, not receipt query fields. */ + +static bool api_request_access(ts_http_request_t *req, char api_name[64], uint32_t *session_id) +{ + const size_t prefix_len = strlen(API_PREFIX); + if (!req->uri || strncmp(req->uri, API_PREFIX "/", prefix_len + 1)) { + ts_http_send_error(req, 404, "API not found"); + return false; + } + const char *endpoint = req->uri + prefix_len + 1; + size_t length = strcspn(endpoint, "?"); + if (!length || length >= 64) { + ts_http_send_error(req, 404, "API not found"); + return false; + } + memcpy(api_name, endpoint, length); + api_name[length] = '\0'; + for (char *p = api_name; *p; ++p) if (*p == '/') *p = '.'; + *session_id = 0; + /* Only verified request headers supply the C session identity. */ + check_auth(req, session_id, TS_PERM_NONE); + ts_api_access_t access; + esp_err_t policy_ret = ts_api_get_access(api_name, &access); + if (policy_ret != ESP_OK) { + ts_http_send_error(req, policy_ret == ESP_ERR_NOT_FOUND ? 404 : 500, "API policy unavailable"); + return false; + } +#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED + if (access.requires_auth) { + esp_err_t auth_ret = check_auth(req, session_id, (ts_perm_level_t)access.minimum_level); + if (auth_ret != ESP_OK) { + ts_http_send_error(req, auth_ret == ESP_ERR_NOT_ALLOWED ? 403 : 401, + auth_ret == ESP_ERR_NOT_ALLOWED && access.minimum_level == TS_PERM_ROOT ? "Administrator permission required" : "Unauthorized"); + return false; + } + } +#endif + uint8_t method = req->method == TS_HTTP_GET ? TS_API_METHOD_GET : + req->method == TS_HTTP_POST ? TS_API_METHOD_POST : req->method == TS_HTTP_PUT ? TS_API_METHOD_PUT : + req->method == TS_HTTP_DELETE ? TS_API_METHOD_DELETE : 0; + if (!method || !(access.allowed_methods & method)) { + ts_http_send_error(req, 405, "Method not allowed"); + return false; + } + + return true; +} + +static bool api_admit(ts_http_request_t *req, void *user_data) +{ + (void)user_data; + char api_name[64]; + uint32_t session_id; + if (!api_request_access(req, api_name, &session_id)) return false; + if (!strncmp(api_name,"auth.",5)) { + if (req->req->content_len>16U*1024U) { + ts_http_send_error(req,413,"Authentication request too large"); + return false; + } + ts_httpd_set_body_receive_budget(10000); + } + return true; +} + static esp_err_t api_handler(ts_http_request_t *req, void *user_data) { (void)user_data; - + #ifdef CONFIG_TS_WEBUI_CORS_ENABLE ts_http_set_cors(req, "*"); #endif - - // Extract endpoint from URI - const char *uri = req->uri; - const char *endpoint = uri + strlen(API_PREFIX) + 1; - - // Convert slashes to dots for API lookup + char api_name[64]; - strncpy(api_name, endpoint, sizeof(api_name) - 1); - api_name[sizeof(api_name) - 1] = '\0'; - - // Remove query string if present - char *query = strchr(api_name, '?'); - if (query) { - *query = '\0'; - } - - // Convert slashes to dots - for (char *p = api_name; *p; p++) { - if (*p == '/') *p = '.'; - } - - // API 请求日志使用 DEBUG 级别,避免干扰调试 + uint32_t session_id; + if (!api_request_access(req, api_name, &session_id)) return ESP_FAIL; if (strncmp(api_name, "log.", 4) != 0) { - TS_LOGD(TAG, "API request: method=%d uri=%s -> api_name=%s", - req->method, uri, api_name); + TS_LOGD(TAG, "API request: method=%d", req->method); } - - uint32_t session_id = 0; - /* Only verified request headers supply the C session identity. */ - check_auth(req, &session_id, TS_PERM_NONE); bool key_generation = strcmp(api_name, "key.generate") == 0; bool rule_import = strcmp(api_name,"automation.rules.import")==0; @@ -194,34 +232,50 @@ static esp_err_t api_handler(ts_http_request_t *req, void *user_data) return send_ret; } - // Parse URL query string parameters (for GET requests) + if (!request) return ts_http_send_error(req, 500, "Request allocation failed"); size_t query_len = httpd_req_get_url_query_len(req->req); if (query_len > 0) { + if (query_len == SIZE_MAX) { + cJSON_Delete(request); + return ts_http_send_error(req, 400, "Invalid query length"); + } char *query_buf = TS_API_MALLOC(query_len + 1); - if (query_buf) { - if (httpd_req_get_url_query_str(req->req, query_buf, query_len + 1) == ESP_OK) { - ts_api_parse_query(request, query_buf); - } - free(query_buf); + if (!query_buf) { + cJSON_Delete(request); + return ts_http_send_error(req, 500, "Query allocation failed"); + } + ts_api_params_status_t parsed = TS_API_PARAMS_INVALID; + if (httpd_req_get_url_query_str(req->req, query_buf, query_len + 1) == ESP_OK) + parsed = ts_api_params_add_query(request, query_buf); + free(query_buf); + if (parsed != TS_API_PARAMS_OK) { + cJSON_Delete(request); + return ts_http_send_error(req, parsed == TS_API_PARAMS_NO_MEM ? 500 : 400, "Invalid or unavailable query"); } } - - // Add body data if present (POST/PUT requests - overrides query params) - if (req->body && req->body_len > 0) { - cJSON *body = rule_import ? ts_config_pack_parse_import_request(req->body,req->body_len) : cJSON_Parse(req->body); - if(rule_import&&!cJSON_IsObject(body)){ - cJSON_Delete(body);cJSON_Delete(request); - return ts_http_send_error(req,400,"invalid_pack"); + + if (req->body_len > 0) { + cJSON *body = rule_import ? ts_config_pack_parse_import_request(req->body, req->body_len) + : ts_api_params_parse_object(req->body, req->body_len); + if (!body || !cJSON_IsObject(body) || !ts_api_params_unique(body, 0)) { + cJSON_Delete(body); cJSON_Delete(request); + return ts_http_send_error(req, 400, rule_import ? "invalid_pack" : "Invalid JSON parameters"); } - if (body) { - cJSON *item; - cJSON_ArrayForEach(item, body) { - cJSON_AddItemToObject(request, item->string, cJSON_Duplicate(item, true)); + cJSON *item; + cJSON_ArrayForEach(item, body) { + if (cJSON_GetObjectItem(request, item->string)) { + cJSON_Delete(body); cJSON_Delete(request); + return ts_http_send_error(req, 400, "Conflicting query and body parameters"); + } + cJSON *copy = cJSON_Duplicate(item, true); + if (!copy || !cJSON_AddItemToObject(request, item->string, copy)) { + cJSON_Delete(copy); cJSON_Delete(body); cJSON_Delete(request); + return ts_http_send_error(req, 500, "Parameter allocation failed"); } - cJSON_Delete(body); } + cJSON_Delete(body); } - + if (key_generation) { const cJSON *rid = cJSON_GetObjectItem(request, "request_id"); if (cJSON_IsString(rid) && strlen(rid->valuestring) < sizeof(key_request_id)) { @@ -244,10 +298,17 @@ static esp_err_t api_handler(ts_http_request_t *req, void *user_data) return ts_http_send_error(req, 401, "Unauthorized"); } + if (ret == ESP_ERR_NOT_ALLOWED && result.code == TS_API_ERR_NO_PERMISSION && + result.message && !strcmp(result.message, "Root permission required")) { + cJSON_Delete(request); + ts_api_result_free(&result); + return ts_http_send_error(req, 403, "Root permission required"); + } + // API 结果日志使用 DEBUG 级别 if (strncmp(api_name, "log.", 4) != 0) { - TS_LOGD(TAG, "API call result: api=%s ret=%d code=%d msg=%s", - api_name, ret, result.code, result.message ? result.message : "null"); + TS_LOGD(TAG, "API call result: api=%s ret=%d code=%d", + api_name, ret, result.code); } if (key_generation) { @@ -259,28 +320,26 @@ static esp_err_t api_handler(ts_http_request_t *req, void *user_data) cJSON_Delete(request); if (key_generation) return send_key_generate_result(req, &result, key_request_id, key_started); + /* A reply allocation failure after a write cannot prove that no effect occurred. */ + const bool response_may_have_effect = req->method != TS_HTTP_GET; if (ret == ESP_OK || result.code == TS_API_OK) { - // Build response JSON cJSON *response = cJSON_CreateObject(); - cJSON_AddNumberToObject(response, "code", result.code); - if (result.message) { - cJSON_AddStringToObject(response, "message", result.message); - } - if (result.data) { - cJSON_AddItemToObject(response, "data", cJSON_Duplicate(result.data, true)); + bool built = response && cJSON_AddNumberToObject(response, "code", result.code); + if (built && result.message) built = cJSON_AddStringToObject(response, "message", result.message) != NULL; + if (built && result.data) { + built = cJSON_AddItemToObject(response, "data", result.data); + if (built) result.data = NULL; /* Transfer this result's sole ownership. */ } - - char *json = cJSON_PrintUnformatted(response); + char *json = built ? cJSON_PrintUnformatted(response) : NULL; cJSON_Delete(response); - - // Free result resources ts_api_result_free(&result); - if (json) { esp_err_t send_ret = ts_http_send_json(req, 200, json); free(json); return send_ret; } + if (response_may_have_effect) + return ts_http_send_json(req, 409, "{\"code\":7,\"error\":\"result_unknown\"}"); return ts_http_send_error(req, 500, "JSON serialization failed"); } else if (ret == ESP_ERR_NOT_FOUND && result.code == TS_API_ERR_NOT_FOUND && result.message && strcmp(result.message, "API not found") == 0) { @@ -291,18 +350,13 @@ static esp_err_t api_handler(ts_http_request_t *req, void *user_data) // Return the actual error from the API handler with HTTP 200 // API errors (like "no data") are business logic errors, not HTTP errors cJSON *response = cJSON_CreateObject(); - /* code and error are the failure itself: if either cannot be written, send HTTP 500 rather - * than a document the client would misread. */ bool built = response && cJSON_AddNumberToObject(response, "code", result.code) && cJSON_AddStringToObject(response, "error", result.message ? result.message : "Internal error"); - /* A failing handler may attach details the client must act on, e.g. the host-key - * fingerprint ssh.exec reports with code 1001/1002 so the UI can ask the user to - * confirm it. Dropping them leaves a bare error and no way to continue. Handlers - * that fail without details leave data NULL, so their responses do not change. */ + /* Details may carry the confirmation the UI needs, so send them whole. */ if (built && result.data) { - cJSON *data = cJSON_Duplicate(result.data, true); - if (data && !cJSON_AddItemToObject(response, "data", data)) cJSON_Delete(data); + built = cJSON_AddItemToObject(response, "data", result.data); + if (built) result.data = NULL; } char *json = built ? cJSON_PrintUnformatted(response) : NULL; @@ -316,6 +370,8 @@ static esp_err_t api_handler(ts_http_request_t *req, void *user_data) free(json); return send_ret; } + if (response_may_have_effect) + return ts_http_send_json(req, 409, "{\"code\":7,\"error\":\"result_unknown\"}"); return ts_http_send_error(req, 500, "Internal error"); } } @@ -332,7 +388,7 @@ static esp_err_t login_handler(ts_http_request_t *req, void *user_data) return ts_http_send_error(req, 400, "Missing body"); } - cJSON *body = cJSON_Parse(req->body); + cJSON *body = ts_api_params_parse_object(req->body, req->body_len); if (!body) { return ts_http_send_error(req, 400, "Invalid JSON"); } @@ -355,16 +411,19 @@ static esp_err_t login_handler(ts_http_request_t *req, void *user_data) esp_err_t ret = ts_auth_login(username->valuestring, password->valuestring, &session_id, token, sizeof(token)); cJSON_Delete(body); + if (ret == ESP_ERR_INVALID_STATE) { + return ts_http_send_error(req, 401, "Account locked due to too many failed attempts"); + } if (ret != ESP_OK) { return ts_http_send_error(req, 401, "Invalid credentials"); } /* 获取用户权限等级 */ - ts_perm_level_t level = TS_PERM_ADMIN; /* 默认 */ ts_session_t session; - if (ts_security_validate_session(session_id, &session) == ESP_OK) { - level = session.level; + if (ts_security_validate_session(session_id, &session) != ESP_OK) { + return ts_http_send_error(req, 401, "Session expired"); } + ts_perm_level_t level = session.level; /* 将权限级别转换为字符串 */ const char *level_str = (level == TS_PERM_ROOT) ? "root" : "admin"; @@ -445,6 +504,9 @@ static esp_err_t file_download_handler(ts_http_request_t *req, void *user_data) ts_http_set_cors(req, "*"); #endif + uint32_t session_id = 0; + if (check_auth(req, &session_id, TS_PERM_READ) != ESP_OK) return ts_http_send_error(req, 401, "Unauthorized"); + // 获取文件路径参数 char path[256] = {0}; esp_err_t ret = ts_http_get_query_param(req, "path", path, sizeof(path)); @@ -455,16 +517,14 @@ static esp_err_t file_download_handler(ts_http_request_t *req, void *user_data) // ts_http_get_query_param already decodes the query value once. TS_LOGD(TAG, "Download request: %s", path); - // 安全检查:只允许访问 /sdcard 和 /spiffs - if (strncmp(path, "/sdcard", 7) != 0 && strncmp(path, "/spiffs", 7) != 0) { - return ts_http_send_error(req, 403, "Access denied: invalid path"); - } - uint32_t session_id = 0; - if (ts_storage_check_write_path(path, false) != ESP_OK && - check_auth(req, &session_id, TS_PERM_ROOT) != ESP_OK) { - return ts_http_send_error(req, 401, "Unauthorized"); - } - + bool needs_admin; + ret = ts_storage_external_read_requires_admin(path, &needs_admin); + if (ret != ESP_OK) return ts_http_send_error(req, ret == ESP_ERR_INVALID_ARG ? 400 : 500, + ret == ESP_ERR_INVALID_ARG ? "storage_path_invalid" : "storage_read_failed"); + ret = check_auth(req, &session_id, needs_admin ? TS_PERM_ADMIN : TS_PERM_READ); + if (ret != ESP_OK) return ts_http_send_error(req, ret == ESP_ERR_NOT_ALLOWED ? 403 : 401, + ret == ESP_ERR_NOT_ALLOWED ? "Administrator permission required" : "Unauthorized"); + // 检查文件是否存在 if (!ts_storage_exists(path)) { return ts_http_send_error(req, 404, "File not found"); @@ -476,7 +536,7 @@ static esp_err_t file_download_handler(ts_http_request_t *req, void *user_data) } // 发送文件 - return ts_http_send_file(req, path); + return ts_http_send_private_file(req, path); } /** @@ -506,7 +566,7 @@ static esp_err_t file_upload_handler(ts_http_request_t *req, void *user_data) if (strncmp(path, "/sdcard/", 8) != 0) { return ts_http_send_error(req, 403, "Upload only allowed to /sdcard"); } - ret = ts_storage_check_write_path(path, false); + ret = ts_storage_check_external_write_path(path, false); if (ret == ESP_ERR_NOT_ALLOWED) return ts_http_send_error(req, 409, "automation_configuration_managed"); if (ret != ESP_OK) return ts_http_send_error(req, 400, "storage_path_invalid"); @@ -528,11 +588,12 @@ static esp_err_t file_upload_handler(ts_http_request_t *req, void *user_data) } // 写入文件 - ret = ts_storage_write_file(path, req->body, req->body_len); + ret = ts_storage_replace_file(path, req->body, req->body_len); if (ret != ESP_OK) { if (ret == ESP_ERR_NOT_ALLOWED) return ts_http_send_error(req, 409, "automation_configuration_managed"); TS_LOGE(TAG, "Failed to write file %s: %s", path, esp_err_to_name(ret)); - return ts_http_send_error(req, 500, "Failed to write file"); + return ts_http_send_error(req, ret == ESP_ERR_NOT_FINISHED ? 409 : 500, + ret == ESP_ERR_NOT_FINISHED ? "file_replace_uncertain" : "Failed to write file"); } TS_LOGD(TAG, "File uploaded: %s (%zu bytes)", path, req->body_len); @@ -609,176 +670,101 @@ static esp_err_t file_upload_handler(ts_http_request_t *req, void *user_data) * This allows browsers to upload firmware directly to ESP32 devices * that cannot access external networks. * - * 使用统一 recovery 目录模式:保存到 /sdcard/recovery/ 然后刷入 + * Original firmware format and SD recovery cache; validate before changing the previous cache. */ -static esp_err_t ota_firmware_upload_handler(ts_http_request_t *req, void *user_data) +/* Keep the original raw APP/WWW and /sdcard/recovery contract. Invalid or + * failed uploads never delete the last recovery set. No publisher registration + * is required; APP completeness is finally checked by the SDK installer. */ +static esp_err_t ota_upload_reply(ts_http_request_t *req, bool firmware) { - (void)user_data; - -#ifdef CONFIG_TS_WEBUI_CORS_ENABLE - ts_http_set_cors(req, "*"); -#endif - - if (!is_binary_upload_complete(req)) { - TS_LOGW(TAG, "Incomplete firmware upload: got %zu of %zu bytes", - req->body_len, req->req ? (size_t)req->req->content_len : 0); - return ts_http_send_error(req, 400, "Incomplete upload"); - } - - // 检查请求体 - if (!req->body || req->body_len == 0) { - return ts_http_send_error(req, 400, "Empty firmware content"); - } - - if (is_browser_ota_busy()) { - return ts_http_send_error(req, 409, "OTA already in progress"); - } - - // 获取 auto_reboot 参数 - char auto_reboot_str[8] = "true"; - ts_http_get_query_param(req, "auto_reboot", auto_reboot_str, sizeof(auto_reboot_str)); - bool auto_reboot = (strcmp(auto_reboot_str, "false") != 0); - - TS_LOGI(TAG, "OTA firmware upload: %zu bytes, auto_reboot=%d", req->body_len, auto_reboot); - - // 新固件上传开始时先移除旧 manifest 和旧 WebUI,避免失败路径留下旧恢复指令。 - clear_recovery_manifest("firmware upload"); - if (unlink(TS_OTA_RECOVERY_WWW_PATH) == 0) { - TS_LOGI(TAG, "Removed stale recovery www.bin"); - } - - // 先保存到 recovery 目录,保持恢复素材;刷写成功后再写 disabled manifest。 - esp_err_t ret = ts_ota_save_upload(req->body, req->body_len, true, false); - if (ret != ESP_OK) { - TS_LOGE(TAG, "ts_ota_save_upload failed: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("firmware save failed"); - return ts_http_send_error(req, 500, "Firmware save failed"); - } - - ret = ts_ota_flash_file_sync(TS_OTA_RECOVERY_FIRMWARE_PATH, true, NULL, NULL); - if (ret != ESP_OK) { - TS_LOGE(TAG, "ts_ota_flash_file_sync failed: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("firmware flash failed"); - if (ret == ESP_ERR_INVALID_STATE) { - return ts_http_send_error(req, 409, "OTA already in progress"); - } - if (ret == ESP_ERR_INVALID_SIZE || ret == ESP_ERR_INVALID_ARG) { + if (!is_binary_upload_complete(req) || !req->body || !req->body_len) + return ts_http_send_error(req, 400, "Incomplete or empty OTA upload"); + uint32_t caller = 0; + if (check_auth(req, &caller, TS_PERM_ADMIN) != ESP_OK) + return ts_http_send_error(req, 403, "Administrator login required"); + const esp_partition_t *partition = firmware ? esp_ota_get_next_update_partition(NULL) : + esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, "www"); + if (!partition) return ts_http_send_error(req, 500, "OTA partition unavailable"); + if (req->body_len > partition->size) + return ts_http_send_error(req, 400, "OTA image exceeds partition capacity"); + if (firmware) { + const size_t offset = sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t); + esp_app_desc_t app; + if (req->body_len < offset + sizeof(app)) + return ts_http_send_error(req, 400, "Invalid firmware image"); + memcpy(&app, (const uint8_t *)req->body + offset, sizeof(app)); + if (((const uint8_t *)req->body)[0] != ESP_IMAGE_HEADER_MAGIC || + app.magic_word != ESP_APP_DESC_MAGIC_WORD) return ts_http_send_error(req, 400, "Invalid firmware image"); - } - return ts_http_send_error(req, 500, "Firmware flash failed"); } - - ret = ts_ota_write_recovery_manifest_from_files(false, false, false); + if (is_browser_ota_busy()) return ts_http_send_error(req, 409, "OTA already in progress"); + static atomic_flag upload_busy = ATOMIC_FLAG_INIT; + if (atomic_flag_test_and_set(&upload_busy)) return ts_http_send_error(req, 409, "OTA upload busy"); + char auto_reboot_text[8] = "true"; + ts_http_get_query_param(req, "auto_reboot", auto_reboot_text, sizeof(auto_reboot_text)); + bool auto_reboot = firmware && strcmp(auto_reboot_text, "false") != 0; + cJSON *reply = cJSON_CreateObject(); + bool ready = reply && cJSON_AddStringToObject(reply, "status", "success") && + cJSON_AddNumberToObject(reply, "size", req->body_len) && + cJSON_AddStringToObject(reply, "message", firmware ? "Firmware uploaded and flashed, pending reboot" : "WWW partition updated"); + if (ready && firmware) ready = cJSON_AddBoolToObject(reply, "reboot_pending", true) && + cJSON_AddBoolToObject(reply, "auto_reboot_requested", auto_reboot); + char *json = ready ? cJSON_PrintUnformatted(reply) : NULL; + cJSON_Delete(reply); + if (!json) { + atomic_flag_clear(&upload_busy); + return ts_http_send_error(req, 500, "Out of memory"); + } + const char *pending = firmware ? "/sdcard/recovery/.firmware-upload.bin" : "/sdcard/recovery/.www-upload.bin"; + const char *destination = firmware ? TS_OTA_RECOVERY_FIRMWARE_PATH : TS_OTA_RECOVERY_WWW_PATH; + esp_err_t ret = ts_storage_mkdir_p("/sdcard/recovery"); + if (ret == ESP_OK) ret = ts_storage_write_file(pending, req->body, req->body_len); + if (ret == ESP_OK) ret = firmware ? ts_ota_flash_file_sync(pending, true, NULL, NULL) : + ts_ota_www_flash_file_sync(pending, NULL, NULL); if (ret != ESP_OK) { - TS_LOGE(TAG, "failed to write disabled app-only recovery manifest: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("firmware manifest update failed"); - return ts_http_send_error(req, 500, "Recovery manifest update failed"); + unlink(pending); + free(json); + atomic_flag_clear(&upload_busy); + return ts_http_send_error(req, ret == ESP_ERR_INVALID_STATE ? 409 : + (ret == ESP_ERR_INVALID_ARG || ret == ESP_ERR_INVALID_SIZE || ret == ESP_ERR_OTA_VALIDATE_FAILED) ? 400 : 500, + "OTA upload did not complete; previous recovery files retained"); + } + /* Flash succeeded. Commit the ordinary recovery file, then its disabled + * manifest. A cache failure must not be reported as complete success. */ + ret = ts_storage_replace_file(destination, req->body, req->body_len); + unlink(pending); + if (ret != ESP_OK || + (firmware || ts_storage_exists(TS_OTA_RECOVERY_FIRMWARE_PATH) ? + ts_ota_write_recovery_manifest_from_files(!firmware, false, false) : ESP_OK) != ESP_OK) { + free(json); + atomic_flag_clear(&upload_busy); + return ts_http_send_json(req, 409, + "{\"status\":\"partial\",\"error\":\"recovery_cache_failed\",\"flash_written\":true}"); } - - TS_LOGI(TAG, "OTA firmware upload successful"); - - // 返回成功响应 - cJSON *response = cJSON_CreateObject(); - cJSON_AddStringToObject(response, "status", "success"); - cJSON_AddNumberToObject(response, "size", req->body_len); - cJSON_AddBoolToObject(response, "reboot_pending", true); - cJSON_AddBoolToObject(response, "auto_reboot_requested", auto_reboot); - cJSON_AddStringToObject(response, "message", "Firmware uploaded and flashed, pending reboot"); - - char *json = cJSON_PrintUnformatted(response); - cJSON_Delete(response); - ret = ts_http_send_json(req, 200, json); free(json); - if (ret == ESP_OK && auto_reboot) { - schedule_reboot_after_response(OTA_UPLOAD_REBOOT_DELAY_MS); - } + atomic_flag_clear(&upload_busy); + if (ret == ESP_OK && auto_reboot) schedule_reboot_after_response(OTA_UPLOAD_REBOOT_DELAY_MS); return ret; } +static esp_err_t ota_firmware_upload_handler(ts_http_request_t *req, void *user_data) +{ + (void)user_data; + return ota_upload_reply(req, true); +} /** * @brief Handle WWW partition upload request * POST /api/v1/ota/www * Body: www.bin content * - * 使用统一 recovery 目录模式:保存到 /sdcard/recovery/www.bin 然后刷入 + * Original www partition and raw image format. */ static esp_err_t ota_www_upload_handler(ts_http_request_t *req, void *user_data) { (void)user_data; - -#ifdef CONFIG_TS_WEBUI_CORS_ENABLE - ts_http_set_cors(req, "*"); -#endif - - if (!is_binary_upload_complete(req)) { - TS_LOGW(TAG, "Incomplete WWW upload: got %zu of %zu bytes", - req->body_len, req->req ? (size_t)req->req->content_len : 0); - return ts_http_send_error(req, 400, "Incomplete upload"); - } - - // 检查请求体 - if (!req->body || req->body_len == 0) { - return ts_http_send_error(req, 400, "Empty www content"); - } - - if (is_browser_ota_busy()) { - return ts_http_send_error(req, 409, "OTA already in progress"); - } - - TS_LOGI(TAG, "WWW partition upload: %zu bytes", req->body_len); - - // WebUI 上传会重写 disabled manifest;先清掉旧 manifest 避免失败路径沿用旧恢复指令。 - clear_recovery_manifest("www upload"); - - // 先保存到 recovery 目录,保持完整恢复包;再同步刷入 www 分区。 - esp_err_t ret = ts_ota_save_upload(req->body, req->body_len, false, false); - if (ret != ESP_OK) { - TS_LOGE(TAG, "ts_ota_save_upload failed: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("www save failed"); - return ts_http_send_error(req, 500, "WWW partition save failed"); - } - - ret = ts_ota_www_flash_file_sync(TS_OTA_RECOVERY_WWW_PATH, NULL, NULL); - if (ret != ESP_OK) { - TS_LOGE(TAG, "ts_ota_www_flash_file_sync failed: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("www flash failed"); - if (ret == ESP_ERR_INVALID_STATE) { - return ts_http_send_error(req, 409, "WWW OTA already in progress"); - } - if (ret == ESP_ERR_INVALID_SIZE) { - return ts_http_send_error(req, 400, "Invalid WWW image size"); - } - return ts_http_send_error(req, 500, "WWW partition flash failed"); - } - - if (ts_storage_exists(TS_OTA_RECOVERY_FIRMWARE_PATH)) { - ret = ts_ota_write_recovery_manifest_from_files(true, false, false); - if (ret != ESP_OK) { - TS_LOGW(TAG, "Full recovery manifest update failed: %s", esp_err_to_name(ret)); - clean_recovery_after_browser_ota_failure("www manifest update failed"); - } - } else { - TS_LOGW(TAG, "Recovery firmware missing after WebUI upload"); - clean_recovery_after_browser_ota_failure("recovery firmware missing after www upload"); - } - - TS_LOGI(TAG, "WWW partition upload successful"); - - // 返回成功响应 - cJSON *response = cJSON_CreateObject(); - cJSON_AddStringToObject(response, "status", "success"); - cJSON_AddNumberToObject(response, "size", req->body_len); - cJSON_AddStringToObject(response, "message", "WWW partition updated"); - - char *json = cJSON_PrintUnformatted(response); - cJSON_Delete(response); - - ret = ts_http_send_json(req, 200, json); - free(json); - return ret; + return ota_upload_reply(req, false); } - esp_err_t ts_webui_api_init(void) { TS_LOGI(TAG, "Initializing API routes"); @@ -788,6 +774,8 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/auth/login", .method = TS_HTTP_POST, .handler = login_handler, + .max_body_bytes = 16U*1024U, + .body_timeout_ms = 10000, .requires_auth = false, .user_data = NULL }; @@ -807,7 +795,8 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/file/download", .method = TS_HTTP_GET, .handler = file_download_handler, - .requires_auth = false, + .requires_auth = true, + .required_level = TS_PERM_READ, .user_data = NULL }; ts_http_server_register_route(&file_download); @@ -817,7 +806,10 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/file/upload", .method = TS_HTTP_POST, .handler = file_upload_handler, + .max_body_bytes = 16U*1024U*1024U, + .body_timeout_ms = 300000, .requires_auth = true, + .required_level = TS_PERM_ADMIN, .user_data = NULL }; ts_http_server_register_route(&file_upload); @@ -827,7 +819,10 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/ota/firmware", .method = TS_HTTP_POST, .handler = ota_firmware_upload_handler, + .max_body_bytes = 16U*1024U*1024U, + .body_timeout_ms = 300000, .requires_auth = true, + .required_level = TS_PERM_ADMIN, .user_data = NULL }; ts_http_server_register_route(&ota_firmware); @@ -837,12 +832,21 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/ota/www", .method = TS_HTTP_POST, .handler = ota_www_upload_handler, + .max_body_bytes = 16U*1024U*1024U, + .body_timeout_ms = 300000, .requires_auth = true, + .required_level = TS_PERM_ADMIN, .user_data = NULL }; ts_http_server_register_route(&ota_www); // Generic API handler for all other routes + size_t generic_body_limit=1024U*1024U; +#ifdef CONFIG_TS_CONFIG_PACK_MAX_SIZE + /* Preserve the existing escaped import envelope of the configured pack size. */ + size_t pack_envelope=(size_t)CONFIG_TS_CONFIG_PACK_MAX_SIZE*6U+1024U; + if (pack_envelope>generic_body_limit) generic_body_limit=pack_envelope; +#endif ts_http_method_t methods[] = {TS_HTTP_GET, TS_HTTP_POST, TS_HTTP_PUT, TS_HTTP_DELETE}; const char *method_names[] = {"GET", "POST", "PUT", "DELETE"}; for (int i = 0; i < 4; i++) { @@ -850,6 +854,9 @@ esp_err_t ts_webui_api_init(void) .uri = API_PREFIX "/*", .method = methods[i], .handler = api_handler, + .admit = api_admit, + .max_body_bytes = generic_body_limit, + .body_timeout_ms = 30000, .requires_auth = false, .user_data = NULL }; diff --git a/components/ts_webui/src/ts_webui_ws.c b/components/ts_webui/src/ts_webui_ws.c index 06c5de1b..289aac16 100644 --- a/components/ts_webui/src/ts_webui_ws.c +++ b/components/ts_webui/src/ts_webui_ws.c @@ -30,6 +30,7 @@ #include "ts_variable.h" #include "esp_http_server.h" #include "cJSON.h" +#include "ts_api_params.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" @@ -41,6 +42,7 @@ #include #define TAG "webui_ws" +#define TS_WS_INPUT_MAX_BYTES (64 * 1024) #ifdef CONFIG_TS_WEBUI_WS_MAX_CLIENTS #define MAX_WS_CLIENTS CONFIG_TS_WEBUI_WS_MAX_CLIENTS @@ -458,12 +460,15 @@ static void terminal_job_destroy(void *data) static bool terminal_job_maintain(void *data) { terminal_job_t *job = data; - bool pending; + bool pending, finished; xSemaphoreTake(s_output_mutex, portMAX_DELAY); + /* Pair completion with this buffer snapshot; the producer can append and + * finish as soon as the lock is released. A stale empty view cannot close it. */ + finished = job->finished; if (job->detached) s_terminal_output_len = 0; size_t n = s_terminal_output_len < 4096 ? s_terminal_output_len : 4096; n = terminal_utf8_prefix(s_terminal_output_buf, n); - if (!n && s_terminal_output_len && job->finished) { + if (!n && s_terminal_output_len && finished) { s_terminal_output_len = 0; job->truncated = true; } if (n) { @@ -487,7 +492,8 @@ static bool terminal_job_maintain(void *data) } pending = s_terminal_output_len != 0; xSemaphoreGive(s_output_mutex); - if (!pending && job->finished && ts_ws_op_close_begin(job->op)) { + TS_WS_TEST_POINT("terminal_output_snapshot"); + if (!pending && finished && ts_ws_op_close_begin(job->op)) { char done[128]; ts_ws_op_stats_t stats; ts_ws_op_stats(TS_WS_OP_TERMINAL,&stats); snprintf(done,sizeof(done),"{\"type\":\"done\",\"code\":%d,\"output_incomplete\":%s,\"stopped\":%s}", job->code, job->truncated || stats.failed ? "true":"false",job->cancel?"true":"false"); @@ -726,6 +732,17 @@ static void peer_closed(ts_ws_peer_t peer) cleanup_disconnected_client(peer); } +/* A rejected frame has not been consumed. Close instead of leaving its payload + * to be interpreted as the next frame on this connection. */ +static esp_err_t reject_input_frame(httpd_req_t *req, ts_ws_peer_t peer, uint16_t code) +{ + uint8_t reason[] = {(uint8_t)(code >> 8), (uint8_t)code}; + httpd_ws_frame_t frame = {.type=HTTPD_WS_TYPE_CLOSE, .payload=reason, .len=sizeof(reason)}; + httpd_ws_send_frame(req, &frame); + cleanup_disconnected_client(peer); + return ESP_FAIL; +} + static esp_err_t ws_handler(httpd_req_t *req) { if (req->method == HTTP_GET) { @@ -752,17 +769,33 @@ static esp_err_t ws_handler(httpd_req_t *req) return ret; } - // 处理关闭帧 - if (ws_pkt.type == HTTPD_WS_TYPE_CLOSE) { - TS_LOGD(TAG, "WebSocket close frame received"); - cleanup_disconnected_client(peer); - return ESP_OK; - } - - if (ws_pkt.len == 0) { + /* This protocol consumes complete JSON text messages, not partial messages. + * The WebUI chunks large SSH input into complete independent messages. */ + if (!ws_pkt.final) return reject_input_frame(req, peer, 1002); + if (ws_pkt.type == HTTPD_WS_TYPE_CLOSE || ws_pkt.type == HTTPD_WS_TYPE_PING || ws_pkt.type == HTTPD_WS_TYPE_PONG) { + if (ws_pkt.len > 125 || (ws_pkt.type == HTTPD_WS_TYPE_CLOSE && ws_pkt.len == 1)) + return reject_input_frame(req, peer, 1002); + uint8_t control[125]; + ws_pkt.payload = control; + if (ws_pkt.len && httpd_ws_recv_frame(req, &ws_pkt, sizeof(control)) != ESP_OK) { + cleanup_disconnected_client(peer); + return ESP_FAIL; + } + if (ws_pkt.type == HTTPD_WS_TYPE_CLOSE) { + ws_pkt.len = 0; + cleanup_disconnected_client(peer); + return httpd_ws_send_frame(req, &ws_pkt); + } + if (ws_pkt.type == HTTPD_WS_TYPE_PING) { + ws_pkt.type = HTTPD_WS_TYPE_PONG; + return httpd_ws_send_frame(req, &ws_pkt); + } return ESP_OK; } - + if (ws_pkt.type != HTTPD_WS_TYPE_TEXT) return reject_input_frame(req, peer, 1003); + if (ws_pkt.len > TS_WS_INPUT_MAX_BYTES) return reject_input_frame(req, peer, 1009); + if (ws_pkt.len == 0) return ESP_OK; + // Allocate buffer for payload (PSRAM first) uint8_t *buf = heap_caps_malloc(ws_pkt.len + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (!buf) { @@ -782,8 +815,13 @@ static esp_err_t ws_handler(httpd_req_t *req) buf[ws_pkt.len] = '\0'; // Parse message - cJSON *msg = cJSON_Parse((char *)buf); + cJSON *msg = ts_api_params_parse_object((char *)buf, ws_pkt.len); free(buf); + if (!msg) { + const char *error = "{\"type\":\"error\",\"message\":\"Invalid JSON message\"}"; + httpd_ws_frame_t frame = {.type=HTTPD_WS_TYPE_TEXT, .payload=(uint8_t *)error, .len=strlen(error)}; + return httpd_ws_send_frame(req, &frame); + } if (msg) { cJSON *type = cJSON_GetObjectItem(msg, "type"); @@ -799,8 +837,19 @@ static esp_err_t ws_handler(httpd_req_t *req) return result; } - TS_LOGD(TAG, "WS msg type=%s from fd=%d", type->valuestring, httpd_req_to_sockfd(req)); + TS_LOGD(TAG, "WS message received from fd=%d", httpd_req_to_sockfd(req)); + if ((!strcmp(type->valuestring, "log_subscribe") || + !strcmp(type->valuestring, "log_set_level") || + !strcmp(type->valuestring, "log_get_history")) && + !ts_ws_peer_authorized(peer, TS_PERM_ADMIN)) { + const char *error = "{\"type\":\"auth_error\",\"message\":\"Permission denied\"}"; + httpd_ws_frame_t frame = {.type=HTTPD_WS_TYPE_TEXT, .payload=(uint8_t *)error, .len=strlen(error)}; + esp_err_t sent = httpd_ws_send_frame(req, &frame); + cJSON_Delete(msg); + return sent; + } + if (strcmp(type->valuestring, "auth") == 0) { handle_auth(req, msg); } @@ -1051,7 +1100,8 @@ static esp_err_t ws_handler(httpd_req_t *req) if (resp_str) { ws_pkt.payload = (uint8_t *)resp_str; ws_pkt.len = strlen(resp_str); - httpd_ws_send_frame(req, &ws_pkt); + if (ts_ws_peer_authorized(peer, TS_PERM_ADMIN)) + httpd_ws_send_frame(req, &ws_pkt); free(resp_str); } } @@ -1350,7 +1400,7 @@ static void update_log_stream_state(void) * credentials or log history. Records are pinned while parsed, never freed or * allocated under the critical section. Published final JSON is immutable. */ typedef struct exec_record { - unsigned refs; uint32_t id; bool done; + unsigned refs; uint32_t id, owner_session_id; bool done; ts_webui_ssh_receipt_t receipt; char json[TS_WS_LEGACY_BYTES]; } exec_record_t; @@ -1377,12 +1427,26 @@ static void exec_cache_clear(void) { portENTER_CRITICAL(&s_exec_cache_lock);exec_record_t *old=s_exec_latest;s_exec_latest=NULL;portEXIT_CRITICAL(&s_exec_cache_lock); exec_record_release(old); } -char *ts_webui_ssh_exec_status(uint32_t id,const char *boot,const char *key,esp_err_t *error) { +static bool exec_receipt_matches(const exec_record_t *record, uint32_t id, + const char *boot, const char *key) +{ + if (!record || record->id != id) + return false; + unsigned char different = 0; + for (unsigned i = 0; i < 32; i++) { + different |= (unsigned char)record->receipt.boot_id[i] ^ (unsigned char)boot[i]; + different |= (unsigned char)record->receipt.result_key[i] ^ (unsigned char)key[i]; + } + return different == 0; +} +static char *exec_status_lookup(uint32_t id,const char *boot,const char *key, + const uint32_t *caller_session_id,esp_err_t *error) { if(error)*error=ESP_ERR_NOT_FOUND; if(!id || !boot || !key || strlen(boot)!=32 || strlen(key)!=32)return NULL; portENTER_CRITICAL(&s_exec_cache_lock); exec_record_t *r=s_exec_active && s_exec_active->id==id?s_exec_active:s_exec_latest; - if(r && (r->id!=id || strcmp(r->receipt.boot_id,boot) || strcmp(r->receipt.result_key,key)))r=NULL; + if(!exec_receipt_matches(r,id,boot,key) || + (caller_session_id && r->owner_session_id != *caller_session_id))r=NULL; bool done=r && r->done;if(r)r->refs++; portEXIT_CRITICAL(&s_exec_cache_lock); if(!r)return NULL; @@ -1391,6 +1455,14 @@ char *ts_webui_ssh_exec_status(uint32_t id,const char *boot,const char *key,esp_ if(error)*error=json?ESP_OK:ESP_ERR_NO_MEM; exec_record_release(r);return json; } +char *ts_webui_ssh_exec_status(uint32_t id,const char *boot,const char *key,esp_err_t *error) { + return exec_status_lookup(id,boot,key,NULL,error); +} +char *ts_webui_ssh_exec_status_for_session(uint32_t id,const char *boot,const char *key, + uint32_t caller_session_id,esp_err_t *error) { + return exec_status_lookup(id,boot,key,&caller_session_id,error); +} + /* SSH Exec 任务参数 */ typedef struct { @@ -1556,7 +1628,8 @@ static void ssh_exec_output_callback(const char *data, size_t len, bool is_stder } params->extracted_value = extracted; should_send_match = true; - TS_LOGI(TAG, "Realtime extract: %s (first=%d)", extracted ? extracted : "(null)", is_first_extract); + TS_LOGI(TAG, "Realtime extraction complete (bytes=%u, first=%d)", + (unsigned)(extracted ? strlen(extracted) : 0), is_first_extract); } else { /* 值相同,释放本次提取的 */ free(extracted); @@ -1610,13 +1683,7 @@ static void ssh_exec_output_callback(const char *data, size_t len, bool is_stder !params->fail_pattern && !params->stop_on_match; - TS_LOGI(TAG, "Variable update check: var_name='%s', continuous=%d, extract=%p, expect=%p, fail=%p, stop=%d", - params->var_name, - is_continuous_mode, - params->extract_pattern, - params->expect_pattern, - params->fail_pattern, - params->stop_on_match); + TS_LOGD(TAG, "SSH variable update: continuous=%d, has_extract=%d, has_expect=%d, has_fail=%d, stop=%d", is_continuous_mode, params->extract_pattern != NULL, params->expect_pattern != NULL, params->fail_pattern != NULL, params->stop_on_match); if (is_continuous_mode && params->var_name[0] && exec_variables_begin(params)) { /* 持续监控模式:实时更新变量 */ @@ -1632,7 +1699,7 @@ static void ssh_exec_output_callback(const char *data, size_t len, bool is_stder var.value.type = TS_AUTO_VAL_STRING; strncpy(var.value.str_val, params->extracted_value, sizeof(var.value.str_val) - 1); esp_err_t ret = ts_variable_upsert(&var); - TS_LOGI(TAG, "Registered %s = %s (ret=%d)", full_var_name, params->extracted_value, ret); + TS_LOGD(TAG, "Extraction variable registered (bytes=%u, ret=%d)", (unsigned)strlen(params->extracted_value), ret); } /* 更新 status 为 running */ @@ -1656,7 +1723,7 @@ static void ssh_exec_output_callback(const char *data, size_t len, bool is_stder var.value.int_val = (int32_t)(esp_timer_get_time() / 1000000); ts_variable_upsert(&var); - TS_LOGD(TAG, "Continuous mode: realtime update %s", params->var_name); + TS_LOGD(TAG, "Continuous extraction variable updated"); exec_variables_end(); } /* 结果导向模式:变量在命令完成时更新(见下方 ssh_exec_task 完成处理) */ @@ -1812,8 +1879,8 @@ static void ssh_exec_task(void *arg) ts_ws_stop_reason_t stop_reason=OP_STOP_NONE; if(ts_ws_op_cancelled(params->op)){ret=ESP_ERR_TIMEOUT;goto execution_finished;} - TS_LOGI(TAG, "SSH exec task started: session_id=%lu, cmd=%s", - (unsigned long)session_id, params->command); + TS_LOGI(TAG, "SSH exec task started: session_id=%lu, command_bytes=%u", + (unsigned long)session_id, (unsigned)strlen(params->command)); /* 如果使用密钥认证,加载私钥 */ if (params->keyid[0] != '\0') { @@ -1827,7 +1894,7 @@ static void ssh_exec_task(void *arg) } else { stop_reason=ts_ws_op_business_end(params->op,false); if(stop_reason){ret=ESP_ERR_TIMEOUT;goto execution_finished;} - TS_LOGE(TAG, "Failed to load key '%s': %s", params->keyid, esp_err_to_name(ret)); + TS_LOGE(TAG, "Failed to load SSH key: %s", esp_err_to_name(ret)); /* 发送错误消息 */ if(!params->pending_final) { cJSON *msg = cJSON_CreateObject(); @@ -2029,12 +2096,7 @@ static void ssh_exec_task(void *arg) (params->expect_pattern || params->fail_pattern || params->extract_pattern) && !params->match_found && !extracted_value; /* 诊断日志:检查变量写入条件 */ - TS_LOGI(TAG, "SSH exec finished: var_name='%s' (has_var=%d), status=%d (is_cancelled=%d), exit_code=%d", - params->var_name, - params->var_name[0] ? 1 : 0, - status, - status == TS_WEBUI_SSH_STATUS_CANCELLED ? 1 : 0, - exit_code); + TS_LOGI(TAG, "SSH exec finished: has_var=%d, status=%d, is_cancelled=%d, exit_code=%d", params->var_name[0] != 0, status, status == TS_WEBUI_SSH_STATUS_CANCELLED, exit_code); /* 存储结果到变量系统 - 包括取消状态也要更新 */ if (params->var_name[0] && exec_variables_begin(params)) { @@ -2055,8 +2117,7 @@ static void ssh_exec_task(void *arg) /* 同步更新到 ts_automation 变量系统 - 使用 register 确保变量存在并更新 */ if(params->conditions_incomplete)status_str="unknown"; - TS_LOGI(TAG, "Writing SSH result to automation variables: var_name=%s, status=%s, exit_code=%d", - params->var_name, status_str, exit_code); + TS_LOGI(TAG, "Writing SSH result to variables (exit_code=%d)", exit_code); char full_var_name[96]; /* 足够容纳 source_id + suffix */ ts_auto_variable_t var = {0}; @@ -2112,7 +2173,7 @@ static void ssh_exec_task(void *arg) var.value.int_val = (int32_t)(esp_timer_get_time() / 1000000); /* 秒级时间戳 */ ts_variable_upsert(&var); - TS_LOGI(TAG, "Synced SSH result to automation variables: %s (7 vars)", params->var_name); + TS_LOGI(TAG, "SSH result variables synchronized (count=7)"); exec_variables_end(); } @@ -2229,6 +2290,8 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch if(params->record)params->record->refs=1; if(!params->output_lock || !params->stream || !params->send_bytes || !params->send_base64 || !params->record)return ESP_ERR_NO_MEM; exec_record_t *record=params->record;record->id=params->session_id; + record->owner_session_id = options ? options->owner_session_id : 0; + ts_ws_op_set_exec_owner(op,record->owner_session_id); if(!s_exec_boot[0])exec_hex_random(s_exec_boot); /* only one exec creator admitted */ strcpy(record->receipt.boot_id,s_exec_boot);exec_hex_random(record->receipt.result_key); if(options && options->receipt)*options->receipt=record->receipt; @@ -2290,11 +2353,11 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch params->max_output_size = options->max_output_size > 0 ? options->max_output_size : 64 * 1024; params->stop_on_match = options->stop_on_match; - TS_LOGI(TAG, "SSH exec options: timeout_ms=%lu, expect=%s, fail=%s, extract=%s, stop_on_match=%d, var=%s", + TS_LOGI(TAG, "SSH exec options: timeout_ms=%lu, has_expect=%d, has_fail=%d, has_extract=%d, stop_on_match=%d, var=%s", (unsigned long)params->timeout_ms, - params->expect_pattern ? params->expect_pattern : "(null)", - params->fail_pattern ? params->fail_pattern : "(null)", - params->extract_pattern ? params->extract_pattern : "(null)", + params->expect_pattern != NULL, + params->fail_pattern != NULL, + params->extract_pattern != NULL, params->stop_on_match, params->var_name[0] ? params->var_name : "(none)"); } else { @@ -2351,8 +2414,7 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch return ESP_ERR_NOT_FOUND; } /* 命令开始时初始化所有变量(重置旧值) */ - TS_LOGI(TAG, "Checking var_name for init: '%s' (len=%d)", - params->var_name, (int)strlen(params->var_name)); + TS_LOGD(TAG, "Checking SSH variable initialization (enabled=%d)", params->var_name[0] != 0); if (params->var_name[0]) { ts_auto_variable_t var = {0}; char full_var_name[96]; @@ -2361,7 +2423,7 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch strncpy(var.source_id, params->var_name, sizeof(var.source_id) - 1); var.flags = 0; - TS_LOGI(TAG, "Initializing 7 variables for source: %s", params->var_name); + TS_LOGD(TAG, "Initializing SSH variables (count=7)"); /* 初始化 status 为 "running" */ snprintf(full_var_name, sizeof(full_var_name), "%s.status", params->var_name); @@ -2412,7 +2474,7 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch var.value.int_val = (int32_t)(esp_timer_get_time() / 1000000); /* 秒级时间戳 */ ts_variable_upsert(&var); - TS_LOGI(TAG, "Initialized variables for %s (status=running)", params->var_name); + TS_LOGD(TAG, "SSH variables initialized (status=running)"); for (unsigned i = 0; i < sizeof(exec_variable_suffixes) / sizeof(exec_variable_suffixes[0]); ++i) { snprintf(full_var_name, sizeof(full_var_name), "%s.%s", params->var_name, exec_variable_suffixes[i]); params->variable_instances[i] = ts_variable_instance(full_var_name); @@ -2442,9 +2504,9 @@ static esp_err_t ts_webui_ssh_exec_start_ex_impl(ts_ws_operation_t *op, const ch *session_id = params->session_id; } - TS_LOGI(TAG, "SSH exec started (extended): session_id=%lu, host=%s, cmd=%s, expect=%s", - (unsigned long)params->session_id, host, command, - params->expect_pattern ? params->expect_pattern : "(none)"); + TS_LOGI(TAG, "SSH exec started (extended): session_id=%lu, host=%s, command_bytes=%u, has_expect=%d", + (unsigned long)params->session_id, host, (unsigned)strlen(command), + params->expect_pattern != NULL); return ESP_OK; } @@ -2490,6 +2552,33 @@ esp_err_t ts_webui_ssh_exec_cancel(uint32_t session_id) return ESP_OK; /* accepted request, not remote termination confirmation */ } +static esp_err_t exec_cancel_lookup(uint32_t id, const char *boot, const char *key, + const uint32_t *caller_session_id) +{ + bool has_receipt = boot || key; + if (!id || (caller_session_id && !*caller_session_id) || + (!caller_session_id && !has_receipt) || + (has_receipt && (!boot || !key || strlen(boot) != 32 || strlen(key) != 32))) + return ESP_ERR_INVALID_STATE; + portENTER_CRITICAL(&s_exec_cache_lock); + bool owned = s_exec_active && s_exec_active->id == id && + (!caller_session_id || s_exec_active->owner_session_id == *caller_session_id) && + (!has_receipt || exec_receipt_matches(s_exec_active, id, boot, key)); + portEXIT_CRITICAL(&s_exec_cache_lock); + if (!owned) return ESP_ERR_INVALID_STATE; + /* IDs are monotonic within this boot. Completion between verification and + * cancellation may reject, but cannot target a replacement operation. */ + return ts_webui_ssh_exec_cancel(id); +} +esp_err_t ts_webui_ssh_exec_cancel_with_receipt(uint32_t id, const char *boot, const char *key) { + return exec_cancel_lookup(id,boot,key,NULL); +} +esp_err_t ts_webui_ssh_exec_cancel_for_session(uint32_t id, const char *boot, const char *key, + uint32_t caller_session_id) { + return exec_cancel_lookup(id,boot,key,&caller_session_id); +} + + bool ts_webui_ssh_exec_is_running(uint32_t session_id) { ts_ws_operation_t *op=ts_ws_op_acquire(TS_WS_OP_EXEC,session_id); diff --git a/components/ts_webui/src/ts_ws_operation.c b/components/ts_webui/src/ts_ws_operation.c index 7f4007e6..2234a3f4 100644 --- a/components/ts_webui/src/ts_ws_operation.c +++ b/components/ts_webui/src/ts_ws_operation.c @@ -12,6 +12,7 @@ struct ts_ws_operation { ts_ws_op_kind_t kind; bool initializing, builder; bool business_accepted; + uint32_t owner_session_id; ts_ws_business_phase_t business; ts_ws_stop_reason_t first_stop; unsigned stop_reasons; @@ -27,9 +28,6 @@ static portMUX_TYPE s_op_lock = portMUX_INITIALIZER_UNLOCKED; static ts_ws_operation_t s_ops[TS_WS_OP_KINDS]; static uint64_t s_op_sequence, s_op_delivery; static bool s_op_accepting, s_op_tick; -static ts_perm_level_t output_level(ts_ws_operation_t *op) { - return op->kind == TS_WS_OP_EXEC ? TS_PERM_READ : TS_PERM_ROOT; -} #define OP_LOCK() portENTER_CRITICAL(&s_op_lock) #define OP_UNLOCK() portEXIT_CRITICAL(&s_op_lock) @@ -51,12 +49,20 @@ ts_ws_operation_t *ts_ws_op_create(ts_ws_op_kind_t kind, ts_ws_peer_t peer, esp_ OP_UNLOCK(); esp_err_t ret=kind!=TS_WS_OP_EXEC ? ts_ws_reserve(&peer,1,true,4096,&op->terminal) : ts_ws_result_reserve(TS_WS_LEGACY_BYTES,&op->terminal); - if (ret == ESP_OK) ts_ws_message_require(op->terminal.message, output_level(op)); + if (ret == ESP_OK) { + ts_ws_message_require(op->terminal.message, TS_PERM_ROOT); + if(kind==TS_WS_OP_EXEC)ts_ws_message_require_session(op->terminal.message,0); + } OP_LOCK(); op->initializing=false; OP_UNLOCK(); if(error)*error=ret; if(ret!=ESP_OK) { ts_ws_op_discard(op); ts_ws_op_executor_done(op); return NULL; } return op; } +void ts_ws_op_set_exec_owner(ts_ws_operation_t *op, uint32_t session_id) { + OP_LOCK();assert(op->kind==TS_WS_OP_EXEC && op->ledger.phase==OP_STARTING); + op->owner_session_id=session_id;OP_UNLOCK(); + ts_ws_message_require_session(op->terminal.message,session_id); +} void ts_ws_op_bind(ts_ws_operation_t *op,void *data,void (*destroy)(void *)) { OP_LOCK(); assert(op->ledger.phase==OP_STARTING && !op->data);op->data=data;op->destroy=destroy;OP_UNLOCK(); } @@ -99,7 +105,7 @@ static bool close_locked(ts_ws_operation_t *op) { } static void close_snapshot(ts_ws_operation_t *op) { if(op->kind!=TS_WS_OP_EXEC){op->terminal_peers[0]=op->peer;op->terminal_count=ts_ws_peer_authorized(op->peer,TS_PERM_ROOT)?1:0;} - else op->terminal_count=ts_ws_peer_snapshot_for_level(op->terminal_peers,TS_WS_CONNECTIONS,TS_PERM_READ); + else op->terminal_count=ts_ws_peer_snapshot_for_session(op->terminal_peers,TS_WS_CONNECTIONS,TS_PERM_ROOT,op->owner_session_id); } bool ts_ws_op_close_begin(ts_ws_operation_t *op) { OP_LOCK();bool winner=close_locked(op);OP_UNLOCK(); @@ -148,14 +154,15 @@ bool ts_ws_op_output_begin(ts_ws_operation_t *op,ts_ws_output_ticket_t *t) { if(ok){op->ledger.preparing++;t->sequence=++op->ledger.tickets;op->ledger.refs++;t->op=op;}OP_UNLOCK(); if(!ok)return false; if(op->kind!=TS_WS_OP_EXEC){t->peers[0]=op->peer;t->count=ts_ws_peer_authorized(op->peer,TS_PERM_ROOT)?1:0;} - else t->count=ts_ws_peer_snapshot_for_level(t->peers,TS_WS_CONNECTIONS,TS_PERM_READ); + else t->count=ts_ws_peer_snapshot_for_session(t->peers,TS_WS_CONNECTIONS,TS_PERM_ROOT,op->owner_session_id); TS_WS_TEST_POINT("B02");return true; } static bool publish_output(ts_ws_output_ticket_t *t,const char *json,bool retryable) { if(!t->op)return false; ts_ws_operation_t *op=t->op;ts_ws_message_t *m=NULL; if(t->count && json)m=ts_ws_message_text(json,strlen(json)); - ts_ws_message_require(m, output_level(op)); + ts_ws_message_require(m, TS_PERM_ROOT); + if(op->kind==TS_WS_OP_EXEC)ts_ws_message_require_session(m,op->owner_session_id); uint64_t tokens[TS_WS_CONNECTIONS]={0};bool winner=false,registered=false; TS_WS_TEST_POINT("B03"); OP_LOCK(); diff --git a/components/ts_webui/src/ts_ws_subscriptions.c b/components/ts_webui/src/ts_ws_subscriptions.c index 508a5d31..7404cfb2 100644 --- a/components/ts_webui/src/ts_ws_subscriptions.c +++ b/components/ts_webui/src/ts_ws_subscriptions.c @@ -3,6 +3,7 @@ #include "ts_ws_transport.h" #include "ts_ws_operation.h" #include "ts_api.h" +#include "ts_ota.h" #include "ts_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" @@ -314,6 +315,26 @@ static void telemetry_worker(void *arg) portENTER_CRITICAL(&s_lock); s_worker=NULL; portEXIT_CRITICAL(&s_lock); vTaskDelete(NULL); } +static cJSON *ota_progress_event(const ts_event_t *event) +{ + if (event->id != TS_EVENT_OTA_PROGRESS || event->data_size != sizeof(ts_ota_progress_t)) return NULL; + ts_ota_progress_t progress; + memcpy(&progress, event->data, sizeof(progress)); + if ((unsigned)progress.state > TS_OTA_STATE_ERROR || progress.progress_percent > 100 || + !memchr(progress.status_msg, 0, sizeof(progress.status_msg))) return NULL; + static const char *states[] = {"idle", "checking", "downloading", "verifying", "writing", "pending_reboot", "error"}; + cJSON *data = cJSON_CreateObject(); + if (!data || !cJSON_AddStringToObject(data, "state", states[progress.state]) || + !cJSON_AddNumberToObject(data, "percent", progress.progress_percent) || + !cJSON_AddNumberToObject(data, "received_size", progress.received_size) || + !cJSON_AddNumberToObject(data, "total_size", progress.total_size) || + !cJSON_AddStringToObject(data, "message", progress.status_msg)) { + cJSON_Delete(data); + return NULL; + } + return data; +} + static void event_handler(const ts_event_t *event, void *arg) { unsigned topic=(unsigned)(uintptr_t)arg; @@ -326,7 +347,7 @@ static void event_handler(const ts_event_t *event, void *arg) if(topic==0 || !demand) return; if(!event || !event->data || !event->data_size) return; /* Parse bounded event bytes, not an assumed NUL terminated buffer. */ - cJSON *data=cJSON_ParseWithLength(event->data,event->data_size); + cJSON *data=topic==9 ? ota_progress_event(event) : cJSON_ParseWithLength(event->data,event->data_size); if(data) {ts_ws_broadcast_to_topic(topics[topic].name,data);cJSON_Delete(data);} } esp_err_t ts_ws_subscriptions_init(void) diff --git a/components/ts_webui/src/ts_ws_transport.c b/components/ts_webui/src/ts_ws_transport.c index a26a2613..4ff991cd 100644 --- a/components/ts_webui/src/ts_ws_transport.c +++ b/components/ts_webui/src/ts_ws_transport.c @@ -26,7 +26,7 @@ static bool s_peer_bound[TS_WS_CONNECTIONS]; static int s_log_levels[TS_WS_CONNECTIONS]; static uint64_t s_log_revisions[TS_WS_CONNECTIONS]; typedef enum {MSG_ORDINARY, MSG_TOPIC, MSG_RESULT, MSG_POWER, MSG_POWER_TICK} message_kind_t; -struct ts_ws_message { unsigned refs; char *text; size_t len, capacity; message_kind_t kind; ts_perm_level_t required_level; }; +struct ts_ws_message { unsigned refs; char *text; size_t len, capacity; message_kind_t kind; ts_perm_level_t required_level; bool session_scoped; uint32_t required_session; }; static char s_power_payloads[TS_WS_POWER_SLOTS][TS_WS_POWER_BYTES]; static unsigned s_power_bytes; static ts_ws_transport_stats_t s_tx_stats; @@ -110,7 +110,7 @@ esp_err_t ts_ws_peer_bind_session(ts_ws_peer_t peer, uint32_t session_id) portEXIT_CRITICAL(&s_lock); return ret; } -bool ts_ws_peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required) +static bool peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required, const uint32_t *expected_session) { uint32_t session_id = 0; bool valid = false; @@ -123,7 +123,7 @@ bool ts_ws_peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required) } } portEXIT_CRITICAL(&s_lock); - if (!valid) return false; + if (!valid || (expected_session && (!*expected_session || session_id != *expected_session))) return false; #ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED if (required == TS_PERM_NONE) return true; ts_session_t session; @@ -155,6 +155,14 @@ bool ts_ws_peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required) return true; #endif } +bool ts_ws_peer_authorized(ts_ws_peer_t peer, ts_perm_level_t required) +{ + return peer_authorized(peer, required, NULL); +} +bool ts_ws_peer_authorized_for_session(ts_ws_peer_t peer, ts_perm_level_t required, uint32_t session_id) +{ + return peer_authorized(peer, required, &session_id); +} void ts_ws_peer_close(ts_ws_peer_t peer) { ts_ws_closed_t closed = NULL; @@ -209,7 +217,7 @@ static ts_ws_message_t *message_alloc(size_t capacity, message_kind_t kind) size_t used=kind>=MSG_POWER ? s_power_bytes : s_tx_stats.bytes-s_power_bytes; size_t limit=kind>=MSG_POWER ? TS_WS_POWER_BUDGET : TS_WS_TOTAL_BYTES-TS_WS_POWER_BUDGET; for (unsigned i=begin; capacity <= limit-used && irefs = 1; m->capacity = capacity; m->kind=kind; m->required_level=TS_PERM_NONE; + m = &s_messages[i]; m->refs = 1; m->capacity = capacity; m->kind=kind; m->required_level=TS_PERM_NONE; m->session_scoped=false; m->required_session=0; if(kind>=MSG_POWER)s_power_bytes+=capacity; s_tx_stats.bytes += capacity; if(s_tx_stats.bytes > s_tx_stats.bytes_high) s_tx_stats.bytes_high=s_tx_stats.bytes; @@ -262,6 +270,10 @@ void ts_ws_message_require(ts_ws_message_t *message, ts_perm_level_t required) { if (message) message->required_level = required; } +void ts_ws_message_require_session(ts_ws_message_t *message, uint32_t session_id) +{ + if (message) { message->session_scoped = true; message->required_session = session_id; } +} ts_ws_message_t *ts_ws_message_json(const char *topic, const cJSON *data, int64_t timestamp) { ts_ws_message_t *m = message_alloc(TS_WS_FRAME_BYTES, true); @@ -325,7 +337,9 @@ static void deliver(void *arg) * on this same task. The stop owner keeps the server alive until refs drain. */ if (valid && (!d->check || d->check(d->revision, d->delivery)) && httpd_ws_get_fd_info(d->peer.server, d->peer.fd) == HTTPD_WS_CLIENT_WEBSOCKET) { - if (!ts_ws_peer_authorized(d->peer, d->message->required_level)) { + if (!(d->message->session_scoped ? + ts_ws_peer_authorized_for_session(d->peer, d->message->required_level, d->message->required_session) : + ts_ws_peer_authorized(d->peer, d->message->required_level))) { ret = ESP_ERR_NOT_ALLOWED; } else { httpd_ws_frame_t frame = {.type = HTTPD_WS_TYPE_TEXT, @@ -524,9 +538,18 @@ static esp_err_t broadcast_filtered(const httpd_ws_frame_t *frame, int level) if(!s_server.stopping) for(unsigned i=0;i= 0) { + unsigned candidates = n; + n = 0; + for(unsigned i=0;ipayload,frame->len); if(!m) return ESP_ERR_NO_MEM; + if(level >= 0) m->required_level = TS_PERM_ADMIN; esp_err_t ret=ESP_OK; for(unsigned i=0;isvg:not(.wm){flex:none} .user-menu{gap:6px} -.main{margin-top:118px;padding:10px;border-radius:22px} +.main{padding:10px;border-radius:22px} } /*END*/ @@ -408,6 +408,14 @@ input[type=radio]:checked{border:5px solid var(--accent-text)} .stat-st.warn i{background:var(--warn-dot)} /* ===== 页面:指令 ===== */ +.command-empty{min-height:316px;padding:36px 24px 44px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center} +.command-empty-icon{display:grid;place-items:center;width:48px;height:48px;margin-bottom:18px;color:var(--ink-2)} +.command-empty-icon>.i{width:44px;height:44px} +.command-empty-title{margin:0;font-size:16px;line-height:24px;font-weight:600;color:var(--ink)} +.command-empty-description{max-width:360px;margin:8px 0 0;font-size:13px;line-height:21px;color:var(--ink-3)} +.command-empty-action{margin-top:24px} +.command-empty-action>.i{width:15px;height:15px} +@media(max-width:600px){.command-empty{min-height:284px;padding:30px 14px 38px}.command-empty-description{max-width:260px}} .host-selector{display:flex;gap:12px;flex-wrap:wrap} .host-selector>.empty{flex:1 1 100%} .host-card{cursor:default} diff --git a/components/ts_webui/web/index.html b/components/ts_webui/web/index.html index 12fd9207..30a47baa 100644 --- a/components/ts_webui/web/index.html +++ b/components/ts_webui/web/index.html @@ -5,7 +5,7 @@ TianshanOS - + diff --git a/components/ts_webui/web/js/api.js b/components/ts_webui/web/js/api.js index 8ae44d84..25f2ea70 100644 --- a/components/ts_webui/web/js/api.js +++ b/components/ts_webui/web/js/api.js @@ -1,6 +1,6 @@ /** * TianshanOS API Client - * + * * 统一的 Core API 调用客户端,支持所有已注册的 API 端点 */ @@ -156,7 +156,7 @@ const FAILURE_CODE_TOKEN = {1: 'invalid_request', 2: 'not_found', 3: 'no_permiss 7: 'no_detail', 8: 'not_supported', 9: 'hardware_failed', 10: 'target_unreachable', 11: 'auth_required'}; const FAILURE_CODE_NAME = {INVALID_ARG: 1, NOT_FOUND: 2, NO_PERMISSION: 3, BUSY: 4, TIMEOUT: 5, NO_MEM: 6, INTERNAL: 7, NOT_SUPPORTED: 8, HARDWARE: 9, CONNECTION: 10, AUTH: 11}; -const FAILURE_UNCONFIRMED = new Set(['result_unknown', 'save_outcome_unknown']); +const FAILURE_UNCONFIRMED = new Set(['credential_write_uncertain', 'file_replace_uncertain', 'result_unknown', 'save_outcome_unknown']); function describeFailure({op, phase = 'failed', params = {}, result = null, error = null, token = null, endpoint = '', write} = {}) { const ready = typeof i18n !== 'undefined' && typeof t === 'function'; // numbers the device sends in `data` (e.g. an HTTP status) can fill the placeholders of the reason's text; the caller's params win @@ -222,7 +222,7 @@ class TianShanAPI { this.token = localStorage.getItem('ts_token'); this.username = localStorage.getItem('ts_username'); this.level = localStorage.getItem('ts_level'); - + // 检查 token 是否过期 const expires = localStorage.getItem('ts_expires'); if (expires && Date.now() > parseInt(expires)) { @@ -244,7 +244,7 @@ class TianShanAPI { localStorage.removeItem('ts_expires'); window.dispatchEvent(new CustomEvent('authChanged')); } - + // Only the latest generation is retained; no credentials or key material. recordKeyGeneration(stage, fields = {}, requestId = this.keyGenerationTrace?.requestId) { const trace = this.keyGenerationTrace; @@ -259,27 +259,28 @@ class TianShanAPI { const headers = { 'Content-Type': 'application/json' }; - - if (this.token) { - headers['Authorization'] = `Bearer ${this.token}`; + + const requestToken = this.token; + if (requestToken) { + headers['Authorization'] = `Bearer ${requestToken}`; } - + // 创建超时控制器 const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); - + const options = { method, headers, signal: controller.signal }; - + if (data && method !== 'GET') { options.body = JSON.stringify(data); // 调试:打印请求体大小 console.debug(`API ${method} ${endpoint}: body size = ${options.body.length} bytes`); } - + let httpStatus; const keyRequestId = endpoint === '/key/generate' && method === 'POST' ? data?.request_id : null; const traceKey = (stage, fields) => { @@ -299,7 +300,7 @@ class TianShanAPI { if (!response.ok) throw new ApiOperationError({error: text}, endpoint, {httpStatus: response.status}); throw parseErr; } - + traceKey('response_parsed', {code: typeof json?.code === 'number' ? json.code : null, generated: json?.data?.generated === true}); // 返回 JSON 响应,即使是错误码也返回(让调用者决定如何处理) if (!response.ok) throw new ApiOperationError(json, endpoint, {httpStatus: response.status}); @@ -323,7 +324,7 @@ class TianShanAPI { json.message = message; window.dispatchEvent(new CustomEvent('authExpired', { detail: { message } })); } - + return json; } catch (error) { traceKey('request_error', {kind: controller.signal.aborted ? 'timeout' : error.kind || (error instanceof SyntaxError ? 'format' : httpStatus >= 400 ? 'http' : 'network'), httpStatus}); @@ -341,16 +342,10 @@ class TianShanAPI { */ async call(apiName, params = null, method = null) { let endpoint = '/' + apiName.replace(/\./g, '/'); - - // 自动判断方法:有参数且非查询类用 POST - if (!method) { - const isQuery = apiName.includes('.list') || apiName.includes('.status') || - apiName.includes('.info') || apiName.includes('.get') || - apiName.includes('.version') || apiName.includes('.partitions') || - apiName.includes('.progress') || apiName.includes('.stats'); - method = (params && !isQuery) ? 'POST' : 'GET'; - } - + + // Read and write APIs accept POST. Keep explicit GET available. + method = method || 'POST'; + // GET 请求时,将 params 转为 query string if (method === 'GET' && params) { const queryParams = new URLSearchParams(); @@ -365,14 +360,14 @@ class TianShanAPI { } params = null; // GET 请求不发送 body } - + return this.request(endpoint, method, params); } - + // ===================================================================== // 认证 API // ===================================================================== - + async login(username, password) { const result = await this.call('auth.login', { username, password }, 'POST'); if (result.code === 0 && (typeof result.data?.token !== 'string' || !result.data.token)) { @@ -391,7 +386,7 @@ class TianShanAPI { } return result; } - + async logout() { // request() captures Authorization before local credentials are cleared. const pending = this.token ? this.call('auth.logout', {token: this.token}, 'POST') : null; @@ -415,13 +410,31 @@ class TianShanAPI { } return { valid: false }; } - + + async passwordUpdate(endpoint, params, ownAccount) { + const token = this.token; + let result; + try { + result = await this.call(endpoint, {token, ...params}, 'POST'); + return result; + } catch (error) { + result = error; + throw error; + } finally { + const revoked = result?.code === 0 && result.data?.reauth_required === true; + const uncertain = ownAccount && apiErrorReason(result) === 'credential_write_uncertain'; + if ((revoked || uncertain) && this.token === token) { + this.clearAuth(); + window.dispatchEvent(new CustomEvent('authExpired')); + } + } + } + async changePassword(oldPassword, newPassword) { - return this.call('auth.change_password', { - token: this.token, + return this.passwordUpdate('auth.change_password', { old_password: oldPassword, new_password: newPassword - }, 'POST'); + }, true); } async setAdminPassword(newPassword) { @@ -432,10 +445,7 @@ class TianShanAPI { } async setRootPassword(newPassword) { - return this.call('auth.root.set_password', { - token: this.token, - new_password: newPassword - }, 'POST'); + return this.passwordUpdate('auth.root.set_password', {new_password: newPassword}, true); } async resetAdminPassword() { @@ -443,7 +453,7 @@ class TianShanAPI { token: this.token }, 'POST'); } - + isLoggedIn() { if (!this.token) { // 尝试从 localStorage 恢复 @@ -470,22 +480,22 @@ class TianShanAPI { } return true; } - + getUsername() { return this.username || localStorage.getItem('ts_username'); } - + getLevel() { return this.level || localStorage.getItem('ts_level'); } - + /** * 检查是否有 root 权限(可访问终端、自动化、指令) */ isRoot() { return this.getLevel() === 'root'; } - + /** * 检查是否是 admin 用户 */ @@ -493,158 +503,157 @@ class TianShanAPI { const level = this.getLevel(); return level === 'admin' || level === 'root'; } - + // ===================================================================== // 系统 API (system.*) // ===================================================================== - - async getSystemInfo() { return this.call('system.info'); } - async getMemoryInfo() { return this.call('system.memory'); } - async getMemoryDetail() { return this.call('system.memory_detail'); } - async getTasks() { return this.call('system.tasks'); } + + async getSystemInfo() { return this.call('system.info', null, 'GET'); } + async getMemoryInfo() { return this.call('system.memory', null, 'GET'); } + async getMemoryDetail() { return this.call('system.memory_detail', null, 'GET'); } + async getTasks() { return this.call('system.tasks', null, 'GET'); } async reboot(delay = 0) { return this.call('system.reboot', { delay }, 'POST'); } - + // ===================================================================== // 时间 API (time.*) // ===================================================================== - - async timeInfo() { return this.call('time.info'); } + + async timeInfo() { return this.call('time.info', null, 'GET'); } async timeSync(timestampMs) { return this.call('time.sync', { timestamp_ms: timestampMs }, 'POST'); } async timeSetNtp(server, index = 0) { return this.call('time.set_ntp', { server, index }, 'POST'); } async timeSetTimezone(timezone) { return this.call('time.set_timezone', { timezone }, 'POST'); } async timeForceSync() { return this.call('time.force_sync', null, 'POST'); } - + // ===================================================================== // 配置 API (config.*) // ===================================================================== - + // 基础配置 - async configGet(key) { return this.call('config.get', { key }); } + async configGet(key) { return this.call('config.get', { key }, 'GET'); } async configSet(key, value, persist = false) { return this.call('config.set', { key, value, persist }, 'POST'); } async configDelete(key) { return this.call('config.delete', { key }, 'POST'); } - async configList(prefix = '') { return this.call('config.list', prefix ? { prefix } : null); } + async configList(prefix = '') { return this.call('config.list', prefix ? { prefix } : null, 'GET'); } async configSave() { return this.call('config.save', null, 'POST'); } - + // 模块化配置 - async configModuleList() { return this.call('config.module.list'); } - async configModuleShow(module) { return this.call('config.module.show', { module }); } + async configModuleList() { return this.call('config.module.list', null, 'GET'); } + async configModuleShow(module) { return this.call('config.module.show', { module }, 'GET'); } async configModuleSet(module, key, value) { return this.call('config.module.set', { module, key, value }, 'POST'); } async configModuleSave(module = null) { return this.call('config.module.save', module ? { module } : null, 'POST'); } async configModuleReset(module, persist = true) { return this.call('config.module.reset', { module, persist }, 'POST'); } - async configSync() { return this.call('config.sync', null, 'POST'); } - + // ===================================================================== // 服务 API (service.*) // ===================================================================== - - async serviceList() { return this.call('service.list'); } - async serviceStatus(name) { return this.call('service.status', { name }); } + + async serviceList() { return this.call('service.list', null, 'GET'); } + async serviceStatus(name) { return this.call('service.status', { name }, 'GET'); } async serviceStart(name) { return this.call('service.start', { name }, 'POST'); } async serviceStop(name) { return this.call('service.stop', { name }, 'POST'); } async serviceRestart(name) { return this.call('service.restart', { name }, 'POST'); } - + // ===================================================================== // LED API (led.*) // ===================================================================== - - async ledList() { return this.call('led.list'); } + + async ledList() { return this.call('led.list', null, 'GET'); } async ledBrightness(device, brightness) { return this.call('led.brightness', { device, brightness }, 'POST'); } async ledClear(device) { return this.call('led.clear', { device }, 'POST'); } async ledSet(device, index, color) { return this.call('led.set', { device, index, color }, 'POST'); } async ledFill(device, color) { return this.call('led.fill', { device, color }, 'POST'); } - async ledEffectList(device = null) { return this.call('led.effect.list', device ? { device } : null); } + async ledEffectList(device = null) { return this.call('led.effect.list', device ? { device } : null, 'GET'); } async ledEffectStart(device, effect, params = {}) { return this.call('led.effect.start', { device, effect, ...params }, 'POST'); } async ledEffectStop(device) { return this.call('led.effect.stop', { device }, 'POST'); } - async ledColorParse(color) { return this.call('led.color.parse', { color }); } - async ledFilterList() { return this.call('led.filter.list'); } + async ledColorParse(color) { return this.call('led.color.parse', { color }, 'GET'); } + async ledFilterList() { return this.call('led.filter.list', null, 'GET'); } async ledFilterStart(device, filter, speed = 50) { return this.call('led.filter.start', { device, filter, speed }, 'POST'); } async ledFilterStop(device) { return this.call('led.filter.stop', { device }, 'POST'); } async ledSave(device) { return this.call('led.save', { device }, 'POST'); } - + // Matrix-specific LED APIs async ledImage(path, device = 'matrix', center = 'image') { return this.call('led.image', { device, path, center }, 'POST'); } async ledQrcode(text, options = {}) { return this.call('led.qrcode', { device: 'matrix', text, ...options }, 'POST'); } async ledText(text, options = {}) { return this.call('led.text', { device: 'matrix', text, ...options }, 'POST'); } async ledTextStop(device = 'matrix') { return this.call('led.text.stop', { device }, 'POST'); } - + // Color Correction APIs - async ledColorCorrectionGet() { return this.call('led.color_correction.get'); } + async ledColorCorrectionGet() { return this.call('led.color_correction.get', null, 'GET'); } async ledColorCorrectionSet(config) { return this.call('led.color_correction.set', config, 'POST'); } async ledColorCorrectionReset() { return this.call('led.color_correction.reset', null, 'POST'); } async ledColorCorrectionExport() { return this.call('led.color_correction.export', null, 'POST'); } async ledColorCorrectionImport() { return this.call('led.color_correction.import', null, 'POST'); } - + // ===================================================================== // 网络 API (network.*, dhcp.*, nat.*) // ===================================================================== - + // 综合网络状态 (包含 ethernet, wifi_sta, wifi_ap) - async networkStatus() { return this.call('network.status'); } + async networkStatus() { return this.call('network.status', null, 'GET'); } async lpmuAccessStart(sudoPassword) { return this.call('network.lpmu_access.start', { sudo_password: sudoPassword }, 'POST'); } - async lpmuAccessStatus() { return this.call('network.lpmu_access.status'); } + async lpmuAccessStatus() { return this.call('network.lpmu_access.status', null, 'GET'); } async lpmuAccessLog(runId, offset = 0) { return this.call('network.lpmu_access.log', { run_id: runId, offset }, 'GET'); } - + // WiFi 相关 - async wifiMode(mode = null) { - return mode ? this.call('network.wifi.mode', { mode }, 'POST') : this.call('network.wifi.mode'); + async wifiMode(mode = null) { + return mode ? this.call('network.wifi.mode', { mode }, 'POST') : this.call('network.wifi.mode', null, 'POST'); } - async wifiScan() { return this.call('network.wifi.scan'); } + async wifiScan() { return this.call('network.wifi.scan', null, 'POST'); } async wifiConnect(ssid, password) { return this.call('network.wifi.connect', { ssid, password }, 'POST'); } async wifiDisconnect() { return this.call('network.wifi.disconnect', null, 'POST'); } - async wifiApConfig(ssid, password = '', channel = 6, hidden = false) { - return this.call('network.wifi.ap.config', { ssid, password, channel, hidden }, 'POST'); + async wifiApConfig(ssid, password = '', channel = 6, hidden = false) { + return this.call('network.wifi.ap.config', { ssid, password, channel, hidden }, 'POST'); } - async wifiApStations() { return this.call('network.wifi.ap.stations'); } - + async wifiApStations() { return this.call('network.wifi.ap.stations', null, 'GET'); } + // 以太网 - async ethStatus() { return this.call('network.eth.status'); } - + async ethStatus() { return this.call('network.eth.status', null, 'GET'); } + // 主机名 - async hostname(name = null) { - return name ? this.call('network.hostname', { hostname: name }, 'POST') : this.call('network.hostname'); + async hostname(name = null) { + return name ? this.call('network.hostname', { hostname: name }, 'POST') : this.call('network.hostname', null, 'POST'); } - + // DHCP 服务器 - async dhcpStatus(iface = null) { return this.call('dhcp.status', iface ? { interface: iface } : null); } - async dhcpClients(iface = null) { return this.call('dhcp.clients', iface ? { interface: iface } : null); } + async dhcpStatus(iface = null) { return this.call('dhcp.status', iface ? { interface: iface } : null, 'GET'); } + async dhcpClients(iface = null) { return this.call('dhcp.clients', iface ? { interface: iface } : null, 'GET'); } async dhcpStart(iface = 'ap') { return this.call('dhcp.start', { interface: iface }, 'POST'); } async dhcpStop(iface = 'ap') { return this.call('dhcp.stop', { interface: iface }, 'POST'); } - + // NAT 网关 - async natStatus() { return this.call('nat.status'); } + async natStatus() { return this.call('nat.status', null, 'GET'); } async natEnable() { return this.call('nat.enable', null, 'POST'); } async natDisable() { return this.call('nat.disable', null, 'POST'); } async natSave() { return this.call('nat.save', null, 'POST'); } - + // ===================================================================== // 设备 API (device.*, monitor.*, fan.*) // ===================================================================== - - async deviceStatus(name = null) { return this.call('device.status', name ? { name } : null); } + + async deviceStatus(name = null) { return this.call('device.status', name ? { name } : null, 'GET'); } async devicePower(name, on) { return this.call('device.power', { name, on }, 'POST'); } async deviceReset(name) { return this.call('device.reset', { name }, 'POST'); } - async agxStatus() { return this.call('monitor.status'); } - async agxData() { return this.call('monitor.data'); } - async fanStatus(id = null) { return this.call('fan.status', id !== null ? { id } : null); } + async agxStatus() { return this.call('monitor.status', null, 'GET'); } + async agxData() { return this.call('monitor.data', null, 'GET'); } + async fanStatus(id = null) { return this.call('fan.status', id !== null ? { id } : null, 'GET'); } async fanSet(id, duty) { return this.call('fan.set', { id, duty }, 'POST'); } async fanMode(id, mode) { return this.call('fan.mode', { id, mode }, 'POST'); } - + // ===================================================================== // 电源 API (power.*) // ===================================================================== - - async powerStatus() { return this.call('power.status'); } - async powerVoltage(channel = null) { return this.call('power.voltage', channel !== null ? { channel } : null); } - async powerStats() { return this.call('power.stats'); } - async powerProtectionStatus() { return this.call('power.protection.status'); } + + async powerStatus() { return this.call('power.status', null, 'GET'); } + async powerVoltage(channel = null) { return this.call('power.voltage', channel !== null ? { channel } : null, 'GET'); } + async powerStats() { return this.call('power.stats', null, 'GET'); } + async powerProtectionStatus() { return this.call('power.protection.status', null, 'GET'); } async powerProtectionSet(config) { return this.call('power.protection.set', config, 'POST'); } - async powerProtectionConfig() { return this.call('power.protection.config'); } - + async powerProtectionConfig() { return this.call('power.protection.config', null, 'GET'); } + // ===================================================================== // 存储/GPIO/温度 API // ===================================================================== - - async storageStatus() { return this.call('storage.status'); } + + async storageStatus() { return this.call('storage.status', null, 'GET'); } async storageMount() { return this.call('storage.mount', null, 'POST'); } async storageUnmount() { return this.call('storage.unmount', null, 'POST'); } async storageList(path = '/sdcard') { return this.call('storage.list', { path }, 'POST'); } @@ -653,7 +662,7 @@ class TianShanAPI { async storageMkdir(path) { return this.call('storage.mkdir', { path }, 'POST'); } async storageRename(from, to) { return this.call('storage.rename', { from, to }, 'POST'); } async storageInfo(path) { return this.call('storage.info', { path }, 'POST'); } - + /** * 下载文件 * @param {string} path - 文件路径 (如 /sdcard/test.txt) @@ -670,7 +679,7 @@ class TianShanAPI { } return response.blob(); } - + /** * 上传文件 * @param {string} path - 目标路径 (如 /sdcard/uploads/file.txt) @@ -690,18 +699,18 @@ class TianShanAPI { } return json; } - - async gpioList() { return this.call('gpio.list'); } - async gpioInfo(pin) { return this.call('gpio.info', { pin }); } - async tempStatus() { return this.call('temp.status'); } - + + async gpioList() { return this.call('gpio.list', null, 'GET'); } + async gpioInfo(pin) { return this.call('gpio.info', { pin }, 'GET'); } + async tempStatus() { return this.call('temp.status', null, 'GET'); } + // ===================================================================== // SSH/SFTP API // ===================================================================== - + // SSH 测试连接 - 支持密码或密钥认证 // options: { trust_new: bool, accept_changed: bool } - async sshTest(host, user, auth, port = 22, options = {}) { + async sshTest(host, user, auth, port = 22, options = {}) { const params = { host, user, port }; if (typeof auth === 'string') { params.password = auth; // 兼容旧调用方式 @@ -714,12 +723,12 @@ class TianShanAPI { params.trust_new = options.trust_new ?? false; // 新主机必须明确确认指纹 params.confirmed_fingerprint = options.confirmed_fingerprint; params.accept_changed = options.accept_changed ?? false; // 指纹变化是否接受(默认 false) - return this.call('ssh.test', params, 'POST'); + return this.call('ssh.test', params, 'POST'); } - + // SSH 执行命令 - 支持密码或密钥认证 // options: { trust_new: bool, accept_changed: bool } - async sshExec(host, user, auth, command, port = 22, options = {}) { + async sshExec(host, user, auth, command, port = 22, options = {}) { const params = { host, user, command, port }; if (typeof auth === 'string') { params.password = auth; // 兼容旧调用方式 @@ -732,140 +741,140 @@ class TianShanAPI { params.trust_new = options.trust_new ?? false; params.confirmed_fingerprint = options.confirmed_fingerprint; params.accept_changed = options.accept_changed ?? false; - return this.call('ssh.exec', params, 'POST'); + return this.call('ssh.exec', params, 'POST'); } - + // 部署公钥 - options: { trust_new, accept_changed } - async sshCopyid(host, user, password, keyid, port = 22, verify = true, options = {}) { - return this.call('ssh.copyid', { + async sshCopyid(host, user, password, keyid, port = 22, verify = true, options = {}) { + return this.call('ssh.copyid', { host, user, password, keyid, port, verify, active_version: options.active_version, trust_new: options.trust_new ?? true, // 部署沿用 0.5.1:首次自动信任新主机 confirmed_fingerprint: options.confirmed_fingerprint, accept_changed: options.accept_changed ?? false - }, 'POST'); + }, 'POST'); } - + // 撤销公钥 - options: { trust_new, accept_changed } - async sshRevoke(host, user, password, keyid, port = 22, options = {}) { - return this.call('ssh.revoke', { + async sshRevoke(host, user, password, keyid, port = 22, options = {}) { + return this.call('ssh.revoke', { host, user, password, keyid, port, trust_new: options.trust_new ?? false, confirmed_fingerprint: options.confirmed_fingerprint, accept_changed: options.accept_changed ?? false - }, 'POST'); + }, 'POST'); } async sshKeygen(id, type = 'ecdsa', comment = '') { return this.call('ssh.keygen', { id, type, comment }, 'POST'); } async sftpLs(host, user, password, path, port = 22) { return this.call('sftp.ls', { host, user, password, path, port }, 'POST'); } - + // ===================================================================== // Key Management API // ===================================================================== - - async keyList() { return this.call('key.list'); } - async keyInfo(id) { return this.call('key.info', { id }); } - async keyGenerate(id, type = 'rsa2048', comment = '', exportable = false, alias = '', hidden = false) { + + async keyList() { return this.call('key.list', null, 'GET'); } + async keyInfo(id) { return this.call('key.info', { id }, 'GET'); } + async keyGenerate(id, type = 'rsa2048', comment = '', exportable = false, alias = '', hidden = false) { const request_id = 'kg-' + Date.now().toString(36) + '-' + (this.keyGenerationSequence = (this.keyGenerationSequence || 0) + 1).toString(36); this.keyGenerationTrace = {requestId: request_id, id, events: []}; this.recordKeyGeneration('submit'); return this.call('key.generate', { id, type, comment, exportable, alias, hidden, request_id }, 'POST'); } async keyDelete(id) { return this.call('key.delete', { id }, 'POST'); } - async keyExport(id) { return this.call('key.export', { id }); } + async keyExport(id) { return this.call('key.export', { id }, 'GET'); } async keyExportPrivate(id) { return this.call('key.exportPrivate', { id }, 'POST'); } - + // ===================================================================== // Known Hosts API // ===================================================================== - - async hostsList() { return this.call('hosts.list'); } - async hostsInfo(host, port = 22) { return this.call('hosts.info', { host, port }); } + + async hostsList() { return this.call('hosts.list', null, 'GET'); } + async hostsInfo(host, port = 22) { return this.call('hosts.info', { host, port }, 'GET'); } async hostsRemove(host, port = 22) { return this.call('hosts.remove', { host, port }, 'POST'); } async hostsUpdate(host, port = 22) { return this.call('hosts.update', { host, port }, 'POST'); } async hostsClear() { return this.call('hosts.clear', {}, 'POST'); } - + // ===================================================================== // Certificate (PKI) Management API // ===================================================================== - + /** 获取 HTTPS 证书 PKI 状态 */ - async certStatus() { return this.call('cert.status'); } - + async certStatus() { return this.call('cert.status', null, 'GET'); } + /** 生成 ECDSA P-256 密钥对 */ - async certGenerateKeypair(force = false) { - return this.call('cert.generate_keypair', { force }, 'POST'); + async certGenerateKeypair(force = false) { + return this.call('cert.generate_keypair', { force }, 'POST'); } - + /** 生成证书签名请求 (CSR) */ - async certGenerateCSR(opts = {}) { - return this.call('cert.generate_csr', opts, 'POST'); + async certGenerateCSR(opts = {}) { + return this.call('cert.generate_csr', opts, 'POST'); } - + /** 安装签发的证书 */ - async certInstall(certPem) { - return this.call('cert.install', { cert_pem: certPem }, 'POST'); + async certInstall(certPem) { + return this.call('cert.install', { cert_pem: certPem }, 'POST'); } - + /** 安装 CA 证书链 */ - async certInstallCA(caPem) { - return this.call('cert.install_ca', { ca_pem: caPem }, 'POST'); + async certInstallCA(caPem) { + return this.call('cert.install_ca', { ca_pem: caPem }, 'POST'); } - + /** 获取设备证书 PEM */ - async certGetCertificate() { - return this.call('cert.get_certificate'); + async certGetCertificate() { + return this.call('cert.get_certificate', null, 'GET'); } - + /** 删除所有 PKI 凭证(需要 confirm=true) */ - async certDelete() { - return this.call('cert.delete', { confirm: true }, 'POST'); + async certDelete() { + return this.call('cert.delete', { confirm: true }, 'POST'); } - + // ===================================================================== // Config Pack API // ===================================================================== - + /** 获取配置包系统信息 */ - async configPackInfo() { - return this.call('config.pack.info'); + async configPackInfo() { + return this.call('config.pack.info', null, 'GET'); } - + /** 导出设备证书(供他人加密配置给本设备) */ - async configPackExportCert() { - return this.call('config.pack.export_cert'); + async configPackExportCert() { + return this.call('config.pack.export_cert', null, 'GET'); } - + /** 验证 .tscfg 配置包签名 */ - async configPackVerify(content = null, path = null) { + async configPackVerify(content = null, path = null) { const params = {}; if (content) params.content = content; if (path) params.path = path; - return this.call('config.pack.verify', params, 'POST'); + return this.call('config.pack.verify', params, 'POST'); } - + /** 导入并解密 .tscfg 配置包 */ - async configPackImport(content = null, path = null, apply = false) { + async configPackImport(content = null, path = null, apply = false) { const params = { apply }; if (content) params.content = content; if (path) params.path = path; - return this.call('config.pack.import', params, 'POST'); + return this.call('config.pack.import', params, 'POST'); } - + /** 导出配置为加密 .tscfg(仅 Developer 设备可用) */ - async configPackExport(name, content, recipientCert, description = null, savePath = null) { - const params = { - name, + async configPackExport(name, content, recipientCert, description = null, savePath = null) { + const params = { + name, content, recipient_cert: recipientCert }; if (description) params.description = description; if (savePath) params.save_path = savePath; - return this.call('config.pack.export', params, 'POST'); + return this.call('config.pack.export', params, 'POST'); } - + /** 列出目录中的 .tscfg 文件 */ - async configPackList(path = '/sdcard/config') { - return this.call('config.pack.list', { path }); + async configPackList(path = '/sdcard/config') { + return this.call('config.pack.list', { path }, 'GET'); } } diff --git a/components/ts_webui/web/js/app.js b/components/ts_webui/web/js/app.js index 8cfb8638..c9d707be 100644 --- a/components/ts_webui/web/js/app.js +++ b/components/ts_webui/web/js/app.js @@ -77,7 +77,7 @@ function renderConfigurationSummary() { async function refreshConfigurationStatus(check = false) { const current = configurationRead('config-status'); const endpoint = check ? 'automation.config.refresh' : 'automation.config.status'; - const result = await api.call(endpoint, {}); + const result = await api.call(endpoint, {}, check ? 'POST' : 'GET'); if (!current()) return null; await configurationResult(result); requireApiSuccess(result, endpoint); @@ -104,7 +104,7 @@ function bindConfigurationEditor(modal, kind, version) { buttons.forEach(button => button.disabled = !context.version); context.ready = (async () => { if (!context.version) { - const result = requireApiSuccess(await api.call('automation.config.status', {}), 'automation.config.status'); + const result = requireApiSuccess(await api.call('automation.config.status', {}, 'GET'), 'automation.config.status'); if (!context.current()) return; context.version = result.data.active_version; context.source = result.data.source; } @@ -234,11 +234,11 @@ async function automationConfigOperation(operation, modal = document.getElementB box.textContent = t('toast.processing'); try { let result; - if (operation === 'check') result = await api.call('automation.config.refresh', {}); - else if (operation === 'backup') result = await api.call('automation.config.backup', {active_version: status.active_version}); - else if (operation === 'enable' || operation === 'disable') result = await api.call('automation.config.enable', {enabled: operation === 'enable', active_version: status.active_version}); + if (operation === 'check') result = await api.call('automation.config.refresh', {}, 'POST'); + else if (operation === 'backup') result = await api.call('automation.config.backup', {active_version: status.active_version}, 'POST'); + else if (operation === 'enable' || operation === 'disable') result = await api.call('automation.config.enable', {enabled: operation === 'enable', active_version: status.active_version}, 'POST'); else { - const preview = requireApiSuccess(await api.call('automation.config.preview', {operation}), 'automation.config.preview').data; + const preview = requireApiSuccess(await api.call('automation.config.preview', {operation}, 'POST'), 'automation.config.preview').data; if (!current() || !modal.isConnected) return; modal.classList.add('hidden'); const confirmation = confirmSheet({title: configText(operation), primary: configText(operation), @@ -249,7 +249,7 @@ async function automationConfigOperation(operation, modal = document.getElementB const accepted = await confirmation; dialog = null; modal.classList.remove('hidden'); if (!accepted || !current() || !modal.isConnected) return; - result = await api.call('automation.config.apply', {operation, active_version: preview.active_version, target_version: preview.target_version}); + result = await api.call('automation.config.apply', {operation, active_version: preview.active_version, target_version: preview.target_version}, 'POST'); } if (!current() || !modal.isConnected) return; await configurationResult(result); @@ -429,7 +429,7 @@ async function refreshUserVariables() { const body = document.getElementById('user-variables-body'), current = configurationRead('variables'); if (!body) return; try { - const result = requireApiSuccess(await api.call('automation.variables.list', {configured_only: true}), 'automation.variables.list'); + const result = requireApiSuccess(await api.call('automation.variables.list', {configured_only: true}, 'GET'), 'automation.variables.list'); if (!current() || !body.isConnected) return; const variables = (result.data.variables || []).map(variable => ({...variable, id: variable.name})); recordConfigurationList('variables', result.data, variables); @@ -919,7 +919,7 @@ async function submitPasswordChange() { async function updateFooterVersion() { try { - const versionData = await api.call('ota.version'); + const versionData = await api.call('ota.version', null, 'GET'); if (versionData?.data?.version) { const versionEl = document.getElementById('footer-version'); if (versionEl) { @@ -1528,7 +1528,7 @@ function usbMuxDisplayName(target) { async function refreshUsbMuxStatus() { const pageCurrent = capturePageValidity(); try { - const result = await api.call('device.usb.status'); + const result = await api.call('device.usb.status', null, 'GET'); if (!pageCurrent()) return; if (result.code === 0 && result.data) { usbMuxConfigured = result.data.configured !== false; @@ -1645,7 +1645,7 @@ let agxPowerState = false; // false=断电(HIGH), true=上电(LOW) async function refreshAgxPowerState() { const pageCurrent = capturePageValidity(); try { - const result = await api.call('device.status', { device: 'agx' }); + const result = await api.call('device.status', { device: 'agx' }, 'GET'); if (!pageCurrent()) return; if (result.code === 0 && result.data) { agxPowerState = result.data.state === 'on' || result.data.state === 'booting'; @@ -1737,7 +1737,7 @@ function startLpmuStatePolling(wasOnline = false) { pending = true; let reachable = null; try { - const result = requireApiSuccess(await api.call('device.ping', {host: '10.10.99.99', timeout: 1000}), 'device.ping'); + const result = requireApiSuccess(await api.call('device.ping', {host: '10.10.99.99', timeout: 1000}, 'POST'), 'device.ping'); if (typeof result.data?.reachable === 'boolean') reachable = result.data.reachable; } catch (error) { console.warn('LPMU reachability check failed', error); } finally { pending = false; } @@ -1789,7 +1789,7 @@ async function refreshLpmuState() { if (lpmuPollingInterval) return; try { - const result = await api.call('device.ping', { host: '10.10.99.99', timeout: 1000 }); + const result = await api.call('device.ping', { host: '10.10.99.99', timeout: 1000 }, 'POST'); if (!pageCurrent()) return; if (result.code === 0 && typeof result.data?.reachable === 'boolean') { lpmuState = result.data.reachable ? 'online' : 'offline'; @@ -2156,7 +2156,7 @@ async function applyTestTemp() { try { // 使用 temp.manual API 设置手动温度 - const result = await api.call('temp.manual', { temperature: temp }); + const result = await api.call('temp.manual', { temperature: temp }, 'POST'); if (result.code === 0) { showToast((typeof t === 'function' ? t('fan.testTempSet', { temp }) : `测试温度已设置为 ${temp}°C`), 'success'); @@ -2177,7 +2177,7 @@ async function applyTestTemp() { async function clearTestTemp() { try { // 清除手动温度,恢复自动模式 - const result = await api.call('temp.select', { source: 'variable' }); + const result = await api.call('temp.select', { source: 'variable' }, 'POST'); if (result.code === 0) { showToast((typeof t === 'function' ? t('fan.testTempCleared') : '测试温度已清除,恢复正常模式'), 'success'); @@ -2228,7 +2228,7 @@ async function setFanSpeed(id, speed) { async function setFanMode(id, mode) { try { - requireApiSuccess(await api.call('fan.mode', { id: id, mode: mode }), 'call'); + requireApiSuccess(await api.call('fan.mode', { id: id, mode: mode }, 'POST'), 'call'); showToast(typeof t === 'function' ? t('fan.modeSwitch', { id, mode: t({off:'common.disabled', manual:'common.manual', auto:'fanPage.modeSmart', curve:'fan.curve'}[mode] || 'common.unknown') }) : `风扇 ${id} 模式已切换为 ${mode}`, 'success'); await refreshFans(); } catch (e) { reportFailure({ op: 'fan.setmode', error: e, write: true }); } @@ -2253,7 +2253,7 @@ function markFanOutputsUnknown(id = null) { async function refreshFans() { try { - const result = requireApiSuccess(await api.call('fan.status'), 'fan.status'); + const result = requireApiSuccess(await api.call('fan.status', null, 'GET'), 'fan.status'); if (result.data) updateFanInfo(result.data); else markFanOutputsUnknown(); } catch (e) { @@ -2329,7 +2329,7 @@ async function loadFanCurveConfig(owner, fanId) { status.textContent = t('modalSettings.loading'); updateFanCurveControls(owner); try { - const result = await api.call('fan.config', { id: fanId }); + const result = await api.call('fan.config', { id: fanId }, 'GET'); if (!fanCurveReadCurrent(owner, 'curveRequest', request)) return; if (result.code !== 0 || !result.data) { status.textContent = fanCurveDraftNotice(); @@ -2748,7 +2748,7 @@ async function loadTempSourceStatus(owner = fanCurveModalOwner) { owner.modal.querySelector('#temp-source-hint').textContent = t('modalSettings.loading'); updateFanCurveControls(owner); try { - const result = await api.call('temp.status'); + const result = await api.call('temp.status', null, 'GET'); if (!fanCurveReadCurrent(owner, 'bindingRequest', request)) return; if (result.code !== 0 || !result.data) owner.bindingError = true; if (result.code === 0 && result.data) { @@ -2789,7 +2789,7 @@ async function loadVariableBindStatus(owner, request) { const varsResult = await api.call('automation.variables.list', { include_value: true, include_meta: false - }); + }, 'GET'); if (!fanCurveReadCurrent(owner, 'bindingRequest', request)) return; if (varsResult.code !== 0 || !varsResult.data?.variables) owner.bindingError = true; if (varsResult.code === 0 && varsResult.data?.variables) { @@ -2813,7 +2813,7 @@ async function loadVariableBindStatus(owner, request) { } try { - const bindResult = await api.call('temp.bind'); + const bindResult = await api.call('temp.bind', null, 'POST'); if (!fanCurveReadCurrent(owner, 'bindingRequest', request)) return; if (bindResult.code !== 0 || !bindResult.data) owner.bindingError = true; const statusEl = document.getElementById('variable-bind-status'); @@ -2933,10 +2933,10 @@ async function bindTempVariable() { weight: Math.max(0, Math.min(1, b.weight || 0)) })); - const result = await api.call('temp.bind', { variables }); + const result = await api.call('temp.bind', { variables }, 'POST'); if (result.code === 0) { - requireApiSuccess(await api.call('temp.select', { source: 'variable' }), 'call'); + requireApiSuccess(await api.call('temp.select', { source: 'variable' }, 'POST'), 'call'); showToast(t('fanPage.tempBoundWeighted', { count: variables.length }), 'success'); @@ -2965,7 +2965,7 @@ async function unbindTempVariable() { owner.bindingWriting = true; updateFanCurveControls(owner); try { - const result = await api.call('temp.bind', { variables: [] }); + const result = await api.call('temp.bind', { variables: [] }, 'POST'); if (result.code === 0) { if (fanCurveReadCurrent(owner, 'bindingRequest', request)) tempVarBindings = []; @@ -3032,7 +3032,7 @@ async function applyFanCurve() { id: fanId, min_duty: minDuty, max_duty: maxDuty - }); + }, 'POST'); requireApiSuccess(limitsResult, 'fan.limits'); @@ -3042,7 +3042,7 @@ async function applyFanCurve() { curve: sortedCurve, hysteresis: hysteresis, min_interval: minInterval - }); + }, 'POST'); requireApiSuccess(curveResult, 'fan.curve'); @@ -3050,7 +3050,7 @@ async function applyFanCurve() { const modeResult = await api.call('fan.mode', { id: fanId, mode: 'curve' - }); + }, 'POST'); requireApiSuccess(modeResult, 'fan.mode'); @@ -3422,7 +3422,7 @@ async function loadDataWidgets() { const revision = dataWidgetsRevision; try { // 1. 尝试从后端加载 - const response = requireApiSuccess(await api.call('ui.widgets.get'), 'ui.widgets.get'); + const response = requireApiSuccess(await api.call('ui.widgets.get', null, 'GET'), 'ui.widgets.get'); if (!pageCurrent()) return; if (revision !== dataWidgetsRevision) return dataWidgetsLoaded; // API 响应格式: {code: 0, data: {widgets: [...], refresh_interval: 5000, source: "sdcard"}} @@ -4103,7 +4103,7 @@ async function refreshDataWidgets() { const variables = Object.create(null); if (varNames.size > 0) { try { - const resp = await api.call('automation.variables.list', { include_meta: false }); + const resp = await api.call('automation.variables.list', { include_meta: false }, 'GET'); if (!pageCurrent()) return; if (resp.code === 0 && resp.data?.variables) { for (const v of resp.data.variables) { @@ -4262,7 +4262,7 @@ async function refreshLogOnce(widgetId) { } const varName = varMatch[1].trim(); - const result = await api.call('automation.variables.get', { name: varName }); + const result = await api.call('automation.variables.get', { name: varName }, 'GET'); if (!pageCurrent()) return; if (result.code !== 0 || result.data?.value === undefined) { @@ -4721,7 +4721,7 @@ function startAutomaticStartRefresh() { if(document.hidden||reading)return; reading=true; try { - const response=await api.call('automation.status'); + const response=await api.call('automation.status', null, 'GET'); if(current()&&response.code===0)renderAutomaticStarts(response.data?.automatic_starts||[]); } catch (_) { /* Existing page connection state reports transport failures. */ } finally {reading=false;} @@ -4739,7 +4739,7 @@ async function refreshQuickActions() { } try { - const result = await api.call('automation.rules.list'); + const result = await api.call('automation.rules.list', null, 'GET'); if (!pageCurrent()) return; recordConfigurationList('quick-rules', result.data || {}, result.data?.rules || []); if (result.code === 0 && result.data && result.data.rules) { @@ -4953,7 +4953,7 @@ function refreshServiceStates() { serviceStatusRead = read; read.promise = (async () => { try { - const result = requireApiSuccess(await api.call('automation.services.list',{}),'automation.services.list'); + const result = requireApiSuccess(await api.call('automation.services.list',{}, 'GET'),'automation.services.list'); if (!read.current() || serviceStatusRead !== read) return; const records = new Map(); for (const run of result.data.items || []) { @@ -4972,7 +4972,7 @@ function refreshServiceStates() { async function waitServiceOperation(runId, operationId, isCurrent) { const deadline = Date.now()+60000; while (isCurrent() && Date.now()' + t('quickActionNotice.goAutomation') + '' : '') + ''; } +function commandSelectionEmptyState() { + return `
+
+

${t('ssh.selectHostFirst')}

+

${t('ssh.selectHostHint')}

+ +
`; +} + async function loadCommandsPage() { const pageCurrent = capturePageValidity(); clearInterval(refreshInterval); @@ -8426,7 +8435,7 @@ async function loadCommandsPage() {
-

${t('ssh.selectHostFirst')}

+ ${commandSelectionEmptyState()}
@@ -8545,7 +8554,7 @@ async function loadHostSelector() { const container = document.getElementById('host-selector'); try { - const result = await api.call('ssh.hosts.list', {}); + const result = await api.call('ssh.hosts.list', {}, 'GET'); if (!pageCurrent()) return; if (result.code !== 0) { // an error is not an empty list container.innerHTML = `

${failureNote({ op: 'host.list', result, endpoint: 'ssh.hosts.list', write: false })}

`; @@ -8614,11 +8623,44 @@ function selectHost(hostId) { refreshCommandsList(); } +async function loadFileIcon(image, path, onFailure) { + const token = api.token; + try { + const blob = await api.fileDownload(path); + if (!image.isConnected || api.token !== token) return; + const url = URL.createObjectURL(blob); + const release = () => URL.revokeObjectURL(url); + image.onload = () => { + release(); + if (api.token !== token) image.removeAttribute('src'); + }; + image.onerror = () => { release(); if (image.isConnected && api.token === token) onFailure(); }; + image.src = url; + } catch (error) { + if (image.isConnected && api.token === token) onFailure(); + } +} + +function updateFileIconPreview(id, path) { + const preview = document.getElementById(id); + const placeholder = (failed) => { + const note = document.createElement('span'); + note.className = 'preview-placeholder'; + note.textContent = t(failed ? 'sshPage.iconPreviewFailed' : 'sshPage.iconPreviewNone'); + preview.replaceChildren(note); + }; + if (!path || !path.startsWith('/sdcard/')) { placeholder(false); return; } + const image = document.createElement('img'); + image.alt = 'icon'; + preview.replaceChildren(image); + void loadFileIcon(image, path, () => placeholder(true)); +} + function commandImageUnavailable(image) { if(!image.isConnected)return; image.hidden=true; const note=image.closest('.command-card')?.querySelector('[data-command-image-note]'); - if(note){note.hidden=false;note.title=new URL(image.src,location.href).searchParams.get('path')||'';} + if(note){note.hidden=false;note.title=image.dataset.filePath||'';} } function refreshCommandsList() { @@ -8627,7 +8669,7 @@ function refreshCommandsList() { const empty = (msgKey) => `

${t(msgKey)}

${createFirstBtn}
`; if (!selectedHostId) { - container.innerHTML = empty('ssh.selectHostFirst'); + container.innerHTML = commandSelectionEmptyState(); return; } @@ -8654,7 +8696,7 @@ function refreshCommandsList() { const iconValue = cmd.icon || 'ri-rocket-line'; let iconHtml; if (iconValue.startsWith('/sdcard/')) { - iconHtml = `${escapeHtml(t('automation.iconLabel'))}`; + iconHtml = `${escapeHtml(t('automation.iconLabel'))}`; } else if (iconValue.startsWith('ri-')) { iconHtml = ``; } else { @@ -8702,6 +8744,9 @@ function refreshCommandsList() { }); if(container.querySelector('[data-service-commands]')){void refreshServiceStates();startServiceStatusRefresh();} + container.querySelectorAll('img[data-file-path]').forEach(image => { + void loadFileIcon(image, image.dataset.filePath, () => commandImageUnavailable(image)); + }); } function showAddCommandModal() { @@ -8812,7 +8857,7 @@ async function showCommandVariables(varName) { const result = await api.call('automation.variables.list', { prefix: `${varName}.`, include_meta: true - }); + }, 'GET'); if (result.code === 0 && result.data && result.data.variables) { const vars = result.data.variables.filter(v => v.source_id === varName || v.name.startsWith(varName + '.')); @@ -8966,13 +9011,7 @@ async function browseCmdIconImage() { * 更新图标图片预览 */ function updateCmdIconPreview(path) { - const preview = document.getElementById('cmd-icon-preview'); - if (path && path.startsWith('/sdcard/')) { - const loadFailed = typeof t === 'function' ? t('sshPage.iconPreviewFailed') : '加载失败'; - preview.innerHTML = `icon`; - } else { - preview.innerHTML = '' + (typeof t === 'function' ? t('sshPage.iconPreviewNone') : '无') + ''; - } + updateFileIconPreview('cmd-icon-preview', path); } /** @@ -9309,7 +9348,7 @@ async function doExportSshCommand(cmdId, recipientCert, includeHost) { params.recipient_cert = recipientCert; } - const result = await api.call('ssh.commands.export', params); + const result = await api.call('ssh.commands.export', params, 'POST'); if (result.code !== 0) throw new ApiOperationError(result, 'ssh.commands.export'); @@ -9532,7 +9571,7 @@ async function executeCommand(idx) { if (ownsExecDisplay(owner)) { owner.finished = true; cancel.style.display = 'none'; } return; } - const result=requireApiSuccess(await api.call('ssh.exec_stream',params),'ssh.exec_stream'); + const result=requireApiSuccess(await api.call('ssh.exec_stream',params, 'POST'),'ssh.exec_stream'); if (!Number.isInteger(result.data?.session_id)) throw new ApiOperationError({},'ssh.exec_stream',{kind:'format',uncertain:true}); if (!ownsExecDisplay(owner)) return; output.textContent+=t('promptRepair.sessionWaiting',{id:result.data.session_id}); @@ -9575,7 +9614,7 @@ async function cancelExecution() { cancelBtn.textContent = typeof t === 'function' ? t('ui.cancelling') : '取消中...'; try { - requireApiSuccess(await api.call('ssh.cancel', { session_id: sessionId }), 'ssh.cancel'); + requireApiSuccess(await api.call('ssh.cancel', { session_id: sessionId }, 'POST'), 'ssh.cancel'); if (!ownsExecDisplay(owner)) return; showToast((typeof t === 'function' ? t('toast.cancelSent') : '取消请求已发送'), 'info'); } catch (e) { @@ -10406,7 +10445,7 @@ async function loadSshHostsData() { const version = ++sshHostsLoadVersion; const pageCurrent = configurationRead('hosts'); try { - const result = requireApiSuccess(await api.call('ssh.hosts.list', {}), 'ssh.hosts.list'); + const result = requireApiSuccess(await api.call('ssh.hosts.list', {}, 'GET'), 'ssh.hosts.list'); if (!pageCurrent()) return false; if (version !== sshHostsLoadVersion) return null; // Superseded, leave the newer list alone. const hosts = result.data?.hosts; @@ -10482,7 +10521,7 @@ async function refreshKnownHostsList() { if (!tbody) return; try { - const result = await api.call('hosts.list', {}); + const result = await api.call('hosts.list', {}, 'GET'); if (!pageCurrent()) return; if (result.code !== 0) { tbody.innerHTML = `
${failureNote({ op: 'knownHost.list', result, endpoint: 'hosts.list', write: false })}
`; @@ -10559,7 +10598,7 @@ async function removeKnownHost(index) { const params = { host: `${host.host}:${host.port}` }; try { - const result = await api.call('hosts.remove', { host: host.host, port: host.port }); + const result = await api.call('hosts.remove', { host: host.host, port: host.port }, 'POST'); if (result.code === 0) { showToast(t('failure.ops.knownHost.remove.done', params), 'success'); await refreshKnownHostsList(); @@ -10593,7 +10632,7 @@ async function testSshHostByIndex(index) { command: 'echo "TianshanOS SSH Test OK"', trust_new: false }; - let execResult = await api.call('ssh.exec', params); + let execResult = await api.call('ssh.exec', params, 'POST'); if ([1001, 1002].includes(execResult.code)) { const changed = execResult.code === 1001; const fingerprint = execResult.data?.fingerprint || execResult.data?.current_fingerprint; @@ -10620,7 +10659,7 @@ async function testSshHostByIndex(index) { params.confirmed_fingerprint = fingerprint; params.trust_new = execResult.code === 1002; params.accept_changed = execResult.code === 1001; - execResult = await api.call('ssh.exec', params); + execResult = await api.call('ssh.exec', params, 'POST'); if ([1001, 1002].includes(execResult.code)) { // a different key now: never trust it silently reportFailure({ op: 'ssh.connect', params: messageParams, result: execResult, token: 'ssh_fingerprint_mismatch', endpoint: 'ssh.exec' }); return; @@ -10721,7 +10760,7 @@ async function doExportSshHost(hostId, recipientCert) { params.recipient_cert = recipientCert; } - const result = await api.call('ssh.hosts.export', params); + const result = await api.call('ssh.hosts.export', params, 'POST'); if (result.code !== 0) throw new ApiOperationError(result, 'ssh.hosts.export'); @@ -10907,7 +10946,7 @@ async function saveSourceEdit() { async function deleteKey(id) { const current = capturePageValidity(); let details = null; - try {details = requireApiSuccess(await api.call('key.delete', {id, preview: true}), 'key.delete').data;} catch (_) { /* The final user decision remains available when the impact cannot be read. */ } + try {details = requireApiSuccess(await api.call('key.delete', {id, preview: true}, 'POST'), 'key.delete').data;} catch (_) { /* The final user decision remains available when the impact cannot be read. */ } if (!current()) return; const lines = [t('ui.confirmDeleteKey', {id}), configText('keyDeleteImpact')]; if (!details?.complete) lines.push(configText('keyImpactUnknown')); @@ -13227,14 +13266,14 @@ async function loadOtaData() { const pageCurrent = capturePageValidity(); try { // 1. 加载 OTA 服务器地址 - const serverResult = await api.call('ota.server.get'); + const serverResult = await api.call('ota.server.get', null, 'GET'); if (!pageCurrent()) return; if (serverResult?.code === 0 && serverResult.data?.url) { document.getElementById('ota-server-input').value = serverResult.data.url; } // 2. 加载版本信息 - const versionResult = await api.call('ota.version'); + const versionResult = await api.call('ota.version', null, 'GET'); if (!pageCurrent()) return; if (versionResult?.code === 0 && versionResult.data) { const v = versionResult.data; @@ -13245,9 +13284,9 @@ async function loadOtaData() { } // 3. 加载分区信息 - const partResult = await api.call('ota.partitions'); + const partResult = await api.call('ota.partitions', null, 'GET'); if (!pageCurrent()) return; - if (partResult?.code === 0 && partResult.data) { + if (partResult?.code === 0 && partResult.data?.next) { displayPartitionsCompact(partResult.data); } @@ -13439,9 +13478,9 @@ async function refreshOtaProgress() { // 根据当前步骤获取不同的进度 let result; if (otaStep === 'www') { - result = await api.call('ota.www.progress'); + result = await api.call('ota.www.progress', null, 'GET'); } else { - result = await api.call('ota.progress'); + result = await api.call('ota.progress', null, 'GET'); } if (!current()) return; @@ -13569,13 +13608,13 @@ async function startWwwOta() { // SD卡方式 result = await api.call('ota.www.start_sdcard', { file: wwwSource - }); + }, 'POST'); } else { // HTTP 方式 result = await api.call('ota.www.start', { url: wwwSource, skip_verify: upgrade.skipVerify - }); + }, 'POST'); } if (otaUpgrade !== upgrade || upgrade.phase !== 'www') return; @@ -13616,7 +13655,7 @@ async function completeOtaUpgrade(upgrade) { // The written inactive partition is the target for every source, including // local files, downgrades and same-version reflashes. No server metadata is needed. try { - const result = requireApiSuccess(await api.call('ota.partitions'), 'ota.partitions'); + const result = requireApiSuccess(await api.call('ota.partitions', null, 'GET'), 'ota.partitions'); if (otaUpgrade !== upgrade || upgrade.phase !== 'reboot') return; const next = result.data?.next; if (!next?.is_bootable || !next.version || !next.label || next.label === result.data?.running?.label) { @@ -13644,7 +13683,7 @@ async function completeOtaUpgrade(upgrade) { try { // system.reboot's delay is in milliseconds. - requireApiSuccess(await api.call('system.reboot', { delay: 1000 }), 'system.reboot'); + requireApiSuccess(await api.call('system.reboot', { delay: 1000 }, 'POST'), 'system.reboot'); } catch (error) { if (otaUpgrade !== upgrade || upgrade.phase !== 'reboot') return; const failure = { op: 'device.reboot', error, endpoint: 'system.reboot', write: true }; @@ -13686,7 +13725,7 @@ function startRebootDetection(upgrade) { } checking = true; try { - const result = requireApiSuccess(await api.call('ota.partitions'), 'ota.partitions'); + const result = requireApiSuccess(await api.call('ota.partitions', null, 'GET'), 'ota.partitions'); if (!current()) return; const running = result.data?.running; lastRunning = running || null; @@ -13764,7 +13803,7 @@ async function otaFromUrl() { try { showToast(typeof t === 'function' ? t('toast.twoStepUpgrade') : '开始两步升级:固件 + WebUI', 'info'); - const result = await api.call('ota.upgrade_url', params); + const result = await api.call('ota.upgrade_url', params, 'POST'); if (otaUpgrade !== upgrade || upgrade.phase !== 'app') return; if (result.code === 0) { @@ -13835,7 +13874,7 @@ async function otaFromFile() { try { showToast(typeof t === 'function' ? t('toast.startingFileUpgrade') : '开始从文件升级固件...', 'info'); - const result = await api.call('ota.upgrade_file', params); + const result = await api.call('ota.upgrade_file', params, 'POST'); if (otaUpgrade !== upgrade || upgrade.phase !== 'app') return; if (result.code === 0) { @@ -13861,7 +13900,7 @@ async function validateOta() { } try { - const result = await api.call('ota.validate'); + const result = await api.call('ota.validate', null, 'POST'); if (result.code === 0) { showToast(typeof t === 'function' ? t('toast.firmwareValidated') : '固件已标记为有效', 'success'); @@ -13885,7 +13924,7 @@ async function confirmRollback() { async function rollbackOta() { try { showToast(typeof t === 'function' ? t('toast.rollingBack') : '正在回滚固件...', 'info'); - const result = await api.call('ota.rollback'); + const result = await api.call('ota.rollback', null, 'POST'); if (result.code === 0) { showToast(typeof t === 'function' ? t('toast.rollbackSuccess') : '回滚成功!系统将在 3 秒后重启...', 'success'); @@ -13915,9 +13954,9 @@ async function abortOta() { // 根据当前步骤中止相应的 OTA let result; if (otaStep === 'www') { - result = await api.call('ota.www.abort'); + result = await api.call('ota.www.abort', null, 'POST'); } else { - result = await api.call('ota.abort'); + result = await api.call('ota.abort', null, 'POST'); } if (otaUpgrade !== upgrade) return; @@ -14030,7 +14069,7 @@ async function saveOtaServer() { const result = await api.call('ota.server.set', { url: serverUrl, save: true // 保存到 NVS - }); + }, 'POST'); if (result.code === 0) { if (serverUrl) { @@ -14100,7 +14139,7 @@ async function checkForUpdates() { // 获取当前版本 if (!currentFirmwareVersion) { - const localResult = await api.call('ota.version'); + const localResult = await api.call('ota.version', null, 'GET'); if (localResult && localResult.code === 0 && localResult.data) { currentFirmwareVersion = localResult.data; } @@ -14803,7 +14842,7 @@ async function refreshAutomationStatus() { if (!container) return; try { - const result = await api.call('automation.status'); + const result = await api.call('automation.status', null, 'GET'); if (!pageCurrent()) return; if (result.code === 0 && result.data) { const d = result.data; @@ -14861,7 +14900,7 @@ async function refreshRules() { if (!container) return; try { - const result = await api.call('automation.rules.list'); + const result = await api.call('automation.rules.list', null, 'GET'); if (!pageCurrent()) return; if (result.code === 0 && result.data && result.data.rules) { const rules = result.data.rules; @@ -14958,7 +14997,7 @@ async function refreshSources() { if (!container) return; try { - const result = await api.call('automation.sources.list'); + const result = await api.call('automation.sources.list', null, 'GET'); if (!pageCurrent()) return; if (result.code === 0 && result.data && result.data.sources) { const sources = result.data.sources; @@ -15070,7 +15109,7 @@ async function refreshActions() { if (!container) return; try { - const result = await api.call('automation.actions.list', {}); + const result = await api.call('automation.actions.list', {}, 'GET'); if (!pageCurrent()) return; if (result.code !== 0) { container.innerHTML = '

' + failureNote({ op: 'action.list', result, endpoint: 'automation.actions.list' }) + '

'; @@ -15465,7 +15504,7 @@ async function loadSshCommandsForAction() { const select = document.getElementById('action-ssh-cmd-id'); if (!select) return; - const result = await api.call('ssh.commands.list', {}); + const result = await api.call('ssh.commands.list', {}, 'GET'); if (!await accept(result.data)) return; select.innerHTML = (""); @@ -15502,7 +15541,7 @@ async function updateSshCmdRefPreview() { // 从 API 获取完整指令信息 try { - const result = await api.call('ssh.commands.get', { id: cmdId }); + const result = await api.call('ssh.commands.get', { id: cmdId }, 'GET'); if (!await accept(result.data) || select.value !== cmdId) return; console.log('SSH command get result:', result); if (result.code === 0 && result.data) { @@ -15830,7 +15869,7 @@ async function loadVarSelectList(asExpr = false) { const result = await api.call('automation.variables.list', { include_value: false, include_meta: false - }); + }, 'GET'); if (result.code !== 0) throw new ApiOperationError(result, 'automation.variables.list'); const variables = result.data?.variables || []; document.getElementById('variable-select-loading').style.display = 'none'; @@ -16080,7 +16119,7 @@ async function editAction(id) { const current = configurationRead('editAction'); const params = { name: actionNames.get(id) || id }; try { - const result = await api.call('automation.actions.get', { id }); + const result = await api.call('automation.actions.get', { id }, 'GET'); if (!current()) return; if (result.code !== 0) { reportFailure({ op: 'action.load', params, result, endpoint: 'automation.actions.get' }); @@ -16392,7 +16431,7 @@ async function showSourceVariables(sourceId) { const result = await api.call('automation.variables.list', { source_id: sourceId, include_meta: true - }); + }, 'GET'); if (result.code === 0 && result.data && result.data.variables) { const vars = result.data.variables.filter(v => v.source_id === sourceId); @@ -16618,7 +16657,7 @@ async function editRule(id) { const params = { name: ruleNames.get(id) || id }; try { // 获取规则详情 - const result = await api.call('automation.rules.get', { id }); + const result = await api.call('automation.rules.get', { id }, 'GET'); if (!current()) return; if (result.code !== 0 || !result.data) { reportFailure({ op: 'rule.load', params, result, endpoint: 'automation.rules.get' }); @@ -16753,7 +16792,7 @@ async function testRestConnection() { url, method, headers: auth ? { 'Authorization': auth } : {} - }); + }, 'POST'); if (!current()) return; if (result.code === 0 && result.data) { @@ -16815,7 +16854,7 @@ async function testWsConnection() { try { // 通过 ESP32 测试 WebSocket(获取第一条消息) - const result = await api.call('automation.proxy.websocket_test', { uri, timeout_ms: 5000 }); + const result = await api.call('automation.proxy.websocket_test', { uri, timeout_ms: 5000 }, 'POST'); if (!current()) return; if (result.code === 0 && result.data) { @@ -16878,7 +16917,7 @@ async function testSioConnection() { const params = { url, timeout_ms: timeout }; if (event) params.event = event; - const result = await api.call('automation.proxy.socketio_test', params); + const result = await api.call('automation.proxy.socketio_test', params, 'POST'); if (!current()) return; if (result.code === 0 && result.data) { @@ -16919,7 +16958,7 @@ async function testSioConnection() { // 显示详细错误 if (result.data && result.data.error) { - modal.querySelector('#sio-json-preview').textContent = result.data.error; + modal.querySelector('#sio-json-preview').textContent = failureText({ op: 'source.testSio', params: { url: shortUrl(url) }, result, endpoint: 'automation.proxy.socketio_test', write: false }); modal.querySelector('#sio-json-preview').style.display = 'block'; } } @@ -17121,7 +17160,7 @@ async function loadSshHostsForSource() { if (varsListDiv) varsListDiv.innerHTML = `${typeof t === 'function' ? t('automation.selectHostCmdFirst') : 'Please select SSH host and command first'}`; try { - const result = await api.call('ssh.hosts.list'); + const result = await api.call('ssh.hosts.list', null, 'GET'); if (!await accept(result.data)) return; if (result.code === 0 && result.data && result.data.hosts) { const hosts = result.data.hosts; @@ -17157,7 +17196,7 @@ async function onSshHostChangeForSource() { if (!hostId) {select.innerHTML = ``;return;} select.innerHTML = ``; try { - const result = requireApiSuccess(await api.call('ssh.commands.list', {host_id: hostId}), 'ssh.commands.list'); + const result = requireApiSuccess(await api.call('ssh.commands.list', {host_id: hostId}, 'GET'), 'ssh.commands.list'); if (!await accept(result.data) || document.getElementById('source-ssh-host').value !== hostId) return; modal._sourceCommands = result.data.commands || []; select.innerHTML = `` + modal._sourceCommands.map((command,index) => @@ -17586,13 +17625,7 @@ async function browseRuleIconImage() { } function updateRuleIconPreview(path) { - const preview = document.getElementById('rule-icon-preview'); - if (path && path.startsWith('/sdcard/')) { - const loadFailed = typeof t === 'function' ? t('sshPage.iconPreviewFailed') : '加载失败'; - preview.innerHTML = `icon`; - } else { - preview.innerHTML = '' + (typeof t === 'function' ? t('sshPage.iconPreviewNone') : '无') + ''; - } + updateFileIconPreview('rule-icon-preview', path); } function clearRuleIconImage() { @@ -17737,7 +17770,7 @@ async function loadActionTemplatesForRule() { const modal = document.getElementById('add-rule-modal'); const accept = configurationEditorRead('add-rule-modal'); try { - const result = await api.call('automation.actions.list', {}); + const result = await api.call('automation.actions.list', {}, 'GET'); if (!await accept(result.data)) return {token: 'configuration_changed', write: false}; if (result.code === 0 && result.data?.templates) { modal._actionTemplates = result.data.templates; @@ -18208,7 +18241,7 @@ async function doExportSource(sourceId) { const params = { id: sourceId }; if (certText) params.recipient_cert = certText; - const result = await api.call('automation.sources.export', params); + const result = await api.call('automation.sources.export', params, 'POST'); if (result.code !== 0) { packBox(resultBox, { op: 'pack.export', params: packParams, result, endpoint: 'automation.sources.export', write: false }); return; } const data = result.data; @@ -18284,7 +18317,7 @@ async function doExportRule(ruleId) { const params = { id: ruleId }; if (certText) params.recipient_cert = certText; - const result = await api.call('automation.rules.export', params); + const result = await api.call('automation.rules.export', params, 'POST'); if (result.code !== 0) { packBox(resultBox, { op: 'pack.export', params: packParams, result, endpoint: 'automation.rules.export', write: false }); return; } const data = result.data; @@ -18359,7 +18392,7 @@ async function doExportAction(actionId) { const params = { id: actionId }; if (certText) params.recipient_cert = certText; - const result = await api.call('automation.actions.export', params); + const result = await api.call('automation.actions.export', params, 'POST'); if (result.code !== 0) { packBox(resultBox, { op: 'pack.export', params: packParams, result, endpoint: 'automation.actions.export', write: false }); return; } const data = result.data; diff --git a/components/ts_webui/web/js/lang/en-US.js b/components/ts_webui/web/js/lang/en-US.js index 464f6578..0c21c9f6 100644 --- a/components/ts_webui/web/js/lang/en-US.js +++ b/components/ts_webui/web/js/lang/en-US.js @@ -922,6 +922,7 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('en-US', { importCommand: 'Import Command', // Empty states selectHostFirst: 'Please select a host first', + selectHostHint: 'Select a host card above to view its commands.', createFirstCommand: 'Create your first command', noCommandsForHost: 'No commands for this host', // Command modal @@ -4262,6 +4263,12 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('en-US', { // what a kind of object is called inside a sentence ({kind}) kinds: { source: 'data source', rule: 'rule', action: 'action template', sshHost: 'SSH host', sshCommand: 'SSH command' }, reasons: { + file_replace_uncertain: {"why":"The file replacement could not be confirmed","hint":"Check the current file and retained previous copy before retrying. Keep temporary files until recovery is confirmed."}, + credential_write_uncertain: {"why":"The password update could not be confirmed","hint":"This account’s sessions were revoked. Sign in again; the new password may already be active. Do not submit repeated changes automatically."}, + ws_invalid_frame: {"why":"the test message framing is invalid","hint":"Check the remote WebSocket service and retry."}, + ws_message_too_large: {"why":"the test message exceeds 64 KiB","hint":"Use a smaller diagnostic message or narrow the source data."}, + ws_send_failed: {"why":"message delivery could not be confirmed","hint":"Check the connection and remote state before retrying."}, + pack_apply_unsupported: {"why":"this device does not support applying a generic configuration pack","hint":"Import a supported pack from its configuration page. Existing settings were not changed."}, access_password_required: {"why": "the application computer administrator password must be a single line", "hint": "Check the password entry."}, access_state_unavailable: {"why": "the management controller could not allocate memory for the network access state", "hint": "Check the management controller memory status and system log."}, access_busy: {"why": "a network access task is already running", "hint": "Wait for the current task to finish and check its result."}, @@ -4328,7 +4335,7 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('en-US', { ssh_result_unknown: { why: 'the result of the command did not reach this page, so it is not known whether it succeeded', hint: 'Check on that host whether the command has finished, and do not simply run it again.' }, // -- Accounts, OTA, files, network, LED and more -- credentials_invalid: { why: 'the username or password is wrong', hint: 'Check them and try again.' }, - account_locked: { why: 'too many wrong attempts have locked this account for a while', hint: 'Wait 5 minutes and try again.' }, + account_locked: {"why":"too many wrong attempts have locked this account for a while","hint":"Keep the device on and wait 5 minutes before trying again. Restarting begins a new cooldown."}, password_length: { why: 'the new password must be 4 to 64 characters long', hint: 'Choose another password.' }, old_password_wrong: { why: 'the current password is wrong', hint: 'Check it and try again.' }, root_required: { why: 'this action needs the root account', hint: 'Log in as root and try again.' }, diff --git a/components/ts_webui/web/js/lang/zh-CN.js b/components/ts_webui/web/js/lang/zh-CN.js index 1a098f47..80b464b6 100644 --- a/components/ts_webui/web/js/lang/zh-CN.js +++ b/components/ts_webui/web/js/lang/zh-CN.js @@ -914,6 +914,7 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('zh-CN', { importCommand: '导入指令', // New keys for i18n createFirstCommand: '创建第一个指令', + selectHostHint: '点击上方主机卡片,查看对应的指令。', selectHostFirst: '请先选择一个主机', noCommandsForHost: '该主机暂无指令', hostNotExistCannotExec: '主机不存在,无法执行', @@ -4224,6 +4225,12 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('zh-CN', { // 句子里怎么称呼一类对象({kind}) kinds: { source: '数据源', rule: '规则', action: '动作模板', sshHost: 'SSH 主机', sshCommand: 'SSH 指令' }, reasons: { + file_replace_uncertain: {"why":"尚未确认文件替换的最终结果","hint":"请先核对原文件及保留副本,不要清理临时文件;确认当前状态后再决定是否重新上传。"}, + credential_write_uncertain: {"why":"密码更新结果尚未确认","hint":"目标账户的会话已撤销,请重新登录;新密码可能已经生效。不要自动反复提交改密。"}, + ws_invalid_frame: {"why":"测试消息的分帧不完整或无效","hint":"请检查远端 WebSocket 服务后重试。"}, + ws_message_too_large: {"why":"测试消息超过 65536 字节","hint":"请缩小测试消息或减少数据源返回的内容。"}, + ws_send_failed: {"why":"消息是否送达尚未确认","hint":"请检查连接和远端状态后再重试。"}, + pack_apply_unsupported: {"why":"此设备不支持通用配置包的一键应用","hint":"请在对应配置页面导入受支持的配置包;现有设置未更改。"}, access_password_required: {"why": "应用计算机管理员密码必须是非空的单行文字", "hint": "请检查密码输入。"}, access_state_unavailable: {"why": "管理控制器无法分配网络接入状态所需的内存", "hint": "请查看管理控制器的内存状态和系统日志。"}, access_busy: {"why": "已有网络接入任务正在执行", "hint": "请等待当前任务完成并查看结果。"}, @@ -4290,7 +4297,7 @@ if (typeof i18n !== 'undefined') i18n.registerLanguage('zh-CN', { ssh_result_unknown: { why: '命令的结果没能送到页面,是否成功未知', hint: '请到那台主机上确认命令是否已经执行完,不要直接重复执行。' }, // —— 账户、OTA、文件、网络、LED 等 —— credentials_invalid: { why: '用户名或密码不对', hint: '请检查后重新输入。' }, - account_locked: { why: '连续输错次数太多,这个账户暂时被锁定', hint: '请等 5 分钟后再试。' }, + account_locked: {"why":"连续输错次数太多,这个账户暂时被锁定","hint":"请保持设备开机,等 5 分钟后再试;重启会重新开始冷却。"}, password_length: { why: '新密码的长度不对(需要 4 到 64 个字符)', hint: '请重新设置密码。' }, old_password_wrong: { why: '当前密码不对', hint: '请检查后重新输入。' }, root_required: { why: '这项操作需要 root 账户', hint: '请换用 root 账户登录后再操作。' }, diff --git a/components/ts_webui/web/js/terminal.js b/components/ts_webui/web/js/terminal.js index 65371b24..b7621b6d 100644 --- a/components/ts_webui/web/js/terminal.js +++ b/components/ts_webui/web/js/terminal.js @@ -678,10 +678,16 @@ class WebTerminal { */ sendSshInput(data) { if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(JSON.stringify({ - type: 'ssh_input', - data: data - })); + // Keep complete JSON messages below the server frame budget. SSH + // input is a stream; preserve every character and surrogate pair. + for (let start = 0; start < data.length;) { + let end = Math.min(start + 2048, data.length); + const last = data.charCodeAt(end - 1); + if (end < data.length && last >= 0xD800 && last <= 0xDBFF && + data.charCodeAt(end) >= 0xDC00 && data.charCodeAt(end) <= 0xDFFF) --end; + this.ws.send(JSON.stringify({type: 'ssh_input', data: data.slice(start, end)})); + start = end; + } } } diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 736ade98..7e4f55bc 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -1266,6 +1266,13 @@ POST /api/v1/log/capture } ``` +### ota.partitions +获取当前运行身份;有效 READ 及以上会话还可读取完整分区详情。 + +**请求**:`GET /api/v1/ota/partitions`(也兼容只读 POST)。 + +未登录或会话失效时只返回 `data.running.label/version/project`,供原升级页面跨重启核对目标;不含地址、容量、备用分区或回滚资格。有效 READ 会话保留原完整响应。其他 OTA 操作的鉴权不变。 + ### ota.version 获取固件版本信息。 diff --git a/docs/releases/v0.6.5.md b/docs/releases/v0.6.5.md new file mode 100644 index 00000000..c36c31b0 --- /dev/null +++ b/docs/releases/v0.6.5.md @@ -0,0 +1,42 @@ +# TianshanOS v0.6.5 更新说明(发布候选) + +本版本基于 v0.6.4,集中修正 API 的登录鉴权、权限检查、请求边界、日志敏感内容和会话生命周期问题;同时保留现有 Web UI、HTTP 访问方式、初始口令、管理员操作范围、原升级包与 SD 恢复流程,不引入新的部署要求。 + +## 主要变化 + +- 补齐 API 与 WebSocket 入口的鉴权、请求方法和参数检查,改密后撤销相关会话,限制日志中的敏感内容。 +- 修正文件读写、上传完整性、执行结果与取消操作的生命周期;保留原文件管理、指令及自动化的合法操作。 +- 修正专用固件上传入口错误返回 409,以及已验证的 DNS、HTTP 读取和数据源相关处理。 +- 修正 AGX 复位状态更新,收敛控制器非冷启动时的 LPMU 自动电源脉冲,保留手动控制及原冷启动检测。 +- 优化指令页未选择主机时的排版,以及窄屏顶栏间距,保留已选择主机后的操作流程。 +- 更新发布仓库识别与 CI 所需 SDK 文件,保留原固件、网页和串口升级包格式。 + +## 升级方式与数据保留 + +请先确认设备当前版本及分区布局,并备份配置。固件与 WWW 网页必须使用同一 Release 的配套文件。 + +| 当前版本/布局 | 升级方式 | +|---|---| +| 0.6.0、0.6.1、0.6.2,以及更早的旧分区布局 | **必须使用本 Release 的 USB/串口升级 ZIP 包**,按包内 README 操作;不能只在 Web UI 上传固件或执行 OTA。 | +| 0.6.3、0.6.4,且已正确采用 0.6.3 新分区布局 | 可通过现有 **Web UI 升级**,更新配套固件和 WWW;本次 0.6.5 没有新增分区调整。 | +| 版本来源不明、定制固件,或不能确认布局 | 不要仅凭版本号判断。请先联系厂商核对;配套串口工具会检查实际布局,不匹配时停止。 | + +串口升级要求来自 **0.6.3 的存储分区调整**,不是本次 API 修复新增的限制。USB/串口升级不等于全片擦除。 + +### 配置、密钥和 SD 卡怎么保留 + +- **配置**:升级前导出可导出的配置,并备份 SD 卡配置文件。旧布局首次升级只初始化原来未分配的新增系统/自动化配置区域;保留原 SD 卡并插好,首次启动会尝试迁移旧配置。保留文件不代表所有旧配置已成功迁移,升级后须逐项核对网络、风扇、主机、指令和自动化,必要时从备份恢复或重新配置。已使用新布局的设备,配套串口工具重复升级时保留系统配置区和自动化应急副本。 +- **密钥与证书**:配套串口工具不擦除原密钥区域及 NVS 加密材料,也不要求删除或更换现有证书。正式升级包不会携带测试身份;升级后请核对原证书、SSH 主机认证及需要解密的配置能否正常使用。密钥备份或导出仍受原有可导出标记限制,不应假定全部私钥都能导出。 +- **SD 卡数据**:配套工具不格式化或清空 SD 卡;仍建议升级前复制整卡备份,升级时保留原卡,不拔卡、不删除旧配置。卡内的旧恢复固件/恢复清单也会被保留,请在升级前按包内说明检查,避免首次启动触发非预期的旧版恢复。 + +请勿使用全片擦除、旧分区表或旧版密码恢复镜像代替本次升级。首次串口迁移会更新两个应用槽,不能依赖另一槽自动退回旧布局版本。升级期间保持供电,完成后再检查业务功能。 + +### 回退注意 + +密码恢复专用镜像会重置账户,不是日常升级或保留身份的回滚镜像。曾运行实验性密码格式的设备,回退旧固件前还需确认账户已迁回原格式;跨分区布局回退应由厂商核对,不能只刷旧应用或旧分区表。 + +## 已知问题 + +控制器在维护重启后曾出现网页/API 持续无法访问;最后两轮取证未复现,根因仍未确定,本版本不宣称解决该问题。HTTP 客户端异步使用的 SDK 合同差异也保留为未决风险,尚未证明它是上述失联原因。 + +指令页无可选主机或主机列表加载失败时的引导仍可能指向不存在的主机卡片,原创建检查仍生效。 diff --git a/docs/repair/xterm-local/requests-en-US.json b/docs/repair/xterm-local/requests-en-US.json index c1b0be15..35f480de 100644 --- a/docs/repair/xterm-local/requests-en-US.json +++ b/docs/repair/xterm-local/requests-en-US.json @@ -5,67 +5,60 @@ "origin": "http://fixture.local" }, { - "url": "http://fixture.local/css/style.css?v=20260928-local-xterm", + "url": "http://fixture.local/css/style.css?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/fonts/remixicon.css?v=20260928-local-xterm", + "url": "http://fixture.local/js/api.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/images/tslogo-48.png", + "url": "http://fixture.local/js/router.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/api.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/terminal.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/router.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/dragSort.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/terminal.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/app.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/dragSort.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/lang/en-US.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/app.js?v=20260928-local-xterm", - "origin": "http://fixture.local" - }, - { - "url": "http://fixture.local/js/lang/en-US.js?v=20260928-local-xterm", - "origin": "http://fixture.local" - }, - { - "url": "http://fixture.local/fonts/remixicon.woff2", + "url": "http://fixture.local/api/v1/ota/version", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/api/v1/ota/version", + "url": "http://fixture.local/fonts/quantify-regular.woff2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/images/tslogo-32.png", + "url": "http://fixture.local/favicon.ico?v=mono-1", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/xterm.css?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/xterm.css?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/xterm.min.js?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/xterm.min.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/fit.min.js?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/fit.min.js?v=0.6.2", "origin": "http://fixture.local" } ], "errors": [], + "resourceFailures": [], "realXterm": true, "externalRequests": 0 } \ No newline at end of file diff --git a/docs/repair/xterm-local/requests-zh-CN.json b/docs/repair/xterm-local/requests-zh-CN.json index ef547b7b..d1c745f7 100644 --- a/docs/repair/xterm-local/requests-zh-CN.json +++ b/docs/repair/xterm-local/requests-zh-CN.json @@ -5,43 +5,35 @@ "origin": "http://fixture.local" }, { - "url": "http://fixture.local/css/style.css?v=20260928-local-xterm", + "url": "http://fixture.local/css/style.css?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/fonts/remixicon.css?v=20260928-local-xterm", + "url": "http://fixture.local/js/api.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/images/tslogo-48.png", + "url": "http://fixture.local/js/router.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/api.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/terminal.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/router.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/dragSort.js?v=0.6.0", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/terminal.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/app.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/dragSort.js?v=20260928-local-xterm", + "url": "http://fixture.local/js/lang/zh-CN.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/js/app.js?v=20260928-local-xterm", - "origin": "http://fixture.local" - }, - { - "url": "http://fixture.local/js/lang/zh-CN.js?v=20260928-local-xterm", - "origin": "http://fixture.local" - }, - { - "url": "http://fixture.local/fonts/remixicon.woff2", + "url": "http://fixture.local/fonts/quantify-regular.woff2", "origin": "http://fixture.local" }, { @@ -49,23 +41,24 @@ "origin": "http://fixture.local" }, { - "url": "http://fixture.local/images/tslogo-32.png", + "url": "http://fixture.local/favicon.ico?v=mono-1", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/xterm.css?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/xterm.css?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/xterm.min.js?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/xterm.min.js?v=0.6.2", "origin": "http://fixture.local" }, { - "url": "http://fixture.local/vendor/xterm/fit.min.js?v=20260928-local-xterm", + "url": "http://fixture.local/vendor/xterm/fit.min.js?v=0.6.2", "origin": "http://fixture.local" } ], "errors": [], + "resourceFailures": [], "realXterm": true, "externalRequests": 0 } \ No newline at end of file diff --git a/docs/security/pki-bootstrap.md b/docs/security/pki-bootstrap.md new file mode 100644 index 00000000..6e1995b0 --- /dev/null +++ b/docs/security/pki-bootstrap.md @@ -0,0 +1,14 @@ +# 当前安全修复与原 Web UI 行为边界 + +本文件取代本轮曾提出的首次唯一口令、业务 HTTPS、额外 CA 确认、独立安全时钟及发布材料登记流程。历史审查和测试记录保留在 audit 中,不代表当前产品策略。 + +- 以已提交的 0.6.4 为行为基线。保留原通用初始口令、HTTP 80、直接 IP 和原映射域名/端口访问;不新增首次配置页面或串口临时口令。 +- admin 保留原安全、配置、网络、文件及升级页能力,包括可导出密钥的导出、SD/SPIFFS/WWW 文件和 SFTP 操作。不可导出标记继续有效;账号管理和原终端/指令/自动化专属操作继续按原 Root 权限执行。 +- API 在实际入口检查登录身份、声明的权限及请求方法;匿名业务写入和用 JSON 自报身份仍被拒绝。原 Web UI 在现有调用处声明读写方法,不增加一份运行时接口映射。 +- 浏览器仍拒绝不同 Origin 及重复请求头;撤销“Host 必须是本机”的白名单。允许映射 Host 意味着不再宣称完整阻止 DNS rebinding。 +- 恢复原 www 分区与 /www 挂载、原固件/WWW 文件、升级及 SD 恢复流程。没有新增发布签名、专用发行密钥或材料登记门槛;保留 API 鉴权、请求长度/时间/容量检查以及 SDK 镜像校验。失败上传不删除先前恢复材料;部分完成必须如实返回。 +- 保留既有独立 mTLS 服务;使用原系统/NTP 时间与已安装 CA,不要求新增的逐次 Root 校时确认或 CA 再确认。Device 证书保留原 Viewer 读取与身份查询,不具有 Operator/Admin 管理权限。 +- 普通配置包保留原 Developer 证书用途和开机离线读取,仍验证既有固定 CA、签名、接收方与 GCM;不会把离线读取伪装成已确认当前时间。可执行自动化包继续使用严格代码签名用途、当前时间或精确已接受记录。 +- 内网及外网暴露方式由设备所有者决定。本轮不启用 eFuse、Secure Boot 或 Flash Encryption,不把这些部署策略记为已修复的漏洞。 + +源码本地验证、真实浏览器夹具、已刷设备的验证分别记录。后续源码未再次刷入前,不能把旧设备证据称为该源码的真机验收。 diff --git a/main/main.c b/main/main.c index 2713a846..cd04a1bb 100644 --- a/main/main.c +++ b/main/main.c @@ -1,3 +1,4 @@ +#include "ts_time_sync.h" /** * @file main.c * @brief TianShanOS Main Entry Point @@ -134,6 +135,7 @@ static void print_system_info(void) */ void app_main(void) { + /* Install before config migration or any network/service TLS consumer. */ esp_err_t ret; // 打印启动横幅 diff --git a/main/root_password_reset_main.c b/main/root_password_reset_main.c index 74c12726..82c028ca 100644 --- a/main/root_password_reset_main.c +++ b/main/root_password_reset_main.c @@ -73,42 +73,6 @@ static void halt_on_error(const char *operation, esp_err_t ret) halt_forever(); } -static esp_err_t compute_password_hash(const char *password, - const uint8_t salt[TS_AUTH_SALT_LEN], - uint8_t hash_out[TS_AUTH_HASH_LEN]) -{ - if (!password || !salt || !hash_out) { - return ESP_ERR_INVALID_ARG; - } - - size_t password_len = strlen(password); - if (password_len < 4 || password_len > 64) { - return ESP_ERR_INVALID_ARG; - } - - uint8_t material[TS_AUTH_SALT_LEN + 64] = {0}; - size_t material_len = TS_AUTH_SALT_LEN + password_len; - - memcpy(material, salt, TS_AUTH_SALT_LEN); - memcpy(material + TS_AUTH_SALT_LEN, password, password_len); - - int ret = mbedtls_sha256(material, material_len, hash_out, 0); - memset(material, 0, sizeof(material)); - - return ret == 0 ? ESP_OK : ESP_FAIL; -} - -static bool constant_time_equal(const uint8_t *a, const uint8_t *b, size_t len) -{ - uint8_t diff = 0; - - for (size_t i = 0; i < len; ++i) { - diff |= a[i] ^ b[i]; - } - - return diff == 0; -} - static esp_err_t verify_auth_config_version(nvs_handle_t handle) { uint8_t stored_version = 0; @@ -120,7 +84,7 @@ static esp_err_t verify_auth_config_version(nvs_handle_t handle) return ret; } - if (stored_version != TS_AUTH_CONFIG_VERSION) { + if (stored_version != TS_AUTH_CONFIG_VERSION && stored_version != TS_AUTH_PROTOTYPE_CONFIG_VERSION) { ESP_LOGE(TAG, "Auth config version mismatch: expected %u, got %u", (unsigned)TS_AUTH_CONFIG_VERSION, (unsigned)stored_version); ESP_LOGE(TAG, "Refusing to proceed because normal firmware may reset all auth users"); @@ -137,21 +101,7 @@ static esp_err_t build_default_credential(const credential_reset_target_t *targe return ESP_ERR_INVALID_ARG; } - memset(credential, 0, sizeof(*credential)); - esp_fill_random(credential->salt, TS_AUTH_SALT_LEN); - - esp_err_t ret = compute_password_hash(target->default_password, - credential->salt, - credential->hash); - if (ret != ESP_OK) { - return ret; - } - - credential->password_changed = false; - credential->failed_attempts = 0; - credential->lockout_until = 0; - - return ESP_OK; + return ts_auth_credential_create(target->default_password, false, credential); } static esp_err_t write_default_credential(nvs_handle_t handle, @@ -166,7 +116,7 @@ static esp_err_t write_default_credential(nvs_handle_t handle, ESP_LOGI(TAG, "Writing NVS blob %s/%s for %s", TS_AUTH_NVS_NAMESPACE, target->credential_key, target->username); - ret = nvs_set_blob(handle, target->credential_key, &credential, sizeof(credential)); + ret = nvs_set_blob(handle, target->credential_key, &credential, TS_AUTH_USER_CREDENTIAL_SIZE); memset(&credential, 0, sizeof(credential)); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to write %s credential", target->username); @@ -184,26 +134,25 @@ static esp_err_t verify_default_credential(nvs_handle_t handle, ESP_LOGE(TAG, "Failed to read back %s credential", target->username); return ret; } - if (readback_len != sizeof(readback)) { + if (readback_len != TS_AUTH_USER_CREDENTIAL_SIZE) { ESP_LOGE(TAG, "%s readback length mismatch: expected %u, got %u", - target->username, (unsigned)sizeof(readback), (unsigned)readback_len); + target->username, (unsigned)TS_AUTH_USER_CREDENTIAL_SIZE, (unsigned)readback_len); memset(&readback, 0, sizeof(readback)); return ESP_ERR_INVALID_SIZE; } - uint8_t expected_hash[TS_AUTH_HASH_LEN] = {0}; - ret = compute_password_hash(target->default_password, readback.salt, expected_hash); + ts_auth_user_credential_t decoded; + ret = ts_auth_credential_decode(&readback, readback_len, &decoded); + bool hash_ok = false; + if (ret == ESP_OK) ret = ts_auth_credential_verify(&decoded, target->default_password, &hash_ok); + memset(&decoded, 0, sizeof(decoded)); if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to compute expected hash for %s readback", target->username); memset(&readback, 0, sizeof(readback)); return ret; } - - bool hash_ok = constant_time_equal(readback.hash, expected_hash, TS_AUTH_HASH_LEN); bool state_ok = !readback.password_changed && readback.failed_attempts == 0 && readback.lockout_until == 0; - memset(expected_hash, 0, sizeof(expected_hash)); memset(&readback, 0, sizeof(readback)); if (!hash_ok || !state_ok) { diff --git a/main/ts_services.c b/main/ts_services.c index b074ce06..d93591ff 100644 --- a/main/ts_services.c +++ b/main/ts_services.c @@ -15,6 +15,7 @@ #include "ts_service.h" #include "ts_event.h" #include "ts_storage.h" +#include "ts_ota.h" #include "ts_console.h" #include "ts_cmd_all.h" #include "ts_hal.h" @@ -29,6 +30,7 @@ #include "ts_keystore.h" #include "ts_known_hosts.h" #include "ts_cert.h" +#include "ts_config_pack.h" #include "ts_pki_client.h" #include "ts_https.h" #include "ts_https_api.h" @@ -159,8 +161,7 @@ static esp_err_t storage_service_start(ts_service_handle_t handle, void *user_da ESP_LOGI(TAG, "SD card mounted at /sdcard"); // ====== SD 卡 Recovery 检查 ====== - // 检查 /sdcard/recovery/ 目录,如果存在且版本不同则自动恢复 - // 这是最低级别的恢复机制,即使 OTA 完全损坏也能工作 + // 保持原版 recovery 目录与清单恢复流程。 ret = ts_ota_check_recovery(); if (ret == ESP_OK) { // 如果执行了恢复,函数不会返回(会重启) @@ -199,7 +200,19 @@ esp_err_t ts_services_prepare_config(void) esp_err_t ret = storage_service_init(NULL, NULL); if (ret == ESP_OK) ret = storage_service_start(NULL, NULL); if (ret == ESP_OK) ret = ts_config_migrate_system(ts_storage_sd_mounted()); - if (ret == ESP_OK) ret = ts_config_schemas_init(); + if (ret == ESP_ERR_NOT_FINISHED) { + ESP_LOGW(TAG, "Encrypted legacy configuration unavailable; retaining existing internal settings. Inspect certificate and package validation."); + ret = ESP_OK; + } + /* HAL/LED can read an already accepted encrypted configuration before the + * network/security service starts. These owners do not generate new keys. */ + if (ret == ESP_OK) { + esp_err_t material = ts_cert_init(); + if (material == ESP_OK) material = ts_config_pack_init(); + if (material != ESP_OK) + ESP_LOGW(TAG, "Early encrypted configuration unavailable: %s", esp_err_to_name(material)); + ret = ts_config_schemas_init(); + } return ret; } @@ -596,7 +609,8 @@ static esp_err_t security_service_stop(ts_service_handle_t handle, void *user_da (void)handle; (void)user_data; - ts_pki_client_deinit(); + esp_err_t ret = ts_pki_client_deinit(); + if (ret != ESP_OK) return ret; ts_cert_deinit(); ts_known_hosts_deinit(); ts_keystore_deinit(); @@ -716,22 +730,30 @@ static void https_coordinator(void *arg) s_https_state.completed = control; portEXIT_CRITICAL(&s_https_control_lock); } - } else if (!ts_https_is_running()) { + } else { ts_cert_pki_status_t status = {0}; ts_https_config_t config = TS_HTTPS_CONFIG_DEFAULT(); esp_err_t ret = ts_cert_get_status(&status); bool ready = ret == ESP_OK && ts_cert_prerequisites(&status, config.require_client_cert); int64_t now = esp_timer_get_time() / 1000; - if (ts_https_retry_due(&retry, status.generation, control, true, ready, now)) { + ts_https_runtime_t runtime; + ts_https_get_runtime(&runtime); + bool replace = runtime.running && + (!ready || runtime.loaded_generation != status.generation); + /* The existing owner also retires obsolete connections. A failed stop + * retains its buffers and follows the same bounded retry policy. */ + bool due = ts_https_retry_due(&retry, status.generation, control, true, + ready || runtime.running, now); + if (due && (replace || (!runtime.running && ready))) { const char *stage = "cleanup"; ret = https_cleanup(); - if (ret == ESP_OK) { stage = "init"; ret = ts_https_init(&config); } - if (ret == ESP_OK) { stage = "default_endpoints"; ret = ts_https_register_default_api(); } + if (ret == ESP_OK && ready) { stage = "init"; ret = ts_https_init(&config); } + if (ret == ESP_OK && ready) { stage = "default_endpoints"; ret = ts_https_register_default_api(); } /* Stop intent supersedes this attempt before starting the listener. */ portENTER_CRITICAL(&s_https_control_lock); bool current = s_https_state.desired && control == s_https_state.control; portEXIT_CRITICAL(&s_https_control_lock); - if (ret == ESP_OK && current) { stage = "start"; ret = ts_https_start(); } + if (ret == ESP_OK && current && ready) { stage = "start"; ret = ts_https_start(); } if (ret != ESP_OK || !current) { esp_err_t cleanup = https_cleanup(); if (cleanup != ESP_OK) { stage = "cleanup"; ret = cleanup; } @@ -954,7 +976,7 @@ static esp_err_t webui_service_start(ts_service_handle_t handle, void *user_data return ret; } - ESP_LOGI(TAG, "WebUI server started on port 80"); + ESP_LOGI(TAG, "WebUI HTTP started"); return ESP_OK; } diff --git a/sdkconfig b/sdkconfig index 13301992..3a5fd0e7 100644 --- a/sdkconfig +++ b/sdkconfig @@ -1680,7 +1680,7 @@ CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set -CONFIG_LWIP_MAX_SOCKETS=16 +CONFIG_LWIP_MAX_SOCKETS=32 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set # CONFIG_LWIP_SO_LINGER is not set CONFIG_LWIP_SO_REUSE=y @@ -1909,7 +1909,7 @@ CONFIG_MBEDTLS_ROM_MD5=y # CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set -# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set +CONFIG_MBEDTLS_HAVE_TIME_DATE=y CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y CONFIG_MBEDTLS_SHA1_C=y CONFIG_MBEDTLS_SHA512_C=y @@ -2455,6 +2455,11 @@ CONFIG_TS_OTA_TASK_STACK_SIZE=8192 CONFIG_TS_OTA_TASK_PRIORITY=5 # end of TianShanOS OTA Configuration +# +# TianShanOS signed releases +# +# end of TianShanOS signed releases + # # TianShanOS Security Configuration # @@ -2503,7 +2508,6 @@ CONFIG_TS_WEBUI_WS_MAX_CLIENTS=8 CONFIG_TS_WEBUI_TERMINAL_OUTPUT_BUF_SIZE=32768 CONFIG_TS_WEBUI_AUTH_REQUIRED=y CONFIG_TS_WEBUI_CORS_ENABLE=y -CONFIG_TS_WEBUI_STATIC_PATH="/www" # end of TianShanOS WebUI Configuration # diff --git a/sdkconfig.defaults b/sdkconfig.defaults index e79434a2..3e6923ad 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -79,6 +79,9 @@ CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # 生产环境还应启用: # CONFIG_SECURE_BOOT=y # CONFIG_SECURE_FLASH_ENC_ENABLED=y +# Signed release proofs occupy the final APP sector, outside ESP image_len. +# Provisioning bootloaders must encrypt the complete APP slot. +# CONFIG_SECURE_FLASH_ENCRYPT_ONLY_IMAGE_LEN_IN_APP_PART is not set # CONFIG_SECURE_BOOT_DISABLE_JTAG=y # ============================================================================ @@ -143,7 +146,7 @@ CONFIG_LWIP_IPV4_NAPT=y # 注:ESP-IDF 5.x NAPT 使用默认连接数,不再需要手动配置 # LWIP Socket 配置(增加限制以支持多连接) -CONFIG_LWIP_MAX_SOCKETS=16 +CONFIG_LWIP_MAX_SOCKETS=32 # LWIP TCP 缓冲区优化(减少内存占用) CONFIG_LWIP_TCP_SND_BUF_DEFAULT=4096 @@ -188,7 +191,6 @@ CONFIG_TS_WEBUI_WS_ENABLE=y CONFIG_TS_WEBUI_WS_MAX_CLIENTS=8 CONFIG_TS_WEBUI_AUTH_REQUIRED=y CONFIG_TS_WEBUI_CORS_ENABLE=y -CONFIG_TS_WEBUI_STATIC_PATH="/www" # ============================================================================ # LED Matrix 配置 @@ -253,3 +255,6 @@ CONFIG_TS_CONFIG_PACK_SIGNING_ROOT_SHA256="ae5d4fe5cb45f725f4e8e26178ce583dfe550 # CONFIG_TS_NET_WIFI_AP_PASS="tianshan123" # CONFIG_TS_NET_WIFI_AP_CHANNEL=1 # CONFIG_TS_NET_WIFI_AP_MAX_CONN=4 + + +CONFIG_MBEDTLS_HAVE_TIME_DATE=y diff --git a/tests/certificate/README.md b/tests/certificate/README.md index 6ae2e369..7e8d8a37 100644 --- a/tests/certificate/README.md +++ b/tests/certificate/README.md @@ -8,7 +8,7 @@ ESP32 hardware configuration. This does not validate hardware TLS or Flash. Prerequisites: C compiler with ASan/UBSan, CMake, Node, Python with `cryptography`, and the existing ESP-IDF checkout. No production credentials are read. Credentials -are generated into the temporary build directory with fixed 2026 validity dates. +are generated into temporary build directories with fixed validity dates. Private keys are test-only, temporary, and never printed. On this macOS workspace (Command Line Tools avoids requiring changes to Xcode's @@ -33,6 +33,12 @@ prebuilt mbedTLS is not sanitizer-instrumented. The application under test is. - `test_time_retry.c`: pure UTC conversion, calendar limits, serial output boundaries, retry schedule and control intent policy. +- test_https_auth.py / test_https_auth.c: production auth unit and request + handler, real mbedTLS PEM parsing and isolated certificate-chain checks. Covers + all five role requirements, device/management separation, missing or ambiguous + OU and certificate/context failures. HTTP transport lookup is a stub; this + does not test an actual TLS handshake. The isolated PKI uses 2020–2099 dates. + --source-ref REV runs the same checks against older production code. - `test_material.c`: includes the entire production certificate implementation; real mbedTLS parses generated PEM and checks keys. Injected heap/parse allocation, NVS set/commit/read and notification failures; pthread readers/writers; metadata diff --git a/tests/certificate/generate_fixtures.py b/tests/certificate/generate_fixtures.py index 54c2b83e..2d5f14fe 100644 --- a/tests/certificate/generate_fixtures.py +++ b/tests/certificate/generate_fixtures.py @@ -12,14 +12,18 @@ other = ec.generate_private_key(ec.SECP256R1()) def name(cn): return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)]) issuer = name('TianShan isolated test CA') -def cert(label, public, start, end, serial, ca=False): +def cert(label, public, start, end, serial, ca=False, constraints=True, cert_sign=None, eku=None): c = (x509.CertificateBuilder().subject_name(issuer if ca else name('localhost')) .issuer_name(issuer).public_key(public.public_key()).serial_number(serial) .not_valid_before(datetime.fromisoformat(start).replace(tzinfo=timezone.utc)) .not_valid_after(datetime.fromisoformat(end).replace(tzinfo=timezone.utc)) - .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]), critical=False)) - if not ca: c = c.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False) + if constraints: c = c.add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) + if cert_sign is not None: + c = c.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, + key_encipherment=False, data_encipherment=False, key_agreement=False, + key_cert_sign=cert_sign, crl_sign=cert_sign, encipher_only=False, decipher_only=False), critical=True) + if not ca: c = c.add_extension(x509.ExtendedKeyUsage(eku if eku is not None else [ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False) out.joinpath(label+'.pem').write_bytes(c.sign(ca_key, hashes.SHA256()).public_bytes(serialization.Encoding.PEM)) cert('ca',ca_key,'2020-01-01','2099-01-01',1,True) cert('a',key,'2026-01-01','2027-01-01',2) @@ -28,3 +32,17 @@ def cert(label, public, start, end, serial, ca=False): cert('expired',key,'2020-01-01','2021-01-01',5) cert('wrong',other,'2026-01-01','2027-01-01',6) out.joinpath('key.pem').write_bytes(key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())) + +cert('ca_signing',ca_key,'2020-01-01','2099-01-01',7,True,cert_sign=True) +cert('ca_wrong_usage',ca_key,'2020-01-01','2099-01-01',8,True,cert_sign=False) +cert('ca_no_constraints',ca_key,'2020-01-01','2099-01-01',9,True,constraints=False) + +cert('client_only',key,'2026-01-01','2027-01-01',10,eku=[ExtendedKeyUsageOID.CLIENT_AUTH]) + +cert('codesign_only',key,'2026-01-01','2027-01-01',11,eku=[ExtendedKeyUsageOID.CODE_SIGNING]) +cert('device_ca',key,'2020-01-01','2099-01-01',12,True,cert_sign=True) +known_ca_key = ca_key +ca_key = ec.generate_private_key(ec.SECP256R1()) +cert('untrusted_issuer',key,'2026-01-01','2027-01-01',13) +cert('untrusted_ca',ca_key,'2020-01-01','2099-01-01',14,True,cert_sign=True) +ca_key = known_ca_key diff --git a/tests/certificate/run_host.sh b/tests/certificate/run_host.sh index ade0b047..385cfed6 100755 --- a/tests/certificate/run_host.sh +++ b/tests/certificate/run_host.sh @@ -1,12 +1,15 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh : "${IDF_PATH:=/Users/massif/esp/v5.5.2/esp-idf}" -: "${CERT_TEST_BUILD:=/tmp/tianshan-certificate-tests}" +: "${CERT_TEST_BUILD:=$TS_TEST_BUILD_ROOT/certificates}" +export CERT_TEST_BUILD : "${CERT_MBEDTLS_BUILD:=/tmp/tianshan-cert-mbedtls}" : "${CERT_TEST_PYTHON:=python3}" export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" mkdir -p "$CERT_TEST_BUILD" +"$CERT_TEST_PYTHON" tests/certificate/test_https_auth.py cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -Itests/certificate/stubs -Icomponents/ts_cert/include -Icomponents/ts_core/ts_config/include -I"$IDF_PATH/components/mbedtls/mbedtls/include" tests/certificate/test_subject.c components/ts_cert/src/ts_cert_subject.c "$CERT_MBEDTLS_BUILD/library/libmbedx509.a" "$CERT_MBEDTLS_BUILD/library/libmbedcrypto.a" -lm -o "$CERT_TEST_BUILD/subject" "$CERT_TEST_BUILD/subject" "$CERT_TEST_PYTHON" tests/certificate/generate_fixtures.py "$CERT_TEST_BUILD/fixtures" @@ -20,7 +23,7 @@ cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -I"$CERT_TEST_BUIL "$CERT_TEST_BUILD/lifecycle" cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -I"$CERT_TEST_BUILD" -Itests/certificate/stubs -Icomponents/ts_cert/include -Icomponents/ts_core/ts_config/include -Icomponents/ts_https/include -Icomponents/ts_https/src -I"$IDF_PATH/components/mbedtls/mbedtls/include" tests/certificate/test_coordinator.c -lpthread -o "$CERT_TEST_BUILD/coordinator" "$CERT_TEST_BUILD/coordinator" -cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -Wno-deprecated-declarations -I"$CERT_TEST_BUILD" -Itests/certificate/stubs -Icomponents/ts_cert/include -Icomponents/ts_core/ts_config/include -Icomponents/ts_https/include -I"$IDF_PATH/components/mbedtls/mbedtls/include" -I"$IDF_PATH/components/json/cJSON" tests/certificate/test_api.c components/ts_cert/src/ts_cert_time.c components/ts_cert/src/ts_cert_subject.c "$IDF_PATH/components/json/cJSON/cJSON.c" "$CERT_MBEDTLS_BUILD/library/libmbedx509.a" "$CERT_MBEDTLS_BUILD/library/libmbedcrypto.a" -lpthread -o "$CERT_TEST_BUILD/api" +cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -Wno-deprecated-declarations -I"$CERT_TEST_BUILD" -Itests/certificate/stubs -Icomponents/ts_cert/include -Icomponents/ts_core/ts_config/include -Icomponents/ts_https/include -Icomponents/ts_webui/include -I"$IDF_PATH/components/mbedtls/mbedtls/include" -I"$IDF_PATH/components/json/cJSON" tests/certificate/test_api.c components/ts_cert/src/ts_cert_time.c components/ts_cert/src/ts_cert_subject.c "$IDF_PATH/components/json/cJSON/cJSON.c" "$CERT_MBEDTLS_BUILD/library/libmbedx509.a" "$CERT_MBEDTLS_BUILD/library/libmbedcrypto.a" -lpthread -o "$CERT_TEST_BUILD/api" "$CERT_TEST_BUILD/api" "$CERT_TEST_BUILD/fixtures" cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -I"$CERT_TEST_BUILD" -Itests/certificate/stubs tests/certificate/test_time_cancel.c -lpthread -o "$CERT_TEST_BUILD/time_cancel" "$CERT_TEST_BUILD/time_cancel" diff --git a/tests/certificate/stubs/esp_https_server.h b/tests/certificate/stubs/esp_https_server.h index 8aa1f820..2b90d6fb 100644 --- a/tests/certificate/stubs/esp_https_server.h +++ b/tests/certificate/stubs/esp_https_server.h @@ -1,6 +1,6 @@ #include "esp_http_server.h" typedef struct { - struct {int server_port,max_open_sockets,recv_wait_timeout,send_wait_timeout,task_caps,stack_size;bool lru_purge_enable,enable_so_linger;} httpd; + struct {int server_port,ctrl_port,max_open_sockets,recv_wait_timeout,send_wait_timeout,task_caps,stack_size;bool lru_purge_enable,enable_so_linger;} httpd; uint16_t port_secure; const uint8_t *servercert,*prvtkey_pem,*cacert_pem; size_t servercert_len,prvtkey_len,cacert_len; diff --git a/tests/certificate/stubs/esp_timer.h b/tests/certificate/stubs/esp_timer.h new file mode 100644 index 00000000..f43e0a86 --- /dev/null +++ b/tests/certificate/stubs/esp_timer.h @@ -0,0 +1,2 @@ +#include +int64_t esp_timer_get_time(void); diff --git a/tests/certificate/stubs/ts_time_sync.h b/tests/certificate/stubs/ts_time_sync.h index 948df4b7..6723806f 100644 --- a/tests/certificate/stubs/ts_time_sync.h +++ b/tests/certificate/stubs/ts_time_sync.h @@ -1 +1,5 @@ +#ifndef CERT_TIME_SYNC_STUB_H +#define CERT_TIME_SYNC_STUB_H +/* The production certificate owner includes this header without using its API. */ #include "platform.h" +#endif diff --git a/tests/certificate/test_coordinator.c b/tests/certificate/test_coordinator.c index 9af37ea4..b425a252 100644 --- a/tests/certificate/test_coordinator.c +++ b/tests/certificate/test_coordinator.c @@ -46,7 +46,8 @@ int main(void) { atomic_store(&allowed,true);simulated_ms=5000;wait_running(true); unsigned count=starts; for(int i=0;i<100;++i)https_conditions_changed(NULL,NULL);settle();assert(starts==count); - stored_generation=2;settle();ts_https_runtime_t r;ts_https_get_runtime(&r);assert(r.loaded_generation==1); + stored_generation=2;settle();ts_https_runtime_t r;ts_https_get_runtime(&r);assert(r.loaded_generation==2); + assert(starts==count+1);count=starts; assert(https_service_stop(NULL,NULL)==0);assert(!ts_https_is_running()); for(int i=0;i<100;++i)https_conditions_changed(NULL,NULL);simulated_ms=100000;settle();assert(starts==count); start_error=ESP_FAIL;assert(https_service_start(NULL,NULL)==0);settle();assert(starts==count+1); diff --git a/tests/certificate/test_https_auth.c b/tests/certificate/test_https_auth.c new file mode 100644 index 00000000..8fd5b177 --- /dev/null +++ b/tests/certificate/test_https_auth.c @@ -0,0 +1,128 @@ +/* Real certificate parsing/auth helpers and extracted production request handler. + * Only the HTTP transport certificate lookup and response/effect boundaries are stubs. */ +#include "ts_https_internal.h" +#include "ts_cert_time.h" +#include "ts_cert.h" +#include "mbedtls/ssl.h" +#include +#include +#include +#include + +#define HTTPD_500_INTERNAL_SERVER_ERROR 500 +static ts_https_config_t s_config = TS_HTTPS_CONFIG_DEFAULT(); +static ts_cert_snapshot_t s_material={.generation=1}; +static ts_cert_pki_status_t fixture_material={.generation=1,.has_private_key=true,.has_certificate=true,.has_ca_chain=true,.key_valid=true,.key_matches=true,.ca_valid=true,.time_ready=true,.cert_info={.is_valid=true}}; +static esp_err_t fixture_material_error; +esp_err_t ts_cert_get_status(ts_cert_pki_status_t *out){*out=fixture_material;return fixture_material_error;} +static const mbedtls_x509_crt *fixture_cert; +static unsigned calls, checks, failures; +static int status; +static ts_https_auth_t observed; +static void check(bool condition, const char *label) { + ++checks; + if (!condition) { ++failures; fprintf(stderr, "FAIL %s\n", label); } +} +static const mbedtls_x509_crt *get_client_cert(httpd_req_t *r) { (void)r; return fixture_cert; } +static int httpd_resp_send_err(httpd_req_t *r,int code,const char *message) { + (void)r; (void)message; status=code; return ESP_OK; +} +esp_err_t ts_https_send_error(ts_https_req_t *r,int code,const char *message) {(void)r;(void)message;status=code;return ESP_OK;} +esp_err_t ts_https_send_unauthorized(ts_https_req_t *r) { (void)r; status=401; return ESP_OK; } +esp_err_t ts_https_send_forbidden(ts_https_req_t *r) { (void)r; status=403; return ESP_OK; } +static int target(ts_https_req_t *r) { ++calls; observed=r->auth; status=200; return ESP_OK; } +#include "https_auth_handler.inc" + +static void request(ts_https_role_t minimum, int expected) { + unsigned before=calls; + ts_https_endpoint_t endpoint={.handler=target,.min_role=minimum}; + httpd_req_t req={.user_ctx=&endpoint}; + check(generic_handler(&req)==ESP_OK,"HTTP response boundary succeeds"); + check(status==expected,"actual handler status matches policy"); + check(calls==before+(expected==200),"rejected request never calls business"); +} +static void parse(const char *dir,const char *name,mbedtls_x509_crt *cert) { + char path[1024]; snprintf(path,sizeof(path),"%s/%s.pem",dir,name); + mbedtls_x509_crt_init(cert); + assert(mbedtls_x509_crt_parse_file(cert,path)==0); +} +int main(int argc,char **argv) { + assert(argc==2); + const bool allowed[5][5]={ + {true,false,false,false,false}, + {true,true,false,false,false}, + {true,true,true,false,false}, + {true,true,true,true,false}, + {true,true,false,false,true} + }; + for(int user=0;user<5;++user) for(int required=0;required<5;++required) { + ts_https_auth_t auth={.authenticated=true,.role=user}; + check(ts_https_role_has_permission(user,required)==allowed[user][required],"5x5 role matrix"); + check(ts_https_check_permission(&auth,required)==allowed[user][required],"5x5 authenticated permission"); + auth.authenticated=false; + check(ts_https_check_permission(&auth,required)==(required==0),"unauthenticated denies protected roles"); + } + check(!ts_https_role_has_permission((ts_https_role_t)-1,TS_HTTPS_ROLE_VIEWER),"negative role denied"); + check(!ts_https_role_has_permission((ts_https_role_t)99,TS_HTTPS_ROLE_ANONYMOUS),"unknown role denied"); + check(!ts_https_role_has_permission(TS_HTTPS_ROLE_ADMIN,(ts_https_role_t)99),"unknown requirement denied"); + check(ts_https_check_permission(NULL,TS_HTTPS_ROLE_ANONYMOUS),"public health without auth"); + check(!ts_https_check_permission(NULL,TS_HTTPS_ROLE_VIEWER),"protected without auth"); + + mbedtls_x509_crt ca;parse(argv[1],"root",&ca); + const char *names[]={"anonymous","viewer","operator","admin","device","mixed-case","missing-ou","unknown-ou", + "duplicate-same","duplicate-mixed","nul-role","long-role"}; + const int roles[]={0,1,2,3,4,3,0,0,0,0,0,0}; + for(unsigned i=0;i=8; + ts_https_auth_t auth;memset(&auth,0xa5,sizeof(auth)); + esp_err_t ret=ts_https_auth_from_cert(&cert,&auth); + check(invalid?ret!=ESP_OK:ret==ESP_OK,names[i]); + check(auth.role==roles[i],"helper role matches full OU"); + check(auth.authenticated==!invalid,"invalid role clears identity"); + if(!invalid) { + check(!strcmp(auth.username,"fixture")&&!strcmp(auth.organization,"Test Organization"),"CN/O display preserved"); + } + fixture_cert=&cert; + for(int required=0;required<5;++required) + request(required,allowed[roles[i]][required]?200:invalid?401:403); + /* The public route and helper must see the same parsed identity. */ + request(TS_HTTPS_ROLE_ANONYMOUS,200); + check(observed.role==auth.role&&observed.authenticated==auth.authenticated,"one identity extractor"); + mbedtls_x509_crt_free(&cert); + } + mbedtls_x509_crt admitted_peer;parse(argv[1],"admin",&admitted_peer);fixture_cert=&admitted_peer; + request(TS_HTTPS_ROLE_ADMIN,200); + fixture_material.ca_valid=false;request(TS_HTTPS_ROLE_ADMIN,503); + request(TS_HTTPS_ROLE_ANONYMOUS,200);check(!observed.authenticated&&observed.role==TS_HTTPS_ROLE_ANONYMOUS,"public health cannot inherit identity from an unapproved context"); + fixture_material.ca_valid=true;fixture_material.generation=2;request(TS_HTTPS_ROLE_ADMIN,503); + request(TS_HTTPS_ROLE_ANONYMOUS,200);check(!observed.authenticated,"stale TLS generation only gets anonymous public health"); + fixture_material.generation=1;fixture_material_error=ESP_FAIL;request(TS_HTTPS_ROLE_ADMIN,503);fixture_material_error=0; + fixture_material.storage_error=true;request(TS_HTTPS_ROLE_ADMIN,503);fixture_material.storage_error=false; + fixture_material.time_ready=false;request(TS_HTTPS_ROLE_ADMIN,503);fixture_material.time_ready=true; + request(TS_HTTPS_ROLE_ADMIN,200);mbedtls_x509_crt_free(&admitted_peer); + mbedtls_x509_crt_free(&ca); + + fixture_cert=NULL; + request(TS_HTTPS_ROLE_ANONYMOUS,200); + for(int role=1;role<5;++role) request(role,401); + s_config.require_client_cert=false; + request(TS_HTTPS_ROLE_ANONYMOUS,200); request(TS_HTTPS_ROLE_ADMIN,401); + s_config.require_client_cert=true; + ts_https_auth_t auth={.authenticated=true,.role=TS_HTTPS_ROLE_ADMIN}; + check(ts_https_auth_from_cert(NULL,&auth)!=ESP_OK&&!auth.authenticated&&auth.role==0,"NULL cert clears stale admin"); + auth=(ts_https_auth_t){.authenticated=true,.role=TS_HTTPS_ROLE_ADMIN}; + check(ts_https_get_client_auth(NULL,&auth)!=ESP_OK&&!auth.authenticated&&auth.role==0,"NULL SSL clears stale admin"); + mbedtls_ssl_context ssl;mbedtls_ssl_init(&ssl); + auth=(ts_https_auth_t){.authenticated=true,.role=TS_HTTPS_ROLE_ADMIN}; + check(ts_https_get_client_auth(&ssl,&auth)!=ESP_OK&&!auth.authenticated&&auth.role==0,"missing peer cert clears stale admin"); + mbedtls_ssl_free(&ssl); + /* A zero-length role value is tested at the parsed-name boundary. */ + mbedtls_x509_crt empty={0};unsigned char ou[]={0x55,4,11}; + empty.subject.oid.p=ou;empty.subject.oid.len=sizeof(ou); + check(ts_https_auth_from_cert(&empty,&auth)!=ESP_OK&&!auth.authenticated,"empty role denied"); + printf("%u checks, %u failures: real mbedTLS PEM/chain, role matrix and actual generic_handler; no TLS sockets\n",checks,failures); + return failures?1:0; +} diff --git a/tests/certificate/test_https_auth.py b/tests/certificate/test_https_auth.py new file mode 100644 index 00000000..041de102 --- /dev/null +++ b/tests/certificate/test_https_auth.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Production auth unit + actual generic_handler, disposable PKI, no network.""" +from pathlib import Path +from datetime import datetime,timezone +import argparse,os,re,subprocess,tempfile +from cryptography import x509 +from cryptography.x509.oid import NameOID,ExtendedKeyUsageOID +from cryptography.hazmat.primitives import hashes,serialization +from cryptography.hazmat.primitives.asymmetric import ec + +ROOT=Path(__file__).resolve().parents[2] +parser=argparse.ArgumentParser() +parser.add_argument("--source-ref",help="Use auth/server production code from a git revision") +args=parser.parse_args() +IDF=Path(os.environ.get("IDF_PATH","/Users/massif/esp/v5.5.2/esp-idf")) +MBED=Path(os.environ.get("CERT_MBEDTLS_BUILD","/tmp/tianshan-cert-mbedtls")) +def source(path): + return subprocess.check_output(["git","show",f"{args.source_ref}:{path}"],cwd=ROOT,text=True) if args.source_ref else (ROOT/path).read_text() +def function(text,name): + match=re.search(r"^(?:static )?[^\n;]+\b"+name+r"\([^;]+?\)\s*\{",text,re.M) + assert match,name + return text[match.start():text.index("\n}",match.start())+2]+"\n" +with tempfile.TemporaryDirectory(prefix="ts-mtls-auth-") as tmp: + d=Path(tmp);stub=d/"stubs";stub.mkdir() + (stub/"esp_http_server.h").write_text("""#pragma once +#include "esp_err.h" +typedef void *httpd_handle_t; +typedef int httpd_method_t; +typedef struct { void *user_ctx; } httpd_req_t; +""") + ca_key=ec.generate_private_key(ec.SECP256R1()) + leaf_key=ec.generate_private_key(ec.SECP256R1()) + issuer=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,"Isolated auth test root")]) + def issue(label,role_values,serial,ca=False): + subject=issuer if ca else x509.Name([ + x509.NameAttribute(NameOID.COMMON_NAME,"fixture"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME,"Test Organization"), + *[x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME,v) for v in role_values]]) + cert=(x509.CertificateBuilder().subject_name(subject).issuer_name(issuer) + .public_key((ca_key if ca else leaf_key).public_key()).serial_number(serial) + .not_valid_before(datetime(2020,1,1,tzinfo=timezone.utc)) + .not_valid_after(datetime(2099,1,1,tzinfo=timezone.utc)) + .add_extension(x509.BasicConstraints(ca=ca,path_length=None),critical=True) + .add_extension(x509.KeyUsage(digital_signature=True,content_commitment=False, + key_encipherment=False,data_encipherment=False,key_agreement=False, + key_cert_sign=ca,crl_sign=ca,encipher_only=None,decipher_only=None),critical=True)) + if not ca:cert=cert.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False) + (d/(label+".pem")).write_bytes(cert.sign(ca_key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)) + issue("root",[],1,True) + cases={n:[n] for n in ["anonymous","viewer","operator","admin","device"]} + cases.update({"mixed-case":["AdMiN"],"missing-ou":[],"unknown-ou":["NotAdmin"], + "duplicate-same":["admin","admin"],"duplicate-mixed":["admin","device"], + "nul-role":["admin\0device"],"long-role":["admin"+"x"*35]}) + for i,(name,roles) in enumerate(cases.items(),2):issue(name,roles,i) + server=source("components/ts_https/src/ts_https.c") + pieces=[] + # The older server had a separate extractor; include it only for before evidence. + if "static void extract_auth_from_cert(" in server: + pieces += [function(server,"extract_dn_field"), + '#define OID_CN "\\x55\\x04\\x03"\n#define OID_O "\\x55\\x04\\x0a"\n#define OID_OU "\\x55\\x04\\x0b"\n', + function(server,"extract_auth_from_cert")] + if "client_auth_current" in server: + pieces.append(function(source("components/ts_cert/src/ts_cert.c"),"ts_cert_prerequisites")) + pieces.append(function(server,"generic_handler")) + (d/"https_auth_handler.inc").write_text("\n".join(pieces)) + auth=d/"auth.c";auth.write_text(source("components/ts_https/src/ts_https_auth.c")) + includes=[d,stub,ROOT/"tests/certificate/stubs",ROOT/"components/ts_https/include", + ROOT/"components/ts_https/src",ROOT/"components/ts_cert/include",IDF/"components/mbedtls/mbedtls/include"] + cmd=["cc","-std=gnu11","-g","-fsanitize=address,undefined","-fno-sanitize-recover=all", + *["-I"+str(p) for p in includes],str(ROOT/"tests/certificate/test_https_auth.c"),str(auth), + str(ROOT/"components/ts_cert/src/ts_cert_time.c"), + *[str(MBED/"library"/("lib"+n+".a")) for n in ["mbedtls","mbedx509","mbedcrypto"]], + "-lpthread","-lm","-o",str(d/"auth")] + subprocess.run(cmd,check=True,cwd=ROOT) + subprocess.run([str(d/"auth"),str(d)],check=True,cwd=ROOT) diff --git a/tests/certificate/test_time_cancel.c b/tests/certificate/test_time_cancel.c index 68f96ba7..01503f23 100644 --- a/tests/certificate/test_time_cancel.c +++ b/tests/certificate/test_time_cancel.c @@ -16,7 +16,8 @@ static int set_clock(const struct timeval *tv,const struct timezone *tz) {(void) int ts_event_post(const char *base,int id,const void *data,size_t length,unsigned wait) { (void)base;(void)id;(void)wait;assert(length==sizeof(delivered));delivered=*(const ts_time_sync_info_t *)data;++notifications;return event_error; } -static struct {_Atomic bool enroll_running,stop_requested;} s_client; +static struct {_Atomic bool enroll_running,stop_requested;void *enroll_task;} s_client; +static void *xTaskGetCurrentTaskHandle(void) {return (void *)1;} static unsigned delays; static bool finish_on_delay; static void vTaskDelay(unsigned t) {(void)t;++delays;if(finish_on_delay)s_client.enroll_running=false;} @@ -34,6 +35,7 @@ int main(void) { for(unsigned i=0;i<3;++i){const char *tz[]={"UTC","CST-8","PST8PDT"};setenv("TZ",tz[i],1);tzset();clock_value=1735689599;assert(ts_time_sync_needs_sync());clock_value=1735689600;assert(!ts_time_sync_needs_sync());} s_client.enroll_running=true;ts_pki_client_stop_auto_enroll();assert(s_client.stop_requested&&s_client.enroll_running&&delays==50); finish_on_delay=true;ts_pki_client_stop_auto_enroll();assert(!s_client.enroll_running); + s_client.enroll_task=(void *)1;s_client.enroll_running=true;unsigned before=delays;ts_pki_client_stop_auto_enroll();assert(delays==before); puts("PASS actual time notifications/UTC readiness and cooperative enrollment stop (syscalls/tasks mocked)"); return 0; } diff --git a/tests/ci/test_policy.py b/tests/ci/test_policy.py index da02f7d9..1856e292 100644 --- a/tests/ci/test_policy.py +++ b/tests/ci/test_policy.py @@ -3,6 +3,7 @@ import importlib.util import json import os +import re from pathlib import Path import subprocess import tempfile @@ -19,14 +20,33 @@ def load(name): profile, gate, web, release = [load(name) for name in ('check_profile', 'check_gate', 'check_web_artifacts', 'check_release_state')] class PolicyTests(unittest.TestCase): + def test_runtime_inputs_are_prepared_on_a_fresh_runner(self): + workflow=(ROOT/'.github/workflows/build.yml').read_text() + runtime=workflow.split(' runtime-tests:\n',1)[1].split('\n build:\n',1)[0] + self.assertIn('needs: [changes, build]',runtime) + sparse=runtime.split('sparse-checkout set ',1)[1].split('\n',1)[0].split() + referenced=set() + for fixture in (ROOT/'tests/runtime').glob('*.py'): + referenced.update(re.findall(r'components/([A-Za-z0-9_-]+)/',fixture.read_text())) + sdk={name for name in referenced if not name.startswith(('ts_','ch405','espressif__'))} + self.assertTrue(sdk <= {path.split('/')[1] for path in sparse},'Missing SDK runtime sources: '+str(sorted(sdk-{path.split('/')[1] for path in sparse}))) + self.assertIn('name: runtime-dependencies-${{ github.sha }}',runtime) + self.assertIn('path: managed_components/espressif__esp_websocket_client',runtime) + build=workflow.split('\n build:\n',1)[1].split('\n web-artifacts:\n',1)[0] + self.assertIn('name: runtime-dependencies-${{ github.sha }}',build) + self.assertIn('path: managed_components/espressif__esp_websocket_client/',build) + self.assertIn('include-hidden-files: true',build) + self.assertIn('if-no-files-found: error',build) + def test_events_keep_main_release_and_force_full(self): cases = [ - ('RMinte-AI/TianshanOS','push','refs/heads/main',{},True), - ('RMinte-AI/TianshanOS','push','refs/heads/develop',{},False), + ('RMinte/TianshanOS','push','refs/heads/main',{},True), + ('RMinte/TianshanOS','push','refs/heads/develop',{},False), ('massif-01/TianshanOS','push','refs/heads/main',{},False), - ('RMinte-AI/TianshanOS','push','refs/tags/v0.6.1',{},True), - ('RMinte-AI/TianshanOS','release','refs/tags/v0.6.1',{'action':'published'},True), - ('RMinte-AI/TianshanOS','workflow_dispatch','refs/heads/main',{},False), + ('RMinte-AI/TianshanOS','push','refs/heads/main',{},False), + ('RMinte/TianshanOS','push','refs/tags/v0.6.1',{},True), + ('RMinte/TianshanOS','release','refs/tags/v0.6.1',{'action':'published'},True), + ('RMinte/TianshanOS','workflow_dispatch','refs/heads/main',{},False), ] for repo,event,ref,payload,publish in cases: with self.subTest(repo=repo,event=event): diff --git a/tests/exec_results/run_host.sh b/tests/exec_results/run_host.sh index b84991da..75866846 100644 --- a/tests/exec_results/run_host.sh +++ b/tests/exec_results/run_host.sh @@ -11,9 +11,12 @@ python3 - "$build" <<'PYCODE' from pathlib import Path import sys s=Path('components/ts_api/src/ts_api_ssh.c').read_text();parts=[] -for name in ['api_ssh_exec_stream','api_ssh_exec_status']: +for name in ['api_ssh_exec_stream_impl','api_ssh_exec_stream','api_ssh_exec_stream_for_session','api_ssh_exec_status_impl','api_ssh_exec_status','api_ssh_exec_status_for_session','api_ssh_cancel_impl','api_ssh_cancel','api_ssh_cancel_for_session']: a=s.index('static esp_err_t '+name+'(');b=s.index('\n}',a)+2;parts.append(s[a:b]) Path(sys.argv[1],'exec_api.inc').write_text('\n'.join(parts)) PYCODE cc -std=gnu11 -g -Wno-deprecated-declarations -Wno-macro-redefined -fsanitize=address,undefined -I"$build" -Itests/ws_subscriptions/stubs -Icomponents/ts_webui/include -Icomponents/ts_webui/src -Icomponents/ts_security/include -Icomponents/ts_automation/include -Icomponents/ts_drivers/include -Icomponents/ts_console/include -Icomponents/ts_net/include -I"$cjson" tests/ws_subscriptions/test_exec_api.c "$cjson/cJSON.c" -lm -o "$build/test" "$build/test" + +cc -std=gnu11 -g -Wno-deprecated-declarations -Wno-macro-redefined -fsanitize=address,undefined -fno-sanitize-recover=all -Itests/ws_subscriptions/stubs -Icomponents/ts_webui/include -Icomponents/ts_webui/src -Icomponents/ts_security/include -Icomponents/ts_automation/include -Icomponents/ts_drivers/include -Icomponents/ts_console/include -Icomponents/ts_net/include -I"$cjson" tests/ws_subscriptions/test_exec_ownership.c "$cjson/cJSON.c" -lm -o "$build/ownership" +"$build/ownership" diff --git a/tests/fan_review/test_review.c b/tests/fan_review/test_review.c index 39cd8a37..216b4d35 100644 --- a/tests/fan_review/test_review.c +++ b/tests/fan_review/test_review.c @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/tests/fixtures/failure-texts/system.json b/tests/fixtures/failure-texts/system.json index d188100d..f16851e2 100644 --- a/tests/fixtures/failure-texts/system.json +++ b/tests/fixtures/failure-texts/system.json @@ -110,12 +110,12 @@ "login.locked": { "zh-CN": { "type": "inline", - "text": "登录失败:连续输错次数太多,这个账户暂时被锁定。请等 5 分钟后再试。", + "text": "登录失败:连续输错次数太多,这个账户暂时被锁定。请保持设备开机,等 5 分钟后再试;重启会重新开始冷却。", "details": null }, "en-US": { "type": "inline", - "text": "Login failed: too many wrong attempts have locked this account for a while. Wait 5 minutes and try again.", + "text": "Login failed: too many wrong attempts have locked this account for a while. Keep the device on and wait 5 minutes before trying again. Restarting begins a new cooldown.", "details": null } }, diff --git a/tests/fixtures/failure-wire/wire-pack-unsupported.json b/tests/fixtures/failure-wire/wire-pack-unsupported.json new file mode 100644 index 00000000..d7da9b00 --- /dev/null +++ b/tests/fixtures/failure-wire/wire-pack-unsupported.json @@ -0,0 +1 @@ +{"code":8,"message":"pack_apply_unsupported","data":{"detail":"Generic configuration pack application is not supported"}} \ No newline at end of file diff --git a/tests/macos27/ui-correction.browser.cjs b/tests/macos27/ui-correction.browser.cjs index cb7e3a35..76dcc9e1 100644 --- a/tests/macos27/ui-correction.browser.cjs +++ b/tests/macos27/ui-correction.browser.cjs @@ -2,7 +2,7 @@ const {test, before, after} = require('node:test'); const assert = require('node:assert/strict'); const path = require('node:path'), fs = require('node:fs'); -const {chromium} = require('../prompts/node_modules/playwright'); +const {chromium} = require('playwright'); const L = require('../macos27-r2/lib.cjs'); const out = path.join(L.REPO, 'output/playwright/ui-correction'); let browser, fixture; diff --git a/tests/prompts/api-methods.browser.test.cjs b/tests/prompts/api-methods.browser.test.cjs new file mode 100644 index 00000000..6d2db9a3 --- /dev/null +++ b/tests/prompts/api-methods.browser.test.cjs @@ -0,0 +1,47 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const kit = require('./pagekit.cjs'); +kit.install(); + +test('real browser sends parameterless validation and stats reset as POST', async () => { + await kit.withPage('zh-CN', call => ({code: 0, data: {method: call.method}}), async ({page, calls}) => { + await page.evaluate(async () => { + await api.call('ota.validate'); + await api.call('automation.action.stats.reset', {id: 'fixture'}); + await api.call('system.info'); + }); + for (const endpoint of ['ota/validate', 'automation/action/stats/reset', 'system/info']) { + assert.ok(calls.some(call => call.endpoint === endpoint && call.method === 'POST'), endpoint); + } + }); +}); + +test('browser device fixture rejects disallowed methods before success responder', async () => { + let reached = false; + await kit.withPage('en-US', call => { + if (call.endpoint === 'ota/validate') reached = true; + return {code: 0}; + }, async ({page}) => { + const status = await page.evaluate(async () => (await fetch('/api/v1/ota/validate')).status); + assert.equal(status, 405); + assert.equal(reached, false); + const result = await page.evaluate(() => api.call('ota.validate')); + assert.equal(result.code, 0); + assert.equal(reached, true); + }); +}); + +test('actual engine controls send writes once and refresh status with GET', async () => { + await kit.withPage('en-US', () => ({code: 0, data: {state: 'running'}}), async ({page, calls}) => { + await page.evaluate(async () => { + const status = document.createElement('div'); + status.id = 'automation-status'; + document.body.appendChild(status); + for (const action of ['start', 'stop', 'pause', 'reload']) await automationControl(action); + }); + assert.deepEqual(calls.filter(call => /^automation\/(start|stop|pause|reload)$/.test(call.endpoint)) + .map(call => [call.endpoint, call.method]), + ['start', 'stop', 'pause', 'reload'].map(action => [`automation/${action}`, 'POST'])); + assert.equal(calls.filter(call => call.endpoint === 'automation/status' && call.method === 'GET').length, 4); + }); +}); diff --git a/tests/prompts/api-methods.json b/tests/prompts/api-methods.json new file mode 100644 index 00000000..6276865c --- /dev/null +++ b/tests/prompts/api-methods.json @@ -0,0 +1,289 @@ +{ + "http": { + "auth/login": 2, + "auth/logout": 2, + "file/download": 1, + "file/upload": 2, + "ota/firmware": 2, + "ota/www": 2 + }, + "logical": { + "auth.admin.reset_password": 2, + "auth.admin.set_password": 2, + "auth.change_password": 2, + "auth.login": 2, + "auth.logout": 2, + "auth.root.set_password": 2, + "auth.status": 2, + "automation.action.stats": 3, + "automation.action.stats.reset": 14, + "automation.actions.add": 14, + "automation.actions.delete": 14, + "automation.actions.execute": 14, + "automation.actions.export": 2, + "automation.actions.get": 3, + "automation.actions.import": 2, + "automation.actions.list": 3, + "automation.actions.update": 14, + "automation.config.apply": 2, + "automation.config.backup": 14, + "automation.config.enable": 14, + "automation.config.preview": 2, + "automation.config.refresh": 14, + "automation.config.status": 3, + "automation.pause": 14, + "automation.proxy.fetch": 2, + "automation.proxy.socketio_test": 2, + "automation.proxy.websocket_test": 2, + "automation.reload": 14, + "automation.resume": 14, + "automation.rules.add": 14, + "automation.rules.delete": 14, + "automation.rules.disable": 14, + "automation.rules.enable": 14, + "automation.rules.export": 2, + "automation.rules.get": 3, + "automation.rules.import": 2, + "automation.rules.list": 3, + "automation.rules.trigger": 14, + "automation.rules.update": 14, + "automation.services.list": 3, + "automation.services.status": 3, + "automation.services.stop": 14, + "automation.sources.add": 14, + "automation.sources.add_mapping": 14, + "automation.sources.delete": 14, + "automation.sources.disable": 14, + "automation.sources.enable": 14, + "automation.sources.export": 2, + "automation.sources.import": 2, + "automation.sources.list": 3, + "automation.sources.remove_mapping": 14, + "automation.sources.update": 14, + "automation.start": 14, + "automation.status": 3, + "automation.stop": 14, + "automation.test.device": 14, + "automation.test.gpio": 14, + "automation.test.led": 14, + "automation.test.ssh": 2, + "automation.variables.delete": 14, + "automation.variables.get": 3, + "automation.variables.list": 3, + "automation.variables.set": 14, + "cert.delete": 14, + "cert.generate_csr": 14, + "cert.generate_keypair": 14, + "cert.get_certificate": 3, + "cert.install": 14, + "cert.install_ca": 14, + "cert.status": 3, + "config.delete": 14, + "config.get": 3, + "config.list": 3, + "config.module.list": 3, + "config.module.reset": 14, + "config.module.save": 14, + "config.module.set": 14, + "config.module.show": 3, + "config.pack.apply": 14, + "config.pack.content": 14, + "config.pack.export": 14, + "config.pack.export_cert": 3, + "config.pack.import": 14, + "config.pack.info": 3, + "config.pack.list": 3, + "config.pack.verify": 14, + "config.save": 14, + "config.set": 14, + "device.fan.set": 14, + "device.fan.status": 3, + "device.ping": 14, + "device.power": 14, + "device.power.status": 3, + "device.reset": 14, + "device.status": 3, + "device.usb.set": 14, + "device.usb.status": 3, + "dhcp.clients": 3, + "dhcp.start": 14, + "dhcp.status": 3, + "dhcp.stop": 14, + "fan.config": 3, + "fan.curve": 14, + "fan.enable": 14, + "fan.limits": 14, + "fan.mode": 14, + "fan.save": 14, + "fan.set": 14, + "fan.status": 3, + "gpio.info": 3, + "gpio.list": 3, + "gpio.set": 14, + "gpio.toggle": 14, + "hosts.clear": 14, + "hosts.info": 3, + "hosts.list": 3, + "hosts.remove": 14, + "hosts.update": 14, + "key.delete": 14, + "key.export": 3, + "key.exportPrivate": 14, + "key.generate": 14, + "key.info": 3, + "key.list": 3, + "led.boot.config": 3, + "led.brightness": 14, + "led.clear": 14, + "led.color.hsv": 3, + "led.color.parse": 3, + "led.color_correction.export": 14, + "led.color_correction.get": 3, + "led.color_correction.import": 14, + "led.color_correction.reset": 14, + "led.color_correction.set": 14, + "led.effect.list": 3, + "led.effect.start": 14, + "led.effect.stop": 14, + "led.fill": 14, + "led.filter.list": 3, + "led.filter.start": 14, + "led.filter.stop": 14, + "led.image": 14, + "led.list": 3, + "led.qrcode": 14, + "led.save": 14, + "led.set": 14, + "led.text": 14, + "led.text.stop": 14, + "log.capture": 14, + "log.clear": 14, + "log.list": 3, + "log.setLevel": 14, + "log.stats": 3, + "monitor.config": 3, + "monitor.data": 3, + "monitor.set_server": 14, + "monitor.start": 14, + "monitor.status": 3, + "monitor.stop": 14, + "nat.disable": 14, + "nat.enable": 14, + "nat.save": 14, + "nat.status": 3, + "network.eth.status": 3, + "network.hostname": 14, + "network.lpmu_access.log": 3, + "network.lpmu_access.start": 14, + "network.lpmu_access.status": 3, + "network.status": 3, + "network.wifi.ap.config": 14, + "network.wifi.ap.stations": 3, + "network.wifi.connect": 14, + "network.wifi.disconnect": 14, + "network.wifi.mode": 14, + "network.wifi.scan": 14, + "ota.abort": 14, + "ota.partitions": 3, + "ota.progress": 3, + "ota.rollback": 14, + "ota.server.get": 3, + "ota.server.set": 14, + "ota.start_file": 14, + "ota.start_url": 14, + "ota.status": 3, + "ota.test_connection": 14, + "ota.upgrade_file": 14, + "ota.upgrade_url": 14, + "ota.upload_abort": 14, + "ota.upload_begin": 14, + "ota.upload_end": 14, + "ota.validate": 14, + "ota.version": 3, + "ota.www.abort": 14, + "ota.www.progress": 3, + "ota.www.start": 14, + "ota.www.start_sdcard": 14, + "power.chip": 3, + "power.debug": 14, + "power.interval.set": 14, + "power.monitor.start": 14, + "power.monitor.stop": 14, + "power.protection.config": 3, + "power.protection.set": 14, + "power.protection.status": 3, + "power.stats": 3, + "power.stats.reset": 14, + "power.status": 3, + "power.threshold.set": 14, + "power.voltage": 3, + "service.list": 3, + "service.restart": 14, + "service.start": 14, + "service.status": 3, + "service.stop": 14, + "sftp.get": 14, + "sftp.ls": 14, + "sftp.mkdir": 14, + "sftp.put": 14, + "sftp.rm": 14, + "sftp.stat": 14, + "ssh.cancel": 14, + "ssh.commands.add": 14, + "ssh.commands.export": 14, + "ssh.commands.get": 3, + "ssh.commands.import": 14, + "ssh.commands.list": 3, + "ssh.commands.remove": 14, + "ssh.commands.update": 14, + "ssh.copyid": 14, + "ssh.exec": 14, + "ssh.exec_status": 3, + "ssh.exec_stream": 14, + "ssh.hosts.add": 14, + "ssh.hosts.export": 14, + "ssh.hosts.get": 3, + "ssh.hosts.import": 14, + "ssh.hosts.list": 3, + "ssh.hosts.remove": 14, + "ssh.hosts.update": 14, + "ssh.keygen": 14, + "ssh.revoke": 14, + "ssh.services.start": 14, + "ssh.test": 14, + "storage.delete": 14, + "storage.info": 3, + "storage.list": 3, + "storage.mkdir": 14, + "storage.mount": 14, + "storage.read": 3, + "storage.rename": 14, + "storage.status": 3, + "storage.unmount": 14, + "system.apis": 3, + "system.cpu": 3, + "system.info": 3, + "system.log.level": 14, + "system.memory": 3, + "system.memory_detail": 3, + "system.reboot": 14, + "system.tasks": 3, + "temp.bind": 14, + "temp.manual": 14, + "temp.read": 3, + "temp.select": 14, + "temp.sources": 3, + "temp.status": 3, + "time.force_sync": 14, + "time.info": 3, + "time.set_ntp": 14, + "time.set_timezone": 14, + "time.sync": 14, + "ui.widgets.get": 3, + "ui.widgets.set": 14, + "wifi.connect": 14, + "wifi.disconnect": 14, + "wifi.scan": 14, + "wifi.status": 3 + } +} diff --git a/tests/prompts/api-methods.test.cjs b/tests/prompts/api-methods.test.cjs new file mode 100644 index 00000000..a48aea47 --- /dev/null +++ b/tests/prompts/api-methods.test.cjs @@ -0,0 +1,73 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const acorn = require('acorn'); +const {harness} = require('./harness.cjs'); +const {logical: contract} = require('./api-methods.json'); +const bits = {GET: 1, POST: 2, PUT: 4, DELETE: 8}; + +async function client() { + const h = harness(); + await h.ready(); + h.run(h.read('js/api.js')); + h.run('api.request = async (endpoint, method, params) => ({endpoint, method, params})'); + return h; +} + +test('default calls fit every real registered API, including parameterless writes', async () => { + const h = await client(); + assert.equal(Object.keys(contract).length, 277); + for (const [name, methods] of Object.entries(contract)) { + for (const params of [null, {}, {probe: 'x'}]) { + const call = await h.run(`api.call(${JSON.stringify(name)}, ${JSON.stringify(params)})`); + assert.ok(methods & bits[call.method], `${name} rejects default ${call.method}`); + assert.equal(call.method, 'POST', name); + } + } + for (const name of ['ota.validate', 'automation.action.stats.reset']) { + assert.equal(contract[name] & bits.GET, 0, `${name} is a write`); + } +}); + +test('explicit GET preserves query encoding and carries no body', async () => { + const h = await client(); + const call = await h.run(`api.call('system.info', {value: 'a &中', zero: 0, no: false, empty: '', absent: null}, 'GET')`); + assert.equal(call.endpoint, '/system/info?value=a+%26%E4%B8%AD&zero=0&no=false'); + assert.equal(call.method, 'GET'); + assert.equal(call.params, null); +}); + +test('literal Web UI callers use methods allowed by the actual registry', async () => { + const h = await client(); + let checked = 0; + for (const file of ['api.js', 'app.js', 'terminal.js']) { + // Audit source, including callers removed by optimization. + const source = fs.readFileSync(path.resolve(__dirname, '../../components/ts_webui/web/js', file), 'utf8'); + const ast = acorn.parse(source, {ecmaVersion: 'latest', locations: true}); + const calls = []; + function visit(node) { + if (!node || typeof node !== 'object') return; + if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && + node.callee.property.name === 'call' && + (node.callee.object.name === 'api' || (file === 'api.js' && node.callee.object.type === 'ThisExpression')) && + typeof node.arguments[0]?.value === 'string') calls.push(node); + for (const value of Object.values(node)) { + if (Array.isArray(value)) value.forEach(visit); + else if (value && typeof value === 'object') visit(value); + } + } + visit(ast); + for (const node of calls) { + const name = node.arguments[0].value; + const where = `${file}:${node.loc.start.line} ${name}`; + assert.ok(Object.hasOwn(contract, name), `${where} is not registered`); + const method = node.arguments[2]; + assert.ok(!method || method.type === 'Literal', `${where} needs a concrete method audit`); + const call = await h.run(`api.call(${JSON.stringify(name)}, {}, ${JSON.stringify(method?.value ?? null)})`); + assert.ok(contract[name] & bits[call.method], `${where} rejects ${call.method}`); + checked++; + } + } + assert.ok(checked > 150, `Only ${checked} callers audited`); +}); diff --git a/tests/prompts/failure-catalog.test.cjs b/tests/prompts/failure-catalog.test.cjs index c8dee003..3802136f 100644 --- a/tests/prompts/failure-catalog.test.cjs +++ b/tests/prompts/failure-catalog.test.cjs @@ -176,7 +176,7 @@ const NOT_FAILURES = new Set(['ok', 'no_change', 'mirror_failed', 'recovery_clea test('every reason token the firmware can send has a message in both languages', () => { const automation = component('ts_api/src/ts_api_automation.c'); - const apiErrors = [automation, component('ts_api/src/ts_api_fan.c')].join('\n'); + const apiErrors = [automation, component('ts_api/src/ts_api_fan.c'), component('ts_api/src/ts_api_led.c')].join('\n'); const config = ['ts_automation_config', 'ts_automation_document', 'ts_automation_references', 'ts_automation_migrate', 'ts_automation_legacy', 'ts_rule_config'].map(name => component('ts_automation/src/' + name + '.c')).join('\n') + '\n' + component('ts_api/src/ts_api_auto_config.c'); const ssh = component('ts_api/src/ts_api_ssh.c'); const tokens = new Set([ @@ -191,8 +191,8 @@ test('every reason token the firmware can send has a message in both languages', ...[...apiErrors.matchAll(/ts_api_result_error\(result, TS_API_ERR_\w+, "([a-z][a-z0-9_]*)"\)/g)].map(m => m[1]), // ts_api_result_reason(result, CODE, "token", detail): the helper the handlers use for a reason the page can state ...[...apiErrors.matchAll(/ts_api_result_reason\(result, TS_API_ERR_\w+, "([a-z][a-z0-9_]*)"/g)].map(m => m[1]), - // reasons the handlers put straight into the message: result->message = strdup("token") - ...[...automation.matchAll(/\bstrdup\("([a-z][a-z0-9_]*)"\)/g)].map(m => m[1]), + // Direct literal API error messages; unrelated strdup payloads are not reason tokens. + ...[...automation.matchAll(/result->message\s*=\s*strdup\("([a-z][a-z0-9_]*)"\)/g)].map(m => m[1]), // the SSH exec errors the WebSocket sends: {"type":"ssh_exec_error","error":""} ...[...component('ts_webui/src/ts_webui_ws.c').matchAll(/"error", "([a-z][a-z0-9_]*)"\)\)!=NULL/g)].map(m => m[1]), ...[...component('ts_webui/src/ts_ws_operation.c').matchAll(/failed \? "([a-z][a-z0-9_]*)" : "([a-z][a-z0-9_]*)"/g)].flatMap(m => [m[1], m[2]]), @@ -208,7 +208,7 @@ test('every reason token the firmware can send has a message in both languages', }); test('the catalogue has no reason that nothing can produce (a sentence nobody can reach is a trap for the next edit)', () => { - const sources = [component('ts_security/src/ts_ssh_service.c'), component('ts_automation/src/ts_action_manager.c'), component('ts_api/src/ts_api_auto_config.c'), component('ts_api/src/ts_api_automation.c'), component('ts_api/src/ts_api_fan.c'), component('ts_api/src/ts_api_ssh.c'), component('ts_api/src/ts_api_key.c'), component('ts_automation/src/ts_rule_engine.c'), + const sources = [component('ts_security/src/ts_ssh_service.c'), component('ts_automation/src/ts_action_manager.c'), component('ts_api/src/ts_api_auto_config.c'), component('ts_api/src/ts_api_automation.c'), component('ts_api/src/ts_api_fan.c'), component('ts_api/src/ts_api_led.c'), component('ts_api/src/ts_api_ssh.c'), component('ts_api/src/ts_api_key.c'), component('ts_automation/src/ts_rule_engine.c'), component('ts_automation/src/ts_rule_config.c'), component('ts_automation/src/ts_automation_config.c'), component('ts_automation/src/ts_automation_document.c'), component('ts_automation/src/ts_automation_references.c'), component('ts_automation/src/ts_automation_migrate.c'), component('ts_automation/src/ts_automation_legacy.c'), component('ts_config_pack/src/ts_config_pack.c'), component('ts_security/src/ts_ssh_client.c'), component('ts_automation/src/ts_rule_pack.c'), component('ts_cert/src/ts_cert.c'), component('ts_webui/src/ts_webui_api.c'), component('ts_webui/src/ts_webui_ws.c'), component('ts_webui/src/ts_ws_operation.c'), read('js/app.js'), read('js/api.js')].join('\n'); // reasons the page produces from the error class, from a transport state, or from the API envelope of other modules const GENERIC = new Set(['busy', 'no_memory', 'not_found', 'no_permission', 'timeout', 'invalid_request', 'invalid_argument', 'not_supported', 'hardware_failed', diff --git a/tests/prompts/file-images.browser.test.cjs b/tests/prompts/file-images.browser.test.cjs new file mode 100644 index 00000000..821359e4 --- /dev/null +++ b/tests/prompts/file-images.browser.test.cjs @@ -0,0 +1,77 @@ +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const kit = require('./pagekit.cjs'); +const {fixture} = require('./configuration-fixture.cjs'); +kit.install(); +const svg = ''; +const headers = {'content-type':'image/svg+xml','cache-control':'no-store','content-disposition':'attachment; filename="download"', 'x-content-type-options':'nosniff', 'content-security-policy':"sandbox; default-src 'none'; frame-ancestors 'none'"}; +const deferred = () => {let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};}; +async function prepare(page) { + await page.evaluate(() => { + api.token='synthetic-file-session-A';api.level='root';api.username='root'; + window.fileUrls={created:[],revoked:[]}; + const create=URL.createObjectURL.bind(URL),revoke=URL.revokeObjectURL.bind(URL); + URL.createObjectURL=blob=>{const url=create(blob);fileUrls.created.push(url);return url;}; + URL.revokeObjectURL=url=>{fileUrls.revoked.push(url);revoke(url);}; + }); + await page.evaluate(()=>loadCommandsPage()); + await page.evaluate(()=>showAddRuleModal()); +} +for (const language of ['zh-CN','en-US']) { + test(`${language}: authenticated file icons, sandboxed SVG and original file download remain usable`,async()=>{ + const base=fixture(); + await kit.withPage(language,base.respond,async({page})=>{ + await prepare(page); + const requests=[]; + await page.route('**/api/v1/file/download?*',async route=>{ + const request=route.request(),url=new URL(request.url()),path=url.searchParams.get('path'); + requests.push({url:url.href,authorization:request.headers().authorization,path}); + if(path.includes('missing'))return route.fulfill({status:404,contentType:'application/json',body:'{"error":"File not found"}'}); + await route.fulfill({status:200,headers,body:path.includes('invalid')?'not an image':svg}); + }); + const path='/sdcard/images/例 图+"1.svg'; + await page.evaluate(path=>{ + selectedHostId='file-fixture';sshCommands[selectedHostId]=[{id:'icon',name:'Existing command',command:'printf ok',icon:path}];refreshCommandsList(); + updateCmdIconPreview(path);updateRuleIconPreview(path); + },path); + await page.waitForFunction(()=>['#commands-list .command-icon img','#cmd-icon-preview img','#rule-icon-preview img'].every(selector=>document.querySelector(selector)?.naturalWidth>0)); + await page.waitForFunction(()=>fileUrls.revoked.length===3); + assert.equal(requests.length,3); + for(const request of requests){assert.equal(request.authorization,'Bearer synthetic-file-session-A');assert.equal(request.path,path);assert.deepEqual([...new URL(request.url).searchParams.keys()],['path']);assert(!request.url.includes('synthetic-file-session'));} + assert.equal(await page.evaluate(()=>window.__privateFileExecuted),undefined); + const downloadPromise=page.waitForEvent('download'); + const downloadable='/sdcard/例 图+1.svg'; + assert.deepEqual(await page.evaluate(path=>downloadFile(path,true),downloadable),{started:true}); + const download=await downloadPromise;assert.equal(download.suggestedFilename(),'例 图+1.svg');assert.equal(await download.failure(),null); + await page.evaluate(()=>{updateCmdIconPreview('/sdcard/missing.svg');updateRuleIconPreview('/sdcard/invalid.svg');sshCommands[selectedHostId][0].icon='/sdcard/missing.svg';refreshCommandsList();}); + await page.waitForFunction(()=>document.querySelector('#cmd-icon-preview .preview-placeholder')&&document.querySelector('#rule-icon-preview .preview-placeholder')&&!document.querySelector('#commands-list [data-command-image-note]').hidden); + assert.equal(await page.locator('#cmd-icon-preview').innerText(),language==='zh-CN'?'加载失败':'Load failed'); + await page.waitForFunction(()=>fileUrls.created.length===fileUrls.revoked.length); + assert.equal(await page.evaluate(()=>window.__privateFileExecuted),undefined); + }); + }); + test(`${language}: late private image cannot update a removed node or changed login`,async()=>{ + const base=fixture(); + await kit.withPage(language,base.respond,async({page})=>{ + await prepare(page); + const holds=new Map(); + await page.route('**/api/v1/file/download?*',async route=>{ + const path=new URL(route.request().url()).searchParams.get('path'),hold=holds.get(path); + if(hold){hold.seen.resolve();await hold.release.promise;} + await route.fulfill({status:200,headers,body:svg}); + }); + for(const mode of ['login','removed']){ + const path=`/sdcard/late-${mode}.svg`,hold={seen:deferred(),release:deferred()};holds.set(path,hold); + await page.evaluate(path=>{const image=document.createElement('img');image.id='late-file-icon';document.body.appendChild(image);window.lateFileLoad=loadFileIcon(image,path,()=>{window.staleFileFailure=true;});},path); + await hold.seen.promise; + await page.evaluate(mode=>{if(mode==='login')api.token='synthetic-file-session-B';else document.getElementById('late-file-icon').remove();},mode); + hold.release.resolve();await page.evaluate(()=>window.lateFileLoad); + assert.equal(await page.evaluate(()=>fileUrls.created.length),0);assert.equal(await page.evaluate(()=>window.staleFileFailure),undefined); + await page.evaluate(()=>document.getElementById('late-file-icon')?.remove()); + } + await page.evaluate(()=>{updateCmdIconPreview('/sdcard/current.svg');}); + await page.waitForFunction(()=>document.querySelector('#cmd-icon-preview img')?.naturalWidth>0&&fileUrls.revoked.length===1); + assert.equal(await page.evaluate(()=>fileUrls.created.length),1); + }); + }); +} diff --git a/tests/prompts/flows.browser.test.cjs b/tests/prompts/flows.browser.test.cjs index ed6ed197..81b4245e 100644 --- a/tests/prompts/flows.browser.test.cjs +++ b/tests/prompts/flows.browser.test.cjs @@ -98,6 +98,7 @@ after(() => { // A scenario: id, setup(page, names) -> DOM the handler needs, act(page, names) -> runs the handler, device {endpoint: answer}, // show: 'toast' | {inline: selector} | {field: id}. `names` are the user's own names for the objects, in the language of the run. const NAMES = {rule: ['夜间关灯', 'Night off'], action: ['重启 AGX', 'Restart AGX'], source: ['温度', 'Temperature']}; +const rootMessageFixtures=new Set(["monitor/set_server", "monitor/start", "monitor/stop", "hosts/remove", "hosts/update", "hosts/clear", "network/lpmu_access/start", "network/lpmu_access/status", "network/lpmu_access/log", "automation/config/refresh", "automation/config/backup", "automation/config/enable", "automation/reload", "automation/variables/set", "automation/variables/delete", "automation/rules/add", "automation/rules/update", "automation/rules/delete", "automation/sources/add", "automation/sources/update", "automation/sources/delete", "automation/sources/add_mapping", "automation/sources/remove_mapping", "automation/actions/add", "automation/actions/update", "automation/actions/delete", "automation/config/preview", "automation/config/apply", "automation/sources/export", "automation/sources/import", "automation/rules/export", "automation/rules/import", "automation/actions/export", "automation/actions/import", "automation/test/ssh", "automation/proxy/websocket_test", "automation/proxy/socketio_test"]); function scenarioTests(file, scenarios) { for (const language of ['zh-CN', 'en-US']) { for (const scenario of scenarios) { @@ -125,6 +126,7 @@ function scenarioTests(file, scenarios) { return fetchOnce(url,options); }; }); + if(Object.keys(scenario.device??{}).some(name=>rootMessageFixtures.has(name)))await page.evaluate(()=>{api.token='fixture-root';api.level='root';api.username='root';}); await scenario.setup?.(page, names); const show = scenario.show ?? 'toast'; const acting = Promise.resolve(scenario.act(page, names)); @@ -180,6 +182,7 @@ const rulesList = (name = 'night-off') => ok({...shownConfiguration, rules: [{id // answer to a write, a batch, a dialog result box) so that the golden sentences below can be read like a document. const dom = html => p => p.evaluate(html => document.body.insertAdjacentHTML('beforeend', html), html); const sure = p => p.evaluate(() => { confirmAction = async () => true; }); +const asRoot = p => p.evaluate(() => {api.token='fixture-root';api.level='root';api.username='root';}); scenarioTests('system', [ // ---- sign in (the reason stays in the form) ...[['wrong-password', '{"code":3,"error":"Invalid username or password"}'], ['locked', '{"code":3,"error":"Account locked due to too many failed attempts"}'], ['no-answer', DROP]].map(([name, answer]) => ({ @@ -188,12 +191,12 @@ scenarioTests('system', [ // ---- device {id: 'device.reboot.no-answer', setup: sure, device: {'system/reboot': DROP}, act: async p => { await p.evaluate(() => confirmReboot()); await p.waitForFunction(() => document.getElementById('toast').classList.contains('toast-warning')); }}, - {id: 'service.restart.busy', act: p => p.evaluate(() => serviceAction('automation', 'restart')), device: {'service/restart': '{"code":4,"error":"busy"}'}}, - {id: 'service.stop.no-answer', act: p => p.evaluate(() => serviceAction('automation', 'stop')), device: {'service/stop': DROP}}, + {id: 'service.restart.busy', setup: p => p.evaluate(() => {api.token='fixture-root';api.level='root';api.username='root';}), act: p => p.evaluate(() => serviceAction('automation', 'restart')), device: {'service/restart': '{"code":4,"error":"busy"}'}}, + {id: 'service.stop.no-answer', setup: p => p.evaluate(() => {api.token='fixture-root';api.level='root';api.username='root';}), act: p => p.evaluate(() => serviceAction('automation', 'stop')), device: {'service/stop': DROP}}, {id: 'fan.setspeed.rejected', setup: p => p.evaluate(() => { refreshFans = async () => {}; }), act: p => p.evaluate(() => setFanSpeed(2, 60)), device: {'fan/set': '{"code":1,"error":"Invalid fan id"}'}}, {id: 'led.brightness.device-not-found', act: p => p.evaluate(() => setBrightness('matrix', 50)), device: {'led/brightness': '{"code":2,"error":"Device not found"}'}}, // ---- files - {id: 'file.mount.failed', setup: p => p.evaluate(() => { refreshFilesPage = async () => {}; }), act: p => p.evaluate(() => mountSdCard()), device: {'storage/mount': '{"code":7,"error":"Failed to mount SD card"}'}}, + {id: 'file.mount.failed', setup: async p => {await asRoot(p);await p.evaluate(() => { refreshFilesPage = async () => {}; });}, act: p => p.evaluate(() => mountSdCard()), device: {'storage/mount': '{"code":7,"error":"Failed to mount SD card"}'}}, {id: 'file.delete.not-found', setup: async p => { await sure(p); await p.evaluate(() => { refreshFilesPage = async () => {}; }); }, act: p => p.evaluate(() => deleteFile('/sdcard/a.txt')), device: {'storage/delete': '{"code":2,"error":"File not found"}'}}, {id: 'file.delete.batch-mixed', show: {inline: '#operation-summary'}, setup: async p => { await sure(p); await p.evaluate(() => { refreshFilesPage = async () => {}; selectedFiles.clear(); selectedFiles.add('/sdcard/a.txt'); selectedFiles.add('/sdcard/b.txt'); selectedFiles.add('/sdcard'); }); }, @@ -202,21 +205,21 @@ scenarioTests('system', [ {id: 'file.createdir.no-answer', setup: async p => { await dom('')(p); await p.evaluate(() => { currentFilePath = '/sdcard'; }); }, act: p => p.evaluate(() => createNewFolder()), device: {'storage/mkdir': DROP}}, // ---- network - {id: 'wifi.scan.wrong-mode', setup: dom(''), show: {inline: '#wifi-scan-results'}, + {id: 'wifi.scan.wrong-mode', setup: async p => {await asRoot(p); await dom('')(p);}, show: {inline: '#wifi-scan-results'}, act: p => p.evaluate(() => showWifiScan()), device: {'network/wifi/scan': '{"code":8,"error":"WiFi scan requires STA or APSTA mode"}'}}, - {id: 'network.nat.no-upstream', setup: p => p.evaluate(() => { refreshNetworkPage = async () => {}; }), act: p => p.evaluate(() => toggleNat()), + {id: 'network.nat.no-upstream', setup: async p => {await asRoot(p); await p.evaluate(() => { refreshNetworkPage = async () => {}; });}, act: p => p.evaluate(() => toggleNat()), device: {'nat/status': ok({enabled: false}), 'nat/enable': '{"code":7,"error":"WiFi STA not connected"}'}}, - {id: 'system.hostname.rejected', setup: dom(''), act: p => p.evaluate(() => setHostname()), device: {'network/hostname': '{"code":1,"error":"Invalid hostname"}'}}, + {id: 'system.hostname.rejected', setup: async p => {await asRoot(p); await dom('')(p);}, act: p => p.evaluate(() => setHostname()), device: {'network/hostname': '{"code":1,"error":"Invalid hostname"}'}}, // ---- OTA {id: 'ota.path.firmware-missing', setup: dom(''), act: p => p.evaluate(() => otaFromFile()), device: {'storage/info': '{"code":2,"error":"File not found"}'}}, {id: 'ota.path.nothing-entered', setup: dom(''), act: p => p.evaluate(() => otaFromFile()), device: {'storage/list': ok({entries: [{name: 'notes.txt', type: 'file'}]})}}, - {id: 'ota.check.server-unreachable', setup: dom('
'), show: {inline: '#ota-update-status'}, + {id: 'ota.check.server-unreachable', setup: async p => {await asRoot(p); await dom('
')(p);}, show: {inline: '#ota-update-status'}, act: p => p.evaluate(() => checkForUpdates()), device: {'ota/test_connection': '{"code":1,"error":"x"}'}}, - {id: 'ota.upload.device-refused', act: p => p.evaluate(async () => { try { await uploadFirmwareToDevice(new ArrayBuffer(3), false); } catch (error) { reportFailure({ op: 'ota.upgrade', error, endpoint: 'ota.proxy', write: true }); } }), + {id: 'ota.upload.device-refused', setup: p => p.evaluate(() => {api.token='fixture-root';api.level='root';api.username='root';}), act: p => p.evaluate(async () => { try { await uploadFirmwareToDevice(new ArrayBuffer(3), false); } catch (error) { reportFailure({ op: 'ota.upgrade', error, endpoint: 'ota.proxy', write: true }); } }), device: {'ota/firmware': '{"status":"error","message":"Not enough space"}'}}, - {id: 'ota.upload.no-answer', act: p => p.evaluate(async () => { try { await uploadFirmwareToDevice(new ArrayBuffer(3), false); } catch (error) { reportFailure({ op: 'ota.upgrade', error, endpoint: 'ota.proxy', write: true }); } }), + {id: 'ota.upload.no-answer', setup: p => p.evaluate(() => {api.token='fixture-root';api.level='root';api.username='root';}), act: p => p.evaluate(async () => { try { await uploadFirmwareToDevice(new ArrayBuffer(3), false); } catch (error) { reportFailure({ op: 'ota.upgrade', error, endpoint: 'ota.proxy', write: true }); } }), device: {'ota/firmware': DROP}}, // ---- certificates and config packs (the result boxes of their dialogs) {id: 'cert.install.no-keypair', show: {inline: '#cert-install-result'}, @@ -451,9 +454,9 @@ scenarioTests('ssh-commands', [ device: startedCommand}, {id: 'command.run.error-text-from-old-firmware', setup: onCommands, act: async p => { await p.evaluate(() => executeCommand(0)); await p.evaluate(() => handleSshExecMessage({type: 'ssh_exec_error', session_id: 5, error: 'SSH connection failed (code=259)'})); }, device: startedCommand}, - {id: 'command.cancel.no-session', setup: async p => { await onCommands(p); await p.evaluate(() => { document.getElementById('exec-result-section').style.display = ''; claimExecDisplay('ssh', document.getElementById('exec-result')); currentExecSessionId = 5; }); }, act: p => p.evaluate(() => cancelExecution()), + {id: 'command.cancel.no-session', setup: async p => { await onCommands(p); await p.evaluate(() => { document.getElementById('exec-result-section').style.display = ''; const owner=claimExecDisplay('ssh', document.getElementById('exec-result')); rememberExecReceipt(owner,{session_id:5,boot_id:'a'.repeat(32),result_key:'b'.repeat(32)}); currentExecSessionId = 5; }); }, act: p => p.evaluate(() => cancelExecution()), device: commandsDevice({'ssh/cancel': '{"code":2,"message":"ssh_no_session"}'})}, - {id: 'command.cancel.no-answer', setup: async p => { await onCommands(p); await p.evaluate(() => { document.getElementById('exec-result-section').style.display = ''; claimExecDisplay('ssh', document.getElementById('exec-result')); currentExecSessionId = 5; }); }, act: p => p.evaluate(() => cancelExecution()), + {id: 'command.cancel.no-answer', setup: async p => { await onCommands(p); await p.evaluate(() => { document.getElementById('exec-result-section').style.display = ''; const owner=claimExecDisplay('ssh', document.getElementById('exec-result')); rememberExecReceipt(owner,{session_id:5,boot_id:'a'.repeat(32),result_key:'b'.repeat(32)}); currentExecSessionId = 5; }); }, act: p => p.evaluate(() => cancelExecution()), device: commandsDevice({'ssh/cancel': DROP})}, {id: 'host.list.commands-page-refused', act: p => p.evaluate(() => { document.body.insertAdjacentHTML('beforeend', '
'); return loadHostSelector(); }), device: {'ssh/hosts/list': '{"code":7,"message":"Failed to list hosts"}'}, show: {inline: '#host-selector'}}, {id: 'pack.export-command.not-allowed', setup: async p => { await onCommands(p); await p.evaluate(() => showExportSshCommandModal('restart')); }, act: p => p.evaluate(() => doExportSshCommandFromModal('restart')), diff --git a/tests/prompts/harness.cjs b/tests/prompts/harness.cjs index 0bfa21a0..eafdcf92 100644 --- a/tests/prompts/harness.cjs +++ b/tests/prompts/harness.cjs @@ -1,7 +1,7 @@ const fs = require('node:fs'); const vm = require('node:vm'); const path = require('node:path'); -const root = path.resolve(__dirname, '../../components/ts_webui/web'); +const root = process.env.TS_TEST_WEB_ROOT ? path.resolve(process.env.TS_TEST_WEB_ROOT) : path.resolve(__dirname, '../../components/ts_webui/web'); const read = file => fs.readFileSync(path.join(root,file),'utf8'); class Element { constructor(tag, doc) { this.tagName=tag.toUpperCase();this.doc=doc;this.children=[];this.style={};this.dataset={};this.attributes={};this.className='';this.textContent='';this.value='';this.disabled=false;this.hidden=false; diff --git a/tests/prompts/key-generation-cache.browser.test.cjs b/tests/prompts/key-generation-cache.browser.test.cjs index 339b9e46..adaea983 100644 --- a/tests/prompts/key-generation-cache.browser.test.cjs +++ b/tests/prompts/key-generation-cache.browser.test.cjs @@ -14,14 +14,15 @@ for(const lang of ['zh-CN','en-US'])test(`${lang}: cached old API, app and langu [`/js/lang/${lang}.js`]:`/js/lang/${lang}.js?v=${newVersion}` }; for(const [name,url] of Object.entries(currentUrls))assert.notEqual(url,name+'?v='+oldVersion); - const oldApi=api.replace(/ const request_id = 'kg-'[\s\S]*?return this.call\('key.generate',[^\n]+/," return this.call('key.generate', { id, type, comment, exportable, alias, hidden }, 'POST');");assert.notEqual(oldApi,api); - const start=app.indexOf('async function generateKey()'),end=app.indexOf('\nfunction formatTimestamp(',start); - const oldApp=app.slice(0,start)+`async function generateKey() { + // Model an older behavior explicitly; whitespace in optimized JS is not a contract. + const oldApi=api+`\nTianShanAPI.prototype.keyGenerate = async function(id,type,comment,exportable,alias,hidden) { + return this.call('key.generate', {id,type,comment,exportable,alias,hidden}, 'POST'); + };\n`; + const oldApp=app+`\ngenerateKey = async function() { const id=document.getElementById('keygen-id').value.trim(); requireApiSuccess(await api.keyGenerate(id,document.getElementById('keygen-type').value), 'keyGenerate'); hideGenerateKeyModal();showToast(t('toast.keyGenerated',{name:id}), 'success');await refreshSecurityPage(); - } - `+app.slice(end); + };\n`; let upgraded=false;const assets=[],posts=[];let keys=[]; const server=http.createServer((req,res)=>{ const url=new URL(req.url,'http://local'),json=data=>{res.setHeader('Content-Type','application/json');res.end(JSON.stringify({code:0,data}));}; diff --git a/tests/prompts/key-generation.test.cjs b/tests/prompts/key-generation.test.cjs index b3fa29dd..618463bc 100644 --- a/tests/prompts/key-generation.test.cjs +++ b/tests/prompts/key-generation.test.cjs @@ -27,7 +27,7 @@ for(const lang of ['zh-CN','en-US']){ for(const failure of ['timeout','network','http','body','json','string-code','missing','wrong-id','response-allocation','response-no-message'])test(`${lang}: ${failure} is unknown, one POST and at most one record check, no automatic retry`,async()=>{ const h=await setup(lang);let posts=0,checks=0; h.ctx.fetch=async(url,opts)=>{ - if(opts.method==='GET'){checks++;return reply({code:0,data:{id:'fixture'}});} + if(new URL(url, 'http://fixture').pathname === '/api/v1/key/info'){checks++;return reply({code:0,data:{id:'fixture'}});} posts++; if(failure==='timeout')return new Promise((r,j)=>opts.signal.addEventListener('abort',()=>j(new Error('aborted')))); if(failure==='network')throw new Error('offline'); diff --git a/tests/prompts/lpmu-lifecycle.browser.test.cjs b/tests/prompts/lpmu-lifecycle.browser.test.cjs index ff9c7c6e..98d4c80e 100644 --- a/tests/prompts/lpmu-lifecycle.browser.test.cjs +++ b/tests/prompts/lpmu-lifecycle.browser.test.cjs @@ -52,7 +52,7 @@ async function open(language) { await page.goto(base + '/#/network'); await page.waitForFunction(() => i18n.isReady()); await page.evaluate(async () => { - closeLoginModal(); api.token='fixture'; api.username='root'; api.level=2; + closeLoginModal(); api.token='fixture'; api.username='root'; api.level='root'; updateAuthUI(); router.appReady=true; const navigate=router.navigate.bind(router); router.navigate=(...args) => window.navigationWork=navigate(...args); diff --git a/tests/prompts/origin.browser.test.cjs b/tests/prompts/origin.browser.test.cjs new file mode 100644 index 00000000..f39d638b --- /dev/null +++ b/tests/prompts/origin.browser.test.cjs @@ -0,0 +1,61 @@ +// Real Chrome requests to two loopback origins. Every fixture API/upgrade enters +// the compiled actual SDK dispatcher, Host/Origin/CORS and body-ordering probe. +// Socket/TLS/auth/business and the HTTPD scratch buffer remain modeled boundaries. +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const http=require('node:http'),crypto=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +const {spawnSync}=require('node:child_process'); +const {chromium}=require('playwright'); +const root=path.resolve(__dirname,'../..'); +function build(file,origin=''){ + const args=['tests/runtime/test_browser_origin.py','--probe-output',file];if(origin)args.push('--allow-origin',origin); + const p=spawnSync('python3',args,{cwd:root,encoding:'utf8',env:{...process.env,PYTHONDONTWRITEBYTECODE:'1'}});assert.equal(p.status,0,p.stdout+p.stderr); +} +test('two browser origins: same-origin UI/CLI work; foreign fetch/form/WS produce no business; explicit origin/proxy policy remains available',async()=>{ + const temp=fs.mkdtempSync(path.join(os.tmpdir(),'ts-browser-origins-'));let browser,server,foreign; + const trace=[],sockets=new Set();let executable=path.join(temp,'default'); + function probe(req,kind){ + const needsAuth=kind!==3&&!req.url.includes('public=1'); + const p=spawnSync(executable,['--probe','http',req.socket.localAddress.replace('::ffff:',''),String(req.socket.localPort),req.headers.host||'ABSENT',req.headers.origin??'ABSENT',String(kind),needsAuth?'1':'0',req.headers.authorization==='Bearer SYNTHETIC_BROWSER_TOKEN'?'1':'0'],{encoding:'utf8'}); + assert.equal(p.status,0,p.stdout+p.stderr);const result=JSON.parse(p.stdout);trace.push({method:kind===2?'WS':req.method,origin:req.headers.origin,authorization:req.headers.authorization,...result});return result; + } + function headers(res,p){if(p.acao)res.setHeader('Access-Control-Allow-Origin',p.acao);if(p.vary)res.setHeader('Vary',p.vary);if(p.acam)res.setHeader('Access-Control-Allow-Methods',p.acam);if(p.acah)res.setHeader('Access-Control-Allow-Headers',p.acah);} + try{ + build(executable); + server=http.createServer((req,res)=>{ + if(!req.url.startsWith('/probe')){res.writeHead(200,{'Content-Type':'text/html'}).end('Origin policy fixture');return;} + const p=probe(req,req.url.startsWith('/probe/ws-http')?4:req.method==='OPTIONS'?3:0);headers(res,p);res.statusCode=p.status; + if(p.ret!==0||p.status===204){res.setHeader('Connection','close');res.end(p.status===204?undefined:'Rejected');return;} + req.on('data',()=>{});req.on('end',()=>{res.setHeader('Content-Type','application/json');res.end('{"ok":true}');}); + }); + server.on('connection',s=>{sockets.add(s);s.on('close',()=>sockets.delete(s));}); + server.on('upgrade',(req,socket)=>{ + const p=probe(req,2);if(p.ret!==0){socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');return;} + const accept=crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+accept+'\r\n\r\n');socket.on('data',()=>socket.destroy()); + }); + foreign=http.createServer((req,res)=>res.writeHead(200,{'Content-Type':'text/html'}).end('Other origin')); + await Promise.all([new Promise(r=>server.listen(0,'127.0.0.1',r)),new Promise(r=>foreign.listen(0,'127.0.0.1',r))]); + const device='http://127.0.0.1:'+server.address().port,other='http://127.0.0.1:'+foreign.address().port; + browser=await chromium.launch({channel:'chrome',headless:true});const page=await browser.newPage();page.setDefaultTimeout(8000); + const call=()=>page.evaluate(async device=>{try{const r=await fetch(device+'/probe',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer SYNTHETIC_BROWSER_TOKEN'},body:'{"x":1}'});return {ok:r.ok,body:await r.json()};}catch(e){return {blocked:true};}},device); + const ws=()=>page.evaluate(device=>new Promise(resolve=>{const s=new WebSocket(device.replace('http:','ws:')+'/ws');const timer=setTimeout(()=>{s.close();resolve('timeout');},5000);s.onopen=()=>{clearTimeout(timer);s.close();resolve('open');};s.onerror=()=>{clearTimeout(timer);resolve('blocked');};}),device); + await page.goto(device);trace.length=0;assert.deepEqual(await call(),{ok:true,body:{ok:true}});assert.equal(trace.length,1);assert.equal(trace[0].business,1);assert.equal(trace[0].origin,device);assert.equal(trace[0].authorization,'Bearer SYNTHETIC_BROWSER_TOKEN');assert.equal(trace[0].acao,device); + trace.length=0;const ordinary=await page.evaluate(async()=>{const r=await fetch('/probe/ws-http');return r.status;});assert.equal(ordinary,400);assert.equal(trace.length,1);assert.equal(trace[0].lookup,1);assert.equal(trace[0].upgrade,0);assert.equal(trace[0].business,0);assert.equal(trace[0].allocations,0);assert.equal(trace[0].auth,0); + trace.length=0;const ordinaryCli=await fetch(device+'/probe/ws-http');assert.equal(ordinaryCli.status,400);assert.equal(trace[0].upgrade,0);assert.equal(trace[0].business,0); + trace.length=0;assert.equal(await ws(),'open');assert.equal(trace.at(-1).upgrade,1); + await page.goto(other);trace.length=0;assert.deepEqual(await call(),{blocked:true});assert(trace.some(r=>r.method==='OPTIONS'));assert(trace.every(r=>r.origin===other&&r.ret!==0&&!r.lookup&&!r.auth&&!r.business&&!r.reads&&!r.allocations)); + trace.length=0;const opaque=await page.evaluate(async device=>{const r=await fetch(device+'/probe?public=1',{method:'POST',mode:'no-cors',headers:{'Content-Type':'text/plain'},body:'{"x":1}'});return r.type;},device);assert.equal(opaque,'opaque');assert.equal(trace.length,1);assert.equal(trace[0].method,'POST');assert.equal(trace[0].origin,other);assert.equal(trace[0].business,0);assert.equal(trace[0].reads,0);assert.equal(trace[0].lookup,0); + trace.length=0;assert.equal(await ws(),'blocked');assert.equal(trace.at(-1).origin,other);assert.equal(trace.at(-1).upgrade,0);assert.equal(trace.at(-1).lookup,0); + // Same transport without Origin still needs its normal authorization. + trace.length=0;let cli=await fetch(device+'/probe',{method:'POST',headers:{Authorization:'Bearer SYNTHETIC_BROWSER_TOKEN'},body:'{"x":1}'});assert.equal(cli.status,200);assert.equal(trace[0].origin,undefined);assert.equal(trace[0].acao,''); + trace.length=0;cli=await fetch(device+'/probe',{method:'POST',body:'{"x":1}'});assert.equal(cli.status,401);assert.equal(trace[0].auth,1);assert.equal(trace[0].business,0);assert.equal(trace[0].reads,0); + // Grant this precise public origin in a separate compiled policy, never by + // accepting arbitrary Host/Origin pairs or by changing the browser settings. + const allowed=path.join(temp,'explicit');build(allowed,other);executable=allowed; + trace.length=0;assert.deepEqual(await call(),{ok:true,body:{ok:true}});assert(trace.some(r=>r.method==='OPTIONS'&&r.status===204&&!r.business));assert(trace.some(r=>r.method==='POST'&&r.business===1&&r.origin===other&&r.acao===other)); + trace.length=0;assert.equal(await ws(),'open');assert.equal(trace.at(-1).upgrade,1); + console.log('PASS real Chrome: same-origin API/WS, credentialed cross-origin preflight denial, opaque simple POST zero effects, foreign WS denied before101, CLI auth retained, exact explicit origin API/WS accepted; ordinary GET to WS-only route rejected'); + }finally{ + await browser?.close();for(const s of sockets)s.destroy();await Promise.all([server&&new Promise(r=>server.close(r)),foreign&&new Promise(r=>foreign.close(r))]);fs.rmSync(temp,{recursive:true,force:true}); + } +}); diff --git a/tests/prompts/ota.browser.test.cjs b/tests/prompts/ota.browser.test.cjs index 9b87833a..2b0f1c44 100644 --- a/tests/prompts/ota.browser.test.cjs +++ b/tests/prompts/ota.browser.test.cjs @@ -467,3 +467,46 @@ for (const language of ['zh-CN', 'en-US']) { }); }); } + +for (const language of ['zh-CN', 'en-US']) { + test(`${language}: expired reboot session confirms minimal running identity without another login`, async () => { + await otaPage(language, 'manual-reboot-session', async ({page, state}) => { + state.running.version = '0.6.2+target'; + let rebooted = false, protected401 = false, probes = 0; + await page.route('**/api/v1/system/reboot', async route => { + rebooted = true; state.running = {...state.running, label: 'ota_1'}; + await route.fulfill({json: {code: 0, data: {status: 'rebooting'}}}); + }); + await page.route('**/api/v1/ota/progress', async route => { + if (!rebooted) return route.fallback(); + protected401 = true; + await route.fulfill({status: 401, json: {error: 'Unauthorized'}}); + }); + await page.route('**/api/v1/ota/partitions', async route => { + if (!rebooted) return route.fallback(); + probes++; + if (probes === 1) return route.abort('connectionrefused'); + // Same version in the old slot must not be accepted. + const running = {label: probes === 2 ? 'ota_0' : state.running.label, version: state.running.version, project: 'TianShanOS'}; + await route.fulfill({json: {code: 0, data: {running}}}); + }); + await manualInput(page, 'SD card', false); + await page.evaluate(() => otaFromFile()); state.app = 'pending_reboot'; + await page.evaluate(() => refreshOtaProgress()); + await page.evaluate(async () => {try {await api.call('ota.progress', null, 'GET');} catch(error) {window.expiredStatus=error.httpStatus;}}); + assert(protected401); assert.equal(await page.evaluate(() => window.expiredStatus),401); + await page.waitForFunction(() => otaUpgrade?.phase === 'done'); + assert(probes >= 3); + assert.equal(await page.locator('#login-modal').isVisible(), false); + assert.equal(await page.locator('#ota-state-text').textContent(), await page.evaluate(() => t('ui.allUpgradeComplete'))); + }); + }); + test(`${language}: minimal partition response is not sent to full card rendering`, async () => { + await otaPage(language, 'manual-public-view', async ({page, state}) => { + const errors=[];page.on('pageerror', error=>errors.push(error.message)); + await page.route('**/api/v1/ota/partitions', route => route.fulfill({json:{code:0,data:{running:{label:'ota_0',version:state.running.version,project:'TianShanOS'}}}})); + await page.evaluate(() => {document.getElementById('ota-partitions').innerHTML='';return loadOtaData();}); + assert.equal(await page.locator('#ota-partitions .partition-card').count(),0);assert.deepEqual(errors,[]); + }); + }); +} diff --git a/tests/prompts/ownership.browser.test.cjs b/tests/prompts/ownership.browser.test.cjs index db629c13..9b584ab9 100644 --- a/tests/prompts/ownership.browser.test.cjs +++ b/tests/prompts/ownership.browser.test.cjs @@ -56,7 +56,8 @@ async function sessionPage(language) { await route.fulfill({json:{code:0,data:{token:`${params.username}-session-${++sequence}`,username:params.username,level:params.username,expires_in:3600,password_changed:true}}}); } else if(url.pathname.endsWith('/auth/status')) { requests.push({endpoint:'status',params,authorization:request.headers().authorization}); - await route.fulfill({json:{code:0,data:{valid:true}}}); + const username=params.token.split('-')[0]; + await route.fulfill({json:{code:0,data:{valid:true,username,level:username,password_changed:true,expires_in:3600}}}); } else if(url.pathname.endsWith('/auth/logout')) { requests.push({endpoint:'logout',params});await route.fulfill({json:{success:true}}); } else if(url.pathname.endsWith('/system/reboot')) { @@ -398,7 +399,7 @@ test('R2: stale finally cannot unlock the new page read',async()=>{ let finishOld,finishNew;api.call=()=>new Promise(r=>finishOld=r);const old=refreshDataWidgets(); router.routes['/']=()=>{};await router.navigate();api.call=()=>new Promise(r=>finishNew=r);const newer=refreshDataWidgets(); const newStarted=typeof finishNew==='function';finishOld({code:0,data:{variables:[]}});await old; - const stillLocked=dataWidgetsRefreshing;if(finishNew)finishNew({code:0,data:{variables:[]}});await newer; + const stillLocked=!!dataWidgetsRefreshing;if(finishNew)finishNew({code:0,data:{variables:[]}});await newer; return {newStarted,stillLocked,released:!dataWidgetsRefreshing}; });assert(r.newStarted&&r.stillLocked&&r.released); }finally{await context.close();} @@ -487,15 +488,16 @@ for(const language of ['zh-CN','en-US']) { const {page,context,errors}=await pageFor(language);try{ await page.goto(base);await page.waitForFunction(()=>i18n.isReady()); const result=await page.evaluate(async()=>{ - closeLoginModal();api.token='admin-token';const calls=[]; + closeLoginModal();api.token='admin-token';api.level='admin';api.username='admin';const calls=[]; window.fetch=async(url,options)=>{calls.push({url,headers:options.headers,body:options.body});return {ok:true,status:200,json:async()=>({status:String(url).includes('/file/upload')?'uploaded':'success'})};}; const file=await api.fileUpload('/sdcard/ordinary file.txt','ordinary'); + api.token='root-token';api.level='root';api.username='root'; const firmware=await uploadImageToDevice('/api/v1/ota/firmware?auto_reboot=false','firmware','ota.firmware'); const www=await uploadImageToDevice('/api/v1/ota/www','www','ota.www'); return {calls,file,firmware,www}; }); assert.equal(result.file.status,'uploaded');assert(result.firmware.success&&result.www.success); - assert.deepEqual(result.calls.map(c=>c.headers.Authorization),['Bearer admin-token','Bearer admin-token','Bearer admin-token']); + assert.deepEqual(result.calls.map(c=>c.headers.Authorization),['Bearer admin-token','Bearer root-token','Bearer root-token']); assert.deepEqual(result.calls.map(c=>c.body),['ordinary','firmware','www']);assert.equal(result.calls[1].headers['Content-Type'],'application/octet-stream');assert.match(result.calls[1].url,/auto_reboot=false$/);assert.deepEqual(errors,[]); }finally{await context.close();} }); @@ -954,3 +956,28 @@ for(const language of ['zh-CN','en-US']){ }finally{await f.context.close();} }); } + +// Binary upload replies use the actual API client and upload list, not a copied formatter. +for (const language of ['zh-CN','en-US']) { + test(`R06: uncertain file replacement retains selection and explains recovery ${language}`,async()=>{ + const {page,context,errors}=await pageFor(language);let attempts=0; + try { + await page.route('**/api/v1/file/upload?*',async route=>{ + attempts++;assert.equal(route.request().method(),'POST'); + assert.equal(route.request().headers().authorization,'Bearer local-root'); + await route.fulfill(attempts===1?{status:409,json:{code:409,error:'file_replace_uncertain'}}:{status:200,json:{status:'uploaded',path:'/sdcard/replacement.bin',size:3}}); + }); + await page.goto(base);await page.waitForFunction(()=>i18n.isReady()); + const first=await page.evaluate(async()=>{ + closeLoginModal();api.token='local-root';api.level='root';api.username='root'; + api.storageStatus=async()=>({code:0,data:{sd:{mounted:true}}});api.storageList=async()=>({code:0,data:{entries:[]}}); + await loadFilesPage();currentFilePath='/sdcard';showUploadDialog();handleFileSelect({target:{files:[new File([new Uint8Array([1,0,3])],'replacement.bin')]}}); + const result=await uploadFiles(); + return {result,text:document.getElementById('upload-list').textContent,selection:filesToUpload.map(f=>f.name),heading:t('failure.ops.file.upload.unknown'),hint:t('failure.reasons.file_replace_uncertain.hint')}; + }); + assert.equal(first.result.success,0);assert.equal(first.result.failures.length,1); + assert.deepEqual(first.selection,['replacement.bin']);assert(first.text.includes(first.heading));assert(first.text.includes(first.hint));assert(!first.text.includes('file_replace_uncertain'));assert.equal(attempts,1); + const second=await page.evaluate(()=>uploadFiles());assert.equal(second.success,1);assert.equal(second.failures.length,0);assert.equal(attempts,2);assert.deepEqual(errors,[]); + } finally {await context.close();} + }); +} diff --git a/tests/prompts/package.json b/tests/prompts/package.json index 5690da12..015b1349 100644 --- a/tests/prompts/package.json +++ b/tests/prompts/package.json @@ -5,8 +5,8 @@ "node": ">=22" }, "scripts": { - "test": "cd ../.. && node --test tests/prompts/static.test.cjs tests/prompts/regression.test.cjs tests/prompts/widgets-structure.test.cjs tests/prompts/key-generation.test.cjs tests/prompts/failure-catalog.test.cjs tests/prompts/ota.test.cjs tests/prompts/device-names.test.cjs", - "test:browser": "cd ../.. && node --test --test-concurrency=2 tests/prompts/browser.test.cjs tests/prompts/ownership.browser.test.cjs tests/prompts/widgets-layout.test.cjs tests/prompts/condition-editor.browser.test.cjs tests/prompts/input-repair.browser.test.cjs tests/prompts/ssh-copyid-cache.browser.test.cjs tests/prompts/ssh-fingerprint.browser.test.cjs tests/prompts/failure-messages.browser.test.cjs tests/prompts/flows.browser.test.cjs tests/prompts/key-generation.browser.test.cjs tests/prompts/key-generation-cache.browser.test.cjs tests/prompts/lpmu-lifecycle.browser.test.cjs tests/prompts/ota.browser.test.cjs tests/prompts/configuration.browser.test.cjs tests/prompts/configuration-lifecycle.browser.test.cjs tests/prompts/widget-config.browser.test.cjs tests/prompts/source-test-lifecycle.browser.test.cjs tests/prompts/service-runs.browser.test.cjs tests/macos27/ui-correction.browser.cjs tests/prompts/exec-results.browser.test.cjs tests/prompts/device-names.browser.test.cjs tests/prompts/toast-layout.browser.test.cjs", + "test": "cd ../.. && node --test tests/prompts/api-methods.test.cjs tests/prompts/static.test.cjs tests/prompts/regression.test.cjs tests/prompts/widgets-structure.test.cjs tests/prompts/key-generation.test.cjs tests/prompts/failure-catalog.test.cjs tests/prompts/ota.test.cjs tests/prompts/device-names.test.cjs", + "test:browser": "cd ../.. && node --test --test-concurrency=2 tests/prompts/api-methods.browser.test.cjs tests/prompts/browser.test.cjs tests/prompts/ownership.browser.test.cjs tests/prompts/widgets-layout.test.cjs tests/prompts/condition-editor.browser.test.cjs tests/prompts/input-repair.browser.test.cjs tests/prompts/ssh-copyid-cache.browser.test.cjs tests/prompts/ssh-fingerprint.browser.test.cjs tests/prompts/failure-messages.browser.test.cjs tests/prompts/flows.browser.test.cjs tests/prompts/key-generation.browser.test.cjs tests/prompts/key-generation-cache.browser.test.cjs tests/prompts/lpmu-lifecycle.browser.test.cjs tests/prompts/ota.browser.test.cjs tests/prompts/configuration.browser.test.cjs tests/prompts/configuration-lifecycle.browser.test.cjs tests/prompts/widget-config.browser.test.cjs tests/prompts/source-test-lifecycle.browser.test.cjs tests/prompts/service-runs.browser.test.cjs tests/macos27/ui-correction.browser.cjs tests/prompts/exec-results.browser.test.cjs tests/prompts/device-names.browser.test.cjs tests/prompts/toast-layout.browser.test.cjs tests/prompts/file-images.browser.test.cjs tests/prompts/origin.browser.test.cjs tests/prompts/ws-input.browser.test.cjs tests/prompts/proxy-samples.browser.test.cjs", "test:xterm": "cd ../.. && node --test tests/prompts/xterm-vendor.test.cjs tests/prompts/xterm-offline.test.cjs", "test:configuration": "cd ../.. && node --test tests/prompts/configuration.browser.test.cjs tests/prompts/configuration-lifecycle.browser.test.cjs tests/prompts/widget-config.browser.test.cjs tests/prompts/source-test-lifecycle.browser.test.cjs tests/prompts/service-runs.browser.test.cjs", "test:packaged": "cd ../.. && node --test tests/prompts/packaged.browser.test.cjs", diff --git a/tests/prompts/pagekit.cjs b/tests/prompts/pagekit.cjs index 068fb14b..0d48d815 100644 --- a/tests/prompts/pagekit.cjs +++ b/tests/prompts/pagekit.cjs @@ -5,20 +5,39 @@ // (an empty success) or kit.DROP (the connection is cut: the device never answers). const {before, after} = require('node:test'); const assert = require('node:assert/strict'); -const http = require('node:http'), fs = require('node:fs'), path = require('node:path'); +const http = require('node:http'), https = require('node:https'), fs = require('node:fs'), path = require('node:path'), os = require('node:os'), crypto = require('node:crypto'); +const {spawnSync} = require('node:child_process'); const {chromium} = require('playwright'); const {root} = require('./harness.cjs'); +const {logical: methodContract, http: routeMethods} = require('./api-methods.json'); +const methodBits = {GET: 1, POST: 2, PUT: 4, DELETE: 8}; const DROP = Symbol('drop'); -let browser; +let browser, tlsOptions, tlsDirectory; function install() { - before(async () => { browser = await chromium.launch({channel: 'chrome', headless: true}); }); - after(async () => { await browser?.close(); }); + before(async () => { + const args = []; + if (process.env.TS_TEST_WEB_TLS === '1') { + tlsDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ts-ui-tls-')); + const key = path.join(tlsDirectory, 'synthetic.key'), cert = path.join(tlsDirectory, 'synthetic.crt'); + const result = spawnSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-days', '2', '-subj', '/CN=127.0.0.1', '-addext', 'subjectAltName=IP:127.0.0.1,DNS:localhost', '-addext', 'basicConstraints=critical,CA:FALSE', '-addext', 'keyUsage=digitalSignature', '-addext', 'extendedKeyUsage=serverAuth', '-keyout', key, '-out', cert], {encoding: 'utf8'}); + assert.equal(result.status, 0, result.stderr); + fs.chmodSync(key, 0o600); + tlsOptions = {key: fs.readFileSync(key), cert: fs.readFileSync(cert), minVersion: 'TLSv1.2'}; + const spki = new crypto.X509Certificate(tlsOptions.cert).publicKey.export({type: 'spki', format: 'der'}); + args.push('--ignore-certificate-errors-spki-list=' + crypto.createHash('sha256').update(spki).digest('base64')); + } + browser = await chromium.launch({channel: 'chrome', headless: true, args}); + }); + after(async () => { + try { await browser?.close(); } + finally { tlsOptions?.key.fill(0); if (tlsDirectory) fs.rmSync(tlsDirectory, {recursive: true, force: true}); } + }); } async function open(language, respond = () => undefined, {viewport} = {}) { const calls = [], errors = []; - const server = http.createServer((req, res) => { + const handler = (req, res) => { const url = new URL(req.url, 'http://local'); const send = body => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(typeof body === 'string' ? body : JSON.stringify(body)); }; if (url.pathname.startsWith('/api/v1/')) { @@ -28,6 +47,13 @@ async function open(language, respond = () => undefined, {viewport} = {}) { req.on('end', () => { const call = {endpoint: url.pathname.slice('/api/v1/'.length), method: req.method, params: req.method === 'GET' ? Object.fromEntries(url.searchParams) : (raw && /json/i.test(req.headers['content-type'] || '') ? JSON.parse(raw) : {})}; calls.push(call); + const methods = routeMethods[call.endpoint] ?? methodContract[call.endpoint.replaceAll('/', '.')]; + if (methods === undefined || !(methods & methodBits[call.method])) { + res.statusCode = methods === undefined ? 404 : 405; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({code: 7, error: methods === undefined ? 'not_found' : 'method_not_allowed'})); + return; + } const out = respond(call); if (out === DROP) { req.socket.destroy(); return; } send(out ?? {code: 0, data: {}}); @@ -36,18 +62,25 @@ async function open(language, respond = () => undefined, {viewport} = {}) { } const file = path.resolve(root, '.' + (url.pathname === '/' ? '/index.html' : url.pathname)); if (!file.startsWith(root + '/')) { res.writeHead(403).end(); return; } - fs.readFile(file, (error, data) => { + const compressed = process.env.TS_TEST_WEB_GZIP === '1' && fs.existsSync(file + '.gz'); + fs.readFile(compressed ? file + '.gz' : file, (error, data) => { if (error) { res.writeHead(404).end(); return; } + if (compressed) { res.setHeader('Content-Encoding', 'gzip'); res.setHeader('Vary', 'Accept-Encoding'); } res.setHeader('Content-Type', ({'.js': 'application/javascript', '.html': 'text/html', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml'})[path.extname(file)] || 'application/octet-stream'); res.end(data); }); - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const base = `http://127.0.0.1:${server.address().port}`; - const context = await browser.newContext({locale: language, ...(viewport ? {viewport} : {})}); + }; + const server = tlsOptions ? https.createServer(tlsOptions, handler) : http.createServer(handler); + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); + const base = `${tlsOptions ? 'https' : 'http'}://127.0.0.1:${server.address().port}`; + let context; + const close = async () => { await context?.close(); server.closeAllConnections?.(); await new Promise(resolve => server.close(resolve)); }; + try { + context = await browser.newContext({locale: language, ...(viewport ? {viewport} : {})}); await context.addInitScript(language => { localStorage.setItem('ts_language', language); - class Socket { static OPEN = 1; static CONNECTING = 0; constructor() { this.readyState = 0; } send() {} close() { this.readyState = 3; } } + window.__NativeWebSocket = window.WebSocket; + class Socket { static OPEN = 1; static CONNECTING = 0; constructor(url) { this.url = url; this.readyState = 0; } send() {} close() { this.readyState = 3; } } window.WebSocket = Socket; }, language); const page = await context.newPage(); @@ -55,7 +88,9 @@ async function open(language, respond = () => undefined, {viewport} = {}) { await page.goto(base); await page.waitForFunction(() => i18n.isReady()); await page.evaluate(() => closeLoginModal()); - return {page, calls, errors, close: async () => { await context.close(); await new Promise(resolve => server.close(resolve)); }}; + if (tlsOptions) assert.equal(new URL(page.url()).protocol, 'https:'); + return {page, calls, errors, server, base, close}; + } catch (error) { await close(); throw error; } } async function withPage(language, respond, run) { const d = await open(language, respond); diff --git a/tests/prompts/proxy-samples.browser.test.cjs b/tests/prompts/proxy-samples.browser.test.cjs new file mode 100644 index 00000000..c14da5d0 --- /dev/null +++ b/tests/prompts/proxy-samples.browser.test.cjs @@ -0,0 +1,22 @@ +// Real UI handlers and both languages, synthetic device replies; no remote sockets. +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const kit=require('./pagekit.cjs');kit.install(); +for(const language of ['zh-CN','en-US'])for(const protocol of ['websocket','socketio'])for(const reason of ['ws_message_too_large','ws_invalid_frame','success']){ + test(`${language} ${protocol}: ${reason} is actionable and source form remains editable`,async()=>{ + const endpoint=protocol==='websocket'?'automation/proxy/websocket_test':'automation/proxy/socketio_test'; + const reply=reason==='success'?{code:0,data:protocol==='websocket'?{connected:true,message:{temperature:23}}:{connected:true,event:'status',data:{temperature:23},available_paths:[{path:'temperature',type:'number',value:23}]}}:{code:7,message:reason,data:{connected:true,error:reason}}; + await kit.withPage(language,call=>call.endpoint===endpoint?reply:undefined,async({page,calls})=>{ + await page.evaluate(protocol=>{api.token='fixture-root';api.level='root';api.username='root';showAddSourceModal();switchSourceType(protocol);document.getElementById(protocol==='websocket'?'source-ws-uri':'source-sio-url').value=protocol==='websocket'?'ws://192.0.2.9:81/feed':'http://192.0.2.9:3000';},protocol); + await page.evaluate(protocol=>protocol==='websocket'?testWsConnection():testSioConnection(),protocol); + const box=protocol==='websocket'?'#ws-test-result':'#sio-test-result',shown=await page.locator(box+' .test-status').innerText(); + assert(shown.trim());assert(!/ws_message_too_large|ws_invalid_frame|undefined|NaN/.test(shown)); + if(reason==='ws_message_too_large')assert(shown.includes(language==='zh-CN'?'65536':'64 KiB')); + if(reason==='ws_invalid_frame')assert(language==='zh-CN'?shown.includes('分帧'):shown.includes('framing')); + if(reason==='success')assert((await page.locator(protocol==='websocket'?'#ws-json-preview':'#sio-json-preview').innerText()).includes('23')); + if(protocol==='socketio'&&reason!=='success')assert(!/ws_message_too_large|ws_invalid_frame/.test(await page.locator('#sio-json-preview').innerText())); + const request=calls.find(call=>call.endpoint===endpoint);assert(request);assert.equal(request.method,'POST'); + assert.equal(await page.locator(protocol==='websocket'?'#source-ws-uri':'#source-sio-url').inputValue(),protocol==='websocket'?'ws://192.0.2.9:81/feed':'http://192.0.2.9:3000'); + }); + }); +} diff --git a/tests/prompts/rule-pack.browser.test.cjs b/tests/prompts/rule-pack.browser.test.cjs deleted file mode 100644 index 290ca8da..00000000 --- a/tests/prompts/rule-pack.browser.test.cjs +++ /dev/null @@ -1,209 +0,0 @@ -// Real page and file picker, local simulated device. Cryptography/storage are verified separately by production C tests. -const {test,before,after}=require('node:test'); -const assert=require('node:assert/strict'); -const fs=require('node:fs'),path=require('node:path'),http=require('node:http'); -const {chromium}=require('playwright'); -const root=path.resolve(__dirname,'../../components/ts_webui/web'); -let browser; -before(async()=>{browser=await chromium.launch({channel:'chrome',headless:true});}); -after(async()=>{await browser?.close();}); -const hash='a'.repeat(64); -const id='night\'"<&>'; -const preview={valid:true,trusted:true,target_matches:true,type:'automation_rule',id,name:'Night test', - signer:'Test Developer',official:true,exists:false,expected_revision:0,expected_generation:7,credential_generation:4, - package_digest:hash,rule:{id,name:'Night test',conditions:[{variable:'future.sample'}],actions:[{type:'log',message:'Test'}]}, - warnings:['dynamic_inputs']}; -async function pageFor(language,mode,run){ - const calls=[];let saved=false,writes=0,sourceEnabled=false; - const server=http.createServer((req,res)=>{ - const url=new URL(req.url,'http://local'); - if(url.pathname.startsWith('/api/v1/')){ - let raw='';req.on('data',part=>raw+=part); - req.on('end',()=>{ - const endpoint=url.pathname.slice(8); - const params=req.method==='GET'?Object.fromEntries(url.searchParams):(raw?JSON.parse(raw):{}); - calls.push({endpoint,params}); - let reply={code:0,data:{}}; - if(endpoint==='automation/sources/list')reply={code:0,data:{sources:[{id:'source-only',label:'Source',enabled:sourceEnabled,type:'ssh'}]}}; - if(endpoint==='automation/sources/enable'||endpoint==='automation/sources/disable'){ - assert.deepEqual(params,{id:'source-only'});sourceEnabled=endpoint.endsWith('/enable'); - } - if(endpoint==='automation/rules/get')reply={code:1,message:'not_found'}; - if(endpoint==='automation/rules/import'){ - if(params.preview){ - const data={...preview,exists:mode==='old',expected_revision:mode==='old'?4:0}; - if(params.tscfg==='unsupported'){res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify({code:1,message:'action_unsupported'}));return;} - if(params.tscfg==='untrusted')data.trusted=false; - if(params.tscfg==='slow'||params.tscfg==='fast')data.rule={...preview.rule,name:params.tscfg}; - reply={code:0,data}; - if(params.tscfg==='slow'){ - setTimeout(()=>{res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(reply));},150);return; - } - } - else{ - ++writes; - assert.equal(params.expected_revision,mode==='old'?4:0); - assert.equal(params.expected_generation,7); - assert.equal(params.credential_generation,4); - assert.equal(params.package_digest,hash); - if(mode==='conflict')reply={code:1,message:'revision_conflict'}; - else{ - saved=true; - if(mode==='lost'||mode==='unknown'||mode==='deleted'){ - res.writeHead(200,{'Content-Type':'application/json'});res.flushHeaders(); - res.write('{"code":0,');setImmediate(()=>res.destroy());return; - } - reply={code:0,data:{id,saved:true,durable:true,runtime_applied:false,restart_required:true,saved_revision:1,saved_generation:8}}; - } - } - } - if(endpoint==='automation/rules/list')reply={code:0,data:{loaded:true,recovery_required:mode==='unknown',rules:saved?[{id,name:'Night test',enabled:false, - readonly:true,restart_required:true,runtime_active:mode==='old',saved_revision:mode==='old'?5:1,active_revision:mode==='old'?4:0,saved_generation:8, - package_digest:hash,conditions_count:1,actions_count:1}]:[]}}; - if(endpoint==='ssh/hosts/list')reply={code:0,data:{hosts:[]}}; - if(endpoint==='ssh/commands/list')reply={code:0,data:{commands:[]}}; - if(endpoint==='automation/rules/list'&&mode==='deleted')reply={code:0,data:{loaded:true,recovery_required:false,rules:[{ - id,name:'Old rule',enabled:true,readonly:false,allow_manual_trigger:true,manual_trigger:true,show_on_dashboard:true, - pending_change:'delete',saved_exists:false,saved_revision:null,saved_generation:8,saved_source:null,package_digest:null, - restart_required:true,runtime_active:true,active_revision:4,revision:4,conditions_count:0,actions_count:1,actions:[{type:'log',message:'old'}]}]}}; - res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(reply)); - });return; - } - const file=path.resolve(root,'.'+(url.pathname==='/'?'/index.html':url.pathname)); - if(!file.startsWith(root+'/')){res.writeHead(403).end();return;} - fs.readFile(file,(error,data)=>{if(error){res.writeHead(404).end();return;} - res.setHeader('Content-Type',({'.js':'application/javascript','.css':'text/css','.html':'text/html','.svg':'image/svg+xml','.woff2':'font/woff2'})[path.extname(file)]||'application/octet-stream'); - res.end(data); - }); - }); - await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); - const context=await browser.newContext({locale:language}); - await context.addInitScript(language=>{ - localStorage.setItem('ts_language',language); - class Socket{static OPEN=1;static CONNECTING=0;constructor(){this.readyState=0;}send(){}close(){this.readyState=3;}} - window.WebSocket=Socket; - },language); - const page=await context.newPage(),errors=[]; - page.on('pageerror',e=>errors.push(e.message)); - try{ - await page.goto('http://127.0.0.1:'+server.address().port); - await page.waitForFunction(()=>i18n.isReady()); - await page.evaluate(()=>{closeLoginModal();document.body.insertAdjacentHTML('beforeend','
');showImportRuleModal();}); - await page.locator('#import-rule-file').setInputFiles({name:'renamed-package.tscfg',mimeType:'application/json',buffer:Buffer.from('local page fixture')}); - await page.waitForFunction(()=>!document.getElementById('import-rule-btn').disabled); - assert.equal(await page.locator('#import-rule-preview b').count(),0,'the signed name must remain text'); - assert.match(await page.locator('#import-rule-preview').innerText(),/Night test<\/b>/); - await run({page,calls,writes:()=>writes,saved:()=>saved}); - assert.deepEqual(errors,[]); - }finally{await context.close();await new Promise(resolve=>server.close(resolve));} -} -// The sentence the page must show for a failed verification / import comes from the failure catalogue (one source of truth). -const said=(page,op,file,extra)=>page.evaluate(([op,file,extra])=>describeFailure({op,params:{kind:t('failure.kinds.rule'),file:file??window._importRuleFilename??''},...extra}).message,[op,file,extra]); -const shown=(page,text)=>page.waitForFunction(text=>document.getElementById('import-rule-result').textContent.includes(text),text); -for(const language of ['zh-CN','en-US']){ - test(language+': preview -> one save -> pending row and escaped ID',async()=>{ - await pageFor(language,'ok',async({page,calls,writes,saved})=>{ - await page.locator('#import-rule-btn').click(); - await page.waitForFunction(()=>document.getElementById('import-rule-result').textContent===t('rulePack.saved')); - await page.waitForFunction(()=>document.querySelector('#rules-list .tr:not(.th)')); - assert(saved());assert.equal(writes(),1); - const buttons=page.locator('#rules-list .tr:not(.th) button'); - for(let i=0;ic.endpoint==='automation/rules/list')); - }); - }); - test(language+': a lost save reply is observed without repeating the write',async()=>{ - await pageFor(language,'lost',async({page,writes})=>{ - await page.locator('#import-rule-btn').click(); - await page.waitForFunction(()=>document.getElementById('import-rule-result').textContent===t('rulePack.saved')); - assert.equal(writes(),1); - }); - }); - test(language+': saved generation conflict requires a fresh preview',async()=>{ - await pageFor(language,'conflict',async({page,writes,saved})=>{ - await page.locator('#import-rule-btn').click(); - await shown(page,await said(page,'pack.import',null,{token:'revision_conflict',write:true})); - assert.equal(writes(),1);assert.equal(saved(),false); - assert(await page.locator('#import-rule-btn').isDisabled()); - }); - }); - test(language+': pending replacement retains only current trigger and export controls',async()=>{ - await pageFor(language,'old',async({page,writes})=>{ - await page.locator('#import-rule-btn').click(); - await page.waitForFunction(()=>document.querySelector('#rules-list .tr:not(.th)')); - const buttons=page.locator('#rules-list .tr:not(.th) button'); - for(const [index,disabled] of [[0,true],[1,false],[2,true],[3,false],[4,true]])assert.equal(await buttons.nth(index).isDisabled(),disabled); - assert.match(await buttons.nth(1).getAttribute('title'),language==='zh-CN'?/当前|旧/:/older/); - assert.equal(await buttons.nth(3).getAttribute('title'),await page.evaluate(()=>t('rulePack.exportCurrent'))); - assert.equal(writes(),1); - }); - }); - test(language+': recovery failure cannot confirm an uncertain save',async()=>{ - await pageFor(language,'unknown',async({page,calls,writes})=>{ - await page.locator('#import-rule-btn').click(); - await shown(page,await said(page,'pack.import',null,{token:'commit_unknown',write:true})); - await page.waitForTimeout(100); - assert(calls.some(c=>c.endpoint==='automation/rules/list'));assert.equal(writes(),1); - assert((await page.locator('#import-rule-result').innerText()).includes(await said(page,'pack.import',null,{token:'commit_unknown',write:true}))); - assert(await page.locator('#import-rule-btn').isDisabled()); - }); - }); - test(language+': out-of-order previews cannot replace the newest selected bytes',async()=>{ - await pageFor(language,'ok',async({page,calls,writes})=>{ - await page.locator('#import-rule-file').setInputFiles({name:'slow.tscfg',buffer:Buffer.from('slow')}); - await page.waitForTimeout(20); - await page.locator('#import-rule-file').setInputFiles({name:'fast.tscfg',buffer:Buffer.from('fast')}); - await page.waitForFunction(()=>!document.getElementById('import-rule-btn').disabled); - await page.waitForTimeout(200); - assert.equal(await page.evaluate(()=>rulePackPreview.rule.name),'fast'); - await page.locator('#import-rule-btn').click(); - await page.waitForFunction(()=>document.getElementById('import-rule-result').textContent===t('rulePack.saved')); - assert.equal(calls.find(c=>c.endpoint==='automation/rules/import'&&!c.params.preview).params.tscfg,'fast');assert.equal(writes(),1); - }); - }); - test(language+': an untrusted preview cannot enable import',async()=>{ - await pageFor(language,'ok',async({page,writes})=>{ - await page.locator('#import-rule-file').setInputFiles({name:'untrusted.tscfg',buffer:Buffer.from('untrusted')}); - await page.waitForFunction(()=>document.getElementById('import-rule-result').classList.contains('error')); - assert(await page.locator('#import-rule-btn').isDisabled());assert.equal(writes(),0); - }); - }); - test(language+': confirmed deletion row and quick action cannot trigger or confirm an uncertain pack save',async()=>{ - await pageFor(language,'deleted',async({page,calls,writes})=>{ - await page.locator('#import-rule-btn').click(); - await shown(page,await said(page,'pack.import',null,{token:'commit_unknown',write:true})); - assert.equal(writes(),1); - await page.evaluate(async()=>{await refreshRules();document.body.insertAdjacentHTML('beforeend','
');await refreshQuickActions();}); - assert.equal(await page.locator('#rules-list .tr:not(.th)').count(),1); - assert.match(await page.locator('#rules-list').innerText(),language==='zh-CN'?/已保存删除,待重启移除/:/Deletion saved; removal requires restart/); - const buttons=page.locator('#rules-list .tr:not(.th) button'); - for(const [i,disabled] of [[0,true],[1,true],[2,true],[3,false],[4,true]])assert.equal(await buttons.nth(i).isDisabled(),disabled); - const card=page.locator('#quick-actions-grid .quick-action-card');assert.equal(await card.count(),1); - assert.equal(await card.getAttribute('data-allowed'),'false');assert.equal(await card.getAttribute('aria-disabled'),'true'); - assert.match(await card.innerText(),language==='zh-CN'?/已保存删除/:/Deletion saved/); - await page.evaluate(id=>triggerQuickAction(id),id); - assert.equal(calls.filter(c=>c.endpoint==='automation/rules/trigger').length,0); - }); - }); - test(language+': unsupported action preview has a translated error and cannot save',async()=>{ - await pageFor(language,'ok',async({page,writes})=>{ - await page.locator('#import-rule-file').setInputFiles({name:'unsupported.tscfg',buffer:Buffer.from('unsupported')}); - await shown(page,await said(page,'pack.verify','unsupported.tscfg',{token:'action_unsupported'})); - assert(await page.locator('#import-rule-btn').isDisabled());assert.equal(writes(),0); - assert.doesNotMatch(await page.locator('#import-rule-result').innerText(),/rulePack\.errors/); - }); - }); - test(language+': datasource switch works without a same-name rule',async()=>{ - await pageFor(language,'ok',async({page,calls})=>{ - await page.evaluate(async()=>{hideImportRuleModal();document.body.insertAdjacentHTML('beforeend','
');await refreshSources();}); - const button=page.locator('#sources-list button[role="switch"]'); - await button.click();await page.waitForFunction(()=>document.querySelector('#sources-list button[role="switch"]').getAttribute('aria-checked')==='true'); - await button.click();await page.waitForFunction(()=>document.querySelector('#sources-list button[role="switch"]').getAttribute('aria-checked')==='false'); - assert.equal(calls.filter(c=>c.endpoint==='automation/sources/enable').length,1); - assert.equal(calls.filter(c=>c.endpoint==='automation/sources/disable').length,1); - assert.equal(calls.filter(c=>c.endpoint==='automation/rules/get').length,0); - }); - }); -} diff --git a/tests/prompts/ws-input.browser.test.cjs b/tests/prompts/ws-input.browser.test.cjs new file mode 100644 index 00000000..5f120a8c --- /dev/null +++ b/tests/prompts/ws-input.browser.test.cjs @@ -0,0 +1,60 @@ +const {test,before,after}=require('node:test'); +const assert=require('node:assert/strict'); +const http=require('node:http'),crypto=require('node:crypto'),fs=require('node:fs'),path=require('node:path'); +const {chromium}=require('playwright'); +let server,browser,base;const records=new Map(),sockets=new Set(); +before(async()=>{ + server=http.createServer((req,res)=>{ + if(req.url==='/terminal.js'){res.setHeader('Content-Type','application/javascript');res.end(fs.readFileSync(path.resolve(process.env.WS_INPUT_TEST_SOURCE||'components/ts_webui/web/js/terminal.js')));} + else{res.setHeader('Content-Type','text/html');res.end('');} + }); + server.on('upgrade',(req,socket,head)=>{ + const id=new URL(req.url,'http://local').pathname,accept=crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64'); + records.set(id,[]);sockets.add(socket);socket.on('close',()=>sockets.delete(socket));socket.on('error',()=>{}); + socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+accept+'\r\n\r\n'); + let pending=Buffer.alloc(0); + const consume=chunk=>{ + pending=Buffer.concat([pending,chunk]); + while(pending.length>=2){ + const fin=!!(pending[0]&128),opcode=pending[0]&15,masked=!!(pending[1]&128);let n=pending[1]&127,offset=2; + if(n===126){if(pending.length<4)return;n=pending.readUInt16BE(2);offset=4;} + else if(n===127){if(pending.length<10)return;n=Number(pending.readBigUInt64BE(2));offset=10;} + if(n>1024*1024){socket.destroy();return;}if(pending.lengthserver.listen(0,'127.0.0.1',resolve));base='http://127.0.0.1:'+server.address().port; + browser=await chromium.launch({channel:'chrome',headless:true}); +}); +after(async()=>{await browser?.close();for(const socket of sockets)socket.destroy();await new Promise(resolve=>server?.close(resolve));}); +for(const kind of ['ASCII','Unicode','escaped controls'])test(kind+': real Chrome sends complete bounded frames without changing SSH input',async()=>{ + const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message)); + try{ + await page.goto(base);await page.waitForFunction(()=>typeof WebTerminal==='function'); + const result=await page.evaluate(async({url,kind})=>{ + const text=kind==='ASCII'?'pasted command \n'.repeat(25000):kind==='Unicode'?'x'.repeat(2047)+'🚀中文'.repeat(20000):'\x01\x02\n\t"\\'.repeat(20000); + const socket=new WebSocket(url);await new Promise((resolve,reject)=>{socket.onopen=resolve;socket.onerror=reject;}); + let sent=0,received=0,done; + const ready=new Promise(resolve=>{done=resolve;}); + socket.onmessage=()=>{received++;if(received===sent)done();}; + const target={ws:{readyState:WebSocket.OPEN,send:data=>{sent++;socket.send(data);}}}; + WebTerminal.prototype.sendSshInput.call(target,text);await ready;socket.close();return {text,sent}; + },{url:base.replace('http:','ws:')+'/'+encodeURIComponent(kind),kind}); + const frames=records.get('/'+encodeURIComponent(kind));assert.equal(frames.length,result.sent);assert(frames.length>1); + assert(frames.every(f=>f.fin&&f.opcode===1&&f.n<=64*1024&&f.json.type==='ssh_input')); + assert.equal(frames.map(f=>f.json.data).join(''),result.text); + assert(frames.every(f=>!/[\uD800-\uDBFF]$/.test(f.json.data)&&! /^[\uDC00-\uDFFF]/.test(f.json.data))); + assert.deepEqual(errors,[]); + }finally{await page.close();} +}); +test('empty input and disconnected input submit no messages',async()=>{ + const page=await browser.newPage();try{ + await page.goto(base);await page.waitForFunction(()=>typeof WebTerminal==='function'); + assert.equal(await page.evaluate(()=>{let calls=0;const send=()=>calls++;WebTerminal.prototype.sendSshInput.call({ws:{readyState:WebSocket.OPEN,send}},'');WebTerminal.prototype.sendSshInput.call({ws:{readyState:WebSocket.CLOSED,send}},'text');return calls;}),0); + }finally{await page.close();} +}); diff --git a/tests/release/test_release.py b/tests/release/test_release.py index 960b421e..1651998b 100644 --- a/tests/release/test_release.py +++ b/tests/release/test_release.py @@ -1,3 +1,4 @@ +import sys import importlib.util import re import tempfile @@ -5,6 +6,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT/'tools')) spec = importlib.util.spec_from_file_location('check_release', ROOT / 'tools/check_release.py') module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) @@ -15,6 +17,23 @@ def test_current_notes_match_version(self): version = (ROOT / 'version.txt').read_text().strip() self.assertEqual(module.validate(f'v{version}', f'{version}+fixture.1234', ROOT).name, f'v{version}.md') + def test_version_identity_has_no_clock_and_changes_with_source(self): + from unittest.mock import patch + import gen_version + with tempfile.TemporaryDirectory() as folder: + root = Path(folder); (root / 'version.txt').write_text('0.6.5\n') + (root / 'main').mkdir(); source = root / 'main/main.c'; source.write_text('int value = 1;\n') + with patch.object(gen_version, 'get_git_hash', return_value=''): + first = gen_version.generate_version(root) + self.assertRegex(first, r'^0\.6\.5\+s[0-9a-f]{8}$') + self.assertEqual(first, gen_version.generate_version(root)) + source.write_text('int value = 2;\n') + self.assertNotEqual(first, gen_version.generate_version(root)) + with patch.object(gen_version, 'get_git_hash', return_value='abcdef12'), patch.object(gen_version, 'is_git_dirty', return_value=False): + self.assertEqual(gen_version.generate_version(root), '0.6.5+abcdef12') + with patch.object(gen_version, 'get_git_hash', return_value='abcdef12'), patch.object(gen_version, 'is_git_dirty', return_value=True): + self.assertRegex(gen_version.generate_version(root), r'^0\.6\.5\+abcdef12d\.[0-9a-f]{8}$') + def test_mismatch_and_missing_notes_rejected(self): with tempfile.TemporaryDirectory() as folder: root = Path(folder) @@ -35,13 +54,13 @@ def test_actual_workflow_release_condition(self): policy = importlib.util.module_from_spec(policy_spec) policy_spec.loader.exec_module(policy) cases = [ - ('RMinte-AI/TianshanOS', 'push', 'refs/heads/main', {}, True), + ('RMinte/TianshanOS', 'push', 'refs/heads/main', {}, True), ('massif-01/TianshanOS', 'push', 'refs/heads/main', {}, False), - ('RMinte-AI/TianshanOS', 'pull_request', 'refs/pull/41/merge', {}, False), - ('RMinte-AI/TianshanOS', 'push', 'refs/heads/develop', {}, False), - ('RMinte-AI/TianshanOS', 'push', 'refs/tags/v0.5.2', {}, True), - ('RMinte-AI/TianshanOS', 'release', 'refs/tags/v0.5.2', {'action': 'published'}, True), - ('RMinte-AI/TianshanOS', 'workflow_dispatch', 'refs/heads/main', {}, False), + ('RMinte/TianshanOS', 'pull_request', 'refs/pull/41/merge', {}, False), + ('RMinte/TianshanOS', 'push', 'refs/heads/develop', {}, False), + ('RMinte/TianshanOS', 'push', 'refs/tags/v0.5.2', {}, True), + ('RMinte/TianshanOS', 'release', 'refs/tags/v0.5.2', {'action': 'published'}, True), + ('RMinte/TianshanOS', 'workflow_dispatch', 'refs/heads/main', {}, False), ] for repo, event, ref, payload, expected in cases: with self.subTest(repo=repo, event=event, ref=ref): @@ -61,11 +80,15 @@ def job(name): self.assertIn('make_latest: "true"', release) self.assertIn('overwrite_files: "true"', release) self.assertNotIn('skip_release', release) - self.assertIn("os.environ['BUILD_VERSION']", release) - self.assertIn("os.environ['BUILD_COMMIT']", release) + self.assertNotIn('Add build identity to the Chinese release notes', release) + self.assertNotIn('notes.open(', release) + self.assertNotIn('body:', release) self.assertIn('firmware/**/*.zip', release) + self.assertIn('firmware/**/*.bin', release) + self.assertIn('name: TianshanOS ${{ steps.preflight.outputs.tag }}', release) + self.assertIn('firmware/**/flasher_args.json', release) self.assertIn('python3 tools/serial_upgrade.py package --build-dir build', job('build')) - self.assertIn('build/tianshanos-serial-*.zip', job('build')) + self.assertNotIn("steps.signed_package", job('build')) self.assertIn('python3 tools/ci/check_profile.py', job('changes')) gate = job('ci-gate') selected = re.search(r'^ needs: \[(.*?)\]$', gate, re.M).group(1) @@ -76,6 +99,27 @@ def job(name): self.assertIn('CI Gate failed: workflow cancelled at the final decision', gate) self.assertNotIn('paths-ignore:', workflow) + def test_public_asset_name_and_flash_mapping_match(self): + import json, subprocess + workflow = (ROOT / '.github/workflows/build.yml').read_text() + step = workflow.split(' - name: Normalize public firmware filename\n', 1)[1].split(' - name:', 1)[0] + body = step.split("python3 - <<'PYTHON'\n", 1)[1].split(' PYTHON', 1)[0] + code = '\n'.join(line[10:] for line in body.splitlines()) + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) / 'firmware'; root.mkdir() + original = b'synthetic firmware bytes' + (root / 'TianShanOS.bin').write_bytes(original) + (root / 'www.bin').write_bytes(b'synthetic web') + args = {'app': {'file': 'TianShanOS.bin'}, 'flash_files': {'0x20000': 'TianShanOS.bin', '0x6a0000': 'www.bin'}} + (root / 'flasher_args.json').write_text(json.dumps(args)) + subprocess.run([sys.executable, '-c', code], cwd=folder, check=True) + self.assertNotIn('TianShanOS.bin', {p.name for p in root.iterdir()}) + self.assertIn('TianshanOS.bin', {p.name for p in root.iterdir()}) + self.assertEqual((root / 'TianshanOS.bin').read_bytes(), original) + actual = json.loads((root / 'flasher_args.json').read_text()) + self.assertEqual(actual['app']['file'], 'TianshanOS.bin') + self.assertEqual(actual['flash_files'], {'0x20000': 'TianshanOS.bin', '0x6a0000': 'www.bin'}) + if __name__ == '__main__': unittest.main() diff --git a/tests/release/test_security_profile.py b/tests/release/test_security_profile.py new file mode 100644 index 00000000..fb143847 --- /dev/null +++ b/tests/release/test_security_profile.py @@ -0,0 +1,121 @@ +"""Effective CMake auth policy and actual ESP app descriptor artifact identity.""" +import hashlib +import os +from unittest.mock import patch +import sys +import importlib.util +import json +import struct +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT/'tools')) +spec = importlib.util.spec_from_file_location('release_security', ROOT/'tools/check_release.py') +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +class SecurityProfileTests(unittest.TestCase): + def profile(self, development=False, recovery=False, auth=True, security=True, webui=True, tls=False): + return dict(schema=2, development=development, recovery=recovery, + webui_enabled=webui, auth_required=auth, security_enabled=security, webui_tls=tls) + + def image(self, path, project='TianShanOS', version='0.6.3'): + # Image/descriptor fixture only, no claim of valid flashable firmware. + data=bytearray(512);data[0]=0xE9;struct.pack_into('addr) +static void dns_setserver(unsigned i,const ip_addr_t *dns){assert(on_tcpip&&i<2);host_resolver[i]=*dns;} +static const ip_addr_t *dns_getserver(unsigned i){assert(on_tcpip&&i<2);return &host_resolver[i];} + static esp_err_t esp_netif_set_dns_info_api(esp_netif_api_msg_t *msg) { esp_netif_dns_param_t *p=msg->data; if(p->dns_type==dns_failure_kind)return ESP_ERR_INVALID_STATE; @@ -199,10 +209,12 @@ static void *exec_tcpip(void *arg) { ctx->ret=ctx->fn(ctx->arg);on_tcpip=false;return NULL; } static void (*after_dispatch)(void); +static esp_err_t read_eth_host_dns(void *context); static esp_err_t esp_netif_tcpip_exec(esp_netif_callback_fn fn,void *arg) { - assert(!on_tcpip);++apply_dispatches;struct exec_context ctx={fn,arg,ESP_FAIL};pthread_t worker; + /* Status reads share TCP/IP but are not DHCP application attempts. */ + assert(!on_tcpip);if(fn!=read_eth_host_dns)++apply_dispatches;struct exec_context ctx={fn,arg,ESP_FAIL};pthread_t worker; assert(!pthread_create(&worker,NULL,exec_tcpip,&ctx));assert(!pthread_join(worker,NULL)); - if(after_dispatch){void (*event)(void)=after_dispatch;after_dispatch=NULL;event();} + if(fn!=read_eth_host_dns&&after_dispatch){void (*event)(void)=after_dispatch;after_dispatch=NULL;event();} return ctx.ret; } static void interface_up(unsigned index) { @@ -377,7 +389,7 @@ static void setup(bool erase_nvs) { } netifs_exist=eth_netif_exists=true;s_link_up=true;initialize_eth_intent();check_start_table=false;console_text[0]=0; fail_stage=FAIL_NONE;stop_calls=start_calls=apply_dispatches=0;after_dispatch=NULL; - memset(dns_writes,0,sizeof(dns_writes)); + memset(dns_writes,0,sizeof(dns_writes));memset(host_resolver,0,sizeof(host_resolver)); dns_failure_kind=-1; model_tick=100;status_reads_before_failure=-1;started_notifications=stopped_notifications=0; fail_read_key=fail_write_key=NULL;fail_open_read=missing_namespace=fail_commit=false;fail_cleanup_stop=false; @@ -499,7 +511,7 @@ static void check_transitions_and_queries(void) { for(unsigned custom=0;custom<2;custom++) { if(!custom)s_state.iface[1].config.pool.dns1[0]=0; else strcpy(s_state.iface[1].config.pool.dns1,"8.8.8.8"); - memset(dns_writes,0,sizeof(dns_writes));assert(ts_net_set_ip_info(TS_NET_IF_ETH,&info)==ESP_OK); + memset(dns_writes,0,sizeof(dns_writes));memset(host_resolver,0,sizeof(host_resolver));assert(ts_net_set_ip_info(TS_NET_IF_ETH,&info)==ESP_OK); assert(dns_writes[0]==1&&dns_writes[1]==1); assert(servers[1].dns_server[0].addr==(custom?inet_addr("8.8.8.8"):info.dns1)); assert(servers[1].dns_server[1].addr==info.dns2); diff --git a/tests/runtime/dhcp_bindings/test_eth_lifecycle.inc b/tests/runtime/dhcp_bindings/test_eth_lifecycle.inc index ea04ccbd..b2acf5c6 100644 --- a/tests/runtime/dhcp_bindings/test_eth_lifecycle.inc +++ b/tests/runtime/dhcp_bindings/test_eth_lifecycle.inc @@ -266,13 +266,24 @@ static void check_eth_lifecycle(void){ hardware_reset();assert(ts_net_manager_init()==ESP_OK&&ts_dhcp_server_init()==ESP_OK); assert(ts_net_manager_start(TS_NET_IF_ETH)==ESP_OK);deliver_events();run_delayed_task(); ts_net_ip_info_t cold_dns={0};assert(ts_net_get_ip_info(TS_NET_IF_ETH,&cold_dns)==ESP_OK); - uint32_t expected=inet_addr(custom?"8.8.8.8":"9.9.9.9"); + uint32_t expected=inet_addr("9.9.9.9"); + assert(host_resolver[0].addr==expected); assert(cold_dns.dns1==expected&&dns_writes[0]==(custom?2:1)); cJSON *visible=cJSON_CreateObject();add_ip_info_to_json(visible,&cold_dns); - assert(!strcmp(cJSON_GetObjectItem(visible,"dns1")->valuestring,custom?"8.8.8.8":"9.9.9.9"));cJSON_Delete(visible); + assert(!strcmp(cJSON_GetObjectItem(visible,"dns1")->valuestring,"9.9.9.9"));cJSON_Delete(visible); assert(option_value(&servers[1],DHCP_OPTION_DNS_SERVER,true)==inet_addr(custom?"8.8.8.8":"192.168.50.1")); assert(ts_dhcp_server_load_config()==ESP_OK); assert(ts_net_get_ip_info(TS_NET_IF_ETH,&cold_dns)==ESP_OK&&cold_dns.dns1==expected); + ts_net_if_config_t staged;assert(ts_net_manager_get_config(TS_NET_IF_ETH,&staged)==ESP_OK); + strcpy(staged.static_ip.dns1,"223.5.5.5");assert(ts_net_manager_set_config(TS_NET_IF_ETH,&staged)==ESP_OK); + assert(host_resolver[0].addr==expected); /* manager staging is not application */ + assert(ts_net_manager_restart(TS_NET_IF_ETH)==ESP_OK);deliver_events();run_delayed_task(); + assert(ts_net_get_ip_info(TS_NET_IF_ETH,&cold_dns)==ESP_OK&&cold_dns.dns1==inet_addr("223.5.5.5")); + assert(host_resolver[0].addr==inet_addr("223.5.5.5")); + ts_net_if_status_t observed;assert(ts_net_manager_get_if_status(TS_NET_IF_ETH,&observed)==ESP_OK); + assert(!strcmp(observed.ip_info.dns1,"223.5.5.5")); + assert(option_value(&servers[1],DHCP_OPTION_DNS_SERVER,true)==inet_addr(custom?"8.8.8.8":"192.168.50.1")); + assert(ts_dhcp_server_load_config()==ESP_OK&&host_resolver[0].addr==inet_addr("223.5.5.5")); } record("P2_cold_boot_same_host_DNS_readback_pool_override_empty_offer_and_reload"); for(unsigned kind=0;kind<2;kind++){ diff --git a/tests/runtime/host_env.sh b/tests/runtime/host_env.sh new file mode 100644 index 00000000..132827d2 --- /dev/null +++ b/tests/runtime/host_env.sh @@ -0,0 +1,7 @@ +# Shared host-test workspace. Explicit caller directories are never removed. +# Source after entering the repository root. Nested suites inherit this owner. +if [[ -z "${TS_TEST_BUILD_ROOT:-}" ]]; then + TS_TEST_BUILD_ROOT=$(mktemp -d "${TMPDIR:-/tmp}/tianshan-host.XXXXXX") + export TS_TEST_BUILD_ROOT + trap 'ts_host_status=$?; if (( ts_host_status == 0 )); then rm -rf -- "$TS_TEST_BUILD_ROOT"; else printf "Host-test artifacts retained: %s\n" "$TS_TEST_BUILD_ROOT" >&2; fi; exit "$ts_host_status"' EXIT +fi diff --git a/tests/runtime/host_paths.py b/tests/runtime/host_paths.py new file mode 100644 index 00000000..70cc23f1 --- /dev/null +++ b/tests/runtime/host_paths.py @@ -0,0 +1,29 @@ +"""Mutable host-test outputs: shared inside one run, isolated between runs. + +SDK/library paths supplied by the caller remain separate read-only inputs. +Standalone Python suites get a private directory retained for diagnosis. +""" +import os +from pathlib import Path +import tempfile + + +def build_dir(suite): + root = os.environ.get("TS_TEST_BUILD_ROOT") + path = Path(root) / suite if root else Path(tempfile.mkdtemp(prefix="ts-" + suite + "-")) + path.mkdir(parents=True, exist_ok=True) + return path + + +def sdk_library_dir(idf): + """Build the actual SDK crypto libraries once in this run's private root.""" + import shutil + import subprocess + native = build_dir("sdk-mbedtls") + if not all((native / "library" / name).exists() for name in ("libmbedcrypto.a", "libmbedx509.a")): + cmake = shutil.which("cmake") or "/Users/massif/.espressif/tools/cmake/3.30.2/CMake.app/Contents/bin/cmake" + env = {**os.environ, "DEVELOPER_DIR": "/Library/Developer/CommandLineTools"} + subprocess.run([cmake, "-S", str(idf / "components/mbedtls/mbedtls"), "-B", str(native), + "-DENABLE_PROGRAMS=OFF", "-DENABLE_TESTING=OFF"], check=True, env=env) + subprocess.run([cmake, "--build", str(native), "--target", "mbedcrypto", "mbedx509", "-j", "4"], check=True, env=env) + return native diff --git a/tests/runtime/http_fetch_stubs/esp_http_client.h b/tests/runtime/http_fetch_stubs/esp_http_client.h new file mode 100644 index 00000000..6b7b8687 --- /dev/null +++ b/tests/runtime/http_fetch_stubs/esp_http_client.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include +#include "esp_err.h" +#define ESP_ERR_HTTP_EAGAIN 0x7001 +typedef struct fixture_client *esp_http_client_handle_t; +typedef enum {HTTP_METHOD_GET,HTTP_METHOD_POST,HTTP_METHOD_PUT,HTTP_METHOD_DELETE} esp_http_client_method_t; +enum {HTTP_EVENT_ON_CONNECTED,HTTP_EVENT_DISCONNECTED,HTTP_EVENT_ERROR,HTTP_EVENT_HEADERS_SENT,HTTP_EVENT_ON_HEADER, + HTTP_EVENT_REDIRECT,HTTP_EVENT_ON_DATA,HTTP_EVENT_ON_FINISH}; +typedef struct {int event_id;esp_http_client_handle_t client;void *user_data,*data;int data_len;char *header_key,*header_value;} esp_http_client_event_t; +typedef struct { + const char *url,*cert_pem,*common_name,*username,*password; + int timeout_ms,buffer_size,buffer_size_tx; + esp_http_client_method_t method; + bool is_async,disable_auto_redirect,skip_cert_common_name_check; + esp_err_t(*event_handler)(esp_http_client_event_t*); + void *user_data; + int(*crt_bundle_attach)(void*); +} esp_http_client_config_t; +esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t*); +esp_err_t esp_http_client_set_header(esp_http_client_handle_t,const char*,const char*); +esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t,int); +esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t,const char*,int); +esp_err_t esp_http_client_close(esp_http_client_handle_t); +esp_err_t esp_http_client_cleanup(esp_http_client_handle_t); +esp_err_t esp_http_client_perform(esp_http_client_handle_t); +int esp_http_client_get_status_code(esp_http_client_handle_t); +int64_t esp_http_client_get_content_length(esp_http_client_handle_t); +bool esp_http_client_is_complete_data_received(esp_http_client_handle_t); diff --git a/tests/runtime/rule_pack/stubs/esp_err.h b/tests/runtime/rule_pack/stubs/esp_err.h index f732eefd..41012bc6 100644 --- a/tests/runtime/rule_pack/stubs/esp_err.h +++ b/tests/runtime/rule_pack/stubs/esp_err.h @@ -12,4 +12,5 @@ typedef int esp_err_t; #define ESP_ERR_NOT_FOUND 0x105 #define ESP_ERR_TIMEOUT 0x106 #define ESP_ERR_NOT_SUPPORTED 0x107 +#define ESP_ERR_NOT_FINISHED 0x10c #define ESP_ERR_NVS_NOT_FOUND 0x1102 diff --git a/tests/runtime/rule_pack/test_crypto.c b/tests/runtime/rule_pack/test_crypto.c index f5ccacbf..424adc45 100644 --- a/tests/runtime/rule_pack/test_crypto.c +++ b/tests/runtime/rule_pack/test_crypto.c @@ -8,7 +8,7 @@ #include "ts_storage.h" #include #include -#include "ts_api.h" +#include static char scratch[512]; static const char *mapped(const char *path,char out[1024]) { if(!strncmp(path,"/sdcard",7)){assert(scratch[0]);snprintf(out,1024,"%s%s",scratch,path+7);return out;}return path; @@ -16,24 +16,59 @@ static const char *mapped(const char *path,char out[1024]) { FILE *fixture_fopen(const char *path,const char *mode){char out[1024];return fopen(mapped(path,out),mode);} int fixture_stat(const char *path,struct stat *st){char out[1024];return stat(mapped(path,out),st);} int fixture_mkdir(const char *path,mode_t mode){char out[1024];return mkdir(mapped(path,out),mode);} -esp_err_t ts_storage_write_file(const char *path,const void *data,size_t size) { - assert(!strncmp(path,"/sdcard/config/",15));FILE *f=fixture_fopen(path,"wb");if(!f)return ESP_FAIL; - bool ok=fwrite(data,1,size,f)==size;return fclose(f)==0&&ok?ESP_OK:ESP_FAIL; +#include "nvs.h" +static unsigned file_writes, directories; +static bool fail_file_write; +static char stored_path[128]; +static char *stored_pack; +esp_err_t ts_storage_write_file(const char *path,const void *data,size_t size) +{ (void)path;(void)data;(void)size;assert(!"unexpected non-atomic file export in crypto test");return ESP_FAIL; } +esp_err_t ts_storage_mkdir_p(const char *path){ + assert(!strcmp(path,"/sdcard/config"));directories++; + if(scratch[0]){char out[1024];if(mkdir(mapped(path,out),0700)&&errno!=EEXIST)return ESP_FAIL;} + return ESP_OK; } -void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t code,const char *message){r->code=code;r->message=(char*)message;} -void ts_api_result_ok(ts_api_result_t *r,cJSON *data){r->code=TS_API_OK;r->data=data;} -#ifndef PACK_BASELINE +esp_err_t ts_storage_replace_file(const char *path,const void *data,size_t size){ + file_writes++;if(fail_file_write)return ESP_FAIL;snprintf(stored_path,sizeof stored_path,"%s",path); + free(stored_pack);stored_pack=malloc(size+1);assert(stored_pack);memcpy(stored_pack,data,size);stored_pack[size]=0; + if(scratch[0]){FILE *f=fixture_fopen(path,"wb");if(!f)return ESP_FAIL;bool ok=fwrite(data,1,size,f)==size;return fclose(f)==0&&ok?ESP_OK:ESP_FAIL;} + return ESP_OK; +} +#include "ts_api.h" +#include +#include +#define heap_caps_malloc(n,c) malloc(n) +#define MALLOC_CAP_SPIRAM 1 +#define MALLOC_CAP_8BIT 2 +#define ESP_LOGW(...) ((void)0) +esp_err_t ts_cert_init(void){return ESP_OK;} +#define TS_LOGI(...) ((void)0) +#define TS_STRDUP_PSRAM strdup +#include "ts_automation_document.h" +#include "ts_rule_codec.h" #define PACK_MALLOC malloc -#include "export_api.inc" -#endif +#include "pack_api.inc" #include "mbedtls/x509_crt.h" #include "mbedtls/oid.h" #include static time_t fixture_time; +time_t ts_time_sync_security_time(void) {return time(NULL);} time_t time(time_t *out){time_t now=fixture_time?fixture_time:TEST_TIME;if(out)*out=now;return now;} static char *device_key, *device_cert, *ca; -static uint32_t generation=1; +static uint32_t generation=1,clock_generation; +uint32_t ts_time_sync_security_generation(void) {return clock_generation;} static bool trusted_time=true; +/* Internal NVS is a storage boundary; real pack crypto and file reads stay real. */ +static struct {char key[16];ts_config_pack_acceptance_t value;} saved[8],pending; +static unsigned saved_count,accept_commits; +static bool fail_accept_read,fail_accept_set,fail_accept_commit,drop_accept_commit,change_clock_on_status; +static int saved_index(const char *key){for(unsigned i=0;i=sizeof(saved[i].value));memcpy(out,&saved[i].value,sizeof saved[i].value);}*n=sizeof saved[i].value;return ESP_OK;} +esp_err_t nvs_set_blob(nvs_handle_t h,const char *key,const void *bytes,size_t n){assert(h==1&&n==sizeof pending.value);if(fail_accept_set)return ESP_FAIL;assert(strlen(key)==15);strcpy(pending.key,key);memcpy(&pending.value,bytes,n);return ESP_OK;} +esp_err_t nvs_commit(nvs_handle_t h){assert(h==1&&pending.key[0]);if(fail_accept_commit)return ESP_FAIL;if(drop_accept_commit)return ESP_OK;int i=saved_index(pending.key);if(i<0){assert(saved_count<8);i=saved_count++;}saved[i]=pending;++accept_commits;return ESP_OK;} + static const char *certificate_after_read; static esp_err_t certificate_read_error; static char *read_file(const char *dir,const char *name) { @@ -60,9 +95,11 @@ esp_err_t ts_cert_parse_certificate(const char *s,size_t n,ts_cert_info_t *info) mbedtls_x509_crt_free(&c);return ESP_OK; } esp_err_t ts_cert_get_info(ts_cert_info_t *i){return device_cert?ts_cert_parse_certificate(device_cert,strlen(device_cert)+1,i):ESP_ERR_INVALID_STATE;} -esp_err_t ts_cert_get_status(ts_cert_pki_status_t *s){memset(s,0,sizeof *s);s->time_ready=trusted_time;s->generation=generation;return ESP_OK;} +esp_err_t ts_cert_get_status(ts_cert_pki_status_t *s){memset(s,0,sizeof *s);s->time_ready=trusted_time;s->generation=generation;if(change_clock_on_status)clock_generation++;return ESP_OK;} esp_err_t ts_cert_get_pack_snapshot(ts_cert_snapshot_t *s){ - memset(s,0,sizeof *s);s->key=strdup(device_key);s->certificate=strdup(device_cert);s->ca=strdup(ca);s->generation=generation;return ESP_OK; + memset(s,0,sizeof *s);if(certificate_read_error)return certificate_read_error; + if(!device_key||!device_cert)return ESP_ERR_INVALID_STATE; + s->key=strdup(device_key);s->certificate=strdup(device_cert);s->ca=ca?strdup(ca):NULL;s->generation=generation;return ESP_OK; } void ts_cert_free_snapshot(ts_cert_snapshot_t *s){if(s->key)memset(s->key,0,strlen(s->key));free(s->key);free(s->certificate);free(s->ca);memset(s,0,sizeof *s);} @@ -78,6 +115,12 @@ static void assert_export(const char *pem) { char expected[65];expected_fingerprint(pem,expected); assert(!strcmp(cJSON_GetObjectItem(response.data,"fingerprint")->valuestring,expected));cJSON_Delete(response.data); } +/* Use the actual legacy file reader and strict command-bearing loader. */ +static ts_config_pack_result_t load_rule_file(const char *path, ts_config_pack_t **pack) { + char *bytes=NULL;size_t length=0;*pack=NULL; + if(file_bytes(path,&bytes,&length)!=ESP_OK)return TS_CONFIG_PACK_ERR_IO; + ts_config_pack_result_t result=ts_config_pack_load_rule_mem(bytes,length,pack);free(bytes);return result; +} static void ordinary_consumers(const char *bytes,size_t size,ts_config_pack_result_t expected,const char *content) { ts_config_pack_t *pack=NULL;assert(ts_config_pack_load_mem(bytes,size,&pack)==expected); if(pack){assert(expected==TS_CONFIG_PACK_OK&&pack->sig_info.valid&&!strcmp(pack->content,content));ts_config_pack_free(pack);} @@ -104,13 +147,13 @@ static void ordinary_identity_cases(const char *dir,const char *certificate_name ordinary_consumers(a_bytes,a_len,TS_CONFIG_PACK_ERR_RECIPIENT,content); cJSON *bad=cJSON_Parse(b_bytes);cJSON *signature=cJSON_GetObjectItem(cJSON_GetObjectItem(bad,"signature"),"signature");signature->valuestring[0]=signature->valuestring[0]=='A'?'B':'A';char *invalid=cJSON_PrintUnformatted(bad); ordinary_consumers(invalid,strlen(invalid),TS_CONFIG_PACK_ERR_SIGNATURE,content);free(invalid);cJSON_Delete(bad); - /* Import/validate remain signature-only; memory load still performs real decryption. */ + /* Hardened import/validate share recipient, trust and decrypt admission. */ free(device_key);device_key=read_file(dir,"other.key");ts_config_pack_t *pack=NULL; assert(ts_config_pack_load_mem(b_bytes,b_len,&pack)==TS_CONFIG_PACK_ERR_DECRYPT&&!pack); free(device_key);device_key=strdup(b_key); free(device_cert);device_cert=NULL;assert(ts_config_pack_get_cert_fingerprint(fp,sizeof(fp))!=ESP_OK); ts_api_result_t response={0};assert(api_config_pack_export_cert(NULL,&response)!=ESP_OK&&!response.data); - ordinary_consumers(b_bytes,b_len,TS_CONFIG_PACK_ERR_RECIPIENT,content); + ordinary_consumers(b_bytes,b_len,TS_CONFIG_PACK_ERR_CERT_CHAIN,content); device_cert=strdup(b_cert); certificate_read_error=ESP_ERR_NO_MEM;assert(ts_config_pack_get_cert_fingerprint(fp,sizeof(fp))==ESP_ERR_NO_MEM); ordinary_consumers(b_bytes,b_len,TS_CONFIG_PACK_ERR_NO_MEM,content);certificate_read_error=ESP_OK; @@ -173,15 +216,40 @@ int main(int argc,char **argv) { mbedtls_x509_crt identity;mbedtls_x509_crt_init(&identity);assert(!mbedtls_x509_crt_parse(&identity,(unsigned char*)device_cert,strlen(device_cert)+1)); unsigned char der_hash[32];char der_fp[65];assert(ts_crypto_hash(TS_HASH_SHA256,identity.raw.p,identity.raw.len,der_hash,32)==ESP_OK);assert(ts_crypto_hex_encode(der_hash,32,der_fp,65)==ESP_OK&&strcmp(initial_fp,der_fp));mbedtls_x509_crt_free(&identity); puts("PASS F73 first certificate after init is current; historical trimmed-PEM identity differs from DER"); + #ifdef PACK_ORDINARY_TLS + free(device_cert);free(device_key);device_cert=read_file(dir,"tls-developer.pem");device_key=read_file(dir,"tls-developer.key"); + ordinary_identity_cases(dir,"recipient.pem","recipient.key"); + char *local=NULL;size_t local_len=0; + ts_config_pack_export_opts_t local_opts={.recipient_cert_pem=device_cert,.recipient_cert_len=strlen(device_cert)+1}; + assert(ts_config_pack_create("offline-data","{\"ordinary\":true}",17,&local_opts,&local,&local_len)==TS_CONFIG_PACK_OK); + ts_config_pack_t *data_pack=NULL; + assert(ts_config_pack_load_rule_mem(local,local_len,&data_pack)==TS_CONFIG_PACK_ERR_SIGNER_ROLE&&!data_pack); + char *selected_ca=ca;ca=read_file(dir,"alternate-root.pem"); + assert(ts_config_pack_load_mem(local,local_len,&data_pack)!=TS_CONFIG_PACK_OK&&!data_pack);free(ca);ca=selected_ca; + char offline_path[1024];snprintf(offline_path,sizeof(offline_path),"%s/offline-data.tscfg",dir); + FILE *offline_file=fopen(offline_path,"wb");assert(offline_file&&fwrite(local,1,local_len,offline_file)==local_len&&!fclose(offline_file)); + memset(saved,0,sizeof(saved));saved_count=accept_commits=0;trusted_time=false;fixture_time=1; + assert(ts_config_pack_load(offline_path,&data_pack)==TS_CONFIG_PACK_OK&&data_pack&&!data_pack->acceptance.accepted_at); + ts_config_pack_free(data_pack);data_pack=NULL;assert(!saved_count&&!accept_commits); + assert(ts_config_pack_load_mem(local,local_len,&data_pack)==TS_CONFIG_PACK_ERR_TIME_UNVERIFIED&&!data_pack); + assert(ts_config_pack_load_rule_mem(local,local_len,&data_pack)==TS_CONFIG_PACK_ERR_TIME_UNVERIFIED&&!data_pack); + assert(!unlink(offline_path));free(local);fixture_time=0;trusted_time=true; + free(device_cert);free(device_key);free(ca);puts("PASS original TLS Developer ordinary round-trip and existing local data before NTP; unselected CA rejected; code-signing and new-import time boundaries retained");return 0; + #endif + #ifndef PACK_UNCONFIGURED ordinary_identity_cases(dir,"developer-renewed.pem","developer.key"); ordinary_identity_cases(dir,"recipient.pem","recipient.key"); + /* Separate the upstream identity scenario from the original admission scenario. */ + memset(saved,0,sizeof saved);memset(&pending,0,sizeof pending);saved_count=accept_commits=0; + file_writes=directories=0;free(stored_pack);stored_pack=NULL;stored_path[0]=0; + #endif #endif #ifdef PACK_EXPORT_PAYLOADS export_payload_cases(dir,argv[2]);free(device_key);free(device_cert);free(ca);return 0; #endif char *recipient=read_file(dir,"recipient.pem"); const char *content="{\"type\":\"automation_rule\",\"rule\":{\"id\":\"night\",\"name\":\"Night\",\"enabled\":true,\"actions\":[{\"type\":\"log\",\"message\":\"test\"}]}}"; - ts_config_pack_export_opts_t opts={.recipient_cert_pem=recipient,.recipient_cert_len=strlen(recipient)}; + ts_config_pack_export_opts_t opts={.recipient_cert_pem=recipient,.recipient_cert_len=strlen(recipient),.description="retained metadata"}; #ifndef PACK_BASELINE char *exact=malloc(opts.recipient_cert_len);memcpy(exact,recipient,opts.recipient_cert_len);opts.recipient_cert_pem=exact; #endif @@ -204,6 +272,9 @@ int main(int argc,char **argv) { puts("PASS unconfigured signing root refuses a cryptographically valid package"); #else assert(made==TS_CONFIG_PACK_OK&&bytes&&length==strlen(bytes)); + ts_config_pack_sig_info_t outbound; + assert(ts_config_pack_verify_mem(bytes,length,&outbound)==TS_CONFIG_PACK_OK&&outbound.valid&&!saved_count); + ts_config_pack_export_opts_t self_opts={.recipient_cert_pem=device_cert,.recipient_cert_len=strlen(device_cert)+1}; char *self=NULL;size_t self_len=0;ts_config_pack_t *self_pack=NULL; assert(ts_config_pack_create("self",content,strlen(content),&self_opts,&self,&self_len)==TS_CONFIG_PACK_OK); @@ -213,6 +284,55 @@ int main(int argc,char **argv) { ts_config_pack_t *pack=NULL;ts_config_pack_acceptance_t accepted={0};uint32_t gen=0; assert(ts_config_pack_load_verified_mem(bytes,length,NULL,&pack,&accepted,&gen)==TS_CONFIG_PACK_OK); assert(gen==generation&&!strcmp(pack->content,content));ts_config_pack_free(pack); + /* File and legacy-memory entry points now share exact durable acceptance. */ + assert(ts_config_pack_load_rule_mem(bytes,length,&pack)==TS_CONFIG_PACK_OK); + assert(!memcmp(&pack->acceptance,&accepted,sizeof accepted)); + assert(pack->name&&!strcmp(pack->name,"ignored-name")&&pack->description&&!strcmp(pack->description,"retained metadata")&&pack->sig_info.is_official);ts_config_pack_free(pack); + assert(saved_count==1&&accept_commits==1); + ts_config_pack_sig_info_t verified_info; + assert(ts_config_pack_verify_mem(bytes,length,&verified_info)==TS_CONFIG_PACK_OK&&verified_info.valid&&verified_info.is_official); + cJSON *request=cJSON_CreateObject();cJSON_AddStringToObject(request,"content",bytes);ts_api_result_t api={0}; + assert(api_config_pack_verify(request,&api)==ESP_OK&&api.code==TS_API_OK&&cJSON_IsTrue(cJSON_GetObjectItem(api.data,"valid")));ts_api_result_free(&api); + assert(api_config_pack_import(request,&api)==ESP_OK&&api.code==TS_API_OK&&file_writes==1&&directories==1); + assert(stored_pack&&!strcmp(stored_pack,bytes)&&!strcmp(stored_path,"/sdcard/config/ignored-name.tscfg")); + assert(!strcmp(cJSON_GetObjectItem(api.data,"saved_path")->valuestring,stored_path));ts_api_result_free(&api); + char *old_stored=stored_pack;fail_file_write=true; + assert(api_config_pack_import(request,&api)!=ESP_OK&&api.code!=TS_API_OK&&stored_pack==old_stored&&!strcmp(stored_pack,bytes)); + ts_api_result_free(&api);fail_file_write=false;cJSON_Delete(request); + + char config_path[1024],json_path[1024];snprintf(config_path,sizeof config_path,"%s/boot.tscfg",dir);snprintf(json_path,sizeof json_path,"%s/boot.json",dir); + FILE *boot=fopen(config_path,"wb");assert(boot&&fwrite(bytes,1,length,boot)==length&&!fclose(boot)); + boot=fopen(json_path,"wb");assert(boot&&fputs("{\"untrusted_fallback\":true}",boot)>=0&&!fclose(boot)); + ts_config_pack_metadata_t imported; + assert(ts_config_pack_validate_file(config_path,&imported)==TS_CONFIG_PACK_OK&&imported.sig_info.valid&&imported.created_at>0&&!strcmp(imported.name,"ignored-name")); + request=cJSON_CreateObject();cJSON_AddStringToObject(request,"path",config_path); + assert(api_config_pack_import(request,&api)==ESP_OK&&api.code==TS_API_OK);ts_api_result_free(&api);cJSON_Delete(request); + assert(ts_config_pack_verify(config_path,&verified_info)==TS_CONFIG_PACK_OK&&verified_info.valid); + trusted_time=false; + assert(ts_config_pack_verify(config_path,&verified_info)==TS_CONFIG_PACK_OK&&verified_info.valid); + assert(ts_config_pack_validate_file(config_path,&imported)==TS_CONFIG_PACK_OK); + assert(ts_config_pack_load(config_path,&pack)==TS_CONFIG_PACK_OK&&!strcmp(pack->content,content));ts_config_pack_free(pack);assert(accept_commits==1); + char *selected=NULL;size_t selected_length=0;bool encrypted=false; + assert(ts_config_pack_load_with_priority(json_path,&selected,&selected_length,&encrypted)==ESP_OK&&encrypted&&!strcmp(selected,content));free(selected); + /* Same valid signature with one extra whitespace byte is a different package. */ + boot=fopen(config_path,"ab");assert(boot&&fputc(' ',boot)!=EOF&&!fclose(boot)); + /* Ordinary local data retains its original offline behavior; executable + * legacy automation still requires exact admitted bytes. */ + assert(ts_config_pack_load_with_priority(json_path,&selected,&selected_length,&encrypted)==ESP_OK&&encrypted&&!strcmp(selected,content));free(selected); + assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_TIME_UNVERIFIED&&!pack); + trusted_time=true; + drop_accept_commit=true;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_IO&&!pack);drop_accept_commit=false; + fail_accept_set=true;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_IO&&!pack);fail_accept_set=false; + fail_accept_commit=true;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_IO&&!pack);fail_accept_commit=false;assert(saved_count==1&&accept_commits==1); + assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_OK);ts_config_pack_free(pack);assert(saved_count==2); + trusted_time=false;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_OK);ts_config_pack_free(pack); + fail_accept_read=true;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_IO&&!pack);fail_accept_read=false; + /* An NVS index hit cannot substitute another complete package identity. */ + saved[1].value.package_sha256[0]^=1;assert(load_rule_file(config_path,&pack)==TS_CONFIG_PACK_ERR_TIME_UNVERIFIED&&!pack);saved[1].value.package_sha256[0]^=1; + assert(remove(config_path)==0);assert(ts_config_pack_load_with_priority(json_path,&selected,&selected_length,&encrypted)==ESP_OK&&!encrypted&&strstr(selected,"untrusted_fallback"));free(selected);assert(remove(json_path)==0); + trusted_time=true;change_clock_on_status=true; + assert(ts_config_pack_load_verified_mem(bytes,length,NULL,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CREDENTIAL_CHANGED&&!pack);change_clock_on_status=false; + /* Expiry is checked when first accepting; accepted exact bytes may reload. */ fixture_time=TEST_TIME+4000LL*86400; assert(ts_config_pack_load_verified_mem(bytes,length,NULL,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); @@ -222,6 +342,12 @@ int main(int argc,char **argv) { assert(ts_config_pack_load_verified_mem(bytes,length,&changed,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); changed=accepted;changed.root_sha256[0]^=1; assert(ts_config_pack_load_verified_mem(bytes,length,&changed,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); + changed=accepted;changed.package_sha256[0]^=1; + assert(ts_config_pack_load_verified_mem(bytes,length,&changed,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); + changed=accepted;changed.signer_sha256[0]^=1; + assert(ts_config_pack_load_verified_mem(bytes,length,&changed,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); + changed=accepted;changed.recipient[0]^=1; + assert(ts_config_pack_load_verified_mem(bytes,length,&changed,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_CERT_CHAIN); trusted_time=false; assert(ts_config_pack_load_verified_mem(bytes,length,NULL,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_TIME_UNVERIFIED); assert(ts_config_pack_load_verified_mem(bytes,length,&accepted,&pack,NULL,NULL)==TS_CONFIG_PACK_OK);ts_config_pack_free(pack); @@ -266,7 +392,7 @@ int main(int argc,char **argv) { cipher[0]=cipher[0]=='A'?'B':'A';bad=cJSON_PrintUnformatted(j); assert(ts_config_pack_load_verified_mem(bad,strlen(bad),NULL,&pack,NULL,NULL)==TS_CONFIG_PACK_ERR_SIGNATURE); free(bad);cJSON_Delete(j); - free(bytes);free(recipient);free(device_key);free(device_cert);free(ca); + free(stored_pack);stored_pack=NULL;free(bytes);free(recipient);free(device_key);free(device_cert);free(ca); puts("PASS real production create/trust/signature/ECDH/HKDF/GCM, cross-device PEM, offline accepted reload, malformed inputs"); #endif return 0; diff --git a/tests/runtime/rule_pack/test_file_trust.c b/tests/runtime/rule_pack/test_file_trust.c new file mode 100644 index 00000000..773301e7 --- /dev/null +++ b/tests/runtime/rule_pack/test_file_trust.c @@ -0,0 +1,61 @@ +/* Reuse the existing disposable PKI and storage boundary, not a second crypto fixture. */ +#include +#define main full_pack_crypto_suite +#include "test_crypto.c" +#undef main +int main(int argc,char **argv) +{ + assert(argc==2);const char *dir=argv[1]; + device_key=read_file(dir,"recipient.key");device_cert=read_file(dir,"recipient.pem");ca=read_file(dir,"root.pem"); + assert(ts_config_pack_init()==ESP_OK); + char *recipient_key=device_key,*recipient_cert=device_cert; + device_key=read_file(dir,"alternate-developer.key");device_cert=read_file(dir,"alternate-developer.pem"); + ts_config_pack_export_opts_t opts={.recipient_cert_pem=recipient_cert,.recipient_cert_len=strlen(recipient_cert)+1}; + char *bytes=NULL;size_t length=0;const char *content="{\"type\":\"automation_rule\",\"rule\":{\"id\":\"night\",\"name\":\"Night\",\"enabled\":true,\"actions\":[{\"type\":\"log\",\"message\":\"fixture\"}]}}"; + assert(ts_config_pack_create("unselected-publisher",content,strlen(content),&opts,&bytes,&length)==TS_CONFIG_PACK_OK); + free(device_key);free(device_cert);device_key=recipient_key;device_cert=recipient_cert; + ts_config_pack_t *pack=NULL; + ts_config_pack_result_t result=ts_config_pack_load_mem(bytes,length,&pack); + if(result==TS_CONFIG_PACK_OK){ts_config_pack_free(pack);fprintf(stderr,"FAIL actual legacy memory loader accepts an unselected publisher\n");return 1;} + assert(result==TS_CONFIG_PACK_ERR_CERT_CHAIN&&!pack&&!saved_count); + ts_config_pack_sig_info_t info={.valid=true}; + assert(ts_config_pack_verify_mem(bytes,length,&info)==TS_CONFIG_PACK_ERR_CERT_CHAIN&&!info.valid); + char temporary[]="/tmp/ts-pack-XXXXXX";assert(mkdtemp(temporary)); + char path[96],plain[96];snprintf(path,sizeof path,"%s/config.tscfg",temporary);snprintf(plain,sizeof plain,"%s/config.json",temporary); + FILE *file=fopen(path,"wb");assert(file&&fwrite(bytes,1,length,file)==length&&!fclose(file)); + file=fopen(plain,"wb");assert(file&&fputs("{\"fallback\":true}",file)>=0&&!fclose(file)); + assert(ts_config_pack_load(path,&pack)==TS_CONFIG_PACK_ERR_CERT_CHAIN&&!pack); + assert(ts_config_pack_verify(path,&info)==TS_CONFIG_PACK_ERR_CERT_CHAIN&&!info.valid); + ts_config_pack_metadata_t metadata={0};assert(ts_config_pack_validate_file(path,&metadata)==TS_CONFIG_PACK_ERR_CERT_CHAIN&&!metadata.sig_info.valid); + char *selected=NULL;size_t selected_len=0;bool used=false; + assert(ts_config_pack_load_with_priority(plain,&selected,&selected_len,&used)!=ESP_OK&&!selected&&!selected_len&&!used); + assert(read_system_file(plain,&selected,&selected_len,&used)==ESP_ERR_NOT_FINISHED&&!selected); + for(unsigned mode=0;mode<2;mode++){ + cJSON *request=cJSON_CreateObject();cJSON_AddStringToObject(request,mode?"path":"content",mode?path:bytes);ts_api_result_t api={0}; + assert(api_config_pack_verify(request,&api)==ESP_OK&&api.code==TS_API_OK&&cJSON_IsFalse(cJSON_GetObjectItem(api.data,"valid")));ts_api_result_free(&api); + assert(api_config_pack_import(request,&api)!=ESP_OK&&api.code!=TS_API_OK&&!api.data&&strstr(api.message,"pack_"));ts_api_result_free(&api);cJSON_Delete(request); + } + char base[96];snprintf(base,sizeof base,"%s/config",temporary); + cJSON *legacy=NULL;ts_auto_config_error_t error={0}; + assert(priority_json(base,TS_AUTO_CONFIG_RULE,&legacy,&error)!=ESP_OK&&!legacy&&!strcmp(error.reason,"signer_untrusted")); + assert(priority_json(base,TS_AUTO_CONFIG_SOURCE,&legacy,&error)!=ESP_OK&&!legacy); + assert(!file_writes&&!directories&&!saved_count); + /* Establish fresh trusted admission through the existing Root import, then + * real boot file reading works with the security clock unavailable. */ + device_key=read_file(dir,"developer.key");device_cert=read_file(dir,"developer.pem"); + char *trusted=NULL;size_t trusted_len=0; + assert(ts_config_pack_create("boot",content,strlen(content),&opts,&trusted,&trusted_len)==TS_CONFIG_PACK_OK); + free(device_key);free(device_cert);device_key=recipient_key;device_cert=recipient_cert; + file=fopen(path,"wb");assert(file&&fwrite(trusted,1,trusted_len,file)==trusted_len&&!fclose(file)); + assert(ts_config_pack_validate_file(path,&metadata)==TS_CONFIG_PACK_OK&&saved_count==1); + trusted_time=false;used=false; + assert(read_system_file(plain,&selected,&selected_len,&used)==ESP_OK&&used&&selected_len==strlen(content)&&!strcmp(selected,content));free(selected); + assert(priority_json(base,TS_AUTO_CONFIG_RULE,&legacy,&error)==ESP_OK&&legacy); + cJSON *provenance=cJSON_GetObjectItem(cJSON_GetObjectItem(legacy,"rule"),"_package"); + assert(cJSON_IsObject(provenance)&&strlen(cJSON_GetObjectItem(provenance,"package")->valuestring)==64&&cJSON_GetObjectItem(provenance,"policy")->valueint==1); + cJSON_Delete(legacy);legacy=NULL; + assert(priority_json(base,TS_AUTO_CONFIG_SOURCE,&legacy,&error)==ESP_OK&&legacy);cJSON_Delete(legacy); + assert(remove(path)==0&&remove(plain)==0&&rmdir(temporary)==0); + free(trusted);free(bytes);free(device_key);free(device_cert);free(ca); + puts("PASS actual file/memory/verify/validate/Root import and boot consumption reject valid-signature unselected publisher; trusted exact admission reloads offline; no plaintext fallback");return 0; +} diff --git a/tests/runtime/run_all.sh b/tests/runtime/run_all.sh index c34fa672..9ce6f462 100755 --- a/tests/runtime/run_all.sh +++ b/tests/runtime/run_all.sh @@ -1,18 +1,51 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" for suite in log codec ssh service_watch; do bash "tests/runtime/run_${suite}.sh" done +python3 tests/runtime/test_sdk_diagnostic_privacy.py bash tests/runtime/run_storage_paths.sh +python3 tests/runtime/test_external_storage_writes.py +python3 tests/runtime/test_external_storage_reads.py +python3 tests/runtime/test_led_file_reads.py bash tests/runtime/run_rule_pack.sh python3 tests/runtime/test_completion.py python3 tests/runtime/test_service_control.py python3 tests/runtime/test_sensitive_auth.py +python3 tests/runtime/test_request_params.py +python3 tests/runtime/test_api_access.py +for case_name in delivery privacy; do + python3 tests/runtime/test_log_delivery.py --case "$case_name" +done +python3 tests/runtime/test_complete_api_inventory.py +python3 tests/runtime/test_default_deny_policy.py +python3 tests/runtime/test_api_diagnostic_privacy.py +python3 tests/runtime/test_exec_delivery.py +python3 tests/runtime/test_api_context.py +python3 tests/runtime/test_config_privacy.py +python3 tests/runtime/test_cert_admission.py +python3 tests/runtime/test_auth_persistence.py +python3 tests/runtime/test_auth_persistence.py --case tokens +python3 tests/runtime/test_auth_persistence.py --case session_race +python3 tests/runtime/test_auth_persistence.py --case revocation +python3 tests/runtime/test_auth_persistence.py --case lockout +python3 tests/runtime/test_api_numeric_security.py +python3 tests/runtime/test_unimplemented_results.py python3 tests/runtime/test_port_forward.py python3 tests/runtime/test_compute_monitor.py python3 tests/runtime/test_http_file_stream.py +python3 tests/runtime/test_receive_budget.py +python3 tests/runtime/test_json_depth.py +python3 tests/runtime/test_proxy_ws_samples.py +python3 tests/runtime/test_ws_sdk_lifecycle.py +python3 tests/runtime/test_ws_diagnostic_transport.py +python3 tests/runtime/test_network_diagnostics.py +python3 tests/runtime/test_api_prebody.py +python3 tests/runtime/test_http_body_integrity.py +python3 tests/runtime/test_browser_origin.py python3 tests/runtime/test_sftp_list.py python3 tests/runtime/test_cli_option_contract.py python3 tests/runtime/test_system_memory.py @@ -20,6 +53,14 @@ python3 tests/runtime/test_system_reboot.py python3 tests/runtime/test_registry_tables.py python3 tests/runtime/test_console_lifecycle.py python3 tests/runtime/test_power_lifecycle.py +python3 tests/runtime/test_agx_reset.py +python3 tests/runtime/test_dns_lifecycle.py +python3 tests/runtime/test_http_transport_polling.py +python3 tests/runtime/test_http_client_privacy.py +python3 tests/runtime/test_http_fetch.py +python3 tests/runtime/test_https_startup.py +python3 tests/runtime/test_pki_http.py +python3 tests/runtime/test_ota_upload_handlers.py python3 tests/runtime/test_ota_lifecycle.py python3 tests/runtime/test_source_sampling.py python3 tests/runtime/test_dhcp_bindings.py @@ -51,5 +92,6 @@ done python3 tests/http_admission/run_host.py python3 tests/terminal_jobs/run_host.py bash tests/terminal_jobs/run_ws.sh +python3 tests/ws_subscriptions/run_input_admission.py bash tests/exec_results/run_host.sh node --test tests/http_admission/reconnect.test.cjs diff --git a/tests/runtime/run_codec.sh b/tests/runtime/run_codec.sh index c4cb87b8..c2da3939 100755 --- a/tests/runtime/run_codec.sh +++ b/tests/runtime/run_codec.sh @@ -1,8 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" -build=/tmp/tianshan-runtime-tests +build="$TS_TEST_BUILD_ROOT/codec" idf=${IDF_PATH:-/Users/massif/esp/v5.5.2/esp-idf} mkdir -p "$build" cc -std=c11 -g -fsanitize=address,undefined -Wno-deprecated-declarations -Itests/runtime/stubs -Itests/certificate/stubs -Icomponents/ts_automation/include -Icomponents/ts_security/include -I"$idf/components/json/cJSON" tests/runtime/test_codec.c components/ts_automation/src/ts_rule_codec.c components/ts_automation/src/ts_action_codec.c components/ts_automation/src/ts_action_filter.c "$idf/components/json/cJSON/cJSON.c" -lpthread -lm -o "$build/codec" diff --git a/tests/runtime/run_config_storage.sh b/tests/runtime/run_config_storage.sh index 3d7fda44..906bddf3 100644 --- a/tests/runtime/run_config_storage.sh +++ b/tests/runtime/run_config_storage.sh @@ -1,8 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh : "${IDF_PATH:=/Users/massif/esp/v5.5.2/esp-idf}" -: "${CONFIG_TEST_BUILD:=/tmp/tianshan-config-storage-tests}" +: "${CONFIG_TEST_BUILD:=$TS_TEST_BUILD_ROOT/config-storage}" mkdir -p "$CONFIG_TEST_BUILD" crypto_link=() if [[ "$(uname -s)" != Darwin ]]; then crypto_link=(-lcrypto); fi @@ -52,6 +53,10 @@ for path,names in [ assert match,name out.append(text[match.start():text.index('\n}',match.start())+2]) Path(sys.argv[1],'system_driver_persistence.inc').write_text('\n'.join(out)) +source=Path('main/ts_services.c').read_text() +start=source.index('esp_err_t ts_services_prepare_config(void)') +end=source.index('\n}',start)+2 +Path(sys.argv[1],'config_boot.inc').write_text(source[start:end]) PY_DRIVER cc "${common[@]}" "${migration_includes[@]}" -Icomponents/ts_drivers/include -I"$CONFIG_TEST_BUILD" tests/runtime/test_system_migration.c \ "$CONFIG_TEST_BUILD/led_persistence.o" "$IDF_PATH/components/json/cJSON/cJSON.c" \ @@ -59,7 +64,7 @@ cc "${common[@]}" "${migration_includes[@]}" -Icomponents/ts_drivers/include -I" "$CONFIG_TEST_BUILD/migration" cc "${common[@]}" -Itests/runtime/storage_stubs -Itests/runtime/rule_pack/stubs \ - -Icomponents/ts_automation/src -Icomponents/ts_core/ts_config/include -Icomponents/ts_security/include \ + -Icomponents/ts_automation/src -Icomponents/ts_storage/include -Icomponents/ts_core/ts_config/include -Icomponents/ts_security/include \ -I"$IDF_PATH/components/json/cJSON" tests/runtime/test_automation_file.c \ tests/runtime/storage_stubs/crypto.c "$IDF_PATH/components/json/cJSON/cJSON.c" \ "${crypto_link[@]}" -lm -o "$CONFIG_TEST_BUILD/files" @@ -94,11 +99,14 @@ parts=[source[begin:end]] for name in ['extract_json_value','cjson_to_value','auto_discover_json_fields','process_source_mappings', 'find_source_index','current_source_index','current_connection_index','sio_find_connection', 'sio_release_connection','ts_source_transport_changed','sio_handle_event_message', - 'ws_handle_message','sio_websocket_event_handler','read_variable_source','ts_source_sio_websocket_url','read_rest_source','sio_http_handshake','stream_connect']: - match=re.search(r'^(?:static )?(?:int|void|esp_err_t|sio_connection_t \*)\s*'+name+r'\([^;]+?\)\s*\{',source,re.M) + 'ws_handle_message','sio_websocket_event_handler','read_variable_source','ts_source_sio_url','read_rest_source','sio_http_handshake','stream_connect']: + match=re.search(r'^(?:static )?(?:int|void|bool|esp_err_t|sio_connection_t \*)\s*'+name+r'\([^;]+?\)\s*\{',source,re.M) assert match,name parts.append(source[match.start():source.index('\n}',match.start())+2]) api_source=Path('components/ts_api/src/ts_api_automation.c').read_text() +start=api_source.index('/* A diagnostic sample is one complete WS message') +end=api_source.index('// WebSocket 测试状态',start) +parts.append(api_source[start:end]) end=api_source.index('} ws_test_ctx_t;')+len('} ws_test_ctx_t;') parts.append(api_source[api_source.rfind('typedef struct {',0,end):end]) match=re.search(r'^static void ws_test_handler\([^;]+?\)\s*\{',api_source,re.M) @@ -198,6 +206,8 @@ cc "${common[@]}" -DCONFIG_TS_AUTOMATION_MAX_RULES=64 -Itests/runtime/storage_st -Icomponents/ts_jsonpath/include \ -Icomponents/ts_api/include \ -I"$IDF_PATH/components/json/cJSON" -I"$CONFIG_TEST_BUILD" \ + -Icomponents/ts_http_fetch/include -Itests/runtime/http_fetch_stubs -I"$IDF_PATH/components/http_parser" \ + components/ts_http_fetch/src/ts_http_url.c "$IDF_PATH/components/http_parser/http_parser.c" \ tests/runtime/test_automation_config.c components/ts_api/src/ts_api_auto_config.c \ components/ts_automation/src/ts_automation_document.c \ components/ts_automation/src/ts_automation_control.c \ diff --git a/tests/runtime/run_log.sh b/tests/runtime/run_log.sh index 25346849..a489460b 100755 --- a/tests/runtime/run_log.sh +++ b/tests/runtime/run_log.sh @@ -1,8 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" -build=/tmp/tianshan-runtime-tests +build="$TS_TEST_BUILD_ROOT/log" mkdir -p "$build" python3 - "$build" <<'PY' from pathlib import Path diff --git a/tests/runtime/run_rule_pack.sh b/tests/runtime/run_rule_pack.sh index 27089fd7..d7681ff1 100755 --- a/tests/runtime/run_rule_pack.sh +++ b/tests/runtime/run_rule_pack.sh @@ -4,6 +4,8 @@ cd "$(dirname "$0")/../.." export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" # Cryptographic verification remains production code with disposable PKI. python3 tests/runtime/test_rule_pack_crypto.py +python3 tests/runtime/test_rule_pack_crypto.py --ordinary-tls python3 tests/runtime/test_rule_pack_crypto.py --unconfigured +python3 tests/runtime/test_rule_pack_crypto.py --file-trust-case # Unified owner + actual rule publication/admission replaces the retired stores. bash tests/runtime/run_config_storage.sh diff --git a/tests/runtime/run_service_runs.sh b/tests/runtime/run_service_runs.sh index 8e291ef1..36a6e9e2 100644 --- a/tests/runtime/run_service_runs.sh +++ b/tests/runtime/run_service_runs.sh @@ -1,8 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh : "${IDF_PATH:=/Users/massif/esp/v5.5.2/esp-idf}" -: "${SERVICE_TEST_BUILD:=/tmp/tianshan-service-runs-tests}" +: "${SERVICE_TEST_BUILD:=$TS_TEST_BUILD_ROOT/service-runs}" mkdir -p "$SERVICE_TEST_BUILD" cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -Wno-deprecated-declarations \ -Itests/runtime/state_stubs -Itests/runtime/ssh_stubs -Itests/runtime/stubs \ diff --git a/tests/runtime/run_ssh.sh b/tests/runtime/run_ssh.sh index 8ce1a9e6..4789d303 100755 --- a/tests/runtime/run_ssh.sh +++ b/tests/runtime/run_ssh.sh @@ -1,8 +1,9 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh export DEVELOPER_DIR="${DEVELOPER_DIR:-/Library/Developer/CommandLineTools}" -build=/tmp/tianshan-runtime-tests +build="$TS_TEST_BUILD_ROOT/ssh" mkdir -p "$build" cc -std=c11 -D_DEFAULT_SOURCE -g -fsanitize=address,undefined -Wno-deprecated-declarations -Itests/runtime/ssh_stubs -Itests/certificate/stubs -Icomponents/ts_security/include -Icomponents/ch405labs_esp_libssh2/libssh2/include tests/runtime/test_ssh.c -lpthread -o "$build/ssh" "$build/ssh" diff --git a/tests/runtime/run_storage_paths.sh b/tests/runtime/run_storage_paths.sh index d17dff5f..e290e9dc 100644 --- a/tests/runtime/run_storage_paths.sh +++ b/tests/runtime/run_storage_paths.sh @@ -1,12 +1,13 @@ #!/bin/bash set -euo pipefail cd "$(dirname "$0")/../.." +source tests/runtime/host_env.sh : "${IDF_PATH:=/Users/massif/esp/v5.5.2/esp-idf}" -: "${STORAGE_PATH_TEST_BUILD:=/tmp/tianshan-storage-path-tests}" +: "${STORAGE_PATH_TEST_BUILD:=$TS_TEST_BUILD_ROOT/storage-paths}" mkdir -p "$STORAGE_PATH_TEST_BUILD" python3 - "$STORAGE_PATH_TEST_BUILD/storage_upload.inc" <<'PYTHON' from pathlib import Path -import sys +import os,sys parts=[] for file,name,signature in ( ('components/ts_net/src/ts_http_server.c','url_decode_inplace','static void '), @@ -14,7 +15,7 @@ for file,name,signature in ( ('components/ts_webui/src/ts_webui_api.c','file_download_handler','static esp_err_t '), ('components/ts_webui/src/ts_webui_api.c','file_upload_handler','static esp_err_t '), ): - source=Path(file).read_text() + source=Path(os.environ.get('STORAGE_UPLOAD_SOURCE',file) if name=='file_upload_handler' else file).read_text() start=source.index(signature+name+'(') parts.append(source[start:source.index('\n}',start)+2]) Path(sys.argv[1]).write_text('\n'.join(parts)) diff --git a/tests/runtime/storage_stubs/esp_random.h b/tests/runtime/storage_stubs/esp_random.h index 205e8f8d..6d91667d 100644 --- a/tests/runtime/storage_stubs/esp_random.h +++ b/tests/runtime/storage_stubs/esp_random.h @@ -1,3 +1,5 @@ #pragma once #include +#include void esp_fill_random(void *buffer, size_t size); +uint32_t esp_random(void); diff --git a/tests/runtime/test_agx_reset.py b/tests/runtime/test_agx_reset.py new file mode 100644 index 00000000..2a7f07c6 --- /dev/null +++ b/tests/runtime/test_agx_reset.py @@ -0,0 +1,192 @@ +"""Actual AGX owner functions: reset completion, shutdown interleaving and power consumers.""" +from pathlib import Path +import argparse +import os +from test_console_lifecycle import body, run_native, IDF + +os.chdir(Path(__file__).resolve().parents[2]) +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--case', choices=['completion', 'interleaved-off', 'errors-notification', 'power', 'lpmu-startup']) +args = parser.parse_args() +driver = 'components/ts_drivers/src/ts_device_ctrl.c' +text = Path(driver).read_text() +code = r''' +#include +#include +#include +#include +#include +#include +#include +#include "esp_err.h" +#include "ts_device_ctrl.h" +#include "cJSON.h" +#define TS_LOGI(...) ((void)0) +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +#define pdMS_TO_TICKS(n) (n) +#define TS_EVENT_BASE_DEVICE_MON 1 +#define TS_EVENT_DEVICE_STATUS_CHANGED 2 +#define GPIO_IS_VALID_OUTPUT_GPIO(pin) ((pin)>=0 && (pin)<49 && ((pin)<22 || (pin)>25)) +typedef void *ts_gpio_handle_t; +typedef pthread_mutex_t portMUX_TYPE; +#define portMUX_INITIALIZER_UNLOCKED PTHREAD_MUTEX_INITIALIZER +#define portENTER_CRITICAL(p) assert(!pthread_mutex_lock(p)) +#define portEXIT_CRITICAL(p) assert(!pthread_mutex_unlock(p)) +static int levels[32],writes,delays[32],delay_count,post_count,shutdown_at_delay; +static uint32_t now_ms; +static bool allocation_fails,post_fails; +static char last_event[256]; +static int64_t esp_timer_get_time(void) {return (int64_t)now_ms*1000;} +static int gpio_set_level(int pin,unsigned level) { + if(!GPIO_IS_VALID_OUTPUT_GPIO(pin)) return ESP_ERR_INVALID_ARG; + assert(pin==1 && writes<32);levels[writes++]=level;return ESP_OK; +} +static int ts_gpio_get_level(ts_gpio_handle_t handle) {(void)handle;return 1;} +static int agx_power_off(void); +static int agx_power_on(void); +static void check_reset_wait(void); +static void vTaskDelay(unsigned ticks) { + assert(delay_count<32);delays[delay_count++]=ticks;now_ms+=ticks; + if(ticks==50 || ticks==1000) check_reset_wait(); + if(shutdown_at_delay==ticks) {shutdown_at_delay=0;assert(agx_power_off()==ESP_OK);} +} +static int ts_event_post(int base,int event,const void *data,size_t length,unsigned timeout) { + assert(base==1 && event==2 && timeout==0 && length<=sizeof(last_event)); + memcpy(last_event,data,length);++post_count;return post_fails?ESP_FAIL:ESP_OK; +} +static cJSON *fixture_object(void) {return allocation_fails?NULL:cJSON_CreateObject();} +#define cJSON_CreateObject fixture_object +''' +system = (IDF / 'components/esp_system/include/esp_system.h').read_text() +code += system[system.index('typedef enum {'):system.index('} esp_reset_reason_t;') + len('} esp_reset_reason_t;')] +code += r''' +static esp_reset_reason_t reset_reason; +static esp_reset_reason_t esp_reset_reason(void) {return reset_reason;} +static int ping_calls,online_at,task_deletes; +static void *s_lpmu_detect_task; +static bool ping_host(const char *ip,int timeout) { + assert(!strcmp(ip,"10.10.99.99") && timeout==1000); + ++ping_calls;return online_at && ping_calls>=online_at; +} +#define LPMU_DEFAULT_IP "10.10.99.99" +static int ts_gpio_set_level(void *pin,int level) { + assert((uintptr_t)pin==46 || (uintptr_t)pin==2); + assert(writes<32);levels[writes++]=level;return ESP_OK; +} +static void vTaskDeleteWithCaps(void *task) {assert(!task);++task_deletes;} +''' +start = text.index('typedef struct {') +code += text[start:text.index('static bool s_initialized', start)] +for name in ['agx_power_on', 'agx_power_off', 'agx_reset', 'ts_device_get_status', 'ts_device_is_powered', 'lpmu_power_toggle', 'lpmu_power_on', 'lpmu_power_off', 'lpmu_reset', 'ts_device_power_on', 'ts_device_power_off', 'ts_device_reset', 'ts_device_state_to_str', 'lpmu_startup_detect_task']: + code += body(driver, name) +code += '\nstatic struct {bool agx_powered,lpmu_powered;} s_pp;\n' +code += body('components/ts_drivers/src/ts_power_policy.c', 'check_device_status') +code += r''' +static void check_reset_wait(void) { + check_device_status();assert(s_pp.agx_powered); + int before=writes;uint32_t boots=s_agx.boot_count; + assert(agx_power_on()==ESP_OK); + assert(writes==before && s_agx.boot_count==boots); +} +''' +code += r''' +static void fixture(void) { + memset(&s_agx,0,sizeof(s_agx));memset(&s_lpmu,0,sizeof(s_lpmu)); + s_agx.configured=true;s_agx.pins.gpio_reset=1;s_agx.state=TS_DEVICE_STATE_ON; + s_agx.power_on_time=500;s_agx.boot_count=7; + s_lpmu.configured=true;s_lpmu.state=TS_DEVICE_STATE_ON; + writes=delay_count=post_count=shutdown_at_delay=0;now_ms=10000; + allocation_fails=post_fails=false;last_event[0]=0; +} +static void completed(void) { + assert(writes==3 && levels[0]==0 && levels[1]==1 && levels[2]==0); + assert(delay_count==2 && delays[0]==50 && delays[1]==1000); + assert(s_agx.state==TS_DEVICE_STATE_ON && s_agx.boot_count==8); + assert(s_agx.power_on_time==11050); + ts_device_status_t status;now_ms+=25; + assert(ts_device_get_status(TS_DEVICE_AGX,&status)==ESP_OK); + assert(status.state==TS_DEVICE_STATE_ON && status.uptime_ms==25 && status.power_good); + assert(ts_device_is_powered(TS_DEVICE_AGX));check_device_status();assert(s_pp.agx_powered); +} + +static void lpmu_fixture(esp_reset_reason_t reason,int online) { + fixture();reset_reason=reason;online_at=online;ping_calls=task_deletes=0; + s_lpmu.state=TS_DEVICE_STATE_OFF;s_lpmu.boot_count=7; + s_lpmu.gpio.power_btn=(void*)46;s_lpmu.gpio.reset=(void*)2; + s_lpmu_detect_task=(void*)1; +} +static void startup_case(esp_reset_reason_t reason,int online,bool pulse) { + lpmu_fixture(reason,online);lpmu_startup_detect_task(NULL); + assert(writes==(pulse?2:0));if(pulse) assert(levels[0]==1 && levels[1]==0); + assert(!s_lpmu_detect_task && task_deletes==1 && post_count==1); + unsigned duration=online==1?5000:online?13000:88000; + assert(now_ms==10000+duration+(pulse?300:0)); + assert(ping_calls==(online?online:19)); + assert(s_lpmu.state==(online?TS_DEVICE_STATE_ON:TS_DEVICE_STATE_OFF)); + assert(s_lpmu.boot_count==(online>1?8:7)); + assert((bool)strstr(last_event,"\"power\":true")==!!online); +} +static void startup_checks(void) { + startup_case(ESP_RST_POWERON,4,true); /* Original cold-on pulse, later discovery. */ + startup_case(ESP_RST_POWERON,1,false); /* Already online: no button. */ + startup_case(ESP_RST_USB,4,false); + startup_case(ESP_RST_SW,4,false); + startup_case(ESP_RST_UNKNOWN,4,false); + startup_case(ESP_RST_USB,0,false); /* All 16 original follow-up probes and timeout. */ + lpmu_fixture(ESP_RST_USB,0); + assert(ts_device_power_on(TS_DEVICE_LPMU)==ESP_OK && writes==2); + assert(ts_device_power_off(TS_DEVICE_LPMU)==ESP_OK && writes==4); + assert(ts_device_reset(TS_DEVICE_LPMU)==ESP_OK && writes==6); + assert(s_lpmu.state==TS_DEVICE_STATE_BOOTING && s_lpmu.boot_count==9); +} + +int main(int argc,char **argv) { + assert(argc==2);const char *name=argv[1];fixture(); + if(!strcmp(name,"lpmu-startup")) { + startup_checks(); + } else if(!strcmp(name,"completion")) { + assert(agx_reset()==ESP_OK);completed();assert(post_count==1); + cJSON *event=cJSON_Parse(last_event);assert(event); + assert(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(event,"device")),"agx")); + assert(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(event,"state")),"on")); + assert(cJSON_IsTrue(cJSON_GetObjectItem(event,"power"))); + assert(cJSON_GetObjectItem(event,"boot_count")->valueint==8);cJSON_Delete(event); + } else if(!strcmp(name,"interleaved-off")) { + /* Actual yield points: a completed shutdown must remain OFF/HIGH. */ + for(int wait=0;wait<2;wait++) { + fixture();shutdown_at_delay=wait?1000:50; + int ret=agx_reset(); + fprintf(stderr,"interleaving delay=%d ret=%d final_state=%d final_level=%d\n",wait?1000:50,ret,s_agx.state,levels[writes-1]); + assert(ret==ESP_ERR_INVALID_STATE); + assert(s_agx.state==TS_DEVICE_STATE_OFF && levels[writes-1]==1); + assert(s_agx.boot_count==7 && s_agx.power_on_time==500); + check_device_status();assert(!s_pp.agx_powered && post_count==1); + assert(strstr(last_event,"off")); + } + } else if(!strcmp(name,"errors-notification")) { + s_agx.pins.gpio_reset=-1;assert(agx_reset()==ESP_ERR_INVALID_STATE); + assert(writes==0 && delay_count==0 && post_count==0 && s_agx.boot_count==7); + fixture();s_agx.pins.gpio_reset=99;assert(agx_reset()==ESP_ERR_INVALID_ARG); + assert(writes==0 && delay_count==0 && post_count==0 && s_agx.state==TS_DEVICE_STATE_ON); + fixture();allocation_fails=true;assert(agx_reset()==ESP_OK);completed();assert(post_count==0); + fixture();post_fails=true;assert(agx_reset()==ESP_OK);completed();assert(post_count==1); + } else { + assert(!strcmp(name,"power"));assert(agx_power_off()==ESP_OK); + assert(s_agx.state==TS_DEVICE_STATE_OFF && writes==1 && levels[0]==1); + check_device_status();assert(!s_pp.agx_powered); + assert(agx_power_on()==ESP_OK);assert(s_agx.state==TS_DEVICE_STATE_ON); + assert(writes==2 && levels[1]==0 && s_agx.boot_count==8); + check_device_status();assert(s_pp.agx_powered && s_pp.lpmu_powered); + assert(agx_power_on()==ESP_OK && writes==2 && s_agx.boot_count==8); + } + printf("PASS device production functions: %s\n",name);return 0; +} +''' +cases = [args.case] if args.case else ['completion', 'interleaved-off', 'errors-notification', 'power', 'lpmu-startup'] +probe = code.replace('int main(int argc,char **argv)', 'static int probe(int argc,char **argv)') +probe += '\nint main(void) {\n' +for index, case in enumerate(cases): + probe += 'char *args' + str(index) + '[]={"test","' + case + '"};probe(2,args' + str(index) + ');\n' +probe += 'return 0;}\n' +run_native(probe, extra_sources=[IDF / 'components/json/cJSON/cJSON.c']) diff --git a/tests/runtime/test_api_access.py b/tests/runtime/test_api_access.py new file mode 100644 index 00000000..41b58f0c --- /dev/null +++ b/tests/runtime/test_api_access.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Actual registry policy lookup: scalar snapshots, no JSON allocation, concurrent updates.""" +from pathlib import Path +import os,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +fixture=ROOT/'tests/runtime/test_cert_admission.py';text=fixture.read_text();ns={'__name__':'access_fixture','__file__':str(fixture)} +exec(compile(text[:text.index('\nwith tempfile.TemporaryDirectory')],str(fixture),'exec'),ns) +code=ns['code'];code=code[:code.index('int main(void)')] +code+=r''' +#include +static unsigned json_attempts; +static void *blocked_json(size_t size){(void)size;json_attempts++;return NULL;} +static atomic_uint race_errors; +static void *writer(void *unused){ + (void)unused;ts_api_endpoint_t ep={.name="fixture.racy",.handler=mutation,.requires_auth=true,.permission="cert.manage",.external_access=TS_API_ACCESS_ROOT,.allowed_methods=TS_API_METHOD_WRITE}; + for(unsigned n=0;n<5000;n++){if(ts_api_register(&ep)!=ESP_OK||ts_api_unregister(ep.name)!=ESP_OK)atomic_fetch_add(&race_errors,1);}return NULL; +} +static void *reader(void *unused){ + (void)unused;for(unsigned n=0;n<5000;n++){ + ts_api_access_t access={0};esp_err_t ret=ts_api_get_access("fixture.racy",&access); + if(ret!=ESP_ERR_NOT_FOUND&&(ret!=ESP_OK||!access.requires_auth||access.minimum_level!=TS_PERM_ROOT))atomic_fetch_add(&race_errors,1); + }return NULL; +} +int main(void){ + ts_api_access_t access={0};check(ts_api_get_access("cert.install",&access)==ESP_ERR_INVALID_STATE,"uninitialized registry cannot provide a policy"); + check(ts_api_init()==ESP_OK&&ts_api_cert_register()==ESP_OK,"real registry and certificate operations register"); + struct {const char *name;bool auth;unsigned level;const char *permission;ts_api_external_access_t role;uint8_t methods;} rows[]={ + {"fixture.public",false,TS_PERM_NONE,NULL,TS_API_ACCESS_PUBLIC,TS_API_METHOD_READ},{"fixture.read",true,TS_PERM_READ,NULL,TS_API_ACCESS_READ,TS_API_METHOD_READ}, + {"ui.widgets.set",true,TS_PERM_ADMIN,NULL,TS_API_ACCESS_ADMIN,TS_API_METHOD_WRITE},{"automation.rules.add",true,TS_PERM_ROOT,NULL,TS_API_ACCESS_ROOT,TS_API_METHOD_WRITE}, + {"automation.actions.execute",true,TS_PERM_ADMIN,NULL,TS_API_ACCESS_ADMIN,TS_API_METHOD_WRITE},{"automation.services.stop",true,TS_PERM_ADMIN,NULL,TS_API_ACCESS_ADMIN,TS_API_METHOD_WRITE}, + {"fixture.capability",false,TS_PERM_ROOT,"cert.manage",TS_API_ACCESS_ROOT,TS_API_METHOD_WRITE} + }; + for(unsigned i=0;i0)&&access.minimum_level==rows[n].level&&access.allowed_methods==rows[n].methods,"explicit roles/methods remain authoritative without prefix or compatibility flag inference"); + } + check(ts_api_get_access(NULL,&access)==ESP_ERR_INVALID_ARG&&ts_api_get_access("cert.status",NULL)==ESP_ERR_INVALID_ARG,"invalid lookup arguments rejected"); + check(ts_api_get_access("missing",&access)==ESP_ERR_NOT_FOUND,"unknown policy explicitly unavailable"); + check(json_attempts==0,"all successful and failing lookups perform zero JSON allocations");cJSON_InitHooks(NULL); + pthread_t a,b;check(!pthread_create(&a,NULL,writer,NULL)&&!pthread_create(&b,NULL,reader,NULL),"parallel registry/query workers start"); + pthread_join(a,NULL);pthread_join(b,NULL);check(atomic_load(&race_errors)==0,"concurrent register/unregister never yields a partial or stale permission snapshot"); + check(ts_api_unregister("fixture.capability")==ESP_OK&&ts_api_get_access("fixture.capability",&access)==ESP_ERR_NOT_FOUND,"unregistered policy immediately unavailable"); + check(ts_api_deinit()==ESP_OK,"real registry deinitializes"); + check(ts_api_get_access("cert.status",&access)==ESP_ERR_INVALID_STATE,"deinitialized registry rejects policy lookup"); + printf("%u checks, %u failures: real registry policy, zero JSON allocations, 5000 writer/reader iterations\n",checks,failures);return failures?1:0; +} +''' +with tempfile.TemporaryDirectory(prefix='ts-api-access-') as tmp: + c=Path(tmp,'test.c');binary=Path(tmp,'test');c.write_text(code) + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize=address,undefined','-fno-sanitize-recover=all',*['-I'+str(p) for p in ns['includes']],str(c),str(ns['IDF']/'components/json/cJSON/cJSON.c'),'-lpthread','-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True,timeout=30) diff --git a/tests/runtime/test_api_context.py b/tests/runtime/test_api_context.py new file mode 100644 index 00000000..1a2a7963 --- /dev/null +++ b/tests/runtime/test_api_context.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Actual registry and SSH descriptors prove verified C context dispatch, including concurrency.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,sys,re,subprocess,tempfile,importlib.util +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT)),text=True) + return (ROOT/path).read_text() +f=ROOT/'tests/runtime/test_cert_admission.py';text=f.read_text();ns={'__file__':str(f),'__name__':'context_fixture'} +a=text.index('api=source(');b=text.index('\nwith tempfile.TemporaryDirectory');argv=sys.argv;sys.argv=[sys.argv[0]] +try:exec(compile(text[:a],str(f),'exec'),ns) +finally:sys.argv=argv +ns['source']=source;exec(compile(text[a:b],str(f),'exec'),ns);code=ns['code'];code=code[:code.index('int main(void)')] +code=code.replace('esp_err_t ts_security_validate_session(', 'static bool context_session_live=true;\nesp_err_t ts_security_validate_session(',1).replace('if(sid<1||sid>4)','if(!context_session_live || sid<1 || (sid>4 && sid!=8))',1).replace('out->level=(ts_perm_level_t)sid','out->level=sid==8?TS_PERM_ROOT:(ts_perm_level_t)sid',1) +code+=r""" +#include +#include +static atomic_uint context_calls,legacy_calls,context_mismatch; +static esp_err_t legacy_handler(const cJSON *p,ts_api_result_t *r){(void)p;atomic_fetch_add(&legacy_calls,1);ts_api_result_ok(r,NULL);return ESP_OK;} +static esp_err_t context_handler(const cJSON *p,uint32_t sid,ts_api_result_t *r){ + const cJSON *expected=cJSON_GetObjectItemCaseSensitive(p,"expected"); + if(!cJSON_IsNumber(expected)||expected->valuedouble!=sid)atomic_fetch_add(&context_mismatch,1); + atomic_fetch_add(&context_calls,1);ts_api_result_ok(r,NULL);return ESP_OK; +} +""" +sp=importlib.util.spec_from_file_location('h',ROOT/'audit/api-security-20261103/tools/extract_inventory.py');h=importlib.util.module_from_spec(sp);sp.loader.exec_module(h) +s=source('components/ts_api/src/ts_api_ssh.c');m=re.search(r'static const ts_api_endpoint_t ssh_endpoints\[\]\s*=\s*\{',s);assert m +part=s[m.start():h.endbrace(h.masked(s),s.index('{',m.start()))+1] +for handler in set(re.findall(r'\.handler\s*=\s*(\w+)',part)):code+='#define '+handler+' legacy_handler\n' +for handler in set(re.findall(r'\.session_handler\s*=\s*(\w+)',part)):code+='#define '+handler+' context_handler\n' +code+=part+'\n' +code+=r""" +static const char *names[]={"ssh.exec_stream","ssh.exec_status","ssh.cancel"}; +static void *parallel(void *arg){ + uint32_t sid=(uint32_t)(uintptr_t)arg;cJSON *p=cJSON_CreateObject();cJSON_AddNumberToObject(p,"expected",sid);cJSON_AddNumberToObject(p,"owner_session_id",99); + for(unsigned i=0;i<1000;i++){ts_api_result_t r={0};assert(ts_api_call_for_session(names[0],p,sid,&r)==ESP_OK);ts_api_result_free(&r);}cJSON_Delete(p);return NULL; +} +int main(void){ + check(ts_api_init()==ESP_OK,"registry initializes");check(ts_api_register_multiple(ssh_endpoints,sizeof(ssh_endpoints)/sizeof(*ssh_endpoints))==ESP_OK,"real SSH descriptor table registers"); + const unsigned ids[]={0,1,2,3,4,5,8,99}; + cJSON *p=cJSON_Parse("{\"session_id\":99,\"caller_session_id\":99,\"owner_session_id\":99,\"role\":\"root\",\"expected\":4}"); + for(unsigned n=0;n<3;n++){ + ts_api_access_t access={0};check(ts_api_get_access(names[n],&access)==ESP_OK&&access.minimum_level==TS_PERM_ROOT&&access.requires_auth,"three private endpoints explicitly Root"); + check(access.allowed_methods==(n==1?TS_API_METHOD_READ:TS_API_METHOD_WRITE),"private method contract"); + for(unsigned i=0;i +#include +#include +#include +#include +#include +#include +#include "ts_api.h" +#define TAG "bounded_api_log_test" +#define TS_STRDUP_PSRAM strdup +static unsigned checks,failures,executions; +static const char *secret="SYNTHETIC_PRIVATE_API_OUTPUT_AND_BEARER"; +static char diagnostics[16384]; +static void capture(const char *tag,const char *format,...){(void)tag;size_t n=strlen(diagnostics);va_list ap;va_start(ap,format);vsnprintf(diagnostics+n,sizeof(diagnostics)-n,format,ap);va_end(ap);} +#define TS_LOGI capture +#define TS_LOGD capture +#define TS_LOGW capture +#define TS_LOGE capture +#define ESP_LOGI capture +#define ESP_LOGW capture +#define ESP_LOGD capture +#define ESP_LOGE capture +static void check(bool value,const char *why){++checks;if(!value){++failures;fprintf(stderr,"FAIL %s\n",why);}} +static const char *esp_err_to_name(esp_err_t code){(void)code;return "synthetic_error";} +"""+header[status_start:status_end]+'\n'+header[result_start:result_end]+'\n' +code+=r""" +static ts_action_status_t returned_status; +static esp_err_t returned_rc; +static bool returned_reason; +esp_err_t ts_action_template_execute_versioned(const char *id,const char *version,ts_action_result_t *out,const char **reason){ + assert(!strcmp(id,"fixture")&&!strcmp(version,"11111111111111111111111111111111"));*reason=NULL;++executions;out->status=returned_status;out->duration_ms=42;snprintf(out->output,sizeof(out->output),"%s",secret);out->reason=returned_reason?"synthetic_failure":NULL;return returned_rc; +} +""" +for name in ['ts_api_result_init','ts_api_result_ok','ts_api_result_error','ts_api_result_reason','ts_api_result_free']:code+=function(api,name) +for name in ['action_execute_failure','api_automation_actions_execute']:code+=function(auto,name) +# Execute the exact diagnostic statements with bounded sensitive inputs. This +# is a sink-format test, not a claim to run WS/Socket.IO transport handlers. +action_manager='components/ts_automation/src/ts_action_manager.c';ssh_api='components/ts_api/src/ts_api_ssh.c';ws_worker='components/ts_webui/src/ts_webui_ws.c' +selectors=[('local',auto,['Local API call detected','Local API dispatch requested']),('fetch',auto,['Proxy fetch']),('ws_uri',auto,['WS test: uri=','WS test timeout=']),('sio_payload',auto,['Socket.IO recv [','Socket.IO received ']),('sio_test',auto,['Socket.IO test:','Socket.IO test timeout=']),('sio_poll',auto,['Socket.IO polling response']),('sio_sid',auto,['Socket.IO session:','Socket.IO session established']),('sio_ws_uri',auto,['Socket.IO WS URL:','Socket.IO WS connection prepared']),('sio_event',auto,['Socket.IO received event:','Socket.IO event received']),('sio_type',auto,['Socket.IO unknown message type']),('http_error',http,['API call result:']),('action_key',action_manager,['Loaded SSH key']),('ssh_key',ssh_api,['Failed to load key','Failed to load SSH key']),('worker_key',ws_worker,['Failed to load key','Failed to load SSH key'])] +code+=r""" +static void diagnostic_sinks(void){ + const char *keyid=secret;size_t key_len=128;struct {const char *keyid;} key_params={secret},*params=&key_params; + const char *api_name=secret,*url=secret,*uri=secret,*base_url=secret,*target_event=secret,*ws_url=secret,*poll_response=secret,*buf=secret,*method_str="POST";int timeout_ms=15000;char type='@'; + struct {int data_len;} incoming={.data_len=128},*data=&incoming; + struct {const char *sid,*event_name;} ctx={.sid=secret,.event_name=secret}; + struct {struct {size_t length;} sample;} sample_value={.sample={128}},*sample_ctx=&sample_value; + ts_api_result_t result={.code=TS_API_ERR_INTERNAL,.message=(char *)secret};esp_err_t ret=ESP_FAIL; +""" +for label,path,prefixes in selectors: + t=source(path);matches=[] + for m in re.finditer(r'(?:TS|ESP)_LOG[IWDE]\(TAG,\s*"([^"\n]+)"',t): + if any(m[1].startswith(prefix) for prefix in prefixes):matches.append(t[m.start():t.index(';',m.start())+1]) + if not matches: + # Shared HTTP receive code emits no protocol diagnostics at all. + assert label in {'fetch','sio_poll','sio_sid'},label + continue + statement=matches[0].replace("ctx->sample.length","sample_ctx->sample.length").replace("keyid->valuestring","keyid") # Actual sink, synthetic pointer owner. + # The general HTTP operation name is a known route identifier, not payload. + pre='api_name="automation.actions.execute";' if label=='http_error' else 'api_name=secret;' + code+='diagnostics[0]=0;'+pre+'\n'+statement+'\ncheck(!strstr(diagnostics,secret),"'+label+' contains no private input");\n' + if label=='sio_type':code+='check(!strchr(diagnostics,\'@\'),"unknown frame byte is not emitted");\n' +code+=r""" +} +int main(void){ + cJSON *params=cJSON_Parse("{\"id\":\"fixture\",\"active_version\":\"11111111111111111111111111111111\"}"); + const ts_action_status_t statuses[]={TS_ACTION_STATUS_SUCCESS,TS_ACTION_STATUS_FAILED,TS_ACTION_STATUS_TIMEOUT,TS_ACTION_STATUS_CANCELLED,TS_ACTION_STATUS_QUEUED}; + for(unsigned i=0;i<5;i++)for(unsigned why=0;why<2;why++){ + returned_status=statuses[i];returned_rc=(returned_status==TS_ACTION_STATUS_SUCCESS||returned_status==TS_ACTION_STATUS_QUEUED)?ESP_OK:ESP_FAIL;returned_reason=why!=0;diagnostics[0]=0;ts_api_result_t r={0};unsigned before=executions; + check(api_automation_actions_execute(params,&r)==ESP_OK&&executions==before+1,"actual action API invokes saved/versioned executor exactly once"); + check(!strstr(diagnostics,secret),"private action output never enters global diagnostics"); + if(returned_status==TS_ACTION_STATUS_QUEUED)check(r.code==TS_API_OK&&cJSON_IsTrue(cJSON_GetObjectItem(r.data,"async")),"queued status contract unchanged"); + else {const char *out=cJSON_GetStringValue(cJSON_GetObjectItem(r.data,"output"));check(out&&!strcmp(out,secret),"exact result output remains available to the invoking caller");} + if(returned_status==TS_ACTION_STATUS_SUCCESS)check(cJSON_GetObjectItem(r.data,"duration_ms")->valueint==42,"successful duration unchanged"); + ts_api_result_free(&r); + } + cJSON_Delete(params);diagnostic_sinks();printf("%u checks, %u failures: actual action API preserves caller results; bounded private-output/URL/handshake/error diagnostic sink tests, no device/network\n",checks,failures);return failures?1:0; +} +""" +with tempfile.TemporaryDirectory(prefix='ts-api-log-privacy-') as tmp: + c=Path(tmp)/'test.c';exe=Path(tmp)/'test';c.write_text(code) + inc=[ROOT/'tests/runtime/storage_stubs',ROOT/'components/ts_api/include',IDF/'components/json/cJSON'] + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize=address,undefined','-fno-sanitize-recover=all',*['-I'+str(p) for p in inc],str(c),str(IDF/'components/json/cJSON/cJSON.c'),'-o',str(exe)],check=True,cwd=ROOT) + subprocess.run([str(exe)],check=True,cwd=ROOT) diff --git a/tests/runtime/test_api_numeric_security.py b/tests/runtime/test_api_numeric_security.py new file mode 100644 index 00000000..4523967a --- /dev/null +++ b/tests/runtime/test_api_numeric_security.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Actual API handlers, SDK cJSON, synthetic hardware/storage/clock boundaries.""" +from pathlib import Path +import argparse, os, re, subprocess, tempfile + +ROOT = Path(__file__).resolve().parents[2] +parser = argparse.ArgumentParser() +parser.add_argument("--source-ref", help="Read production functions from a git revision for before/after evidence") +args = parser.parse_args() +IDF = Path(os.environ.get("IDF_PATH", "/Users/massif/esp/v5.5.2/esp-idf")) +def body(path, name, optional=False): + source = subprocess.check_output(["git", "show", f"{args.source_ref}:{path}"], cwd=ROOT, text=True) if args.source_ref else (ROOT/path).read_text() + m = re.search(r"^(?:static )?[^\n;]+\b"+name+r"\([^;]+?\)\s*\{",source,re.M) + if not m and optional:return "" + assert m,name + return source[m.start():source.index("\n}",m.start())+2]+"\n" + +code=r''' +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include "ts_api.h" +#include "ts_security.h" +#include "ts_variable.h" +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 +#include "ts_fan.h" +#include "ts_led.h" +#include "ts_temp_source.h" +#include "ts_time_sync.h" +#include "ts_config_pack.h" +#include "ts_storage.h" +#define TS_LOGI(...) ((void)0) +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +#define ESP_LOGI(...) ((void)0) +#define TS_CONFIG_MODULE_FAN 5 +#define ESP_ERR_NOT_ALLOWED 0x10d +#define TS_STRDUP_PSRAM strdup +static unsigned mutations, saves, pack_creates, security_sets; +static bool get_fail, alloc_fail; +static unsigned min_seen,max_seen,brightness_seen; +static int64_t integer_seen,time_seen; +static double double_seen; +static int16_t temp_seen; +static ts_fan_config_t config={.min_duty=20,.max_duty=100,.hysteresis=30,.min_interval=2000}; +esp_err_t ts_fan_get_config(ts_fan_id_t id,ts_fan_config_t *out) {(void)id;if(get_fail)return ESP_FAIL;*out=config;return ESP_OK;} +esp_err_t ts_fan_set_limits(ts_fan_id_t id,uint8_t min,uint8_t max){(void)id;mutations++;min_seen=min;max_seen=max;return ESP_OK;} +esp_err_t ts_fan_set_curve(ts_fan_id_t id,const ts_fan_curve_point_t *c,uint8_t n){(void)id;(void)c;(void)n;mutations++;return ESP_OK;} +esp_err_t ts_fan_set_hysteresis(ts_fan_id_t id,int16_t h,uint32_t t){(void)id;assert(h>=0&&h<=200&&t>=100&&t<=60000);mutations++;return ESP_OK;} +esp_err_t ts_fan_save_full_config(ts_fan_id_t id){(void)id;saves++;return ESP_OK;} +static bool ts_config_module_is_registered(int m){(void)m;return true;} +static int ts_config_module_persist(int m){(void)m;saves++;return ESP_OK;} +static const char *resolve_device_name(const char *n){return n;} +ts_led_device_t ts_led_device_get(const char *n){(void)n;return (ts_led_device_t)1;} +esp_err_t ts_led_device_set_brightness(ts_led_device_t d,uint8_t n){(void)d;mutations++;brightness_seen=n;return ESP_OK;} +uint8_t ts_led_device_get_brightness(ts_led_device_t d){(void)d;return brightness_seen;} +esp_err_t ts_temp_set_manual(int16_t n){mutations++;temp_seen=n;return ESP_OK;} +esp_err_t ts_temp_set_manual_mode(bool n){(void)n;mutations++;return ESP_OK;} +bool ts_temp_is_manual_mode(void){return true;} +int16_t ts_temp_get_effective(ts_temp_data_t *d){memset(d,0,sizeof(*d));return 0;} +const char *ts_temp_source_type_to_str(ts_temp_source_type_t s){(void)s;return "manual";} +esp_err_t ts_time_sync_set_time(int64_t n,ts_time_source_t s){(void)s;mutations++;time_seen=n;return ESP_OK;} +static int ts_config_set_bool(const char *k,bool n){(void)k;(void)n;mutations++;return ESP_OK;} +static int ts_config_set_int64(const char *k,int64_t n){(void)k;mutations++;integer_seen=n;return ESP_OK;} +static int ts_config_set_double(const char *k,double n){(void)k;mutations++;double_seen=n;return ESP_OK;} +static int ts_config_set_string(const char *k,const char *n){(void)k;(void)n;mutations++;return ESP_OK;} +bool ts_config_pack_can_export(void){return true;} +ts_config_pack_result_t ts_config_pack_create(const char *n,const char *j,size_t len,const ts_config_pack_export_opts_t *o,char **out,size_t *size){ + (void)n;(void)o;assert(len==strlen(j));pack_creates++;*out=strdup("{}");*size=2;return TS_CONFIG_PACK_OK; +} +static void pack_failure(ts_api_result_t *r,ts_config_pack_result_t e){(void)e;ts_api_result_error(r,TS_API_ERR_INTERNAL,"fixture");} +esp_err_t ts_storage_check_write_path(const char *p,bool b){(void)p;(void)b;assert(false);return ESP_FAIL;} +esp_err_t ts_storage_check_external_write_path(const char *p,bool b){return ts_storage_check_write_path(p,b);} +esp_err_t ts_storage_mkdir_p(const char *p){(void)p;assert(false);return ESP_FAIL;} +esp_err_t ts_storage_write_file(const char *p,const void *d,size_t n){(void)p;(void)d;(void)n;assert(false);return ESP_FAIL;} +esp_err_t ts_config_pack_save(const char *p,const char *d,size_t n){(void)p;(void)d;(void)n;assert(false);return ESP_FAIL;} +static char *export_strdup(const char *s){return alloc_fail?NULL:strdup(s);} +static char *export_print(const cJSON *j){return alloc_fail?NULL:cJSON_PrintUnformatted(j);} +''' + +code+=r''' +static ts_temp_bound_var_t shared_bindings[TS_TEMP_MAX_BOUND_VARS]; +static uint8_t shared_binding_count; +static unsigned variable_reads; +static bool caller_live=true; +esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *session){ + if(!caller_live||sid<1||sid>5)return ESP_ERR_NOT_FOUND; + session->level=sid==1?TS_PERM_ROOT:sid==2?TS_PERM_ADMIN:sid==3?TS_PERM_READ:sid==4?TS_PERM_NONE:TS_PERM_WRITE;return ESP_OK; +} +static int64_t esp_timer_get_time(void){return 3000000;} +esp_err_t ts_temp_bind_variables(const ts_temp_bound_var_t *vars,uint8_t count){assert(count<=TS_TEMP_MAX_BOUND_VARS);++mutations;memcpy(shared_bindings,vars,count*sizeof(*vars));shared_binding_count=count;return ESP_OK;} +esp_err_t ts_temp_bind_variable(const char *name){ts_temp_bound_var_t value={.weight=1};snprintf(value.name,sizeof value.name,"%s",name);return ts_temp_bind_variables(&value,1);} +esp_err_t ts_temp_unbind_variable(void){++mutations;shared_binding_count=0;return ESP_OK;} +esp_err_t ts_temp_get_bound_variables(ts_temp_bound_var_t *vars,uint8_t *count){memcpy(vars,shared_bindings,shared_binding_count*sizeof(*vars));*count=shared_binding_count;return ESP_OK;} +esp_err_t ts_temp_get_bound_variable(char *name,size_t capacity){if(!shared_binding_count)return ESP_ERR_NOT_FOUND;snprintf(name,capacity,"%s",shared_bindings[0].name);return ESP_OK;} +esp_err_t ts_variable_get_info(const char *name,ts_variable_info_t *info){++variable_reads;memset(info,0,sizeof *info);snprintf(info->name,sizeof info->name,"%s",name);info->value.type=TS_AUTO_VAL_FLOAT;info->value.float_val=45;info->last_update_ms=2900;return ESP_OK;} +esp_err_t ts_temp_get_status(ts_temp_status_t *status){memset(status,0,sizeof *status);status->current_temp=450;status->current_valid=true;status->active_source=TS_TEMP_SOURCE_VARIABLE;return ESP_OK;} +''' +for f in ["ts_api_result_ok","ts_api_result_error","ts_api_result_free"]: + code+=body("components/ts_api/src/ts_api.c",f) +for file,names in [ + ("ts_api_fan.c",["api_fan_limits","api_fan_curve"]), + ("ts_api_led.c",["api_led_brightness"]), + ("ts_api_temp.c",["api_temp_manual"]), + ("ts_api_time.c",["api_time_sync"]), + ("ts_api_config.c",["api_config_set"])]: + for name in names: code+=body("components/ts_api/src/"+file,name) +code+=body("components/ts_api/src/ts_api_temp.c","variable_info_to_float") +code+=body("components/ts_api/src/ts_api_temp.c","api_temp_bind") +binding_session=body("components/ts_api/src/ts_api_temp.c","api_temp_bind_for_session",optional=True) +code+=binding_session +code+="#define strdup export_strdup\n#define cJSON_PrintUnformatted export_print\n" +code+=body("components/ts_api/src/ts_api_config_pack.c","api_config_pack_export") +code+="#undef strdup\n#undef cJSON_PrintUnformatted\n" +code+=r''' +static void binding_policy_checks(void); +static unsigned failures,checks; +static void check(bool value,const char *what){checks++;if(!value){failures++;fprintf(stderr,"FAIL %s\n",what);}} +typedef esp_err_t (*handler)(const cJSON *,ts_api_result_t *); +static void request(handler h,cJSON *p,bool valid,const char *label){ + unsigned before=mutations;ts_api_result_t result={0};int ret=h(p,&result); + check(valid?ret==ESP_OK:ret!=ESP_OK,label); + if(!valid)check(mutations==before,"rejected request has no hardware/clock/config mutations"); + ts_api_result_free(&result);cJSON_Delete(p); +} +static void json(handler h,const char *text,bool valid){request(h,cJSON_Parse(text),valid,text);} +/* Set nonfinite doubles directly: SDK CreateNumber itself casts NaN to int. */ +static cJSON *number(const char *base,const char *key,double n){cJSON *p=cJSON_Parse(base),*v=cJSON_CreateNumber(isfinite(n)?n:0);v->valuedouble=n;cJSON_AddItemToObject(p,key,v);return p;} +int main(void){ + binding_policy_checks(); + double bad[]={-256,256,300,1e30,NAN,INFINITY,-INFINITY,1.5}; + for(unsigned i=0;ivaluedouble==45,"current approved temperature, weights and freshness unchanged"); + check(mutations==before,"query never mutates binding");ts_api_result_free(&result); + } + cJSON *params=cJSON_Parse("{\"variables\":[{\"name\":\"new.approved.temperature\",\"weight\":1}]}");ts_api_result_t result={0}; + check(api_temp_bind_for_session(params,1,&result)==ESP_OK&&!strcmp(shared_bindings[0].name,"new.approved.temperature"),"Root may deliberately select the shared temperature source");ts_api_result_free(&result); + caller_live=false;unsigned before=mutations;check(api_temp_bind_for_session(params,1,&result)!=ESP_OK&&mutations==before,"revoked Root denied before hardware binding");caller_live=true;ts_api_result_free(&result);cJSON_Delete(params); + params=cJSON_Parse("{\"variable\":null}");check(api_temp_bind_for_session(params,1,&result)==ESP_OK&&!shared_binding_count,"Root unbind retained");ts_api_result_free(&result);cJSON_Delete(params); + params=cJSON_Parse("{\"variable\":\"uart.temperature\"}");check(api_temp_bind(params,&result)==ESP_OK&&!strcmp(shared_bindings[0].name,"uart.temperature"),"trusted internal C/UART binding retains its explicit capability");ts_api_result_free(&result);cJSON_Delete(params); +} +''' +else: + code+='static void binding_policy_checks(void){}\\n' +includes=[ROOT/"tests/runtime/rule_pack/stubs"] +includes += [ROOT/("components/"+x+"/include") for x in ["ts_api","ts_drivers","ts_led","ts_net","ts_config_pack","ts_storage","ts_security","ts_automation","ts_core/ts_config"]] +includes += [IDF/"components/json/cJSON"] +with tempfile.TemporaryDirectory(prefix="ts-api-numeric-") as tmp: + c=Path(tmp)/"probe.c";exe=Path(tmp)/"probe";c.write_text(code) + subprocess.run(["cc","-std=gnu11","-g","-fsanitize=address,undefined,float-cast-overflow", + "-fno-sanitize-recover=all","-Wno-deprecated-declarations",*["-I"+str(p) for p in includes],str(c), + str(IDF/"components/json/cJSON/cJSON.c"),"-lm","-o",str(exe)],check=True) + subprocess.run([str(exe)],check=True) diff --git a/tests/runtime/test_api_prebody.py b/tests/runtime/test_api_prebody.py new file mode 100644 index 00000000..478f1337 --- /dev/null +++ b/tests/runtime/test_api_prebody.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Actual route registration, HTTP/HTTPS wrappers and generic API admission. + +Policy values come from real declarations via the existing HTTP fixture adapter; +header/session/SDK I/O and business effects are synthetic. Full real registry, +body-token handlers and browser flows are separate regression suites. +""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',ROOT),text=True) + return (ROOT/path).read_text() +def function(text,name): + m=re.search(r'^(?:static )?[^\n;]+\b'+name+r'\([^;]+?\)\s*\{',text,re.M);assert m,name + return text[m.start():text.index('\n}',m.start())+2]+'\n' +fixture=ROOT/'tests/runtime/test_sensitive_auth.py';text=fixture.read_text();ns={'__name__':'prebody_fixture','__file__':str(fixture)} +exec(compile(text[:text.index('\nidf = Path(')],str(fixture),'exec'),ns) +code=ns['code'];code=code[:code.index('int main(void) {')] +# The real auth owner is separately tested; inject role change at receive here. +code=code.replace('static bool session_live = true;', 'static bool session_live = true;static bool downgrade_after_read,root_downgraded;') +code=code.replace('*session=1;*level=TS_PERM_ROOT;', '*session=1;*level=root_downgraded?TS_PERM_READ:TS_PERM_ROOT;') + +web=source('components/ts_webui/src/ts_webui_api.c') +if args.source_package: + for name in ('check_auth','api_request_access','api_admit','api_handler'): + current=ns['extract'](name) + replacement=function(web,name) if re.search(r'\b'+name+r'\([^;]*?\)\s*\{',web) else '' + code=code.replace(current,replacement,1) +with tempfile.TemporaryDirectory(prefix='ts-prebody-sdk-') as sdk_dir: + namespace={'__name__':'prebody_sdk_generator'} + exec(compile(source('tools/prepare_httpd_admission.py'),'prepare.py','exec'),namespace) + namespace['prepare'](Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf')),Path(sdk_dir)) + sdk=(Path(sdk_dir)/'httpd_txrx.c').read_text() + budget=re.search(r'/\* TS_RX_BUDGET_BEGIN[\s\S]*?/\* TS_RX_BUDGET_END \*/',sdk) + stub='static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;}' + if budget: + code=code.replace(stub,'static uint32_t esp_log_timestamp(void){return 0;}\n'+budget.group()+'\nstatic uint32_t selected_body_budget(void){return s_receive_budget;}\n') + else: + code=code.replace(stub,stub+'\nstatic void ts_httpd_receive_begin(void){}\nstatic void ts_httpd_receive_end(void){}\nstatic uint32_t selected_body_budget(void){return 0;}\n') +code=code.replace('typedef struct { int content_len;const char *query; } httpd_req_t;', + 'typedef struct{size_t content_len;const char *query,*uri,*auth;int method;void *user_ctx;} httpd_req_t;') +code=code.replace('.body=body,.body_len=body?strlen(body):0', '.body=(char*)body,.body_len=body?strlen(body):0') +code=code.replace('int method; const char *body; size_t body_len;', 'int method; char *body; size_t body_len;') +code=code.replace('(void)key;if (!r->auth) return ESP_ERR_NOT_FOUND;snprintf(out,n,"Bearer %s",r->auth);', + '(void)key;const char *auth=r->auth?r->auth:r->req?r->req->auth:NULL;if (!auth) return ESP_ERR_NOT_FOUND;snprintf(out,n,"Bearer %s",auth);') +header=(ROOT/'components/ts_net/include/ts_http_server.h').read_text();start=header.index('typedef esp_err_t (*ts_http_handler_t)');end=header.index('} ts_http_route_t;',start)+len('} ts_http_route_t;');code+='typedef int ts_http_method_t;\n'+header[start:end]+'\n' +code+=r''' +#define HTTP_GET TS_HTTP_GET +#define HTTP_OPTIONS 6 +#define HTTPD_500_INTERNAL_SERVER_ERROR 500 +#define HTTPD_SOCK_ERR_TIMEOUT -7 +static bool s_stopping,body_oom,revoke_after_read; +static unsigned receives,body_allocations,checks,failures; +static size_t body_position;static const char *body_wire;static size_t body_wire_len; +static void check(bool ok,const char *label){++checks;if(!ok){++failures;fprintf(stderr,"FAIL %s\n",label);}} +static int httpd_resp_set_status(httpd_req_t *r,const char *v){(void)r;status=atoi(v);return ESP_OK;} +static int httpd_resp_sendstr(httpd_req_t *r,const char *v){(void)r;(void)v;return ESP_OK;} +static int httpd_resp_send_err(httpd_req_t *r,int value,const char *v){(void)r;(void)v;status=value;return ESP_OK;} +static void *body_allocate(size_t n){++body_allocations;return body_oom||n>2U*1024U*1024U?NULL:malloc(n);} +#define TS_MALLOC_PSRAM body_allocate +static int httpd_req_recv(httpd_req_t *r,char *out,size_t n){ + (void)r;++receives;assert(body_position+n<=body_wire_len);if(n>1024)n=1024;if(body_wire)memcpy(out,body_wire+body_position,n);else memset(out,' ',n);body_position+=n;if(revoke_after_read)session_live=false;if(downgrade_after_read)root_downgraded=true;return (int)n; +} +''' +http=source('components/ts_net/src/ts_http_server.c');https=source('components/ts_net/src/ts_https_server.c') +for name in ('ts_http_authorize_route','ts_http_admit_body','ts_http_receive_body','http_handler_wrapper'): + if name+'(' in http:code+=function(http,name) +code+=function(https,'https_handler_wrapper') +code+=r''' +static ts_http_route_t registered[12];static unsigned registered_count; +static esp_err_t ts_http_server_register_route(const ts_http_route_t *r){assert(registered_count<12);registered[registered_count++]=*r;return ESP_OK;} +''' +for name in ('login_handler','logout_handler','options_handler','file_upload_handler','ota_firmware_upload_handler','ota_www_upload_handler'): + code+='static esp_err_t '+name+'(ts_http_request_t *r,void *u){(void)u;calls++;assert(r->body_len==r->req->content_len);if(body_wire&&r->body_len)assert(!memcmp(r->body,body_wire,r->body_len));status=200;return ESP_OK;}\n' +code+=function(web,'ts_webui_api_init') +code+=r''' +static void reset(void){ts_httpd_receive_end();ts_httpd_receive_begin();body_oom=revoke_after_read=downgrade_after_read=root_downgraded=false;session_live=true;receives=body_allocations=0;body_position=0;status=calls=0;free(response);response=NULL;} +static void request(unsigned transport,const char *uri,const char *auth,int method,const char *body,size_t n,int expected,bool admitted){ + reset();body_wire=body;body_wire_len=n;ts_http_route_t *route=NULL;for(unsigned i=0;i0),"authorized body received exactly once");check(calls==1&&result==ESP_OK,"normal registered business executed once");check(selected_body_budget()==(!strncmp(uri,"/api/v1/auth",12)?10000:30000),"actual SDK owner selects the correct body deadline once");} +} +static void special_request(unsigned transport,ts_http_route_t *route,const char *auth,const char *body,size_t length,bool allowed){ + reset();body_wire=body;body_wire_len=length;httpd_req_t req={.user_ctx=route,.uri=route->uri,.method=route->method,.auth=auth,.content_len=length}; + int ret=transport?https_handler_wrapper(&req):http_handler_wrapper(&req); + check(status==(allowed?200:413),"dedicated auth/upload route preserves success or denies over-limit bytes"); + check(allowed?(calls==1&&body_position==length):(calls==0&&!body_allocations&&!receives&&ret==ESP_FAIL),"dedicated route refuses allocation/read before effects or forwards exact authorized bytes"); + if(allowed)check(selected_body_budget()==300000,"large upload keeps its explicit300s allowance"); +} +int main(void){ + check(ts_webui_api_init()==ESP_OK&®istered_count==11,"actual route registration retained"); + unsigned generic=0;for(unsigned i=0;ihandler!=file_upload_handler&&special->handler!=ota_firmware_upload_handler&&special->handler!=ota_www_upload_handler)continue; + for(unsigned downgrade=0;downgrade<2;downgrade++){ + reset();revoke_after_read=!downgrade;downgrade_after_read=downgrade; + httpd_req_t late={.user_ctx=special,.uri=special->uri,.method=TS_HTTP_POST,.auth="root",.content_len=1572864};body_wire=binary;body_wire_len=1572864; + int effect=w?https_handler_wrapper(&late):http_handler_wrapper(&late); + check(effect==ESP_FAIL&&status==(downgrade?403:401)&&calls==0&&body_position==1572864,"dedicated file/APP/WWW route rechecks revocation or below-admin downgrade after full large receive, before any handler"); + } + for(unsigned role=0;role<3;role++){ + const char *auth[]={NULL,"admin","read"};reset();httpd_req_t denied={.user_ctx=special,.uri=special->uri,.method=TS_HTTP_POST,.auth=auth[role],.content_len=1572864};body_wire=binary;body_wire_len=1572864; + int effect=w?https_handler_wrapper(&denied):http_handler_wrapper(&denied); + bool allowed=role==1&&special->required_level==TS_PERM_ADMIN; + check(allowed?(effect==ESP_OK&&status==200&&calls==1&&body_position==1572864):(effect==ESP_FAIL&&status==(role?403:401)&&!receives&&!body_allocations&&!calls),"file Admin access stays usable; other wrong initial identities refused before body allocation"); + } + } + free(binary); + + request(w,"/api/v1/time/force_sync",NULL,TS_HTTP_POST,NULL,1048576,401,false); + request(w,"/api/v1/time/force_sync","admin",TS_HTTP_POST,payload,strlen(payload),200,true); + request(w,"/api/v1/log/clear","read",TS_HTTP_POST,NULL,1048576,403,false); + request(w,"/api/v1/storage/list",NULL,TS_HTTP_GET,NULL,1048576,401,false); + request(w,"/api/v1/time/force_sync","root",TS_HTTP_GET,NULL,1048576,405,false); + request(w,"/api/v1/missing","root",TS_HTTP_POST,NULL,1048576,404,false); + request(w,"/api/v1/fixture/internal","root",TS_HTTP_POST,NULL,1048576,405,false); + request(w,"/api/v1/system/info",NULL,TS_HTTP_GET,NULL,0,200,true); + request(w,"/api/v1/system/info?fixture=1",NULL,TS_HTTP_GET,NULL,0,200,true); + request(w,"/api/v1/time/force_sync","root",TS_HTTP_POST,payload,strlen(payload),200,true); + check(cJSON_IsString(cJSON_GetObjectItem(received_params,"fixture"))&&!strcmp(cJSON_GetObjectItem(received_params,"fixture")->valuestring,"kept"),"authorized JSON fields preserved"); + request(w,"/api/v1/log/clear","admin",TS_HTTP_POST,payload,strlen(payload),200,true); + const char *token="{\"token\":\"body-token-fixture\"}"; + for(unsigned i=0;i<3;i++){const char *names[]={"/api/v1/auth/logout","/api/v1/auth/status","/api/v1/auth/change_password"};request(w,names[i],NULL,TS_HTTP_POST,token,strlen(token),200,true);check(cJSON_IsString(cJSON_GetObjectItem(received_params,"token")),"body-token endpoint forwarded to existing token validator");} + reset();ts_http_route_t *route=NULL;for(unsigned i=0;i +#include +#include +#include +#include +#include +#include +#include "ts_security.h" +#include "ts_auth_layout.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "ts_crypto.h" +#include "ts_api.h" +#include "mbedtls/base64.h" +#include "mbedtls/sha256.h" +#include "mbedtls/sha512.h" +#include "mbedtls/pkcs5.h" +#include "mbedtls/platform_util.h" +#define TS_LOGI(...) ((void)0) +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +#define TS_MALLOC_PSRAM malloc +#define TS_CONFIG_KEYS_PARTITION "keys" +#define NVS_READWRITE 1 +#define ESP_ERR_NVS_NOT_FOUND 0x1102 +typedef int nvs_handle_t; +static ts_auth_user_credential_t disk[2],backup[2]; +static size_t disk_size[2],backup_size[2]; +static bool present[2],version_present,handles[16]; +static uint8_t version; +#define CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE 1 +typedef struct {int unused;} esp_partition_t; +typedef enum {ESP_OTA_IMG_NEW,ESP_OTA_IMG_PENDING_VERIFY,ESP_OTA_IMG_VALID,ESP_OTA_IMG_INVALID,ESP_OTA_IMG_UNDEFINED} esp_ota_img_states_t; +static bool trial_boot,boot_state_error; +static const esp_partition_t *esp_ota_get_running_partition(void){static esp_partition_t p;return &p;} +static int esp_ota_get_state_partition(const esp_partition_t *p,esp_ota_img_states_t *state){(void)p;*state=trial_boot?ESP_OTA_IMG_PENDING_VERIFY:ESP_OTA_IMG_VALID;return boot_state_error?ESP_FAIL:ESP_OK;} +static int next_handle,writes,commits,fail_read=-1,fail_set=-1,bad_size=-1,fail_commit_at; +static bool fail_version_read,fail_version_set,fail_version_readback; +static int fail_blob_readback=-1; +static unsigned checks,failures; +static uint32_t random_state=123; +static void check(bool ok,const char *label){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",label);}} +static const char *esp_err_to_name(int e){(void)e;return "fixture";} +static int64_t clock_us=1000000; +static int64_t esp_timer_get_time(void){return clock_us;} +static void (*random_hook)(void); +static size_t random_length;static uint8_t random_bytes[64];static bool random_zero; +static void esp_fill_random(void *p,size_t n){if(random_hook)random_hook();for(size_t i=0;i>24;}random_length=n;assert(n<=sizeof(random_bytes));memcpy(random_bytes,p,n);} +static bool valid_handle(nvs_handle_t h){return h>0&&h<16&&handles[h];} +static int index_of(const char *k){if(!strcmp(k,"cred_admin"))return 0;assert(!strcmp(k,"cred_root"));return 1;} +static int nvs_open(const char *n,int mode,nvs_handle_t *out){(void)n;(void)mode;assert(next_handle<15);*out=++next_handle;handles[*out]=true;return ESP_OK;} +static int nvs_open_from_partition(const char *p,const char *n,int mode,nvs_handle_t *out){(void)p;return nvs_open(n,mode,out);} +static void nvs_close(nvs_handle_t h){assert(valid_handle(h));handles[h]=false;} +static int nvs_get_blob(nvs_handle_t h,const char *k,void *out,size_t *len){ + if(!valid_handle(h))return ESP_ERR_INVALID_STATE;int i=index_of(k); + if(i==fail_read){fail_read=-1;return ESP_FAIL;}if(!present[i])return ESP_ERR_NVS_NOT_FOUND; + size_t size=disk_size[i]?disk_size[i]:sizeof(disk[i]);if(i==bad_size)--size;assert(*len>=size); + memcpy(out,&disk[i],size);*len=size;return ESP_OK; +} +static int nvs_set_blob(nvs_handle_t h,const char *k,const void *p,size_t n){ + if(!valid_handle(h))return ESP_ERR_INVALID_STATE;int i=index_of(k);assert(n==sizeof(disk[i])||n==TS_AUTH_LEGACY_CREDENTIAL_SIZE); + if(i==fail_set){fail_set=-1;return ESP_FAIL;}memset(&disk[i],0,sizeof(disk[i]));memcpy(&disk[i],p,n);disk_size[i]=n;present[i]=true;writes++;if(fail_blob_readback==i){fail_blob_readback=-1;fail_read=i;}return ESP_OK; +} +/* Deliberately adverse: a failed commit does not roll back an already visible set. */ +static int nvs_commit(nvs_handle_t h){assert(valid_handle(h));commits++;return fail_commit_at==commits?ESP_FAIL:ESP_OK;} +static int nvs_get_u8(nvs_handle_t h,const char *k,uint8_t *out){ + (void)k;assert(valid_handle(h));if(fail_version_read){fail_version_read=false;return ESP_FAIL;} + if(!version_present)return ESP_ERR_NVS_NOT_FOUND;*out=version;return ESP_OK; +} +static int nvs_set_u8(nvs_handle_t h,const char *k,uint8_t v){ + (void)k;assert(valid_handle(h));if(fail_version_set)return ESP_FAIL;version=v;version_present=true;if(fail_version_readback){fail_version_readback=false;fail_version_read=true;}return ESP_OK; +} +static int nvs_erase_key(nvs_handle_t h,const char *k){(void)h;(void)k;return ESP_OK;} +static int ts_ssh_hosts_config_init(void){return ESP_OK;} +static int ts_ssh_commands_config_init(void){return ESP_OK;} +static int ts_ssh_service_init(void){return ESP_OK;} +static int ts_ssh_log_watch_init(void){return ESP_OK;} +''' +if args.case in ("revocation", "tokens"): + code=code.replace("#define TS_LOGI(...) ((void)0)",r''' +#include +static char body_diagnostic[1024];static size_t body_diagnostic_used;static bool body_diagnostic_enabled; +static void body_log(const char *tag,const char *format,...){ + (void)tag;if(!body_diagnostic_enabled||body_diagnostic_used>=sizeof(body_diagnostic)-1)return; + va_list ap;va_start(ap,format);int n=vsnprintf(body_diagnostic+body_diagnostic_used,sizeof(body_diagnostic)-body_diagnostic_used,format,ap);va_end(ap); + if(n>0)body_diagnostic_used+=(size_t)n +static pthread_mutex_t slot_race_lock=PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t slot_race_changed=PTHREAD_COND_INITIALIZER; +static bool slot_matched,slot_worker_waiting,slot_worker_finished,slot_hook_armed; +static _Thread_local bool slot_recycler; +static _Thread_local unsigned slot_lock_depth; +static atomic_uint slot_logs_under_gate; +static void slot_log(const char *tag,const char *message,...){(void)tag;(void)message;if(slot_lock_depth)atomic_fetch_add(&slot_logs_under_gate,1);} +#undef TS_LOGI +#undef TS_LOGW +#undef TS_LOGE +#define TS_LOGI slot_log +#define TS_LOGW slot_log +#define TS_LOGE slot_log +static int slot_take(SemaphoreHandle_t gate,unsigned timeout){ + if(slot_recycler){pthread_mutex_lock(&slot_race_lock);slot_worker_waiting=true;pthread_cond_broadcast(&slot_race_changed);pthread_mutex_unlock(&slot_race_lock);} + int ret=xSemaphoreTakeRecursive(gate,timeout);if(ret)++slot_lock_depth;return ret; +} +static int slot_give(SemaphoreHandle_t gate){assert(slot_lock_depth);--slot_lock_depth;return xSemaphoreGiveRecursive(gate);} +#define xSemaphoreTakeRecursive slot_take +#define xSemaphoreGiveRecursive slot_give +static void wait_slot_flag(bool *flag){ + struct timespec until;clock_gettime(CLOCK_REALTIME,&until);until.tv_sec+=5; + while(!*flag)assert(pthread_cond_timedwait(&slot_race_changed,&slot_race_lock,&until)==0); +} +static void token_match_boundary(void){ + if(!slot_hook_armed)return;slot_hook_armed=false; + pthread_mutex_lock(&slot_race_lock);slot_matched=true;pthread_cond_broadcast(&slot_race_changed); + if(slot_lock_depth)wait_slot_flag(&slot_worker_waiting);else wait_slot_flag(&slot_worker_finished); + pthread_mutex_unlock(&slot_race_lock); +} +""" +if "ts_auth_credential_create" in source("components/ts_security/src/ts_auth.c"): + code+='\n'+re.sub(r"^#include[^\n]*\n","",source("components/ts_auth_layout/src/ts_auth_credential.c"),flags=re.M) +for filename in ["ts_security.c","ts_auth.c"]: + implementation=source("components/ts_security/src/"+filename) + if args.case=="session_race" and filename=="ts_security.c": + anchor=' if (diff != 0) continue;' + assert implementation.count(anchor)==1 + implementation=implementation.replace(anchor,anchor+'\n token_match_boundary();') + code+="\n#undef TAG\n"+re.sub(r"^#include[^\n]*\n","",implementation,flags=re.M) +if args.case in ("revocation","lockout"): + code+=r''' +esp_err_t ts_api_register(const ts_api_endpoint_t *e){(void)e;return ESP_OK;} +void ts_api_result_ok(ts_api_result_t *r,cJSON *data){r->code=TS_API_OK;r->data=data;} +void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t code,const char *m){r->code=code;r->message=strdup(m);} +''' + code+='\n#undef TAG\n'+re.sub(r"^#include[^\n]*\n","",source("components/ts_api/src/ts_api_auth.c"),flags=re.M) +if args.case in ("revocation","lockout"): + code+=r''' +/* Keep the real login and HTTP handler, inject revocation at their boundary. */ +typedef struct {const char *body;size_t body_len;} ts_http_request_t; +static int http_status;static cJSON *http_json;static bool revoke_after_login;static char http_error[160]; +static esp_err_t ts_http_send_error(ts_http_request_t *r,int status,const char *m){(void)r;snprintf(http_error,sizeof(http_error),"%s",m);http_status=status;return ESP_OK;} +static esp_err_t ts_http_send_json(ts_http_request_t *r,int status,const char *json){(void)r;http_status=status;http_json=cJSON_Parse(json);return ESP_OK;} +static esp_err_t login_boundary(const char *user,const char *password,uint32_t *sid,char *token,size_t size){ + esp_err_t ret=ts_auth_login(user,password,sid,token,size); + if(ret==ESP_OK&&revoke_after_login)assert(ts_auth_logout(*sid)==ESP_OK); + return ret; +} +#define ts_auth_login login_boundary + +''' + web=source("components/ts_webui/src/ts_webui_api.c") + start=web.index("static esp_err_t login_handler(") + code+=web[start:web.index("\n}",start)+2]+"\n#undef ts_auth_login\n" +code+=r''' +/* Fixed reader/init from committed 0.6.4 120f0c79b, independent of current codec. */ +typedef struct {uint8_t salt[16],hash[32];bool password_changed;uint32_t failed_attempts,lockout_until;} stock_credential_t; +_Static_assert(sizeof(stock_credential_t)==60,"stock 0.6.4 layout"); +static nvs_handle_t stock_nvs;static bool stock_initialized;static unsigned stock_resets; +static esp_err_t stock_force_create_user(const char *name,ts_perm_level_t level){(void)name;(void)level;stock_resets++;return ESP_FAIL;} +static esp_err_t stock_load_user_credential(const char *username, stock_credential_t *cred) +{ + char key[32]; + snprintf(key, sizeof(key), "cred_%s", username); + + size_t len = sizeof(stock_credential_t); + esp_err_t ret = nvs_get_blob(stock_nvs, key, cred, &len); + + return ret; +} +static esp_err_t stock_save_user_credential(const char *username, const stock_credential_t *cred) +{ + char key[32]; + snprintf(key, sizeof(key), "cred_%s", username); + + esp_err_t ret = nvs_set_blob(stock_nvs, key, cred, sizeof(stock_credential_t)); + if (ret == ESP_OK) { + nvs_commit(stock_nvs); + } + return ret; +} +static esp_err_t stock_init_user_if_needed(const char *username, ts_perm_level_t level) +{ + stock_credential_t cred; + + if (stock_load_user_credential(username, &cred) == ESP_OK) { + /* 开机计时相关的临时锁定不能沿用到本次启动。 */ + if (cred.failed_attempts || cred.lockout_until) { + cred.failed_attempts = 0; + cred.lockout_until = 0; + return stock_save_user_credential(username, &cred); + } + return ESP_OK; + } + + return stock_force_create_user(username, level); +} +esp_err_t stock_auth_init(void) +{ + if (stock_initialized) return ESP_OK; + + esp_err_t ret = nvs_open(TS_AUTH_NVS_NAMESPACE, NVS_READWRITE, &stock_nvs); + if (ret != ESP_OK) { + TS_LOGE(TAG, "Failed to open NVS namespace: %s", esp_err_to_name(ret)); + return ret; + } + + /* 检查配置版本,版本变化时强制重置所有用户 */ + uint8_t stored_version = 0; + nvs_get_u8(stock_nvs, TS_AUTH_CONFIG_VERSION_KEY, &stored_version); + + if (stored_version != TS_AUTH_CONFIG_VERSION) { + TS_LOGW(TAG, "Auth config version changed (%d -> %d), resetting all users", + stored_version, TS_AUTH_CONFIG_VERSION); + /* 强制重新创建所有用户 */ + stock_force_create_user("admin", TS_PERM_ADMIN); + stock_force_create_user("root", TS_PERM_ROOT); + /* 保存新版本号 */ + nvs_set_u8(stock_nvs, TS_AUTH_CONFIG_VERSION_KEY, TS_AUTH_CONFIG_VERSION); + nvs_commit(stock_nvs); + } else { + /* 初始化默认用户(如果不存在) */ + ret = stock_init_user_if_needed("admin", TS_PERM_ADMIN); + if (ret == ESP_OK) ret = stock_init_user_if_needed("root", TS_PERM_ROOT); + if (ret != ESP_OK) { + nvs_close(stock_nvs); + return ret; + } + } + + stock_initialized = true; + TS_LOGI(TAG, "Auth module initialized (version %d)", TS_AUTH_CONFIG_VERSION); + return ESP_OK; +} +static void original_firmware_accepts(const char *admin,const char *root){ + stock_initialized=false;stock_resets=0;int previous=writes; + check(stock_auth_init()==ESP_OK&&!stock_resets&&version==3,"actual original firmware boots without recreating either account"); + check(writes==previous,"stock startup does not replace migrated password records"); + const char *passwords[]={admin,root}; + for(unsigned u=0;u<2;u++){stock_credential_t credential;check(stock_load_user_credential(u?"root":"admin",&credential)==ESP_OK,"original reader accepts exact 60-byte record");unsigned char bytes[80],hash[32];size_t n=strlen(passwords[u]);memcpy(bytes,credential.salt,16);memcpy(bytes+16,passwords[u],n);assert(!mbedtls_sha256(bytes,16+n,hash,0));check(!memcmp(hash,credential.hash,32),"original password algorithm authenticates the same custom password");} + nvs_close(stock_nvs); +} +static void prototype_record(unsigned u,const char *password,bool changed){ + memset(&disk[u],0,sizeof(disk[u]));memset(disk[u].salt,31+u,16);disk[u].format=TS_AUTH_CREDENTIAL_MAGIC;disk[u].rounds=10000;disk[u].password_changed=changed; + assert(!mbedtls_pkcs5_pbkdf2_hmac_ext(MBEDTLS_MD_SHA256,(const unsigned char*)password,strlen(password),disk[u].salt,16,10000,32,disk[u].hash));disk_size[u]=68;present[u]=true;version=4;version_present=true; +} + +static void power_cycle(void){ + memset(handles,0,sizeof(handles));next_handle=0;s_initialized=false;s_auth_initialized=false;s_auth_nvs=0; + clock_us=1000000;writes=commits=0;fail_read=fail_set=bad_size=-1;fail_commit_at=0;fail_version_read=fail_version_set=fail_version_readback=false;fail_blob_readback=-1; + assert(ts_security_init()==ESP_OK); +} +static void restore(void){ + memcpy(disk,backup,sizeof(disk));memcpy(disk_size,backup_size,sizeof(disk_size));present[0]=present[1]=true;version=TS_AUTH_CONFIG_VERSION;version_present=true;power_cycle(); +} +static unsigned active_sessions(void){unsigned n=0;for(unsigned i=0;i0)--json_budget;return malloc(size);} + +static void release_body_result(ts_api_result_t *r){cJSON_Delete(r->data);free(r->message);*r=(ts_api_result_t){0};} +static void body_token_api_tests(void){ + setup_users();char root_a[128],root_b[128],admin[128];uint32_t root_sid=session_for("root","root-fixture",root_a); + session_for("root","root-fixture",root_b);session_for("admin","admin-fixture",admin); + const char *bad[]={"","invalid-token","AAAA","AAAAAAAAAAAAAAAAAAAAAA=="}; + for(unsigned i=0;ivaluestring,users[u]),"core API login uses actual session level"); + check(valid_token(cJSON_GetObjectItemCaseSensitive(result.data,"token")->valuestring),"core API login returns usable full token"); + cJSON_Delete(result.data);free(result.message); + char *body=cJSON_PrintUnformatted(p);ts_http_request_t req={.body=body,.body_len=strlen(body)};cJSON_Delete(p);http_status=0; + assert(login_handler(&req,NULL)==ESP_OK); + check(http_status==200&&http_json,"normal dedicated HTTP login succeeds"); + check(!strcmp(cJSON_GetObjectItemCaseSensitive(cJSON_GetObjectItemCaseSensitive(http_json,"data"),"level")->valuestring,users[u]),"HTTP login uses actual session level"); + cJSON_Delete(http_json);http_json=NULL;revoke_after_login=true; + assert(login_handler(&req,NULL)==ESP_OK);revoke_after_login=false; + check(http_status==401&&!http_json,"HTTP login cannot report success for a session revoked before response creation"); + cJSON_Delete(http_json);http_json=NULL;free(body); + } + for(unsigned op=0;op<3;op++){ + setup_users();char root[128],root2[128],admin[128],admin2[128],fresh[128];session_for("root","root-fixture",root);session_for("root","root-fixture",root2);session_for("admin","admin-fixture",admin);session_for("admin","admin-fixture",admin2); + ts_api_handler_t handler=op==0?api_auth_admin_set_password:op==1?api_auth_admin_reset_password:api_auth_root_set_password; + api_update(handler,root,NULL,op==1?NULL:"manager-fixture",true,op==2); + check(valid_token(root)==(op!=2)&&valid_token(root2)==(op!=2),"root sessions revoked only when target is root"); + check(valid_token(admin)==(op==2)&&valid_token(admin2)==(op==2),"all and only target admin sessions revoked"); + const char *user=op==2?"root":"admin";const char *pass=op==1?TS_AUTH_DEFAULT_ADMIN_PASSWORD:"manager-fixture"; + session_for(user,pass,fresh);check(valid_token(fresh),"root-managed credential supports subsequent login"); + } + for(unsigned failure=0;failure<4;failure++){ + setup_users();char root[128],admin[128];session_for("root","root-fixture",root);session_for("admin","admin-fixture",admin); + if(failure==0)fail_set=1;if(failure==1)fail_commit_at=commits+1; + api_update(failure==3?api_auth_admin_set_password:api_auth_change_password,failure==3?admin:root,failure==2?"wrong":"root-fixture","failure-fixture",false,false); + check(valid_token(root)==(failure!=1)&&valid_token(admin),"only an accepted unconfirmed password write revokes target sessions; other account is retained"); + } + for(unsigned op=0;op<3;op++)for(unsigned failure=0;failure<2;failure++){ + setup_users();char root[128],admin[128];session_for("root","root-fixture",root);session_for("admin","admin-fixture",admin); + if(failure==0)fail_set=op==2?1:0;else fail_commit_at=commits+1; + ts_api_handler_t handler=op==0?api_auth_admin_set_password:op==1?api_auth_admin_reset_password:api_auth_root_set_password; + api_update(handler,root,NULL,op==1?NULL:"failure-fixture",false,false); + check(valid_token(root)==!(failure==1&&op==2)&&valid_token(admin)==!(failure==1&&op!=2),"unconfirmed manager writes revoke only target; rejected set preserves sessions"); + } + for(unsigned op=0;op<4;op++)for(int budget=0;budget<7;budget++){ + setup_users();char root[128],admin[128];session_for("root","root-fixture",root);session_for("admin","admin-fixture",admin); + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"token",root);cJSON_AddStringToObject(p,"old_password","root-fixture");cJSON_AddStringToObject(p,"new_password","response-fixture"); + ts_api_handler_t handlers[]={api_auth_change_password,api_auth_admin_set_password,api_auth_admin_reset_password,api_auth_root_set_password}; + int before=writes;json_budget=budget;cJSON_Hooks hooks={.malloc_fn=limited_json_alloc,.free_fn=free};cJSON_InitHooks(&hooks); + ts_api_result_t result={0};esp_err_t ret=handlers[op](p,&result);json_budget=-1;cJSON_InitHooks(NULL); + check(ret==ESP_ERR_NO_MEM&&result.code==TS_API_ERR_NO_MEM,"required reauth response allocation failure is reported"); + check(writes==before,"response allocation failure occurs before credential mutation"); + check(valid_token(root)&&valid_token(admin),"response allocation failure does not revoke any session"); + cJSON_Delete(p);cJSON_Delete(result.data);free(result.message); + } + setup_users();check(ts_auth_set_root_password("root-fixture")==ESP_OK&&active_sessions()==0,"updating a target without sessions stays usable"); + /* Stop a login immediately after old-password verification. The setter either + * reaches the real pthread-backed auth gate or completes (old implementation). + * No sleep controls the ordering. */ + random_hook=pause_after_verify;observe_gate=true; + pthread_t login_thread,set_thread;assert(!pthread_create(&login_thread,NULL,racing_login,NULL)); + pthread_mutex_lock(&race_lock);while(!login_paused)pthread_cond_wait(&race_changed,&race_lock);pthread_mutex_unlock(&race_lock); + assert(!pthread_create(&set_thread,NULL,racing_set,NULL)); + pthread_mutex_lock(&race_lock);while(!setter_at_gate&&!setter_done)pthread_cond_wait(&race_changed,&race_lock);release_login=true;pthread_cond_broadcast(&race_changed);pthread_mutex_unlock(&race_lock); + assert(!pthread_join(login_thread,NULL));assert(!pthread_join(set_thread,NULL));random_hook=NULL;observe_gate=false; + check(race_login_ret==ESP_OK&&race_set_ret==ESP_OK,"concurrent login and update both terminate normally"); + check(!valid_token(race_token),"old-password login cannot issue a surviving session after update/revocation"); + check(ts_auth_verify_password("root","race-new-root",NULL)==ESP_OK,"raced password update remains usable"); + printf("%u checks, %u failures: actual auth/session/API handlers, SDK crypto and ordered pthread race; synthetic NVS\n",checks,failures); + return failures?1:0; +} + +''' +if args.case=="lockout": + code+=r''' +static esp_err_t wrong_attempt(unsigned u){return ts_auth_verify_password(u?"root":"admin","wrong-fixture",NULL);} +static esp_err_t correct_attempt(unsigned u){return ts_auth_verify_password(u?"root":"admin",u?"root-fixture":"admin-fixture",NULL);} +static void five_wrong(unsigned u){for(unsigned n=0;n<5;n++)check(wrong_attempt(u)==ESP_ERR_INVALID_ARG,"five guesses reach threshold without granting a session");} +static int lockout_tests(void){ + power_cycle();assert(ts_auth_init()==ESP_OK);assert(ts_auth_set_admin_password("admin-fixture")==ESP_OK);assert(ts_auth_set_root_password("root-fixture")==ESP_OK);memcpy(backup,disk,sizeof(backup));memcpy(backup_size,disk_size,sizeof(backup_size)); + for(unsigned u=0;u<2;u++){ + restore();assert(ts_auth_init()==ESP_OK); + for(unsigned n=1;n<5;n++){ + check(wrong_attempt(u)==ESP_ERR_INVALID_ARG,"wrong guess rejected"); + check(disk[u].failed_attempts==n,"partial failure count advances across reboots"); + user_credential_t before[2];memcpy(before,disk,sizeof(before));power_cycle(); + check(ts_auth_init()==ESP_OK&&writes==0&&commits==0&&!memcmp(before,disk,sizeof(before)),"reboot preserves both credential blobs and performs no NVS write"); + } + check(wrong_attempt(u)==ESP_ERR_INVALID_ARG,"fifth wrong guess rejected"); + check(disk[u].failed_attempts==0&&disk[u].lockout_until!=0,"fifth guess persists lock marker"); + char token[128];uint32_t sid=0;unsigned active=active_sessions(); + check(ts_auth_login(u?"root":"admin",u?"root-fixture":"admin-fixture",&sid,token,sizeof(token))==ESP_ERR_INVALID_STATE&&active_sessions()==active,"correct login during lock cannot issue a session"); + int before_writes=writes,before_commits=commits; + for(unsigned n=0;n<10;n++)check((n%2?wrong_attempt(u):correct_attempt(u))==ESP_ERR_INVALID_STATE,"locked requests reject both correct and wrong passwords"); + check(writes==before_writes&&commits==before_commits,"locked requests do not write or commit NVS"); + check(correct_attempt(1-u)==ESP_OK,"one account lock does not block the other account"); + clock_us+=100LL*1000000;check(ts_auth_init()==ESP_OK,"repeated init is idempotent"); + clock_us+=199LL*1000000;check(correct_attempt(u)==ESP_ERR_INVALID_STATE,"299 seconds remains locked"); + clock_us+=1000000;check(correct_attempt(u)==ESP_OK,"300-second boundary accepts correct password without restarting cooldown"); + check(disk[u].failed_attempts==0&&disk[u].lockout_until==0,"successful post-cooldown verification durably clears marker"); + check(!memcmp(disk[u].salt,backup[u].salt,TS_AUTH_SALT_LEN)&&!memcmp(disk[u].hash,backup[u].hash,TS_AUTH_HASH_LEN),"cooldown does not change password material"); + } + /* Existing v3 stores may contain a prior boot's large absolute uptime. + * All nonzero markers receive exactly one new bounded boot cooldown. */ + const uint32_t markers[]={1,7*86400+300,UINT32_MAX}; + for(unsigned u=0;u<2;u++)for(unsigned m=0;m<3;m++){ + restore();disk[u].lockout_until=markers[m];power_cycle();user_credential_t before=disk[u]; + check(ts_auth_init()==ESP_OK&&!memcmp(&before,&disk[u],sizeof(before))&&writes==0&&commits==0,"legacy marker boot is read-only"); + check(correct_attempt(u)==ESP_ERR_INVALID_STATE,"boot rearms a bounded lock regardless of old deadline"); + clock_us+=299LL*1000000;check(correct_attempt(u)==ESP_ERR_INVALID_STATE,"legacy lock remains until boundary"); + clock_us+=1000000;check(correct_attempt(u)==ESP_OK&&disk[u].lockout_until==0,"large old uptime never causes an unbounded lock"); + } + for(unsigned u=0;u<2;u++){ + restore();assert(ts_auth_init()==ESP_OK);five_wrong(u);clock_us+=300LL*1000000; + check(wrong_attempt(u)==ESP_ERR_INVALID_ARG&&disk[u].failed_attempts==1&&disk[u].lockout_until==0,"first wrong guess after cooldown starts a fresh persisted budget"); + for(unsigned n=0;n<4;n++)check(wrong_attempt(u)==ESP_ERR_INVALID_ARG,"next bounded budget counts each wrong guess"); + check(correct_attempt(u)==ESP_ERR_INVALID_STATE,"next five wrong guesses lock again"); + + restore();disk[u].failed_attempts=UINT32_MAX;power_cycle();assert(ts_auth_init()==ESP_OK); + check(correct_attempt(u)==ESP_ERR_INVALID_STATE,"out-of-range persisted counter cannot wrap into fresh attempts"); + clock_us+=300LL*1000000;check(correct_attempt(u)==ESP_OK&&disk[u].failed_attempts==0,"counter anomaly still permits bounded recovery"); + + restore();disk[u].lockout_until=1;power_cycle();assert(ts_auth_init()==ESP_OK);clock_us+=300LL*1000000;fail_commit_at=commits+1; + char token[128];uint32_t sid=0;unsigned active=active_sessions(); + check(ts_auth_login(u?"root":"admin",u?"root-fixture":"admin-fixture",&sid,token,sizeof(token))==ESP_FAIL&&active_sessions()==active,"post-cooldown cleanup commit failure cannot issue a new session"); + + restore();disk[u].lockout_until=1;power_cycle();fail_read=u; + check(ts_auth_init()==ESP_FAIL&&!s_auth_initialized&&disk[u].lockout_until==1&&writes==0,"locked record read failure fails closed without resetting credentials"); + check(ts_auth_init()==ESP_OK&&correct_attempt(u)==ESP_ERR_INVALID_STATE,"read retry retains boot lock"); + + restore();assert(ts_auth_init()==ESP_OK);char root_token[128];sid=0;assert(ts_auth_login("root","root-fixture",&sid,root_token,sizeof(root_token))==ESP_OK);five_wrong(u); + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"token",root_token);cJSON_AddStringToObject(p,"new_password","recovered-fixture");ts_api_result_t result={0}; + esp_err_t ret=(u?api_auth_root_set_password:api_auth_admin_set_password)(p,&result); + check(ret==ESP_OK&&result.code==TS_API_OK,"existing root session can recover a login-locked account"); + check(ts_auth_verify_password(u?"root":"admin","recovered-fixture",NULL)==ESP_OK&&disk[u].lockout_until==0,"authorized password update clears runtime and persisted lock"); + check(cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(result.data,"reauth_required"))==(u==1),"lock recovery retains target-based re-login policy"); + cJSON_Delete(p);cJSON_Delete(result.data);free(result.message); + + restore();assert(ts_auth_init()==ESP_OK);five_wrong(u); + p=cJSON_CreateObject();cJSON_AddStringToObject(p,"username",u?"root":"admin");cJSON_AddStringToObject(p,"password",u?"root-fixture":"admin-fixture");result=(ts_api_result_t){0}; + check(api_auth_login(p,&result)==ESP_ERR_INVALID_STATE&&result.code==TS_API_ERR_AUTH&&!strcmp(result.message,"Account locked due to too many failed attempts"),"core API reports account lock"); + cJSON_Delete(result.data);free(result.message);char *body=cJSON_PrintUnformatted(p);cJSON_Delete(p);ts_http_request_t req={.body=body,.body_len=strlen(body)};http_status=0; + assert(login_handler(&req,NULL)==ESP_OK); + check(http_status==401&&!strcmp(http_error,"Account locked due to too many failed attempts"),"dedicated HTTP login reports the same actionable lock reason"); + clock_us+=300LL*1000000;assert(login_handler(&req,NULL)==ESP_OK); + check(http_status==200&&http_json,"HTTP login remains usable when cooldown ends");cJSON_Delete(http_json);http_json=NULL;free(body); + } + check(sizeof(user_credential_t)==68&&TS_AUTH_CONFIG_VERSION==3&&TS_AUTH_USER_CREDENTIAL_SIZE==60,"credential format/version and legacy prefix are explicit"); + printf("%u checks, %u failures: actual auth/session/core API/HTTP login with synthetic time and NVS; no device\n",checks,failures); + return failures?1:0; +} + +''' +if args.case=="tokens": + code+=r""" +static int token_tests(void){ + power_cycle();char first[128],other[128],fresh[128],changed[128];uint32_t a=0,b=0,out=0; + assert(ts_auth_init()==ESP_OK&&ts_auth_set_root_password("root-fixture")==ESP_OK); + body_diagnostic[0]=0;body_diagnostic_used=0;body_diagnostic_enabled=true; + char logged_token[128],sid_text[16];uint32_t logged_sid=0; + check(ts_auth_login("root","root-fixture",&logged_sid,logged_token,sizeof(logged_token))==ESP_OK,"actual root login succeeds with current credential owner"); + snprintf(sid_text,sizeof(sid_text),"%08lx",(unsigned long)logged_sid); + check(strstr(body_diagnostic,"root")&&!strstr(body_diagnostic,sid_text)&&!strstr(body_diagnostic,logged_token),"actual login logs retain account name without SID or token"); + check(ts_auth_logout(logged_sid)==ESP_OK&&!strstr(body_diagnostic,sid_text),"actual logout log does not leak SID"); + body_diagnostic_enabled=false; + + check(ts_security_create_session("root",TS_PERM_ROOT,&a)==ESP_OK&&a!=0,"issued session is nonzero"); + + uint8_t unissued_raw[17]={0};memcpy(unissued_raw,&a,4); + for(size_t length=0;length<=sizeof(unissued_raw);++length){ + size_t capacity=sizeof(changed);assert(ts_crypto_base64_encode(unissued_raw,length,changed,&capacity)==ESP_OK); + check(ts_security_validate_token(changed,&out)!=ESP_OK,"unissued session and every decoded length 0..17 cannot authenticate"); + } + check(ts_security_validate_token("not-base64",&out)!=ESP_OK,"malformed base64 cannot authenticate"); + check(ts_security_generate_token(a,first,sizeof(first))==ESP_OK,"normal opaque token generation succeeds"); + uint8_t raw[16];size_t n=sizeof(raw); + check(ts_crypto_base64_decode(first,strlen(first),raw,&n)==ESP_OK&&n==16&&strlen(first)==24,"16-byte credential retains existing 24-character Base64 wire length"); + check(random_length==sizeof(raw)&&!memcmp(raw,random_bytes,sizeof(raw)),"all 16 credential bytes originate from RNG, not identity/clock"); + check(ts_security_validate_token(first,&out)==ESP_OK&&out==a,"opaque credential resolves original session"); + uint8_t inferred[16]={0};memcpy(inferred,&a,4);uint32_t known_uptime=(uint32_t)(clock_us/1000);memcpy(inferred+12,&known_uptime,4); + /* Even granting the synthetic test identity and uptime cannot replace the + * issued nonce. This bounded fixture is not an exhaustive search claim. */ + for(unsigned padding=0;padding<256;++padding){ + memset(inferred+4,(int)padding,8);size_t capacity=sizeof(changed); + assert(ts_crypto_base64_encode(inferred,sizeof(inferred),changed,&capacity)==ESP_OK); + check(ts_security_validate_token(changed,&out)!=ESP_OK,"metadata-shaped synthetic reconstruction is not the issued opaque credential"); + } + + check(ts_security_create_session("admin",TS_PERM_ADMIN,&b)==ESP_OK&&b!=a&&b!=0,"second identity is distinct and nonzero"); + check(ts_security_generate_token(b,other,sizeof(other))==ESP_OK,"second session generates independent credential"); + check(ts_security_validate_token(other,&out)==ESP_OK&&out==b&&ts_security_check_permission(out,TS_PERM_ADMIN)&&!ts_security_check_permission(out,TS_PERM_ROOT),"credential lookup across slots retains actual Admin privilege"); + check(ts_security_validate_token(first,&out)==ESP_OK&&out==a,"second login preserves first token"); + for(unsigned i=0;imethod;++http_calls;http_offset=0;http_authorization[0]=0; - http_bundle=cfg->crt_bundle_attach==esp_crt_bundle_attach;http_skip_name=cfg->skip_cert_common_name_check; - snprintf(http_url,sizeof(http_url),"%s",cfg->url);return (void*)1;} -static esp_err_t esp_http_client_set_header(esp_http_client_handle_t c,const char *name,const char *value) -{(void)c;assert(!strcmp(name,"Authorization"));snprintf(http_authorization,sizeof(http_authorization),"%s",value);return ESP_OK;} -static esp_err_t esp_http_client_open(esp_http_client_handle_t c,int n){(void)c;(void)n;return ESP_OK;} -static int esp_http_client_fetch_headers(esp_http_client_handle_t c){(void)c;return 0;} -static int esp_http_client_get_status_code(esp_http_client_handle_t c){(void)c;return 200;} -static int esp_http_client_read(esp_http_client_handle_t c,char *out,int size) -{(void)c;const char *data=http_payload;int length=(int)strlen(data);if(http_offset)return 0;assert(size>=length);memcpy(out,data,length);http_offset=length;return length;} -static esp_err_t esp_http_client_close(esp_http_client_handle_t c){(void)c;return ESP_OK;} -static esp_err_t esp_http_client_cleanup(esp_http_client_handle_t c){(void)c;return ESP_OK;} +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request,ts_http_fetch_result_t *reply) +{ + memset(reply,0,sizeof(*reply));http_method=request->method;++http_calls; + http_default_ca=request->cert_pem==NULL;http_headers_only=request->headers_only; + snprintf(http_url,sizeof(http_url),"%s",request->url); + snprintf(http_authorization,sizeof(http_authorization),"%s",request->authorization?request->authorization:""); + reply->status=200;reply->body=strdup(http_payload);reply->length=strlen(http_payload);reply->content_length=reply->length; + return reply->body?ESP_OK:ESP_ERR_NO_MEM; +} esp_err_t ts_api_call(const char *name,const cJSON *params,ts_api_result_t *result) {(void)params;assert(!strcmp(name,"example.status"));++local_api_calls;result->code=0;result->data=cJSON_Parse("{\"temperature\":21}");return ESP_OK;} typedef const char *esp_event_base_t; typedef struct {char *data_ptr;int data_len,payload_len,payload_offset;bool fin;uint8_t op_code;} esp_websocket_event_data_t; -typedef struct {const char *uri;int buffer_size,reconnect_timeout_ms,network_timeout_ms,ping_interval_sec;bool enable_close_reconnect;esp_err_t (*crt_bundle_attach)(void *);} esp_websocket_client_config_t; +typedef struct {const char *uri;int buffer_size,reconnect_timeout_ms,network_timeout_ms,ping_interval_sec;bool enable_close_reconnect,disable_auto_reconnect;esp_err_t (*crt_bundle_attach)(void *);} esp_websocket_client_config_t; enum {WEBSOCKET_EVENT_CONNECTED=1,WEBSOCKET_EVENT_DISCONNECTED,WEBSOCKET_EVENT_DATA,WEBSOCKET_EVENT_ERROR,WEBSOCKET_EVENT_CLOSED}; #define SIO_MSG_BUF_SIZE 8192 #define SIO_PROBE_MSG "2probe" @@ -118,6 +113,7 @@ static unsigned stream_tasks_created; static void sio_connection_task(void *arg) {(void)arg;assert(false);} static BaseType_t xTaskCreateWithCaps(void (*task)(void *),const char *name,unsigned stack,void *arg,unsigned priority,TaskHandle_t *out,unsigned caps) {assert(task==sio_connection_task&&name&&stack==6144&&arg&&priority==5&&caps);*out=(void *)1;++stream_tasks_created;return pdPASS;} +static void *heap_caps_realloc(void *p,size_t n,unsigned caps) {(void)caps;return realloc(p,n);} #include "source_transport.inc" void ts_source_config_activate(void) { /* Task creation and real networking are outside this fixture. */ } @@ -413,13 +409,13 @@ static void rule_config_cases(void) static void source_cases(void) { char transport_url[256]; - ts_source_sio_websocket_url("https://example.invalid:443", "sid", transport_url, sizeof(transport_url)); + ts_source_sio_url("https://example.invalid:443", "sid", transport_url, sizeof(transport_url)); assert(!strcmp(transport_url,"wss://example.invalid:443/socket.io/?EIO=4&transport=websocket&sid=sid")); - ts_source_sio_websocket_url("http://example.invalid:80", "sid", transport_url, sizeof(transport_url)); + ts_source_sio_url("http://example.invalid:80", "sid", transport_url, sizeof(transport_url)); assert(!strcmp(transport_url,"ws://example.invalid:80/socket.io/?EIO=4&transport=websocket&sid=sid")); char sid[64]={0};http_payload="0{\"sid\":\"fixture\"}"; assert(sio_http_handshake("https://example.invalid:443",sid,sizeof(sid))==ESP_OK&&!strcmp(sid,"fixture")); - assert(!strncmp(http_url,"https://",8)&&http_bundle&&!http_skip_name); + assert(!strncmp(http_url,"https://",8)&&http_default_ca&&!http_headers_only); http_payload="{\"temperature\":21}"; /* Real runtime handshake: standard server sends no WS noop acknowledgement. */ ts_auto_source_t protocol={.enabled=true,.type=TS_AUTO_SRC_SOCKETIO,.mapping_count=1}; @@ -505,9 +501,9 @@ static void source_cases(void) assert(stream&&stream->source_instance==ws.instance&&stream->type==TS_AUTO_SRC_WEBSOCKET&&stream->pending_mutex); assert(stream_connect(ws.id,TS_AUTO_SRC_WEBSOCKET)==ESP_OK&&stream_tasks_created==before_stream+1); esp_websocket_client_config_t stream_config=test_stream_client_config(stream,3210,ws.websocket.uri); - assert(stream_config.enable_close_reconnect&&stream_config.reconnect_timeout_ms==3210&&stream_config.crt_bundle_attach==esp_crt_bundle_attach); + assert(stream_config.enable_close_reconnect&&!stream_config.disable_auto_reconnect&&stream_config.reconnect_timeout_ms==3210&&stream_config.crt_bundle_attach==esp_crt_bundle_attach); stream->type=TS_AUTO_SRC_SOCKETIO;stream_config=test_stream_client_config(stream,3210,ws.websocket.uri); - assert(!stream_config.enable_close_reconnect&&stream_config.reconnect_timeout_ms==10000);stream->type=TS_AUTO_SRC_WEBSOCKET; + assert(!stream_config.enable_close_reconnect&&stream_config.disable_auto_reconnect&&stream_config.reconnect_timeout_ms==10000);stream->type=TS_AUTO_SRC_WEBSOCKET; sio_websocket_event_handler(stream,NULL,WEBSOCKET_EVENT_CONNECTED,NULL); assert(ts_source_get_copy(ws.id,&ws)==ESP_OK&&ws.connected); char message[]="{\"data\":{\"temperature\":23}}";int length=(int)strlen(message); @@ -537,7 +533,7 @@ static void source_cases(void) sio_websocket_event_handler(stream,NULL,WEBSOCKET_EVENT_DATA,&control);ws_test_handler(&test,NULL,WEBSOCKET_EVENT_DATA,&control); part=(esp_websocket_event_data_t){.data_ptr=framed+8,.data_len=framed_length-8,.payload_len=framed_length-8,.fin=true,.op_code=0}; sio_websocket_event_handler(stream,NULL,WEBSOCKET_EVENT_DATA,&part);ws_test_handler(&test,NULL,WEBSOCKET_EVENT_DATA,&part); - assert(test.received&&!strcmp(test.message,framed));free(test.message);test_process_pending(stream); + assert(test.received&&!strcmp(test.sample.data,framed));free(test.sample.data);test_process_pending(stream); assert(ts_variable_get("plain_ws.temperature",&mapped)==ESP_OK&&mapped.int_val==25); /* A separate empty FIN completes the buffered message in both paths. */ char empty_fin_message[]="{\"data\":{\"temperature\":26}}"; @@ -553,7 +549,7 @@ static void source_cases(void) sio_websocket_event_handler(stream,NULL,WEBSOCKET_EVENT_DATA,&part); assert(stream->pending_json&&!strcmp(stream->pending_json,empty_fin_message)); ws_test_handler(&test,NULL,WEBSOCKET_EVENT_DATA,&part); - assert(test.received&&!strcmp(test.message,empty_fin_message));free(test.message);test_process_pending(stream); + assert(test.received&&!strcmp(test.sample.data,empty_fin_message));free(test.sample.data);test_process_pending(stream); assert(ts_variable_get("plain_ws.temperature",&mapped)==ESP_OK&&mapped.int_val==26); char next_message[]="{\"data\":{\"temperature\":27}}"; part=(esp_websocket_event_data_t){.data_ptr=next_message,.data_len=(int)strlen(next_message),.payload_len=(int)strlen(next_message),.fin=true,.op_code=1}; diff --git a/tests/runtime/test_automation_file.c b/tests/runtime/test_automation_file.c index 74122b06..616b5835 100644 --- a/tests/runtime/test_automation_file.c +++ b/tests/runtime/test_automation_file.c @@ -16,6 +16,8 @@ static int test_rename(const char *, const char *); #define mkdir(path, mode) test_mkdir(path, mode) #define unlink(path) test_unlink(path) #define rename(from, to) test_rename(from, to) +#include "../../components/ts_storage/src/ts_file_store.c" +#undef TAG #include "../../components/ts_automation/src/ts_automation_file.c" #undef fopen #undef stat @@ -72,7 +74,8 @@ static void loaded(ts_auto_file_location_t location,const char *expected) static void interrupted(ts_auto_file_location_t location) { const paths_t *p=&s_paths[location]; - assert(write_pending(p->pending,new_json)==ESP_OK); + bool created; + assert(store_prepare(p->pending,new_json,strlen(new_json),&created)==ESP_OK && created); assert(test_rename(p->current,p->previous)==0); loaded(location,old_json); } diff --git a/tests/runtime/test_automation_legacy.c b/tests/runtime/test_automation_legacy.c index c7917c0b..b613a17e 100644 --- a/tests/runtime/test_automation_legacy.c +++ b/tests/runtime/test_automation_legacy.c @@ -73,6 +73,9 @@ static ts_config_pack_result_t decrypted_fixture(const char *text,size_t length, { if(reject_pack)return TS_CONFIG_PACK_ERR_SIGNATURE; *out=calloc(1,sizeof(**out));assert(*out); + (*out)->acceptance.policy=1;(*out)->acceptance.accepted_at=1; + memset((*out)->acceptance.package_sha256,'a',64);memset((*out)->acceptance.signer_sha256,'b',64); + memset((*out)->acceptance.root_sha256,'c',64);memset((*out)->acceptance.recipient,'d',64); (*out)->content=strndup(text,length);(*out)->content_len=length;return TS_CONFIG_PACK_OK; } ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text,size_t length, @@ -84,9 +87,10 @@ ts_config_pack_result_t ts_config_pack_load_verified_mem(const char *text,size_t if(missing_signing_root)return TS_CONFIG_PACK_ERR_TRUST_NOT_CONFIGURED; return decrypted_fixture(text,length,out); } -ts_config_pack_result_t ts_config_pack_load_mem(const char *text,size_t length,ts_config_pack_t **out) +ts_config_pack_result_t ts_config_pack_load_rule_mem(const char *text,size_t length,ts_config_pack_t **out) { ++pack_calls;++raw_pack_calls; + if(missing_signing_root)return TS_CONFIG_PACK_ERR_TRUST_NOT_CONFIGURED; return decrypted_fixture(text,length,out); } void ts_config_pack_free(ts_config_pack_t *pack) { free(pack->content);free(pack); } @@ -182,7 +186,9 @@ int main(void) assert(!strcmp(error.reason,"signature_invalid")); reset();snprintf(path,sizeof(path),"%s/sources",test_root);assert(!mkdir(path,0775));reject_pack=false;missing_signing_root=true; write_file("sources/card.tscfg","{\"type\":\"automation_source\",\"source\":{\"id\":\"card\",\"type\":\"rest\",\"enabled\":true,\"url\":\"http://192.0.2.10/status\",\"method\":\"GET\",\"auth_header\":\"synthetic-token\",\"json_path\":\"data.power\",\"mappings\":[{\"json_path\":\"data.power\",\"var_name\":\"card.power\"}]}}"); - json=read_config(true);assert(raw_pack_calls==1); + assert(ts_auto_legacy_read(true,&json,&error)!=ESP_OK&&!json&&raw_pack_calls==1); + assert(!strcmp(error.reason,"signing_trust_unconfigured"));missing_signing_root=false; + json=read_config(true);assert(raw_pack_calls==2); ts_auto_document_t *document=NULL;assert(ts_auto_document_decode(json,&document,&error)==ESP_OK); assert(document->source_count==1 && document->sources[0].type==TS_AUTO_SRC_REST && !strcmp(document->sources[0].rest.url,"http://192.0.2.10/status") && diff --git a/tests/runtime/test_browser_origin.py b/tests/runtime/test_browser_origin.py new file mode 100644 index 00000000..be85dd53 --- /dev/null +++ b/tests/runtime/test_browser_origin.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Actual generated SDK dispatch/header reader, Host/Origin policy, HTTP/HTTPS +wrappers, body receiver, CORS and options handler. Synthetic socket/TLS/auth/IO. +No device, DNS lookup or external service. --probe-output builds a local browser bridge. +""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile,json +ROOT=Path(__file__).resolve().parents[2];IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf')) +p=argparse.ArgumentParser();p.add_argument('--source-package');p.add_argument('--probe-output');p.add_argument('--allow-origin',default='');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + q=subprocess.run(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT)),capture_output=True,text=True);return q.stdout if q.returncode==0 else None + return (ROOT/path).read_text() if (ROOT/path).exists() else None +def function(text,name): + m=re.search(r'^(?:static )?[^\n;]+\b'+name+r'\([^;]+?\)\s*\{',text,re.M);assert m,name + return text[m.start():text.index('\n}',m.start())+2]+'\n' +policy=source('components/ts_net/src/ts_http_origin.c') +code=r""" +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define CONFIG_HTTPD_WS_SUPPORT 1 +#define CONFIG_HTTPD_MAX_URI_LEN 256 +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 +#define CONFIG_TS_WEBUI_CORS_ENABLE 1 +#define CONFIG_LWIP_LOCAL_HOSTNAME "rm01" +#define TS_HTTP_ORIGIN_MAX_BYTES 288 +#define TS_NET_HOSTNAME_MAX_LEN 32 +#define ESP_OK 0 +#define ESP_FAIL -1 +#define ESP_ERR_NO_MEM 0x101 +#define ESP_ERR_INVALID_ARG 0x102 +#define ESP_ERR_INVALID_STATE 0x103 +#define ESP_ERR_INVALID_SIZE 0x104 +#define ESP_ERR_NOT_FOUND 0x105 +#define ESP_ERR_NOT_ALLOWED 0x106 +#define ESP_ERR_HTTPD_RESULT_TRUNC 0x7007 +#define HTTP_GET 0 +#define HTTP_POST 1 +#define HTTP_OPTIONS 2 +#define HTTPD_400_BAD_REQUEST 400 +#define HTTPD_403_FORBIDDEN 403 +#define HTTPD_404_NOT_FOUND 404 +#define HTTPD_405_METHOD_NOT_ALLOWED 405 +#define HTTPD_500_INTERNAL_SERVER_ERROR 500 +#define HTTPD_SOCK_ERR_TIMEOUT -2 +#define UF_PATH 0 +#define ESP_LOGD(...) ((void)0) +#define ESP_LOGW(...) ((void)0) +#define LOG_FMT(x) x +static bool s_stopping; +typedef int esp_err_t,httpd_err_code_t; +static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;} +typedef struct httpd_req httpd_req_t; +typedef esp_err_t (*sdk_handler_t)(httpd_req_t *); +struct sock_db {int fd;bool ws_handshake_done,ws_control_frames;sdk_handler_t ws_handler;void *ws_user_ctx;}; +struct http_parser_url {unsigned field_set;struct {size_t off,len;} field_data[1];}; +struct httpd_req_aux {char *scratch;size_t scratch_cur_size;unsigned req_hdrs_count;struct http_parser_url url_parse_res;bool ws_handshake_detect;struct sock_db *sd;}; +struct httpd_req {void *handle,*user_ctx,*aux;const char *uri;int method;size_t content_len;}; +struct httpd_data {httpd_req_t hd_req;struct httpd_req_aux hd_req_aux;}; +typedef struct {bool is_websocket,handle_ws_control_frames;int method;void *user_ctx;sdk_handler_t handler;const char *supported_subprotocol;} httpd_uri_t; +typedef struct {httpd_req_t *req;const char *uri;int method;char *body;size_t body_len;char cors_origin[TS_HTTP_ORIGIN_MAX_BYTES];} ts_http_request_t; +typedef struct {esp_err_t (*handler)(ts_http_request_t *,void *);void *user_data;bool requires_auth;unsigned required_level;bool (*admit)(ts_http_request_t*,void*);size_t max_body_bytes;uint32_t body_timeout_ms;} ts_http_route_t; +static unsigned checks,failures,lookups,upgrades,peers,businesses,body_reads,allocations,auth_checks; +static int status;static bool tls,socket_error,authorized; +static struct sockaddr_storage socket_address; +static const char *acao,*vary,*acam,*acah;static char captured_acao[288],captured_vary[32],captured_acam[96],captured_acah[96]; +static const char *redirect_location;static char saved_redirect[1400];static bool redirect_no_store,redirect_no_referrer; +static char raw_headers[2048];static unsigned raw_count;static size_t raw_used; +static void check(bool b,const char *why){++checks;if(!b){++failures;fprintf(stderr,"FAIL %s\n",why);}} +static bool httpd_valid_req(httpd_req_t *r){return r&&r->aux;} +static void *httpd_get_global_transport_ctx(void *handle){(void)handle;return tls?(void*)1:NULL;} +static int httpd_req_to_sockfd(httpd_req_t *r){(void)r;return 17;} +static int test_getsockname(int fd,struct sockaddr *out,socklen_t *len){assert(fd==17);if(socket_error)return -1;memcpy(out,&socket_address,sizeof(socket_address));*len=sizeof(socket_address);return 0;} +#define getsockname test_getsockname +static esp_err_t ts_net_copy_hostname(char *out,size_t n){snprintf(out,n,"ControlUnit");return ESP_OK;} +static esp_err_t ts_net_manager_copy_hostname(char *out,size_t n){snprintf(out,n,"rack-node");return ESP_OK;} +static void capture(void){if(redirect_location)snprintf(saved_redirect,sizeof(saved_redirect),"%s",redirect_location);if(acao)snprintf(captured_acao,sizeof(captured_acao),"%s",acao);if(vary)snprintf(captured_vary,sizeof(captured_vary),"%s",vary);if(acam)snprintf(captured_acam,sizeof(captured_acam),"%s",acam);if(acah)snprintf(captured_acah,sizeof(captured_acah),"%s",acah);} +static int httpd_resp_set_hdr(httpd_req_t *r,const char *name,const char *value){(void)r;if(!strcmp(name,"Location"))redirect_location=value;if(!strcmp(name,"Cache-Control")&&!strcmp(value,"no-store"))redirect_no_store=true;if(!strcmp(name,"Referrer-Policy")&&!strcmp(value,"no-referrer"))redirect_no_referrer=true;if(!strcmp(name,"Access-Control-Allow-Origin"))acao=value;if(!strcmp(name,"Vary"))vary=value;if(!strcmp(name,"Access-Control-Allow-Methods"))acam=value;if(!strcmp(name,"Access-Control-Allow-Headers"))acah=value;return ESP_OK;} +static int httpd_resp_set_status(httpd_req_t *r,const char *text){(void)r;status=atoi(text);return ESP_OK;} +static int httpd_resp_sendstr(httpd_req_t *r,const char *text){(void)r;(void)text;if(!status)status=200;capture();return ESP_OK;} +static int httpd_resp_send_err(httpd_req_t *r,int code,const char *text){(void)r;(void)text;status=code;capture();return ESP_OK;} +static int httpd_req_handle_err(httpd_req_t *r,int code){return httpd_resp_send_err(r,code,"fixture");} +static void *allocate(size_t n){++allocations;return malloc(n);} +#define TS_MALLOC_PSRAM allocate +static int httpd_req_recv(httpd_req_t *r,char *out,size_t n){(void)r;memset(out,'x',n);++body_reads;return (int)n;} +static bool ts_http_authorize_route(ts_http_request_t *r,const ts_http_route_t *route){++auth_checks;if(!route->requires_auth||authorized)return true;httpd_resp_send_err(r->req,401,"Unauthorized");return false;} +static esp_err_t ts_http_send_error(ts_http_request_t *r,int code,const char *why){return httpd_resp_send_err(r->req,code,why);} +static esp_err_t ts_http_send_response(ts_http_request_t *r,int code,const char *type,const char *body){(void)type;(void)body;status=code;capture();return ESP_OK;} +""" +with tempfile.TemporaryDirectory(prefix='ts-origin-sdk-source-') as tmp: + namespace={'__name__':'origin_sdk_generator'};exec(compile(source('tools/prepare_httpd_admission.py'),'prepare_httpd_admission.py','exec'),namespace);namespace['prepare'](IDF,Path(tmp)) + sdk_uri=(Path(tmp)/'httpd_uri.c').read_text() if (Path(tmp)/'httpd_uri.c').exists() else (IDF/'components/esp_http_server/src/httpd_uri.c').read_text() + sdk_parse=(Path(tmp)/'httpd_parse.c').read_text() if (Path(tmp)/'httpd_parse.c').exists() else None + if policy: + code+=function(sdk_parse,'ts_httpd_get_single_header') + code+=re.sub(r'^#include[^\n]*\n','',policy,flags=re.M)+'\n' +http=source('components/ts_net/src/ts_http_server.c') +for name in ['ts_http_set_cors','ts_http_admit_body','ts_http_receive_body','http_handler_wrapper']:code+=function(http,name) +code+=function(source('components/ts_net/src/ts_https_server.c'),'https_handler_wrapper') +code+=function(source('components/ts_webui/src/ts_webui_api.c'),'options_handler') +code+=r""" +static esp_err_t business(ts_http_request_t *r,void *ctx){(void)ctx;++businesses;assert(r->body_len==r->req->content_len);if(r->body_len)assert(r->body[r->body_len]==0);ts_http_set_cors(r,"*");return httpd_resp_sendstr(r->req,"{\"ok\":true}");} +static esp_err_t peer(httpd_req_t *r){(void)r;++peers;return ESP_OK;} +static esp_err_t httpd_ws_respond_server_handshake(httpd_req_t *r,const char *protocol){(void)r;(void)protocol;++upgrades;status=101;return ESP_OK;} +static httpd_uri_t selected; +static httpd_uri_t *httpd_find_uri_handler(struct httpd_data *h,const char *u,size_t n,int method,httpd_err_code_t *error){(void)h;(void)u;(void)n;(void)method;(void)error;++lookups;return &selected;} +"""+function(sdk_uri,'httpd_uri') +code+='#define HAS_POLICY '+str(int(bool(policy)))+'\n' +code+=r""" +static void header(const char *name,const char *value){if(!value)return;size_t n=strlen(name)+strlen(value)+3;assert(raw_used+nsin6_family=AF_INET6;a->sin6_port=htons(port);assert(inet_pton(AF_INET6,local_ip,&a->sin6_addr)==1);} + else {struct sockaddr_in *a=(void*)&socket_address;a->sin_family=AF_INET;a->sin_port=htons(port);assert(inet_pton(AF_INET,local_ip,&a->sin_addr)==1);} +} +static int dispatch(const char *host,const char *origin,unsigned kind,bool duplicate_host,bool duplicate_origin,bool needs_auth){ + header("Host",host);header("Origin",origin);header("X-Unrelated","metadata");if(duplicate_host)header("hOsT",host);if(duplicate_origin)header("ORIGIN",origin); + struct sock_db sd={.fd=17};struct httpd_data hd={0};hd.hd_req_aux=(struct httpd_req_aux){.scratch=raw_headers,.scratch_cur_size=raw_used,.req_hdrs_count=raw_count,.url_parse_res={.field_set=1,.field_data={{0,8}}},.ws_handshake_detect=kind==2,.sd=&sd}; + hd.hd_req=(httpd_req_t){.handle=&hd,.aux=&hd.hd_req_aux,.uri="/fixture",.method=(kind==2||kind==4)?HTTP_GET:kind==3?HTTP_OPTIONS:HTTP_POST,.content_len=(kind==2||kind==3||kind==4)?0:7}; + ts_http_route_t route={.handler=kind==3?options_handler:business,.requires_auth=needs_auth};selected=(httpd_uri_t){.is_websocket=(kind==2||kind==4),.method=hd.hd_req.method,.user_ctx=&route,.handler=(kind==2||kind==4)?peer:kind==1?https_handler_wrapper:http_handler_wrapper}; + return httpd_uri(&hd); +} +static void request(const char *host,const char *origin,bool allowed,unsigned kind){ + reset(kind==1,"192.168.1.4",kind==1?443:80);int ret=dispatch(host,origin,kind,false,false,false); + if(allowed){check(ret==ESP_OK,"known device/explicit authority and admitted origin remain usable");check(lookups==1,"admitted request enters actual SDK route lookup");if(kind==2)check(upgrades==1&&peers==1&&!businesses,"allowed WS upgrades before its peer handler");else if(kind==3)check(status==204&&!businesses&&!body_reads&&!allocations,"valid preflight is metadata only");else check(businesses==1&&auth_checks==2&&body_reads==1&&allocations==1,"HTTP/HTTPS executes one business after route auth before and after the single body read"); + if(kind!=2)check(origin?!strcmp(captured_acao,origin)&&!strcmp(captured_vary,"Origin"):!captured_acao[0],"CORS echoes only verified original origin; CLI has no wildcard");} + else {check(ret!=ESP_OK&&status>=400,"untrusted/malformed request is rejected");check(!lookups&&!upgrades&&!peers&&!businesses&&!auth_checks&&!body_reads&&!allocations,"rejected before route lookup, WS101, auth/body allocation or any business");check(!captured_acao[0],"denied origins get no ACAO");} +} +#if HAS_POLICY +static void strict_headers(void){ + reset(false,"192.168.1.4",80);header("Host","\t rm01.local\t ");header("Origin",""); + struct httpd_req_aux aux={.scratch=raw_headers,.scratch_cur_size=raw_used,.req_hdrs_count=raw_count};httpd_req_t req={.aux=&aux};char out[32]; + check(ts_httpd_get_single_header(&req,"HOST",out,sizeof(out))==ESP_OK&&!strcmp(out,"rm01.local"),"strict SDK reader trims only surrounding OWS"); + check(ts_httpd_get_single_header(&req,"origin",out,sizeof(out))==ESP_OK&&!out[0],"empty Origin remains present rather than CLI absence"); + check(ts_httpd_get_single_header(&req,"Missing",out,sizeof(out))==ESP_ERR_NOT_FOUND,"absent header is distinguishable"); + check(ts_httpd_get_single_header(&req,"Host",out,1)==ESP_ERR_HTTPD_RESULT_TRUNC&&!out[0],"short output never returns a truncated identity"); + header("hOsT","rm01.local");aux.scratch_cur_size=raw_used;aux.req_hdrs_count=raw_count; + check(ts_httpd_get_single_header(&req,"Host",out,sizeof(out))==ESP_ERR_INVALID_ARG,"identical mixed-case duplicate remains ambiguous"); + aux.req_hdrs_count=1;aux.scratch_cur_size=5;check(ts_httpd_get_single_header(&req,"Host",out,sizeof(out))==ESP_ERR_INVALID_ARG,"unterminated SDK scratch is refused within allocation bounds"); + aux.scratch_cur_size=0;check(ts_httpd_get_single_header(&req,"Host",out,sizeof(out))==ESP_ERR_INVALID_ARG,"empty scratch cannot claim parsed header"); + aux.scratch=NULL;check(ts_httpd_get_single_header(&req,"Host",out,sizeof(out))==ESP_ERR_INVALID_ARG,"missing SDK scratch fails closed"); + aux.req_hdrs_count=0;check(ts_httpd_get_single_header(&req,"Origin",out,sizeof(out))==ESP_ERR_NOT_FOUND,"zero parsed headers is ordinary absence"); + check(ts_httpd_get_single_header(NULL,"Host",out,sizeof(out))==ESP_ERR_INVALID_ARG,"invalid SDK request fails closed"); + check(ts_httpd_get_single_header(&req,NULL,out,sizeof(out))==ESP_ERR_INVALID_ARG,"invalid header argument fails closed"); +} +#endif +static void ordinary_ws_get(void){ + for(unsigned tls=0;tls<2;tls++)for(unsigned attempt=0;attempt<32;attempt++){ + reset(tls,"192.168.1.4",tls?443:80); + int ret=dispatch(tls?"192.168.1.4:443":"192.168.1.4",NULL,4,false,false,false); + check(ret!=ESP_OK&&status==400,"ordinary GET to WS-only route closes with400"); + check(lookups==1&&!upgrades&&!peers&&!businesses&&!auth_checks&&!body_reads&&!allocations,"missing Upgrade never reaches application peer owner or body allocation"); + } +} + +static int unit(void){ + if(CONFIG_CASE==0)for(unsigned kind=0;kind<4;kind++){request("public.example","https://public.example",true,kind);request("public.example:8443","https://public.example:8443",true,kind);request("public.example","https://foreign.example",false,kind);} + const char *known_hosts[]={"192.168.1.4","192.168.1.4:80","rm01","RM01.LOCAL","controlunit.local","rack-node.local"}; + const char *origins[]={NULL,"http://192.168.1.4","https://192.168.1.4","http://192.168.1.4:8080","http://evil.test","null","","http://192.168.1.4/","http://user@192.168.1.4","http://192.168.1.4 http://evil.test","http://192.168.1.4:0","http://192.168.1.4:65536"}; + if(CONFIG_CASE==2){for(unsigned kind=0;kind<4;kind++)request("192.168.1.4",NULL,false,kind);goto done;} + if(CONFIG_CASE==1){ + for(unsigned kind=0;kind<4;kind++){request(kind==1?"192.168.1.4:443":"192.168.1.4","https://dashboard.example",true,kind);request("proxy.example:9000","http://proxy.example:9000",true,kind);request("dashboard.example","https://dashboard.example",true,kind);request("dashboard.example",NULL,true,kind);request("unknown.example","https://dashboard.example",true,kind);request("proxy.example:9001","http://proxy.example:9000",true,kind);}goto done; + } + for(unsigned kind=0;kind<4;kind++){ + for(unsigned h=0;hhd_req;',' /* changed request ownership */')) + try:namespace['prepare'](Path(tmp),Path(tmp)/'output') + except ValueError:pass + else:raise AssertionError('SDK URI source drift silently omitted admission') + print('PASS 19 build-origin configuration cases; actual SDK dispatch anchor drift fails closed; installed SDK unchanged') +def build(path,configuration,case): + c=Path(str(path)+'.c');c.write_text(code.replace('CONFIG_CASE',str(case))) + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize='+os.environ.get('ORIGIN_TEST_SANITIZER','address,undefined'),'-fno-sanitize-recover=all','-DTS_HTTP_TRUSTED_ORIGINS='+json.dumps(configuration),str(c),'-o',str(path)],check=True) +if args.probe_output: + build(Path(args.probe_output),args.allow_origin,0);print(args.probe_output) +else: + with tempfile.TemporaryDirectory(prefix='ts-browser-origin-') as tmp: + for case,conf in [(0,''),(1,'https://dashboard.example,http://proxy.example:9000'),(2,'*')]: + exe=Path(tmp)/str(case);build(exe,conf,case);subprocess.run([str(exe)],check=True,timeout=20) + if policy: + configuration_checks() diff --git a/tests/runtime/test_cert_admission.py b/tests/runtime/test_cert_admission.py new file mode 100644 index 00000000..0d29369a --- /dev/null +++ b/tests/runtime/test_cert_admission.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Actual registry/dispatcher/cert registration; PKI effect boundary is a counter.""" +from pathlib import Path +import argparse,os,re,subprocess,tempfile + +ROOT=Path(__file__).resolve().parents[2] +IDF=Path(os.environ.get("IDF_PATH","/Users/massif/esp/v5.5.2/esp-idf")) +parser=argparse.ArgumentParser() +parser.add_argument("--source-ref") +args=parser.parse_args() +def source(path): + return subprocess.check_output(["git","show",f"{args.source_ref}:{path}"],cwd=ROOT,text=True) if args.source_ref else (ROOT/path).read_text() +def function(s,name): + m=re.search(r"^(?:static )?[^\n;]+\b"+name+r"\([^;]+?\)\s*\{",s,re.M);assert m,name + return s[m.start():s.index("\n}",m.start())+2]+"\n" +api=source("components/ts_api/src/ts_api.c") +api=api[:api.index("\nesp_err_t ts_api_register_all(void)")] +api=re.sub(r"^#include[^\n]*\n","",api,flags=re.M) +code=r''' +#define _DEFAULT_SOURCE +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 +#include +#include +#include +#include +#include +#include +#include "ts_api.h" +#include "ts_security.h" +#include "freertos/semphr.h" +#define TS_LOGD(...) ((void)0) +#define TS_LOGI(...) ((void)0) +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +static bool fail_permission_copy; +static char *registry_strdup(const char *s){return fail_permission_copy&&!strcmp(s,"cert.manage")?NULL:strdup(s);} +#define TS_STRDUP_PSRAM registry_strdup +#define MALLOC_CAP_SPIRAM 1 +#define MALLOC_CAP_8BIT 2 +static unsigned mutations,reads,checks,failures; +static int allocation_budget=-1; +static void *metadata_malloc(size_t n){if(allocation_budget==0)return NULL;if(allocation_budget>0)--allocation_budget;return malloc(n);} +static void check(bool value,const char *label){checks++;if(!value){failures++;fprintf(stderr,"FAIL %s\n",label);}} +static void *heap_caps_calloc(size_t n,size_t size,unsigned caps){(void)caps;return calloc(n,size);} +static cJSON *ts_config_pack_parse_import_request(const char *s,size_t n){(void)n;return cJSON_Parse(s);} +esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){ + if(sid==6){memset(out,0,sizeof(*out));out->session_id=sid;out->level=TS_PERM_NONE;return ESP_OK;} + if(sid<1||sid>4)return ESP_ERR_NOT_FOUND; + memset(out,0,sizeof(*out));out->session_id=sid;out->level=(ts_perm_level_t)sid;return ESP_OK; +} +esp_err_t ts_storage_check_write_path(const char *s,bool children){(void)s;(void)children;return ESP_OK;} +''' +code+=api +code+=r''' +static esp_err_t mutation(const cJSON *p,ts_api_result_t *r){(void)p;++mutations;ts_api_result_ok(r,cJSON_CreateObject());return ESP_OK;} +static esp_err_t readonly(const cJSON *p,ts_api_result_t *r){(void)p;++reads;ts_api_result_ok(r,cJSON_CreateObject());return ESP_OK;} +#define api_cert_status readonly +#define api_cert_get_certificate readonly +#define api_cert_generate_keypair mutation +#define api_cert_generate_csr mutation +#define api_cert_install mutation +#define api_cert_install_ca mutation +#define api_cert_delete mutation +''' +code+=function(source("components/ts_api/src/ts_api_cert.c"),"ts_api_cert_register") +code+=r''' +int main(void){ + check(ts_api_init()==ESP_OK,"actual registry init"); + check(ts_api_cert_register()==ESP_OK,"actual certificate registration"); + cJSON *list=ts_api_list(TS_API_CAT_SECURITY); + check(cJSON_GetArraySize(list)==7,"all certificate registrations covered");cJSON_Delete(list); + ts_api_endpoint_t copy_test={.name="fixture.failed_permission",.description="fixture",.handler=mutation,.permission="cert.manage",.external_access=TS_API_ACCESS_ROOT,.allowed_methods=TS_API_METHOD_WRITE}; + fail_permission_copy=true; + check(ts_api_register(©_test)==ESP_ERR_NO_MEM,"permission-copy failure rejects registration"); + cJSON *failed_entry=ts_api_get_info(copy_test.name); + check(failed_entry==NULL,"failed policy cannot leave an admitted entry"); + fail_permission_copy=false; + /* No malformed slot or duplicate remains after a failed registration. */ + if(failed_entry){cJSON_Delete(failed_entry);ts_api_unregister(copy_test.name);} + check(ts_api_register(©_test)==ESP_OK,"failed slot reusable"); + check(ts_api_unregister(copy_test.name)==ESP_OK,"test operation cleanup"); + const char *writes[]={"cert.generate_keypair","cert.generate_csr","cert.install","cert.install_ca","cert.delete"}; + const uint32_t identities[]={0,1,2,3,4,5,99}; + cJSON *params=cJSON_Parse("{\"session_id\":4,\"role\":\"root\",\"permission\":\"cert.manage\"}"); + for(unsigned n=0;n<5;n++){ + cJSON *info=ts_api_get_info(writes[n]); + check(cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(info,"requires_auth")),"mutation declares authentication"); + const char *permission=cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(info,"permission")); + check(permission&&!strcmp(permission,"cert.manage"),"mutation declares management capability");cJSON_Delete(info); + for(unsigned i=0;iname); + if(expected[i].raw_auth>=0)check(endpoint->requires_auth==expected[i].raw_auth,"raw source auth flag retains prior focused assertion"); + return ts_api_register(endpoint); +} +static esp_err_t checked_multiple(const ts_api_endpoint_t *endpoints,size_t count){ + for(size_t i=0;i0),"role matches independent policy, including TOKEN vs PUBLIC"); + check(access.allowed_methods==expected[i].methods,"method declaration matches independent contract"); + cJSON *info=ts_api_get_info(name); + check(info&&cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(info,"requires_auth"))==(level>0),"serialized auth metadata agrees with independent role");cJSON_Delete(info); + for(unsigned j=0;j=level&&ids[j]<=4);ts_api_result_t result={0}; + esp_err_t rc=ts_api_call_for_session(name,params,ids[j],&result); + if((rc==ESP_OK)!=allowed)fprintf(stderr,"ADMISSION name=%s sid=%u mode=%u expected=%u code=%u\n",name,ids[j],access.external_access,allowed,result.code); + check((rc==ESP_OK)==allowed,"verified C role decides admission; forged JSON and valid NONE cannot elevate"); + check(mutations==before+allowed,"denial never reaches substituted business boundary");ts_api_result_free(&result); + } + } + const char *internal[]={"cert.install","fan.set","system.reboot","config.set","time.sync","ssh.exec","auth.root.set_password","monitor.set_server"}; + for(unsigned i=0;i #include diff --git a/tests/runtime/test_compute_monitor.py b/tests/runtime/test_compute_monitor.py index e764bb33..055a4093 100644 --- a/tests/runtime/test_compute_monitor.py +++ b/tests/runtime/test_compute_monitor.py @@ -9,6 +9,20 @@ code = RTOS.replace('int held;} *TaskHandle_t;', 'int held;atomic_bool deleted;} *TaskHandle_t;') + r''' #include "ts_compute_monitor.h" #include "cJSON.h" +#include "ts_http_fetch.h" +#include +static char monitor_diagnostics[32768]; +static pthread_mutex_t diagnostics_mutex=PTHREAD_MUTEX_INITIALIZER; +static void monitor_log(const char *tag,const char *format,...){(void)tag;pthread_mutex_lock(&diagnostics_mutex);size_t used=strlen(monitor_diagnostics);va_list args;va_start(args,format);vsnprintf(monitor_diagnostics+used,sizeof(monitor_diagnostics)-used,format,args);va_end(args);pthread_mutex_unlock(&diagnostics_mutex);} +#undef ESP_LOGI +#undef ESP_LOGD +#undef ESP_LOGW +#undef ESP_LOGE +#define ESP_LOGI monitor_log +#define ESP_LOGD monitor_log +#define ESP_LOGW monitor_log +#define ESP_LOGE monitor_log + #ifndef ESP_ERR_NOT_ALLOWED #define ESP_ERR_NOT_ALLOWED 0x10d #endif @@ -20,8 +34,6 @@ TS_EVT_AGX_CONNECTED=100,TS_EVT_AGX_DISCONNECTED,TS_EVT_AGX_ERROR,TS_EVT_AGX_DATA_UPDATED, WEBSOCKET_EVENT_ANY=-1,WEBSOCKET_EVENT_CONNECTED=1,WEBSOCKET_EVENT_DISCONNECTED, WEBSOCKET_EVENT_DATA,WEBSOCKET_EVENT_ERROR}; -typedef struct {const char *url;int timeout_ms;} esp_http_client_config_t; -typedef void *esp_http_client_handle_t; typedef struct {const char *uri;int buffer_size,reconnect_timeout_ms,network_timeout_ms,ping_interval_sec;} esp_websocket_client_config_t; typedef struct {const char *data_ptr;int data_len;} esp_websocket_event_data_t; typedef void (*ws_callback_t)(void *,esp_event_base_t,int32_t,void *); @@ -37,8 +49,15 @@ static atomic_int other_cleanup,data_posts,callback_data,retry_count,retry_skip; static int control_result,init_result,self_stop_result,self_deinit_result,self_driver_result; static bool self_check,fail_binary; +static atomic_ulong json_allocations,json_releases; +static void *count_json_alloc(size_t size){void *value=malloc(size);if(value)++json_allocations;return value;} +static void count_json_release(void *value){if(value)++json_releases;free(value);} + static unsigned retry_ms[16]; static char last_ws_url[256]; +static const char *handshake_payload="0{\"sid\":\"fixture-session\"}"; +static int handshake_status=200; + static SemaphoreHandle_t notifications[128]; static pthread_mutex_t notification_mutex=PTHREAD_MUTEX_INITIALIZER; static SemaphoreHandle_t notification(TaskHandle_t task) { @@ -98,20 +117,17 @@ } return ESP_OK; } -static esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *cfg){ - assert(cfg->timeout_ms==5000);return (void *)1; -} -static int esp_http_client_open(void *client,int n){ - (void)client;(void)n;++http_calls; +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request,ts_http_fetch_result_t *reply){ + assert(request->timeout_ms==5000&&request->maximum_body>0&&request->current&&request->context); + ++http_calls;memset(reply,0,sizeof(*reply)); if(hold_http){xSemaphoreGive(http_entered);assert(xSemaphoreTake(http_release,portMAX_DELAY));} - return mode==1?ESP_FAIL:ESP_OK; -} -static int esp_http_client_fetch_headers(void *client){(void)client;return 24;} -static int esp_http_client_read(void *client,char *out,int n){ - (void)client;const char *reply="0{\"sid\":\"fixture-session\"}";assert(n>(int)strlen(reply));strcpy(out,reply);return strlen(reply); + ++http_cleanup; + if(!request->current(request->context))return ESP_ERR_INVALID_STATE; + if(mode==1)return ESP_FAIL; + const char *payload=handshake_payload; + reply->status=handshake_status;reply->body=strdup(payload);reply->length=strlen(payload);reply->content_length=reply->length; + return reply->body?ESP_OK:ESP_ERR_NO_MEM; } -static int esp_http_client_close(void *client){(void)client;return ESP_OK;} -static int esp_http_client_cleanup(void *client){(void)client;++http_cleanup;return ESP_OK;} static int esp_websocket_client_send_text(esp_websocket_client_handle_t client,const char *text,int n,unsigned timeout){ (void)client;(void)timeout;assert(!strcmp(text,"2probe")||!strcmp(text,"5")||!strcmp(text,"3"));return n; } @@ -122,7 +138,7 @@ struct task local={0};current_task=&local;esp_websocket_client_handle_t client=arg; if(mode!=4){ emit(client,WEBSOCKET_EVENT_CONNECTED,NULL);emit(client,WEBSOCKET_EVENT_DATA,"3probe"); - emit(client,WEBSOCKET_EVENT_DATA,"42[\"tegrastats_update\",{\"temperature\":{\"cpu\":42.5},\"ram\":{\"used\":20,\"total\":100},\"gpu\":{\"gr3d_freq\":17}}]"); + emit(client,WEBSOCKET_EVENT_DATA,"42[\"tegrastats_update\",{\"temperature\":{\"cpu\":42.5},\"ram\":{\"used\":20,\"total\":100},\"gpu\":{\"gr3d_freq\":17},\"private_canary\":\"SYNTHETIC_RAW_MONITOR_CANARY\"}]"); } while(!client->stop)vTaskDelay(1);return NULL; } @@ -190,7 +206,10 @@ #define ts_compute_monitor_is_initialized cli_query_initialized ''' code += body('components/ts_api/src/ts_api_monitor.c', 'api_monitor_config') +# Observe the real CLI freeing its cJSON_PrintUnformatted buffer through libc free. +code += '\n#define free count_json_release\n' code += body('components/ts_console/commands/ts_cmd_monitor.c', 'do_monitor_config') +code += '\n#undef free\n' code += '\n#undef ts_compute_monitor_is_running\n#undef ts_compute_monitor_is_initialized\n' code += r''' @@ -241,6 +260,7 @@ } static pthread_t begin_control(int op){pthread_t t;control_done=false;assert(!pthread_create(&t,NULL,control,(void *)(intptr_t)op));return t;} int main(void){ + cJSON_Hooks json_hooks={.malloc_fn=count_json_alloc,.free_fn=count_json_release};cJSON_InitHooks(&json_hooks); SemaphoreHandle_t *signals[]={&init_entered,&init_release,&entry_entered,&entry_release,&create_entered,&create_release, ¬ify_entered,¬ify_release,&cleanup_entered,&http_entered,&http_release,&retry_entered,&callback_entered,&callback_release,&tail_entered,&tail_release}; for(unsigned i=0;ishould_stop,false); + const char *invalid_sid[]={"{}","0{\"sid\":\"\"}","0{\"sid\":3}","0{\"sid\":\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"}"}; + for(unsigned i=0;isession_id,"fixture-session")); + assert(ts_compute_monitor_deinit()==ESP_OK);join_workers(); + assert(!strstr(monitor_diagnostics,"fixture-session")&&!strstr(monitor_diagnostics,"SYNTHETIC_RAW_MONITOR_CANARY")); + puts("PASS actual monitor rejects empty/typed/oversized SID and bad status;global diagnostics contain neither session IDs nor raw response/event canaries"); for(unsigned i=0;i +#include +#include +#include +#include +#include +#include +#include +#include "ts_api.h" +#include "ts_security.h" +#include "ts_config_module.h" +#define TS_LOGD(...) ((void)0) +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +#define TS_STRDUP_PSRAM strdup +#define ESP_ERR_NOT_ALLOWED 0x10d +static unsigned reads,writes,calls,checks,failures; +static bool session_live=true,session_downgrade, revoke_during_read, downgrade_during_read; +static const char *row_response; +static bool effect_response, allocation_stop_after_effect; +static void *deny_allocation(size_t size){(void)size;return NULL;} +static char password[80]="SYNTHETIC_AP_PASSWORD"; +static void check(bool value,const char *label){checks++;if(!value){failures++;fprintf(stderr,"FAIL %s\n",label);}} +esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){ + if(!session_live||sid<1||sid>5)return ESP_ERR_NOT_FOUND; + memset(out,0,sizeof(*out));out->session_id=sid;out->level=sid==1?(session_downgrade?TS_PERM_READ:TS_PERM_ROOT):sid==2?TS_PERM_ADMIN:sid==3?TS_PERM_READ:sid==5?TS_PERM_WRITE:TS_PERM_NONE;return ESP_OK; +} +esp_err_t ts_storage_check_write_path(const char *p,bool children){(void)p;(void)children;return ESP_OK;} +bool ts_config_module_is_registered(ts_config_module_t m){return m==TS_CONFIG_MODULE_WIFI||m==TS_CONFIG_MODULE_SYSTEM;} +bool ts_config_module_is_dirty(ts_config_module_t m){(void)m;return false;} +esp_err_t ts_config_module_get_bool(ts_config_module_t m,const char *k,bool *v){(void)m;(void)k;reads++;*v=false;return ESP_OK;} +esp_err_t ts_config_module_get_uint(ts_config_module_t m,const char *k,uint32_t *v){(void)m;(void)k;reads++;*v=6;return ESP_OK;} +esp_err_t ts_config_module_get_string(ts_config_module_t m,const char *k,char *v,size_t n){ + reads++;if(revoke_during_read)session_live=false;if(downgrade_during_read)session_downgrade=true;const char *value=NULL; + if(m==TS_CONFIG_MODULE_WIFI){ + if(!strcmp(k,"mode"))value="ap"; + if(!strcmp(k,"ap.ssid"))value="Lab + 中文"; + if(!strcmp(k,"ap.password"))value=password; + } + if(m==TS_CONFIG_MODULE_SYSTEM&&!strcmp(k,"timezone"))value="UTC"; + if(!value)return ESP_ERR_NOT_FOUND;snprintf(v,n,"%s",value);return ESP_OK; +} +esp_err_t ts_config_module_set_bool(ts_config_module_t m,const char *k,bool v){(void)m;(void)k;(void)v;assert(false);return ESP_FAIL;} +esp_err_t ts_config_module_set_uint(ts_config_module_t m,const char *k,uint32_t v){(void)m;(void)k;(void)v;assert(false);return ESP_FAIL;} +esp_err_t ts_config_module_set_int(ts_config_module_t m,const char *k,int32_t v){(void)m;(void)k;(void)v;assert(false);return ESP_FAIL;} +esp_err_t ts_config_module_set_string(ts_config_module_t m,const char *k,const char *v){ + assert(m==TS_CONFIG_MODULE_WIFI&&!strcmp(k,"ap.password"));writes++;snprintf(password,sizeof(password),"%s",v);return ESP_OK; +} +esp_err_t ts_config_get_int64(const char *k,int64_t *v,int64_t d){(void)k;(void)v;(void)d;reads++;return ESP_ERR_NOT_FOUND;} +esp_err_t ts_config_get_bool(const char *k,bool *v,bool d){(void)k;(void)v;(void)d;reads++;return ESP_ERR_NOT_FOUND;} +esp_err_t ts_config_get_double(const char *k,double *v,double d){(void)k;(void)v;(void)d;reads++;return ESP_ERR_NOT_FOUND;} +esp_err_t ts_config_get_string(const char *k,char *v,size_t n,const char *d){ + (void)d;reads++;if(revoke_during_read)session_live=false;if(downgrade_during_read)session_downgrade=true;snprintf(v,n,"%s",!strcmp(k,"system.language")?"zh-CN":"SYNTHETIC_ARBITRARY_CREDENTIAL");return ESP_OK; +} +cJSON *ts_api_get_info(const char *name){ + cJSON *info=cJSON_CreateObject();cJSON_AddBoolToObject(info,"requires_auth",!strcmp(name,"config.module.set"));return info; +} +''' +for name in ["ts_api_result_init","ts_api_result_ok","ts_api_result_error","ts_api_result_free"]: + code+=function("components/ts_api/src/ts_api.c",name) +for name in ["parse_module_name","module_to_name","add_module_config_to_json","api_config_module_show","api_config_get","api_config_module_set"]: + code+=function("components/ts_api/src/ts_api_config.c",name) +code+='static char s_ota_server_url[256]=\"https://synthetic-user:synthetic-pass@example.invalid/?token=PRIVATE-CANARY\";\n' +code+=function('components/ts_api/src/ts_api_ota.c','api_ota_server_get') +code+=r''' +esp_err_t ts_api_call(const char *name,const cJSON *p,ts_api_result_t *result){ + calls++; + if(!strcmp(name,"config.module.show"))return api_config_module_show(p,result); + if(!strcmp(name,"config.get"))return api_config_get(p,result); + if(!strcmp(name,"config.module.set"))return api_config_module_set(p,result); + assert(false);return ESP_FAIL; +} +''' +# Coarse policy comes from the actual source descriptor table. This fixture +# controls the store/session boundary; the full real registry is tested separately. +configuration_source=subprocess.check_output(["git","show",f"{args.source_ref}:components/ts_api/src/ts_api_config.c"],cwd=ROOT,text=True) if args.source_ref else (ROOT/"components/ts_api/src/ts_api_config.c").read_text() +start=configuration_source.index("static const ts_api_endpoint_t config_apis[]") +end=configuration_source.index("\n };",start)+7 +metadata=configuration_source[start:end] +metadata=re.sub(r"\.handler\s*=\s*\w+", ".handler = NULL", metadata) +code+=metadata+"\n" +code+=r''' +esp_err_t ts_api_get_access(const char *name,ts_api_access_t *access){ + if(row_response){*access=(ts_api_access_t){.external_access=effect_response?TS_API_ACCESS_ADMIN:TS_API_ACCESS_READ,.minimum_level=effect_response?TS_PERM_ADMIN:TS_PERM_READ,.requires_auth=true,.allowed_methods=effect_response?TS_API_METHOD_WRITE:TS_API_METHOD_READ};return ESP_OK;} + for(unsigned i=0;iexternal_access; + *access=(ts_api_access_t){.external_access=mode,.allowed_methods=e->allowed_methods?e->allowed_methods:TS_API_METHOD_ALL}; + access->requires_auth=mode==TS_API_ACCESS_LEGACY?e->requires_auth:mode>=TS_API_ACCESS_READ&&mode<=TS_API_ACCESS_ROOT; + access->minimum_level=mode==TS_API_ACCESS_LEGACY?TS_PERM_READ:access->requires_auth?mode-TS_API_ACCESS_PUBLIC:TS_PERM_NONE;return ESP_OK; + } + return ESP_ERR_NOT_FOUND; +} +''' +code+=r''' +static esp_err_t private_row_handler(const cJSON *params,ts_api_result_t *result){ + (void)params;++calls;cJSON *data=cJSON_Parse(row_response); + if(!data){ts_api_result_error(result,TS_API_ERR_NO_MEM,"no_memory");return ESP_ERR_NO_MEM;} + ts_api_result_ok(result,data);if(allocation_stop_after_effect){cJSON_Hooks hooks={deny_allocation,free};cJSON_InitHooks(&hooks);}if(revoke_during_read)session_live=false;if(downgrade_during_read)session_downgrade=true; + return ESP_OK; +} +''' +code+='static esp_err_t api_call_dispatch(const char *name,const cJSON *p,uint32_t sid,bool external,ts_api_result_t *r){(void)sid;(void)external;return ts_api_call(name,p,r); }\n' +code+='static esp_err_t privacy_show(const cJSON *p,ts_api_result_t *r){calls++;return api_config_module_show(p,r);}\nstatic esp_err_t privacy_get(const cJSON *p,ts_api_result_t *r){calls++;return api_config_get(p,r);}\nstatic esp_err_t privacy_set(const cJSON *p,ts_api_result_t *r){calls++;return api_config_module_set(p,r);}\n/* The registry snapshot is the boundary in this store-focused fixture; actual\n * atomic registry replacement is covered in test_default_deny_policy.py. */\nstatic esp_err_t copy_external_call(const char *name,ts_api_access_t *access,ts_api_handler_t *handler,ts_api_session_handler_t *session_handler){\n esp_err_t ret=ts_api_get_access(name,access);if(ret!=ESP_OK)return ret;*session_handler=NULL;\n *handler=row_response?private_row_handler:!strcmp(name,"config.module.show")?privacy_show:!strcmp(name,"config.get")?privacy_get:privacy_set;return ESP_OK;\n}\n' +code+=function("components/ts_api/src/ts_api.c","project_config_fields",optional=True) +code+=function("components/ts_api/src/ts_api.c","config_read_projection",optional=True) +code+=function("components/ts_api/src/ts_api.c","project_result_fields",optional=True) +code+=function("components/ts_api/src/ts_api.c","private_result_projection",optional=True) +code+=function("components/ts_api/src/ts_api.c","ts_api_call_for_session") +code+=r''' +static void module(uint32_t sid,const char *name,bool secret){ + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"module",name); + ts_api_result_t result={0};unsigned before=writes,read_before=reads,call_before=calls; + esp_err_t ret=ts_api_call_for_session("config.module.show",p,sid,&result); + if(!session_live||sid<1||sid>5){ + check(ret!=ESP_OK,"anonymous/invalid/revoked module read refused");check(reads==read_before&&calls==call_before&&!result.data,"module denial before handler/store/secret"); + ts_api_result_free(&result);cJSON_Delete(p);return; + } + check(ret==ESP_OK,"authenticated module show succeeds"); + cJSON *wifi=cJSON_GetObjectItemCaseSensitive(result.data,!strcasecmp(name,"all")?"wifi":"config"); + check(cJSON_IsObject(wifi),"original single/all response shape"); + check(!!cJSON_GetObjectItemCaseSensitive(wifi,"ap.password")==secret,"AP password visible to authenticated administrators"); + check(cJSON_IsString(cJSON_GetObjectItemCaseSensitive(wifi,"ap.ssid")),"SSID remains available"); + check(cJSON_GetObjectItemCaseSensitive(wifi,"ap.channel")->valueint==6,"channel remains available"); + check(writes==before,"projection never writes settings"); + ts_api_result_free(&result);cJSON_Delete(p); +} + +static int json_allocations,json_fail_at; +static void *fail_json_allocation(size_t size){return ++json_allocations==json_fail_at?NULL:malloc(size);} +static void projection_checks(void){ + const char *names[]={"ssh.hosts.list","ssh.hosts.get","ssh.commands.list","ssh.commands.get","automation.sources.list","automation.rules.list","automation.rules.get","automation.actions.list","automation.actions.get","ota.server.get"}; + const char *collections[]={"hosts",NULL,"commands",NULL,"sources","rules",NULL,"templates",NULL,NULL}; + const char *row="{\"configured\":true,\"id\":\"public-id\",\"name\":\"Public name\",\"label\":\"Public label\",\"enabled\":true,\"host\":\"192.0.2.4\",\"port\":22,\"type\":\"rest\",\"runtime_active\":true,\"revision\":7,\"conditions_count\":2,\"actions_count\":3,\"trigger_count\":4,\"automatic_start\":{\"state\":\"waiting\",\"reason\":\"automatic_start_timeout\",\"retry_after_ms\":123,\"unknown\":\"PRIVATE-CANARY\"},\"ssh_commands\":[\"command-id\",{\"command\":\"PRIVATE-CANARY\"}],\"runtime_instance\":\"0000000000000001\",\"poll_interval_ms\":1000,\"connected\":true,\"mapping_count\":2,\"async\":false,\"use_count\":3,\"username\":\"PRIVATE-CANARY\",\"keyid\":\"PRIVATE-CANARY\",\"command\":\"PRIVATE-CANARY\",\"expectPattern\":\"PRIVATE-CANARY\",\"conditions\":[{\"expr\":\"PRIVATE-CANARY\"}],\"actions\":[{\"http\":{\"body\":\"PRIVATE-CANARY\"}}],\"rest_url\":\"https://example.invalid/?token=PRIVATE-CANARY\",\"auth_header\":\"PRIVATE-CANARY\",\"rest_auth\":\"PRIVATE-CANARY\",\"last_value\":\"PRIVATE-CANARY\",\"mappings\":[{\"secret\":\"PRIVATE-CANARY\"}],\"cli\":{\"command\":\"PRIVATE-CANARY\"},\"value\":\"PRIVATE-CANARY\",\"new_future_field\":{\"value\":\"PRIVATE-CANARY\"}}"; + cJSON *params=cJSON_Parse("{\"role\":\"root\",\"session_id\":1,\"include_private\":true,\"show_hidden\":true,\"fields\":\"*\"}"); + for(unsigned n=0;n0&&sid!=4;bool full=sid==1||(sid==2&&strcmp(names[n],"automation.sources.list")); + esp_err_t ret=ts_api_call_for_session(names[n],params,sid,&result); + check((ret==ESP_OK)==allowed,"configuration metadata enforces live C identity, including NONE and WRITE"); + if(!allowed)check(calls==before&&!result.data,"denied metadata never calls producer or returns rows"); + else { + char *json=cJSON_PrintUnformatted(result.data);check(json!=NULL,"metadata serializes"); + check((strstr(json,"PRIVATE-CANARY")!=NULL)==full,"all raw/nested/URL/unknown fields visible to original authenticated administrators"); + check(!strcmp(names[n],"ota.server.get") ? cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(result.data,"configured")) : strstr(json,"Public name")!=NULL,"approved names/labels or configured state preserved"); + check(cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(result.data,"restricted"))==(!full),"explicit projection marker"); + if(!full&&collections[n])check(cJSON_GetObjectItemCaseSensitive(result.data,"count")->valueint==1&&cJSON_IsArray(cJSON_GetObjectItemCaseSensitive(result.data,collections[n])),"list shape/count survives projection"); + cJSON *item=collections[n]?cJSON_GetArrayItem(cJSON_GetObjectItemCaseSensitive(result.data,collections[n]),0):result.data; + if(!full&&!strcmp(names[n],"automation.rules.list")){ + cJSON *start=cJSON_GetObjectItem(item,"automatic_start");check(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(start,"state")),"waiting")&&cJSON_GetObjectItem(start,"retry_after_ms")->valueint==123,"automatic restart status remains operational"); + check(cJSON_GetArraySize(cJSON_GetObjectItem(item,"ssh_commands"))==1,"service command ID references retained without arbitrary objects"); + } + if(!full&&!strcmp(names[n],"ssh.hosts.list"))check(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(item,"host")),"192.0.2.4"),"approved host address telemetry retained"); + free(json); + } + ts_api_result_free(&result); + } + for(int downgrade=0;downgrade<2;++downgrade){ + revoke_during_read=!downgrade;downgrade_during_read=downgrade;ts_api_result_t result={0}; + check(ts_api_call_for_session(names[n],params,1,&result)!=ESP_OK&&!result.data,"Root response discarded when revoked or downgraded during producer read"); + ts_api_result_free(&result);session_live=true;session_downgrade=revoke_during_read=downgrade_during_read=false; + } + for(int point=1;point<=256;++point){ + ts_api_result_t result={0};json_allocations=0;json_fail_at=point;cJSON_Hooks hooks={fail_json_allocation,free};cJSON_InitHooks(&hooks); + esp_err_t ret=ts_api_call_for_session(names[n],params,3,&result);cJSON_InitHooks(NULL); + if(ret!=ESP_OK)check(result.code!=TS_API_OK&&!result.data,"allocation failures expose no partial raw data"); + else {char *text=cJSON_PrintUnformatted(result.data);check(text&&!strstr(text,"PRIVATE-CANARY"),"every successful allocation outcome is projected");free(text);} + ts_api_result_free(&result); + } + } + + effect_response=true; + const char *effect="{\"async\":false,\"status\":\"done\",\"duration_ms\":42,\"output\":\"PRIVATE-CANARY\",\"detail\":\"PRIVATE-CANARY\",\"unknown\":\"PRIVATE-CANARY\"}"; + row_response=effect; + for(unsigned sid=0;sid<=5;++sid){ + ts_api_result_t result={0};unsigned before=calls;bool allowed=sid==1||sid==2; + esp_err_t ret=ts_api_call_for_session("automation.actions.execute",params,sid,&result); + check((ret==ESP_OK)==allowed&&calls==before+allowed,"existing action capability stays Admin/Root with one execution"); + if(allowed){char *json=cJSON_PrintUnformatted(result.data);check((strstr(json,"PRIVATE-CANARY")!=NULL)==(sid==1||sid==2),"private action output kept for original authenticated admin");check(cJSON_GetObjectItem(result.data,"duration_ms")->valueint==42,"duration and successful write outcome preserved");free(json);} + ts_api_result_free(&result); + } + for(unsigned changed=0;changed<3;++changed){ + ts_api_result_t result={0};unsigned before=calls;revoke_during_read=changed==0;downgrade_during_read=changed==1;allocation_stop_after_effect=changed==2; + unsigned sid=changed==2?2:1;esp_err_t ret=ts_api_call_for_session("automation.actions.execute",params,sid,&result);cJSON_InitHooks(NULL); + check(ret==ESP_OK&&result.code==TS_API_OK&&calls==before+1,"post-effect revoke/downgrade/OOM never creates a false failed write"); + char *json=cJSON_PrintUnformatted(result.data);check(json&&((strstr(json,"PRIVATE-CANARY")!=NULL)==(changed==2))&&cJSON_GetObjectItem(result.data,"duration_ms")->valueint==42,"live admin output preserved; revoked or downgraded acknowledgement safely redacted");free(json);ts_api_result_free(&result); + session_live=true;session_downgrade=revoke_during_read=downgrade_during_read=allocation_stop_after_effect=false; + } + effect_response=false;row_response=NULL;cJSON_Delete(params); +} +int main(void){ + projection_checks(); + const char *private_reads[]={"config.get","config.module.show"}; + for(unsigned operation=0;operation<2;++operation)for(unsigned changed=0;changed<2;++changed){ + cJSON *request=cJSON_Parse(operation?"{\"module\":\"wifi\"}":"{\"key\":\"custom.credential\"}");ts_api_result_t response={0}; + revoke_during_read=changed==0;downgrade_during_read=changed==1; + check(ts_api_call_for_session(private_reads[operation],request,1,&response)!=ESP_OK&&!response.data,"actual raw config/module read drops secret after in-flight Root revoke/downgrade"); + ts_api_result_free(&response);cJSON_Delete(request);session_live=true;session_downgrade=revoke_during_read=downgrade_during_read=false; + } + + ts_api_result_t ota={0}; + check(api_ota_server_get(NULL,&ota)==ESP_OK&&cJSON_IsTrue(cJSON_GetObjectItem(ota.data,"configured"))&&!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(ota.data,"url")),s_ota_server_url),"actual trusted getter keeps exact configured URL");ts_api_result_free(&ota); + s_ota_server_url[0]=0;check(api_ota_server_get(NULL,&ota)==ESP_OK&&cJSON_IsFalse(cJSON_GetObjectItem(ota.data,"configured"))&&!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(ota.data,"url")),""),"actual empty configuration distinguishable from redaction");ts_api_result_free(&ota); + + for(uint32_t sid=0;sid<=3;sid++){ + module(sid,"wifi",sid==1||sid==2);module(sid,"WiFi",sid==1||sid==2);module(sid,"all",sid==1||sid==2); + const char *keys[]={"system.language","custom.credential","ordinary.hostname"}; + for(unsigned i=0;i<3;i++){ + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"KeY",keys[i]); + cJSON_AddNumberToObject(p,"session_id",1);cJSON_AddStringToObject(p,"role","root"); + ts_api_result_t result={0};unsigned before=reads,submitted=calls; + bool allowed=i==0||sid==1||sid==2; + esp_err_t ret=ts_api_call_for_session("config.get",p,sid,&result); + check(allowed?ret==ESP_OK:ret!=ESP_OK,"generic raw config role policy"); + if(!allowed){check(reads==before&&calls==submitted,"raw denial before store/handler");check(!result.data,"denial exposes no value");} + else check(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(result.data,"value")),i==0?"zh-CN":"SYNTHETIC_ARBITRARY_CREDENTIAL"),"allowed config result preserved"); + ts_api_result_free(&result);cJSON_Delete(p); + } + } + session_live=false;module(1,"wifi",false);module(99,"all",false); + cJSON *p=cJSON_Parse("{\"key\":\"custom.credential\"}");ts_api_result_t result={0};unsigned before=reads; + check(ts_api_call_for_session("config.get",p,1,&result)!=ESP_OK&&reads==before,"revoked root cannot read raw config"); + ts_api_result_free(&result);cJSON_Delete(p);session_live=true; + p=cJSON_Parse("{\"module\":\"wifi\",\"key\":\"ap.password\",\"value\":\"NEW_SYNTHETIC_PASSWORD\"}"); + check(ts_api_call_for_session("config.module.set",p,3,&result)!=ESP_OK&&writes==0,"READ cannot change generic module settings");ts_api_result_free(&result); + check(ts_api_call_for_session("config.module.set",p,2,&result)==ESP_OK,"Original admin configuration update restored"); + ts_api_result_free(&result);cJSON_Delete(p); + check(writes==1&&!strcmp(password,"NEW_SYNTHETIC_PASSWORD"),"explicit supplied password retained, no mask writeback"); + module(2,"wifi",true);module(1,"wifi",true); + p=cJSON_Parse("{\"module\":\"wifi\"}");before=writes; + check(ts_api_call("config.module.show",p,&result)==ESP_OK,"trusted internal caller unchanged"); + check(cJSON_IsString(cJSON_GetObjectItemCaseSensitive(cJSON_GetObjectItemCaseSensitive(result.data,"config"),"ap.password")),"internal result retains original secret"); + check(writes==before,"all read paths leave stored credential unchanged"); + ts_api_result_free(&result);cJSON_Delete(p); + printf("%u checks, %u failures: actual policy/config handlers, synthetic store/session; no real secrets\n",checks,failures); + return failures?1:0; +} +''' +includes=[ROOT/"tests/runtime/rule_pack/stubs"] +includes += [ROOT/("components/"+p+"/include") for p in ["ts_api","ts_security","ts_core/ts_config"]] +includes += [IDF/"components/json/cJSON"] +with tempfile.TemporaryDirectory(prefix="ts-config-privacy-") as tmp: + c=Path(tmp)/"test.c";exe=Path(tmp)/"test";c.write_text(code) + subprocess.run(["cc","-std=gnu11","-g","-fsanitize=address,undefined","-fno-sanitize-recover=all", + "-Wno-deprecated-declarations",*["-I"+str(p) for p in includes],str(c), + str(IDF/"components/json/cJSON/cJSON.c"),"-lm","-o",str(exe)],check=True,cwd=ROOT) + subprocess.run([str(exe)],check=True,cwd=ROOT) diff --git a/tests/runtime/test_console_lifecycle.py b/tests/runtime/test_console_lifecycle.py index 7d957b0b..51bf3a8b 100644 --- a/tests/runtime/test_console_lifecycle.py +++ b/tests/runtime/test_console_lifecycle.py @@ -90,7 +90,7 @@ def body(path, name): static void *task_entry(void *p) {current_task=p;current_task->fn(current_task->arg);assert(false);return NULL;} static int xTaskCreate(void (*fn)(void *),const char *name,unsigned stack,void *arg,unsigned priority,TaskHandle_t *out) { (void)name;(void)stack;(void)priority;if(fail_next_create){fail_next_create=false;return pdFALSE;} - TaskHandle_t t=calloc(1,sizeof(*t));assert(t&&task_count<128);t->fn=fn;t->arg=arg;tasks[task_count++]=t;*out=t; + TaskHandle_t t=calloc(1,sizeof(*t));assert(t&&task_count<128);t->fn=fn;t->arg=arg;tasks[task_count++]=t;if(out)*out=t; assert(!pthread_create(&t->thread,NULL,task_entry,t));return pdPASS; } static void vTaskDelete(TaskHandle_t handle) {assert(!handle);assert(current_task&¤t_task->held==0);pthread_exit(NULL);} @@ -111,7 +111,7 @@ def service_source(): return re.sub(r'^#include[^\n]*\n', '', Path('components/ts_core/ts_service/src/ts_service.c').read_text(), flags=re.M) -def run_native(code, extra_sources=(), extra_headers=None): +def run_native(code, extra_sources=(), extra_headers=None, extra_include_dirs=()): with tempfile.TemporaryDirectory(prefix='ts-local-lifecycle-') as directory: root = Path(directory) (root / 'test.c').write_text(code) @@ -122,6 +122,7 @@ def run_native(code, extra_sources=(), extra_headers=None): target.write_text(content) subprocess.run(['cc', '-std=gnu11', '-g', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-Wno-deprecated-declarations', '-I' + str(root), + *['-I' + str(path) for path in extra_include_dirs], '-Itests/runtime/rule_pack/stubs', '-Icomponents/ts_core/ts_service/include', '-Icomponents/ts_console/include', '-Icomponents/ts_drivers/include', '-Icomponents/ts_api/include', '-I' + str(IDF / 'components/json/cJSON'), diff --git a/tests/runtime/test_default_deny_policy.py b/tests/runtime/test_default_deny_policy.py new file mode 100644 index 00000000..69685a6b --- /dev/null +++ b/tests/runtime/test_default_deny_policy.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Real management registrations/registry/dispatcher; synthetic business boundary.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,sys,re,subprocess,tempfile,importlib.util +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT)),text=True) + return (ROOT/path).read_text() +f=ROOT/'tests/runtime/test_cert_admission.py';text=f.read_text();ns={'__file__':str(f),'__name__':'auth_policy_fixture'} +a=text.index('api=source(');b=text.index('\nwith tempfile.TemporaryDirectory');argv=sys.argv;sys.argv=[sys.argv[0]] +try:exec(compile(text[:a],str(f),'exec'),ns) +finally:sys.argv=argv +ns['source']=source;exec(compile(text[a:b],str(f),'exec'),ns);code=ns['code'];code=code[:code.index('int main(void)')] +sp=importlib.util.spec_from_file_location('h',ROOT/'audit/api-security-20261103/tools/extract_inventory.py');h=importlib.util.module_from_spec(sp);sp.loader.exec_module(h) +# Trigger one trusted registry replacement immediately after the policy/handler +# snapshot unlock. Old code performs a second lookup and invokes the new Root +# handler under the earlier public policy; new code invokes its copied handler. +lookup='copy_external_call' if 'static esp_err_t copy_external_call(' in code else 'ts_api_get_access' +lookup_body=ns['function'](code,lookup) +code=code.replace(lookup_body,lookup_body.replace(' xSemaphoreGive(s_api.mutex);',' xSemaphoreGive(s_api.mutex);native_after_snapshot();')) +code='static void native_after_snapshot(void);\n'+code +code+=r""" +static bool replace_after_snapshot; +static unsigned public_snapshot_calls,root_replacement_calls; +static esp_err_t public_snapshot_handler(const cJSON *p,ts_api_result_t *r){(void)p;++public_snapshot_calls;ts_api_result_ok(r,NULL);return ESP_OK;} +static esp_err_t root_replacement_handler(const cJSON *p,ts_api_result_t *r){(void)p;++root_replacement_calls;ts_api_result_ok(r,NULL);return ESP_OK;} +static void native_after_snapshot(void){ + if(!replace_after_snapshot)return;replace_after_snapshot=false; + assert(ts_api_unregister("fixture.snapshot")==ESP_OK); + ts_api_endpoint_t replacement={.name="fixture.snapshot",.handler=root_replacement_handler,.external_access=TS_API_ACCESS_ROOT,.allowed_methods=TS_API_METHOD_WRITE}; + assert(ts_api_register(&replacement)==ESP_OK); +} +""" +code+=r""" +int main(void){ + check(ts_api_init()==ESP_OK,"real registry initializes"); + const unsigned identities[]={0,1,2,3,4,5,99}; + ts_api_endpoint_t internals[]={ + {.name="fixture.internal",.handler=mutation}, + {.name="automation.hidden_internal",.handler=mutation,.requires_auth=true}, + {.name="fixture.cert.manage",.handler=mutation,.permission="cert.manage"}, + {.name="system.unexposed",.handler=mutation,.requires_auth=true,.permission="admin"}}; + cJSON *params=cJSON_Parse("{\"session_id\":4,\"role\":\"root\",\"permission\":\"cert.manage\",\"minimum_level\":0}"); + for(unsigned n=0;n<4;n++){ + check(ts_api_register(&internals[n])==ESP_OK,"internal-only operation registers for trusted C use"); + ts_api_access_t access={0};check(ts_api_get_access(internals[n].name,&access)==ESP_OK,"internal metadata query succeeds"); + check(access.external_access==TS_API_ACCESS_INTERNAL&&!access.allowed_methods&&!access.requires_auth&&!access.minimum_level,"no name/legacy flag/permission creates external role or verbs"); + for(unsigned i=0;i<7;i++){ + ts_api_result_t r={0};unsigned before=mutations; + check(ts_api_call_for_session(internals[n].name,params,identities[i],&r)==ESP_ERR_NOT_SUPPORTED&&r.code==TS_API_ERR_NOT_SUPPORTED,"all external identities including Root are denied before dispatch"); + check(mutations==before,"unexposed operation never reaches handler");ts_api_result_free(&r); + } + ts_api_result_t r={0};unsigned before=mutations;check(ts_api_call(internals[n].name,params,&r)==ESP_OK&&mutations==before+1,"trusted internal original handler contract remains");ts_api_result_free(&r); + } + ts_api_endpoint_t ambiguous={.name="fixture.missing_role",.handler=mutation,.allowed_methods=TS_API_METHOD_READ}; + check(ts_api_register(&ambiguous)==ESP_ERR_INVALID_ARG,"nonzero verbs without explicit external role rejected"); + ts_api_endpoint_t pub={.name="automation.explicit_public",.handler=mutation,.requires_auth=true,.permission="admin",.external_access=TS_API_ACCESS_PUBLIC,.allowed_methods=TS_API_METHOD_READ}; + check(ts_api_register(&pub)==ESP_OK,"explicit public declaration accepted without name/legacy inference");ts_api_access_t a={0};check(ts_api_get_access(pub.name,&a)==ESP_OK&&!a.requires_auth&&!a.minimum_level&&a.allowed_methods==TS_API_METHOD_READ,"explicit declaration is role and method truth"); + ts_api_result_t r={0};unsigned before=mutations;check(ts_api_call_for_session(pub.name,params,0,&r)==ESP_OK&&mutations==before+1,"explicit public positive");ts_api_result_free(&r); + ts_api_endpoint_t root={.name="fixture.explicit_root",.handler=mutation,.requires_auth=false,.external_access=TS_API_ACCESS_ROOT,.allowed_methods=TS_API_METHOD_WRITE}; + check(ts_api_register(&root)==ESP_OK,"explicit Root accepted despite unused compatibility flag");before=mutations;check(ts_api_call_for_session(root.name,params,3,&r)!=ESP_OK&&mutations==before,"Admin cannot weaken explicit Root with JSON");ts_api_result_free(&r);check(ts_api_call_for_session(root.name,params,4,&r)==ESP_OK&&mutations==before+1,"Root positive");ts_api_result_free(&r); + root.name="fixture.root_methods_missing";root.allowed_methods=0;check(ts_api_register(&root)==ESP_ERR_INVALID_ARG,"explicit role without verbs rejected"); + root.name="fixture.root_bad_methods";root.allowed_methods=128;check(ts_api_register(&root)==ESP_ERR_INVALID_ARG,"unknown method bits rejected"); + + ts_api_endpoint_t snapshot={.name="fixture.snapshot",.handler=public_snapshot_handler,.external_access=TS_API_ACCESS_PUBLIC,.allowed_methods=TS_API_METHOD_READ}; + check(ts_api_register(&snapshot)==ESP_OK,"public snapshot fixture registers");replace_after_snapshot=true; + check(ts_api_call_for_session(snapshot.name,params,0,&r)==ESP_OK&&public_snapshot_calls==1&&!root_replacement_calls,"concurrent replacement cannot run new Root handler under old public authorization");ts_api_result_free(&r); + check(ts_api_get_access(snapshot.name,&a)==ESP_OK&&a.minimum_level==TS_PERM_ROOT,"replacement really occurred; later requests see new Root policy"); + cJSON_Delete(params);check(ts_api_deinit()==ESP_OK,"cleanup");printf("%u checks, %u failures: default-deny external dispatch, trusted internal calls and explicit authority; real registry, synthetic business/session boundaries\n",checks,failures);return failures?1:0; +} +""" +with tempfile.TemporaryDirectory(prefix='ts-auth-policy-') as tmp: + c=Path(tmp)/'probe.c';exe=Path(tmp)/'probe';c.write_text(code) + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize=address,undefined','-fno-sanitize-recover=all',*['-I'+str(p) for p in ns['includes']],str(c),str(ns['IDF']/'components/json/cJSON/cJSON.c'),'-lpthread','-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True,timeout=20) diff --git a/tests/runtime/test_dhcp_bindings.py b/tests/runtime/test_dhcp_bindings.py index 24bfefe9..9688f970 100644 --- a/tests/runtime/test_dhcp_bindings.py +++ b/tests/runtime/test_dhcp_bindings.py @@ -32,9 +32,9 @@ def manager_identifiers(text): end = manager.index('static ts_net_manager_state_t s_state = {0};') defines = '\n'.join(line for line in manager.splitlines() if line.startswith('#define NVS_')) (output / 'manager_types.inc').write_text(manager_identifiers(defines + '\n' + manager[begin:end])) - (output / 'manager_core.inc').write_text('static esp_err_t stop_eth(void);\n' + manager_identifiers('\n\n'.join(sorted( + (output / 'manager_core.inc').write_text('static pthread_mutex_t s_hostname_lock=PTHREAD_MUTEX_INITIALIZER;\n#define portENTER_CRITICAL(m) pthread_mutex_lock(m)\n#define portEXIT_CRITICAL(m) pthread_mutex_unlock(m)\nstatic char s_authority_hostname[TS_NET_HOSTNAME_MAX_LEN],s_active_hostname[TS_NET_HOSTNAME_MAX_LEN];\nstatic esp_err_t stop_eth(void);\n' + manager_identifiers('\n\n'.join(sorted( (function(manager, n) for n in manager_names if re.search(r'^(?:static )?[\w *]+\b' + n + r'\([^;]*?\)\s*\{', manager, re.M)), key=manager.index)))) - (output / 'eth_creation.inc').write_text(function(driver, 'create_eth_netif_with_dhcps')) + (output / 'eth_creation.inc').write_text((function(driver, 'set_eth_host_dns')+'\n' if 'static esp_err_t set_eth_host_dns(' in driver else '')+function(driver, 'create_eth_netif_with_dhcps')) init = function(driver, 'ts_eth_init') calls = list(re.finditer(r'^ [^\n]*create_eth_netif_with_dhcps\(', init, re.M)) assert len(calls) == 1, 'ETH init must have one netif creation call' @@ -45,7 +45,7 @@ def manager_identifiers(text): (output / 'eth_init_creation.inc').write_text(init[begin:end] + '\n'.join(re.findall(r'^ s_driver_stop_complete = [^;]+;', init, re.M))) (output / 'eth_events.inc').write_text('\n\n'.join(function(driver, n) for n in ['dhcp_start_task', 'eth_event_handler', 'ts_eth_start', 'ts_eth_stop'])) - (output / 'network_setter.inc').write_text('\n'.join(function(network, n) for n in ['get_netif', 'ts_net_get_ip_info', 'ts_net_set_ip_info', 'ts_net_get_status'])) + (output / 'network_setter.inc').write_text((function(network,'read_eth_host_dns')+'\n' if 'static esp_err_t read_eth_host_dns(' in network else '')+'\n'.join(function(network, n) for n in ['get_netif', 'ts_net_get_ip_info', 'ts_net_set_ip_info', 'ts_net_get_status'])) (output / 'network_cli.inc').write_text('\n'.join(function(console,n) for n in ['do_net_set','do_net_ip','do_net_start','do_net_stop','do_net_restart'])) diff --git a/tests/runtime/test_dns_lifecycle.py b/tests/runtime/test_dns_lifecycle.py new file mode 100644 index 00000000..138a6325 --- /dev/null +++ b/tests/runtime/test_dns_lifecycle.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Actual bounded DNS owner; synthetic lwIP scheduling, real pthread/semaphore races.""" +from pathlib import Path +import re +from test_console_lifecycle import RTOS, run_native + +root=Path(__file__).resolve().parents[2] +code=RTOS+r''' +#include +#include "ts_dns.h" +#include "lwip/dns.h" +#include "lwip/tcpip.h" +static atomic_uint live_requests,peak_requests; +static bool fail_allocation,fail_semaphore; +static void *request_calloc(size_t count,size_t size){ + if(fail_allocation)return NULL;void *p=calloc(count,size);assert(p); + unsigned live=atomic_fetch_add(&live_requests,1)+1,peak=atomic_load(&peak_requests); + while(live>peak&&!atomic_compare_exchange_weak(&peak_requests,&peak,live)){}return p; +} +static void request_free(void *p){assert(atomic_fetch_sub(&live_requests,1));free(p);} +static SemaphoreHandle_t request_semaphore(void){return fail_semaphore?NULL:xSemaphoreCreateBinary();} +static pthread_mutex_t dns_lock=PTHREAD_MUTEX_INITIALIZER; +static atomic_bool pending_ready; +static bool defer_queue,queue_failure; +static int dns_mode; +enum {DNS_CACHED,DNS_PENDING,DNS_ERROR}; +static unsigned dns_calls; +static void (*queued)(void *);static void *queued_arg; +static dns_found_callback pending;static void *pending_arg; +static _Thread_local bool in_tcpip; +static ip_addr_t answer; +err_t tcpip_try_callback(void (*fn)(void *),void *arg){ + if(queue_failure)return ERR_MEM; + if(defer_queue){assert(!queued);queued=fn;queued_arg=arg;return ERR_OK;} + in_tcpip=true;fn(arg);in_tcpip=false;return ERR_OK; +} +err_t dns_gethostbyname_addrtype(const char *name,ip_addr_t *address,dns_found_callback found,void *context,unsigned char type){ + assert(in_tcpip&&name&&type==LWIP_DNS_ADDRTYPE_DEFAULT);dns_calls++; + if(dns_mode==DNS_CACHED){*address=answer;return ERR_OK;} + if(dns_mode==DNS_ERROR)return ERR_VAL; + pthread_mutex_lock(&dns_lock);assert(!pending);pending=found;pending_arg=context;atomic_store(&pending_ready,true);pthread_mutex_unlock(&dns_lock);return ERR_INPROGRESS; +} +#define calloc request_calloc +#define free request_free +#define xSemaphoreCreateBinary request_semaphore +''' +code+=re.sub(r'^#include[^\n]*\n','',(root/'components/ts_dns/src/ts_dns.c').read_text(),flags=re.M) +code+=r''' +#undef calloc +#undef free +#undef xSemaphoreCreateBinary +static unsigned checks; +static void check(bool yes,const char *message){checks++;if(!yes){fprintf(stderr,"FAIL %s\n",message);abort();}} +static bool current(void *context){return !atomic_load((atomic_bool *)context);} +typedef struct {atomic_bool cancelled;esp_err_t result;ip_addr_t address;} caller_t; +static void *caller(void *context){ + caller_t *c=context;char name[64];strcpy(name,"worker.example"); + c->result=ts_dns_resolve(name,esp_timer_get_time()+1000000,current,&c->cancelled,&c->address);return NULL; +} +typedef struct {dns_found_callback fn;void *argument;} completion_t; +static completion_t take_completion(void){ + pthread_mutex_lock(&dns_lock);assert(pending);completion_t c={pending,pending_arg};pending=NULL;pending_arg=NULL;atomic_store(&pending_ready,false);pthread_mutex_unlock(&dns_lock);return c; +} +static void finish(completion_t c,const ip_addr_t *address){in_tcpip=true;c.fn("worker.example",address,c.argument);in_tcpip=false;} +static SemaphoreHandle_t pause_target,callback_resume; +static atomic_bool callback_paused; +static void pause_after_signal(SemaphoreHandle_t semaphore){ + if(semaphore==pause_target){atomic_store(&callback_paused,true);assert(xSemaphoreTake(callback_resume,portMAX_DELAY));} +} +static void *completer(void *arg){completion_t c=*(completion_t *)arg;finish(c,&answer);return NULL;} +int main(void){ + assert(ipaddr_aton("192.0.2.7",&answer));ip_addr_t result;memset(&result,0xa5,sizeof(result)); + atomic_bool cancelled=false; + check(ts_dns_resolve("127.0.0.1",esp_timer_get_time()+100000,current,&cancelled,&result)==ESP_OK&&!atomic_load(&live_requests)&&!dns_calls,"numeric IPv4 never queues DNS or allocates callback state"); + check(ts_dns_resolve("::1",esp_timer_get_time()+100000,current,&cancelled,&result)==ESP_OK&&!dns_calls,"numeric IPv6 retains the same immediate path"); + check(ts_dns_resolve("bad",esp_timer_get_time()-1,current,&cancelled,&result)==ESP_ERR_TIMEOUT&&!atomic_load(&live_requests),"expired caller cannot start a resolution"); + atomic_store(&cancelled,true);check(ts_dns_resolve("bad",esp_timer_get_time()+100000,current,&cancelled,&result)==ESP_ERR_INVALID_STATE,"canceled caller cannot queue DNS");atomic_store(&cancelled,false); + char too_long[257];memset(too_long,'a',256);too_long[256]=0; + check(ts_dns_resolve(too_long,esp_timer_get_time()+100000,NULL,NULL,&result)==ESP_ERR_INVALID_ARG,"oversized hostname is rejected before allocation"); + dns_mode=DNS_CACHED; + check(ts_dns_resolve("cached.example",esp_timer_get_time()+100000,NULL,NULL,&result)==ESP_OK&&!memcmp(&result,&answer,sizeof(result))&&!atomic_load(&live_requests)&&!atomic_load(&s_query_active),"cached completion may run before queue submission returns without losing its caller reference"); + for(unsigned failure=0;failure<4;failure++){ + fail_allocation=failure==0;fail_semaphore=failure==1;queue_failure=failure==2;dns_mode=failure==3?DNS_ERROR:DNS_CACHED; + esp_err_t r=ts_dns_resolve("failure.example",esp_timer_get_time()+100000,NULL,NULL,&result); + check(r!=ESP_OK&&!atomic_load(&live_requests)&&!atomic_load(&s_query_active),"allocation/semaphore/queue/synchronous DNS failures release exactly their own resources"); + }fail_allocation=fail_semaphore=queue_failure=false; + /* A caller can expire before the TCP/IP queue dispatches. It owns no borrowed + * callback input, and no late DNS packet is initiated after it returns. */ + defer_queue=true;dns_mode=DNS_PENDING;unsigned before=dns_calls; + check(ts_dns_resolve("queued.example",esp_timer_get_time()+20000,NULL,NULL,&result)==ESP_ERR_TIMEOUT&&atomic_load(&live_requests)==1&&atomic_load(&s_query_active),"timeout returns while the queued callback retains its own input and semaphore"); + check(ts_dns_resolve("second.example",esp_timer_get_time()+10000,NULL,NULL,&result)==ESP_ERR_TIMEOUT&&atomic_load(&live_requests)==1,"an orphaned callback keeps one bounded DNS slot; retries do not allocate additional contexts"); + void (*start)(void *)=queued;void *start_arg=queued_arg;queued=NULL;queued_arg=NULL;in_tcpip=true;start(start_arg);in_tcpip=false; + check(dns_calls==before&&!atomic_load(&live_requests)&&!atomic_load(&s_query_active),"late TCP/IP dispatch observes retired intent before issuing DNS");defer_queue=false; + /* DNS is already in flight when its caller is canceled and freed. */ + caller_t *retired=calloc(1,sizeof(*retired));pthread_t calling; + assert(!pthread_create(&calling,NULL,caller,retired));WAIT_UNTIL(atomic_load(&pending_ready));atomic_store(&retired->cancelled,true);assert(!pthread_join(calling,NULL)); + check(retired->result==ESP_ERR_INVALID_STATE&&atomic_load(&live_requests)==1,"in-flight cancellation returns without freeing a callback-owned semaphore");free(retired); + finish(take_completion(),NULL); + check(!atomic_load(&live_requests)&&!atomic_load(&s_query_active),"late failure after caller/hostname lifetime ended releases the orphan without accessing freed caller data"); + /* Force callback give -> caller return -> next query before the old callback + * releases its last reference. Its cleanup must not clear the new slot. */ + caller_t first={0},second={0};pthread_t one,two,finishing; + assert(!pthread_create(&one,NULL,caller,&first));WAIT_UNTIL(atomic_load(&pending_ready));completion_t old=take_completion(); + pause_target=((resolve_request_t *)old.argument)->completed;callback_resume=xSemaphoreCreateBinary();after_binary_give=pause_after_signal; + assert(!pthread_create(&finishing,NULL,completer,&old));WAIT_UNTIL(atomic_load(&callback_paused));assert(!pthread_join(one,NULL)); + check(first.result==ESP_OK&&!memcmp(&first.address,&answer,sizeof(answer))&&atomic_load(&live_requests)==1,"caller can return with stable copied address while completing callback still owns its reference"); + assert(!pthread_create(&two,NULL,caller,&second));WAIT_UNTIL(atomic_load(&pending_ready)); + check(atomic_load(&s_query_active)&&atomic_load(&live_requests)==2,"new query has its own context while the old callback finishes"); + xSemaphoreGive(callback_resume);assert(!pthread_join(finishing,NULL));after_binary_give=NULL; + check(atomic_load(&s_query_active)&&atomic_load(&live_requests)==1,"old post-signal cleanup cannot release the new query's admission slot"); + atomic_store(&second.cancelled,true);assert(!pthread_join(two,NULL));completion_t later=take_completion();finish(later,&answer); + check(second.result==ESP_ERR_INVALID_STATE&&!atomic_load(&live_requests)&&!atomic_load(&s_query_active),"new canceled caller never receives an old or late address, and all callback state retires");vSemaphoreDelete(callback_resume); + check(atomic_load(&peak_requests)<=2,"callback state remains bounded across forced schedules"); + printf("%u checks: actual DNS lifecycle, numeric v4/v6 boundary, queue/cache/failure, canceled and delayed callbacks, deterministic pthread ownership race; synthetic lwIP only\n",checks); +} +''' +headers={ + 'ts_dns.h':(root/'components/ts_dns/include/ts_dns.h').read_text(), + 'lwip/ip_addr.h':'''#pragma once +#include +#include +typedef struct {int family;unsigned char bytes[16];} ip_addr_t; +#define ip_addr_set_zero(p) memset((p),0,sizeof(*(p))) +#define ip_addr_copy(to,from) ((to)=(from)) +static int ipaddr_aton(const char *s,ip_addr_t *p){ip_addr_set_zero(p);if(inet_pton(AF_INET,s,p->bytes)==1){p->family=AF_INET;return 1;}if(inet_pton(AF_INET6,s,p->bytes)==1){p->family=AF_INET6;return 1;}return 0;} +''', + 'lwip/dns.h':'''#pragma once +#include "lwip/ip_addr.h" +#define DNS_MAX_NAME_LENGTH 256 +#define LWIP_DNS_ADDRTYPE_DEFAULT 2 +#define ERR_OK 0 +#define ERR_MEM -1 +#define ERR_INPROGRESS -5 +#define ERR_VAL -6 +typedef int err_t; +typedef void (*dns_found_callback)(const char *,const ip_addr_t *,void *); +err_t dns_gethostbyname_addrtype(const char *,ip_addr_t *,dns_found_callback,void *,unsigned char); +''', + 'lwip/tcpip.h':'#pragma once\n#include "lwip/dns.h"\nerr_t tcpip_try_callback(void (*)(void *),void *);\n', +} +run_native(code,extra_headers=headers) diff --git a/tests/runtime/test_exec_delivery.py b/tests/runtime/test_exec_delivery.py new file mode 100644 index 00000000..1c3d239e --- /dev/null +++ b/tests/runtime/test_exec_delivery.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Replay the actual private-output pipeline against current or frozen C sources.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf')) +text=(ROOT/'tests/ws_subscriptions/test_exec_ownership.c').read_text();text=text[:text.index('static void queued_checks')] +# Only use the existing initiation/observation/result API for the frozen-source +# comparison. No shim implements or substitutes the security boundary under test. +text=re.sub(r'assert\(!ts_ws_peer_authorized_for_session\(bound_peer\(3\),TS_PERM_ROOT,7\)\);','',text) +text=re.sub(r' ts_ws_peer_t peers\[TS_WS_CONNECTIONS\];[^\n]+\n','',text) +text+='int main(void){cJSON_Hooks hooks={tracked_malloc,tracked_free};cJSON_InitHooks(&hooks);private_setup();run_business(7,false);puts("PASS actual private-output replay: other authenticated Root and lower roles receive no private events");}\n' +with tempfile.TemporaryDirectory(prefix='ts-exec-delivery-') as tmp: + t=Path(tmp) + if args.source_package: + with ZipFile(args.source_package) as z: + for f in ['components/ts_webui/src/ts_webui_ws.c','components/ts_webui/src/ts_ws_transport.c','components/ts_webui/src/ts_ws_operation.c']: + n='current-source/'+f + data=z.read(n) if n in z.namelist() else subprocess.check_output(['git','show','35e081ac8:'+f],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT))) + (t/Path(f).name).write_bytes(data) + source=t/'probe.c';source.write_text(text);exe=t/'probe' + includes=[t,ROOT/'tests/ws_subscriptions',ROOT/'tests/ws_subscriptions/stubs',ROOT/'components/ts_webui/include',ROOT/'components/ts_webui/src',ROOT/'components/ts_security/include',ROOT/'components/ts_automation/include',ROOT/'components/ts_drivers/include',ROOT/'components/ts_console/include',ROOT/'components/ts_net/include',IDF/'components/json/cJSON'] + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-Wno-macro-redefined','-fsanitize=address,undefined','-fno-sanitize-recover=all',*['-I'+str(i) for i in includes],str(source),str(IDF/'components/json/cJSON/cJSON.c'),'-lm','-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True,timeout=30) diff --git a/tests/runtime/test_expansion.py b/tests/runtime/test_expansion.py index af7da39a..91423d8a 100644 --- a/tests/runtime/test_expansion.py +++ b/tests/runtime/test_expansion.py @@ -1,4 +1,5 @@ """Exercise the production variable expander, including exact capacities.""" +from host_paths import build_dir from pathlib import Path import os, re, subprocess source = Path('components/ts_automation/src/ts_action_manager.c').read_text() @@ -36,7 +37,7 @@ puts("PASS production expansion: 62/63 chars, exact fit, overflow rejects empty, unknown and Shell expressions preserved, long names, numeric values"); } ''' -build=Path('/tmp/tianshan-runtime-tests');build.mkdir(exist_ok=True) +build=build_dir('expansion');build.mkdir(exist_ok=True) (build/'expansion.c').write_text(code) env={**os.environ,'DEVELOPER_DIR':'/Library/Developer/CommandLineTools'} subprocess.run(['cc','-D_POSIX_C_SOURCE=200809L','-std=c11','-g','-fsanitize=address,undefined','-ftrivial-auto-var-init=pattern','-Itests/runtime/stubs','-Itests/certificate/stubs','-Icomponents/ts_automation/include','-Icomponents/ts_security/include',str(build/'expansion.c'),'-o',str(build/'expansion')],check=True,env=env) diff --git a/tests/runtime/test_external_storage_reads.py b/tests/runtime/test_external_storage_reads.py new file mode 100644 index 00000000..4fe5794f --- /dev/null +++ b/tests/runtime/test_external_storage_reads.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Actual registry, external storage callbacks, HTTP download, path classifier and FAT resolver. +FS/SDK/FAT/auth-record boundaries are synthetic; this is not a physical-card test. +Before package uses its original handler when no session callback was registered. +""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile,sys +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT)),text=True) + return (ROOT/path).read_text() +f=ROOT/'tests/runtime/test_cert_admission.py';text=f.read_text();ns={'__file__':str(f),'__name__':'storage_read_fixture'};a=text.index('api=source(');b=text.index('\nwith tempfile.TemporaryDirectory');argv=sys.argv;sys.argv=[sys.argv[0]] +try:exec(compile(text[:a],str(f),'exec'),ns) +finally:sys.argv=argv +ns['source']=source;exec(compile(text[a:b],str(f),'exec'),ns);code=ns['code'];code=code[:code.index('int main(void)')] +code=code.replace('#include "ts_api.h"','#include "ts_api.h"\n#include "ts_storage.h"',1) +code=code.replace('esp_err_t ts_storage_check_write_path(const char *s,bool children){(void)s;(void)children;return ESP_OK;}','') +code=code.replace('esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){','static unsigned revoked_sid;\nesp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){\n if(sid&&sid==revoked_sid)return ESP_ERR_NOT_FOUND;') +function=ns['function'];IDF=ns['IDF'] +code+=r""" +#include "ts_storage.h" +#include "ts_config_partitions.h" +#define api_storage_status readonly +#define api_storage_mount mutation +#define api_storage_unmount mutation +#define api_storage_delete mutation +#define api_storage_mkdir mutation +#define api_storage_rename mutation +#define api_storage_list readonly +#define api_storage_info readonly +#define api_storage_read readonly +static unsigned lookups,reads_after_lookup,active_sid; +static bool lookup_error,revoke_during_lookup; +typedef unsigned char BYTE; +typedef enum {FR_OK,FR_NO_FILE,FR_NO_PATH,FR_DISK_ERR} FRESULT; +typedef struct {char fname[256];} FILINFO; +static char s_mount_point[32]="/sdcard"; +static void *s_card=(void *)1; +void ts_storage_sd_lock(void){} +void ts_storage_sd_unlock(void){} +static BYTE ff_diskio_get_pdrv_card(void *card){(void)card;return 0;} +static FRESULT f_stat(const char *path,FILINFO *info){ + ++lookups;if(revoke_during_lookup)revoked_sid=active_sid; + if(lookup_error)return FR_DISK_ERR; + const char *name=strrchr(path,'/')+1; + if(!strcmp(name,"missing"))return FR_NO_FILE; + if(!strcmp(name,"CONFID~1")||!strcmp(name,"confıg"))name="config"; + if(!strcmp(name,"PKIPRI~1"))name="pki"; + snprintf(info->fname,sizeof(info->fname),"%s",name);return FR_OK; +} +""" +driver=source('components/ts_storage/src/ts_storage_sd.c') +if 'esp_err_t ts_storage_sd_resolve_name(' in driver:code+=function(driver,'ts_storage_sd_resolve_name') +if 'bool ts_storage_sd_name_is(' in driver:code+=function(driver,'ts_storage_sd_name_is') +code+=source('components/ts_storage/src/ts_storage_paths.c')+'\n' +storage=source('components/ts_api/src/ts_api_storage.c') +if 'static esp_err_t storage_read_for_session(' in storage: + for name in ['storage_read_for_session','storage_list_for_session','storage_info_for_session','storage_file_for_session']:code+=function(storage,name) +start=storage.index('static const ts_api_endpoint_t s_storage_endpoints[]');end=storage.index('\n};',start)+3;code+=storage[start:end]+'\n'+function(storage,'ts_api_storage_register') +code+=r""" +typedef struct {const char *path;unsigned identity;} ts_http_request_t; +static int status; +static unsigned sent_files; +static esp_err_t ts_http_get_query_param(ts_http_request_t *r,const char *key,char *out,size_t n){(void)key;snprintf(out,n,"%s",r->path);return ESP_OK;} +static esp_err_t check_auth(ts_http_request_t *r,uint32_t *sid,ts_perm_level_t required){ts_session_t s;if(ts_security_validate_session(r->identity,&s)!=ESP_OK)return ESP_ERR_NOT_FOUND;*sid=r->identity;return s.level>=required?ESP_OK:ESP_ERR_NOT_ALLOWED;} +static esp_err_t ts_http_send_error(ts_http_request_t *r,int code,const char *why){(void)r;(void)why;status=code;return ESP_OK;} +bool ts_storage_exists(const char *p){(void)p;return true;} +bool ts_storage_is_dir(const char *p){(void)p;return false;} +static esp_err_t ts_http_send_private_file(ts_http_request_t *r,const char *p){(void)r;(void)p;++sent_files;status=200;return ESP_OK;} +""" +code+=function(source('components/ts_webui/src/ts_webui_api.c'),'file_download_handler') +code+=r""" +static void reading(const char *name,const char *path,unsigned identity,bool private_path,bool invalid){ + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"path",path);cJSON_AddStringToObject(p,"role","root");cJSON_AddNumberToObject(p,"session_id",4);cJSON_AddBoolToObject(p,"requires_root",false); + unsigned before=reads,stat_before=lookups;ts_api_result_t r={0};active_sid=identity;esp_err_t rc=ts_api_call_for_session(name,p,identity,&r); + bool valid=identity>=1&&identity<=4,allowed=valid&&!invalid&&(!private_path||identity>=3); + check((rc==ESP_OK&&r.code==TS_API_OK)==allowed,"path/verified identity decides external read result");check(reads==before+allowed,"rejected private/invalid read never enters business/file handler");if(!valid)check(lookups==stat_before,"anonymous/invalid session denied before FAT metadata"); + ts_api_result_free(&r);cJSON_Delete(p); +} +static void downloading(const char *path,unsigned identity,bool private_path,bool invalid){ + unsigned before=sent_files,stat_before=lookups;status=0;active_sid=identity;ts_http_request_t r={.path=path,.identity=identity};file_download_handler(&r,NULL); + bool valid=identity>=1&&identity<=4,allowed=valid&&!invalid&&(!private_path||identity>=3);int expected=!valid?401:invalid?400:private_path&&identity<3?403:200; + check(status==expected,"dedicated download gives correct login/admin/path status");check(sent_files==before+allowed,"rejected download never reaches private-file sender");if(!valid)check(lookups==stat_before,"anonymous download denied before FAT metadata"); +} +int main(void){ + check(ts_api_init()==ESP_OK&&ts_api_storage_register()==ESP_OK,"real registry and nine storage names initialize"); + + const struct {const char *name;unsigned level,methods,mode;} policies[]={ + {"storage.status",0,3,TS_API_ACCESS_PUBLIC},{"storage.mount",3,14,TS_API_ACCESS_ADMIN},{"storage.unmount",3,14,TS_API_ACCESS_ADMIN},{"storage.list",1,3,TS_API_ACCESS_READ},{"storage.delete",3,14,TS_API_ACCESS_ADMIN},{"storage.mkdir",3,14,TS_API_ACCESS_ADMIN},{"storage.rename",3,14,TS_API_ACCESS_ADMIN},{"storage.info",1,3,TS_API_ACCESS_READ},{"storage.read",1,3,TS_API_ACCESS_READ}}; + cJSON *names_all=ts_api_list(TS_API_CAT_MAX);check(cJSON_GetArraySize(names_all)==9,"actual nine storage registrations are complete");cJSON_Delete(names_all); + for(unsigned i=0;i<9;i++){ts_api_access_t access={0};check(ts_api_get_access(policies[i].name,&access)==ESP_OK,"all storage policies query");check(access.minimum_level==policies[i].level&&access.allowed_methods==policies[i].methods&&access.external_access==policies[i].mode&&access.requires_auth==(policies[i].level>0),"nine independent role/method contracts");} + const char *private_paths[]={"/sdcard/config/network.json","/sdcard/CONFIG/ssh_hosts/a","/sdcard/foo/../config/wifi.json","/sdcard/config. /wifi.json","/sdcard/config\\wifi.json","/sdcard/confıg/wifi.json","/sdcard/CONFID~1/wifi.json","/sdcard/pki/ca-chain.crt","/sdcard/PKIPRI~1/ca-chain.crt","/spiffs/keys","/www/js/app.js","/autocfg/state.json"}; + const char *data_paths[]={"/sdcard","/sdcard/images/pic.png","/sdcard/自定义/file.txt","/sdcard/logs/sys.log","/sdcard/missing/file.txt","/sdcard/config/../images/pic.png","/sdcard/literal%2Fconfig/file"}; + const char *invalid_paths[]={"/sdcard-other/a","/spiffs-other/a","/unknown/a","relative","/","/sdcard/config\t/a"}; + const char *names[]={"storage.list","storage.info","storage.read"};unsigned identities[]={0,1,2,3,4,5,99}; + for(unsigned who=0;who<7;who++){ + for(unsigned i=0;i +#include +#include +#include +#include "ts_api.h" +#include "ts_storage.h" +#include "ts_config_partitions.h" +#include "ts_config_pack.h" +#define TS_LED_CC_SDCARD_JSON_PATH "/sdcard/config/led_color_correction.json" +#define TS_LOGI(...) ((void)0) +#define TS_LOGD(...) ((void)0) +#define TS_LOGE(...) ((void)0) +typedef void *ts_ssh_session_t,*ts_sftp_session_t; +static unsigned checks,failures,writes,connections,closed; +static char target[256]; +static void check(bool value,const char *why){++checks;if(!value){++failures;fprintf(stderr,"FAIL: %s\n",why);}} +void ts_api_result_ok(ts_api_result_t *r,cJSON *d){r->code=TS_API_OK;r->data=d;} +void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t c,const char *m){r->code=c;r->message=(char *)m;} +bool ts_storage_sd_name_is(const char *path,const char *name){return !strcmp(name,"automation")&&!strcmp(path,"/sdcard/config/AUTOMA~1");} +bool ts_storage_exists(const char *p){(void)p;return true;} +bool ts_storage_is_dir(const char *p){(void)p;return false;} +esp_err_t ts_storage_delete(const char *p){++writes;snprintf(target,sizeof(target),"%s",p);return ESP_OK;} +esp_err_t ts_storage_rmdir_r(const char *p){return ts_storage_delete(p);} +esp_err_t ts_storage_mkdir_p(const char *p){return ts_storage_delete(p);} +esp_err_t ts_storage_rename(const char *a,const char *b){(void)a;return ts_storage_delete(b);} +static esp_err_t connect_sftp(const cJSON *p,ts_ssh_session_t *a,ts_sftp_session_t *b){(void)p;++connections;*a=(void *)1;*b=(void *)2;return ESP_OK;} +static void close_sftp(ts_ssh_session_t a,ts_sftp_session_t b){assert(a==(void *)1&&b==(void *)2);++closed;} +static esp_err_t ts_sftp_get(ts_sftp_session_t s,const char *remote,const char *local,void *a,void *b){(void)s;(void)remote;(void)a;(void)b;return ts_storage_delete(local);} +static bool ts_led_cc_is_initialized(void){return true;} +static esp_err_t ts_led_cc_save_to_sdcard(const char *p){return ts_storage_delete(p?p:TS_LED_CC_SDCARD_JSON_PATH);} +""" +code+=r""" +bool ts_config_pack_can_export(void){return true;} +ts_config_pack_result_t ts_config_pack_create(const char *n,const char *j,size_t z,const ts_config_pack_export_opts_t *o,char **out,size_t *len){(void)n;(void)j;(void)z;(void)o;*out=strdup("{}");*len=2;return TS_CONFIG_PACK_OK;} +esp_err_t ts_config_pack_save(const char *p,const char *d,size_t z){(void)d;(void)z;ts_storage_delete(p);return TS_CONFIG_PACK_OK;} +static void pack_failure(ts_api_result_t *r,ts_config_pack_result_t e){(void)e;ts_api_result_error(r,TS_API_ERR_INTERNAL,"pack error");} +""" +code+='esp_err_t ts_storage_sd_resolve_name(const char *p,char *n,size_t z){const char *name=!strcmp(p,"/sdcard/config/AUTOMA~1")?"automation":strrchr(p,\'/\')+1;snprintf(n,z,"%s",name);return ESP_OK;}\n' +code+=source('components/ts_storage/src/ts_storage_paths.c')+'\n' +for path,names in [('components/ts_api/src/ts_api_storage.c',['storage_mutation_failure','api_storage_delete','api_storage_mkdir','api_storage_rename']),('components/ts_api/src/ts_api_sftp.c',['api_sftp_get']),('components/ts_api/src/ts_api_led.c',['api_led_cc_export']),('components/ts_api/src/ts_api_config_pack.c',['api_config_pack_export'])]: + for name in names:code+=body(path,name) +code+=r""" +static void call_writer(unsigned which,const char *path,bool allowed){ + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"path",path);cJSON_AddStringToObject(p,"remote","/remote/data");cJSON_AddStringToObject(p,"local",path); + cJSON_AddStringToObject(p,"from",which==2?path:"/sdcard/data/a.txt");cJSON_AddStringToObject(p,"to",which==2?"/sdcard/data/b.txt":path); + cJSON_AddStringToObject(p,"name","synthetic");cJSON_AddStringToObject(p,"content","{}");cJSON_AddStringToObject(p,"recipient_cert","synthetic");cJSON_AddStringToObject(p,"save_path",path); + ts_api_result_t r={0};unsigned before=writes,conn=connections,done=closed;esp_err_t rc; + switch(which){case 0:rc=api_storage_delete(p,&r);break;case 1:rc=api_storage_mkdir(p,&r);break;case 2:case 3:rc=api_storage_rename(p,&r);break;case 4:rc=api_sftp_get(p,&r);break;case 5:rc=api_led_cc_export(p,&r);break;default:rc=api_config_pack_export(p,&r);break;} + if(allowed){check(rc==ESP_OK&&r.code==TS_API_OK&&writes==before+(which==6?2:1),"ordinary SD destination reaches only intended mkdir/save boundaries");if(which==4)check(connections==conn+1&&closed==done+1,"valid SFTP connects and closes exactly once");} + else {check(rc!=ESP_OK&&r.code!=TS_API_OK,"unsupported mount/owned destination is refused");check(writes==before,"refused operation never reaches mutation boundary");check(connections==conn&&closed==done,"invalid SFTP destination never contacts remote");} + cJSON_Delete(p);cJSON_Delete(r.data); +} +int main(void){ + const char *blocked[]={"/sdcard","/sdcard/","/","/www-other/a","/autocfg/state.json","/unknown/a","relative/file","/sdcard-other/a","/sdcardx/a","/sdcard/config/automation/state.json","/sdcard/config/AUTOMA~1/state.json","/sdcard/config\\automation\\state.json","/sdcard/config\t/file"}; + for(unsigned i=0;ivaluestring)==160&&cJSON_GetObjectItem(r.data,"status")->valueint==500);ts_api_result_free(&r);} {ts_api_result_t r={0};proxy_http_error(&r,404,NULL);assert(cJSON_GetObjectItem(r.data,"status")->valueint==404&&!cJSON_GetObjectItem(r.data,"detail"));ts_api_result_free(&r);} + {ts_api_result_t r={0};pack_failure(&r,TS_CONFIG_PACK_ERR_UNSUPPORTED);sent_with_detail(r,"wire-pack-unsupported.json",TS_API_ERR_NOT_SUPPORTED,"pack_apply_unsupported","Generic configuration pack application is not supported");} /* config packs: every result has a reason token of its own, the library's English text goes to the details */ {ts_api_result_t r={0};pack_failure(&r,TS_CONFIG_PACK_ERR_RECIPIENT);sent_with_detail(r,"wire-pack-wrong-device.json",TS_API_ERR_INVALID_ARG,"pack_wrong_device","Not intended for this device");} {ts_api_result_t r={0};pack_failure(&r,TS_CONFIG_PACK_ERR_SIGNATURE);sent_with_detail(r,"wire-pack-signature.json",TS_API_ERR_INVALID_ARG,"pack_signature_invalid","Signature verification failed");} @@ -197,6 +200,7 @@ def extract(path, name): assert(token&&token[0]&&strcmp(token,"pack_verify_failed")); /* every real failure has its own token */ for(const char *c=token;*c;c++) assert((*c>='a'&&*c<='z')||(*c>='0'&&*c<='9')||*c=='_'); } + assert(!strcmp(ts_config_pack_reason(TS_CONFIG_PACK_OK),"ok")); assert(!strcmp(ts_config_pack_reason((ts_config_pack_result_t)99),"pack_verify_failed")); /* every refusal state of the engine has a token, and the token depends only on the state and on start / pause */ assert(!strcmp(engine_refusal_token(TS_AUTO_STATE_PAUSED,false),"engine_paused")&&!strcmp(engine_refusal_token(TS_AUTO_STATE_PAUSED,true),"engine_paused")); diff --git a/tests/runtime/test_http_body_integrity.py b/tests/runtime/test_http_body_integrity.py new file mode 100644 index 00000000..220f9b7c --- /dev/null +++ b/tests/runtime/test_http_body_integrity.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Real HTTP/HTTPS wrappers, body receiver and response status; synthetic SDK I/O.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2] +p=argparse.ArgumentParser();p.add_argument('--source-ref');p.add_argument('--source-package');p.add_argument('--case',choices=['all','bodies','statuses'],default='all');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=ROOT,text=True) + return subprocess.check_output(['git','show',args.source_ref+':'+path],cwd=ROOT,text=True) if args.source_ref else (ROOT/path).read_text() +def function(text,name,required=True): + m=re.search(r'^(?:static )?esp_err_t '+name+r'\([^;]*?\)\s*\{',text,re.M) + if not m:assert not required,name;return '' + return text[m.start():text.index('\n}',m.start())+2]+'\n' +http=source('components/ts_net/src/ts_http_server.c');https=source('components/ts_net/src/ts_https_server.c') +code=r''' +#include +#include +#include +#include +#include +#include +typedef int esp_err_t; +static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;} +#define ESP_OK 0 +#define ESP_FAIL -1 +#define ESP_ERR_INVALID_ARG 0x102 +#define HTTP_GET 0 +#define HTTPD_SOCK_ERR_TIMEOUT -7 +#define HTTPD_500_INTERNAL_SERVER_ERROR 500 +#define TS_LOGW(...) ((void)0) +#define TS_LOGE(...) ((void)0) +typedef struct {void *user_ctx;const char *uri;int method;size_t content_len;} httpd_req_t; +typedef struct {httpd_req_t *req;const char *uri;int method;char *body;size_t body_len;} ts_http_request_t; +typedef struct {int (*handler)(ts_http_request_t*,void*);void *user_data;bool (*admit)(ts_http_request_t*,void*);size_t max_body_bytes;uint32_t body_timeout_ms;} ts_http_route_t; +static bool s_stopping,oom;static unsigned calls,reads,allocations,status;static int failure;static size_t position,fail_after; +static unsigned char payload[73791];static char wire_status[64];static char response_body[200]; +static void *allocate(size_t n){allocations++;return oom?NULL:malloc(n);} +#define TS_MALLOC_PSRAM allocate +static bool ts_http_authorize_route(ts_http_request_t *r,const ts_http_route_t *d){(void)r;(void)d;return true;} +static int httpd_resp_set_status(httpd_req_t *r,const char *s){(void)r;snprintf(wire_status,sizeof(wire_status),"%s",s);return 0;} +static int httpd_resp_sendstr(httpd_req_t *r,const char *s){(void)r;(void)s;return 0;} +static int httpd_resp_set_hdr(httpd_req_t *r,const char *key,const char *value){(void)r;assert(!strcmp(key,"Cache-Control")&&!strcmp(value,"no-store"));return ESP_OK;} +static int httpd_resp_set_type(httpd_req_t *r,const char *s){(void)r;(void)s;return 0;} +static int httpd_resp_send(httpd_req_t *r,const char *b,size_t n){(void)r;assert(n=fail_after){int ret=failure;failure=-1;return ret==-2?0:ret;} + size_t got=n>1024?1024:n;if(failure&&got>fail_after-position)got=fail_after-position; + assert(position+got<=sizeof(payload));memcpy(b,payload+position,got);position+=got;return (int)got; +} +static int business(ts_http_request_t *r,void *d){ + (void)d;calls++;assert(r->body_len==r->req->content_len); + if(r->body_len){assert(r->body[r->body_len]=='\0');assert(!memcmp(r->body,payload,r->body_len));}return ESP_OK; +} +''' +code+=function(http,'ts_http_send_response')+function(http,'ts_http_send_json')+function(http,'ts_http_send_error') +code+=function(http,'ts_http_admit_body')+function(http,'ts_http_receive_body',False)+function(http,'http_handler_wrapper')+function(https,'https_handler_wrapper') +code+=r''' +static void reset(void){oom=false;calls=reads=allocations=status=0;position=0;failure=0;fail_after=0;wire_status[0]=response_body[0]=0;} +static void bodies(void){ + for(unsigned i=0;i0));} + const int errors[]={-1,0,HTTPD_SOCK_ERR_TIMEOUT}; + for(unsigned i=0;i +#include "mbedtls/base64.h" +#undef ESP_LOGD +#undef ESP_LOGE +static char diagnostics[8192]; +static void private_log(const char *fmt,...){size_t used=strlen(diagnostics);va_list args;va_start(args,fmt);vsnprintf(diagnostics+used,sizeof(diagnostics)-used,fmt,args);va_end(args);} +#define ESP_LOGD(tag,...) private_log(__VA_ARGS__) +#define ESP_LOGE(tag,...) private_log(__VA_ARGS__) +#define TAG "http-privacy" +#define esp_crypto_base64_encode mbedtls_base64_encode +#define ESP_RETURN_ON_FALSE(condition,result,tag,...) do{if(!(condition))return(result);}while(0) +#define ESP_GOTO_ON_FALSE(condition,result,label,tag,...) do{if(!(condition)){ret=(result);goto label;}}while(0) +#define HTTP_EVENT_ON_HEADER 3 +static unsigned header_callbacks,event_callbacks,authorization_writes; +static bool fail_authorization; +static char delivered_key[100],delivered_value[256],authorization[256]; +typedef struct client { + struct {const char *username,*password;} connection_info; + char *current_header_key,*current_header_value; + struct {char *header_key,*header_value;} event; +} *esp_http_client_handle_t; +static esp_err_t esp_http_client_set_header(esp_http_client_handle_t client,const char *key,const char *value){(void)client;assert(!strcmp(key,"Authorization"));authorization_writes++;snprintf(authorization,sizeof(authorization),"%s",value);return fail_authorization?ESP_FAIL:ESP_OK;} +static void http_dispatch_event(esp_http_client_handle_t client,int event,void *data,int length){assert(event==HTTP_EVENT_ON_HEADER&&!data&&!length);header_callbacks++;snprintf(delivered_key,sizeof(delivered_key),"%s",client->event.header_key);snprintf(delivered_value,sizeof(delivered_value),"%s",client->event.header_value);} +static void http_dispatch_event_to_event_loop(int event,void *data,size_t length){assert(event==HTTP_EVENT_ON_HEADER&&data&&length==sizeof(esp_http_client_handle_t));event_callbacks++;} +''' +code+=body(IDF/'components/esp_http_client/lib/http_auth.c','http_auth_basic') +for path,suffix in ((original_path,'original'),(prepared,'prepared')): + for name in ('esp_http_client_prepare_basic_auth','http_on_header_event'): + code+=body(path,name).replace(name+'(',name+'_'+suffix+'(',1) +code+=r''' +static unsigned checks; +static void check(bool ok,const char *why){checks++;if(!ok){fprintf(stderr,"FAIL %s\n",why);abort();}} +static void reset(void){diagnostics[0]=authorization[0]=delivered_key[0]=delivered_value[0]=0;header_callbacks=event_callbacks=authorization_writes=0;fail_authorization=false;} +int main(void){ + struct client client={.connection_info={"synthetic-user","synthetic-password"}}; + reset();check(esp_http_client_prepare_basic_auth_original(&client)==ESP_OK&&authorization_writes==1,"original SDK creates real Basic credential"); + check(strstr(diagnostics,EXPECTED_BASIC)!=NULL,"original SDK Debug record contains directly reversible synthetic Basic credential"); + reset();check(esp_http_client_prepare_basic_auth_prepared(&client)==ESP_OK&&authorization_writes==1&&!strcmp(authorization,EXPECTED_BASIC),"prepared SDK sends identical Basic authorization through actual SDK base64 producer"); + check(!strstr(diagnostics,"synthetic-user")&&!strstr(diagnostics,"synthetic-password")&&!strstr(diagnostics,EXPECTED_BASIC)&&strstr(diagnostics,"prepared"),"prepared diagnostics retain state and never authentication bytes"); + fail_authorization=true;check(esp_http_client_prepare_basic_auth_prepared(&client)==ESP_FAIL,"header-setting failure semantics unchanged"); + const char *keys[]={"Set-Cookie","Authorization","X-Private-Fixture"}; + for(unsigned i=0;i<3;i++){ + reset();client.current_header_key=strdup(keys[i]);client.current_header_value=strdup("synthetic-private-response-value"); + check(http_on_header_event_original(&client)==0&&header_callbacks==1&&event_callbacks==1&&strstr(diagnostics,"synthetic-private-response-value"),"original SDK response-header Debug path discloses synthetic private field"); + check(!client.current_header_key&&!client.current_header_value,"original SDK callback releases owned header strings"); + reset();client.current_header_key=strdup(keys[i]);client.current_header_value=strdup("synthetic-private-response-value"); + check(http_on_header_event_prepared(&client)==0&&header_callbacks==1&&event_callbacks==1&&!strcmp(delivered_key,keys[i])&&!strcmp(delivered_value,"synthetic-private-response-value"),"same complete private headers still delivered once to actual application and event loop boundaries"); + check(!client.current_header_key&&!client.current_header_value&&!strstr(diagnostics,"synthetic-private-response-value")&&!strstr(diagnostics,keys[i]),"prepared global Debug receives neither field name/value while cleanup remains complete"); + } + printf("%u checks: actual original/prepared SDK Basic auth + header events, real SDK base64 crypto, preserved credentials/callbacks/error/cleanup with private global logs; no network or real secrets\n",checks); +} +''' +expected='Basic '+base64.b64encode(b'synthetic-user:synthetic-password').decode() +code='#define EXPECTED_BASIC "'+expected+'"\n'+code +sdk=sdk_library_dir(IDF) +run_native(code,[sdk/'library/libmbedcrypto.a'],(),[IDF/'components/mbedtls/mbedtls/include']) +assert hashlib.sha256(original_path.read_bytes()).hexdigest()==metadata['http_sdk_sha256'] +print('PASS 10 exact SDK diagnostic sites adapted, source drift rejects and shared SDK byte hashes unchanged') + +# Replay exact reviewed sink statements without claiming a socket handshake. +# The error formatter itself runs in full and preserves its application event. +private = re.compile(r'\b(?:host|ws->sub_protocol|ws->auth|ws->headers|ws->buffer|server_key|client_key|expected_server_key|client->errormsg_buffer|client->config->scheme|uri|client->config->host)\b') +def private_statements(text): + return [m.group() for m in re.finditer(r'ESP_LOG(?:D|E)\s*\([\s\S]*?\);', text) + if private.search(re.sub(r'"(?:\\.|[^"\\])*"', '""', m.group()))] +original_sinks=private_statements(ws_original.decode())+private_statements(websocket_original.decode()) +assert len(original_sinks)==11, original_sinks +prepared_sinks=[] +# Find each replacement at the same source line, not a duplicated test policy. +for original_text,prepared_text in [(ws_original.decode(),(work/'transport_ws.c').read_text()),(websocket_original.decode(),(work/'esp_websocket_client.c').read_text())]: + for statement in private_statements(original_text): + before=original_text[:original_text.index(statement)] + # Match the enclosing function's statement ordinal. Formatting adaptation + # adds lines, so a source-line offset is not a stable identifier. + prefix=list(re.finditer(r'ESP_LOG(?:D|E)\s*\([\s\S]*?\);',before)) + prepared_sinks.append(list(re.finditer(r'ESP_LOG(?:D|E)\s*\([\s\S]*?\);',prepared_text))[len(prefix)].group()) +with tempfile.TemporaryDirectory(prefix='ts-sdk-ws-anchor-') as directory: + fake=Path(directory) + for src in (original_path,transport_path,ws_path): + out=fake/src.relative_to(IDF);out.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(src,out) + managed=fake/'managed.c';managed.write_bytes(websocket_original) + for i,statement in enumerate(original_sinks): + is_transport=statement in ws_original.decode() + target=fake/ws_path.relative_to(IDF) if is_transport else managed + clean=ws_original.decode() if is_transport else websocket_original.decode() + target.write_text(clean.replace(statement,statement.replace('ESP_LOG','DRIFT_LOG',1),1)) + output=fake/('out-'+str(i)) + try:preparation.prepare(fake,output,managed) + except ValueError:pass + else:raise AssertionError('changed WS diagnostic anchor accepted: '+statement) + assert not output.exists(), 'partial generated sources published after rejected drift' + target.write_text(clean) + +ws_code=RTOS+r''' +#undef ESP_LOGD +#undef ESP_LOGE +#define TAG "ws-privacy" +#define ESP_LOGD(tag,...) private_log(__VA_ARGS__) +#define ESP_LOGE(tag,...) private_log(__VA_ARGS__) +#define WEBSOCKET_EVENT_ERROR 9 +#define WS_OVER_TCP_SCHEME "ws" +#define WS_OVER_TLS_SCHEME "wss" +static char diagnostics[8192],event_text[4096];static unsigned events,checks;static bool fail_alloc; +static void private_log(const char *fmt,...){size_t used=strlen(diagnostics);va_list a;va_start(a,fmt);vsnprintf(diagnostics+used,sizeof(diagnostics)-used,fmt,a);va_end(a);} +struct config{const char *scheme,*host;int port;}; +typedef struct ws_client{size_t errormsg_size;char *errormsg_buffer;struct config *config;} *esp_websocket_client_handle_t; +static void *error_alloc(size_t n){return fail_alloc?NULL:malloc(n);} +static int esp_websocket_client_dispatch_event(esp_websocket_client_handle_t client,int event,const char *data,int len){(void)client;assert(event==WEBSOCKET_EVENT_ERROR&&len>=0&&(size_t)len==strlen(data));events++;snprintf(event_text,sizeof(event_text),"%s",data);return ESP_OK;} +#define malloc error_alloc +''' +ws_code+=body(work/'esp_websocket_client.c','esp_websocket_client_error')+'\n#undef malloc\n' +for suffix,statements in [('original',original_sinks),('prepared',prepared_sinks)]: + ws_code+='static void sinks_'+suffix+'(const char *secret){\n'+r''' + const char *host=secret,*server_key=secret,*client_key=secret,*expected_server_key=secret,*uri=secret;int port=443,needed_size=(int)strlen(secret); + struct {const char *sub_protocol,*auth,*headers,*buffer;} storage={secret,secret,secret,secret},*ws=&storage; + struct config config={secret,secret,443};struct ws_client instance={.errormsg_buffer=(char*)secret,.config=&config},*client=&instance; +'''+'\n'.join(statements)+'\n}\n' +ws_code+=r''' +static void check(bool ok,const char *why){checks++;if(!ok){fprintf(stderr,"FAIL %s\n",why);abort();}} +static void reset(void){diagnostics[0]=event_text[0]=0;events=0;} +int main(void){ + const char *secret="synthetic-ws-private-user:password/query-token"; + reset();sinks_original(secret);check(strstr(diagnostics,secret)!=NULL,"original SDK diagnostic statements disclose synthetic authentication/URI contents"); + reset();sinks_prepared(secret);check(!strstr(diagnostics,secret)&&diagnostics[0],"all eleven adapted diagnostics preserve state/count without private bytes"); + struct ws_client client={0};char expected[4096]; + snprintf(expected,sizeof(expected),"uri=%s count=%d fractional=%.2f length=%zu",secret,731,4.25,strlen(secret)); + reset();check(esp_websocket_client_error(&client,"uri=%s count=%d fractional=%.2f length=%zu",secret,731,4.25,strlen(secret))==ESP_OK,"actual formatted SDK error succeeds"); + check(events==1&&!strcmp(event_text,expected),"va_copy retains complete mixed arguments exactly once in application event"); + check(!strstr(diagnostics,secret)&&strstr(diagnostics,"WebSocket client error"),"error event contents do not enter global error log"); + size_t original_size=client.errormsg_size;char *original_buffer=client.errormsg_buffer; + reset();check(esp_websocket_client_error(&client,"code=%d",7)==ESP_OK&&events==1&&!strcmp(event_text,"code=7")&&client.errormsg_buffer==original_buffer&&client.errormsg_size==original_size,"existing error storage reused without truncation"); + reset();fail_alloc=true;check(esp_websocket_client_error(&client,"%04096d",1)==ESP_ERR_NO_MEM&&!events&&!client.errormsg_buffer&&!client.errormsg_size,"allocation failure emits no partial or stale error event");fail_alloc=false; + reset();check(esp_websocket_client_error(&client,"retry=%s:%u",secret,17u)==ESP_OK&&events==1&&strstr(event_text,secret)&&!strstr(diagnostics,secret),"normal application callback recovers after allocation failure with private bytes intact"); + free(client.errormsg_buffer); + printf("%u checks: actual prepared WebSocket error formatter/event, exact eleven original/prepared sink statements, preserved mixed varargs/storage/error paths; no network or real secrets\n",checks); +} +''' +run_native(ws_code) +assert websocket_path.read_bytes()==websocket_original and ws_path.read_bytes()==ws_original +print('PASS eleven WS diagnostic anchors individually reject drift before any output; shared SDK and managed dependency unchanged') diff --git a/tests/runtime/test_http_fetch.py b/tests/runtime/test_http_fetch.py new file mode 100644 index 00000000..6f9844cf --- /dev/null +++ b/tests/runtime/test_http_fetch.py @@ -0,0 +1,126 @@ +"""Actual shared HTTP owner and URL/DNS snapshot; SDK events and clock substituted.""" +from pathlib import Path +from test_console_lifecycle import IDF, run_native + +root=Path(__file__).resolve().parents[2] +code=r''' +#include +#include +#include +#include +#include +#include +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#include "ts_dns.h" +static int scenario; +enum {NORMAL,PARTIAL,TOO_BIG,UNKNOWN_BIG,WAIT,CANCEL,DNS_FAIL,DNS_LATE,AUTH_RETRY,REDIRECT,HEADER_ACK,EXPIRE_EVENT}; +static int64_t clock_us; +static bool actor=true,fail_init,fail_header,fail_body,fail_heap; +static unsigned dns_calls,clients,cleanups,closes,performs,checks; +static char numeric_url[2300],host_header[300],tls_name[260],authorization[100],body_sent[100]; +static const char *expected_ca; +static void check(bool value,const char *message){checks++;if(!value){fprintf(stderr,"FAIL %s scenario=%d\n",message,scenario);abort();}} +static void *body_malloc(size_t n){return fail_body?NULL:malloc(n);} +static void *body_heap(size_t n,unsigned caps){(void)caps;return fail_heap?NULL:body_malloc(n);} +static bool caller(void *context){assert(context==&actor);return actor;} +int64_t esp_timer_get_time(void){return clock_us;} +void vTaskDelay(unsigned ticks){clock_us+=(int64_t)ticks*1000;} +static int esp_crt_bundle_attach(void *p){(void)p;return ESP_OK;} +static char *ipaddr_ntoa_r(const ip_addr_t *ip,char *out,int size){snprintf(out,(size_t)size,"%s",ip->v6?"2001:db8::10":"192.0.2.10");return out;} +esp_err_t ts_dns_resolve(const char *host,int64_t deadline,bool(*current)(void*),void *context,ip_addr_t *out){ + ++dns_calls;assert(!current||current(context));out->v6=strchr(host,':')!=NULL; + if(scenario==DNS_FAIL)return ESP_ERR_NOT_FOUND; + if(scenario==DNS_LATE){clock_us=deadline;return ESP_ERR_TIMEOUT;} + return ESP_OK; +} +struct fixture_client {esp_http_client_config_t config;int status;int64_t declared;bool complete,closed;}; +esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config){ + check(config->is_async&&config->disable_auto_redirect&&!config->skip_cert_common_name_check,"async, no redirect forwarding and mandatory names"); + check(config->cert_pem==expected_ca&&(expected_ca?!config->crt_bundle_attach:config->crt_bundle_attach!=NULL),"explicit issuer or SDK bundle"); + snprintf(numeric_url,sizeof(numeric_url),"%s",config->url);snprintf(tls_name,sizeof(tls_name),"%s",config->common_name?config->common_name:""); + if(fail_init)return NULL; + struct fixture_client *client=calloc(1,sizeof(*client));client->config=*config;client->status=200;client->declared=3;clients++;return client; +} +esp_err_t esp_http_client_set_header(esp_http_client_handle_t client,const char *name,const char *value){(void)client; + if(fail_header)return ESP_FAIL; + if(!strcmp(name,"Host"))snprintf(host_header,sizeof(host_header),"%s",value); + if(!strcmp(name,"Authorization"))snprintf(authorization,sizeof(authorization),"%s",value); + return ESP_OK; +} +esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client,int timeout){(void)client;check(timeout==0,"SDK polls have no per-operation blocking timeout");return ESP_OK;} +esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client,const char *body,int length){(void)client;assert(length==(int)strlen(body));snprintf(body_sent,sizeof(body_sent),"%s",body);return ESP_OK;} +esp_err_t esp_http_client_close(esp_http_client_handle_t client){closes++;client->closed=true;return ESP_OK;} +esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client){cleanups++;free(client);return ESP_OK;} +int esp_http_client_get_status_code(esp_http_client_handle_t client){return client->status;} +int64_t esp_http_client_get_content_length(esp_http_client_handle_t client){return client->declared;} +bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client){return client->complete;} +static void event(esp_http_client_handle_t client,int kind,const char *data,int length){esp_http_client_event_t e={.client=client,.event_id=kind,.user_data=client->config.user_data,.data=(void*)data,.data_len=length};client->config.event_handler(&e);} +esp_err_t esp_http_client_perform(esp_http_client_handle_t client){ + performs++; + if(scenario==WAIT)return ESP_ERR_HTTP_EAGAIN; + event(client,HTTP_EVENT_ON_CONNECTED,NULL,0); + event(client,HTTP_EVENT_HEADERS_SENT,NULL,0); + if(scenario==CANCEL)actor=false; + if(scenario==EXPIRE_EVENT)clock_us+=10000000; + if(scenario==REDIRECT){client->status=302;client->declared=0;client->complete=true;event(client,HTTP_EVENT_REDIRECT,NULL,0);event(client,HTTP_EVENT_ON_FINISH,NULL,0);return ESP_OK;} + if(scenario==AUTH_RETRY){client->status=401;event(client,HTTP_EVENT_ON_DATA,"bad",3);event(client,HTTP_EVENT_ON_FINISH,NULL,0);check(!client->closed,"header-only mode cannot suppress authentication retries");event(client,HTTP_EVENT_HEADERS_SENT,NULL,0);client->status=200;} + if(scenario==TOO_BIG)client->declared=9999; + if(scenario==UNKNOWN_BIG){client->declared=-1;event(client,HTTP_EVENT_ON_DATA,"1234567890",10);event(client,HTTP_EVENT_ON_DATA,"1234567890",10);} + else event(client,HTTP_EVENT_ON_DATA,"abc",3); + client->complete=scenario!=PARTIAL; + if(client->complete&&!client->closed)event(client,HTTP_EVENT_ON_FINISH,NULL,0); + return client->closed?ESP_FAIL:ESP_OK; +} +#define malloc body_malloc +#define heap_caps_malloc body_heap +''' +for name in ['ts_http_target.c','ts_http_fetch.c']: + code+='#include "'+str(root/'components/ts_http_fetch/src'/name)+'"\n' +code+=r''' +#undef malloc +static ts_http_fetch_config_t request; +static ts_http_fetch_result_t reply; +static void reset(int chosen){scenario=chosen;clock_us=0;actor=true;fail_init=fail_header=fail_body=fail_heap=false;dns_calls=clients=cleanups=closes=performs=0;expected_ca=NULL;numeric_url[0]=host_header[0]=tls_name[0]=authorization[0]=body_sent[0]=0;request=(ts_http_fetch_config_t){.url="https://sensor.fixture:8443/read?x=1",.method=HTTP_METHOD_GET,.timeout_ms=20,.maximum_body=16,.current=caller,.context=&actor};memset(&reply,0,sizeof(reply));} +static esp_err_t fetch(void){esp_err_t result=ts_http_fetch(&request,&reply);check(clients==cleanups,"every initialized client is cleaned");if(result!=ESP_OK)check(!reply.body&&!reply.length,"failed/truncated samples cannot become partial success");return result;} +int main(void){ + reset(NORMAL);check(fetch()==ESP_OK&&reply.length==3&&!strcmp(reply.body,"abc"),"normal complete body");check(reply.dns_ok&&reply.connected&&!strcmp(reply.resolved_ip,"192.0.2.10"),"diagnostic phases come from actual resolver and SDK connection event");check(!strcmp(numeric_url,"https://192.0.2.10:8443/read?x=1")&&!strcmp(host_header,"sensor.fixture:8443")&&!strcmp(tls_name,"sensor.fixture"),"resolved address is pinned while Host/SNI retain original authority");free(reply.body); + reset(NORMAL);request.url="http://[::1]:8080/read";request.method=HTTP_METHOD_POST;request.body="{}";request.authorization="Bearer synthetic";check(fetch()==ESP_OK&&!tls_name[0]&&!strcmp(host_header,"[::1]:8080")&&!strcmp(body_sent,"{}")&&!strcmp(authorization,"Bearer synthetic"),"HTTP LAN/IPv6 POST and credentials preserved");free(reply.body); + reset(NORMAL);expected_ca="synthetic private issuer";request.cert_pem=expected_ca;check(fetch()==ESP_OK,"private CA does not disable hostname verification");free(reply.body); + for(int i=PARTIAL;i<=DNS_LATE;i++){reset(i);check(fetch()!=ESP_OK,"partial,overflow,deadline,cancel,DNS failures reject");if(i==WAIT)check(clock_us==20000&&performs==20,"one total deadline includes all polls");} + reset(AUTH_RETRY);check(fetch()==ESP_OK&&reply.length==3&&!strcmp(reply.body,"abc"),"auth retry returns only final body");free(reply.body); + reset(AUTH_RETRY);request.headers_only=true;check(fetch()==ESP_OK&&reply.status==200&&!reply.body&&closes,"webhook header acknowledgment survives401 challenge and closes after200"); + reset(HEADER_ACK);request.headers_only=true;check(fetch()==ESP_OK&&reply.status==200&&!reply.body&&closes,"webhook needs no body allocation/drain"); + reset(EXPIRE_EVENT);check(fetch()==ESP_ERR_TIMEOUT,"callback data cannot arrive after total deadline"); + reset(REDIRECT);check(fetch()==ESP_OK&&reply.status==302&&clients==1,"redirect is returned without another target or credential forwarding");free(reply.body); + reset(NORMAL);fail_init=true;check(fetch()==ESP_ERR_NO_MEM,"client allocation failure releases body and target"); + reset(NORMAL);fail_header=true;check(fetch()==ESP_FAIL&&!performs,"request setup failure precedes transport effects"); + reset(NORMAL);fail_body=true;check(fetch()==ESP_ERR_NO_MEM&&!dns_calls&&!clients,"body allocation fails before DNS/transport"); + reset(NORMAL);fail_heap=true;check(fetch()==ESP_OK,"internal RAM fallback retained if PSRAM allocation unavailable");free(reply.body); + const char *bad[]={"file:///sdcard/a","https://bad host/read","https://sensor.fixture:0/a","https://sensor.fixture/\\x"}; + for(unsigned i=0;iv6)\nesp_err_t ts_dns_resolve(const char*,int64_t,bool(*)(void*),void*,ip_addr_t*);\n', + 'esp_crt_bundle.h':'#pragma once\n','esp_heap_caps.h':'#pragma once\n#define MALLOC_CAP_SPIRAM 1\n#define MALLOC_CAP_8BIT 2\n', + 'esp_timer.h':'#pragma once\nint64_t esp_timer_get_time(void);\n', + 'freertos/FreeRTOS.h':'#pragma once\n','freertos/task.h':'#pragma once\nvoid vTaskDelay(unsigned);\n', + 'http_parser.h':(IDF/'components/http_parser/http_parser.h').read_text()}) +run_native(code,[IDF/'components/http_parser/http_parser.c',IDF/'components/json/cJSON/cJSON.c',root/'components/ts_http_fetch/src/ts_http_url.c'],headers) diff --git a/tests/runtime/test_http_file_stream.py b/tests/runtime/test_http_file_stream.py index c00e51b5..05b0fd69 100644 --- a/tests/runtime/test_http_file_stream.py +++ b/tests/runtime/test_http_file_stream.py @@ -1,5 +1,11 @@ """Production file sender and HTTP wrapper, real stdio incl. injected read EIO.""" from test_console_lifecycle import body, run_native +import os +from pathlib import Path + +def sender_body(path,name): + override=os.environ.get("TS_JSON_CACHE_BEFORE") + return body(Path(override)/path if override and (Path(override)/path).exists() else path,name) code = r''' #define _DARWIN_C_SOURCE @@ -20,11 +26,20 @@ #define HTTP_GET 0 #define HTTPD_SOCK_ERR_TIMEOUT -7 #define HTTPD_500_INTERNAL_SERVER_ERROR 500 +#define HTTPD_200 "200 OK" +#define HTTPD_400 "400 Bad Request" +#define HTTPD_404 "404 Not Found" +#define HTTPD_500 "500 Internal Server Error" #define TAG "fixture" +static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;} typedef struct {void *user_ctx;const char *uri;int method;size_t content_len;} httpd_req_t; typedef struct {httpd_req_t *req;const char *uri;int method;char *body;size_t body_len;} ts_http_request_t; -typedef struct {int (*handler)(ts_http_request_t*,void*);void *user_data;} ts_http_route_t; -static bool s_stopping,accept_gzip; +typedef struct {int (*handler)(ts_http_request_t*,void*);void *user_data;bool (*admit)(ts_http_request_t*,void*);size_t max_body_bytes;uint32_t body_timeout_ms;} ts_http_route_t; +static bool s_stopping,accept_gzip,fail_type; +static unsigned header_calls,fail_header; +static char mime[100],disposition[900],csp[120],nosniff[30]; +static const char *disposition_pointer; +static bool ts_http_authorize_route(ts_http_request_t *r,const ts_http_route_t *d){(void)r;(void)d;return true;} static size_t fault_after=SIZE_MAX,position,received; static int opened,closed,ends,chunks,fail_chunk,fail_end,json_errors; static char payload[100000],wire[100000]; @@ -50,10 +65,15 @@ cookie_io_functions_t io={.read=cookie_reader,.close=closer};return fopencookie(f,"r",io); #endif } -static int httpd_resp_set_type(httpd_req_t *r,const char *s){(void)r;(void)s;return ESP_OK;} +static int httpd_resp_set_type(httpd_req_t *r,const char *s){(void)r;snprintf(mime,sizeof(mime),"%s",s);return fail_type?ESP_FAIL:ESP_OK;} static char encoding[20],cache[100]; -static int httpd_resp_set_hdr(httpd_req_t *r,const char *k,const char *s){(void)r;if(!strcmp(k,"Content-Encoding"))strcpy(encoding,s);if(!strcmp(k,"Cache-Control"))strcpy(cache,s);return ESP_OK;} -static int httpd_resp_send(httpd_req_t *r,const char *p,size_t n){(void)r;memcpy(wire+received,p,n);received+=n;return ESP_OK;} +static int httpd_resp_set_hdr(httpd_req_t *r,const char *k,const char *s){ + (void)r;if(++header_calls==fail_header)return ESP_FAIL; + if(!strcmp(k,"Content-Encoding"))strcpy(encoding,s);if(!strcmp(k,"Cache-Control"))strcpy(cache,s); + if(!strcmp(k,"Content-Disposition")){strcpy(disposition,s);disposition_pointer=s;}if(!strcmp(k,"Content-Security-Policy"))strcpy(csp,s);if(!strcmp(k,"X-Content-Type-Options"))strcpy(nosniff,s); + return ESP_OK; +} +static int httpd_resp_send(httpd_req_t *r,const char *p,size_t n){(void)r;if(disposition_pointer)assert(!strcmp(disposition_pointer,disposition));if(n)memcpy(wire+received,p,n);received+=n;return ESP_OK;} static int httpd_resp_send_chunk(httpd_req_t *r,const char *p,size_t n){ if(!n){++ends;return fail_end?ESP_FAIL:ESP_OK;} if(++chunks==fail_chunk)return ESP_FAIL;return httpd_resp_send(r,p,n); @@ -65,27 +85,55 @@ static int httpd_req_recv(httpd_req_t *r,void *p,size_t n){(void)r;(void)p;(void)n;assert(false);return -1;} #define fopen open_stream ''' -code += body('components/ts_net/src/ts_http_server.c', 'ts_http_send_file') +for name in ['send_file', 'ts_http_send_file', 'ts_http_send_private_file']: + code += body('components/ts_net/src/ts_http_server.c', name) code += '\n#undef fopen\n' +code += body('components/ts_net/src/ts_http_server.c', 'ts_http_admit_body') +code += body('components/ts_net/src/ts_http_server.c', 'ts_http_receive_body') code += body('components/ts_net/src/ts_http_server.c', 'http_handler_wrapper') +code += sender_body('components/ts_net/src/ts_http_server.c','ts_http_send_response') +code += sender_body('components/ts_net/src/ts_http_server.c','ts_http_send_json') +code += '\ntypedef ts_http_request_t ts_https_req_t;\n' +code += sender_body('components/ts_https/src/ts_https.c','ts_https_send_json') code += r''' static int route_file(ts_http_request_t *r,void *p){return ts_http_send_file(r,p);} -static void reset(void){opened=closed=ends=chunks=fail_chunk=fail_end=json_errors=0;received=0;encoding[0]=cache[0]=0;fault_after=SIZE_MAX;} +static int route_private_file(ts_http_request_t *r,void *p){return ts_http_send_private_file(r,p);} +static void reset(void){opened=closed=ends=chunks=fail_chunk=fail_end=json_errors=0;disposition_pointer=NULL;received=header_calls=fail_header=0;fail_type=false;encoding[0]=cache[0]=mime[0]=disposition[0]=csp[0]=nosniff[0]=0;fault_after=SIZE_MAX;} static void make(const char *p,size_t n){FILE *f=fopen(p,"wb");assert(f);assert(fwrite(payload,1,n,f)==n);assert(!fclose(f));} static int request(const char *p){ts_http_route_t route={route_file,(void*)p};httpd_req_t req={.user_ctx=&route,.uri=p,.method=HTTP_GET};return http_handler_wrapper(&req);} +static int private_request(const char *p){ts_http_route_t route={route_private_file,(void*)p};httpd_req_t req={.user_ctx=&route,.uri="/api/v1/file/download",.method=HTTP_GET};return http_handler_wrapper(&req);} int main(void){ + const char *json="{\"private_key\":\"synthetic-json-canary\",\"code\":0}"; + httpd_req_t raw={0};ts_http_request_t json_req={.req=&raw}; + int statuses[]={200,201,400,401,403,404,409,413,429,500,503}; + for(unsigned i=0;i=32768));assert(opened==closed); + reset();assert(private_request("file+v1.bin")==ESP_OK); + assert(!strcmp(cache,"no-store")&&!strcmp(nosniff,"nosniff")&&strstr(csp,"sandbox")&&strstr(csp,"default-src 'none'")&&strstr(disposition,"attachment;")&&received==sizes[i]&&!memcmp(wire,payload,received)&&!json_errors); + assert(ends==(sizes[i]>=32768)&&opened==closed); } make("file+v1.bin",65536); size_t boundaries[]={0,1,8192,17000,65535}; for(unsigned i=0;i +#include +#include +#include +#define ESP_LOGV(...) ((void)0) +#define ESP_STATIC_ANALYZER_CHECK(condition,result) do {if(condition)return(result);} while(0) +typedef struct {int sockfd;void *tls;} transport_esp_tls_t; +typedef transport_esp_tls_t *esp_transport_handle_t; +static transport_esp_tls_t *ssl_get_context_data(esp_transport_handle_t transport){return transport;} +static int esp_tls_get_bytes_avail(void *tls){(void)tls;return 0;} +static void esp_transport_capture_errno(esp_transport_handle_t transport,int error){(void)transport;(void)error;} +static struct timeval *esp_transport_utils_ms_to_timeval(int ms,struct timeval *value){if(ms<0)return NULL;value->tv_sec=ms/1000;value->tv_usec=(ms%1000)*1000;return value;} +''' +code+='\n'.join(functions)+'\n#define HTTP_MAX_HEADER_SIZE 16384\n#include "'+str(IDF/'components/http_parser/http_parser.c')+'"\n' +client_prepared=(work/'esp_http_client.c').read_text() +start=client_prepared.index('static int esp_http_client_get_data(') +end=client_prepared.index('\n}\n',start)+3 +code+=r''' +#define HTTP_STATE_RES_ON_DATA_START 4 +#define HTTP_METHOD_HEAD 2 +#define ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN -3 +typedef struct {char *data;int len;} esp_http_buffer_t; +typedef struct {esp_http_buffer_t *buffer;int64_t data_process,content_length;} fixture_response_t; +typedef struct fixture_client {int state,timeout_ms;bool is_async,is_chunk_complete;struct {int method;} connection_info;fixture_response_t *response;http_parser *parser;http_parser_settings *parser_settings;void *transport;} fixture_client_t; +typedef fixture_client_t *esp_http_client_handle_t; +static int transport_read_result; +static int esp_transport_read(void *transport,char *data,int length,int timeout){(void)transport;(void)data;(void)length;(void)timeout;return transport_read_result;} +''' +# Actual prepared SDK get_data uses its configured receive buffer size. +code=code.replace('int state,timeout_ms;bool','int state,timeout_ms,buffer_size_rx;bool') +code+=client_prepared[start:end] +code+=r''' +static unsigned checks;static size_t body_bytes; +static void check(bool value,const char *message){checks++;if(!value){fprintf(stderr,"FAIL %s\n",message);abort();}} +static int body(http_parser *parser,const char *bytes,size_t length){(void)parser;(void)bytes;body_bytes+=length;return 0;} +static void header_size(size_t length,bool valid){ + char *message=malloc(length+128);assert(message);size_t prefix=(size_t)sprintf(message,"HTTP/1.1 200 OK\r\nX-Fixture: "); + memset(message+prefix,'x',length);const char *end="\r\nContent-Length: 0\r\n\r\n";memcpy(message+prefix+length,end,strlen(end));size_t total=prefix+length+strlen(end); + http_parser parser;http_parser_init(&parser,HTTP_RESPONSE);http_parser_settings settings={0};size_t parsed=http_parser_execute(&parser,&settings,message,total); + check(valid?(parsed==total&&HTTP_PARSER_ERRNO(&parser)==HPE_OK):HTTP_PARSER_ERRNO(&parser)==HPE_HEADER_OVERFLOW,"actual SDK parser enforces selected full-header limit without reimplementing parsing");free(message); +} +static int eof_complete(http_parser *parser){((esp_http_client_handle_t)parser->data)->is_chunk_complete=true;return 0;} +static void eof_case(const char *message,int read_result,bool complete){ + http_parser parser;http_parser_init(&parser,HTTP_RESPONSE);http_parser_settings settings={.on_message_complete=eof_complete}; + char bytes[64];esp_http_buffer_t buffer={.data=bytes};fixture_response_t response={.buffer=&buffer}; + fixture_client_t client={.state=HTTP_STATE_RES_ON_DATA_START,.is_async=true,.response=&response,.parser=&parser,.parser_settings=&settings}; + parser.data=&client;assert(http_parser_execute(&parser,&settings,message,strlen(message))==strlen(message)); + transport_read_result=read_result;errno=EAGAIN;int result=esp_http_client_get_data((esp_http_client_handle_t)&client); + check(complete?(result==0&&client.is_chunk_complete&&HTTP_PARSER_ERRNO(&parser)==HPE_OK&&errno==0):!client.is_chunk_complete,"confirmed FIN completes only legal EOF framing; short CL/chunks, resets and retry-without-data never become complete"); +} +int main(void){ + int pair[2];assert(!socketpair(AF_UNIX,SOCK_STREAM,0,pair));transport_esp_tls_t transport={.sockfd=pair[0]}; + errno=EIO;check(base_poll_read(&transport,0)==0&&errno==EAGAIN,"zero-timeout no-data poll is retryable nonblocking I/O"); + errno=EIO;check(base_poll_read(&transport,1)==0&&errno==EIO,"positive blocking-timeout errno behavior is unchanged"); + assert(write(pair[1],"a",1)==1);errno=EAGAIN; + check(base_poll_read(&transport,0)>0&&errno==0,"read readiness cannot inherit stale EAGAIN");char byte;assert(read(pair[0],&byte,1)==1); + errno=EAGAIN;check(base_poll_write(&transport,0)>0&&errno==0,"write readiness cannot hide a later real write failure behind stale EAGAIN"); + int flags=fcntl(pair[0],F_GETFL,0);assert(flags>=0&&!fcntl(pair[0],F_SETFL,flags|O_NONBLOCK)); + char block[4096];memset(block,'x',sizeof(block));while(write(pair[0],block,sizeof(block))>0){}assert(errno==EAGAIN||errno==EWOULDBLOCK); + errno=EIO;check(base_poll_write(&transport,0)==0&&errno==EAGAIN,"full send buffer yields EAGAIN without blocking"); + close(pair[0]);errno=0;check(base_poll_read(&transport,0)<0&&errno==EBADF,"actual select error retains its error instead of becoming retryable");close(pair[1]); + header_size(8192,true);header_size(16300,true);header_size(16400,false); + http_parser parser;http_parser_init(&parser,HTTP_RESPONSE);http_parser_settings settings={.on_body=body}; + const char *header="HTTP/1.1 200 OK\r\nContent-Length: 32768\r\n\r\n";assert(http_parser_execute(&parser,&settings,header,strlen(header))==strlen(header)); + char bytes[32768];memset(bytes,0x5a,sizeof(bytes));check(http_parser_execute(&parser,&settings,bytes,sizeof(bytes))==sizeof(bytes)&&body_bytes==sizeof(bytes)&&HTTP_PARSER_ERRNO(&parser)==HPE_OK,"header budget does not truncate legitimate binary bodies larger than 16KiB"); + eof_case("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nbody",ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN,true); + eof_case("HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nbody",ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN,false); + eof_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nbody\r\n",ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN,false); + eof_case("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nbody",-7,false); + eof_case("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nbody",0,false); + printf("%u checks: actual project-prepared SDK poll functions on local socketpairs, actual SDK HTTP parser, idempotent generation and unchanged SDK checkout; no remote service\n",checks); +} +''' +run_native(code) diff --git a/tests/runtime/test_https_startup.py b/tests/runtime/test_https_startup.py new file mode 100644 index 00000000..a326358e --- /dev/null +++ b/tests/runtime/test_https_startup.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Actual SDK HTTPS startup owner; deterministic allocation and server faults. +--before deliberately fails the original SDK's failed-start ownership assertion. +""" +from pathlib import Path +import re,subprocess,tempfile,os,sys,importlib.util +sdk=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf'));path=sdk/'components/esp_https_server/src/https_server.c';source=path.read_text();original=source +root=Path(__file__).resolve().parents[2] +spec=importlib.util.spec_from_file_location('httpd_preparation',root/'tools/prepare_httpd_admission.py');mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod) +if '--before' not in sys.argv: + with tempfile.TemporaryDirectory(prefix='ts-https-prepare-') as temp: + output=Path(temp)/'out';mod.prepare_https(sdk,output);source=(output/'https_server.c').read_text();mod.prepare_https(sdk,output);assert (output/'https_server.c').read_text()==source + for i,anchor in enumerate(['Server shuts down, releasing SSL context',' ret = httpd_start(&handle, &config->httpd);',' free((void *) cfg->servercert_buf);']): + fake=Path(temp)/('drift-'+str(i));target=fake/'components/esp_https_server/src/https_server.c';target.parent.mkdir(parents=True);assert anchor in original;target.write_text(original.replace(anchor,anchor+' /* drift */',1)) + try:mod.prepare_https(fake,fake/'out') + except ValueError:pass + else:raise AssertionError('HTTPS SDK allocation anchor drift accepted') + assert not(fake/'out').exists() +assert path.read_text()==original,'installed SDK must remain unchanged' + +def function(name): + m=re.search(r'^(?:static )?(?:esp_err_t|void) '+name+r'\([^;]+?\)\s*\{',source,re.M);assert m,name;return source[m.start():source.index('\n}',m.end())+2]+'\n' +code=r''' +#include +#include +#include +#include +#include +#include +typedef int esp_err_t; +#define ESP_OK 0 +#define ESP_FAIL -1 +#define ESP_ERR_NO_MEM 0x101 +#define ESP_ERR_INVALID_ARG 0x102 +#define ESP_ERR_NOT_SUPPORTED 0x107 +#define HTTPD_SSL_TRANSPORT_SECURE 1 +#define HTTPS_SERVER_EVENT_START 1 +#define HTTPS_SERVER_EVENT_STOP 2 +#define ESP_LOGI(...) ((void)0) +#define ESP_LOGD(...) ((void)0) +#define ESP_LOGW(...) ((void)0) +#define ESP_LOGE(...) ((void)0) +static int budget=-1,live; +static void *blocks[32]; +static void *test_malloc(size_t n){if(!budget)return NULL;if(budget>0)budget--;void *p=malloc(n);if(p){for(unsigned i=0;i<32;i++)if(!blocks[i]){blocks[i]=p;live++;return p;}assert(false);}return p;} +static void *test_calloc(size_t n,size_t s){void *p=test_malloc(n*s);if(p)memset(p,0,n*s);return p;} +static void test_free(void *p){if(!p)return;for(unsigned i=0;i<32;i++)if(blocks[i]==p){blocks[i]=NULL;live--;free(p);return;}assert(!"unowned or duplicate SDK free");} +#define malloc test_malloc +#define calloc test_calloc +#define free test_free +typedef struct {void *userdata;const char **alpn_protos;unsigned tls_handshake_timeout_ms;unsigned char *cacert_buf,*servercert_buf;void *serverkey_buf;size_t cacert_bytes,servercert_bytes,serverkey_bytes;bool use_secure_element;void *ticket_ctx;} esp_tls_cfg_server_t; +typedef void *httpd_handle_t; +typedef struct {void *global_transport_ctx;void(*global_transport_ctx_free_fn)(void*);int(*open_fn)(httpd_handle_t,int);unsigned server_port;} httpd_config_t; +struct httpd_ssl_config {httpd_config_t httpd;bool session_tickets,use_secure_element,use_ecdsa_peripheral;void *ssl_userdata;const char **alpn_protos;unsigned tls_handshake_timeout_ms;int user_cb;const unsigned char *cacert_pem,*servercert,*prvtkey_pem;size_t cacert_len,servercert_len,prvtkey_len;unsigned port_secure,port_insecure;int transport_mode;}; +typedef struct httpd_ssl_ctx {esp_tls_cfg_server_t *tls_cfg;int user_cb;int(*open_fn)(httpd_handle_t,int);} httpd_ssl_ctx_t; +static int esp_tls_cfg_server_session_tickets_init(esp_tls_cfg_server_t *cfg){cfg->ticket_ctx=malloc(31);return cfg->ticket_ctx?ESP_OK:ESP_ERR_NO_MEM;} +static void esp_tls_cfg_server_session_tickets_free(esp_tls_cfg_server_t *cfg){if(cfg)free(cfg->ticket_ctx);} +static const char *esp_err_to_name(int e){(void)e;return "synthetic";} +static int httpd_ssl_open(httpd_handle_t h,int fd){(void)h;(void)fd;return ESP_OK;} +static bool force_start_failure; +static httpd_config_t active; +static int httpd_start(httpd_handle_t *out,const httpd_config_t *cfg){if(force_start_failure)return ESP_FAIL;active=*cfg;*out=(void*)1;return ESP_OK;} +static int httpd_stop(httpd_handle_t h){assert(h==(void*)1);if(active.global_transport_ctx_free_fn)active.global_transport_ctx_free_fn(active.global_transport_ctx);memset(&active,0,sizeof(active));return ESP_OK;} +static void http_dispatch_event_to_event_loop(int type,void *p,size_t n){(void)type;(void)p;(void)n;} +''' +for name in (['ts_httpd_free_tls_config'] if 'ts_httpd_free_tls_config(' in source else [])+['free_secure_context','create_secure_context','httpd_ssl_start','httpd_ssl_stop']:code+=function(name) +code+=r''' +static struct httpd_ssl_config config(void){return(struct httpd_ssl_config){.transport_mode=HTTPD_SSL_TRANSPORT_SECURE,.session_tickets=true,.cacert_pem=(void*)"CA",.cacert_len=3,.servercert=(void*)"CERT",.servercert_len=5,.prvtkey_pem=(void*)"SYNTHETIC_PRIVATE_KEY",.prvtkey_len=22,.port_secure=8443};} +int main(void){ + struct httpd_ssl_config cfg=config();httpd_handle_t handle=NULL; + assert(httpd_ssl_start(&handle,&cfg)==ESP_OK&&handle&&live==6);assert(httpd_ssl_stop(handle)==ESP_OK&&live==0); + force_start_failure=true;cfg=config();handle=NULL;assert(httpd_ssl_start(&handle,&cfg)!=ESP_OK&&!handle); + fprintf(stderr,"actual SDK start-failure retained allocations=%d\n",live); + assert(live==0&&"HTTPS start failure must reclaim configuration, tickets, CA, certificate and private key"); + unsigned cases=0; + for(unsigned tickets=0;tickets<2;tickets++)for(unsigned fail=0;fail<2;fail++)for(int allowance=0;allowance<8;allowance++){ + assert(!live);budget=allowance;force_start_failure=fail;cfg=config();cfg.session_tickets=tickets;handle=NULL;int ret=httpd_ssl_start(&handle,&cfg);budget=-1; + if(ret==ESP_OK){assert(handle==(void*)1);assert(httpd_ssl_stop(handle)==ESP_OK);}else assert(!handle); + assert(live==0&&"partial TLS setup must release every successful allocation");cases++; + } + force_start_failure=false;cfg=config();cfg.servercert=NULL;handle=NULL;assert(httpd_ssl_start(&handle,&cfg)==ESP_ERR_INVALID_ARG&&!handle&&!live); + cfg=config();cfg.prvtkey_pem=NULL;assert(httpd_ssl_start(&handle,&cfg)==ESP_ERR_INVALID_ARG&&!handle&&!live); + printf("PASS %u allocation/failure cases: actual SDK HTTPS create/start/stop cleanup, tickets on/off, missing certificate/key, normal success, no source mutation or TLS socket\n",cases); +} +''' +with tempfile.TemporaryDirectory(prefix='ts-https-sdk-fault-') as tmp: + c=Path(tmp)/'test.c';exe=Path(tmp)/'test';c.write_text(code);subprocess.run(['cc','-std=gnu11','-g','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(c),'-o',str(exe)],check=True);subprocess.run([str(exe)],check=True) diff --git a/tests/runtime/test_json_depth.py b/tests/runtime/test_json_depth.py new file mode 100644 index 00000000..24f73a8f --- /dev/null +++ b/tests/runtime/test_json_depth.py @@ -0,0 +1,73 @@ +"""Compile the real SDK JSON target under the actual application CMake policy. +The baseline option compiles unchanged SDK defaults for a negative comparison. +No SDK source edits, devices or network are involved. +""" +from pathlib import Path +import argparse, os, shutil, subprocess, tempfile + +ROOT = Path(__file__).resolve().parents[2] +IDF = Path(os.environ.get('IDF_PATH', '/Users/massif/esp/v5.5.2/esp-idf')) +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--baseline', action='store_true') +args = parser.parse_args() +cmake = shutil.which('cmake') or '/Users/massif/.espressif/tools/cmake/3.30.2/CMake.app/Contents/bin/cmake' +code = r''' +#include "cJSON.h" +#include +#include +#include +#include +static unsigned live, peak, checks; +static void *counted_malloc(size_t size) {void *p=malloc(size);if(p){++live;if(live>peak)peak=live;}return p;} +static void counted_free(void *p) {if(p){assert(live);--live;free(p);}} +static void check(int ok,const char *why) {++checks;if(!ok){fprintf(stderr,"FAIL %s\n",why);abort();}} +static char *nested(unsigned depth,int object) { + char *text=malloc(depth*7+8),*at=text;assert(text); + for(unsigned i=0;i +#include +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 #include "ts_config_partitions.h" #include "ts_storage.h" #include #include #include +#include #define CONFIG_TS_CONFIG_PACK_MAX_SIZE 65536 #define TS_LOGI(...) ((void)0) #define TS_LOGE(...) ((void)0) #define TS_LOGD(...) ((void)0) #define API_PREFIX "/api/v1" +#define TS_HTTP_GET 0 +#define TS_HTTP_POST 1 +#define TS_HTTP_PUT 2 +#define TS_HTTP_DELETE 3 #define TS_API_MALLOC malloc typedef struct {size_t content_len,query_len;} test_http_req_t; typedef struct {const char *uri;const char *body;size_t body_len;int method;test_http_req_t *req;} ts_http_request_t; /* This suite uses an authenticated caller; role boundaries have their own suite. */ -enum { TS_PERM_NONE=0, TS_PERM_READ=1, TS_PERM_ROOT=4 }; +static int validation_calls, revoke_on_validation, downgrade_on_validation; +esp_err_t ts_security_validate_session(uint32_t sid, ts_session_t *session) { + ++validation_calls; + if (!sid || validation_calls == revoke_on_validation) return ESP_ERR_NOT_FOUND; + session->level = sid == 3 ? TS_PERM_ROOT : sid == 2 ? TS_PERM_ADMIN : sid == 1 ? TS_PERM_READ : TS_PERM_NONE; + if (validation_calls == downgrade_on_validation) session->level = TS_PERM_READ; + return ESP_OK; +} +static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;} static esp_err_t check_auth(ts_http_request_t *req,uint32_t *session,int required) {(void)req;(void)required;*session=1;return ESP_OK;} cJSON *ts_api_get_info(const char *name) { (void)name;cJSON *info=cJSON_CreateObject();cJSON_AddBoolToObject(info,"requires_auth",true);return info; } esp_err_t ts_storage_check_write_path(const char *path,bool internal) {(void)path;(void)internal;assert(!"unexpected storage read in keystore test");return ESP_FAIL;} +esp_err_t ts_api_get_access(const char *name,ts_api_access_t *access){(void)name;access->requires_auth=true;access->minimum_level=TS_PERM_READ;access->allowed_methods=TS_API_METHOD_ALL;return ESP_OK;} static size_t httpd_req_get_url_query_len(void *p){return p?((test_http_req_t *)p)->query_len:0;} static esp_err_t httpd_req_get_url_query_str(void *p,char *b,size_t n){return ESP_FAIL;} esp_err_t ts_http_send_json(ts_http_request_t *,int,const char *); @@ -54,6 +79,27 @@ #include "cJSON.h" static size_t allocation_size_fail; static void *key_alloc(size_t n){return n==allocation_size_fail?NULL:malloc(n);} +void *heap_caps_malloc(size_t n,unsigned caps){(void)caps;return key_alloc(n);} +static char diagnostics[16384]; +static pthread_mutex_t diagnostics_lock=PTHREAD_MUTEX_INITIALIZER; +static void capture_log(const char *tag,const char *format,...) { + pthread_mutex_lock(&diagnostics_lock);(void)tag;size_t used=strlen(diagnostics);va_list ap;va_start(ap,format); + vsnprintf(diagnostics+used,sizeof diagnostics-used,format,ap);va_end(ap);pthread_mutex_unlock(&diagnostics_lock); +} +#undef ESP_LOGI +#undef ESP_LOGW +#undef ESP_LOGE +#undef ESP_LOGD +#define ESP_LOGI capture_log +#define ESP_LOGW capture_log +#define ESP_LOGE capture_log +#define ESP_LOGD capture_log +#undef TS_LOGI +#undef TS_LOGE +#undef TS_LOGD +#define TS_LOGI capture_log +#define TS_LOGE capture_log +#define TS_LOGD capture_log #define TS_MALLOC_PSRAM key_alloc #define TS_STRDUP_PSRAM strdup #define ESP_ERR_INVALID_RESPONSE 0x108 @@ -86,8 +132,15 @@ static pthread_cond_t gate_cond=PTHREAD_COND_INITIALIZER; static bool gate_enabled;static int gate_arrived,gate_target; static char sent_json[4096];static int send_status; +static const char *pause_read; +static bool read_arrived, read_release, writer_started; +static atomic_bool writer_done; static entry *find(const char *key) {for(int i=0;i<40;i++)if(db[i].used&&!strcmp(db[i].key,key))return &db[i];return NULL;} -static esp_err_t get(const char *key,void *out,size_t *len){if(fail_get&&!strcmp(fail_get,key))return ESP_FAIL;entry *e=find(key);if(!e)return ESP_ERR_NVS_NOT_FOUND;if(out&&*lenlen)return ESP_ERR_NVS_INVALID_LENGTH;if(out)memcpy(out,e->data,e->len);*len=e->len;return ESP_OK;} +static esp_err_t get(const char *key,void *out,size_t *len){if(fail_get&&!strcmp(fail_get,key))return ESP_FAIL;entry *e=find(key);if(!e)return ESP_ERR_NVS_NOT_FOUND;if(out&&*lenlen)return ESP_ERR_NVS_INVALID_LENGTH;if(out&&pause_read&&!strcmp(key,pause_read)){ + pthread_mutex_lock(&gate_lock);read_arrived=true;pthread_cond_broadcast(&gate_cond); + while(!read_release)pthread_cond_wait(&gate_cond,&gate_lock);pthread_mutex_unlock(&gate_lock); + } + if(out)memcpy(out,e->data,e->len);*len=e->len;return ESP_OK;} static esp_err_t set(const char *key,const void *data,size_t len){ writes++;bool failed=fail_key&&!strcmp(fail_key,key)&&++write_hits==fail_write_at; if(fail_restore&&!strcmp(key,"_index")&&!strcmp(data,"keep"))failed=true; @@ -126,12 +179,12 @@ esp_err_t ts_api_automation_proxy_fetch_for_session(const cJSON *params,uint32_t session_id,ts_api_result_t *result){ (void)params;(void)session_id;(void)result;assert(!"unexpected proxy call in keystore test");return ESP_FAIL; } -void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t c,const char *s){r->code=c;r->message=strdup(s);} +void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t c,const char *s){free(r->message);cJSON_Delete(r->data);r->data=NULL;r->code=c;r->message=strdup(s);} void ts_api_result_ok(ts_api_result_t *r,cJSON *data){r->code=0;r->data=data;} void ts_api_result_free(ts_api_result_t *r){free(r->message);cJSON_Delete(r->data);memset(r,0,sizeof(*r));} esp_err_t ts_http_send_json(ts_http_request_t *r,int status,const char *j){strcpy(sent_json,j);send_status=status;return ESP_OK;} esp_err_t ts_http_send_error(ts_http_request_t *r,int status,const char *j){strcpy(sent_json,j);send_status=status;return ESP_OK;} -static void reset(void){assert(!live_crypto);memset(db,0,sizeof(db));fail_key=fail_get=fail_erase=NULL;fail_write_at=fail_commit_at=commit_calls=writes=write_hits=0;fail_partial=fail_restore=false;crypto_calls=crypto_error=private_error=public_error=0;private_empty=false;gate_enabled=false;gate_arrived=gate_target=0;allocation_size_fail=0;fail_response_alloc=false;} +static void reset(void){diagnostics[0]=0;validation_calls=revoke_on_validation=downgrade_on_validation=0;pause_read=NULL;read_arrived=read_release=writer_started=false;writer_done=false;assert(!live_crypto);memset(db,0,sizeof(db));fail_key=fail_get=fail_erase=NULL;fail_write_at=fail_commit_at=commit_calls=writes=write_hits=0;fail_partial=fail_restore=false;crypto_calls=crypto_error=private_error=public_error=0;private_empty=false;gate_enabled=false;gate_arrived=gate_target=0;allocation_size_fail=0;fail_response_alloc=false;} static esp_err_t store(const char *id){ts_keystore_keypair_t p={"SYNTHETIC",10,"SYNTHETIC",10};return ts_keystore_store_key(id,&p,TS_KEYSTORE_TYPE_RSA_2048,NULL);} static ts_keystore_generate_result_t detail; static esp_err_t generate(const char *id){return ts_keystore_generate_key_with_result(id,TS_KEYSTORE_TYPE_RSA_2048,NULL,&detail);} @@ -142,9 +195,123 @@ static void *always_fail(size_t n){return NULL;} static int json_alloc_count,json_fail_at; static void *fail_one_json_alloc(size_t n){return ++json_alloc_count==json_fail_at?NULL:malloc(n);} + +struct read_work {bool private;ts_keystore_key_info_t info;char *bytes;size_t length;esp_err_t result;}; +static void *read_work(void *arg){struct read_work *w=arg;w->result=w->private? + ts_keystore_read_exportable_private_record("same",&w->info,&w->bytes,&w->length): + ts_keystore_read_public_record("same",true,&w->info,&w->bytes,&w->length);return NULL;} +static void *replace_work(void *arg){(void)arg;pthread_mutex_lock(&gate_lock);writer_started=true;pthread_cond_broadcast(&gate_cond);pthread_mutex_unlock(&gate_lock); + ts_keystore_keypair_t pair={"NEW-PRIVATE",12,"NEW-PUBLIC",11};ts_keystore_gen_opts_t opts={.comment="new",.exportable=false}; + assert(ts_keystore_delete_key("same")==ESP_OK); + assert(STORE_OPTS("same",&pair,TS_KEYSTORE_TYPE_ECDSA_P256,&opts)==ESP_OK);writer_done=true;return NULL;} +static void read_result(esp_err_t ret,ts_api_result_t *r,bool okay) { + assert((ret==ESP_OK)==okay);assert((r->code==TS_API_OK)==okay);if(!okay)assert(!r->data); + ts_api_result_free(r); +} int main(int argc,char **argv){ assert(ts_keystore_init()==ESP_OK);reset(); + + if(!strcmp(argv[1],"visibility")){ + assert(store("visible")==ESP_OK); + ts_keystore_keypair_t pair={"SECRET-PRIVATE",15,"SECRET-PUBLIC",14}; + ts_keystore_gen_opts_t opts={.comment="SECRET-COMMENT",.alias="SECRET-ALIAS",.hidden=true,.exportable=true}; + assert(STORE_OPTS("vault42",&pair,TS_KEYSTORE_TYPE_ECDSA_P384,&opts)==ESP_OK); + cJSON *p=cJSON_Parse("{\"id\":\"vault42\",\"show_hidden\":true,\"role\":\"root\",\"session_id\":3}"); + for(uint32_t sid=0;sid<=4;++sid){ + ts_api_result_t r={0};esp_err_t ret=api_key_list_for_session(p,sid,&r); + if(sid==0||sid==4)read_result(ret,&r,false); + else {assert(ret==ESP_OK&&r.code==0);char *json=cJSON_PrintUnformatted(r.data);assert((strstr(json,"SECRET-")!=NULL)==(sid==2||sid==3));assert(cJSON_GetObjectItem(r.data,"count")->valueint==((sid==2||sid==3)?2:1));free(json);ts_api_result_free(&r);} + read_result(api_key_info_for_session(p,sid,&r),&r,sid==2||sid==3); + read_result(api_key_export_for_session(p,sid,&r),&r,sid==2||sid==3); + read_result(api_key_export_private_for_session(p,sid,&r),&r,sid==2||sid==3); + } + ts_api_result_t r={0};read_result(api_key_list(p,&r),&r,true);read_result(api_key_info(p,&r),&r,true);read_result(api_key_export(p,&r),&r,true); + cJSON_ReplaceItemInObject(p,"id",cJSON_CreateString("visible")); + for(uint32_t sid=1;sid<=3;++sid){read_result(api_key_info_for_session(p,sid,&r),&r,true);read_result(api_key_export_for_session(p,sid,&r),&r,true);read_result(api_key_export_private_for_session(p,sid,&r),&r,false);} + char *raw=NULL;size_t len=0;assert(ts_keystore_load_private_key("visible",&raw,&len)==ESP_OK&&len==9);secure_free_key(raw,len); + assert(ts_keystore_export_private_key_to_file("visible","unused")==ESP_ERR_NOT_ALLOWED); + cJSON_ReplaceItemInObject(p,"id",cJSON_CreateString("vault42")); + for(int which=0;which<4;++which)for(int downgrade=0;downgrade<2;++downgrade){ + validation_calls=0;revoke_on_validation=downgrade?0:2;downgrade_on_validation=downgrade?2:0; + esp_err_t (*handlers[])(const cJSON*,uint32_t,ts_api_result_t*)={api_key_list_for_session,api_key_info_for_session,api_key_export_for_session,api_key_export_private_for_session}; + read_result(handlers[which](p,3,&r),&r,false); + } + revoke_on_validation=downgrade_on_validation=0; + for(int which=0;which<4;++which)for(int n=1;n<=96;++n){ + json_alloc_count=0;json_fail_at=n;cJSON_Hooks hooks={fail_one_json_alloc,free};cJSON_InitHooks(&hooks); + esp_err_t (*handlers[])(const cJSON*,uint32_t,ts_api_result_t*)={api_key_list_for_session,api_key_info_for_session,api_key_export_for_session,api_key_export_private_for_session}; + esp_err_t ret=handlers[which](p,3,&r);cJSON_InitHooks(NULL); + if(ret==ESP_OK){assert(r.data);if(which>=2)assert(cJSON_GetObjectItem(r.data,which==3?"private_key":"public_key")&&cJSON_GetObjectItem(r.data,"comment"));else if(which==1)assert(cJSON_GetObjectItem(r.data,"alias"));else assert(cJSON_GetArraySize(cJSON_GetObjectItem(r.data,"keys"))==2);}else assert(r.code!=TS_API_OK&&!r.data); + ts_api_result_free(&r); + } + assert(!strstr(diagnostics,"vault42")&&!strstr(diagnostics,"SECRET-")&&!strstr(diagnostics,"visible")); + cJSON_Delete(p); + } + if(!strcmp(argv[1],"read_bounds")){ + assert(store("one")==ESP_OK&&store("two")==ESP_OK); + struct {uint32_t before;ts_keystore_key_info_t info[1];uint32_t after;} bounded={.before=0x12345678,.after=0x87654321}; + size_t count=1;assert(ts_keystore_list_keys_ex(bounded.info,&count,false)==ESP_OK&&count==1&&bounded.before==0x12345678&&bounded.after==0x87654321); + count=0;assert(ts_keystore_list_keys(bounded.info,&count)==ESP_OK&&!count); + fail_get="one_meta";count=1;assert(ts_keystore_list_keys_ex(bounded.info,&count,false)!=ESP_OK&&!count);fail_get=NULL; + const char *invalid[]={"[]","{}","{\"type\":1}","{\"type\":\"future\"}","{\"type\":\"rsa2048\",\"hidden\":0}","{\"type\":\"rsa2048\",\"hidden\":true,\"hidden\":false}","{\"type\":\"rsa2048\",\"comment\":null}","{\"type\":\"rsa2048\",\"created_at\":-1}","{\"type\":\"rsa2048\",\"created_at\":4294967296}","{\"type\":\"rsa2048\",\"created_at\":0.5}","{\"type\":\"rsa2048\",\"exportable\":\"true\"}","{\"type\":\"rsa2048\",\"future_secret\":true}","{\"type\":\"rsa2048\"} {}"}; + for(unsigned i=0;ivaluestring,"hide-log")&&!strstr(diagnostics,"hide-log"));ts_api_result_free(&r);cJSON_Delete(params); + reset();fail_response_alloc=true;params=cJSON_Parse("{\"id\":\"hide-log\",\"hidden\":true}");assert(api_key_generate(params,&r)==ESP_ERR_NO_MEM);cJSON_InitHooks(NULL);assert(find("hide-log_priv")&&!strstr(diagnostics,"hide-log"));ts_api_result_free(&r);cJSON_Delete(params); + } + if(!strcmp(argv[1],"file_import")){ + char path[]="/tmp/ts-keystore-input-XXXXXX";int fd=mkstemp(path);assert(fd>=0);FILE *file=fdopen(fd,"wb");assert(file);const char *private_text="-----BEGIN RSA PRIVATE KEY-----\nSYNTHETIC\n-----END RSA PRIVATE KEY-----\n";assert(fwrite(private_text,1,strlen(private_text),file)==strlen(private_text)&&!fclose(file)); + assert(ts_keystore_import_from_file("import",path,"note")==ESP_OK);ts_keystore_key_info_t info;assert(ts_keystore_get_key_info("import",&info)==ESP_OK&&!info.exportable&&!info.has_public_key); + entry snapshot[40];memcpy(snapshot,db,sizeof db);assert(ts_keystore_import_from_file("import",path,NULL)==ESP_ERR_INVALID_STATE&&!memcmp(snapshot,db,sizeof db)); + char public_path[256];snprintf(public_path,sizeof public_path,"%s.pub",path);file=fopen(public_path,"wb");assert(file&&fwrite("ssh-rsa SYNTHETIC",1,17,file)==17&&!fclose(file));assert(ts_keystore_import_from_file("pair",path,NULL)==ESP_OK&&ts_keystore_get_key_info("pair",&info)==ESP_OK&&info.has_public_key); + file=fopen(public_path,"wb");assert(file);for(int i=0;i=0&&(size_t)n #include #include @@ -119,7 +152,8 @@ def whole(path): static ts_led_image_t s_current_image; static ts_font_t *s_current_font; static char s_current_font_name[32]; -static const char *ts_console_get_raw_cmdline(void) {return NULL;} +static const char *private_raw_command; +static const char *ts_console_get_raw_cmdline(void) {return private_raw_command;} static ts_led_layer_t s_current_image_layer; static int ts_console_error(const char *format,...) {(void)format;return 0;} static int ts_console_printf(const char *format,...) {(void)format;return 0;} @@ -127,6 +161,12 @@ def whole(path): void ts_api_result_error(ts_api_result_t *r,ts_api_result_code_t code,const char *message) {r->code=code;r->message=(char*)message;} void ts_api_result_ok(ts_api_result_t *r,cJSON *data) {r->code=TS_API_OK;r->data=data;} ''' +# Replay only the actual diagnostic prelude of cmd_led; full argtable dispatch +# is not exercised here. The normal draw/text/file business path below is real. +cmd = body(CLI,'cmd_led') +start = cmd.index(' const char *cmdline = ts_console_get_raw_cmdline();') +stop = cmd.index(' if (nerrors != 0 && cmdline)',start) +code += '\nstatic void private_command_diagnostic(int nerrors){\n'+cmd[start:stop]+'\n}\n' for name in ['resolve_device_name','do_led_on','do_led_off','do_led_effect','do_led_image','do_led_qrcode','parse_text_align','extract_param_from_cmdline','extract_text_from_cmdline','parse_escape_sequences','build_font_path','do_led_draw_text','do_led_clear']: code += body(CLI,name) for name in ['parse_color_param','api_led_set','api_led_fill','api_led_clear','api_led_effect_start','api_led_qrcode','api_led_save']: @@ -360,6 +400,17 @@ def whole(path): api(api_led_effect_start,"{\"device\":\"touch\",\"effect\":\"solid\",\"color\":\"red\"}");api(api_led_effect_start,"{\"device\":\"board\",\"effect\":\"solid\",\"color\":\"blue\"}");api(api_led_effect_start,"{\"device\":\"matrix\",\"effect\":\"solid\",\"color\":\"green\"}");assert(((ts_led_layer_impl_t*)layers[0])->anim_color.r==255&&((ts_led_layer_impl_t*)layers[1])->anim_color.b==255&&((ts_led_layer_impl_t*)layers[2])->anim_color.g==255); int custom=7;def.func=custom_animation;def.user_data=&custom;assert(ts_led_animation_start(layers[0],&def)==ESP_OK&&((ts_led_layer_impl_t*)layers[0])->anim_data==&custom);assert(ts_led_animation_stop(layers[0])==ESP_OK&&custom==7); assert(do_led_off("touch")==0&&do_led_on("touch","red")==0);start_render();frames(s_touch,3,false);assert(((fake_strip*)((ts_led_device_impl_t*)s_touch)->strip_handle)->pixels[0].r>0); + /* Real raw-command extraction and rendering copy; diagnostics are observed + * separately from the private console response. Renderer tasks are stopped. */ + stop_render();private_log_capture=true;private_raw_command="led --draw-text --device matrix --font normal --text \"private-LED-凭据\""; + private_command_diagnostic(2);private_absent("private-LED-凭据"); + assert(do_led_draw_text("matrix",NULL,NULL,"green","left",NULL,NULL,0,0,false,false,30)==0); + private_check(!strcmp(s_overlays[0].text,"private-LED-凭据"),"UTF-8 exact renderer input preserved");private_absent("private-LED-凭据"); + private_raw_command=NULL;private_log_used=0;private_log[0]=0; + assert(do_led_draw_text("matrix","plain-private-text","normal","green","left",NULL,NULL,0,0,false,false,30)==0);private_check(!strcmp(s_overlays[0].text,"plain-private-text"),"direct text renderer input preserved");private_absent("plain-private-text"); + FILE *private_file=fopen("private-text-secret.txt","wb");assert(private_file);fputs("file-private-凭据\r\n",private_file);fclose(private_file);private_log_used=0;private_log[0]=0; + assert(do_led_draw_text("matrix",NULL,"normal","green","left","private-text-secret.txt",NULL,0,0,false,false,30)==0);private_check(!strcmp(s_overlays[0].text,"file-private-凭据"),"file contents and newline trim preserved");private_absent("file-private-凭据");private_absent("private-text-secret.txt");assert(unlink("private-text-secret.txt")==0); + private_check(private_log_used>0,"safe diagnostic metadata retained");private_log_capture=false;private_log_used=0;private_log[0]=0;start_render(); assert(do_led_draw_text("matrix","A","normal","green","left",NULL,"left",1,2,true,false,50)==0);ts_led_layer_t overlay=s_overlays[0].overlay_layer;assert(ts_led_text_overlay_is_active("matrix")); ts_led_effect_config_t invert={.type=TS_LED_EFFECT_INVERT};assert(ts_led_layer_set_effect(layers[2],&invert)==ESP_OK); api(api_led_clear,"{\"device\":\"matrix\"}");assert(((ts_led_layer_impl_t*)overlay)->visible);frames(s_matrix,3,false);assert(((fake_strip*)((ts_led_device_impl_t*)s_matrix)->strip_handle)->lit_frames>0); @@ -389,7 +440,7 @@ def whole(path): teardown();fresh();assert(ts_led_load_boot_config("matrix")==ESP_OK);frames(s_matrix,4,true);assert(ts_led_get_current_state("matrix",&state)==ESP_OK&&!state.enabled&&!strcmp(state.qrcode_text,"B07")&&!state.image_path[0]&&!state.animation[0]&&state.brightness==149&&state.filter_speed==29); assert(do_led_effect("matrix","solid",50,"red")==0);assert(ts_led_save_boot_config("matrix")==ESP_OK&&nvs_find("led.mat.clr")>=0);assert(do_led_effect("matrix","solid",50,NULL)==0);assert(ts_led_save_boot_config("matrix")==ESP_OK&&nvs_find("led.mat.clr")<0); teardown();fresh();assert(ts_led_load_boot_config("matrix")==ESP_OK);assert(!((ts_led_layer_impl_t*)ts_led_layer_get(s_matrix,0))->anim_data); - check_fades();start_render();check_b09_render();teardown();check_qr_color_restore();free(s_delayed_image_timer);s_delayed_image_timer=NULL;vSemaphoreDelete(action_context.stats_mutex);free(s_anim_state);puts("PASS actual LED controls, independent RGB ownership, composition/CC/driver HAL output gate, QR layer handoff and NVS save/reset/rebuild/load"); + check_fades();start_render();check_b09_render();teardown();check_qr_color_restore();free(s_delayed_image_timer);s_delayed_image_timer=NULL;vSemaphoreDelete(action_context.stats_mutex);free(s_anim_state);assert(private_failures==0);puts("PASS LED diagnostic privacy: raw UTF-8 command/direct/file render bytes preserved, raw and hex omitted");puts("PASS actual LED controls, independent RGB ownership, composition/CC/driver HAL output gate, QR layer handoff and NVS save/reset/rebuild/load"); } ''' headers = {path.name: path.read_text() for path in Path('components/ts_led/include').glob('*.h')} diff --git a/tests/runtime/test_led_file_reads.py b/tests/runtime/test_led_file_reads.py new file mode 100644 index 00000000..659aa842 --- /dev/null +++ b/tests/runtime/test_led_file_reads.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Three real LED session callbacks and registration + shared storage/FAT classification. +LED/image/config business operations are counters; real business positive tests remain +in the existing LED runtime suite. No actual device or private files. +""" +from pathlib import Path +import re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2] +f=ROOT/'tests/runtime/test_external_storage_reads.py' +t=f.read_text();ns={'__file__':str(f),'__name__':'led_file_fixture'} +exec(compile(t[:t.index('\nwith tempfile.TemporaryDirectory')],str(f),'exec'),ns) +code=ns['code'].replace('int main(void)','static int storage_cases(void)') +source,function,IDF=ns['source'],ns['function'],ns['IDF'] +led=source('components/ts_api/src/ts_api_led.c') +start=led.index('static const ts_api_endpoint_t led_endpoints[]');table=led[start:led.index('\n};',start)+3] +code+='\n#define TS_LED_CC_SDCARD_JSON_PATH "/sdcard/config/led_color_correction.json"\n' +for name in set(re.findall(r'\.handler\s*=\s*(\w+)',table)):code+='#define '+name+' readonly\n' +if 'static esp_err_t led_read_for_session(' in led: + for name in ['led_read_for_session','led_image_for_session','led_qrcode_for_session','led_cc_import_for_session']:code+=function(led,name) +code+=table+'\n'+function(led,'ts_api_led_register') +count=len(re.findall(r'\.name\s*=',table)) +code+=r""" +static void consumer(const char *name,const char *path,unsigned sid,bool private_path,bool invalid){ + cJSON *p=cJSON_CreateObject();if(path)cJSON_AddStringToObject(p,!strcmp(name,"led.qrcode")?"bg_image":"path",path); + cJSON_AddStringToObject(p,"role","root");cJSON_AddNumberToObject(p,"session_id",4);cJSON_AddBoolToObject(p,"internal",true); + unsigned before=reads,stat_before=lookups;ts_api_result_t result={0};active_sid=sid; + esp_err_t ret=ts_api_call_for_session(name,p,sid,&result); + bool valid=sid==3||sid==4,allowed=valid&&!invalid&&(!private_path||sid>=3); + check((ret==ESP_OK&&result.code==TS_API_OK)==allowed,"verified identity/private path controls LED consumer"); + check(reads==before+allowed,"refused consumer cannot stop animation, open file, change calibration or hardware"); + if(!valid)check(lookups==stat_before,"non-Admin denied before FAT metadata"); + if(valid&&private_path&&sid<3&&!invalid)check(result.code==TS_API_ERR_NO_PERMISSION&&!strcmp(result.message,"Administrator permission required"),"private consumer returns standard Root upgrade reason"); + ts_api_result_free(&result);cJSON_Delete(p); +} +int main(void){ + if(storage_cases()!=0)return 1; + check(ts_api_init()==ESP_OK&&ts_api_led_register()==ESP_OK,"actual LED registrations initialize"); +"""+f' cJSON *list=ts_api_list(TS_API_CAT_LED);check(cJSON_GetArraySize(list)=={count},"complete LED table retained");cJSON_Delete(list);\n'+r""" + const char *names[]={"led.image","led.qrcode","led.color_correction.import"}; + const char *private_paths[]={"/sdcard/config/wifi.json","/sdcard/CONFIG/key.bin","/sdcard/confıg/file","/sdcard/CONFID~1/file","/sdcard/config. /file","/sdcard/foo/../config/file","/sdcard/pki/ca-chain.crt","/sdcard/PKIPRI~1/key","/spiffs/private","/www/image.bmp","/autocfg/state.json"}; + const char *ordinary[]={"/sdcard/images/a.bmp","/sdcard/自定义/a.gif","/sdcard/config/../images/a.bmp","/sdcard/missing/a.json"}; + const char *invalid[]={"/unknown/a","/sdcard-other/a","relative/a","/sdcard/config\t/a","/"}; + unsigned identities[]={0,1,2,3,4,5,99}; + for(unsigned i=0;i<7;i++)for(unsigned n=0;n<3;n++){ + unsigned sid=identities[i];ts_api_access_t access;check(ts_api_get_access(names[n],&access)==ESP_OK&&access.minimum_level==TS_PERM_ADMIN&&access.allowed_methods==TS_API_METHOD_WRITE,"all three retain Admin/write metadata with dynamic private upgrade"); + for(unsigned p=0;p +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cJSON.h" +typedef int esp_err_t; +enum {ESP_OK=0,ESP_FAIL=-1,ESP_ERR_INVALID_ARG=0x102,ESP_ERR_INVALID_STATE=0x103,ESP_ERR_NO_MEM=0x101,TS_API_ERR_INVALID_ARG=1,TS_API_ERR_NO_MEM=6,TS_API_ERR_BUSY=10}; +typedef struct {int code;char *message;cJSON *data;} ts_api_result_t; +static void ts_api_result_error(ts_api_result_t *r,int code,const char *msg){r->code=code;r->message=strdup(msg);} +static void ts_api_result_ok(ts_api_result_t *r,cJSON *data){r->code=0;r->data=data;} +#define TS_LOGI(...) ((void)0) +#define TS_LOGE(...) ((void)0) +static unsigned checks,failures,sockets,closes,sends,waits;static int scenario; +static int64_t now_us; +static void *json_fail(size_t size){(void)size;return NULL;} +static void check(bool v,const char *m){checks++;if(!v){failures++;fprintf(stderr,"FAIL %s scenario=%d\n",m,scenario);}} +static int64_t esp_timer_get_time(void){return now_us;} +static uint16_t inet_chksum(const void *p,size_t n){(void)p;(void)n;return 0;} +static uint8_t packet[128];static size_t packet_size;static struct sockaddr_in target; +static int fake_socket(int f,int t,int p){assert(f==AF_INET&&t==SOCK_RAW&&p==IPPROTO_ICMP);sockets++;return scenario==1?-1:5;} +static int fake_close(int fd){assert(fd==5);closes++;return 0;} +static int fake_fcntl(int fd,int cmd,...){assert(fd==5);(void)cmd;return scenario==2?-1:0;} +static int fake_setsockopt(int fd,int l,int o,const void *v,socklen_t n){(void)fd;(void)l;(void)o;(void)v;(void)n;return 0;} +static ssize_t fake_sendto(int fd,const void *p,size_t n,int flags,const struct sockaddr *to,socklen_t len){ + assert(fd==5);(void)flags;(void)len;sends++;memcpy(packet,p,n);packet_size=n;memcpy(&target,to,sizeof(target)); + if(scenario==3){errno=EIO;return -1;}if(scenario==5&&sends==1){errno=EAGAIN;return -1;}return (ssize_t)n; +} +static int fake_select(int n,fd_set *r,fd_set *w,fd_set *e,struct timeval *t){ + (void)n;(void)r;(void)w;(void)e;assert(t);waits++; + if(scenario==4){now_us+=(int64_t)t->tv_sec*1000000+t->tv_usec;return 0;} + if(scenario==6&&waits==1){errno=EINTR;return -1;}now_us+=1000;return 1; +} +static ssize_t fake_recvfrom(int fd,void *p,size_t n,int flags,struct sockaddr *from,socklen_t *len){ + assert(fd==5&&n>=packet_size+20);(void)flags;memset(p,0,20);((uint8_t*)p)[0]=0x45;memcpy((uint8_t*)p+20,packet,packet_size);((uint8_t*)p)[20]=0; + memcpy(from,&target,sizeof(target));if(scenario==7)((struct sockaddr_in*)from)->sin_addr.s_addr^=1;*len=sizeof(target);return (ssize_t)packet_size+20; +} +#define socket fake_socket +#define close fake_close +#define fcntl fake_fcntl +#define setsockopt fake_setsockopt +#define select fake_select +#define sendto fake_sendto +#define recvfrom fake_recvfrom +''' +code=code.replace('#include ','#include \n#include ') +for name in ['ping_wait','device_ping_impl','api_device_ping']: + if re.search(r'\b'+name+r'\([^;]+?\)\s*\{',source):code+=function(source,name) +# The production gate is a single nonblocking owner, not a second test policy. +if 's_ping_busy' in source:code=code.replace('static int64_t now_us;','static atomic_flag s_ping_busy=ATOMIC_FLAG_INIT;\nstatic int64_t now_us;') +code+=r''' +static void release(ts_api_result_t *r){cJSON_Delete(r->data);free(r->message);} +static ts_api_result_t invoke(const char *json){cJSON *p=cJSON_Parse(json);assert(p);ts_api_result_t r={0};api_device_ping(p,&r);cJSON_Delete(p);return r;} +int main(void){ + const char *invalid[]={"{\"timeout\":-1}","{\"timeout\":0}","{\"timeout\":0.5}","{\"timeout\":2147483648}","{\"timeout\":30001}","{\"timeout\":\"1000\"}","{\"host\":\"invalid\"}","{\"host\":123}"}; + for(unsigned i=0;i +#define TS_API_ERR_INVALID_ARG 1 +#define TS_API_ERR_NO_MEM 6 +#define TS_API_ERR_BUSY 10 +typedef struct {int code;char *message;cJSON *data;} ts_api_result_t; +static void ts_api_result_error(ts_api_result_t *r,int error,const char *message){r->code=error;r->message=strdup(message);} +static void ts_api_result_ok(ts_api_result_t *r,cJSON *data){r->code=0;r->data=data;} +static void *probe_json_fail(size_t size){(void)size;return NULL;} +static const char *esp_err_to_name(int error){(void)error;return "synthetic_transport_error";} +static atomic_flag s_ota_probe_busy=ATOMIC_FLAG_INIT; +''' +ota_source=(root/'components/ts_api/src/ts_api_ota.c').read_text() +for name in ['ota_test_connection_impl','api_ota_test_connection']:http_code+=function(ota_source,name) +http_code+=r''' +static void dispose(ts_api_result_t *r){cJSON_Delete(r->data);free(r->message);} +static ts_api_result_t probe(const char *url){cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"url",url);ts_api_result_t r={0};api_ota_test_connection(p,&r);cJSON_Delete(p);return r;} +int main(void){ + const char *bad[]={"ftp://fixture.invalid/file","https://fixture.invalid:0/","http://fixture.invalid/\r\nInjected:yes","relative/path"}; + for(unsigned i=0;ishared HTTP/DNS/URL owner;synthetic transport/time,no network\n",checks);return 0; +} +''' +ns['run_native'](http_code,[ns['IDF']/'components/http_parser/http_parser.c',ns['IDF']/'components/json/cJSON/cJSON.c',root/'components/ts_http_fetch/src/ts_http_url.c'],ns['headers']) + +# Same API result fixture; execute both existing scan APIs through their real +# WiFi owner. Only the radio SDK and its completion/timeout are substituted. +wifi_code=code.split('static bool ping_wait(')[0] +wifi_code+=r''' +#define TS_API_ERR_INTERNAL 7 +#define TS_API_ERR_HARDWARE 5 +#define TS_WIFI_MODE_OFF 0 +#define TS_WIFI_MODE_STA 1 +#define TS_WIFI_MODE_AP 2 +#define TS_WIFI_MODE_APSTA 3 +#define TS_LOGW(...) ((void)0) +static bool s_initialized=true;static int s_mode=TS_WIFI_MODE_STA; +static int scan_error,result_error;static bool scan_oom;static unsigned scans,record_calls,record_allocs,record_frees; +typedef struct {int unused;} wifi_scan_config_t; +typedef struct {char ssid[32];uint8_t bssid[6];int8_t rssi;uint8_t channel;int auth_mode;} ts_wifi_scan_result_t; +typedef struct {char ssid[33];uint8_t bssid[6];int8_t rssi;uint8_t primary;int authmode;} wifi_ap_record_t; +static int esp_wifi_scan_start(const wifi_scan_config_t *c,bool blocking){assert(c&&blocking);check(c->unused==0,"scan keeps bounded SDK default configuration");scans++;return scan_error;} +static int esp_wifi_scan_get_ap_records(uint16_t *count,wifi_ap_record_t *records){record_calls++;assert(*count==20);if(result_error)return result_error;memset(records,0,sizeof(*records));strcpy(records[0].ssid,"Synthetic WiFi");records[0].rssi=-30;records[0].primary=6;*count=1;return ESP_OK;} +static void *scan_alloc(size_t size){if(scan_oom)return NULL;record_allocs++;return malloc(size);} +static void scan_free(void *p){if(p)record_frees++;free(p);} +#define TS_MALLOC_PSRAM scan_alloc +#define free scan_free +''' +wifi_source=(root/'components/ts_net/src/ts_wifi.c').read_text() +for name in ['ts_wifi_scan_start','ts_wifi_scan_get_results']:wifi_code+=function(wifi_source,name) +wifi_code+=r''' +#undef free +static const char *auth_mode_str(int type){(void)type;return "WPA2";} +static const char *auth_mode_to_str(int type){return auth_mode_str(type);} +static void add_mac_to_json(cJSON *j,const char *key,const uint8_t *b){(void)b;cJSON_AddStringToObject(j,key,"00:00:00:00:00:00");} +''' +for path,name in [('ts_api_wifi.c','api_wifi_scan'),('ts_api_network.c','api_network_wifi_scan')]:wifi_code+=function((root/'components/ts_api/src'/path).read_text(),name) +wifi_code+=r''' +int main(void){ + for(unsigned api=0;api<2;api++)for(unsigned fault=0;fault<6;fault++){ + s_initialized=fault!=1;s_mode=fault==2?TS_WIFI_MODE_AP:TS_WIFI_MODE_STA;scan_error=fault==3?0x300c:0;result_error=fault==4?ESP_FAIL:0;scan_oom=fault==5;scans=record_calls=record_allocs=record_frees=0; + ts_api_result_t r={0};esp_err_t ret=api?api_network_wifi_scan(NULL,&r):api_wifi_scan(NULL,&r); + if(!fault){check(ret==ESP_OK&&!r.code&&cJSON_GetArraySize(cJSON_GetObjectItem(r.data,"networks"))==1,"both real scan APIs preserve authorized network list");check(!strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(r.data,"networks"),0),"ssid")),"Synthetic WiFi"),"SSID/channel result shape preserved");} + else check(ret!=ESP_OK&&r.code&&!r.data,"mode/SDK blocking timeout/results/OOM faults cannot claim success"); + check(record_allocs==record_frees,"scan result buffer always released");if(fault==1||fault==2)check(!scans&&!record_calls,"invalid owner state cannot start radio scan");if(fault==3||fault==5)check(!record_calls,"scan timeout/OOM cannot consume result buffer");cJSON_Delete(r.data);free(r.message); + } + printf("%u checks: actual two WiFi scan APIs and owner;synthetic bounded radio SDK,no device\n",checks);return failures?1:0; +} +''' +with tempfile.TemporaryDirectory(prefix='ts-wifi-diagnostics-') as td: + d=Path(td);(d/'test.c').write_text(wifi_code);cjson=ns['IDF']/'components/json/cJSON' + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(cjson),str(d/'test.c'),str(cjson/'cJSON.c'),'-lm','-o',str(d/'test')],check=True) + subprocess.run([str(d/'test')],check=True,timeout=15) diff --git a/tests/runtime/test_ota_lifecycle.py b/tests/runtime/test_ota_lifecycle.py index b66578a7..c18e49ec 100644 --- a/tests/runtime/test_ota_lifecycle.py +++ b/tests/runtime/test_ota_lifecycle.py @@ -18,15 +18,16 @@ def function(path,name): rtos=RTOS.replace('#define TS_EVENT_BASE_SERVICE 1',r''' #define TS_EVENT_BASE_SERVICE 1 #define TS_EVENT_BASE_OTA 9 -static atomic_int ota_events[9];static void (*ota_event_hook)(int); +static atomic_int ota_events[0x060a];static void (*ota_event_hook)(int); ''').replace('if(event==TS_EVENT_SERVICE_STOPPED)++stopped_events;', -'''if(base==TS_EVENT_BASE_OTA){assert(event>=0&&event<9);++ota_events[event];if(ota_event_hook)ota_event_hook(event);}else if(event==TS_EVENT_SERVICE_STOPPED)++stopped_events;''') +'''if(base==TS_EVENT_BASE_OTA){assert(event>=0&&event<0x060a);++ota_events[event];if(ota_event_hook)ota_event_hook(event);}else if(event==TS_EVENT_SERVICE_STOPPED)++stopped_events;''') code=rtos+r''' #include #include #include "esp_app_format.h" #include "esp_app_desc.h" #include "ts_ota.h" +#include "esp_partition.h" #include "ts_api.h" #define TAG "local-ota" #define OTA_MALLOC heap_alloc @@ -90,12 +91,12 @@ def function(path,name): } static void reset_fixture(void) { assert(!s_ota_running&&!s_ota_task_handle&&!s_ota_url);s_state=TS_OTA_STATE_IDLE;s_error=TS_OTA_ERR_NONE;s_total_size=s_received_size=0;strcpy(s_status_msg,"idle");s_upload_handle=0;s_upload_in_progress=false;https_running=false;https_aborts=flash_aborts=restarts=boot_choices=begin_calls=end_calls=0;written_size=0;pause_stage=PAUSE_NONE;pause_once=false;finish_before_create_returns=false; - for(int i=0;i<9;i++)ota_events[i]=0; + for(int i=0;i<0x060a;i++)ota_events[i]=0; } static void refused_without_mutation(void) { - ts_ota_progress_t before,after;assert(ts_ota_get_progress(&before)==ESP_OK);char message[64];strcpy(message,before.status_msg);int events[9];for(int i=0;i<9;i++)events[i]=ota_events[i]; + ts_ota_progress_t before,after;assert(ts_ota_get_progress(&before)==ESP_OK);char message[64];strcpy(message,before.status_msg);int events[0x060a];for(int i=0;i<0x060a;i++)events[i]=ota_events[i]; ts_api_result_t r={0};assert(api_ota_abort(NULL,&r)==ESP_ERR_NOT_SUPPORTED&&r.code!=TS_API_OK&&!cJSON_HasObjectItem(r.data,"aborted"));ts_api_result_free(&r);assert(ts_ota_get_progress(&after)==ESP_OK); - assert(after.state==before.state&&after.error==before.error&&after.total_size==before.total_size&&after.received_size==before.received_size&&!strcmp(after.status_msg,message));for(int i=0;i<9;i++)assert(ota_events[i]==events[i]);assert(!flash_aborts&&!https_aborts); + assert(after.state==before.state&&after.error==before.error&&after.total_size==before.total_size&&after.received_size==before.received_size&&!strcmp(after.status_msg,message));for(int i=0;i<0x060a;i++)assert(ota_events[i]==events[i]);assert(!flash_aborts&&!https_aborts); } static void start_from_api(void) {cJSON *params=cJSON_Parse("{\"file\":\"normal.bin\",\"no_reboot\":true}");ts_api_result_t r={0};assert(api_ota_start_file(params,&r)==ESP_OK&&r.code==TS_API_OK&&cJSON_IsTrue(cJSON_GetObjectItem(r.data,"started")));cJSON_Delete(params);ts_api_result_free(&r);} static void complete_worker(void) {join_tasks();assert(!s_ota_running&&!s_ota_task_handle&&!s_ota_url&&s_ota_config.url==NULL);assert(s_state==TS_OTA_STATE_PENDING_REBOOT&&s_error==TS_OTA_ERR_NONE);assert(begin_calls==1&&end_calls==1&&boot_choices==1&&!flash_aborts&&written_size==sizeof(firmware)&&!memcmp(written_bytes,firmware,sizeof(firmware)));assert(!ota_events[TS_EVENT_OTA_ABORTED]);} @@ -117,7 +118,7 @@ def function(path,name): puts("PASS actual SD task/API abort: queued/read/write/verify/boot/completed refuse unchanged; local bytes/boot result, no_reboot, create failure/fast exit, original idle/error/HTTPS/upload paths"); } ''' -headers={'ts_ota.h':Path('components/ts_ota/include/ts_ota.h').read_text(), +headers={'ts_ota_events.h':Path('components/ts_core/ts_event/include/ts_ota_events.h').read_text(),'ts_ota.h':Path('components/ts_ota/include/ts_ota.h').read_text(), 'esp_partition.h':'#pragma once\n#include \ntypedef struct {char label[17];uint32_t address,size;} esp_partition_t;\n', 'esp_app_format.h':(IDF/'components/bootloader_support/include/esp_app_format.h').read_text(), 'esp_app_desc.h':(IDF/'components/esp_app_format/include/esp_app_desc.h').read_text(), diff --git a/tests/runtime/test_ota_upload_handlers.py b/tests/runtime/test_ota_upload_handlers.py new file mode 100644 index 00000000..ceace562 --- /dev/null +++ b/tests/runtime/test_ota_upload_handlers.py @@ -0,0 +1,84 @@ +"""Actual original-format APP/WWW HTTP handlers; real cJSON, synthetic SD/SDK flash. +Checks API admission, complete bodies, SDK/cache faults and preservation of the old recovery set. +Never opens a device or a real /sdcard path. +""" +from pathlib import Path +from test_console_lifecycle import RTOS, IDF, body, run_native +root=Path(__file__).resolve().parents[2] +code=RTOS+r""" +#include "cJSON.h" +#include "ts_ota.h" +#include "esp_partition.h" +#include "ts_security.h" +#include "esp_app_format.h" +#include "esp_app_desc.h" +#include +#include +#define OTA_UPLOAD_REBOOT_DELAY_MS 2000 +#define ESP_ERR_OTA_VALIDATE_FAILED 0x1503 +#define ESP_ERR_NOT_ALLOWED 0x10d +#define ESP_PARTITION_TYPE_DATA 1 +#define ESP_PARTITION_SUBTYPE_DATA_SPIFFS 0x82 +#define TS_OTA_RECOVERY_FIRMWARE_PATH "/sdcard/recovery/TianShanOS.bin" +#define TS_OTA_RECOVERY_WWW_PATH "/sdcard/recovery/www.bin" +static bool busy,no_reboot,send_failure,deny_auth,cache_failure,manifest_failure; +static unsigned writes,installs,renames,replacements,manifests,reboots,unlinks,status,allocations,fail_allocation,checks; +static esp_err_t write_result,install_result; +static unsigned cache[2]; +static bool pending_exists; +static char response[512]; +static const esp_partition_t target={.size=4096}; +typedef struct {int content_len;} raw_request_t; +typedef struct {raw_request_t *req;void *body;size_t body_len;} ts_http_request_t; +static void *json_malloc(size_t n){return ++allocations==fail_allocation?NULL:malloc(n);} +static esp_err_t check_auth(ts_http_request_t *r,uint32_t *sid,ts_perm_level_t level){(void)r;assert(level==TS_PERM_ADMIN);*sid=11;return deny_auth?ESP_ERR_NOT_ALLOWED:ESP_OK;} +static const esp_partition_t *esp_ota_get_next_update_partition(const esp_partition_t *p){assert(!p);return ⌖} +static const esp_partition_t *esp_partition_find_first(int type,int subtype,const char *label){assert(type==1&&subtype==0x82&&!strcmp(label,"www"));return ⌖} +static bool is_browser_ota_busy(void){return busy;} +static esp_err_t ts_http_get_query_param(ts_http_request_t *r,const char *key,char *out,size_t n){(void)r;assert(!strcmp(key,"auto_reboot"));snprintf(out,n,"%s",no_reboot?"false":"true");return ESP_OK;} +static esp_err_t ts_http_send_error(ts_http_request_t *r,int code,const char *why){(void)r;status=code;snprintf(response,sizeof(response),"%s",why);return ESP_OK;} +static esp_err_t ts_http_send_json(ts_http_request_t *r,int code,const char *json){(void)r;status=code;snprintf(response,sizeof(response),"%s",json);return send_failure?ESP_FAIL:ESP_OK;} +static void schedule_reboot_after_response(uint32_t delay){assert(delay==2000);reboots++;} +static esp_err_t ts_storage_mkdir_p(const char *path){assert(!strcmp(path,"/sdcard/recovery"));return ESP_OK;} +static esp_err_t ts_storage_write_file(const char *path,const void *bytes,size_t n){assert(strstr(path,"-upload.bin")&&bytes&&n);writes++;pending_exists=true;return write_result;} +esp_err_t ts_ota_flash_file_sync(const char *path,bool downgrade,ts_ota_progress_cb_t cb,void *ctx){assert(strstr(path,".firmware-upload.bin")&&downgrade&&!cb&&!ctx);installs++;return install_result;} +esp_err_t ts_ota_www_flash_file_sync(const char *path,ts_ota_progress_cb_t cb,void *ctx){assert(strstr(path,".www-upload.bin")&&!cb&&!ctx);installs++;return install_result;} +static bool ts_storage_exists(const char *path){assert(!strcmp(path,TS_OTA_RECOVERY_FIRMWARE_PATH));return true;} +esp_err_t ts_ota_write_recovery_manifest_from_files(bool www,bool force,bool armed){(void)www;assert(!force&&!armed);manifests++;return manifest_failure?ESP_FAIL:ESP_OK;} +/* FAT rename cannot overwrite either existing recovery image. */ +static int fake_rename(const char *from,const char *to){assert(strstr(from,"-upload.bin"));unsigned kind=!strcmp(to,TS_OTA_RECOVERY_WWW_PATH);assert(kind||!strcmp(to,TS_OTA_RECOVERY_FIRMWARE_PATH));renames++;if(cache[kind]){errno=EEXIST;return -1;}cache[kind]=2;pending_exists=false;return 0;} +static esp_err_t ts_storage_replace_file(const char *path,const void *bytes,size_t n){unsigned kind=!strcmp(path,TS_OTA_RECOVERY_WWW_PATH);assert(kind||!strcmp(path,TS_OTA_RECOVERY_FIRMWARE_PATH));assert(bytes&&n&&pending_exists&&installs==1);replacements++;if(cache_failure)return ESP_FAIL;cache[kind]=2;return ESP_OK;} +static int fake_unlink(const char *path){assert(strstr(path,"-upload.bin"));unlinks++;pending_exists=false;return 0;} +#define rename fake_rename +#define unlink fake_unlink +""" +source=root/'components/ts_webui/src/ts_webui_api.c' +for name in ['is_binary_upload_complete','ota_upload_reply','ota_firmware_upload_handler','ota_www_upload_handler']:code+=body(source,name) +code+=r""" +static void check(bool ok,const char *why){checks++;if(!ok){fprintf(stderr,"FAIL %s HTTP %u\n",why,status);abort();}} +static void reset(void){busy=no_reboot=send_failure=deny_auth=cache_failure=manifest_failure=false;writes=installs=renames=replacements=manifests=reboots=unlinks=status=allocations=fail_allocation=0;write_result=install_result=ESP_OK;response[0]=0;cache[0]=cache[1]=1;pending_exists=false;} +int main(void){ + cJSON_Hooks hooks={json_malloc,free};cJSON_InitHooks(&hooks); + uint8_t bytes[1024]={ESP_IMAGE_HEADER_MAGIC};esp_app_desc_t app={.magic_word=ESP_APP_DESC_MAGIC_WORD};memcpy(bytes+sizeof(esp_image_header_t)+sizeof(esp_image_segment_header_t),&app,sizeof(app)); + raw_request_t raw={sizeof(bytes)};ts_http_request_t req={&raw,bytes,sizeof(bytes)}; + esp_err_t (*handlers[])(ts_http_request_t*,void*)={ota_firmware_upload_handler,ota_www_upload_handler}; + for(unsigned kind=0;kind<2;kind++){ + reset();handlers[kind](&req,NULL);check(status==200&&writes==1&&installs==1&&!renames&&replacements==1&&cache[kind]==2&&cache[!kind]==1&&manifests==1&&reboots==(kind==0)&&unlinks==1&&!pending_exists,"existing APP/WWW cache replaced through owner under FAT rename semantics");unsigned allocated=allocations; + for(unsigned fail=1;fail<=allocated;fail++){reset();fail_allocation=fail;handlers[kind](&req,NULL);check(status==500&&!writes&&!installs&&!renames&&!replacements&&!manifests&&!reboots,"all acknowledgement allocation faults precede persistent effects");} + reset();deny_auth=true;handlers[kind](&req,NULL);check(status==403&&!writes&&!installs&&!allocations,"real admin identity required before effects"); + reset();raw.content_len++;handlers[kind](&req,NULL);check(status==400&&!writes&&!installs&&!allocations,"truncated upload rejected before persistence");raw.content_len--; + reset();req.body_len=5000;raw.content_len=5000;handlers[kind](&req,NULL);check(status==400&&!writes&&!installs,"capacity guard precedes header access/write");req.body_len=raw.content_len=sizeof(bytes); + reset();busy=true;handlers[kind](&req,NULL);check(status==409&&!writes&&!installs,"active original worker still blocks browser upload"); + reset();write_result=ESP_FAIL;handlers[kind](&req,NULL);check(status==500&&writes==1&&!installs&&!renames&&!replacements&&!manifests&&!reboots,"staging failure preserves old recovery materials"); + const esp_err_t faults[]={ESP_ERR_OTA_VALIDATE_FAILED,ESP_ERR_INVALID_SIZE,ESP_ERR_INVALID_STATE,ESP_FAIL}; + for(unsigned i=0;i<4;i++){reset();install_result=faults[i];handlers[kind](&req,NULL);check(status==(i<2?400:i==2?409:500)&&installs==1&&!renames&&!replacements&&!manifests&&!reboots&&unlinks==1&&cache[kind]==1&&cache[!kind]==1&&!pending_exists,"SDK validation/write failure cannot replace old files or manifest");} + for(unsigned i=0;i<2;i++){reset();cache_failure=!i;manifest_failure=i;handlers[kind](&req,NULL);check(status==409&&installs==1&&!renames&&replacements==1&&cache[kind]==(i?2:1)&&cache[!kind]==1&&manifests==i&&!reboots&&unlinks==1&&!pending_exists&&strstr(response,"flash_written")&&strstr(response,"partial"),"post-flash cache failure is explicit partial result, no automatic restart");} + reset();no_reboot=true;handlers[kind](&req,NULL);check(status==200&&installs==1&&!reboots,"original APP+WWW no-reboot sequence preserved"); + reset();send_failure=true;check(handlers[kind](&req,NULL)==ESP_FAIL&&installs==1&&!reboots,"lost HTTP acknowledgement cannot auto-reboot"); + } + reset();bytes[0]=0;ota_firmware_upload_handler(&req,NULL);check(status==400&&!writes&&!installs,"invalid original firmware magic cannot affect old recovery set"); + cJSON_InitHooks(NULL);printf("%u checks: actual original-format APP/WWW handlers; cJSON allocation and SD/SDK/cache failure boundaries, no device\n",checks); +} +""" +headers={'esp_partition.h':'#pragma once\n#include \ntypedef struct {char label[17];uint32_t address,size;} esp_partition_t;\n','esp_app_format.h':(IDF/'components/bootloader_support/include/esp_app_format.h').read_text(),'esp_app_desc.h':(IDF/'components/esp_app_format/include/esp_app_desc.h').read_text(),'esp_assert.h':'#pragma once\n#define ESP_STATIC_ASSERT _Static_assert\n','esp_attr.h':'#pragma once\n#define FORCE_INLINE_ATTR static inline\n'} +run_native(code,[IDF/'components/json/cJSON/cJSON.c'],headers,[root/'components/ts_ota/include',root/'components/ts_security/include',root/'components/ts_core/ts_event/include']) diff --git a/tests/runtime/test_pki_http.py b/tests/runtime/test_pki_http.py new file mode 100644 index 00000000..4c8b2302 --- /dev/null +++ b/tests/runtime/test_pki_http.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Actual PKI operations and request-local replies; synthetic transport/cert/NVS. +Shared real HTTP/TLS framing, DNS and deadlines run in test_http_fetch.py. +""" +from pathlib import Path +import re +from test_console_lifecycle import RTOS,IDF,run_native,body +root=Path(__file__).resolve().parents[2] +source=(root/'components/ts_pki_client/src/ts_pki_client.c').read_text() +code=RTOS+r''' +typedef int StaticSemaphore_t; +typedef pthread_mutex_t portMUX_TYPE; +#define portMUX_INITIALIZER_UNLOCKED PTHREAD_MUTEX_INITIALIZER +#define portENTER_CRITICAL(p) pthread_mutex_lock(p) +#define portEXIT_CRITICAL(p) pthread_mutex_unlock(p) +static SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic(StaticSemaphore_t *storage){(void)storage;return xSemaphoreCreateRecursiveMutex();} + +#include "ts_pki_client.h" +#include "ts_cert.h" +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#include "cJSON.h" +#include +#include +#include +#ifndef ESP_ERR_INVALID_RESPONSE +#define ESP_ERR_INVALID_RESPONSE 0x108 +#endif +static atomic_uint checks,failures,json_allocs,json_frees; +static atomic_int json_budget=-1; +static pthread_mutex_t log_mutex=PTHREAD_MUTEX_INITIALIZER; +static char diagnostics[16384]; +static void log_capture(const char *tag,const char *format,...){(void)tag;pthread_mutex_lock(&log_mutex);size_t n=strlen(diagnostics);va_list args;va_start(args,format);vsnprintf(diagnostics+n,sizeof(diagnostics)-n,format,args);va_end(args);pthread_mutex_unlock(&log_mutex);} +#undef ESP_LOGD +#undef ESP_LOGI +#undef ESP_LOGE +#undef ESP_LOGW +#define ESP_LOGD log_capture +#define ESP_LOGI log_capture +#define ESP_LOGE log_capture +#define ESP_LOGW log_capture +static void check(bool ok,const char *why){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",why);}} +static pthread_mutex_t json_mutex=PTHREAD_MUTEX_INITIALIZER; +static void *json_live[128]; +static void *json_alloc(size_t n){if(json_budget==0)return NULL;if(json_budget>0)json_budget--;void *p=malloc(n);if(p){pthread_mutex_lock(&json_mutex);unsigned i=0;while(i<128&&json_live[i])i++;assert(i<128);json_live[i]=p;json_allocs++;pthread_mutex_unlock(&json_mutex);}return p;} +static void json_free(void *p){if(p){pthread_mutex_lock(&json_mutex);for(unsigned i=0;i<128;i++)if(json_live[i]==p){json_live[i]=NULL;json_frees++;break;}pthread_mutex_unlock(&json_mutex);}free(p);} +static _Thread_local const char *fixture_reply="{\"status\":\"pending\",\"request_id\":7}"; +static _Thread_local int fixture_status=200; +static _Thread_local esp_err_t fixture_error=ESP_OK; +static _Thread_local bool hold_response; +static SemaphoreHandle_t reply_entered,reply_release; +static atomic_uint requests,certificate_installs,ca_installs; +static char requested_url[256];static unsigned captured_timeout; +static SemaphoreHandle_t enroll_wait_entered; +static void tracked_delay(unsigned ticks){if(enroll_wait_entered)xSemaphoreGive(enroll_wait_entered);vTaskDelay(ticks);} +#define vTaskDelay tracked_delay +static bool reject_certificate,reject_ca,stored_ca_valid=true,has_stored_certificate; +#define ESP_MAC_WIFI_STA 1 +static esp_err_t esp_read_mac(uint8_t *mac,int role){(void)role;memset(mac,0x11,6);return ESP_OK;} +esp_err_t ts_cert_get_status(ts_cert_pki_status_t *out){memset(out,0,sizeof(*out));out->has_ca_chain=out->ca_valid=stored_ca_valid;out->has_certificate=out->has_private_key=has_stored_certificate;out->cert_info.validity=TS_CERT_VALIDITY_VALID;return ESP_OK;} +bool ts_cert_has_keypair(void){return true;} +esp_err_t ts_cert_generate_keypair(void){return ESP_OK;} +esp_err_t ts_cert_generate_csr_default(char *out,size_t *n){const char *csr="SYNTHETIC_PUBLIC_CSR";assert(*n>strlen(csr));strcpy(out,csr);*n=strlen(csr)+1;return ESP_OK;} +esp_err_t ts_cert_install_certificate(const char *pem,size_t n){certificate_installs++;check(n==strlen(pem)+1&&!strcmp(pem,"SYNTHETIC_CERTIFICATE"),"exact requested certificate reaches material owner");return reject_certificate?ESP_FAIL:ESP_OK;} +esp_err_t ts_cert_install_ca_chain(const char *pem,size_t n){ca_installs++;check(n==strlen(pem)+1&&!strcmp(pem,"SYNTHETIC_CA_CHAIN"),"exact requested CA reaches material owner");return reject_ca?ESP_FAIL:ESP_OK;} +esp_err_t ts_cert_install_issued_certificate_ex(const char *pem,size_t n,ts_cert_op_error_t *detail){ + (void)detail;certificate_installs++;check(n==strlen(pem)+1&&!strcmp(pem,"SYNTHETIC_CERTIFICATE"),"exact certificate uses the single issuer-verifying material owner");return reject_certificate?ESP_FAIL:stored_ca_valid?ESP_OK:ESP_ERR_INVALID_STATE; +} +bool ts_cert_prerequisites(const ts_cert_pki_status_t *s,bool ca){(void)s;(void)ca;return false;} +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *req,ts_http_fetch_result_t *out){ + captured_timeout=req->timeout_ms;snprintf(requested_url,sizeof(requested_url),"%s",req->url);requests++;check(req->timeout_ms>0&&req->timeout_ms<=TS_PKI_HTTP_TIMEOUT_MS&&req->maximum_body==8191,"existing PKI 30s total/8KiB reply limit passes to shared owner"); + check(req->method==HTTP_METHOD_GET||req->method==HTTP_METHOD_POST,"PKI methods retained"); + if(req->method==HTTP_METHOD_POST){check(req->content_type&&!strcmp(req->content_type,"application/json")&&req->body,"CSR JSON content type/body retained");int saved_budget=atomic_exchange(&json_budget,-1);cJSON *csr=cJSON_Parse(req->body);check(csr&&cJSON_IsString(cJSON_GetObjectItem(csr,"csr_pem"))&&cJSON_IsString(cJSON_GetObjectItem(csr,"device_id"))&&cJSON_IsString(cJSON_GetObjectItem(csr,"description"))&&cJSON_IsArray(cJSON_GetObjectItem(csr,"suggested_san_ips")),"every transmitted CSR body retains all required fields");cJSON_Delete(csr);json_budget=saved_budget;} + if(fixture_error!=ESP_OK)return fixture_error; + out->status=fixture_status;out->length=strlen(fixture_reply);out->body=strdup(fixture_reply); + if(hold_response){xSemaphoreGive(reply_entered);xSemaphoreTake(reply_release,portMAX_DELAY);} + return ESP_OK; +} +#define free json_free +'''+re.sub(r'^#include[^\n]*\n','',source,flags=re.M)+r''' +#undef vTaskDelay +static unsigned dependency_stops; +void ts_cert_deinit(void){dependency_stops++;} +static void ts_known_hosts_deinit(void){dependency_stops++;} +static void ts_keystore_deinit(void){dependency_stops++;} +static void ts_security_deinit(void){dependency_stops++;} +'''+body(root/'main/ts_services.c','security_service_stop')+r''' +static void reset_reply(const char *reply,int status){fixture_reply=reply;fixture_status=status;fixture_error=ESP_OK;reject_certificate=reject_ca=false;} +static void *held_status(void *cancel){hold_response=true;reset_reply("{\"status\":\"approved\"}",200);ts_pki_enroll_status_t status;esp_err_t ret=ts_pki_client_check_status(&status);check(cancel?ret!=ESP_OK&&status==TS_PKI_ENROLL_ERROR:ret==ESP_OK&&status==TS_PKI_ENROLL_APPROVED,"held reply is either its own approved result or cooperatively cancelled by deinit");return NULL;} +static void *blocking_enrollment(void *unused){(void)unused;reset_reply("{\"status\":\"pending\",\"request_id\":7}",200);check(ts_pki_client_enroll_blocking(60)==ESP_ERR_INVALID_STATE,"blocking workflow cooperatively exits while waiting after deinit cancellation");return NULL;} +int main(void){ + cJSON_Hooks hooks={json_alloc,json_free};cJSON_InitHooks(&hooks); + ts_pki_client_config_t config;ts_pki_client_get_default_config(&config);config.auto_start=false;config.use_https=true;strcpy(config.server_host,"synthetic-host.invalid"); + check(ts_pki_client_init_with_config(&config)==ESP_OK,"PKI init no global HTTP buffer allocation"); + check(ts_pki_client_submit_csr()==ESP_OK&&s_client.request_id==7,"manual CSR submission and request ID retained"); + const char *states[]={"approved","rejected","pending","unknown"};const ts_pki_enroll_status_t want[]={TS_PKI_ENROLL_APPROVED,TS_PKI_ENROLL_REJECTED,TS_PKI_ENROLL_PENDING,TS_PKI_ENROLL_ERROR}; + for(unsigned i=0;i<4;i++){char text[128];snprintf(text,sizeof(text),"{\"status\":\"%s\"}",states[i]);reset_reply(text,200);ts_pki_enroll_status_t status;check(ts_pki_client_check_status(&status)==ESP_OK&&status==want[i],"complete status JSON maps unchanged");} + const char *invalid[]={"", "not-json", "[]", "null", "true", "{} trailing", "{\"status\":\"approved\"}{}"}; + for(unsigned i=0;i #include #include "ts_api.h" +#include "ts_security.h" #include "ts_power_policy.h" #include "ts_power_monitor.h" #include "freertos/semphr.h" @@ -290,7 +291,7 @@ def function(path, name): with tempfile.TemporaryDirectory(prefix='ts-power-settings-') as directory: build = Path(directory); (build / 'test.c').write_text(code) subprocess.run(['cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', - '-fno-sanitize-recover=all', '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', + '-fno-sanitize-recover=all', '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', '-Icomponents/ts_security/include', '-Icomponents/ts_drivers/include', '-I' + str(cjson), '-I' + str(argtable), str(build / 'test.c'), str(cjson / 'cJSON.c'), *map(str, argtable.glob('*.c')), '-lpthread', '-lm', '-o', str(build / 'test')], check=True) diff --git a/tests/runtime/test_probe.py b/tests/runtime/test_probe.py index b95bdd4f..3ebb790c 100644 --- a/tests/runtime/test_probe.py +++ b/tests/runtime/test_probe.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 +from host_paths import build_dir import sys """Actual C shell builder + /bin/sh/grep, synthetic files only.""" import ctypes, pathlib, subprocess, tempfile root=pathlib.Path(__file__).resolve().parents[2] -out=pathlib.Path('/tmp/tianshan-runtime-tests/probe.dylib') +out=build_dir('probe') / 'probe.dylib' subprocess.run(['cc',*(['-isysroot','/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk'] if sys.platform == 'darwin' else []),'-shared','-fPIC','-I'+str(root/'components/ts_security/include'),str(root/'components/ts_security/src/ts_ssh_probe.c'),'-o',str(out)],check=True) lib=ctypes.CDLL(str(out)); lib.ts_ssh_log_probe_command.restype=ctypes.c_bool;lib.ts_ssh_probe_token.restype=ctypes.c_bool with tempfile.TemporaryDirectory(prefix='ts-probe-') as temp: diff --git a/tests/runtime/test_proxy_ws_samples.py b/tests/runtime/test_proxy_ws_samples.py new file mode 100644 index 00000000..6dfa312e --- /dev/null +++ b/tests/runtime/test_proxy_ws_samples.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Production diagnostic WS/SIO callbacks with real cJSON; synthetic SDK events, +allocator faults and semaphore effects. No network, device or real credentials. +""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2] +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +f='components/ts_api/src/ts_api_automation.c' +if args.source_package: + with ZipFile(args.source_package) as z:t=z.read('current-source/'+f).decode() +else:t=(ROOT/f).read_text() +def function(name): + m=re.search(r'^static [^\n;]+\b'+name+r'\([^;]+?\)\s*\{',t,re.M);assert m,name + return t[m.start():t.index('\n}',m.end())+2]+'\n' +def struct(name): + e=t.index('} '+name+';')+len('} '+name+';');a=t.rfind('typedef struct',0,e);return t[a:e]+'\n' +def diagnostic_budget_fixture(): + """Real entry points/callbacks. Substitute only SDK I/O, monotonic time and + JSON-path presentation helpers (those have independent codec tests).""" + if args.source_package: return '' # Historical packages predate these helpers. + support=r""" +#include +#include "ts_api.h" +#include "ts_http_fetch.h" +#include "ts_http_url.h" +#define TS_LOGW capture +#define TS_STRDUP_PSRAM strdup +#define pdTRUE 1 +#define pdMS_TO_TICKS(ms) (ms) +typedef unsigned TickType_t; +typedef void (*ws_callback_t)(void *,esp_event_base_t,int32_t,void *); +typedef void *esp_websocket_client_handle_t; +typedef struct {const char *uri;unsigned buffer_size,network_timeout_ms;int port;void *ext_transport;bool disable_auto_reconnect;int (*crt_bundle_attach)(void *);} esp_websocket_client_config_t; +#define WEBSOCKET_EVENT_ANY -1 +static int64_t fake_now,operation_deadline; +static unsigned created_sems,deleted_sems,http_calls,ws_inits,ws_starts,ws_stops,ws_destroys,sends,wait_index; +static unsigned connect_delay,probe_delay,data_delay,http_delay,send_delay; +static int expire_event_stage; +static const char *polling_payload;static char captured_ws_uri[512]; +static unsigned transports_created,transports_destroyed; +typedef struct {void *websocket;int port;} ts_api_ws_test_transport_t; +static bool is_sio,partial_send,registration_failure,start_failure,init_failure,omit_data; +static ws_callback_t registered_callback;static void *registered_context; +static int64_t esp_timer_get_time(void){return fake_now;} +static int esp_crt_bundle_attach(void *v){(void)v;return 0;} +/* Constructor/destructor boundary only. The transport implementation and real + * SDK dispatch are verified separately; this fixture proves both API consumers. */ +static esp_err_t ts_api_ws_test_transport_init(ts_api_ws_test_transport_t *owner,const char *uri,int64_t deadline){ + check(deadline==operation_deadline,"API transports receive the original absolute operation deadline");struct http_parser_url parsed;check(ts_ws_url_parse(uri,&parsed),"actual external transport receives the validated WS URI");owner->websocket=(void*)2;owner->port=parsed.field_set&(1U<websocket){transports_destroyed++;owner->websocket=NULL;}} + +static const char *esp_err_to_name(esp_err_t e){(void)e;return "synthetic_sdk_failure";} +static SemaphoreHandle_t xSemaphoreCreateBinary(void){check(created_sems<3,"bounded diagnostic semaphores");return ++created_sems;} +static void vSemaphoreDelete(SemaphoreHandle_t s){check(s>0&&s<=3,"only owned semaphore deleted");deleted_sems++;} +static void inject_text(const char *text){esp_websocket_event_data_t e={.fin=true,.op_code=1,.data_ptr=text,.data_len=(int)strlen(text),.payload_len=(int)strlen(text)};registered_callback(registered_context,0,WEBSOCKET_EVENT_DATA,&e);} +static bool xSemaphoreTake(SemaphoreHandle_t sem,TickType_t ticks){ + if(gives[sem]){gives[sem]--;return true;} + unsigned stage=wait_index++,delay=stage==0?connect_delay:is_sio&&stage==1?probe_delay:data_delay; + check(fake_now+(int64_t)ticks*1000<=operation_deadline,"each wait uses the remaining operation budget"); + if(ticksuri);ws_inits++;check(cfg->ext_transport==(void*)2&&cfg->port>0,"actual API binds external bounded transport and explicit port");check(cfg->disable_auto_reconnect&&cfg->crt_bundle_attach==esp_crt_bundle_attach,"existing reconnect/TLS trust settings retained");check(cfg->network_timeout_ms>0&&cfg->network_timeout_ms<=30000,"no zero or wrapped SDK timeout");return init_failure?NULL:(void*)1; +} +static esp_err_t esp_websocket_register_events(void *client,int event,ws_callback_t cb,void *ctx){(void)client;(void)event;registered_callback=cb;registered_context=ctx;return registration_failure?ESP_FAIL:ESP_OK;} +static esp_err_t esp_websocket_client_start(void *client){(void)client;ws_starts++;return start_failure?ESP_FAIL:ESP_OK;} +static esp_err_t esp_websocket_client_stop(void *client){check(client!=NULL,"stop owned client");ws_stops++;return ESP_OK;} +static esp_err_t esp_websocket_client_destroy(void *client){check(client!=NULL,"destroy owned client");ws_destroys++;return ESP_OK;} +static int esp_websocket_client_send_text(void *client,const char *text,int length,TickType_t ticks){ + (void)client;(void)text;sends++;check(fake_now+(int64_t)ticks*1000<=operation_deadline,"send never receives a fresh fixed timeout"); + if(ticksmaximum_body==2047&&req->timeout_ms&&fake_now+(int64_t)req->timeout_ms*1000<=operation_deadline,"SIO polling consumes the same total budget"); + if(http_delay>=req->timeout_ms){fake_now+=(int64_t)req->timeout_ms*1000;return ESP_ERR_TIMEOUT;} + fake_now+=(int64_t)http_delay*1000;out->status=200;out->body=strdup(polling_payload);return ESP_OK; +} +static cJSON *extract_json_value(cJSON *v,const char *path){return cJSON_GetObjectItem(v,path);} +static void collect_json_paths(cJSON *value,const char *prefix,cJSON *out,int depth){(void)value;(void)prefix;(void)out;(void)depth;} +""" + api=(ROOT/'components/ts_api/src/ts_api.c').read_text() + for name in ['ts_api_result_error','ts_api_result_reason','ts_api_result_free']: + m=re.search(r'^(?:static )?[^\n;]+\b'+name+r'\([^;]+?\)\s*\{',api,re.M);assert m,name + support+=api[m.start():api.index('\n}',m.end())+2]+'\n' + source=(ROOT/'components/ts_automation/src/ts_source_manager.c').read_text() + m=re.search(r'^bool ts_source_sio_url\([^;]+?\)\s*\{',source,re.M);assert m + support+=source[m.start():source.index('\n}',m.end())+2]+'\n' + for name in ['proxy_test_timeout','proxy_test_remaining_ms','proxy_test_send','api_automation_proxy_ws_test','api_automation_proxy_socketio_test']:support+=function(name) + support+=r""" +static void reset_operation(bool sio,unsigned budget){ + memset(gives,0,sizeof(gives));created_sems=deleted_sems=http_calls=ws_inits=ws_starts=ws_stops=ws_destroys=sends=wait_index=0; + transports_created=transports_destroyed=0;expire_event_stage=-1; + polling_payload="0{\"sid\":\"synthetic_session\"}";captured_ws_uri[0]=0;fake_now=0;operation_deadline=(int64_t)budget*1000;is_sio=sio; + connect_delay=100;probe_delay=100;data_delay=100;http_delay=100;send_delay=10; + partial_send=registration_failure=start_failure=init_failure=omit_data=false;registered_callback=NULL;registered_context=NULL; +} +static void invoke_operation(cJSON *p,ts_api_result_t *r){if(is_sio)api_automation_proxy_socketio_test(p,r);else api_automation_proxy_ws_test(p,r);} +static cJSON *operation_params(unsigned timeout){ + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,is_sio?"url":"uri",is_sio?"https://fixture.invalid":"wss://fixture.invalid/data"); + if(timeout)cJSON_AddNumberToObject(p,"timeout_ms",timeout);return p; +} +static void verify_operation_cleanup(void){ + check(transports_created==transports_destroyed,"every diagnostic external transport released after client join");check(created_sems==deleted_sems,"all diagnostic semaphores released");check(ws_destroys==ws_inits-(init_failure?1:0),"every initialized client destroyed exactly once");} +static void diagnostic_budget_tests(void){ + + char url[512],small[8]; + check(ts_source_sio_url("HTTPS://[::1]:8443/prefix/","opaque&transport=polling/#?+%",url,sizeof(url))&&!strcmp(url,"wss://[::1]:8443/prefix/socket.io/?EIO=4&transport=websocket&sid=opaque%26transport%3Dpolling%2F%23%3F%2B%25"),"one validated base preserves TLS,IPv6,path and percent-encodes all SID query delimiters"); + check(ts_source_sio_url("http://user:synthetic@fixture.invalid/prefix/",NULL,url,sizeof(url))&&!strcmp(url,"http://user:synthetic@fixture.invalid/prefix/socket.io/?EIO=4&transport=polling"),"polling preserves existing path and URI credentials without double slash"); + check(!ts_source_sio_url("https://fixture.invalid","sid",small,sizeof(small))&&!small[0],"short output rejects without returning truncated connection target"); + const char *bad_base[]={"https://fixture.invalid/?transport=x","https://fixture.invalid/#fragment","ws://fixture.invalid","https://bad host","https://fixture.invalid:0"}; + for(unsigned i=0;ivaluedouble=NAN;ts_api_result_t r={0};invoke_operation(p,&r);check(r.code==TS_API_ERR_INVALID_ARG&&!ws_inits,"nonfinite timeout rejected before conversion");ts_api_result_free(&r);cJSON_Delete(p); + for(unsigned kind=0;kind<3;kind++){ + reset_operation(sio,1000);p=operation_params(1000);const char *field=kind==0?"json_path":sio?"event":"subscribe"; + if(kind==1)cJSON_AddBoolToObject(p,field,true);else {size_t length=kind==0||sio?256:4097;char *text=malloc(length+1);memset(text,'a',length);text[length]=0;cJSON_AddStringToObject(p,field,text);free(text);} + r=(ts_api_result_t){0};invoke_operation(p,&r);check(r.code==TS_API_ERR_INVALID_ARG&&!created_sems&&!http_calls&&!ws_inits,"wrong type or oversized diagnostic selector rejected before effects");ts_api_result_free(&r);cJSON_Delete(p); + } + reset_operation(sio,1000);p=operation_params(1000);json_budget=0;cJSON_Hooks oom_hooks={json_malloc,free};cJSON_InitHooks(&oom_hooks);r=(ts_api_result_t){0};invoke_operation(p,&r);json_budget=-1;cJSON_InitHooks(NULL); + check(r.code==TS_API_ERR_NO_MEM&&!http_calls&&!ws_inits,"response allocation failure has no network effects");verify_operation_cleanup();ts_api_result_free(&r);cJSON_Delete(p); + // Original UI values, default timeout and normal protocol stay usable. + for(unsigned mode=0;mode<3;mode++){ + reset_operation(sio,mode==2?30000:mode?5000:sio?15000:10000);p=operation_params(mode==2?30000:mode?5000:0);if(!sio)cJSON_AddStringToObject(p,"subscribe","{\"subscribe\":true}");r=(ts_api_result_t){0};invoke_operation(p,&r); + check(r.code==TS_API_OK&&cJSON_IsTrue(cJSON_GetObjectItem(r.data,"connected")),"original UI/default handshake and sample succeed"); + check(ws_starts==1&&ws_stops==1&&ws_destroys==1&&fake_now +#include +#include +#include +#include +#include +#include +#include "cJSON.h" +typedef int SemaphoreHandle_t; +typedef int esp_event_base_t; +enum {WEBSOCKET_EVENT_CONNECTED,WEBSOCKET_EVENT_CLOSED,WEBSOCKET_EVENT_DISCONNECTED,WEBSOCKET_EVENT_DATA,WEBSOCKET_EVENT_ERROR}; +typedef struct {bool fin;uint8_t op_code;const char *data_ptr;int data_len,payload_len,payload_offset;} esp_websocket_event_data_t; +#define MALLOC_CAP_SPIRAM 1 +#define MALLOC_CAP_8BIT 2 +static unsigned checks,failures,allocations,max_allocation,gives[4]; +static bool fail_alloc;static int json_budget=-1; +static char logs[8192]; +static void capture(const char *tag,const char *fmt,...){(void)tag;size_t n=strlen(logs);va_list ap;va_start(ap,fmt);vsnprintf(logs+n,sizeof(logs)-n,fmt,ap);va_end(ap);} +#define TAG "fixture" +#define TS_LOGI capture +#define TS_LOGD capture +#define TS_LOGE capture +static void xSemaphoreGive(SemaphoreHandle_t s){if(s>=0&&s<4)gives[s]++;} +static void *heap_caps_realloc(void *p,size_t n,int caps){(void)caps;allocations++;if(n>max_allocation)max_allocation=(unsigned)n;if(fail_alloc||n>65537)return NULL;return realloc(p,n);} +static void *heap_caps_malloc(size_t n,int caps){return heap_caps_realloc(NULL,n,caps);} +static void *json_malloc(size_t n){if(json_budget==0)return NULL;if(json_budget>0)json_budget--;return malloc(n);} +static void check(bool ok,const char *why){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",why);}} +''' +if modern:code+='#define PROXY_WS_SAMPLE_MAX (64U*1024U)\n'+struct('proxy_ws_sample_t')+function('proxy_ws_sample_append') +code+=struct('ws_test_ctx_t')+function('ws_test_handler')+struct('sio_test_ctx_t')+function('sio_try_parse_event')+function('sio_parse_message')+function('sio_ws_handler') +if modern:code+=r''' +#define WS_DATA(c) ((c).sample.data) +#define WS_LENGTH(c) ((c).sample.length) +#define WS_FAILED(c) ((c).failed) +#define SIO_FAILED(c) ((c).failed) +#define SIO_CAP(c) ((c).sample.capacity) +#define SIO_RX_FREE(c) free((c).sample.data) +''' +else:code+=r''' +#define WS_DATA(c) ((c).message) +#define WS_LENGTH(c) ((c).message_len) +#define WS_FAILED(c) ((c).error!=NULL) +#define SIO_FAILED(c) ((c).error!=NULL) +#define SIO_CAP(c) ((c).fragment_cap) +#define SIO_RX_FREE(c) free((c).fragment_buf) +''' +code+=diagnostic_budget_fixture() if not args.source_package else 'static void diagnostic_budget_tests(void){}\n' +code+=r''' +static void ws_event(ws_test_ctx_t *c,int opcode,bool fin,const char *p,int n,int total,int offset){esp_websocket_event_data_t e={fin,(uint8_t)opcode,p,n,total,offset};ws_test_handler(c,0,WEBSOCKET_EVENT_DATA,&e);} +static void sio_event(sio_test_ctx_t *c,int opcode,bool fin,const char *p,int n,int total,int offset){esp_websocket_event_data_t e={fin,(uint8_t)opcode,p,n,total,offset};sio_ws_handler(c,0,WEBSOCKET_EVENT_DATA,&e);} +static void ws_free(ws_test_ctx_t *c){free(WS_DATA(*c));free(c->error);memset(c,0,sizeof(*c));} +static void sio_free(sio_test_ctx_t *c){free(c->sid);free(c->message);free(c->event_name);free(c->error);SIO_RX_FREE(*c);memset(c,0,sizeof(*c));} +int main(void){ + char text[128]="{\"v\":\"中文 123\"}",event[128]="42[\"status\",{\"value\":12345}]";int n=(int)strlen(text),en=(int)strlen(event);memset(text+n,'x',sizeof(text)-(size_t)n);memset(event+en,'x',sizeof(event)-(size_t)en); + // Every SDK cut, including cuts in UTF-8 or at the first byte of a number. + for(int cut=1;cut1024?1024:size-at;ws_event(&c,1,true,large+at,(int)got,(int)size,(int)at);at+=got;} + check(c.received&&!WS_FAILED(c)&&WS_LENGTH(c)==size&&!memcmp(WS_DATA(c),large,size),"WS normal 8 KiB/64 KiB exact sample, no silent truncation");ws_free(&c);free(large);if(size==65536)break; + } + + // Exact 64 KiB Socket.IO sample remains available, including all payload bytes. + {const char *prefix="42[\"status\",{\"value\":\"",*suffix="\"}]";size_t size=65536,head=strlen(prefix),tail=strlen(suffix);char *large=malloc(size+1);memcpy(large,prefix,head);memset(large+head,'z',size-head-tail);memcpy(large+size-tail,suffix,tail+1);sio_test_ctx_t sample={.data_sem=1};for(size_t at=0;at1024?1024:size-at;sio_event(&sample,1,true,large+at,(int)count,(int)size,(int)at);at+=count;}check(sample.received&&sample.message&&strlen(sample.message)==size-head-tail+12,"SIO 64 KiB exact message retains full payload");sio_free(&sample);free(large);} + {ws_test_ctx_t empty={.data_sem=1};ws_event(&empty,1,false,text,n,n,0);ws_event(&empty,0,true,NULL,0,0,0);check(empty.received&&WS_LENGTH(empty)==(size_t)n&&!memcmp(WS_DATA(empty),text,n),"empty continuation FIN completes buffered WS sample");ws_free(&empty);} + // An oversized declared message is rejected before any allocation/read-copy. + ws_test_ctx_t w={.data_sem=1};unsigned before=allocations;ws_event(&w,1,true,"x",1,65537,0);check(WS_FAILED(w)&&!w.received&&allocations==before,"WS oversized frame rejected before allocation");ws_free(&w); + sio_test_ctx_t c={.data_sem=1,.upgrade_sem=2};before=allocations;sio_event(&c,1,true,"4",1,INT_MAX,0);check(SIO_FAILED(c)&&!c.received&&allocations==before,"SIO oversized frame rejected before allocation");sio_free(&c); + // Never allow a sequence of incomplete frames to grow the diagnostic heap. + c=(sio_test_ctx_t){.data_sem=1};char block[4096];memset(block,'x',sizeof(block));memcpy(block,"42[",3);sio_event(&c,1,false,block,4096,4096,0);memset(block,'x',sizeof(block)); + for(int i=0;i<20;i++)sio_event(&c,0,false,block,4096,4096,0); + check(SIO_FAILED(c)&&!c.received&&SIO_CAP(c)<=65537&&max_allocation<=65537,"SIO aggregate continuation budget bounded before realloc");before=allocations;sio_event(&c,0,true,"1]",2,2,0);check(allocations==before&&!c.received,"failed SIO ignores all later payload");sio_free(&c); + // Offset, declared length, opcode and FIN consistency are SDK callback contracts. + for(unsigned kind=0;kind<7;kind++){ + w=(ws_test_ctx_t){.data_sem=1};c=(sio_test_ctx_t){.data_sem=1}; + ws_event(&w,1,true,text,2,n,0);sio_event(&c,1,true,event,2,en,0); + int offset=kind==0?3:kind==1?0:2,total=kind==2?n+1:n,stotal=kind==2?en+1:en,opcode=kind==3?2:1; + int got=kind==4?n:kind==5?-1:1;bool fin=kind!=6; + ws_event(&w,opcode,fin,text+2,got,total,offset);sio_event(&c,opcode,fin,event+2,kind==4?en:got,stotal,offset); + check(WS_FAILED(w)&&!w.received,"WS invalid metadata fails instead of mixing messages");check(SIO_FAILED(c)&&!c.received,"SIO invalid metadata fails instead of mixing messages");ws_free(&w);sio_free(&c); + } + w=(ws_test_ctx_t){.data_sem=1};ws_event(&w,0,true,"x",1,1,0);check(WS_FAILED(w)&&!w.received,"orphan continuation fails");ws_free(&w); + w=(ws_test_ctx_t){.data_sem=1};char nul[3]={'a',0,'b'};ws_event(&w,1,true,nul,3,3,0);check(WS_FAILED(w)&&!w.received,"embedded NUL cannot publish a truncated text result");ws_free(&w); + // Existing allocation remains owned on realloc failure and all errors wake waiters. + w=(ws_test_ctx_t){.data_sem=1};ws_event(&w,1,false,block,4096,4096,0);fail_alloc=true;before=gives[1];ws_event(&w,0,true,block,4096,4096,0);fail_alloc=false;check(WS_FAILED(w)&&!w.received&&gives[1]>before,"WS realloc failure truthful and wakes waiter");ws_free(&w); + c=(sio_test_ctx_t){.data_sem=1,.upgrade_sem=2};fail_alloc=true;before=gives[1];sio_event(&c,1,true,event,en,en,0);fail_alloc=false;check(SIO_FAILED(c)&&!c.received&&gives[1]>before,"SIO realloc failure truthful and wakes waiter");sio_free(&c); + // JSON payload print failure cannot signal a successful event with no payload. + for(int budget=0;budget<20;budget++){ + c=(sio_test_ctx_t){.data_sem=1};cJSON_Hooks hooks={json_malloc,free};json_budget=budget;cJSON_InitHooks(&hooks);sio_event(&c,1,true,event,en,en,0);json_budget=-1;cJSON_InitHooks(NULL); + check(!c.received||(c.message&&c.event_name&&!strcmp(c.message,"{\"value\":12345}")),"SIO event OOM never reports partial success");sio_free(&c); + } + // Engine.IO setup, filtering, complete-message reuse and secret-free diagnostics. + logs[0]=0;c=(sio_test_ctx_t){.data_sem=1,.upgrade_sem=2,.target_event="private_event_SYNTHETIC"};const char *open="0{\"sid\":\"private_sid_SYNTHETIC\"}";sio_event(&c,1,true,open,(int)strlen(open),(int)strlen(open),0);check(c.sid&&!strcmp(c.sid,"private_sid_SYNTHETIC"),"Engine.IO open retained");sio_event(&c,1,true,"3probe",6,6,0);check(c.upgraded,"probe retained");sio_event(&c,1,true,event,en,en,0);check(!c.received,"nonmatching event remains filtered");const char *selected="42[\"private_event_SYNTHETIC\",{\"v\":1}]";sio_event(&c,1,true,selected,(int)strlen(selected),(int)strlen(selected),0);check(c.received&&c.message&&!strcmp(c.message,"{\"v\":1}"),"matching event full payload retained");check(!strstr(logs,"private_sid_SYNTHETIC")&&!strstr(logs,"private_event_SYNTHETIC"),"shared logs omit remote session/event payload");sio_free(&c); + diagnostic_budget_tests(); + printf("%u checks, %u failures: actual diagnostic WS/SIO callbacks and allocator boundaries; synthetic SDK events, no network/device\n",checks,failures);return failures?1:0; +} +''' +IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf'));cjson=IDF/'components/json/cJSON' +with tempfile.TemporaryDirectory(prefix='ts-proxy-samples-') as tmp: + c=Path(tmp)/'test.c';c.write_text(code);exe=Path(tmp)/'test' + subprocess.run(['cc','-std=gnu11','-g','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(cjson),'-I'+str(ROOT/'tests/runtime/storage_stubs'),'-I'+str(ROOT/'tests/runtime/http_fetch_stubs'),'-I'+str(ROOT/'components/ts_api/include'),'-I'+str(ROOT/'components/ts_http_fetch/include'),'-I'+str(IDF/'components/http_parser'),str(c),str(cjson/'cJSON.c'),str(ROOT/'components/ts_http_fetch/src/ts_http_url.c'),str(IDF/'components/http_parser/http_parser.c'),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True,timeout=30) diff --git a/tests/runtime/test_receive_budget.py b/tests/runtime/test_receive_budget.py new file mode 100644 index 00000000..a788d1cd --- /dev/null +++ b/tests/runtime/test_receive_budget.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Actual generated SDK receive/session functions; deterministic clock/socket I/O. + +No external network, device, real credentials or wall-clock slow-request traffic. +""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2] +IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf')) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',ROOT),text=True) + return (ROOT/path).read_text() +def function(text,name): + m=re.search(r'^(?:static )?[\w *]+\b'+name+r'\([^;]*?\)\s*\{',text,re.M);assert m,name + return text[m.start():text.index('\n}',m.end())+2]+'\n' +with tempfile.TemporaryDirectory(prefix='ts-rx-budget-') as tmp: + t=Path(tmp);namespace={'__name__':'rx_fixture_generator'};exec(compile(source('tools/prepare_httpd_admission.py'),'prepare.py','exec'),namespace);namespace['prepare'](IDF,t) + txrx=(t/'httpd_txrx.c').read_text();sess=(t/'httpd_sess.c').read_text();parse=(t/'httpd_parse.c').read_text() + block=re.search(r'/\* TS_RX_BUDGET_BEGIN[\s\S]*?/\* TS_RX_BUDGET_END \*/',txrx) + code=r""" +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#define ESP_OK 0 +#define ESP_FAIL -1 +#define ESP_ERR_INVALID_SIZE 0x104 +#define HTTPD_SOCK_ERR_TIMEOUT -7 +#define ESP_LOGD(...) ((void)0) +#define ESP_LOGW(...) ((void)0) +#define LOG_FMT(x) x +#define MIN(a,b) ((a)<(b)?(a):(b)) +typedef int esp_err_t; +typedef enum {HTTPD_RECV_OPT_NONE,HTTPD_RECV_OPT_BLOCKING,HTTPD_RECV_OPT_HALT_AFTER_PENDING} httpd_recv_opt_t; +static _Thread_local uint32_t fake_clock,step; +static _Thread_local unsigned reads; +static _Thread_local int result_bytes; +static uint32_t esp_log_timestamp(void){return fake_clock;} +struct sock_db {void *handle;int fd;char pending_data[128];size_t pending_len;uint64_t lru_counter;int(*recv_fn)(void*,int,char*,size_t,int);}; +struct httpd_req_aux {struct sock_db *sd;}; +typedef struct {struct httpd_req_aux *aux;} httpd_req_t; +struct httpd_data {uint64_t lru_counter;}; +static int fake_recv(void *handle,int fd,char *out,size_t n,int flags){(void)handle;(void)fd;(void)flags;++reads;fake_clock+=step;if(reads>64)return -99;if(result_bytes<=0)return result_bytes;size_t got=(size_t)result_bytescontent_len = \(\(int\)parser->content_length[\s\S]*?;',parse);assert m + code+='static bool ts_httpd_decode_content_length(uint64_t wire,bool present,bool chunked,size_t *length){(void)present;(void)chunked;struct{uint32_t content_len;}req,*r=&req;struct{uint64_t content_length;}p={wire},*parser=&p;'+m.group()+'*length=r->content_len;return true;}\n' + ws=(t/'httpd_ws.c').read_text() + if 'uint64_t wide_len =' in ws: + match=re.search(r'uint64_t wide_len =[\s\S]*?frame->len = \(size_t\)wide_len;',ws) + else:match=re.search(r'frame->len = \(\(\(uint64_t\)length_bytes\[0\][\s\S]*?;',ws) + assert match + # Execute the exact SDK narrowing block with the ESP32's32-bit frame field. + # Pointers/other library code remain native64-bit; this is an ABI model. + code+='\n#undef SIZE_MAX\n#define SIZE_MAX UINT32_MAX\nstatic int decode_ws_32(const uint8_t length_bytes[8],uint32_t *out){struct{uint32_t len;}value={0},*frame=&value;\n'+match.group()+'\n*out=frame->len;return ESP_OK;}\n#undef SIZE_MAX\n#define SIZE_MAX __SIZE_MAX__\n' + code+=r""" +static atomic_uint checks,failures; +static void check(bool ok,const char *label){atomic_fetch_add(&checks,1);if(!ok){atomic_fetch_add(&failures,1);fprintf(stderr,"FAIL SDK receive %s\n",label);}} +static void reset(void){ts_httpd_receive_end();fake_clock=0;step=0;reads=0;result_bytes=1;} +static void one_body(httpd_req_t *req,uint32_t budget,uint32_t increment){ + reset();ts_httpd_receive_begin();ts_httpd_set_body_receive_budget(budget);step=increment;char data[32];int ret=0;unsigned attempts=0; + do{ret=httpd_recv(req,data,1);++attempts;}while(ret>0&&attempts<40); + check(ret==HTTPD_SOCK_ERR_TIMEOUT&&attempts<=2,"body total budget expires despite successful partial receives");ts_httpd_receive_end(); +} +static int lifecycle_mode; +static httpd_req_t *lifecycle_req; +static int httpd_req_new(struct httpd_data *hd,struct sock_db *s){(void)hd;(void)s;char b[4];if(lifecycle_mode==1){fake_clock+=15000;return httpd_recv(lifecycle_req,b,1)==HTTPD_SOCK_ERR_TIMEOUT?ESP_FAIL:ESP_OK;}if(lifecycle_mode==2)return ESP_FAIL;return ESP_OK;} +static int httpd_req_delete(struct httpd_data *hd){(void)hd;return lifecycle_mode==3?ESP_FAIL:ESP_OK;} +""" + if 'httpd_sess_process_impl(' in sess:code+=function(sess,'httpd_sess_process_impl') + code+=function(sess,'httpd_sess_process') + code+=r""" +static void *worker(void *arg){uintptr_t kind=(uintptr_t)arg;struct sock_db sd={.recv_fn=fake_recv};struct httpd_req_aux aux={&sd};httpd_req_t req={&aux};char b[4];for(unsigned i=0;i<1000;i++){reset();ts_httpd_receive_begin();ts_httpd_set_body_receive_budget(kind?10:100);fake_clock=20;check((httpd_recv(&req,b,1)==HTTPD_SOCK_ERR_TIMEOUT)==(kind!=0),"independent server-task deadlines cannot leak across listeners");ts_httpd_receive_end();}return NULL;} +int main(void){ + struct sock_db sd={.recv_fn=fake_recv};struct httpd_req_aux aux={&sd};httpd_req_t req={&aux};char data[64]; + reset();fake_clock=500000;check(httpd_recv(&req,data,4)==1,"outside request lifetime has no stale timeout"); + reset();ts_httpd_receive_begin();step=4000;unsigned n=0;int ret=0;do{ret=httpd_recv(&req,data,1);++n;}while(ret>0&&n<20);check(ret==HTTPD_SOCK_ERR_TIMEOUT&&n==4,"slow header fragments share one15s budget");check(reads==4,"deadline checked after a late successful socket read");ts_httpd_receive_end(); + one_body(&req,10000,6000);one_body(&req,30000,16000);one_body(&req,300000,160000); + reset();ts_httpd_receive_begin();ts_httpd_set_body_receive_budget(10);fake_clock=9;ts_httpd_set_body_receive_budget(300000);step=1;check(httpd_recv(&req,data,1)==HTTPD_SOCK_ERR_TIMEOUT,"second admission cannot extend an auth budget");ts_httpd_receive_end(); + reset();ts_httpd_receive_begin();ts_httpd_set_body_receive_budget(UINT32_MAX);fake_clock=300000;check(httpd_recv(&req,data,1)==HTTPD_SOCK_ERR_TIMEOUT&&!reads,"SDK clamps maximum body budget before another receive");ts_httpd_receive_end(); + reset();fake_clock=UINT32_MAX-100;ts_httpd_receive_begin();fake_clock+=15000;check(httpd_recv(&req,data,1)==HTTPD_SOCK_ERR_TIMEOUT,"monotonic32-bit millisecond wrap remains bounded");ts_httpd_receive_end(); + reset();ts_httpd_receive_begin();ts_httpd_set_body_receive_budget(10);step=6;check(httpd_recv_with_opt(&req,data,8,HTTPD_RECV_OPT_BLOCKING)==HTTPD_SOCK_ERR_TIMEOUT&&reads==2,"blocking SDK receive checks deadline inside every partial-read loop");ts_httpd_receive_end(); + reset();ts_httpd_receive_begin();result_bytes=0;check(httpd_recv_with_opt(&req,data,8,HTTPD_RECV_OPT_BLOCKING)==0&&reads==1,"EOF exits blocking read instead of spinning");ts_httpd_receive_end(); + reset();sd.pending_len=3;memcpy(sd.pending_data+sizeof(sd.pending_data)-3,"abc",3);ts_httpd_receive_begin();check(httpd_recv_with_opt(&req,data,3,HTTPD_RECV_OPT_HALT_AFTER_PENDING)==3&&!memcmp(data,"abc",3)&&!reads,"pending data remains exact and needs no socket read");ts_httpd_receive_end(); + reset();sd.pending_len=3;memcpy(sd.pending_data+sizeof(sd.pending_data)-3,"abc",3);ts_httpd_receive_begin();fake_clock=15000;check(httpd_recv_with_opt(&req,data,3,HTTPD_RECV_OPT_HALT_AFTER_PENDING)==HTTPD_SOCK_ERR_TIMEOUT&&sd.pending_len==3&&!reads,"expired request cannot consume pending bytes");ts_httpd_receive_end();sd.pending_len=0; + reset();ts_httpd_receive_begin();result_bytes=16;step=1;check(httpd_recv_with_opt(&req,data,64,HTTPD_RECV_OPT_BLOCKING)==64&&reads==4,"normal fragmented body bytes are unchanged");ts_httpd_receive_end(); + struct httpd_data hd={0};lifecycle_req=&req; + for(lifecycle_mode=0;lifecycle_mode<4;lifecycle_mode++){reset();int r=httpd_sess_process(&hd,&sd);check(lifecycle_mode==0?r==ESP_OK:r!=ESP_OK,"actual SDK session wrapper preserves normal/error paths");fake_clock=UINT32_MAX;check(httpd_recv(&req,data,1)>0,"every session exit clears receive lifetime");} + for(unsigned i=0;i<8;i++){uint64_t values[]={0,1,1024,16U*1024U*1024U,16U*1024U*1024U+1,UINT32_MAX,(uint64_t)UINT32_MAX+1,UINT64_MAX};size_t value=123;bool ok=ts_httpd_decode_content_length(values[i],i!=7,false,&value);bool allowed=i<4||i==7;check(ok==allowed&&(!ok||value==(i==7?0:values[i])),"wire length bound and exact64-bit absence sentinel cannot truncate");} + size_t explicit_length=123;check(!ts_httpd_decode_content_length(UINT64_MAX,true,false,&explicit_length),"explicit maximum wire length is not an absent-header sentinel");check(!ts_httpd_decode_content_length(UINT64_MAX,false,true,&explicit_length),"unsupported chunked body is refused before handler dispatch");check(!ts_httpd_decode_content_length(16,true,true,&explicit_length),"chunked and length combination cannot select an alternate length"); + for(unsigned i=0;i<10;i++){uint64_t values[]={0,125,126,65535,65536,UINT32_MAX,(uint64_t)UINT32_MAX+1,(uint64_t)UINT32_MAX+65,(uint64_t)INT64_MAX+1,UINT64_MAX};uint8_t encoded[8];for(unsigned b=0;b<8;b++)encoded[b]=(uint8_t)(values[i]>>(56-b*8));uint32_t decoded=123;int ret=decode_ws_32(encoded,&decoded);bool allowed=i<6;check(allowed?(ret==ESP_OK&&decoded==values[i]):ret==ESP_ERR_INVALID_SIZE,"actual SDK64-bit WS length cannot wrap into a small32-bit frame");} + pthread_t threads[2];for(uintptr_t i=0;i<2;i++)assert(!pthread_create(&threads[i],NULL,worker,(void*)i));for(unsigned i=0;i<2;i++)pthread_join(threads[i],NULL); + printf("%u checks, %u failures: actual SDK receive/session/length code; deterministic socket/clock +2000 per-task operations, no network/device\n",atomic_load(&checks),atomic_load(&failures));return atomic_load(&failures)?1:0; +} +""" + (t/'test.c').write_text(code) + subprocess.run(['cc','-std=gnu11','-g','-fsanitize='+os.environ.get('RECEIVE_TEST_SANITIZER','address,undefined'),'-fno-sanitize-recover=all',str(t/'test.c'),'-pthread','-o',str(t/'test')],check=True) + subprocess.run([str(t/'test')],check=True,timeout=30) diff --git a/tests/runtime/test_registry_tables.py b/tests/runtime/test_registry_tables.py index 2c8986d2..6e0518ed 100644 --- a/tests/runtime/test_registry_tables.py +++ b/tests/runtime/test_registry_tables.py @@ -42,6 +42,7 @@ def function(text, name): #include #include #include "ts_api.h" +#include "ts_security.h" #include "freertos/semphr.h" #define TS_LOGD(...) ((void)0) #define TS_LOGI(...) ((void)0) @@ -75,7 +76,8 @@ def function(text, name): char name[64]; snprintf(name, sizeof(name), "%s.fixture", expected[i]); ts_api_endpoint_t endpoint = { .name = name, .description = "Registry fixture", .category = i, - .handler = fixture_handler, .requires_auth = true, .permission = "admin" + .handler = fixture_handler, .requires_auth = true, .permission = "admin", + .external_access = TS_API_ACCESS_READ, .allowed_methods = TS_API_METHOD_READ }; assert(ts_api_register(&endpoint) == ESP_OK); cJSON *info = ts_api_get_info(name); @@ -228,7 +230,7 @@ def function(text, name): subprocess.run([ 'cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', - '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', '-I' + str(cjson), + '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', '-Icomponents/ts_security/include', '-I' + str(cjson), '-Icomponents/ts_core/ts_config/include', '-Icomponents/ts_hal/include', '-I' + str(idf / 'components/soc/esp32s3/include'), str(build / 'test.c'), str(cjson / 'cJSON.c'), '-lpthread', '-o', str(build / 'test') diff --git a/tests/runtime/test_request_params.py b/tests/runtime/test_request_params.py new file mode 100644 index 00000000..69bf7763 --- /dev/null +++ b/tests/runtime/test_request_params.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Actual HTTP/login/local-proxy admission; effects, allocation and HTTP I/O synthetic.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,subprocess,tempfile,re +ROOT=Path(__file__).resolve().parents[2] +os.chdir(ROOT) +parser=argparse.ArgumentParser();parser.add_argument('--source-package');args=parser.parse_args() +fixture=ROOT/'tests/runtime/test_sensitive_auth.py' +text=fixture.read_text();ns={'__name__':'params_fixture','__file__':str(fixture)} +exec(compile(text[:text.index("\nidf = Path(")],str(fixture),'exec'),ns) +code=ns['code'];code=code[:code.index('int main(void) {')] +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],text=True) + return (ROOT/path).read_text() +def function(text,name): + m=re.search(r'^(?:static )?[^\n;]+\b'+name+r'\([^;]+?\)\s*\{',text,re.M);assert m,name + return text[m.start():text.index('\n}',m.start())+2]+'\n' +if args.source_package: + code=code.replace(ns['extract']('api_handler'),function(source('components/ts_webui/src/ts_webui_api.c'),'api_handler'),1) + before=ns['extract']('ts_api_automation_proxy_fetch_for_session',(ROOT/'components/ts_api/src/ts_api_automation.c').read_text()) + after=function(source('components/ts_api/src/ts_api_automation.c'),'ts_api_automation_proxy_fetch_for_session') + code=code.replace(before[:before.index(' // 外部 HTTP 请求')],after[:after.index(' // 外部 HTTP 请求')],1) +code=code.replace('#define TS_API_MALLOC(size) malloc(size)',r''' +static bool fail_query_alloc;static int json_budget=-1; +static void *query_alloc(size_t size){return fail_query_alloc?NULL:malloc(size);} +static void *json_alloc(size_t size){if(json_budget==0)return NULL;if(json_budget>0)--json_budget;return malloc(size);} +#define TS_API_MALLOC(size) query_alloc(size) +''',1) +# Stop fault injection at the effect boundary; outgoing response OOM is a separate contract. +code=code.replace(' ++calls;strcpy(received_name,name);',' json_budget=-1;++calls;strcpy(received_name,name);',1) +code+=r''' +#define ESP_ERR_INVALID_STATE 0x103 +static unsigned login_attempts; +static esp_err_t ts_auth_login(const char *user,const char *password,uint32_t *sid,char *token,size_t size){ + (void)user;(void)password;login_attempts++;*sid=1;snprintf(token,size,"fixture-token");return ESP_OK; +} +static bool ts_auth_password_changed(const char *user){(void)user;return true;} +''' +code+=function(source('components/ts_webui/src/ts_webui_api.c'),'login_handler') +code+=r''' +static unsigned checks,failures; +static void expect(bool ok,const char *label){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",label);}} +static void admit(const char *uri,const char *body,size_t length,int expected_status,bool dispatch){ + const char *query=strchr(uri,'?');httpd_req_t native={.query=query?query+1:NULL}; + ts_http_request_t req={.req=&native,.uri=uri,.method=1,.body=body,.body_len=length,.auth="root"}; + int before=calls;status=0;free(response);response=NULL;api_handler(&req,NULL); + expect(status==expected_status,"HTTP status follows admission result");expect(calls==before+dispatch,"invalid request has zero business effects"); +} +int main(void){ + const char *bad[]={"{","[]","null","true","3","\"string\"","{\"x\":1}tail","{\"x\":1}{\"y\":2}", + "{\"path\":\"a\",\"path\":\"b\"}","{\"path\":\"a\",\"PATH\":\"b\"}","{\"p\\u0061th\":\"a\",\"path\":\"b\"}", + "{\"data\":{\"x\":1,\"x\":2}}","{\"path\":\"a\\u0000b\"}","{\"x\\u0000y\":1}","{\"x\":1e999}","{\"x\":\"raw\nline\"}"}; + for(unsigned n=0;nvalueint==2222&&!strcmp(cJSON_GetObjectItem(received_params,"label")->valuestring,"A B%2E"),"once-only decoding, numeric coercion and disjoint body merge preserved"); + char deep[256];unsigned pos=0;for(unsigned i=0;i<33;i++){memcpy(deep+pos,"{\"x\":",5);pos+=5;}deep[pos++]='0';for(unsigned i=0;i<33;i++)deep[pos++]='}';deep[pos]=0; + admit("/api/v1/hosts/info",deep,pos,400,false); + char *long_body=malloc(32768);memset(long_body,'x',32768);memcpy(long_body,"{\"command\":\"",12);memcpy(long_body+32764,"\"}",3); + admit("/api/v1/hosts/info",long_body,32766,200,true);free(long_body); + fail_query_alloc=true;admit("/api/v1/hosts/info?host=fixture",NULL,0,500,false);fail_query_alloc=false; + cJSON_Hooks hooks={.malloc_fn=json_alloc,.free_fn=free}; + for(int budget=0;budget<100;budget++){ + const char *body="{\"command\":\"full fixture\",\"data\":{\"name\":\"value\"},\"n\":0}"; + cJSON *expected=cJSON_Parse(body);int before=calls;httpd_req_t native={0};ts_http_request_t req={.req=&native,.uri="/api/v1/hosts/info",.method=1,.body=body,.body_len=strlen(body),.auth="root"}; + json_budget=budget;cJSON_InitHooks(&hooks);api_handler(&req,NULL);json_budget=-1;cJSON_InitHooks(NULL); + expect(calls==before||(calls==before+1&&cJSON_Compare(expected,received_params,true)),"OOM never dispatches partial JSON parameters");cJSON_Delete(expected); + } + for(unsigned n=0;n>24;}} +typedef int nvs_handle_t; +""" + security = source('components/ts_security/src/ts_security.c') + code += security[security.index('typedef struct {'):security.index('esp_err_t ts_security_init(')] + code += function(security,'ts_security_random') + code += security[security.index('static void ts_security_destroy_sessions_by_client_locked'):] + crypto = source('components/ts_security/src/ts_crypto.c') + code += function(crypto,'ts_crypto_base64_encode')+function(crypto,'ts_crypto_base64_decode') + code += r""" +static unsigned checks,failures; +static void check(bool ok,const char *label){++checks;if(!ok){++failures;fprintf(stderr,"FAIL %s\n",label);}} +static void sdk_log(const char *tag,const char *format,...){char text[512];va_list a;va_start(a,format);vsnprintf(text,sizeof(text),format,a);va_end(a);emit("D (1) %s: %s\n",tag,text);} +#define ESP_LOGD sdk_log +#define ESP_LOGW sdk_log +#define ESP_LOGE sdk_log +#define LOG_FMT(x) x +#define ESP_LOG_BUFFER_HEX_LEVEL(tag,data,n,level) dump_hex(tag,data,n) +static void dump_hex(const char *tag,const void *data,size_t n){char out[256];size_t at=0;for(size_t i=0;iaux&&r->handle;} +""" + for file,name in [('parse','cb_header_value'),('parse','cb_url'),('txrx','httpd_resp_set_hdr'),('ws','httpd_ws_get_response_subprotocol')]:code += function(sdk[file],name) + # Exercise each additional diagnostic statement that references private data. + # These are exact generated SDK statements, not hand-written sanitizers. + private = re.compile(r'\b(?:r->uri|req->uri|at|ws_upgrade_hdr_val|key|version_val|server_raw_text|server_key_encoded|subprotocol|supported_subprotocol|msg|dummy)\b') + statements=[] + for name,text in sdk.items(): + for m in re.finditer(r'ESP_LOG(?:D|W|E|BUFFER_HEX_LEVEL)\s*\([\s\S]*?\);',text): + statement=m.group() + if private.search(re.sub(r'"(?:\\.|[^"\\])*"', '""', statement)) and not ('NEWLIB_NANO_COMPAT' in statement):statements.append((name,statement)) + code += r""" +static void additional_sink_statements(const char *secret){ + struct httpd_req req_value={0},*req=&req_value,*r=req;strcpy(req->uri,secret);req->method=1; + const char *at=secret,*ws_upgrade_hdr_val=secret,*key=secret,*version_val=secret,*server_raw_text=secret,*server_key_encoded=secret,*supported_subprotocol=secret,*msg=secret; + char subprotocol[128];strcpy(subprotocol,secret);const void *dummy=secret;size_t length=strlen(secret);int recv_len=(int)length;const char *status="400 Bad Request"; +""" + # Actual generic-API request diagnostic: the URI can contain credentials + # even when the SDK itself has stopped printing request bytes. + web = source('components/ts_webui/src/ts_webui_api.c') + request_log = re.search(r'TS_LOGD\(TAG, "API request:[\s\S]*?\);', web) + assert request_log + code += 'const char *uri=secret,*api_name=secret;\n#define TS_LOGD sdk_log\n' + code += '\n'.join(statement for _,statement in statements)+'\n'+request_log.group()+'\n}\n' + + code += r""" +static ts_log_entry_t entries[128];static pthread_mutex_t ring=PTHREAD_MUTEX_INITIALIZER; +static void reset_logs(void){memset(entries,0,sizeof(entries));s_log_ctx.buffer.head=s_log_ctx.buffer.count=0;console_size=0;console_output[0]=0;} +static int capture_console(const char *fmt,va_list a){int n=vsnprintf(console_output+console_size,sizeof(console_output)-console_size,fmt,a);assert(n>=0&&(size_t)n +#include +#include "ts_http_url.h" #include #include +#include #include #include #include #include "cJSON.h" typedef int esp_err_t; -enum { ESP_OK=0, ESP_FAIL=-1, ESP_ERR_NOT_FOUND=1, ESP_ERR_NOT_ALLOWED=2, ESP_ERR_INVALID_ARG=4, TS_API_OK=0, TS_API_ERR_NOT_FOUND=3, TS_API_ERR_INTERNAL=7, TS_API_ERR_INVALID_ARG=1, TS_API_ERR_AUTH=11, ESP_ERR_NO_MEM=0x101, TS_API_ERR_NO_MEM=6 }; -typedef enum { TS_PERM_NONE=0, TS_PERM_READ=1, TS_PERM_ADMIN=3, TS_PERM_ROOT=4 } ts_perm_level_t; +enum { ESP_OK=0, ESP_FAIL=-1, ESP_ERR_NOT_FOUND=1, ESP_ERR_NOT_ALLOWED=2, ESP_ERR_INVALID_ARG=4, TS_API_OK=0, TS_API_ERR_NOT_FOUND=2, TS_API_ERR_NO_PERMISSION=3, TS_API_ERR_NOT_SUPPORTED=8, TS_API_ERR_INTERNAL=7, TS_API_ERR_INVALID_ARG=1, TS_API_ERR_AUTH=11, ESP_ERR_NO_MEM=0x101, TS_API_ERR_NO_MEM=6 }; +typedef enum { TS_PERM_NONE=0, TS_PERM_READ=1, TS_PERM_WRITE=2, TS_PERM_ADMIN=3, TS_PERM_ROOT=4 } ts_perm_level_t; typedef struct { int content_len;const char *query; } httpd_req_t; typedef struct { httpd_req_t *req; const char *uri; int method; const char *body; size_t body_len; const char *auth; const char *path; } ts_http_request_t; typedef struct { int code; char *message; cJSON *data; } ts_api_result_t; typedef struct { uint32_t session_id; ts_perm_level_t level; } ts_session_t; static bool session_live = true; static esp_err_t ts_security_validate_session(uint32_t sid, ts_session_t *session) { + if(sid==4 && session_live){if(session)*session=(ts_session_t){sid,TS_PERM_NONE};return ESP_OK;} if (!session_live || !sid || sid > 3) return ESP_ERR_NOT_FOUND; if (session) *session = (ts_session_t){sid,sid==1?TS_PERM_ROOT:sid==2?TS_PERM_ADMIN:TS_PERM_READ}; return ESP_OK; } static void ts_api_result_init(ts_api_result_t *r) {memset(r,0,sizeof(*r));} -static void ts_api_result_error(ts_api_result_t *r,int code,const char *message) {r->code=code;r->message=strdup(message);} +static void ts_api_result_error(ts_api_result_t *r,int code,const char *message) {free(r->message);cJSON_Delete(r->data);r->data=NULL;r->code=code;r->message=strdup(message);} static bool fail_query_copy; +static bool fail_after_business,fail_next_json; +static void *proxy_json_malloc(size_t n){if(fail_next_json){fail_next_json=false;return NULL;}return malloc(n);} + static char *query_strdup(const char *s){return fail_query_copy?NULL:strdup(s);} +static char *query_strndup(const char *s,size_t n){return fail_query_copy?NULL:strndup(s,n);} static int status, calls;static cJSON *received_params;static char received_name[64]; static char *response; #define TS_LOGD(...) ((void)0) @@ -50,12 +68,14 @@ def extract(name, implementation=source): #define TS_API_MALLOC(size) malloc(size) static const char *esp_err_to_name(int e) {(void)e; return "error";} static int64_t esp_timer_get_time(void) {return 0;} +static void ts_httpd_set_body_receive_budget(uint32_t milliseconds){(void)milliseconds;} static size_t httpd_req_get_url_query_len(httpd_req_t *r) {return r->query?strlen(r->query):0;} static esp_err_t httpd_req_get_url_query_str(httpd_req_t *r,char *b,size_t n) {assert(r->query&&strlen(r->query)query);return ESP_OK;} static esp_err_t ts_http_get_header(ts_http_request_t *r,const char *key,char *out,size_t n) { (void)key;if (!r->auth) return ESP_ERR_NOT_FOUND;snprintf(out,n,"Bearer %s",r->auth);return ESP_OK; } static esp_err_t ts_auth_validate_request(const char *header,uint32_t *session,ts_perm_level_t *level) { + if(!session_live)return ESP_ERR_NOT_FOUND; if (!strcmp(header,"Bearer root")) {*session=1;*level=TS_PERM_ROOT;return ESP_OK;} if (!strcmp(header,"Bearer admin")) {*session=2;*level=TS_PERM_ADMIN;return ESP_OK;} if (!strcmp(header,"Bearer read")) {*session=3;*level=TS_PERM_READ;return ESP_OK;} @@ -70,12 +90,15 @@ def extract(name, implementation=source): static esp_err_t ts_http_get_query_param(ts_http_request_t *r,const char *key,char *out,size_t n) { (void)key;if(!r->path)return ESP_ERR_NOT_FOUND;snprintf(out,n,"%s",r->path);return ESP_OK; } -static esp_err_t ts_http_send_file(ts_http_request_t *r,const char *path) {(void)r;(void)path;status=200;return ESP_OK;} +static esp_err_t ts_http_send_private_file(ts_http_request_t *r,const char *path) {(void)r;(void)path;status=200;return ESP_OK;} static bool ts_storage_exists(const char *path) {(void)path;return true;} static bool ts_storage_is_dir(const char *path) {(void)path;return false;} static esp_err_t ts_storage_check_write_path(const char *path,bool children) { (void)children;return strstr(path,"/config/automation/")||!strncmp(path,"/autocfg/",9)?ESP_ERR_NOT_ALLOWED:ESP_OK; } +static esp_err_t ts_storage_external_read_requires_admin(const char *path,bool *root) { + *root=!strncmp(path,"/spiffs",7)||!strncmp(path,"/www",4)||!strncmp(path,"/autocfg",8)||strstr(path,"/config/")||strstr(path,"/pki/");return ESP_OK; +} static cJSON *ts_api_get_info(const char *name) { if (!strcmp(name,"missing")) return NULL; cJSON *info=cJSON_CreateObject(); @@ -90,6 +113,18 @@ def extract(name, implementation=source): cJSON *items=cJSON_AddArrayToObject(result->data,"sources"),*row=cJSON_CreateObject(); cJSON_AddStringToObject(row,"id","weather");cJSON_AddStringToObject(row,"rest_auth","secret");cJSON_AddStringToObject(row,"auth_header","alias-secret");cJSON_AddItemToArray(items,row); } + const char *collection=!strcmp(name,"ssh.hosts.list")?"hosts":!strcmp(name,"ssh.commands.list")?"commands": + !strcmp(name,"automation.rules.list")?"rules":!strcmp(name,"automation.actions.list")?"templates": + !strcmp(name,"automation.variables.list")?"variables":NULL; + if(collection)cJSON_AddArrayToObject(result->data,collection); + if(!strcmp(name,"config.module.show")) { + const cJSON *module=cJSON_GetObjectItem(request,"module"); + cJSON *wifi=cJSON_AddObjectToObject(result->data,cJSON_IsString(module)&&!strcmp(module->valuestring,"all")?"wifi":"config"); + cJSON_AddStringToObject(wifi,"ap.password","AP_SYNTHETIC_SECRET");cJSON_AddStringToObject(wifi,"ap.ssid","Privacy Lab"); + } + if(!strcmp(name,"config.get")) + cJSON_AddStringToObject(result->data,"value","synthetic-config-value"); + if(fail_after_business){result->message=strdup("Synthetic business accepted");fail_next_json=true;} return ESP_OK; } static void ts_api_result_free(ts_api_result_t *r) {free(r->message);cJSON_Delete(r->data);} @@ -99,58 +134,428 @@ def extract(name, implementation=source): (void)r;(void)result;(void)id;(void)start;return ESP_OK; } ''' +code = code.replace('#include \"cJSON.h\"', '#include \"cJSON.h\"\n#include \"' + str(Path('components/ts_api/include/ts_api_policy.h').resolve()) + '\"', 1) metadata = r""" -typedef struct { const char *name, *description; int category; void *handler; bool requires_auth; } ts_api_endpoint_t; +typedef struct { const char *name, *description; int category; void *handler; bool requires_auth; const char *permission; ts_api_external_access_t external_access; uint8_t allowed_methods; void *session_handler; } ts_api_endpoint_t; #define TS_API_CAT_STORAGE 0 #define TS_API_CAT_SECURITY 1 #define TS_API_CAT_SYSTEM 2 +#define TS_API_CAT_FAN 3 +#define TS_API_CAT_HAL 4 +#define TS_API_CAT_DEVICE 5 +#define TS_API_CAT_POWER 6 +#define TS_API_CAT_LED 7 +#define TS_API_CAT_NETWORK 8 +#define TS_API_CAT_CONFIG 9 """ -for filename, array in [('ts_api_storage.c','s_storage_endpoints'),('ts_api_ssh.c','ssh_endpoints'),('ts_api_ui.c','ui_endpoints')]: +for filename, array in [('ts_api_storage.c','s_storage_endpoints'),('ts_api_ssh.c','ssh_endpoints'),('ts_api_sftp.c','sftp_endpoints'),('ts_api_ui.c','ui_endpoints'),('ts_api_cert.c','cert_apis'),('ts_api_fan.c','s_fan_endpoints'),('ts_api_gpio.c','s_gpio_endpoints'),('ts_api_power.c','s_power_endpoints'),('ts_api_device.c','device_endpoints'),('ts_api_led.c','led_endpoints'),('ts_api_log.c','endpoints'),('ts_api_system.c','system_apis'),('ts_api_service.c','s_service_endpoints'),('ts_api_dhcp.c','endpoints'),('ts_api_nat.c','endpoints'),('ts_api_time.c','endpoints'),('ts_api_config.c','config_apis'),('ts_api_auth.c','s_auth_endpoints'),('ts_api_network.c','network_endpoints'),('ts_api_wifi.c','endpoints')]: implementation = Path('components/ts_api/src', filename).read_text() start = implementation.index('static const ts_api_endpoint_t ' + array + '[]') - table = implementation[start:implementation.index('\n};', start) + 3] - for handler in set(re.findall(r'\.handler\s*=\s*(\w+)', table)): + table = implementation[start:start+re.search(r'\n[ \t]*};',implementation[start:]).end()] + if filename in ('ts_api_dhcp.c','ts_api_nat.c','ts_api_time.c','ts_api_wifi.c'): + table=re.sub(r'\bendpoints\b',filename.removesuffix('.c')+'_endpoints',table) + for handler in set(re.findall(r'\.(?:handler|session_handler)\s*=\s*(\w+)', table)): metadata += '#define ' + handler + ' NULL\n' metadata += table + '\n' +# The recovery controls are local entries of the actual OTA registration table. +ota_source=Path('components/ts_api/src/ts_api_ota.c').read_text() +ota_start=ota_source.index(' ts_api_endpoint_t endpoints[] = {') +ota_table=ota_source[ota_start:ota_start+re.search(r'\n[ \t]*};',ota_source[ota_start:]).end()] +ota_table=ota_table.replace('ts_api_endpoint_t endpoints[]','static const ts_api_endpoint_t ota_endpoints[]',1) +for handler in set(re.findall(r'\.(?:handler|session_handler)\s*=\s*(\w+)',ota_table)): + metadata+='#define '+handler+' NULL\n' +metadata+=ota_table+'\n' +# Read the remaining scalar declarations, including explicit fields after five +# dynamic .name assignments. Their actual registration/copy behavior is tested +# independently by test_complete_api_inventory.py. +remaining=[] +for filename in ['ts_api_monitor.c','ts_api_ui.c','ts_api_temp.c','ts_api_hosts.c','ts_api_automation.c','ts_api_lpmu_access.c']: + text=Path('components/ts_api/src',filename).read_text();names=list(re.finditer(r'\.name\s*=\s*"([\w.]+)"',text)) + for i,m in enumerate(names): + block=text[m.end():names[i+1].start() if i+1=TS_API_ACCESS_READ&&remaining_policies[i].mode<=TS_API_ACCESS_ROOT; + cJSON_AddNumberToObject(info,"external_access",remaining_policies[i].mode); + cJSON_AddNumberToObject(info,"allowed_methods",remaining_policies[i].methods); + } cJSON_AddBoolToObject(info,"requires_auth",required);return info; """, 1) +code += '#include \"' + str(Path('components/ts_api/include/ts_api_params.h').resolve()) + '\"\n' code += extract('ts_api_parse_query', Path('components/ts_api/src/ts_api.c').read_text()) +code += extract('classify_external_access', Path('components/ts_api/src/ts_api.c').read_text()) +code += r''' +/* Metadata adapter for the HTTP slice; the real live-registry lookup is covered + * separately by test_api_access.py and the complete registry suites. */ +static esp_err_t ts_api_get_access(const char *name,ts_api_access_t *access){ + cJSON *info=ts_api_get_info(name);if(!info)return ESP_ERR_NOT_FOUND; + const cJSON *auth=cJSON_GetObjectItemCaseSensitive(info,"requires_auth"),*permission=cJSON_GetObjectItemCaseSensitive(info,"permission"); + if(!cJSON_IsBool(auth)){cJSON_Delete(info);return ESP_FAIL;} + const cJSON *mode=cJSON_GetObjectItemCaseSensitive(info,"external_access"),*methods=cJSON_GetObjectItemCaseSensitive(info,"allowed_methods"); + classify_external_access(cJSON_IsNumber(mode)?mode->valueint:TS_API_ACCESS_INTERNAL,cJSON_IsNumber(methods)?methods->valueint:0,access);cJSON_Delete(info);return ESP_OK; +} +''' +code += 'static esp_err_t api_call_dispatch(const char *name,const cJSON *params,uint32_t sid,bool external,ts_api_result_t *result){\n (void)external;\n#ifdef CONFIG_TS_WEBUI_AUTH_REQUIRED\n const cJSON *path=cJSON_GetObjectItem(params,"path");\n if(!strcmp(name,"storage.read")&&cJSON_IsString(path)&&strstr(path->valuestring,"/config/")&&sid!=1&&sid!=2){\n ts_api_result_error(result,TS_API_ERR_NO_PERMISSION,"Root permission required");return ESP_ERR_NOT_ALLOWED;\n }\n#endif\n return ts_api_call(name,params,result);\n}\n' +code += 'typedef esp_err_t (*ts_api_handler_t)(const cJSON *,ts_api_result_t *);\ntypedef esp_err_t (*ts_api_session_handler_t)(const cJSON *,uint32_t,ts_api_result_t *);\n' +code += '/* Registry/business boundary for this protocol fixture. Real snapshot and\n * concurrent replacement behavior are exercised by test_default_deny_policy. */\nstatic char protocol_operation[128];\nstatic esp_err_t protocol_context_handler(const cJSON *p,uint32_t sid,ts_api_result_t *r){return api_call_dispatch(protocol_operation,p,sid,true,r);}\nstatic esp_err_t copy_external_call(const char *name,ts_api_access_t *access,ts_api_handler_t *handler,ts_api_session_handler_t *session_handler){\n esp_err_t ret=ts_api_get_access(name,access);if(ret!=ESP_OK)return ret;\n snprintf(protocol_operation,sizeof(protocol_operation),"%s",name);*handler=NULL;*session_handler=protocol_context_handler;return ESP_OK;\n}\n' +# Reuse this real HTTP/core dispatch fixture for the OTA public/full view seam. +code += '#undef api_ota_partitions\n#undef api_ota_partitions_for_session\n' +code = code.replace('static char protocol_operation[128];', 'static esp_err_t protocol_ota_handler(const cJSON *,uint32_t,ts_api_result_t *);\nstatic char protocol_operation[128];', 1) +ota_header = Path('components/ts_ota/include/ts_ota.h').read_text() +ota_types_start = ota_header.rfind('typedef struct {', 0, ota_header.index('} ts_ota_version_info_t;')) +code += ota_header[ota_types_start:ota_header.index('} ts_ota_partition_info_t;')+len('} ts_ota_partition_info_t;')] +code += r''' +static unsigned ota_next_reads,ota_rollback_reads; +static bool ota_running_error; +static esp_err_t ts_ota_get_running_partition_info(ts_ota_partition_info_t *info) { + if(ota_running_error)return ESP_FAIL;memset(info,0,sizeof(*info));strcpy(info->label,"ota_1");info->address=0x320000;info->size=0x300000;info->is_bootable=true;strcpy(info->version.version,"same-build");strcpy(info->version.project_name,"TianShanOS");return ESP_OK; +} +static esp_err_t ts_ota_get_next_partition_info(ts_ota_partition_info_t *info) { + ++ota_next_reads;ts_ota_get_running_partition_info(info);strcpy(info->label,"ota_0");info->address=0x20000;return ESP_OK; +} +static bool ts_ota_can_rollback(void) {++ota_rollback_reads;return true;} +''' +code += extract('ts_security_check_permission', Path('components/ts_security/src/ts_security.c').read_text()) +code += extract('ts_api_result_ok', Path('components/ts_api/src/ts_api.c').read_text()) +for name in ['ota_partition_json','api_ota_partitions','api_ota_partitions_for_session']: + code += extract(name, ota_source) +code += 'static esp_err_t protocol_ota_handler(const cJSON *p,uint32_t sid,ts_api_result_t *r){++calls;return api_ota_partitions_for_session(p,sid,r);}' +code = code.replace('*session_handler=protocol_context_handler;', '*session_handler=!strcmp(name,"ota.partitions")?protocol_ota_handler:protocol_context_handler;', 1) +code += extract('project_result_fields', Path('components/ts_api/src/ts_api.c').read_text()) +code += extract('private_result_projection', Path('components/ts_api/src/ts_api.c').read_text()) code += extract('ts_api_call_for_session', Path('components/ts_api/src/ts_api.c').read_text()) # Keep the actual local proxy branch; the external network path is forbidden in this offline fixture. proxy_root=Path(os.environ.get('SOURCE_BASELINE_ROOT','.')) proxy = extract('ts_api_automation_proxy_fetch_for_session', (proxy_root/'components/ts_api/src/ts_api_automation.c').read_text()) -code += '#define strdup query_strdup\n' + proxy[:proxy.index(' // 外部 HTTP 请求')] + ' assert(!"external network reached"); return ESP_FAIL;\n}\n#undef strdup\n' +network_start=proxy.index(' esp_http_client_method_t') +code += 'static unsigned outbound;static bool allow_outbound;\n#define strdup query_strdup\n#define strndup query_strndup\n'+proxy[:network_start]+' assert(allow_outbound);++outbound;result->code=TS_API_OK;result->data=cJSON_CreateObject();return ESP_OK;\n}\n#undef strdup\n#undef strndup\n' + code += extract('api_automation_proxy_fetch', Path('components/ts_api/src/ts_api_automation.c').read_text()) -code += extract('check_auth') + extract('api_handler') + extract('file_download_handler') +code += extract('check_auth') +if 'static bool api_request_access(' in source: + code += extract('api_request_access') + extract('api_admit') +code += extract('api_handler') + extract('file_download_handler') code += r''' -static void api(const char *uri,const char *body,const char *auth,int expected_status) { - const char *query=strchr(uri,'?');httpd_req_t native={.query=query?query+1:NULL};ts_http_request_t req={.req=&native,.uri=uri,.method=1,.body=body,.body_len=body?strlen(body):0,.auth=auth}; +static void api_method(const char *uri,const char *body,const char *auth,int expected_status,int method) { + const char *query=strchr(uri,'?');httpd_req_t native={.query=query?query+1:NULL};ts_http_request_t req={.req=&native,.uri=uri,.method=method,.body=body,.body_len=body?strlen(body):0,.auth=auth}; status=0;free(response);response=NULL;api_handler(&req,NULL);if(status!=expected_status)fprintf(stderr,"HTTP %s expected %d received %d: %s\n",uri,expected_status,status,response?response:"");assert(status==expected_status); } +static void api(const char *uri,const char *body,const char *auth,int expected_status){api_method(uri,body,auth,expected_status,TS_HTTP_POST);} static void file(const char *path,const char *auth,int expected_status) { ts_http_request_t req={.path=path,.auth=auth};status=0;file_download_handler(&req,NULL);assert(status==expected_status); } int main(void) { - api("/api/v1/automation/sources/list",NULL,NULL,200);assert(strstr(response,"weather")&&!strstr(response,"secret")); + + /* Actual OTA handler/HTTP admission: a rebooted bearer gets only running identity. */ + const char *ota_auths[]={NULL,"expired","read","root"}; + for(unsigned i=0;i<4;i++)for(unsigned get=0;get<2;get++){ + unsigned next=ota_next_reads,rollback=ota_rollback_reads; + api_method("/api/v1/ota/partitions",get?NULL:"{\"session_id\":1,\"role\":\"root\",\"full\":true}",ota_auths[i],200,get?TS_HTTP_GET:TS_HTTP_POST); + cJSON *reply=cJSON_Parse(response),*data=cJSON_GetObjectItem(reply,"data"),*running=cJSON_GetObjectItem(data,"running");assert(running); + if(i<2){assert(cJSON_GetArraySize(data)==1&&cJSON_GetArraySize(running)==3&&!cJSON_GetObjectItem(running,"address")&&!cJSON_GetObjectItem(data,"next"));assert(ota_next_reads==next&&ota_rollback_reads==rollback);} + else{assert(cJSON_GetObjectItem(running,"address")&&cJSON_GetObjectItem(data,"next")&&cJSON_GetObjectItem(data,"can_rollback"));assert(ota_next_reads==next+1&&ota_rollback_reads==rollback+1);} + cJSON_Delete(reply); + } + ts_api_result_t ota_result={0};ts_api_call_for_session("ota.partitions",NULL,4,&ota_result);assert(ota_result.code==0&&cJSON_GetArraySize(ota_result.data)==1);ts_api_result_free(&ota_result); + ts_api_result_init(&ota_result);api_ota_partitions(NULL,&ota_result);assert(cJSON_GetObjectItem(ota_result.data,"next"));ts_api_result_free(&ota_result); + session_live=false;api_method("/api/v1/ota/partitions",NULL,"root",200,TS_HTTP_GET); + unsigned before_unauthorized=calls;api_method("/api/v1/ota/progress",NULL,"root",401,TS_HTTP_GET);api("/api/v1/system/reboot","{}","root",401);assert(calls==before_unauthorized);session_live=true; + ota_running_error=true;api_method("/api/v1/ota/partitions",NULL,NULL,200,TS_HTTP_GET);assert(strstr(response,"Partition information unavailable"));ota_running_error=false; + puts("PASS actual OTA public/full handler and HTTP/core dispatch: no/expired/NONE vs READ/Root, GET/POST, forged identity, protected401 and running-read failure"); + /* Missing declaration has zero verbs even when the request has no valid + * JSON body. Role/permission strings cannot make this an external API. */ + api("/api/v1/fixture/internal","not-json",NULL,405); + api("/api/v1/fixture/internal","not-json","root",405); + const char *privacy_auth[]={NULL,"read","admin","root"}; + const uint32_t privacy_sid[]={0,3,2,1}; + for(unsigned i=0;i<4;++i) { + api("/api/v1/config/module/show","{\"module\":\"wifi\"}",privacy_auth[i],i?200:401); + if(i)assert(strstr(response,"Privacy Lab")&&!!strstr(response,"AP_SYNTHETIC_SECRET")==(i>=2)); + api("/api/v1/config/module/show","{\"module\":\"all\"}",privacy_auth[i],i?200:401); + if(i)assert(!!strstr(response,"AP_SYNTHETIC_SECRET")==(i>=2));else assert(!response||!strstr(response,"AP_SYNTHETIC_SECRET")); + int submitted=calls; + api("/api/v1/config/get","{\"key\":\"custom.credential\",\"session_id\":1}",privacy_auth[i],i>=2?200:401); + assert(calls==submitted+(i>=2)); + api("/api/v1/config/get","{\"key\":\"system.language\"}",privacy_auth[i],200); + const char *names[]={"config.module.show","config.get"}; + const char *urls[]={"http://localhost/api/v1/config/module/show?module=wifi","http://localhost/api/v1/config/get?key=custom.credential"}; + const char *bodies[]={"{\"module\":\"wifi\"}","{\"key\":\"custom.credential\"}"}; + for(unsigned n=0;n<2;++n) { + cJSON *params=cJSON_Parse(bodies[n]),*proxy_params=cJSON_CreateObject(); + cJSON_AddStringToObject(proxy_params,"url",urls[n]);cJSON_AddNumberToObject(proxy_params,"session_id",1); + ts_api_result_t direct={0},proxy_result={0}; + ts_api_call_for_session(names[n],params,privacy_sid[i],&direct); + ts_api_automation_proxy_fetch_for_session(proxy_params,privacy_sid[i],&proxy_result); + assert(direct.code==proxy_result.code); + if(direct.code==TS_API_OK) { + cJSON *body=cJSON_GetObjectItemCaseSensitive(proxy_result.data,"body"); + assert(cJSON_Compare(direct.data,cJSON_GetObjectItemCaseSensitive(body,"data"),true)); + } + ts_api_result_free(&direct);ts_api_result_free(&proxy_result);cJSON_Delete(params);cJSON_Delete(proxy_params); + } + } + puts("PASS configuration privacy across actual HTTP/core/local proxy: language bootstrap, authenticated admin raw reads, both module shapes and forged JSON"); + const char *hardware_ops[]={"fan.status","fan.config","gpio.list","gpio.info","fan.set","fan.mode","fan.enable","fan.limits","fan.curve","fan.save","gpio.set","gpio.toggle"}; + for(unsigned n=0;n=4,allowed=n==0||(identity>0&&(!control||identity>=2)); + int expected=!allowed?(identity?403:401):control&&get?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",hardware_ops[n]);int previous=calls; + api_method(uri,"{\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",hardware_ops[n]);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS twelve actual fan/GPIO descriptor policies through HTTP and local proxy: minimal public/read metadata, Admin controls, GET no side effects"); + const char *power_public[]={"device.status","device.fan.status","device.power.status","device.usb.status","power.status","power.voltage","power.chip","power.protection.status"}; + const char *power_reads[]={"power.stats","power.protection.config"}; + const char *power_controls[]={"device.power","device.reset","device.fan.set","device.usb.set","device.ping","power.stats.reset","power.threshold.set","power.interval.set","power.debug","power.protection.set","power.monitor.start","power.monitor.stop"}; + for(unsigned n=0;n<22;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + const char *name=n<8?power_public[n]:n<10?power_reads[n-8]:power_controls[n-10];bool control=n>=10,allowed=n<8||(identity>0&&(!control||identity>=2)); + int expected=!allowed?(identity?403:401):control&&get?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",name);int previous=calls;api_method(uri,"{\"session_id\":1,\"role\":\"root\"}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result);assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS twenty-two power/device descriptor policies through real HTTP/local proxy; Admin controls and active ping, GET no effects, public home telemetry retained"); + const char *led_ops[]={"led.list","led.brightness","led.clear","led.set","led.fill","led.effect.list","led.effect.start","led.effect.stop","led.color.parse","led.color.hsv","led.filter.list","led.filter.start","led.filter.stop","led.image","led.qrcode","led.text","led.text.stop","led.save","led.boot.config","led.color_correction.get","led.color_correction.set","led.color_correction.reset","led.color_correction.export","led.color_correction.import"}; + const char *led_reads[]={"led.boot.config","led.color.hsv","led.color.parse","led.color_correction.get","led.effect.list","led.filter.list"}; + for(unsigned n=0;n0&&(!control||identity>=2));int expected=!allowed?(identity?403:401):control&&get?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",name);int previous=calls;api_method(uri,"{\"session_id\":1,\"role\":\"root\",\"brightness\":0}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s?brightness=0",name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST");ts_api_result_t result={0};previous=calls; + ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result);assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS all twenty-four LED descriptor policies through HTTP/local proxy: Admin controls/calibration file export, GET no effects, public device summary"); + const char *log_ops[]={"log.list","log.stats","log.clear","log.setLevel","log.capture"}; + for(unsigned n=0;n<5;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + bool allowed=identity>=2;int expected=!allowed?(identity?403:401):n>=2&&get?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",log_ops[n]);int previous=calls;api_method(uri,"{\"session_id\":1,\"role\":\"root\"}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",log_ops[n]);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST");ts_api_result_t result={0};previous=calls; + ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result);assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS all five log descriptor policies through HTTP/local proxy: Admin reads/control, GET control refuses before log access"); + const struct {const char *name;unsigned required,methods;} management_ops[]={{"system.info",0,3},{"system.memory",0,3},{"system.memory_detail",3,3},{"system.cpu",0,3},{"system.tasks",3,3},{"system.reboot",3,14},{"system.log.level",3,14},{"system.apis",1,3},{"service.list",0,3},{"service.status",0,3},{"service.start",3,14},{"service.stop",3,14},{"service.restart",3,14},{"dhcp.status",1,3},{"dhcp.clients",1,3},{"dhcp.start",3,14},{"dhcp.stop",3,14},{"nat.status",1,3},{"nat.enable",3,14},{"nat.disable",3,14},{"nat.save",3,14}}; + for(unsigned n=0;n<21;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + unsigned level=identity==0?0:identity==1?1:identity==2?3:4;bool allowed=level>=management_ops[n].required; + int expected=!allowed?(identity?403:401):get&&!(management_ops[n].methods&TS_API_METHOD_GET)?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",management_ops[n].name);int previous=calls; + api_method(uri,"{\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",management_ops[n].name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS twenty-one system/service/DHCP/NAT real descriptor policies through HTTP/local proxy: minimal telemetry public, diagnostics and writes Admin, GET control has no effects"); + const struct {const char *name;unsigned required,methods;} auth_outer_ops[]={{"auth.login",0,2},{"auth.logout",0,2},{"auth.status",0,2},{"auth.change_password",0,2},{"auth.admin.set_password",4,2},{"auth.root.set_password",4,2},{"auth.admin.reset_password",4,2}}; + for(unsigned n=0;n<7;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + unsigned level=identity==0?0:identity==1?1:identity==2?3:4;bool allowed=level>=auth_outer_ops[n].required; + int expected=!allowed?(identity?403:401):get&&!(auth_outer_ops[n].methods&TS_API_METHOD_GET)?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",auth_outer_ops[n].name);int previous=calls; + api_method(uri,"{\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",auth_outer_ops[n].name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS seven auth descriptor outer policies through HTTP/local proxy: password login/public entry and body-token workflows; account administration Root; all POST only, GET control has no effects"); + const struct {const char *name;unsigned required,methods;} network_config_ops[]={{"config.get",0,3},{"config.set",3,14},{"config.delete",3,14},{"config.list",3,3},{"config.save",3,14},{"config.module.list",1,3},{"config.module.show",1,3},{"config.module.set",3,14},{"config.module.save",3,14},{"config.module.reset",3,14},{"network.status",0,3},{"network.wifi.mode",3,14},{"network.wifi.scan",3,14},{"network.wifi.connect",3,14},{"network.wifi.disconnect",3,14},{"network.wifi.ap.config",3,14},{"network.wifi.ap.stations",1,3},{"network.eth.status",0,3},{"network.hostname",3,14},{"wifi.status",0,3},{"wifi.scan",3,14},{"wifi.connect",3,14},{"wifi.disconnect",3,14},{"dhcp.status",1,3},{"dhcp.clients",1,3},{"dhcp.start",3,14},{"dhcp.stop",3,14},{"nat.status",1,3},{"nat.enable",3,14},{"nat.disable",3,14},{"nat.save",3,14}}; + for(unsigned n=0;n<31;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + unsigned level=identity==0?0:identity==1?1:identity==2?3:4;bool allowed=level>=network_config_ops[n].required; + int expected=!allowed?(identity?403:401):get&&!(network_config_ops[n].methods&TS_API_METHOD_GET)?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",network_config_ops[n].name);int previous=calls; + api_method(uri,"{\"key\":\"system.language\",\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s?key=system.language",network_config_ops[n].name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS thirty-one network/config real descriptor policies through HTTP/local proxy: minimal status/language public, original config/network writes Admin, GET control has no effects"); + const struct {const char *name;unsigned required,methods;} time_ops[]={{"time.info",0,3},{"time.sync",3,14},{"time.set_ntp",3,14},{"time.set_timezone",3,14},{"time.force_sync",3,14}}; + for(unsigned n=0;n<5;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + unsigned level=identity==0?0:identity==1?1:identity==2?3:4;bool allowed=level>=time_ops[n].required; + int expected=!allowed?(identity?403:401):get&&!(time_ops[n].methods&TS_API_METHOD_GET)?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",time_ops[n].name);int previous=calls; + api_method(uri,"{\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",time_ops[n].name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS five time real descriptor policies through HTTP/local proxy: time info public, original writes Admin, GET control has no effects"); + const struct {const char *name;unsigned required,methods;} ssh_ops[]={{"ssh.exec_status",4,3},{"ssh.services.start",3,14},{"ssh.exec",4,14},{"ssh.exec_stream",4,14},{"ssh.cancel",4,14},{"ssh.test",3,14},{"ssh.copyid",3,14},{"ssh.revoke",3,14},{"ssh.keygen",3,14},{"ssh.hosts.list",1,3},{"ssh.hosts.add",3,14},{"ssh.hosts.update",3,14},{"ssh.hosts.remove",3,14},{"ssh.hosts.get",1,3},{"ssh.hosts.export",3,14},{"ssh.hosts.import",3,14},{"ssh.commands.list",1,3},{"ssh.commands.add",4,14},{"ssh.commands.update",4,14},{"ssh.commands.remove",4,14},{"ssh.commands.get",1,3},{"ssh.commands.export",4,14},{"ssh.commands.import",4,14},{"sftp.ls",3,14},{"sftp.get",3,14},{"sftp.put",3,14},{"sftp.rm",3,14},{"sftp.mkdir",3,14},{"sftp.stat",3,14}}; + for(unsigned n=0;n<29;n++)for(unsigned identity=0;identity<4;identity++)for(unsigned get=0;get<2;get++){ + unsigned level=identity==0?0:identity==1?1:identity==2?3:4;bool allowed=level>=ssh_ops[n].required; + int expected=!allowed?(identity?403:401):get&&!(ssh_ops[n].methods&TS_API_METHOD_GET)?405:200;bool dispatch=expected==200; + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",ssh_ops[n].name);int previous=calls; + api_method(uri,"{\"role\":\"root\",\"session_id\":1}",privacy_auth[identity],expected,get?TS_HTTP_GET:TS_HTTP_POST);assert(calls==previous+dispatch); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",ssh_ops[n].name);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method",get?"GET":"POST"); + ts_api_result_t result={0};previous=calls;ts_api_automation_proxy_fetch_for_session(input,privacy_sid[identity],&result); + assert((result.code==TS_API_OK)==dispatch&&calls==previous+dispatch);ts_api_result_free(&result);cJSON_Delete(input); + } + puts("PASS twenty-nine SSH/SFTP real descriptor policies through HTTP/local proxy: read metadata requires login, original security/SFTP management Admin; command execution Root, GET control has no effects"); + int denied_before=calls; + api("/api/v1/cert/install?bad=%Q2","{",NULL,401);assert(calls==denied_before); + api("/api/v1/cert/install?bad=%Q2","{","read",403);assert(calls==denied_before); + api("/api/v1/cert/install?bad=%Q2","{","root",400);assert(calls==denied_before); + const char *cert_writes[]={"cert.generate_keypair","cert.generate_csr","cert.install","cert.install_ca","cert.delete"}; + for(unsigned n=0;n<5;++n)for(unsigned i=0;i<4;++i) { + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",cert_writes[n]); + int previous=calls;bool allowed=i>=2; + api(uri,"{\"session_id\":1,\"role\":\"root\",\"permission\":\"cert.manage\"}",privacy_auth[i],allowed?200:(i?403:401)); + assert(calls==previous+allowed); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s?session_id=1",cert_writes[n]); + cJSON *p=cJSON_CreateObject();cJSON_AddStringToObject(p,"url",url);cJSON_AddStringToObject(p,"method","POST"); + ts_api_result_t result={0};previous=calls; + ts_api_automation_proxy_fetch_for_session(p,privacy_sid[i],&result); + assert((result.code==TS_API_OK)==allowed&&calls==previous+allowed); + ts_api_result_free(&result);cJSON_Delete(p); + } + for(unsigned n=0;n<5;n++){ + char uri[96],url[160];snprintf(uri,sizeof(uri),"/api/v1/%s",cert_writes[n]);int previous=calls; + api_method(uri,"{}","root",405,TS_HTTP_GET);assert(calls==previous); + snprintf(url,sizeof(url),"http://localhost/api/v1/%s",cert_writes[n]);cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddStringToObject(input,"method","GET"); + ts_api_result_t result={0};ts_api_automation_proxy_fetch_for_session(input,1,&result);assert(result.code==TS_API_ERR_NOT_SUPPORTED&&calls==previous);ts_api_result_free(&result);cJSON_Delete(input); + } + api("/api/v1/cert/status",NULL,NULL,200);api("/api/v1/cert/get_certificate",NULL,NULL,200); + puts("PASS PKI management metadata on actual HTTP/local proxy: anonymous/READ/WRITE denied before dispatch; original Admin/Root management and public status/PEM retained"); + int prior_source_calls=calls;api("/api/v1/automation/sources/list",NULL,NULL,401);assert(calls==prior_source_calls); api("/api/v1/automation/sources/list",NULL,"admin",200);assert(strstr(response,"weather")&&!strstr(response,"secret")); api("/api/v1/automation/sources/list",NULL,"root",200);assert(strstr(response,"secret")&&strstr(response,"alias-secret")); int before=calls; api("/api/v1/automation/sources/export","{}",NULL,401);assert(calls==before); - api("/api/v1/automation/sources/export","{}","admin",401);assert(calls==before); + api("/api/v1/automation/sources/export","{}","admin",403);assert(calls==before); api("/api/v1/automation/sources/export","{}","root",200);assert(calls==before+1); - api("/api/v1/automation/actions/add","{}","admin",401); + api("/api/v1/automation/actions/add","{}","admin",403); const char *home_operations[]={"services/list","services/status","services/stop","rules/trigger","actions/execute"}; for(unsigned i=0;ivaluestring,"192.0.2.8")); assert(cJSON_GetObjectItem(received_params,"port")->valueint==2222&&cJSON_IsNumber(cJSON_GetObjectItem(received_params,"port"))); assert(!strcmp(cJSON_GetObjectItem(received_params,"label")->valuestring,"A B%2E")); - assert(!strcmp(cJSON_GetObjectItem(received_params,"empty")->valuestring,"")&&!strcmp(cJSON_GetObjectItem(received_params,"bad")->valuestring,"%Q2")); - assert(!strcmp(cJSON_GetObjectItem(received_params,"h%6fst")->valuestring,"key")&&!cJSON_GetObjectItem(received_params,"bare")); - assert(!strcmp(cJSON_GetObjectItem(received_params,"dup")->valuestring,"first")&&cJSON_GetObjectItem(received_params,"extra")->valueint==7); - /* Original cJSON append order retains duplicate query/body items, unchanged. */ - unsigned hosts=0,dups=0;for(cJSON *i=received_params->child;i;i=i->next){hosts+=!strcmp(i->string,"host");dups+=!strcmp(i->string,"dup");}assert(hosts==2&&dups==2); + assert(!strcmp(cJSON_GetObjectItem(received_params,"empty")->valuestring,"")&&cJSON_GetObjectItem(received_params,"extra")->valueint==7); + before=calls;api("/api/v1/hosts/info?bad=%Q2",NULL,"read",400);assert(calls==before); + api("/api/v1/hosts/info?dup=first&dup=second",NULL,"read",400);assert(calls==before); + api("/api/v1/hosts/info?host=query","{\"HOST\":\"body\"}","read",400);assert(calls==before); + /* The trusted parser itself retains its historical grammar. */ + char legacy_query[]="bad=%Q2&h%6fst=key&bare&dup=first&dup=second";cJSON *legacy=cJSON_CreateObject();ts_api_parse_query(legacy,legacy_query); + assert(!strcmp(cJSON_GetObjectItem(legacy,"bad")->valuestring,"%Q2")&&!strcmp(cJSON_GetObjectItem(legacy,"h%6fst")->valuestring,"key")&&!cJSON_GetObjectItem(legacy,"bare")); + unsigned dups=0;for(cJSON *i=legacy->child;i;i=i->next)dups+=!strcmp(i->string,"dup");assert(dups==2);cJSON_Delete(legacy); const char *query_targets[]={"system.memory","hosts.info","ssh.exec","automation.sources.export","storage.read"}; for(unsigned i=0;i<5;++i)for(uint32_t sid=0;sid<=3;++sid){ const char *query="host=192.0.2.8&port=2222&label=A+B%252E&session_id=1&path=%2Fsdcard%2Fconfig%2Fautomation%2Fstate.json"; cJSON *expected=cJSON_Parse("{\"host\":\"192.0.2.8\",\"port\":2222,\"label\":\"A B%2E\",\"session_id\":1,\"path\":\"/sdcard/config/automation/state.json\"}"); ts_api_result_t direct={0},proxy_result={0};ts_api_call_for_session(query_targets[i],expected,sid,&direct); char url[320];snprintf(url,sizeof(url),"http://localhost/api/v1/%s?%s",query_targets[i],query); - cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddNumberToObject(input,"session_id",1); + cJSON *input=cJSON_CreateObject();cJSON_AddStringToObject(input,"url",url);cJSON_AddNumberToObject(input,"session_id",1);cJSON_AddStringToObject(input,"method","POST"); int previous=calls;ts_api_automation_proxy_fetch_for_session(input,sid,&proxy_result); assert(proxy_result.code==direct.code); if(direct.code==TS_API_OK){ @@ -228,13 +678,38 @@ def extract(name, implementation=source): cJSON *allocation_input=cJSON_Parse("{\"url\":\"http://localhost/api/v1/hosts/info?host=192.0.2.8\"}");ts_api_result_t allocation_result={0}; assert(ts_api_automation_proxy_fetch_for_session(allocation_input,1,&allocation_result)==ESP_ERR_NO_MEM&&allocation_result.code==TS_API_ERR_NO_MEM&&calls==before); ts_api_result_free(&allocation_result);cJSON_Delete(allocation_input);fail_query_copy=false; + const char *foreign_targets[]={"http://localhost.attacker/api/v1/system/info","http://127.0.0.10/api/v1/system/info","https://example.invalid/path?next=http://localhost/api/v1/system/info"}; + for(unsigned i=0;ivalueint==TS_API_ERR_AUTH);cJSON_Delete(refused); - api("/api/v1/automation/proxy/fetch","{\"url\":\"http://localhost/api/v1/hosts/info?host=192.0.2.8&port=2222\"}",NULL,200); + before=calls;api("/api/v1/automation/proxy/fetch?session_id=1","{\"url\":\"http://localhost/api/v1/ssh/exec?session_id=1\",\"method\":\"POST\"}",NULL,401);assert(calls==before); + + api("/api/v1/automation/proxy/fetch","{\"url\":\"http://localhost/api/v1/hosts/info?host=192.0.2.8&port=2222\"}","read",200); assert(!strcmp(received_name,"hosts.info")&&!strcmp(cJSON_GetObjectItem(received_params,"host")->valuestring,"192.0.2.8")); session_live=false; + before=calls;api("/api/v1/cert/install","{\"cert_pem\":\"synthetic\"}","root",401);assert(calls==before); + api("/api/v1/config/module/show","{\"module\":\"wifi\"}","root",401);assert(calls==before); + api("/api/v1/config/get","{\"key\":\"custom.credential\"}","root",401); api("/api/v1/system/memory",NULL,"root",200);api("/api/v1/ssh/exec","{}","root",401); - api("/api/v1/automation/sources/list",NULL,"root",200);assert(!strstr(response,"secret"));session_live=true; + before=calls;api("/api/v1/automation/sources/list",NULL,"root",401);assert(calls==before);session_live=true; + + unsigned outbound_before=outbound;allow_outbound=true; + api("/api/v1/automation/proxy/fetch","{\"url\":\"https://fixture.invalid/data?secret=synthetic\",\"role\":\"root\",\"session_id\":1}",NULL,401);assert(outbound==outbound_before); + for(unsigned who=1;who<3;who++){ + api("/api/v1/automation/proxy/fetch","{\"url\":\"https://fixture.invalid/data\",\"role\":\"root\",\"session_id\":1}",privacy_auth[who],403);assert(outbound==outbound_before); + } + api("/api/v1/automation/proxy/fetch","{\"url\":\"https://fixture.invalid/data\"}","root",200);assert(outbound==outbound_before+1);allow_outbound=false; + puts("PASS external proxy Root gate before synthetic network sink; anonymous denied outside body, forged JSON cannot elevate; local destination policy retained"); cJSON_Delete(received_params);free(response);puts("PASS shared HTTP/local proxy roles, public reads, protected paths, redaction, forged JSON and revoked sessions"); } ''' @@ -244,13 +719,14 @@ def extract(name, implementation=source): with tempfile.TemporaryDirectory(prefix='ts-sensitive-auth-') as directory: build = Path(directory) (build / 'test.c').write_text(code) - subprocess.run(['cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-I' + str(cjson), - str(build / 'test.c'), str(cjson / 'cJSON.c'), '-o', str(build / 'test')], check=True) + subprocess.run(['cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-I' + str(cjson), *['-I'+str(p) for p in url_native_includes], + str(build / 'test.c'), str(cjson / 'cJSON.c'), *map(str,url_native_sources), '-o', str(build / 'test')], check=True) subprocess.run([str(build / 'test')], check=True) noauth = code.replace('#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1', '') start = noauth.index('int main(void) {') noauth = noauth[:start] + r""" int main(void) { + api("/api/v1/fixture/internal","not-json",NULL,405); api("/api/v1/automation/sources/export","{}",NULL,200); api("/api/v1/ui/widgets/set","{}",NULL,200); api("/api/v1/ui/widgets/get",NULL,NULL,200); @@ -260,221 +736,10 @@ def extract(name, implementation=source): } """ (build / 'noauth.c').write_text(noauth) - subprocess.run(['cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-I' + str(cjson), - str(build / 'noauth.c'), str(cjson / 'cJSON.c'), '-o', str(build / 'noauth')], check=True) + subprocess.run(['cc', '-std=gnu11', '-g', '-Wno-deprecated-declarations', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-I' + str(cjson), *['-I'+str(p) for p in url_native_includes], + str(build / 'noauth.c'), str(cjson / 'cJSON.c'), *map(str,url_native_sources), '-o', str(build / 'noauth')], check=True) subprocess.run([str(build / 'noauth')], check=True) -# Run the production credential/session implementation with a persistent NVS -# fixture and a controllable boot clock. Crypto uses the SDK's actual routines. -auth_code = r''' -#include -#include -#include -#include -#include -#include -#include "ts_security.h" -#include "ts_auth_layout.h" -#include "ts_crypto.h" -#include "mbedtls/base64.h" -#include "mbedtls/sha256.h" -#include "mbedtls/sha512.h" -#define CONFIG_TS_SECURITY_TOKEN_EXPIRE_SEC 86400 -#define TS_CONFIG_KEYS_PARTITION "keys" -#define NVS_READWRITE 1 -#define TS_MALLOC_PSRAM malloc -typedef int nvs_handle_t; -static ts_auth_user_credential_t stored[2]; -static bool present[2]; -static uint8_t version; -static int writes; -static int open_handles, fail_write_user=-1; -static int64_t clock_us; -static uint32_t random_state=12345; -static char logs[8192]; -static void capture_log(const char *tag,const char *format,...) { - (void)tag; - size_t used=strlen(logs); - va_list ap;va_start(ap,format);vsnprintf(logs+used,sizeof(logs)-used,format,ap);va_end(ap); -} -#define TS_LOGI capture_log -#define TS_LOGW capture_log -#define TS_LOGE capture_log -static const char *esp_err_to_name(int e) {(void)e;return "fixture error";} -static int64_t esp_timer_get_time(void) {return clock_us;} -static void esp_fill_random(void *p,size_t n) { - for(size_t i=0;i>24;} -} -static int user_index(const char *key) { - if(!strcmp(key,"cred_admin"))return 0; - assert(!strcmp(key,"cred_root"));return 1; -} -static int nvs_open(const char *name,int mode,nvs_handle_t *handle) {(void)name;(void)mode;*handle=++open_handles;return ESP_OK;} -static int nvs_open_from_partition(const char *part,const char *name,int mode,nvs_handle_t *handle) { - (void)part;return nvs_open(name,mode,handle); -} -static void nvs_close(nvs_handle_t handle) {(void)handle;assert(open_handles>0);--open_handles;} -static int nvs_get_blob(nvs_handle_t handle,const char *key,void *out,size_t *len) { - (void)handle;int i=user_index(key);if(!present[i])return ESP_ERR_NOT_FOUND; - assert(*len>=sizeof(stored[i]));memcpy(out,&stored[i],sizeof(stored[i]));*len=sizeof(stored[i]);return ESP_OK; -} -static int nvs_set_blob(nvs_handle_t handle,const char *key,const void *data,size_t len) { - (void)handle;int i=user_index(key);assert(len==sizeof(stored[i])); - if(i==fail_write_user){fail_write_user=-1;return ESP_FAIL;} - memcpy(&stored[i],data,len);present[i]=true;++writes;return ESP_OK; -} -static int nvs_commit(nvs_handle_t handle) {(void)handle;return ESP_OK;} -static int nvs_get_u8(nvs_handle_t handle,const char *key,uint8_t *out) {(void)handle;(void)key;*out=version;return ESP_OK;} -static int nvs_set_u8(nvs_handle_t handle,const char *key,uint8_t value) {(void)handle;(void)key;version=value;return ESP_OK;} -static int nvs_erase_key(nvs_handle_t handle,const char *key) {(void)handle;(void)key;return ESP_OK;} -static int ts_ssh_hosts_config_init(void) {return ESP_OK;} -static int ts_ssh_commands_config_init(void) {return ESP_OK;} -static int ts_ssh_service_init(void) {return ESP_OK;} -static int ts_ssh_log_watch_init(void) {return ESP_OK;} -''' -auth_code = '#include \n' + auth_code -crypto_source = Path('components/ts_security/src/ts_crypto.c').read_text() -for name in ['ts_crypto_hash', 'ts_crypto_base64_encode', 'ts_crypto_base64_decode']: - start = crypto_source.index('esp_err_t ' + name + '(') - auth_code += crypto_source[start:crypto_source.index('\n}', start) + 2] + '\n' -for filename in ['ts_security.c', 'ts_auth.c']: - implementation = Path('components/ts_security/src', filename).read_text() - auth_code += '\n#undef TAG\n' + re.sub(r'^#include[^\n]*\n', '', implementation, flags=re.M) -auth_code += r''' -static void boot(void) { - s_auth_initialized=false;s_initialized=false;clock_us=0;open_handles=0; - assert(ts_security_init()==ESP_OK);assert(ts_auth_init()==ESP_OK); -} -static void fixture(void) { - boot(); - assert(ts_auth_set_admin_password("admin-fixture")==ESP_OK); - assert(ts_auth_set_root_password("root-fixture")==ESP_OK); - logs[0]=0; -} -static uint32_t login(const char *user,const char *password,char *token) { - uint32_t sid=0;assert(ts_auth_login(user,password,&sid,token,128)==ESP_OK);return sid; -} -static void request(const char *token,ts_perm_level_t expected) { - char header[160];snprintf(header,sizeof(header),"Bearer %s",token); - uint32_t sid=0;ts_perm_level_t level=TS_PERM_NONE; - assert(ts_auth_validate_request(header,&sid,&level)==ESP_OK);assert(level==expected); - assert(ts_security_check_permission(sid,TS_PERM_READ)); - assert(ts_security_check_permission(sid,TS_PERM_ROOT)==(expected==TS_PERM_ROOT)); -} -static void lock(const char *user) { - for(int i=0;i<5;i++)assert(ts_auth_verify_password(user,"wrong-password",NULL)==ESP_ERR_INVALID_ARG); -} -int main(int argc,char **argv) { - assert(argc==2);fixture();const char *mode=argv[1]; - if(!strcmp(mode,"normal")) { - char token[128];uint32_t sid=login("root","root-fixture",token);request(token,TS_PERM_ROOT); - assert(ts_auth_logout(sid)==ESP_OK);assert(ts_security_validate_token(token,&sid)!=ESP_OK); - sid=login("admin","admin-fixture",token);request(token,TS_PERM_ADMIN); - assert(ts_auth_logout(sid)==ESP_OK); - login("root","root-fixture",token);request(token,TS_PERM_ROOT); - assert(ts_auth_password_changed("admin")&&ts_auth_password_changed("root")); - } else if(!strcmp(mode,"sid_only")||!strcmp(mode,"altered_tail")) { - char token[128],forged[128];uint32_t sid=login("root","root-fixture",token),result=0; - uint8_t raw[16];size_t n=sizeof(raw);assert(ts_crypto_base64_decode(token,strlen(token),raw,&n)==ESP_OK); - if(!strcmp(mode,"sid_only")) { - size_t encoded=sizeof(forged);assert(ts_crypto_base64_encode(raw,4,forged,&encoded)==ESP_OK); - assert(ts_security_validate_token(forged,&result)!=ESP_OK); - } else for(size_t byte=0;byte queue admission -> executor entry -> SSH -> durable run registry. Only transport, driver storage and RTOS scheduling are simulated. """ +from host_paths import build_dir from pathlib import Path import os,re,subprocess root=Path.cwd();sdk=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf'))/'components/json/cJSON' @@ -320,7 +321,7 @@ def typedef(name): puts("PASS service API/executor: queued plan and persistence before launch, stale start cancellation, responsive cached reads, admitted-I/O cleanup, deleted-definition controls, frozen target, expiry, queue rejection and unknown remote state"); } ''' -build=Path(os.environ.get('SERVICE_TEST_BUILD','/tmp/tianshan-service-runs-tests'));build.mkdir(exist_ok=True);(build/'service_control.c').write_text(code) +build=Path(os.environ['SERVICE_TEST_BUILD']) if os.environ.get('SERVICE_TEST_BUILD') else build_dir('service-runs');build.mkdir(exist_ok=True);(build/'service_control.c').write_text(code) args=['cc','-std=c11','-D_DEFAULT_SOURCE','-g','-fsanitize=address,undefined','-Wno-deprecated-declarations'] for path in ['tests/runtime/state_stubs','tests/runtime/ssh_stubs','tests/runtime/stubs','tests/runtime/storage_stubs','tests/certificate/stubs','components/ts_security/include','components/ts_automation/include','components/ts_automation/src','components/ts_api/include',str(sdk)]:args+=['-I'+path] args += [str(build/'service_control.c'),'components/ts_security/src/ts_ssh_service.c','components/ts_security/src/ts_ssh_run_store.c','components/ts_security/src/ts_ssh_log_watch.c','components/ts_security/src/ts_ssh_probe.c','components/ts_security/src/ts_ssh_pattern.c',str(sdk/'cJSON.c'),'-lpthread','-lm','-o',str(build/'service_control')] diff --git a/tests/runtime/test_source_sampling.py b/tests/runtime/test_source_sampling.py index 922534a8..371fcab7 100644 --- a/tests/runtime/test_source_sampling.py +++ b/tests/runtime/test_source_sampling.py @@ -9,6 +9,7 @@ args=parser.parse_args() MANAGER='components/ts_automation/src/ts_source_manager.c' RUNTIME='components/ts_automation/src/ts_source_runtime.c' +ACTION='components/ts_automation/src/ts_action_manager.c' def source(path): chosen=args.source_root/path return chosen if chosen.exists() else Path(path) @@ -16,9 +17,22 @@ def function(path,name):return body(source(path),name) rtos=re.sub(r'static int64_t esp_timer_get_time\(void\) \{[^\n]+\}', 'static int64_t clock_ms=100000; static int64_t esp_timer_get_time(void) {return clock_ms*1000;}',RTOS) code=rtos+r''' +#undef ESP_LOGD +#undef ESP_LOGI +#undef ESP_LOGW +#undef ESP_LOGE +static char source_diagnostics[32000]; +static void source_diagnostic(const char *fmt,...){size_t used=strlen(source_diagnostics);va_list args;va_start(args,fmt);vsnprintf(source_diagnostics+used,sizeof(source_diagnostics)-used,fmt,args);va_end(args);} +#define ESP_LOGD(tag,...) source_diagnostic(__VA_ARGS__) +#define ESP_LOGI(tag,...) source_diagnostic(__VA_ARGS__) +#define ESP_LOGW(tag,...) source_diagnostic(__VA_ARGS__) +#define ESP_LOGE(tag,...) source_diagnostic(__VA_ARGS__) + #include "ts_source_runtime.h" #include "ts_api.h" #include "cJSON.h" +#include "ts_http_fetch.h" +#include "ts_http_url.h" #define TAG "local-source" #define CONFIG_TS_AUTOMATION_MAX_SOURCES 4 #define ESP_ERR_INVALID_RESPONSE 0x108 @@ -27,28 +41,32 @@ def function(path,name):return body(source(path),name) #define ts_source_runtime ts_test_runtime static struct {atomic_bool activation_pending;} s_sio_ctx; static int activation_calls,variable_reads,http_calls,http_status=200; +static bool transport_test_active;static int transport_published,transport_creates,transport_updates; static int64_t request_duration;static void (*during_read)(void); static const char *http_payload="{\"temperature\":21}"; static int http_offset;static char actual_api_name[64];static cJSON *actual_params; static bool fail_query_copy; static esp_err_t api_hosts_info(const cJSON *,ts_api_result_t *); static char *query_copy(const char *s) {if(fail_query_copy)return NULL;return strdup(s);} -typedef void *esp_http_client_handle_t; -enum {HTTP_METHOD_GET,HTTP_METHOD_POST}; -typedef struct {const char *url;int method,timeout_ms,buffer_size;bool skip_cert_common_name_check;int (*crt_bundle_attach)(void*);} esp_http_client_config_t; -static int esp_crt_bundle_attach(void *p){(void)p;return ESP_OK;} -static esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *c){assert(c->url&&c->method==HTTP_METHOD_GET);++http_calls;http_offset=0;return (void*)1;} -static int esp_http_client_set_header(void *c,const char *n,const char *v){(void)c;(void)n;(void)v;return ESP_OK;} -static int esp_http_client_open(void *c,int n){(void)c;(void)n;return ESP_OK;} -static int esp_http_client_fetch_headers(void *c){(void)c;clock_ms+=request_duration;return 0;} -static int esp_http_client_get_status_code(void *c){(void)c;return http_status;} -static int esp_http_client_read(void *c,char *out,int n){(void)c;if(during_read){void(*hook)(void)=during_read;during_read=NULL;hook();}size_t len=strlen(http_payload);assert(n>=(int)len);if(http_offset)return 0;memcpy(out,http_payload,len);http_offset=(int)len;return (int)len;} -static int esp_http_client_close(void *c){(void)c;return ESP_OK;} -static int esp_http_client_cleanup(void *c){(void)c;return ESP_OK;} +static ts_http_fetch_config_t captured_fetch; +static int performed,cleaned,selected_method;static bool client_init_failure;static int perform_result=ESP_OK; +static char post_body[512],content_type[64]; +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request,ts_http_fetch_result_t *reply){ + assert(request->url);captured_fetch=*request;++http_calls;memset(reply,0,sizeof(*reply)); + if(client_init_failure)return ESP_ERR_NO_MEM; + ++performed;++cleaned;selected_method=request->method;clock_ms+=request_duration; + snprintf(post_body,sizeof(post_body),"%s",request->body?request->body:""); + snprintf(content_type,sizeof(content_type),"%s",request->content_type?request->content_type:""); + if(during_read){void(*hook)(void)=during_read;during_read=NULL;hook();} + if(perform_result!=ESP_OK)return perform_result; + reply->status=http_status;reply->content_length=(int64_t)strlen(http_payload); + if(!request->headers_only){reply->body=strdup(http_payload);reply->length=strlen(http_payload);} + return ESP_OK; +} static void ts_variable_registration_begin(void){} static void ts_variable_registration_end(void){} static int process_source_mappings(ts_auto_source_t *s,cJSON *j){(void)s;(void)j;assert(false);return 0;} -static int auto_discover_json_fields(ts_auto_source_t *s,cJSON *j,const char *p,int d,bool c){(void)s;(void)j;(void)p;(void)d;(void)c;assert(false);return 0;} +static int auto_discover_json_fields(ts_auto_source_t *s,cJSON *j,const char *p,int d,bool c){(void)s;(void)p;(void)d;assert(transport_test_active);const cJSON *v=cJSON_GetObjectItem(j,"temperature");assert(cJSON_IsNumber(v));transport_published=v->valueint;if(c)transport_creates++;else transport_updates++;return 1;} static cJSON *ts_jsonpath_get(cJSON *j,const char *p){return cJSON_Duplicate(cJSON_GetObjectItem(j,p),true);} static esp_err_t read_variable_source(ts_auto_source_t *s,ts_auto_value_t *v){(void)s;++variable_reads;*v=(ts_auto_value_t){.type=TS_AUTO_VAL_INT,.int_val=7};return ESP_OK;} void ts_source_config_activate(void){++activation_calls;} @@ -69,6 +87,54 @@ def function(path,name):return body(source(path),name) code+=function(MANAGER,name) code+=body('components/ts_api/src/ts_api.c','ts_api_parse_query') code+='#define strdup query_copy\n'+function(MANAGER,'read_rest_source')+'\n#undef strdup\n' +code+=function(ACTION,'execute_webhook') +manager=source(MANAGER).read_text();end=manager.index('} sio_connection_t;')+len('} sio_connection_t;');start=manager.rfind('typedef struct {',0,end) +code+='\ntypedef void *esp_websocket_client_handle_t;\n#define SIO_SID_MAX_LEN 64\n#define SIO_EVENT_PREFIX "42"\n'+manager[start:end]+'\n' +code+=r""" +#define SIO_MSG_BUF_SIZE 8192 +#define SIO_PROBE_MSG "2probe" +#define SIO_UPGRADE_MSG "5" +#define SIO_PING_MSG "2" +#define SIO_PONG_MSG "3" +typedef const char *esp_event_base_t; +typedef struct {char *data_ptr;int data_len,payload_len,payload_offset;bool fin;uint8_t op_code;} esp_websocket_event_data_t; +typedef struct {const char *uri;int buffer_size,reconnect_timeout_ms,network_timeout_ms,ping_interval_sec;bool enable_close_reconnect,disable_auto_reconnect;int (*crt_bundle_attach)(void *);} esp_websocket_client_config_t; +enum {WEBSOCKET_EVENT_ANY,WEBSOCKET_EVENT_CONNECTED,WEBSOCKET_EVENT_DISCONNECTED,WEBSOCKET_EVENT_DATA,WEBSOCKET_EVENT_ERROR,WEBSOCKET_EVENT_CLOSED}; +static void sio_websocket_event_handler(void *,esp_event_base_t,int32_t,void *); +static sio_connection_t *transport_conn; +static unsigned transport_clients,transport_stops,transport_phase,transport_waits; +static char transport_urls[2][512];static bool transport_sdk_reconnect_disabled[2]; +static int esp_crt_bundle_attach(void *p){(void)p;return 0;} +static int esp_websocket_client_send_text(void *c,const char *s,int n,int wait){(void)c;(void)s;(void)wait;return n;} +static void *heap_caps_realloc(void *p,size_t n,unsigned caps){(void)caps;return realloc(p,n);} +static void *esp_websocket_client_init(const esp_websocket_client_config_t *c){assert(transport_clients<2);strcpy(transport_urls[transport_clients],c->uri);transport_sdk_reconnect_disabled[transport_clients]=c->disable_auto_reconnect;return (void *)(uintptr_t)++transport_clients;} +static int esp_websocket_register_events(void *client,int event,void(*fn)(void *,esp_event_base_t,int32_t,void *),void *arg){assert(client&&event==WEBSOCKET_EVENT_ANY&&fn==sio_websocket_event_handler&&arg==transport_conn);return ESP_OK;} +static int esp_websocket_client_start(void *client){assert(client);return ESP_OK;} +static int esp_websocket_client_stop(void *client){assert(client);transport_stops++;return ESP_OK;} +static int esp_websocket_client_destroy(void *client){assert(client);return ESP_OK;} +static int xTaskNotifyGive(TaskHandle_t task){assert(task);return 1;} +static void sio_release_connection(sio_connection_t *c,bool activate){assert(c==transport_conn&&!activate);c->allocated=false;} +#define vTaskDeleteWithCaps(task) return +static unsigned ulTaskNotifyTake(int clear,unsigned wait){ + (void)clear;clock_ms+=wait;if(wait!=200)return 0;assert(++transport_waits<12); + if(transport_phase==1){ + sio_websocket_event_handler(transport_conn,NULL,WEBSOCKET_EVENT_DISCONNECTED,NULL); + http_payload="0{\"sid\":\"second-session\"}";transport_phase=2;return 0; + } + if(transport_phase==3||(transport_phase==2&&transport_clients<2)){transport_conn->should_stop=true;return 0;} + sio_websocket_event_handler(transport_conn,NULL,WEBSOCKET_EVENT_CONNECTED,NULL); + char probe[]="3probe";esp_websocket_event_data_t e={.data_ptr=probe,.data_len=6,.payload_len=6,.fin=true,.op_code=1}; + sio_websocket_event_handler(transport_conn,NULL,WEBSOCKET_EVENT_DATA,&e); + char first[]="42[\"telemetry\",{\"temperature\":41}]",second[]="42[\"telemetry\",{\"temperature\":42}]"; + e.data_ptr=transport_phase==0?first:second;e.data_len=e.payload_len=(int)strlen(e.data_ptr); + sio_websocket_event_handler(transport_conn,NULL,WEBSOCKET_EVENT_DATA,&e); + transport_phase=transport_phase==0?1:3;return 0; +} +""" +for name in ['current_connection_index','sio_handle_event_message','ts_source_sio_url','sio_http_handshake']: + code+=function(MANAGER,name) +for name in ['ws_handle_message','sio_websocket_event_handler','sio_connection_task']: + code+=function(MANAGER,name) for name in ['poll_instance','ts_source_poll_all']: code+=function(MANAGER,name) code+=re.search(r'^esp_err_t ts_source_poll\(.*$',source(MANAGER).read_text(),re.M).group(0)+'\n' @@ -101,9 +167,55 @@ def function(path,name):return body(source(path),name) extern void replace_source(void);during_read=replace_source;assert(ts_source_poll_all()==0&&sample->instance==3);unchanged(0,0,0); reset();strcpy(sample->rest.url,"http://127.0.0.1/api/v1/hosts/info?host=192.0.2.8&label=A+B%252E&n=12&port=2222");strcpy(sample->rest.path,"port");assert(ts_source_poll_all()==1&&!http_calls&&sample->last_value.int_val==2222);assert(!strcmp(actual_api_name,"hosts.info"));assert(!strcmp(cJSON_GetObjectItem(actual_params,"host")->valuestring,"192.0.2.8"));assert(!strcmp(cJSON_GetObjectItem(actual_params,"label")->valuestring,"A B%2E"));assert(cJSON_IsNumber(cJSON_GetObjectItem(actual_params,"n"))&&cJSON_GetObjectItem(actual_params,"n")->valueint==12); fail_query_copy=true;clock_ms+=60000;assert(ts_source_poll_all()==0&&sample->last_update_ms==100000&&sample->last_attempt_ms==160000);fail_query_copy=false; + + /* Protocol contents still reach the actual source owner, not global logs. */ + reset();source_diagnostics[0]=0;strcpy(sample->rest.url,"https://fixture.invalid/read?token=synthetic-rest-query-secret"); + http_payload="{\"temperature\":73,\"token\":\"synthetic-rest-body-secret\"}"; + assert(ts_source_poll_all()==1&&sample->last_value.int_val==73&&!strstr(source_diagnostics,"synthetic-rest-query-secret")&&!strstr(source_diagnostics,"synthetic-rest-body-secret")); + source_diagnostics[0]=0;http_payload="0{\"sid\":\"synthetic-sio-session-secret\",\"upgrades\":[\"websocket\"]}"; + char sid[64]={0};assert(sio_http_handshake("https://fixture.invalid",sid,sizeof(sid))==ESP_OK&&!strcmp(sid,"synthetic-sio-session-secret")&&!strstr(source_diagnostics,"synthetic-sio-session-secret")); + reset();sample->type=TS_AUTO_SRC_SOCKETIO;strcpy(sample->socketio.event,"private_event");sample->auto_discover=true; + sio_connection_t conn={.source_instance=sample->instance,.type=sample->type,.pending_mutex=xSemaphoreCreateMutex()};strcpy(conn.source_id,sample->id); + source_diagnostics[0]=0;sio_handle_event_message(&conn,"42[\"private_event\",{\"token\":\"synthetic-sio-response-secret\",\"value\":42}]"); + assert(sample->connected&&sample->last_value.type==TS_AUTO_VAL_STRING&&strstr(sample->last_value.str_val,"synthetic-sio-response-secret")&&conn.pending_json&&strstr(conn.pending_json,"synthetic-sio-response-secret")&&!strstr(source_diagnostics,"synthetic-sio-response-secret")); + free(conn.pending_json);vSemaphoreDelete(conn.pending_mutex); + /* Verify actual consumers configure the shared transport; its TLS factory is exercised separately. */ + reset();strcpy(sample->rest.url,"https://fixture.invalid/read");assert(ts_source_poll_all()==1); + assert(captured_fetch.timeout_ms==10000&&captured_fetch.maximum_body==4095&&!captured_fetch.cert_pem&&!captured_fetch.headers_only); + const char *schemes[]={"http://fixture.invalid/hook","https://fixture.invalid/hook"}; + const char *methods[]={"GET","POST","PUT"};int expected_methods[]={HTTP_METHOD_GET,HTTP_METHOD_POST,HTTP_METHOD_PUT}; + ts_auto_action_t action={.type=TS_AUTO_ACT_WEBHOOK};strcpy(action.webhook.body_template,"{\"value\":\"synthetic-body\"}"); + for(unsigned u=0;u<2;u++)for(unsigned m=0;m<3;m++){ + strcpy(action.webhook.url,schemes[u]);strcpy(action.webhook.method,methods[m]);http_status=204;perform_result=ESP_OK;content_type[0]=post_body[0]=0;int before=cleaned; + assert(execute_webhook(&action)==ESP_OK&&captured_fetch.headers_only&&captured_fetch.timeout_ms==5000&&selected_method==expected_methods[m]&&cleaned==before+1&&!strcmp(post_body,action.webhook.body_template)); + if(m)assert(!strcmp(content_type,"application/json")); + } + int before=cleaned;perform_result=ESP_FAIL;assert(execute_webhook(&action)==ESP_FAIL&&cleaned==before+1);perform_result=ESP_OK; + http_status=401;assert(execute_webhook(&action)==ESP_FAIL);http_status=200; + before=performed;client_init_failure=true;assert(execute_webhook(&action)==ESP_ERR_NO_MEM&&performed==before);client_init_failure=false; + action.type=TS_AUTO_ACT_LOG;before=http_calls;assert(execute_webhook(&action)==ESP_ERR_INVALID_ARG&&http_calls==before); + puts("PASS actual REST/Webhook shared transport consumers: HTTP/HTTPS GET/POST/PUT/body/typed deadlines/caps/status/failure retained;real shared SDK TLS factory has separate owner suite"); + puts("PASS actual REST/SIO diagnostic privacy: exact query/body read, SID returned, response summary and full pending JSON retained, no synthetic protocol canaries in global logs"); + /* Real SIO owner task: first session publishes, network disconnects, then + * a new handshake/SID must precede resumed event publication. */ + reset();sample->type=TS_AUTO_SRC_SOCKETIO;sample->auto_discover=true; + strcpy(sample->socketio.url,"http://fixture.invalid");strcpy(sample->socketio.event,"telemetry");sample->socketio.reconnect_ms=5000; + sio_connection_t reconnect={.source_instance=sample->instance,.type=sample->type,.pending_mutex=xSemaphoreCreateMutex(),.allocated=true,.task_handle=(TaskHandle_t)1}; + strcpy(reconnect.source_id,sample->id);transport_conn=&reconnect;transport_test_active=true; + http_payload="0{\"sid\":\"first-session\"}";http_status=200;transport_clients=transport_stops=transport_phase=transport_waits=0; + sio_connection_task(&reconnect);transport_test_active=false; + assert(transport_clients==2&&transport_stops==2&&http_calls==2); + assert(strstr(transport_urls[0],"first-session")&&strstr(transport_urls[1],"second-session")); + assert(transport_sdk_reconnect_disabled[0]&&transport_sdk_reconnect_disabled[1]); + assert(transport_published==42&&transport_creates==1&&transport_updates==1&&!reconnect.allocated&&!reconnect.pending_mutex); + puts("PASS real SIO task disconnect -> new handshake/SID -> temperature publish; one owner, no old-SID SDK retry, no fan/TTL changes"); cJSON_Delete(actual_params);free(ts_source_runtime.sources);vSemaphoreDelete(ts_source_runtime.mutex);puts("PASS actual REST/poll/publication: failure intervals, success freshness, slow completion cadence, manual/zero/VARIABLE, retained/new/stale instances, actual local API query receiver and allocation failure");} void replace_source(void){publish(false);} ''' headers={p.name:p.read_text() for p in [Path('components/ts_automation/include/ts_automation_types.h'),Path('components/ts_automation/include/ts_source_manager.h'),Path('components/ts_automation/src/ts_source_runtime.h')]} headers.update({'freertos/FreeRTOS.h':'#pragma once\n','freertos/semphr.h':'#pragma once\n'}) -run_native(code,[IDF/'components/json/cJSON/cJSON.c'],headers) +headers.update({name:(Path('components/ts_http_fetch/include')/name).read_text() for name in ['ts_http_fetch.h','ts_http_url.h']}) +headers['esp_http_client.h']=Path('tests/runtime/http_fetch_stubs/esp_http_client.h').read_text() +headers['http_parser.h']=(IDF/'components/http_parser/http_parser.h').read_text() + +run_native(code,[IDF/'components/json/cJSON/cJSON.c',IDF/'components/http_parser/http_parser.c',Path('components/ts_http_fetch/src/ts_http_url.c')],headers) diff --git a/tests/runtime/test_ssh_cli_controls.py b/tests/runtime/test_ssh_cli_controls.py index e17a1cd5..2755ae17 100644 --- a/tests/runtime/test_ssh_cli_controls.py +++ b/tests/runtime/test_ssh_cli_controls.py @@ -148,6 +148,15 @@ def function(path, name): code += knowntext[knowntext.index('#define NVS_NAMESPACE'):knowntext.index('/* ============================================================================\n * 外部声明')] for name in ['simple_hash','make_nvs_key','ts_known_hosts_init','ts_known_hosts_deinit','ts_known_hosts_add_manual','ts_known_hosts_list','ts_known_hosts_count','ts_known_hosts_clear']: code += function(KNOWN,name) +# Exercise the original security-page endpoint with the same NVS fixture. +code += r''' +static bool fail_hosts_alloc; +static void *hosts_alloc(size_t size) {return fail_hosts_alloc?NULL:malloc(size);} +const char *ts_host_key_type_str(ts_host_key_type_t type) {(void)type;return "ed25519";} +#define malloc hosts_alloc +''' +code += function('components/ts_api/src/ts_api_hosts.c','api_hosts_list') +code += '#undef malloc\n' # The storage adapter reads a real immutable document shape. Mutation is the # local configuration-store boundary, accepting only the original empty array. code += r''' @@ -199,7 +208,13 @@ def function(path, name): printf("PASS %s actual revoke: single/duplicate empty, mixed retention, absent and open/read/move/chmod/transport failures\n",cli?"CLI":"API"); } static int command(int (*handler)(int,char**),const char *tail) {char buffer[512];snprintf(buffer,sizeof(buffer),"%s",tail);char *argv[32];int argc=0;char *p=strtok(buffer," ");while(p){assert(argc<32);argv[argc++]=p;p=strtok(NULL," ");}console_output[0]=0;return handler(argc,argv);} -static void check_known(void) {assert(ts_known_hosts_init()==ESP_OK);uint8_t unrelated=9;assert(nvs_set_blob(s_state.nvs,"other_blob",&unrelated,1)==ESP_OK);assert(ts_known_hosts_add_manual("fixture.invalid",22,"synthetic-fingerprint",TS_HOST_KEY_ED25519)==ESP_OK);assert(command(registered_hosts,"hosts --list")==0);ts_known_host_t rows[2];size_t count=0;assert(ts_known_hosts_list(rows,2,&count)==ESP_OK&&count==1&&!strcmp(rows[0].host,"fixture.invalid"));assert(ts_known_hosts_count()==1);assert(command(registered_hosts,"hosts --clear")==1&&ts_known_hosts_count()==1);assert(command(registered_hosts,"hosts --clear --yes")==0&&ts_known_hosts_count()==0);assert(command(registered_hosts,"hosts --clear --yes")==0);assert(ts_known_hosts_deinit()==ESP_OK);puts("PASS actual stored h_ key, list/count and confirmed known-host clear");} +static void check_known(void) {ts_api_result_t r={0}; + assert(api_hosts_list(NULL,&r)==ESP_OK&&cJSON_GetArraySize(cJSON_GetObjectItem(r.data,"hosts"))==0);ts_api_result_free(&r); + assert(ts_known_hosts_init()==ESP_OK);uint8_t unrelated=9;assert(nvs_set_blob(s_state.nvs,"other_blob",&unrelated,1)==ESP_OK);assert(ts_known_hosts_add_manual("fixture.invalid",22,"synthetic-fingerprint",TS_HOST_KEY_ED25519)==ESP_OK);assert(command(registered_hosts,"hosts --list")==0);ts_known_host_t rows[2];size_t count=0;assert(ts_known_hosts_list(rows,2,&count)==ESP_OK&&count==1&&!strcmp(rows[0].host,"fixture.invalid"));assert(ts_known_hosts_count()==1); + assert(api_hosts_list(NULL,&r)==ESP_OK);cJSON *rows_json=cJSON_GetObjectItem(r.data,"hosts"); + assert(cJSON_GetArraySize(rows_json)==1&&!strcmp(cJSON_GetObjectItem(cJSON_GetArrayItem(rows_json,0),"host")->valuestring,"fixture.invalid"));ts_api_result_free(&r); + fail_hosts_alloc=true;assert(api_hosts_list(NULL,&r)==ESP_ERR_NO_MEM&&r.code==TS_API_ERR_NO_MEM);ts_api_result_free(&r);fail_hosts_alloc=false; + assert(api_hosts_list(NULL,&r)==ESP_OK);ts_api_result_free(&r);assert(command(registered_hosts,"hosts --clear")==1&&ts_known_hosts_count()==1);assert(command(registered_hosts,"hosts --clear --yes")==0&&ts_known_hosts_count()==0);assert(command(registered_hosts,"hosts --clear --yes")==0);assert(ts_known_hosts_deinit()==ESP_OK);puts("PASS actual known-host UI API: uninitialized/listed rows/allocation failure/retry; stored h_ key and confirmed CLI clear");} static void check_deployed(void) {remote_reset("ssh-ed25519 OTHER retained\n");strcpy(deployed_rows[0].id,"fixture-host");deployed_view.document.hosts=deployed_rows;deployed_view.document.host_count=1;assert(command(registered_hosts,"hosts --deployed")==0);assert(command(registered_hosts,"hosts --deployed --clear")==1&&!collection_replaces&&ts_ssh_hosts_config_count()==1);assert(command(registered_hosts,"hosts --deployed --clear --yes")==0&&collection_replaces==1&&ts_ssh_hosts_config_count()==0);assert(command(registered_hosts,"hosts --deployed")==0);assert(command(registered_hosts,"hosts --deployed --clear --yes")==0&&collection_replaces==1&&!view_readers);char *remote=read_file("remote/.ssh/authorized_keys");assert(!strcmp(remote,"ssh-ed25519 OTHER retained\n")&&!remote_calls);free(remote);puts("PASS actual frozen view count, original clear confirmation and empty collection");} static void check_auth(void) { const char *modes[]={"--exec normal","--test"}; diff --git a/tests/runtime/test_ssh_copyid.py b/tests/runtime/test_ssh_copyid.py index e466c20f..79c8fa22 100644 --- a/tests/runtime/test_ssh_copyid.py +++ b/tests/runtime/test_ssh_copyid.py @@ -1,10 +1,11 @@ """Execute production ssh.copyid with synthetic SSH and registration failures.""" +from host_paths import build_dir from pathlib import Path import os import re import subprocess -build = Path('/tmp/tianshan-ssh-host-tests') +build = build_dir('ssh-copyid') build.mkdir(exist_ok=True) idf = Path(os.environ.get('IDF_PATH', '/Users/massif/esp/v5.5.2/esp-idf')) @@ -123,6 +124,7 @@ def extract(path, name): static esp_err_t ts_http_send_error(void *req,int status,const char *msg) {return ESP_FAIL;} static esp_err_t send_result(esp_err_t ret,ts_api_result_t result) { void *req=NULL; + const bool response_may_have_effect=false; """ + web_source[start:end] + '\nreturn ESP_FAIL;\n}\n' code += r''' static cJSON *item(ts_api_result_t *r,const char *key) {return cJSON_GetObjectItem(r->data,key);} diff --git a/tests/runtime/test_ssh_fingerprint_wire.py b/tests/runtime/test_ssh_fingerprint_wire.py index 5857006b..89be1f92 100644 --- a/tests/runtime/test_ssh_fingerprint_wire.py +++ b/tests/runtime/test_ssh_fingerprint_wire.py @@ -8,6 +8,7 @@ them in tests/fixtures/ssh-fingerprint/. The browser suite replays those bytes into the real Web UI, so firmware and UI cannot drift apart unnoticed. Regenerate with UPDATE_FIXTURES=1 after an intentional wire-format change. """ +from host_paths import build_dir from pathlib import Path import json import os @@ -15,7 +16,7 @@ import subprocess import sys -build = Path('/tmp/tianshan-ssh-host-tests') +build = build_dir('ssh-fingerprint') build.mkdir(exist_ok=True) wire_dir = build / 'wire' wire_dir.mkdir(exist_ok=True) @@ -120,9 +121,11 @@ def extract(path, name): code += r''' static char *http_body; static int http_error_status; +static int http_json_status; +static bool response_may_have_effect; static char http_error_text[96]; static esp_err_t ts_http_send_json(void *req,int status,const char *json) { - assert(status==200);free(http_body);http_body=strdup(json);return ESP_OK; + assert(status==200||status==409);http_json_status=status;free(http_body);http_body=strdup(json);return ESP_OK; } static esp_err_t ts_http_send_error(void *req,int status,const char *msg) { http_error_status=status;snprintf(http_error_text,sizeof http_error_text,"%s",msg);return ESP_FAIL; @@ -329,7 +332,29 @@ def extract(path, name): } if(alloc_calls=1 && without_details>=1 && internal_error>=1); + assert(with_details>=1 && without_details==0 && internal_error>=1); +} +static void success_write_allocation_failure(void) { + cJSON_Hooks counting={counting_malloc,free}; + int complete=0,unknown=0; + response_may_have_effect=true; + for(int k=1;k<=64;k++) { + ts_api_result_t r={0}; + cJSON *data=cJSON_Parse("{\"operation_id\":123,\"boot_id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"result_key\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"}");assert(data); + ts_api_result_ok(&r,data);free(http_body);http_body=NULL;http_error_status=0; + alloc_calls=0;alloc_fail_at=k;cJSON_InitHooks(&counting); + assert(send_result(ESP_OK,r)==ESP_OK);cJSON_InitHooks(NULL); + cJSON *wire=cJSON_Parse(http_body);assert(wire&&!http_error_status); + if(http_json_status==409) { + assert(cJSON_GetObjectItem(wire,"code")->valueint==7&&!strcmp(str(wire,"error"),"result_unknown"));++unknown; + } else { + assert(http_json_status==200&&cJSON_GetObjectItem(wire,"code")->valueint==0); + cJSON *d=cJSON_GetObjectItem(wire,"data");assert(d&&cJSON_GetObjectItem(d,"operation_id")->valueint==123); + assert(!strcmp(str(d,"boot_id"),"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")&&!strcmp(str(d,"result_key"),"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));++complete; + } + cJSON_Delete(wire);if(alloc_callsst_size=strlen(color_file);return 0;} + if (encrypted_late && strstr(path, "/ui_widgets.tscfg")) { memset(out,0,sizeof(*out)); return 0; } if (encrypted_net && strstr(path, "/net.tscfg")) { memset(out,0,sizeof(*out)); return 0; } errno=ENOENT; return -1; } @@ -156,13 +157,16 @@ esp_err_t ts_cert_init(void) esp_err_t ts_config_pack_init(void) { return ESP_OK; } ts_config_pack_result_t ts_config_pack_load(const char *path, ts_config_pack_t **out) { - assert(strstr(path,"/net.tscfg")); ++pack_reads; + ++pack_reads; + if(strstr(path,"/ui_widgets.tscfg")) return TS_CONFIG_PACK_ERR_SIGNATURE; + assert(strstr(path,"/net.tscfg")); if (fail_pack) return TS_CONFIG_PACK_ERR_DECRYPT; *out=calloc(1,sizeof(**out)); assert(*out); (*out)->content=strdup("{\"eth.ip\":\"192.0.2.8\"}"); (*out)->content_len=strlen((*out)->content); return TS_CONFIG_PACK_OK; } +const char *ts_config_pack_strerror(ts_config_pack_result_t result){(void)result;return "synthetic selected pack trust error";} void ts_config_pack_free(ts_config_pack_t *pack) { if (pack) { free(pack->content); free(pack); } @@ -181,7 +185,7 @@ static void fixture(void) { for (size_t i=0;idata,"current-root",13)); assert(!system_record("ts_cfg_state","system_v") && find("keys_nvs","ts_auth","cred_root")); fail_pack=false; - assert(ts_config_migrate_system(true)==ESP_OK && pack_reads==2); + assert(ts_config_migrate_system(true)==ESP_OK && pack_reads==3); + assert(!memcmp(system_record("ts_auth","cred_root")->data,"current-root",13)); assert(!memcmp(system_record("ts_net","config")->data,"{\"eth.ip\":\"192.0.2.8\"}",22)); put("nvs","ts_ui","widgets",NVS_TYPE_BLOB,"{\"widgets\":[1]}",15); unsigned reads=file_reads; - assert(ts_config_migrate_system(true)==ESP_OK && reads==file_reads && pack_reads==2); + assert(ts_config_migrate_system(true)==ESP_OK && reads==file_reads && pack_reads==3); assert(!memcmp(system_record("ts_ui","widgets")->data,"{\"widgets\":[1]}",15)); + fixture();encrypted_net=encrypted_late=true; + assert(ts_config_migrate_system(true)==ESP_ERR_NOT_FINISHED&&!erased); + assert(!memcmp(system_record("ts_net","config")->data,"{\"eth.ip\":\"192.0.2.1\"}",22)); + fixture();encrypted_net=fail_pack=true;boot_schemas=0; + assert(ts_services_prepare_config()==ESP_OK&&boot_schemas==1); + assert(!system_record("ts_cfg_state","system_v")&&!erased); + assert(!memcmp(system_record("ts_net","config")->data,"{\"eth.ip\":\"192.0.2.1\"}",22)); color_storage(); driver_storage(); fixture(); diff --git a/tests/runtime/test_system_reboot.py b/tests/runtime/test_system_reboot.py index b227934f..77d3fb0e 100644 --- a/tests/runtime/test_system_reboot.py +++ b/tests/runtime/test_system_reboot.py @@ -28,7 +28,11 @@ #include #include #include +#include +#define pdPASS 1 #include "ts_api.h" +#include "ts_security.h" +#define ESP_ERR_NOT_ALLOWED 0x10d #include "freertos/semphr.h" #include "argtable3.h" #define TS_LOGD(...) ((void)0) @@ -118,7 +122,7 @@ with tempfile.TemporaryDirectory(prefix='ts-system-reboot-') as directory: build = Path(directory); (build / 'test.c').write_text(code) subprocess.run(['cc', '-std=gnu11', '-g', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', - '-Wno-deprecated-declarations', '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', + '-Wno-deprecated-declarations', '-Itests/runtime/storage_stubs', '-Icomponents/ts_api/include', '-Icomponents/ts_security/include', '-I' + str(cjson), '-I' + str(argtable), str(build / 'test.c'), str(cjson / 'cJSON.c'), *map(str, argtable.glob('*.c')), '-lpthread', '-lm', '-o', str(build / 'test')], check=True) cases = [args.case] if args.case else normal if args.group == 'normal' else defects if args.group == 'defect' else normal + defects diff --git a/tests/runtime/test_unimplemented_results.py b/tests/runtime/test_unimplemented_results.py new file mode 100644 index 00000000..153b9934 --- /dev/null +++ b/tests/runtime/test_unimplemented_results.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Actual legacy API/core functions reject unimplemented work; synthetic decrypted content only.""" +from pathlib import Path +from zipfile import ZipFile +import argparse,os,re,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf')) +def source(path): + if args.source_package: + with ZipFile(args.source_package) as z: + if 'current-source/'+path in z.namelist():return z.read('current-source/'+path).decode() + return subprocess.check_output(['git','show','35e081ac8:'+path],cwd=os.environ.get('SOURCE_REPOSITORY',str(ROOT)),text=True) + return (ROOT/path).read_text() +def function(path,name): + t=source(path);m=re.search(r'^(?:static )?[^\n;]+\b'+name+r'\([^;]+?\)\s*\{',t,re.M);assert m,name + return t[m.start():t.index('\n}',m.start())+2]+'\n' +code=r''' +#include +#include +#include +#include +#include +#include "ts_api.h" +#include "ts_config_pack.h" +#define ESP_LOGI(...) ((void)0) +#define ESP_LOGE(...) ((void)0) +#define TS_LOGI(...) ((void)0) +#define TS_MALLOC_PSRAM malloc +#define TS_STRDUP_PSRAM strdup +static unsigned checks,failures,opens,loads,module_writes; +static bool s_initialized=true,fail_json; +static void check(bool ok,const char *why){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",why);}} +static void *json_malloc(size_t n){return fail_json?NULL:malloc(n);} +/* These are only old-function read/decrypt boundaries, never a PKI trust test. */ +static FILE *fixture_open(const char *p,const char *mode){(void)p;(void)mode;opens++;FILE *f=tmpfile();assert(f);fputs("{}",f);rewind(f);return f;} +ts_config_pack_result_t ts_config_pack_load_mem(const char *text,size_t len,ts_config_pack_t **out){ + (void)text;(void)len;loads++;*out=calloc(1,sizeof(**out));assert(*out);(*out)->content=strdup("{\"network\":{},\"led\":{},\"fan\":{}}");assert((*out)->content);return TS_CONFIG_PACK_OK; +} +void ts_config_pack_free(ts_config_pack_t *p){if(p){free(p->content);free(p);}} +''' +for name in ['ts_api_result_init','ts_api_result_free','ts_api_result_ok','ts_api_result_error','ts_api_result_reason']:code+=function('components/ts_api/src/ts_api.c',name) +t=source('components/ts_config_pack/src/ts_config_pack.c');a=t.index('static const char *s_error_messages[]');b=t.index('\n};',a)+3;code+=t[a:b]+'\n' +for name in ['ts_config_pack_strerror','ts_config_pack_reason']:code+=function('components/ts_config_pack/src/ts_config_pack.c',name) +code+='#define fopen fixture_open\n'+function('components/ts_config_pack/src/ts_config_pack.c','ts_config_pack_apply_file')+'#undef fopen\n' +code+=source('components/ts_api/src/ts_api_pack.h')+'\n' +code+=function('components/ts_api/src/ts_api_config_pack.c','api_config_pack_apply') +code+=r''' +int main(void){ + cJSON_Hooks hooks={json_malloc,free};cJSON_InitHooks(&hooks); + cJSON *params=cJSON_Parse("{\"path\":\"/synthetic/old.tscfg\",\"device\":\"matrix\",\"index\":1,\"count\":2,\"color\":\"#010203\"}");assert(params); + ts_api_result_t result={0}; + cJSON *modules=(cJSON*)(uintptr_t)1;ts_config_pack_result_t rc=ts_config_pack_apply_file("/synthetic/old.tscfg",&modules); + check(rc==TS_CONFIG_PACK_ERR_UNSUPPORTED,"core rejects unimplemented module application");check(modules==NULL,"module names are not claimed applied");check(opens==0&&loads==0&&module_writes==0,"unsupported apply opens/decrypts/applies nothing"); + if(modules&&(uintptr_t)modules!=1)cJSON_Delete(modules); + check(api_config_pack_apply(params,&result)==ESP_ERR_NOT_SUPPORTED&&result.code==TS_API_ERR_NOT_SUPPORTED,"API reports unsupported instead of success"); + check(result.message&&!strcmp(result.message,"pack_apply_unsupported"),"specific reason reaches client");check(!result.data||!cJSON_IsTrue(cJSON_GetObjectItem(result.data,"success")),"no false apply success payload");ts_api_result_free(&result); + check(!strcmp(ts_config_pack_reason(TS_CONFIG_PACK_ERR_UNSUPPORTED),"pack_apply_unsupported")&&strstr(ts_config_pack_strerror(TS_CONFIG_PACK_ERR_UNSUPPORTED),"not supported"),"core reason and detail defined"); + modules=(cJSON*)(uintptr_t)1;check(ts_config_pack_apply_file(NULL,&modules)==TS_CONFIG_PACK_ERR_INVALID_ARG&&modules==NULL,"null path has no stale applied output"); + s_initialized=false;modules=(cJSON*)(uintptr_t)1;check(ts_config_pack_apply_file("x",&modules)==TS_CONFIG_PACK_ERR_NOT_INIT&&modules==NULL,"uninitialized has no stale applied output");s_initialized=true; + check(api_config_pack_apply(NULL,&result)==ESP_ERR_INVALID_ARG&&result.code==TS_API_ERR_INVALID_ARG,"missing path keeps argument error");ts_api_result_free(&result); + /* Failure to allocate optional detail must never turn rejection into success. */ + fail_json=true;check(api_config_pack_apply(params,&result)==ESP_ERR_NOT_SUPPORTED&&result.code==TS_API_ERR_NOT_SUPPORTED,"JSON OOM retains apply rejection");ts_api_result_free(&result); + fail_json=false; + cJSON_Delete(params);printf("%u checks, %u failures: actual unsupported pack API/core; no file/decrypt/application side effects; LED0.6.4 positive and invalid-range checks in test_led_controls.py; synthetic old decrypted payload is not PKI evidence\n",checks,failures);return failures?1:0; +} +''' +with tempfile.TemporaryDirectory(prefix='ts-unimplemented-') as tmp: + c=Path(tmp)/'probe.c';exe=Path(tmp)/'probe';c.write_text(code) + includes=[ROOT/'tests/runtime/rule_pack/stubs'] + includes += [ROOT/('components/'+module+'/include') for module in ['ts_api','ts_drivers','ts_led','ts_net','ts_config_pack','ts_storage','ts_security','ts_core/ts_config']] + includes += [IDF/'components/json/cJSON'] + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-fsanitize=address,undefined','-fno-sanitize-recover=all',*['-I'+str(p) for p in includes],str(c),str(IDF/'components/json/cJSON/cJSON.c'),'-lm','-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True,timeout=20) diff --git a/tests/runtime/test_ws_diagnostic_transport.py b/tests/runtime/test_ws_diagnostic_transport.py new file mode 100644 index 00000000..5723eadd --- /dev/null +++ b/tests/runtime/test_ws_diagnostic_transport.py @@ -0,0 +1,138 @@ +"""Actual diagnostic transport + SDK transport dispatch/WS handshake and frames. +Only DNS, raw TCP/TLS I/O and scheduler/clock are synthetic. No network/device. +""" +from pathlib import Path +import importlib.util,os,tempfile +from test_console_lifecycle import IDF,run_native,body +from host_paths import sdk_library_dir +root=Path(__file__).resolve().parents[2] +sdk=sdk_library_dir(IDF) +websocket_source=Path(os.environ.get('TS_WS_COMPONENT_SOURCE',str(root/'managed_components/espressif__esp_websocket_client/esp_websocket_client.c'))) +spec=importlib.util.spec_from_file_location('prepare',root/'tools/prepare_http_transport_polling.py');prepare=importlib.util.module_from_spec(spec);spec.loader.exec_module(prepare) +with tempfile.TemporaryDirectory(prefix='ts-ws-diag-prepared-') as directory: + prepared=Path(directory);prepare.prepare(IDF,prepared,websocket_source) + headers={name:(IDF/'components/tcp_transport/include'/name).read_text() for name in ['esp_transport.h','esp_transport_tcp.h','esp_transport_ssl.h','esp_transport_ws.h']} + headers.update({'esp_transport_internal.h':(IDF/'components/tcp_transport/private_include/esp_transport_internal.h').read_text(), + 'esp_tls_crypto.h':(IDF/'components/esp-tls/esp-tls-crypto/esp_tls_crypto.h').read_text(), + 'esp_tls.h':'''#pragma once +#include +#include "esp_err.h" +struct esp_tls_last_error{int last_error,esp_tls_error_code,esp_tls_flags;}; +typedef struct esp_tls_last_error esp_tls_last_error_t; +typedef struct {const unsigned char *key;size_t key_size;const char *hint;} psk_hint_key_t; +typedef int esp_tls_addr_family_t; +typedef int esp_tls_proto_ver_t; +struct ifreq; +#define ESP_TLS_ERR_TYPE_SYSTEM 3 +#define ESP_ERR_ESP_TLS_TCP_CLOSED_FIN 0x7001 +#define ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT 0x7002 +#define ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST 0x7003 +static inline int esp_tls_get_and_clear_error_type(void *h,int t,int *out){(void)h;(void)t;*out=0;return 0;} +''', + 'esp_log.h':'#pragma once\n#define ESP_LOGD(...) ((void)0)\n#define ESP_LOGV(...) ((void)0)\n#define ESP_STATIC_ANALYZER_CHECK(condition,value) do{if(condition)return(value);}while(0)\n#define ESP_LOGI(...) ((void)0)\n#define ESP_LOGW(...) ((void)0)\n#define ESP_LOGE(...) ((void)0)\n', + 'esp_timer.h':'#pragma once\n#include \nint64_t esp_timer_get_time(void);\n', + 'esp_crt_bundle.h':'#pragma once\nint esp_crt_bundle_attach(void *);\n', + 'freertos/FreeRTOS.h':'#pragma once\n#define pdMS_TO_TICKS(n) (n)\n', + 'freertos/task.h':'#pragma once\nvoid vTaskDelay(unsigned);\n', + 'ts_dns.h':'#pragma once\n#include \n#include \n#include "esp_err.h"\ntypedef struct {char text[64];} ip_addr_t;\nesp_err_t ts_dns_resolve(const char*,int64_t,bool(*)(void*),void*,ip_addr_t*);\nchar *ipaddr_ntoa_r(const ip_addr_t*,char*,int);\n', + 'ts_http_url.h':(root/'components/ts_http_fetch/include/ts_http_url.h').read_text(), + 'http_parser.h':(IDF/'components/http_parser/http_parser.h').read_text()}) + code=r''' +#define _DARWIN_C_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include "esp_transport.h" +#include "esp_transport_ssl.h" +#include "esp_tls_crypto.h" +#include "ts_dns.h" +#include "mbedtls/base64.h" +#include "mbedtls/sha1.h" +static unsigned checks,allocations;static int allocation_budget=-1;static void *live[128];static unsigned live_count; +static void check(bool v,const char *m){checks++;if(!v){fprintf(stderr,"FAIL %s\n",m);abort();}} +static void *tracked_malloc(size_t size){if(allocation_budget==0)return NULL;if(allocation_budget>0)allocation_budget--;void *p=malloc(size);if(p){assert(live_count<128);live[live_count++]=p;allocations++;}return p;} +static void tracked_free(void *p){if(!p)return;unsigned i;for(i=0;itext,"192.0.2.8");return ESP_OK; +} +char *ipaddr_ntoa_r(const ip_addr_t *ip,char *out,int cap){snprintf(out,(size_t)cap,"%s",ip->text);return out;} +#define malloc tracked_malloc +#define calloc tracked_calloc +#define free tracked_free +#define strdup tracked_strdup +''' + code+='#define TAG sdk_dispatch_tag\n#include "'+str(IDF/'components/tcp_transport/transport.c')+'"\n#undef TAG\n' + code+=body(IDF/'components/tcp_transport/transport_internal.c','esp_transport_utils_ms_to_timeval') + code+='#define CONFIG_WS_BUFFER_SIZE 1024\n#define getrandom fixture_random\n#define TAG sdk_ws_tag\n#include "'+str(prepared/'transport_ws.c')+'"\n#undef TAG\n#undef getrandom\n' + code+=r''' +typedef struct {bool connected;int64_t connect_at,read_at;char wire[1024];size_t wire_len,cursor;} raw_t; +static raw_t *raw; +static int raw_close(esp_transport_handle_t t){raw_t *r=esp_transport_get_context_data(t);r->connected=false;return 0;} +static int raw_destroy(esp_transport_handle_t t){tracked_free(esp_transport_get_context_data(t));raw=NULL;return 0;} +static int raw_async(esp_transport_handle_t t,const char *host,int port,int timeout){ + raw_t *r=esp_transport_get_context_data(t);async_calls++;check(timeout==0,"connect uses nonblocking SDK API");check(port==8080||port==8443,"original port retained");snprintf(actual_target,sizeof(actual_target),"%s",host);check(!strcmp(host,"192.0.2.8"),"socket connects only to pinned numeric address"); + if(connect_stall||now_usconnect_at)return 0;r->connected=true;return 1; +} +static int raw_poll_read(esp_transport_handle_t t,int timeout){raw_t *r=esp_transport_get_context_data(t);check(timeout==0,"read readiness never blocks SDK");return !read_stall&&r->cursorwire_len&&now_us>=r->read_at;} +static int raw_poll_write(esp_transport_handle_t t,int timeout){(void)t;check(timeout==0,"write readiness never blocks SDK");return !write_stall;} +static int raw_read(esp_transport_handle_t t,char *out,int length,int timeout){ + raw_t *r=esp_transport_get_context_data(t);check(timeout==0&&length>0,"bounded WS parser uses nonblocking raw read");if(io_retry){io_retry=false;errno=EAGAIN;return -1;} + if(r->cursor==r->wire_len){errno=EAGAIN;return -1;}out[0]=r->wire[r->cursor++];r->read_at=now_us+(slow_header?10000:0);return 1; +} +static int raw_write(esp_transport_handle_t t,const char *text,int length,int timeout){ + raw_t *r=esp_transport_get_context_data(t);check(timeout==0&&length>0,"upgrade/write never blocks SDK"); + if(length>=4&&!strncmp(text,"GET ",4)){ + assert((size_t)lengthwire,sizeof(r->wire),"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n",accept);assert(count>0);r->wire_len=(size_t)count;r->cursor=0; + const char payload[]="{\"temperature\":23}";r->wire[r->wire_len++]=(char)0x81;r->wire[r->wire_len++]=sizeof(payload)-1;memcpy(r->wire+r->wire_len,payload,sizeof(payload)-1);r->wire_len+=sizeof(payload)-1; + } + return length; +} +static esp_transport_handle_t raw_init(void){esp_transport_handle_t t=esp_transport_init();if(!t)return NULL;raw=calloc(1,sizeof(*raw));if(!raw){esp_transport_destroy(t);return NULL;}raw->connect_at=now_us+10000;esp_transport_set_context_data(t,raw);esp_transport_set_func(t,NULL,raw_read,raw_write,raw_close,raw_poll_read,raw_poll_write,raw_destroy);esp_transport_set_async_connect_func(t,raw_async);return t;} +esp_transport_handle_t esp_transport_tcp_init(void){return raw_init();} +esp_transport_handle_t esp_transport_ssl_init(void){return raw_init();} +void esp_transport_ssl_set_common_name(esp_transport_handle_t t,const char *name){(void)t;actual_sni=name;} +void esp_transport_ssl_crt_bundle_attach(esp_transport_handle_t t,esp_err_t(*attach)(void*)){(void)t;actual_bundle=attach==esp_crt_bundle_attach;} +''' + code+='#include "'+str(root/'components/ts_api/src/ts_api_ws_test_transport.c')+'"\n' + code+=r''' +static void reset(void){check(!live_count,"previous test releases every transport/string");now_us=0;dns_calls=async_calls=0;dns_fail=dns_stall=connect_stall=read_stall=write_stall=bad_accept=slow_header=io_retry=false;actual_sni=NULL;actual_bundle=false;upgrade_request[0]=actual_target[0]=0;allocation_budget=-1;} +int main(void){ + for(unsigned secure=0;secure<2;secure++){ + reset();ts_api_ws_test_transport_t owner;const char *uri=secure?"wss://user:synthetic@node.fixture:8443/feed?x=1":"ws://node.fixture:8080/feed?x=1"; + check(ts_api_ws_test_transport_init(&owner,uri,500000)==ESP_OK,"real constructor succeeds"); + if(secure)check(actual_bundle&&!strcmp(actual_sni,"node.fixture"),"TLS keeps bundle and original name before numeric connect"); + check(esp_transport_connect(owner.websocket,owner.hostname,owner.port,500)==0,"real SDK WS handshake and actual SHA/Base64 succeed"); + check(strstr(upgrade_request,"GET /feed?x=1 HTTP/1.1\r\n")&&strstr(upgrade_request,secure?"Host: node.fixture:8443\r\n":"Host: node.fixture:8080\r\n"),"path/query and original Host retained"); + if(secure)check(strstr(upgrade_request,"Authorization: Basic dXNlcjpzeW50aGV0aWM=\r\n"),"existing URI Basic authentication preserved"); + char output[64];size_t used=0;while(used<18){int n=esp_transport_read(owner.websocket,output+used,(int)(sizeof(output)-used),500);check(n>0,"real SDK frame parser reads complete payload");used+=(size_t)n;}output[used]=0;check(!strcmp(output,"{\"temperature\":23}"),"actual WS payload unchanged");check(dns_calls==1&&now_us<500000,"single resolution/shared budget");esp_transport_close(owner.websocket);ts_api_ws_test_transport_destroy(&owner);check(!live_count&&!raw,"all SDK handles and credentials freed"); + } + for(unsigned fault=0;fault<7;fault++){ + reset();dns_fail=fault==0;dns_stall=fault==1;connect_stall=fault==2;read_stall=fault==3;write_stall=fault==4;bad_accept=fault==5;slow_header=fault==6; + ts_api_ws_test_transport_t owner;check(ts_api_ws_test_transport_init(&owner,"wss://node.fixture:8443/feed",100000)==ESP_OK,"fault fixture allocates original owner"); + check(esp_transport_connect(owner.websocket,owner.hostname,owner.port,100)<0,"DNS/connect/read/write/accept/drip failures reject handshake");check(now_us<=100000,"slow whole handshake cannot multiply timeout");ts_api_ws_test_transport_destroy(&owner);check(!live_count&&!raw,"every failure releases all SDK transports"); + } + reset();ts_api_ws_test_transport_t owner;check(ts_api_ws_test_transport_init(&owner,"ws://node.fixture:8080/",100000)==ESP_OK,"retry fixture init");io_retry=true;check(esp_transport_connect(owner.websocket,owner.hostname,owner.port,100)==0,"nonblocking EAGAIN read retries without treating it as EOF");ts_api_ws_test_transport_destroy(&owner); + for(int budget=0;budget<32;budget++){reset();allocation_budget=budget;esp_err_t ret=ts_api_ws_test_transport_init(&owner,"wss://user:synthetic@node.fixture:8443/feed?q=1",100000);allocation_budget=-1;if(ret==ESP_OK)ts_api_ws_test_transport_destroy(&owner);check(!live_count&&!raw,"constructor allocation sweep cannot leak any handle/string");} + reset();check(ts_api_ws_test_transport_init(&owner,"ftp://node.fixture/",100000)==ESP_ERR_INVALID_ARG&&!live_count&&!dns_calls,"invalid target rejects before transport/DNS");check(ts_api_ws_test_transport_init(&owner,"ws://node.fixture/",0)==ESP_ERR_TIMEOUT&&!live_count,"expired operation cannot allocate a client"); + printf("%u checks: actual diagnostic owner+SDK transport/WS handshake/frame/crypto;synthetic raw TCP/TLS,DNS,clock only;no network\n",checks);return 0; +} +''' + run_native(code,[IDF/'components/http_parser/http_parser.c',root/'components/ts_http_fetch/src/ts_http_url.c',sdk/'library/libmbedcrypto.a'],headers,[root/'components/ts_api/src',IDF/'components/mbedtls/mbedtls/include']) diff --git a/tests/runtime/test_ws_sdk_lifecycle.py b/tests/runtime/test_ws_sdk_lifecycle.py new file mode 100644 index 00000000..3756a865 --- /dev/null +++ b/tests/runtime/test_ws_sdk_lifecycle.py @@ -0,0 +1,135 @@ +"""Actual SDK worker publication/destruction and external close contract. +Synthetic scheduling only; actual prepared SDK function bodies, ASan/UBSan. +""" +from pathlib import Path +import importlib.util, os, re, subprocess, tempfile +from test_console_lifecycle import IDF +root = Path(__file__).resolve().parents[2] +source = Path(os.environ.get('TS_WS_COMPONENT_SOURCE', str(root / 'managed_components/espressif__esp_websocket_client/esp_websocket_client.c'))) +spec = importlib.util.spec_from_file_location('prepare', root / 'tools/prepare_http_transport_polling.py') +prepare = importlib.util.module_from_spec(spec); spec.loader.exec_module(prepare) + +def function(text, name): + match = re.search(r'^(?:static )?esp_err_t ' + name + r'\([^;]+?\)\s*\{', text, re.M) + assert match, name + return text[match.start():text.index('\n}', match.end()) + 2] + '\n' + +def native(directory, name, code): + src = directory / (name + '.c'); exe = directory / name + src.write_text(code) + subprocess.run(['cc', '-std=gnu11', '-g', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', str(src), '-pthread', '-o', str(exe)], check=True) + subprocess.run([str(exe)], check=True, timeout=15) + +with tempfile.TemporaryDirectory(prefix='ts-ws-sdk-lifetime-') as temporary: + directory = Path(temporary) + prepare.prepare(IDF, directory, source) + text = (directory / 'esp_websocket_client.c').read_text() + code=r''' + #include + #include + #include + #include + typedef int esp_err_t;typedef void *TaskHandle_t; + #define ESP_OK 0 + #define ESP_FAIL -1 + #define ESP_ERR_INVALID_ARG 2 + #define WEBSOCKET_STATE_INIT 1 + #define WEBSOCKET_STATE_UNKNOW 0 + #define STOPPED_BIT 1 + #define CLOSE_FRAME_SENT_BIT 2 + #define portMAX_DELAY 0xffffffffu + #define pdTRUE 1 + #define ESP_LOGE(...) ((void)0) + #define ESP_LOGI(...) ((void)0) + #define ESP_LOGW(...) ((void)0) + typedef struct {void *ext_transport;const char *task_name;unsigned task_stack,task_prio;} config_t; + typedef struct client {int state;config_t *config;void *transport;TaskHandle_t task_handle;unsigned *status_bits;bool run;void *lock;} *esp_websocket_client_handle_t; + static bool fail_create;static unsigned failures,waits; + static int xSemaphoreTakeRecursive(void *lock,unsigned timeout){(void)lock;(void)timeout;return 1;} + static int xSemaphoreGiveRecursive(void *lock){(void)lock;return 1;} + static void check(bool v,const char *s){if(!v){failures++;printf("FAIL %s\n",s);}} + static TaskHandle_t xTaskGetCurrentTaskHandle(void){return (void*)1;} + static unsigned xEventGroupClearBits(unsigned *bits,unsigned mask){*bits &=~mask;return *bits;} + static unsigned xEventGroupSetBits(unsigned *bits,unsigned mask){*bits |=mask;return *bits;} + static unsigned xEventGroupGetBits(unsigned *bits){return *bits;} + static unsigned xEventGroupWaitBits(unsigned *bits,unsigned mask,bool clear,bool all,unsigned timeout){(void)clear;(void)all;(void)timeout;waits++;check((*bits&mask)==mask,"stop/destroy would wait forever after early completed worker");return *bits;} + static void esp_websocket_client_task(void *p){esp_websocket_client_handle_t c=p;c->task_handle=NULL;c->state=WEBSOCKET_STATE_UNKNOW;xEventGroupSetBits(c->status_bits,STOPPED_BIT);} + static int xTaskCreate(void (*task)(void*),const char *name,unsigned stack,void *arg,unsigned prio,TaskHandle_t *out){(void)name;(void)stack;(void)prio;if(fail_create)return 0;*out=(void*)2;task(arg);return pdTRUE;} + static int esp_websocket_client_create_transport(esp_websocket_client_handle_t c){(void)c;return ESP_FAIL;} + '''+function(text, 'stop_wait_task')+function(text, 'esp_websocket_client_start')+function(text, 'esp_websocket_client_stop')+r''' + int main(void){ + for(unsigned fault=0;fault<2;fault++){ + unsigned bits=STOPPED_BIT;config_t config={.ext_transport=(void*)3};struct client client={.config=&config,.status_bits=&bits};fail_create=fault; + check((esp_websocket_client_start(&client)==ESP_OK)==!fault,"actual SDK start success/failure"); + check(bits&STOPPED_BIT,"creator must not clear completed worker or failed-create stop state"); + esp_websocket_client_stop(&client); + } + printf("actual SDK early-task/stop state: %u failures;synthetic scheduler only,no task/network\n",failures);return failures?1:0; + } + ''' + native(directory, 'start', code) + + a=text.index(' esp_websocket_client_dispatch_event(client, WEBSOCKET_EVENT_FINISH, NULL, 0);');b=text.index(' vTaskDelete(NULL);',a)+len(' vTaskDelete(NULL);');tail=text[a:b] + code=r''' + #define _POSIX_C_SOURCE 200809L + #include + #include + #include + #include + #include + #include + #include + #include + #define ESP_OK 0 + #define ESP_ERR_INVALID_ARG 2 + #define WEBSOCKET_STATE_UNKNOW 0 + #define WEBSOCKET_EVENT_FINISH 12 + #define STOPPED_BIT 1 + #define portMAX_DELAY 0xffffffffu + #define ESP_LOGE(...) ((void)0) + typedef int esp_err_t; + typedef struct client {void *transport;unsigned *status_bits;int state;bool selected_for_destroying;pthread_mutex_t *lock;} *esp_websocket_client_handle_t; + static pthread_mutex_t gate;static pthread_t worker,destroyer;static atomic_bool worker_locked,destructor_entered;static unsigned destroyed; + static esp_err_t esp_websocket_client_destroy(esp_websocket_client_handle_t); + static int xSemaphoreTakeRecursive(pthread_mutex_t *lock,unsigned timeout){(void)timeout;pthread_mutex_lock(lock);if(pthread_equal(pthread_self(),worker))atomic_store(&worker_locked,true);return 1;} + static int xSemaphoreGiveRecursive(pthread_mutex_t *lock){if(pthread_equal(pthread_self(),worker))atomic_store(&worker_locked,false);pthread_mutex_unlock(lock);return 1;} + static void destroy_and_free_resources(esp_websocket_client_handle_t client){destroyed++;free(client);} + static int stop_wait_task(esp_websocket_client_handle_t client){(void)client;assert(!"already stopped fixture must not wait");return 0;} + static unsigned xEventGroupGetBits(unsigned *bits){return *bits;} + static void *destroy_client(void *p){atomic_store(&destructor_entered,true);esp_websocket_client_destroy(p);return NULL;} + static esp_websocket_client_handle_t observed; + static unsigned xEventGroupSetBits(unsigned *bits,unsigned mask){ + *bits|=mask;pthread_create(&destroyer,NULL,destroy_client,observed);while(!atomic_load(&destructor_entered))sched_yield(); + /* Before the fix there is no publication lock: force the real destructor + * to complete before the SDK worker performs its next client access. */ + if(!atomic_load(&worker_locked))pthread_join(destroyer,NULL); + return *bits; + } + static void esp_websocket_client_dispatch_event(void *c,int e,void *d,int n){(void)c;(void)e;(void)d;(void)n;} + static int esp_transport_close(void *p){(void)p;return 0;} + static void vTaskDelete(void *p){(void)p;} + '''+function(text, 'esp_websocket_client_destroy')+'\nstatic void finish(esp_websocket_client_handle_t client){\n'+tail+'\n}\n'+r''' + int main(void){ + pthread_mutexattr_t attr;pthread_mutexattr_init(&attr);pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);pthread_mutex_init(&gate,&attr);pthread_mutexattr_destroy(&attr);worker=pthread_self();unsigned bits=0; + observed=calloc(1,sizeof(*observed));observed->lock=&gate;observed->status_bits=&bits;observed->state=1;finish(observed); + if(atomic_load(&destructor_entered)&&!atomic_load(&worker_locked))pthread_join(destroyer,NULL); + assert(destroyed==1);pthread_mutex_destroy(&gate);puts("PASS actual SDK finish/destructor: publication barrier joins last client/event access;deterministic pthread schedule,no network");return 0; + } + ''' + native(directory, 'finish', code) + # Execute the real close-poll expression. Opaque external transports must + # never reach direct socket access; built-in transport keeps SDK behavior. + match = re.search(r'int ret = client->config->ext_transport \? 1 :\s*esp_transport_ws_poll_connection_closed\(client->transport, 1000\);', text) + assert match, 'external close contract changed' + code = r""" +#include +#include +static unsigned polls; +static int esp_transport_ws_poll_connection_closed(void *t,int ms){assert(t && ms==1000);polls++;return -7;} +struct config{void *ext_transport;};struct client{struct config *config;void *transport;}; +static int close_poll(struct client *client){ +""" + match.group(0) + r""" +return ret;} +int main(void){struct config cfg={.ext_transport=(void*)1};struct client c={.config=&cfg,.transport=(void*)2};assert(close_poll(&c)==1 && !polls);cfg.ext_transport=0;assert(close_poll(&c)==-7 && polls==1);puts("PASS actual SDK external close skips direct socket;built-in close retained");} +""" + native(directory, 'close', code) diff --git a/tests/ws_subscriptions/run_control.sh b/tests/ws_subscriptions/run_control.sh index cc2bed1d..800124dd 100644 --- a/tests/ws_subscriptions/run_control.sh +++ b/tests/ws_subscriptions/run_control.sh @@ -9,8 +9,10 @@ python3 - "$build" <<'PYCODE' from pathlib import Path import sys s=Path('components/ts_api/src/ts_api_ssh.c').read_text() -a=s.index('static esp_err_t api_ssh_cancel('); b=s.index('\n}',a)+2 -Path(sys.argv[1],'api_cancel.inc').write_text(s[a:b]) +parts=[] +for name in ['api_ssh_cancel_impl','api_ssh_cancel','api_ssh_cancel_for_session']: + a=s.index('static esp_err_t '+name+'(');b=s.index('\n}',a)+2;parts.append(s[a:b]) +Path(sys.argv[1],'api_cancel.inc').write_text('\n'.join(parts)) PYCODE "${CC:-cc}" -std=gnu11 -g -Wno-deprecated-declarations -Wno-macro-redefined -fsanitize=address,undefined \ -I"$build" -Itests/ws_subscriptions/stubs -Icomponents/ts_webui/include -Icomponents/ts_webui/src -Icomponents/ts_security/include -Icomponents/ts_automation/include -Icomponents/ts_drivers/include -Icomponents/ts_console/include -Icomponents/ts_net/include -I"$cjson" \ diff --git a/tests/ws_subscriptions/run_host.sh b/tests/ws_subscriptions/run_host.sh index 787c52c9..7d05457b 100755 --- a/tests/ws_subscriptions/run_host.sh +++ b/tests/ws_subscriptions/run_host.sh @@ -17,7 +17,7 @@ for source,names,out in [ ('components/ts_webui/src/ts_webui.c',['ts_webui_stop','ts_webui_deinit','ts_webui_is_running'],'webui_stop.inc')]: s=Path(source).read_text();parts=[] for name in names: - m=re.search(r'^(?:esp_err_t|bool) '+name+r'\(void\)\s*\{',s,re.M);assert m,name + m=re.search(r'^(?:static )?(?:esp_err_t|bool|void) '+name+r'\([^;]*\)\s*\{',s,re.M);assert m,name parts.append(s[m.start():s.index('\n}',m.start())+2]) Path(sys.argv[1],out).write_text('\n'.join(parts)) PY diff --git a/tests/ws_subscriptions/run_input_admission.py b/tests/ws_subscriptions/run_input_admission.py new file mode 100644 index 00000000..29bac352 --- /dev/null +++ b/tests/ws_subscriptions/run_input_admission.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +from pathlib import Path +from zipfile import ZipFile +import argparse,os,subprocess,tempfile +ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) +p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() +IDF=Path(os.environ.get('IDF_PATH','/Users/massif/esp/v5.5.2/esp-idf'));cjson=IDF/'components/json/cJSON' +with tempfile.TemporaryDirectory(prefix='ts-ws-input-') as tmp: + if args.source_package: + rel='components/ts_webui/src/ts_webui_ws.c' + with ZipFile(args.source_package) as z: + name='current-source/'+rel + old=z.read(name) if name in z.namelist() else subprocess.check_output(['git','show','35e081ac8:'+rel]) + Path(tmp,'ts_webui_ws.c').write_bytes(old) + exe=Path(tmp,'test') + include=['tests/ws_subscriptions/stubs','components/ts_webui/include','components/ts_webui/src','components/ts_security/include','components/ts_automation/include','components/ts_drivers/include','components/ts_console/include','components/ts_net/include',str(cjson)] + subprocess.run(['cc','-std=gnu11','-g','-Wno-deprecated-declarations','-Wno-macro-redefined','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+tmp,*['-I'+p for p in include],'tests/ws_subscriptions/test_input_admission.c',str(cjson/'cJSON.c'),'-lm','-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True,timeout=30) diff --git a/tests/ws_subscriptions/run_operation_adapter.sh b/tests/ws_subscriptions/run_operation_adapter.sh index 116eca51..870d2335 100644 --- a/tests/ws_subscriptions/run_operation_adapter.sh +++ b/tests/ws_subscriptions/run_operation_adapter.sh @@ -23,6 +23,9 @@ import sys source=Path('components/ts_webui/src/ts_webui_api.c').read_text() a=source.index('esp_err_t ts_webui_api_init(void)');b=source.index('\n}',a)+2 Path(sys.argv[1],'webui_route_registration.inc').write_text(source[a:b]) +source=Path('components/ts_net/src/ts_https_server.c').read_text() +a=source.index('static esp_err_t https_handler_wrapper(httpd_req_t *req)\n{');b=source.index('\n}',a)+2 +Path(sys.argv[1],'https_route_wrapper.inc').write_text(source[a:b]) PY_ROUTES for auth in enabled disabled; do auth_flags=() diff --git a/tests/ws_subscriptions/run_reviewer.sh b/tests/ws_subscriptions/run_reviewer.sh index caa66058..e168e84a 100644 --- a/tests/ws_subscriptions/run_reviewer.sh +++ b/tests/ws_subscriptions/run_reviewer.sh @@ -9,12 +9,12 @@ python3 - "$build" <<'PY' from pathlib import Path import sys,re for source,names,dest in [ - ('components/ts_net/src/ts_http_server.c',['http_handler_wrapper'],'reviewer_http.inc'), + ('components/ts_net/src/ts_http_server.c',['ts_http_authorize_route','ts_http_admit_body','ts_http_receive_body','http_handler_wrapper'],'reviewer_http.inc'), ('main/ts_core_init.c',['core_release_components','core_init_rollback','ts_core_start','ts_core_stop','ts_core_deinit'],'reviewer_core.inc'), ('components/ts_core/ts_service/src/ts_service.c',['stop_service_internal','ts_service_stop','ts_service_stop_all','ts_service_deinit'],'reviewer_service.inc')]: s=Path(source).read_text();parts=[] for name in names: - m=re.search(r'^(?:static )?esp_err_t '+name+r'\([^;]*?\)\n\{',s,re.M);assert m,name + m=re.search(r'^(?:static )?(?:esp_err_t|bool) '+name+r'\([^;]*?\)\n\{',s,re.M);assert m,name parts.append(s[m.start():s.index('\n}',m.start())+2]) Path(sys.argv[1],dest).write_text('\n'.join(parts)) PY @@ -26,5 +26,5 @@ cc -std=gnu11 -g -fsanitize=address,undefined -Itests/ws_subscriptions/stubs -I" cc -std=gnu11 -g -fsanitize=address,undefined -Wno-deprecated-declarations -Icomponents/ts_core/ts_event/include -Itests/ws_subscriptions/stubs -Icomponents/ts_core/ts_event/src -I"$cjson" -I"$build" tests/ws_subscriptions/test_reviewer_core.c -o "$build/core" "$build/core" -cc -std=gnu11 -g -fsanitize=address,undefined -Itests/ws_subscriptions/stubs -I"$cjson" -I"$build" tests/ws_subscriptions/test_reviewer_http.c -o "$build/http" +cc -std=gnu11 -g -fsanitize=address,undefined -Itests/ws_subscriptions/stubs -Icomponents/ts_net/include -I"$cjson" -I"$build" tests/ws_subscriptions/test_reviewer_http.c -o "$build/http" "$build/http" diff --git a/tests/ws_subscriptions/stubs/esp_https_server.h b/tests/ws_subscriptions/stubs/esp_https_server.h new file mode 100644 index 00000000..5761018c --- /dev/null +++ b/tests/ws_subscriptions/stubs/esp_https_server.h @@ -0,0 +1,2 @@ +#pragma once +#include "platform.h" diff --git a/tests/ws_subscriptions/stubs/platform.h b/tests/ws_subscriptions/stubs/platform.h index e19315bf..490d3500 100644 --- a/tests/ws_subscriptions/stubs/platform.h +++ b/tests/ws_subscriptions/stubs/platform.h @@ -59,7 +59,7 @@ typedef struct {void*data;size_t data_size;int id;} ts_event_t; #define TS_EVENT_BASE_OTA "ota" #define TS_EVENT_SYSTEM_INFO_CHANGED 1 #define TS_EVENT_DEVICE_STATUS_CHANGED 2 -#define TS_EVENT_OTA_PROGRESS_UPDATE 3 +#include "../../../components/ts_core/ts_event/include/ts_ota_events.h" #ifdef TEST_FAIL_EVENTS extern int test_event_fail_at, test_event_registers; #endif @@ -95,8 +95,10 @@ static inline int ts_event_unregister_sync(void*h,unsigned t) {(void)h;(void)t;r #endif typedef void *httpd_handle_t; typedef struct {httpd_handle_t handle;void*sess_ctx;void(*free_ctx)(void*);int fd;int method;void*user_ctx;const char*uri;size_t content_len;} httpd_req_t; -typedef struct {int type;uint8_t*payload;size_t len;} httpd_ws_frame_t; +typedef struct {bool final,fragmented;int type;uint8_t*payload;size_t len;} httpd_ws_frame_t; #define HTTPD_WS_TYPE_TEXT 1 +#define HTTPD_WS_TYPE_PING 9 +#define HTTPD_WS_TYPE_PONG 10 #define HTTPD_WS_CLIENT_WEBSOCKET 2 static inline int httpd_req_to_sockfd(httpd_req_t*r) {return r->fd;} int httpd_ws_get_fd_info(httpd_handle_t,int); diff --git a/tests/ws_subscriptions/stubs/ts_api_params.h b/tests/ws_subscriptions/stubs/ts_api_params.h new file mode 100644 index 00000000..0ab5a407 --- /dev/null +++ b/tests/ws_subscriptions/stubs/ts_api_params.h @@ -0,0 +1,3 @@ +#pragma once +/* Compile the real shared parser; only platform dependencies are synthetic. */ +#include "../../../components/ts_api/include/ts_api_params.h" diff --git a/tests/ws_subscriptions/stubs/ts_ota.h b/tests/ws_subscriptions/stubs/ts_ota.h new file mode 100644 index 00000000..e781a65f --- /dev/null +++ b/tests/ws_subscriptions/stubs/ts_ota.h @@ -0,0 +1 @@ +#include "../../../components/ts_ota/include/ts_ota.h" diff --git a/tests/ws_subscriptions/stubs/ts_ota_events.h b/tests/ws_subscriptions/stubs/ts_ota_events.h new file mode 100644 index 00000000..640f0916 --- /dev/null +++ b/tests/ws_subscriptions/stubs/ts_ota_events.h @@ -0,0 +1 @@ +#include "../../../components/ts_core/ts_event/include/ts_ota_events.h" diff --git a/tests/ws_subscriptions/test_control.c b/tests/ws_subscriptions/test_control.c index a72d5d1e..a068e79c 100644 --- a/tests/ws_subscriptions/test_control.c +++ b/tests/ws_subscriptions/test_control.c @@ -15,7 +15,7 @@ static bool ownership_case(void){ ssh_cleanup();shell_task.fn(shell_task.arg);finish_all();return ok; } static bool early_cancel_case(void){ - setup();uint32_t id;assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + setup();uint32_t id;assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); unsigned before=commands_submitted;assert(ts_webui_ssh_exec_cancel(id)==ESP_OK);exec_task.fn(exec_task.arg);finish_all();return commands_submitted==before; } static uint32_t target_id; @@ -73,17 +73,17 @@ static void cancellation_phases(void){ const char *phases[]={"key","create","connect","auth","submit","C02","C03","C04"}; for(unsigned i=0;ifn(host_timer);cancel_now();} static void intersecting_failures(void){ setup();unsigned c=cancelled_frames; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&target_id)==0); + assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&target_id)==0); remote_hook=observe_then_cancel;exec_task.fn(exec_task.arg);remote_hook=NULL; finish_all();assert(cancelled_frames==c+2); /* delivery failure cannot hide the real cancellation result */ setup();unsigned t=timeout_frames;c=cancelled_frames; - ts_webui_ssh_options_t opts={.timeout_ms=1000,.collect_output=true}; + ts_webui_ssh_options_t opts={.owner_session_id=7,.timeout_ms=1000,.collect_output=true}; assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&opts,&target_id)==0); remote_hook=timeout_then_cancel;exec_task.fn(exec_task.arg);remote_hook=NULL;finish_all(); assert(timeout_frames==t+2 && cancelled_frames==c); @@ -127,13 +127,22 @@ static void intersecting_failures(void){ } static void api_controls(void){ s_op_sequence=0x80000000u; /* valid public uint32 IDs must not pass through signed valueint */ - setup();assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&target_id)==0); + setup();ts_webui_ssh_receipt_t receipt;ts_webui_ssh_options_t options={.owner_session_id=7,.receipt=&receipt,.collect_output=true}; + assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&target_id)==0); const char *bad[]={"{}","{\"session_id\":0}","{\"session_id\":-1}","{\"session_id\":1.5}","{\"session_id\":4294967296}","{\"session_id\":\"1\"}"}; for(unsigned i=0;iop));} cJSON *j=cJSON_CreateObject();cJSON_AddNumberToObject(j,"session_id",target_id); + ts_api_result_t denied={0};assert(api_ssh_cancel(j,&denied)!=0);assert(!ts_ws_op_cancelled(((ssh_exec_task_params_t*)exec_task.arg)->op)); + cJSON_AddStringToObject(j,"boot_id",receipt.boot_id);cJSON_AddStringToObject(j,"result_key",receipt.result_key); + for(unsigned byte=0;byte<32;byte++){ + cJSON *key=cJSON_GetObjectItem(j,"result_key");key->valuestring[byte]^=1;denied=(ts_api_result_t){0};assert(api_ssh_cancel(j,&denied)!=0);key->valuestring[byte]^=1; + cJSON *boot=cJSON_GetObjectItem(j,"boot_id");boot->valuestring[byte]^=1;denied=(ts_api_result_t){0};assert(api_ssh_cancel(j,&denied)!=0);boot->valuestring[byte]^=1; + assert(!ts_ws_op_cancelled(((ssh_exec_task_params_t*)exec_task.arg)->op)); + } + ts_api_result_t r={0};assert(api_ssh_cancel(j,&r)==0 && cJSON_IsTrue(cJSON_GetObjectItem(r.data,"cancelled")));cJSON_Delete(r.data); exec_task.fn(exec_task.arg);drive_all();r=(ts_api_result_t){0};assert(api_ssh_cancel(j,&r)!=0);cJSON_Delete(j);finish_all(); - puts("PASS actual ssh.cancel API exact-ID validation and accepted-intent response; ended operations reject without wildcard control"); + puts("PASS actual ssh.cancel API exact unsigned ID + private boot/result receipt; missing/64 mutated receipt bytes cause no cancellation; owner retry accepts intent, completed jobs reject"); } int main(int argc,char **argv){ cJSON_Hooks h={tracked_malloc,tracked_free};cJSON_InitHooks(&h);sent_hook=result_observe; diff --git a/tests/ws_subscriptions/test_exec_api.c b/tests/ws_subscriptions/test_exec_api.c index 8266b501..0dfa5b06 100644 --- a/tests/ws_subscriptions/test_exec_api.c +++ b/tests/ws_subscriptions/test_exec_api.c @@ -29,5 +29,30 @@ int main(void){ opts.receipt=&second;assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&opts,&b)==ESP_OK); char *result=ts_webui_ssh_exec_status(a,first.boot_id,first.result_key,NULL);assert(result&&strstr(result,"ssh_exec_done"));tracked_free(result); exec_task.fn(exec_task.arg);drive_all();assert(!ts_webui_ssh_exec_status(a,first.boot_id,first.result_key,NULL));finish_all(); + /* A leaked receipt cannot delegate an externally owned operation to another login. */ + for(unsigned mode=0;mode<3;mode++){ + bool cancel=mode!=0; + setup();cJSON *request=cJSON_Parse("{\"host\":\"fake\",\"user\":\"u\",\"password\":\"p\",\"command\":\"cmd\",\"owner_session_id\":8,\"caller_session_id\":8,\"session_id\":8,\"role\":\"root\"}");ts_api_result_t start_reply={0}; + assert(api_ssh_exec_stream_for_session(request,7,&start_reply)==ESP_OK);cJSON_Delete(request); + ssh_exec_task_params_t *params=exec_task.arg;assert(params->record->owner_session_id==7);assert(!cJSON_GetObjectItem(start_reply.data,"owner_session_id")); + cJSON *control=cJSON_Duplicate(start_reply.data,true);assert(control); + if(mode==2){cJSON_DeleteItemFromObject(control,"boot_id");cJSON_DeleteItemFromObject(control,"result_key");} + for(unsigned other=0;other<10;other++)if(other!=7){ + ts_api_result_t denied={0};assert(api_ssh_exec_status_for_session(start_reply.data,other,&denied)!=ESP_OK&&denied.code==TS_API_ERR_NOT_FOUND); + denied=(ts_api_result_t){0};assert(api_ssh_cancel_for_session(control,other,&denied)!=ESP_OK&&denied.code==TS_API_ERR_NOT_FOUND);assert(!ts_ws_op_cancelled(params->op)); + } + ts_api_result_t owner_reply={0};assert(api_ssh_exec_status_for_session(start_reply.data,7,&owner_reply)==ESP_OK);cJSON_Delete(owner_reply.data); + if(mode==2){ + ts_api_result_t denied={0};assert(api_ssh_cancel(control,&denied)!=ESP_OK); + cJSON *partial=cJSON_Duplicate(control,true);cJSON_AddStringToObject(partial,"boot_id","bad"); + denied=(ts_api_result_t){0};assert(api_ssh_cancel_for_session(partial,7,&denied)!=ESP_OK);cJSON_Delete(partial);assert(!ts_ws_op_cancelled(params->op)); + } + if(cancel){owner_reply=(ts_api_result_t){0};assert(api_ssh_cancel_for_session(control,7,&owner_reply)==ESP_OK);cJSON_Delete(owner_reply.data);} + cJSON_Delete(control); + unsigned submitted=commands_submitted;exec_task.fn(exec_task.arg);drive_all();assert(commands_submitted==submitted+!cancel); + ts_api_result_t denied={0};assert(api_ssh_exec_status_for_session(start_reply.data,8,&denied)!=ESP_OK&&denied.code==TS_API_ERR_NOT_FOUND); + owner_reply=(ts_api_result_t){0};assert(api_ssh_exec_status_for_session(start_reply.data,7,&owner_reply)==ESP_OK);cJSON_Delete(owner_reply.data);cJSON_Delete(start_reply.data);finish_all(); + } + puts("PASS real private EXEC callbacks: original UI ID-only cancel works for its initiating login; other sessions including zero cannot query/cancel with or without the receipt; unbound/partial controls rejected; owner completion/cancel and final result remain usable"); puts("PASS real initiation/status API: allocation sweep prepares receipt before submit, exact owned lookup, current plus latest only, completion evicts older result"); } diff --git a/tests/ws_subscriptions/test_exec_ownership.c b/tests/ws_subscriptions/test_exec_ownership.c new file mode 100644 index 00000000..5c618e8b --- /dev/null +++ b/tests/ws_subscriptions/test_exec_ownership.c @@ -0,0 +1,81 @@ +/* Whole production WS/controller/transport, authenticated synthetic I/O. */ +#define OP_ADAPTER_NO_MAIN +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 +#include "test_operation_adapter.c" +static bool owner_live=true; +static ts_perm_level_t owner_level=TS_PERM_ROOT; +esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){ + if(sid<7||sid>11||(sid==7&&!owner_live))return ESP_ERR_NOT_FOUND; + ts_perm_level_t levels[]={TS_PERM_ROOT,TS_PERM_ROOT,TS_PERM_ADMIN,TS_PERM_READ,TS_PERM_WRITE}; + if(out)*out=(ts_session_t){.session_id=sid,.level=sid==7?owner_level:levels[sid-7]};return ESP_OK; +} +esp_err_t ts_auth_validate_request(const char *header,uint32_t *sid,ts_perm_level_t *level){ + const char *tokens[]={"Bearer owner","Bearer other","Bearer admin","Bearer read","Bearer write"}; + for(unsigned i=0;i<5;i++)if(!strcmp(header,tokens[i])){ts_session_t s;if(ts_security_validate_session(i+7,&s)!=ESP_OK)return ESP_ERR_NOT_FOUND;*sid=i+7;*level=s.level;return ESP_OK;}return ESP_ERR_NOT_FOUND; +} +static ts_ws_peer_t bound_peer(int fd){return *(ts_ws_peer_t*)reqs[fd].sess_ctx;} +static void authenticate(int fd,const char *token){ + char text[128];snprintf(text,sizeof(text),"{\"type\":\"auth\",\"token\":\"%s\",\"owner_session_id\":7,\"level\":4}",token); + reqs[fd].method=1;incoming=text;current=(void*)3;assert(ws_handler(&reqs[fd])==ESP_OK);incoming=NULL;current=(void*)1;assert(strstr(payloads[fd],"auth_ok")); +} +static unsigned raw[32],matches[32],done[32]; +static void observe_private(httpd_ws_frame_t *f){ + cJSON *m=cJSON_ParseWithLength((char*)f->payload,f->len);assert(m);const cJSON *t=cJSON_GetObjectItem(m,"type"); + if(cJSON_IsString(t)&&!strncmp(t->valuestring,"ssh_exec_",9)){raw[sent_fd]++;if(!strcmp(t->valuestring,"ssh_exec_match"))matches[sent_fd]++;if(!strcmp(t->valuestring,"ssh_exec_done"))done[sent_fd]++;assert(!cJSON_HasObjectItem(m,"boot_id")&&!cJSON_HasObjectItem(m,"result_key"));}cJSON_Delete(m); +} +static void private_setup(void){ + setup();owner_live=true;owner_level=TS_PERM_ROOT;memset(raw,0,sizeof(raw));memset(matches,0,sizeof(matches));memset(done,0,sizeof(done));sent_hook=observe_private; + for(int fd=3;fd<=8;fd++)open_peer(fd); + authenticate(1,"owner");authenticate(2,"owner");authenticate(3,"other");authenticate(4,"admin");authenticate(5,"read");authenticate(6,"write");authenticate(8,"read"); + assert(ts_ws_peer_authorized(bound_peer(3),TS_PERM_ROOT));assert(!ts_ws_peer_authorized_for_session(bound_peer(3),TS_PERM_ROOT,7)); + ts_ws_peer_t peers[TS_WS_CONNECTIONS];assert(ts_ws_peer_snapshot_for_session(peers,TS_WS_CONNECTIONS,TS_PERM_ROOT,7)==2);assert(!ts_ws_peer_snapshot_for_session(peers,TS_WS_CONNECTIONS,TS_PERM_ROOT,0)); +} +static void no_other_receivers(void){for(unsigned fd=3;fd<=8;fd++)assert(raw[fd]==0);} +static void matching_output(void){ssh_exec_task_params_t *p=exec_task.arg;ssh_exec_output_callback("REA",3,false,p);drive_all();ssh_exec_output_callback("DY value=",9,false,p);ssh_exec_output_callback("42;",3,false,p);assert(p->output_buffer&&strstr(p->output_buffer,"READY value=42;"));drive_all();} +static void run_business(unsigned owner, bool zero_observers){ + ts_webui_ssh_receipt_t receipt={0};ts_webui_ssh_options_t options={.owner_session_id=owner,.receipt=&receipt,.collect_output=true,.expect_pattern="READY",.extract_pattern="value=(.*);",.var_name="fake"}; + unsigned submitted=commands_submitted,writes=variable_writes;uint32_t id; + remote_hook=matching_output;assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==ESP_OK); + exec_task.fn(exec_task.arg);remote_hook=NULL;drive_all();assert(commands_submitted==submitted+1&&variable_writes>writes+7); + char *text=ts_webui_ssh_exec_status_for_session(id,receipt.boot_id,receipt.result_key,owner,NULL);assert(text); + cJSON *result=cJSON_Parse(text);tracked_free(text);assert(result&&cJSON_GetObjectItem(result,"output_bytes")->valuedouble>=15); + assert(!strcmp(cJSON_GetObjectItem(result,"execution_status")->valuestring,"success")&&cJSON_IsTrue(cJSON_GetObjectItem(result,"expect_matched"))&&!strcmp(cJSON_GetObjectItem(result,"extracted")->valuestring,"42"));cJSON_Delete(result);assert(!strcmp(stored_extract,"42")); + no_other_receivers();if(zero_observers)assert(!raw[1]&&!raw[2]);else{assert(raw[1]&&raw[2]&&matches[1]&&matches[2]&&done[1]==1&&done[2]==1);} + finish_all(); +} +static void queued_checks(unsigned mode){ + private_setup();ts_webui_ssh_receipt_t receipt;ts_webui_ssh_options_t options={.owner_session_id=7,.receipt=&receipt};uint32_t id; + assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==ESP_OK);ssh_exec_task_params_t *p=exec_task.arg; + ts_ws_output_ticket_t ticket;assert(ts_ws_op_output_begin(p->op,&ticket)&&ticket.count==2); + ts_ws_op_output_finish(&ticket,"{\"type\":\"ssh_exec_output\",\"data\":\"queued private\"}"); + if(mode==0)owner_live=false; + if(mode==1)owner_level=TS_PERM_ADMIN; + if(mode==2){close_peer(1);open_peer(1);authenticate(1,"other");} + pump();no_other_receivers();assert(!raw[1]);if(mode==2)assert(raw[2]==1);else assert(!raw[2]); + ts_ws_op_stats_t stats;ts_ws_op_stats(TS_WS_OP_EXEC,&stats);assert(!stats.unsettled&&stats.failed==(mode==2)&&ts_ws_op_business_running(p->op)); + if(mode==2){close_peer(1);open_peer(1);authenticate(1,"owner");} + owner_live=true;owner_level=TS_PERM_ROOT;unsigned before=commands_submitted; + exec_task.fn(exec_task.arg);drive_all();assert(commands_submitted==before+1);no_other_receivers();if(mode==2)assert(raw[1]&&done[1]==1); + finish_all(); +} +static void expire_before_final(void){owner_live=false;} +static void final_delivery_check(void){ + private_setup();ts_webui_ssh_receipt_t receipt;ts_webui_ssh_options_t options={.owner_session_id=7,.receipt=&receipt};uint32_t id;unsigned submitted=commands_submitted; + assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==ESP_OK); + barrier_name="B08";barrier_action=expire_before_final;exec_task.fn(exec_task.arg);drive_all();assert(!barrier_action&&commands_submitted==submitted+1&&!done[1]&&!done[2]);no_other_receivers(); + char *result=ts_webui_ssh_exec_status(id,receipt.boot_id,receipt.result_key,NULL);assert(result&&strstr(result,"ssh_exec_done"));tracked_free(result);owner_live=true;finish_all(); +} +int main(void){ + cJSON_Hooks hooks={tracked_malloc,tracked_free};cJSON_InitHooks(&hooks); + private_setup();run_business(7,false); + private_setup();close_peer(1);close_peer(2);run_business(7,true); + private_setup();run_business(0,true); + for(unsigned i=0;i<3;i++)queued_checks(i); + final_delivery_check(); + private_setup();ts_ws_message_t *m=ts_ws_message_text("{\"type\":\"ssh_exec_output\"}",strlen("{\"type\":\"ssh_exec_output\"}"));assert(m);ts_ws_message_require(m,TS_PERM_ROOT);ts_ws_message_require_session(m,7); + assert(ts_ws_transport_submit(bound_peer(3),m,0,0,NULL,NULL)==ESP_OK);ts_ws_message_release(m);pump();assert(!raw[3]); + /* A zero-owner restriction remains deny-all even if submitted directly. */ + m=ts_ws_message_text("{\"type\":\"ssh_exec_output\"}",strlen("{\"type\":\"ssh_exec_output\"}"));assert(m);ts_ws_message_require_session(m,0);assert(ts_ws_transport_submit(bound_peer(1),m,0,0,NULL,NULL)==ESP_OK);ts_ws_message_release(m);pump();assert(!raw[1]); + finish_all(); + puts("PASS private EXEC: only same-session Root receives start/bytes/match/final; other Root/Admin/READ/WRITE/unbound/forged peers see zero; queued revoke/downgrade/fd reuse rechecked; reconnect works; zero observers/internal owner=0 preserve actual command/result/extraction/variable writes"); +} diff --git a/tests/ws_subscriptions/test_exec_results.c b/tests/ws_subscriptions/test_exec_results.c index 5887b0fe..8682f453 100644 --- a/tests/ws_subscriptions/test_exec_results.c +++ b/tests/ws_subscriptions/test_exec_results.c @@ -33,7 +33,7 @@ int main(void){ for(mode=0;mode<6;mode++){ setup();memset(lengths,0,sizeof(lengths));sent_hook=capture;remote_hook=produce; if(mode==2)send_fail_fd=2; - ts_webui_ssh_receipt_t receipt;ts_webui_ssh_options_t options={.receipt=&receipt,.collect_output=true,.extract_pattern=mode==4?"value=(.*)":mode==5?"missing=(.*);":NULL,.max_output_size=mode>=4?1024:65536};uint32_t id;unsigned before=commands_submitted; + ts_webui_ssh_receipt_t receipt;ts_webui_ssh_options_t options={.owner_session_id=7,.receipt=&receipt,.collect_output=true,.extract_pattern=mode==4?"value=(.*)":mode==5?"missing=(.*);":NULL,.max_output_size=mode>=4?1024:65536};uint32_t id;unsigned before=commands_submitted; assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==ESP_OK); char *status=ts_webui_ssh_exec_status(id,receipt.boot_id,receipt.result_key,NULL);assert(status&&strstr(status,"ssh_exec_running"));tracked_free(status); assert(!ts_webui_ssh_exec_status(id,receipt.boot_id,"00000000000000000000000000000000",NULL)); diff --git a/tests/ws_subscriptions/test_f1_f2.c b/tests/ws_subscriptions/test_f1_f2.c index d27086cb..ec73d348 100644 --- a/tests/ws_subscriptions/test_f1_f2.c +++ b/tests/ws_subscriptions/test_f1_f2.c @@ -36,7 +36,11 @@ int main(int argc,char**argv){ } if(!strcmp(argv[1],"exec") || !strcmp(argv[1],"continuous")){ bool partial=!strcmp(argv[1],"exec");if(partial)open_peer(2);uint32_t id; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0);ssh_exec_task_params_t *params=exec_task.arg; + /* Output tests opt into the initiating identity; internal ownerless Exec + * deliberately has no browser observers after the privacy fix. */ + if(partial)assert(ts_ws_peer_bind_session(*(ts_ws_peer_t*)reqs[2].sess_ctx,7)==ESP_OK); + ts_webui_ssh_options_t options={.owner_session_id=7,.collect_output=true}; + assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==0);ssh_exec_task_params_t *params=exec_task.arg; if(!partial)queue_fail=true; ssh_exec_output_callback("part",4,false,params); /* Exec output is staged by the callback and published by worker maintenance. */ diff --git a/tests/ws_subscriptions/test_http_auth.c b/tests/ws_subscriptions/test_http_auth.c index 33d1f062..91a982f0 100644 --- a/tests/ws_subscriptions/test_http_auth.c +++ b/tests/ws_subscriptions/test_http_auth.c @@ -10,6 +10,9 @@ #define API_PREFIX "/api/v1" #define HTTPD_SOCK_ERR_TIMEOUT -2 #define HTTPD_500_INTERNAL_SERVER_ERROR 500 +#define HTTPD_404_NOT_FOUND 404 +#define HTTPD_405_METHOD_NOT_ALLOWED 405 +typedef int httpd_err_code_t; #define ESP_LOG_ERROR 1 static unsigned body_reads, body_allocations, handled; static int response_status; @@ -18,14 +21,18 @@ static void *body_malloc(size_t n) {body_allocations++;return malloc(n);} #define TS_MALLOC_PSRAM body_malloc static void esp_log_level_set(const char *tag,int level) {(void)tag;(void)level;} typedef struct {const char *uri;int method;esp_err_t(*handler)(httpd_req_t*);void *user_ctx;} httpd_uri_t; -typedef struct {unsigned server_port,max_uri_handlers,recv_wait_timeout,send_wait_timeout,stack_size,task_caps;int max_open_sockets,keep_alive_idle,keep_alive_interval,keep_alive_count;bool keep_alive_enable,lru_purge_enable;void *uri_match_fn,*global_user_ctx,*global_user_ctx_free_fn,*global_transport_ctx,*global_transport_ctx_free_fn;esp_err_t(*open_fn)(httpd_handle_t,int);} httpd_config_t; +typedef struct {unsigned server_port,ctrl_port,max_uri_handlers,recv_wait_timeout,send_wait_timeout,stack_size,task_caps;int max_open_sockets,keep_alive_idle,keep_alive_interval,keep_alive_count;bool keep_alive_enable,lru_purge_enable;void *uri_match_fn,*global_user_ctx,*global_user_ctx_free_fn,*global_transport_ctx,*global_transport_ctx_free_fn;esp_err_t(*open_fn)(httpd_handle_t,int);} httpd_config_t; #define HTTPD_DEFAULT_CONFIG() ((httpd_config_t){.server_port=80}) #define MALLOC_CAP_INTERNAL 4 static void *httpd_uri_match_wildcard; -static esp_err_t httpd_start(httpd_handle_t *handle,const httpd_config_t *config) {(void)config;*handle=(void*)11;return ESP_OK;} -static esp_err_t httpd_stop(httpd_handle_t handle) {(void)handle;return ESP_OK;} +static unsigned primary_sdk_stops; +static esp_err_t httpd_start(httpd_handle_t *handle,const httpd_config_t *config) { + assert(config->ctrl_port==32768&&config->server_port==80);*handle=(void*)11;return ESP_OK; +} +static esp_err_t httpd_stop(httpd_handle_t handle) {assert(handle==(void*)11);primary_sdk_stops++;return ESP_OK;} + static httpd_uri_t captured[64];static unsigned route_count; -static esp_err_t httpd_register_uri_handler(httpd_handle_t handle,const httpd_uri_t *route) {(void)handle;captured[route_count++]=*route;return ESP_OK;} +static esp_err_t httpd_register_uri_handler(httpd_handle_t handle,const httpd_uri_t *route) {assert(handle==(void*)11);captured[route_count++]=*route;return ESP_OK;} static esp_err_t httpd_unregister_uri_handler(httpd_handle_t h,const char *uri,int method) {(void)h;(void)uri;(void)method;return ESP_OK;} static int httpd_req_recv(httpd_req_t *req,char *body,size_t size) {(void)req;body_reads++;memset(body,'x',size);return (int)size;} static esp_err_t httpd_resp_set_status(httpd_req_t *req,const char *status) {(void)req;response_status=atoi(status);return ESP_OK;} @@ -58,6 +65,10 @@ esp_err_t ts_auth_validate_request(const char *header,uint32_t *sid,ts_perm_leve int httpd_ws_get_fd_info(httpd_handle_t h,int fd){(void)h;(void)fd;return 0;} static int httpd_get_client_list(httpd_handle_t h,size_t *n,int *fds){(void)h;(void)fds;*n=0;return ESP_OK;} static int httpd_ws_send_frame(httpd_req_t *req,httpd_ws_frame_t *frame){(void)req;(void)frame;return ESP_OK;} +#include "ts_http_server.h" +/* SDK receive-budget hook and Origin policy have separate whole-policy suites. */ +void ts_httpd_set_body_receive_budget(uint32_t ms){(void)ms;} +esp_err_t ts_http_validate_browser_request(httpd_req_t *req,char *out,size_t size){(void)req;if(out&&size)out[0]=0;return ESP_OK;} #include "ts_http_server.c" static esp_err_t upload_handler(ts_http_request_t *req,void *user_data) { assert(user_data==NULL);assert(req->body_len==4&&!memcmp(req->body,"xxxx",4));handled++;return ts_http_send_json(req,200,"{\"status\":\"success\"}"); @@ -65,8 +76,9 @@ static esp_err_t upload_handler(ts_http_request_t *req,void *user_data) { static void request(unsigned index,const char *token,bool allowed) { unsigned reads=body_reads,allocations=body_allocations,handlers=handled;response_status=0;authorization=token; httpd_req_t req={.handle=(void*)11,.method=HTTP_POST,.uri=captured[index].uri,.user_ctx=captured[index].user_ctx,.content_len=4}; - assert(captured[index].handler(&req)==ESP_OK); - assert(response_status==(allowed?200:401));assert(handled==handlers+allowed); + esp_err_t ret=captured[index].handler(&req);assert(allowed?ret==ESP_OK:ret!=ESP_OK); + int denied_status=token&&(!strcmp(token,"Bearer read")||!strcmp(token,"Bearer admin"))?403:401; + assert(response_status==(allowed?200:denied_status));assert(handled==handlers+allowed); assert(body_reads==reads+allowed&&body_allocations==allocations+allowed); } #define login_handler upload_handler @@ -77,9 +89,17 @@ static void request(unsigned index,const char *token,bool allowed) { #define ota_www_upload_handler upload_handler #define api_handler upload_handler #define options_handler upload_handler +/* Generic API admission is exercised in test_api_prebody.py; this unit + * isolates the full transport owner, dedicated route roles and body handling. */ +static bool api_admit(ts_http_request_t *req,void *data){(void)req;(void)data;return true;} #include "webui_route_registration.inc" -int main(void) { - assert(ts_http_server_start()==ESP_OK);assert(ts_webui_api_init()==ESP_OK); +#include "https_route_wrapper.inc" +static void exercise_routes(void) { + route_count=0; + assert(ts_http_server_start()==ESP_OK); + assert(ts_http_server_get_handle()==(void*)11); + assert(ts_http_server_start()==ESP_OK); + assert(ts_webui_api_init()==ESP_OK); unsigned uploads=0,public_generic=0; for(unsigned i=0;irequired_level==TS_PERM_ADMIN);copy->requires_auth=false; + request(i,"Bearer read",false);request(i,"Bearer admin",true);request(i,"Bearer root",true);copy->requires_auth=true; + } +#else request(i,"Bearer read",true);request(i,"Bearer admin",true);request(i,"Bearer root",true); +#endif } if(!strcmp(uri,"/api/v1/*") && captured[i].method!=HTTP_OPTIONS) { public_generic++;assert(!s_registered_routes[i].requires_auth);request(i,NULL,true); } } assert(uploads==3&&public_generic==4);assert(ts_http_server_stop()==ESP_OK); - puts("PASS actual HTTP routes/wrapper: upload rejects before body/read/allocation; READ/Admin/Root and public generic routes unchanged (also auth-disabled build)"); + puts("PASS actual HTTP routes/wrapper: upload roles enforce original Admin file/firmware/WWW capability before body/read/allocation on HTTP and HTTPS; public generic routes unchanged (also auth-disabled build)"); +} + +int main(void){ + exercise_routes();assert(primary_sdk_stops==1&&!s_server&&!s_route_count); + puts("PASS complete original HTTP owner and dedicated upload roles; HTTPS wrapper admission also checked, SDK boundaries substituted"); } diff --git a/tests/ws_subscriptions/test_input_admission.c b/tests/ws_subscriptions/test_input_admission.c new file mode 100644 index 00000000..7d650323 --- /dev/null +++ b/tests/ws_subscriptions/test_input_admission.c @@ -0,0 +1,63 @@ +/* Entire production WS unit/controller/transport, synthetic credentials and socket I/O. */ +#define CONFIG_TS_WEBUI_AUTH_REQUIRED 1 +#define OP_ADAPTER_NO_MAIN +#include "test_operation_adapter.c" +#ifndef TS_WS_INPUT_MAX_BYTES +#define TS_WS_INPUT_MAX_BYTES (64 * 1024) +#endif +esp_err_t ts_security_validate_session(uint32_t sid,ts_session_t *out){if(sid!=7)return ESP_ERR_NOT_FOUND;if(out)*out=(ts_session_t){.session_id=7,.level=TS_PERM_ROOT};return ESP_OK;} +esp_err_t ts_auth_validate_request(const char *header,uint32_t *sid,ts_perm_level_t *level){if(strcmp(header,"Bearer root-token"))return ESP_ERR_NOT_FOUND;*sid=7;*level=TS_PERM_ROOT;return ESP_OK;} +static unsigned checks,failures; +static void *json_oom(size_t size){(void)size;return NULL;} +static void expect(bool ok,const char *label){checks++;if(!ok){failures++;fprintf(stderr,"FAIL %s\n",label);}} +static esp_err_t input(const char *body,size_t length,int type,bool final,bool override){ + incoming=body;incoming_length=length;incoming_type=type;incoming_final=final;incoming_override=override; + reqs[1].method=1;current=(void*)3;esp_err_t ret=ws_handler(&reqs[1]);current=(void*)1; + incoming=NULL;incoming_override=false;incoming_final=true;incoming_type=1;return ret; +} +static void shell_start(void){setup();const char *j="{\"type\":\"ssh_connect\",\"token\":\"root-token\",\"host\":\"fake\",\"user\":\"u\"}";assert(input(j,strlen(j),1,true,false)==ESP_OK&&ts_ws_op_busy());} +static void shell_finish(void){sent_hook=NULL;close_peer(1);shell_task.fn(shell_task.arg);finish_all();} +static int observed_type;static size_t observed_len;static uint8_t observed_control[125]; +static void observe_control(httpd_ws_frame_t *frame){observed_type=frame->type;observed_len=frame->len;if(frame->len<=sizeof(observed_control))memcpy(observed_control,frame->payload,frame->len);} +int main(void){ + cJSON_Hooks hooks={tracked_malloc,tracked_free};cJSON_InitHooks(&hooks); + const char *bad[]={"{","[]","null","{\"type\":\"ssh_input\",\"data\":\"probe\"}tail","{\"type\":\"ssh_input\",\"TYPE\":\"ping\",\"data\":\"probe\"}","{\"type\":\"ssh_input\",\"data\":\"probe\",\"data\":\"other\"}","{\"type\":\"ssh_input\",\"data\":\"probe\\u0000tail\"}"}; + shell_start(); + for(unsigned i=0;i=1&&scenario<=3?close_during_prepare:scenario==5?old_failure_exit:try_replace; ts_ws_output_ticket_t ticket; @@ -41,8 +41,8 @@ int main(void){ immediate=false;stop();assert(!live_allocations); } for(kind=0;kind +static char diagnostic_trace[65536]; +static size_t diagnostic_used; +static void capture_diagnostic(const char *tag,const char *format,...){ + (void)tag;if(diagnostic_used>=sizeof(diagnostic_trace)-1)return; + va_list args;va_start(args,format);int n=vsnprintf(diagnostic_trace+diagnostic_used,sizeof(diagnostic_trace)-diagnostic_used,format,args);va_end(args); + if(n>0)diagnostic_used+=(size_t)nhandle,r->fd,f);} static esp_err_t httpd_sess_trigger_close(httpd_handle_t h,int fd){(void)h;if(reqs[fd].sess_ctx)close_peer(fd);return ESP_OK;} static const char *incoming; -static int httpd_ws_recv_frame(httpd_req_t *r,httpd_ws_frame_t *f,size_t n){(void)r;if(!incoming)return ESP_FAIL;f->type=1;f->len=strlen(incoming);if(n)memcpy(f->payload,incoming,f->len);return 0;} +static bool incoming_override,incoming_final=true,incoming_read_fail; +static int incoming_type=1;static size_t incoming_length; +static unsigned input_headers,input_payloads; +static int httpd_ws_recv_frame(httpd_req_t *r,httpd_ws_frame_t *f,size_t n){ + (void)r;if(!incoming&&!incoming_override)return ESP_FAIL; + if(n)input_payloads++;else input_headers++; + f->type=incoming_type;f->final=incoming_final;f->len=incoming_override?incoming_length:strlen(incoming); + if(n){if(incoming_read_fail)return ESP_FAIL;assert(f->len<=n);if(f->len)memcpy(f->payload,incoming,f->len);}return 0; +} static size_t rejected_allocation_size; static void *adapter_malloc(size_t n){return rejected_allocation_size==n?NULL:tracked_malloc(n);} static void *host_heap_malloc(size_t n,unsigned caps){(void)caps;return adapter_malloc(n);} @@ -168,7 +191,12 @@ void ts_console_request_interrupt(void){} esp_err_t ts_log_add_callback(ts_log_callback_t cb,ts_log_level_t l,void *arg,ts_log_callback_handle_t *out){(void)cb;(void)l;(void)arg;*out=(void*)1;return 0;} static int remove_log_result; esp_err_t ts_log_remove_callback(ts_log_callback_handle_t h){(void)h;return remove_log_result;} -size_t ts_log_buffer_search(ts_log_entry_t *e,size_t n,ts_log_level_t min,ts_log_level_t max,const char *tag,const char *keyword){(void)e;(void)n;(void)min;(void)max;(void)tag;(void)keyword;return 0;} +static unsigned log_history_reads; +static void (*log_history_hook)(void); +size_t ts_log_buffer_search(ts_log_entry_t *e,size_t n,ts_log_level_t min,ts_log_level_t max,const char *tag,const char *keyword){ + (void)min;(void)max;(void)tag;(void)keyword;log_history_reads++;if(log_history_hook)log_history_hook();if(!n)return 0; + memset(e,0,sizeof(*e));e->level=TS_LOG_INFO;strcpy(e->message,"SYNTHETIC PRIVATE LOG");strcpy(e->tag,"fixture");strcpy(e->task_name,"fixture");return 1; +} httpd_handle_t ts_http_server_get_handle(void){return (void*)11;} void ts_http_server_set_stop_hooks(esp_err_t(*stop)(httpd_handle_t),void(*stopped)(httpd_handle_t)){(void)stop;(void)stopped;} static int adapter_create_caps(void(*fn)(void*),const char*n,unsigned stack,void*arg,unsigned p,TaskHandle_t*out,unsigned caps){ @@ -188,7 +216,12 @@ static void adapter_delete_caps(TaskHandle_t task){ } static void drive_all(void){for(unsigned i=0;i<12;i++){test_now+=100000;ts_ws_op_poll();pump();timer_pump();}assert(!timer_queued);} static void drive_matching_output(void){for(unsigned i=0;i<12;i++){ts_ws_op_poll();pump();timer_pump();}assert(!timer_queued);} -static void setup(void){variable_instance=1;variable_initialized=true;command_current=true;start();memset(s_clients,0,sizeof(s_clients));s_server=(void*)11;s_ws_stopping=false;ts_ws_op_enable();transport_server.closed=peer_closed;for(int fd=1;fd<=2;fd++){reqs[fd]=(httpd_req_t){.handle=(void*)11,.fd=fd};current=(void*)3;assert(add_client(&reqs[fd],WS_CLIENT_TYPE_EVENT)==ESP_OK);}current=(void*)1;} +static void setup(void){variable_instance=1;variable_initialized=true;command_current=true;start();memset(s_clients,0,sizeof(s_clients));s_server=(void*)11;s_ws_stopping=false;ts_ws_op_enable();transport_server.closed=peer_closed;for(int fd=1;fd<=2;fd++){reqs[fd]=(httpd_req_t){.handle=(void*)11,.fd=fd};current=(void*)3;assert(add_client(&reqs[fd],WS_CLIENT_TYPE_EVENT)==ESP_OK);}current=(void*)1; +#ifndef CONFIG_TS_WEBUI_AUTH_REQUIRED + /* Observable synthetic executions belong to identity 7, not every peer. */ + for(int fd=1;fd<=2;fd++)assert(ts_ws_peer_bind_session(*(ts_ws_peer_t*)reqs[fd].sess_ctx,7)==ESP_OK); +#endif +} static void finish_all(void){drive_all();assert(!ts_ws_op_busy());exec_cache_clear();stop();assert(!live_allocations);} static void connect_shell(void){cJSON *j=cJSON_Parse("{\"host\":\"fake\",\"user\":\"fake\"}");current=(void*)3;handle_ssh_connect(&reqs[1],j);current=(void*)1;cJSON_Delete(j);} static unsigned terminal_frames,output_frames,connected_frames,disconnecting_frames;static bool output_after_terminal; @@ -231,6 +264,11 @@ static void stop_progress_shell(void){ } progress(); } +/* Explicit private observation fixture; trusted internal owner=0 is tested separately. */ +static esp_err_t observed_exec_start(const char *host,uint16_t port,const char *user,const char *key,const char *password,const char *command,uint32_t *id){ + ts_webui_ssh_options_t options={.owner_session_id=7}; + return ts_webui_ssh_exec_start_ex(host,port,user,key,password,command,&options,id); +} static void operation_cross_tests(void){ uint32_t id;ts_ws_op_stats_t ledger; setup();connect_shell();unsigned dc=disconnecting_frames;incoming="{\"type\":\"ssh_disconnect\"}";reqs[1].method=1;current=(void*)3;assert(ws_handler(&reqs[1])==ESP_OK);current=(void*)1;incoming=NULL;shell_task.fn(shell_task.arg);finish_all();assert(disconnecting_frames==dc+1); @@ -245,7 +283,7 @@ static void operation_cross_tests(void){ puts("PASS G1 same observable assertion: old rejection callback cannot corrupt replacement Shell (whole production unit)"); setup();terminal_frames=output_frames=0;output_after_terminal=false; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); ssh_exec_task_params_t *params=exec_task.arg;ts_ws_peer_t peer=*(ts_ws_peer_t*)reqs[1].sess_ctx; m=ts_ws_message_text("block",5);assert(ts_ws_transport_submit(peer,m,0,0,NULL,NULL)==0);ts_ws_message_release(m); ssh_exec_output_callback("A",1,false,params);barrier_name="B02";barrier_action=g2_preparing_output; @@ -253,7 +291,7 @@ static void operation_cross_tests(void){ exec_task.fn(exec_task.arg);finish_all(); puts("PASS G2 revised result contract: observation failure while output prepares leaves execution OPEN; final result waits for actual completion"); - setup();terminal_frames=0;ts_webui_ssh_options_t opts={.timeout_ms=1000,.collect_output=true,.extract_pattern="value=(.*)",.var_name="fake"}; + setup();terminal_frames=0;ts_webui_ssh_options_t opts={.owner_session_id=7,.timeout_ms=1000,.collect_output=true,.extract_pattern="value=(.*)",.var_name="fake"}; assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&opts,&id)==0); timer_queue_fail=true;exec_task.fn(exec_task.arg);drive_all();assert(ts_ws_op_busy()); params=exec_task.arg;assert(params->timer_phase==2 && !params->session); @@ -287,10 +325,10 @@ static void operation_cross_tests(void){ puts("PASS original timeout and stop-on-match business abort semantics retained"); setup();before=aborts;remote_hook=cancel_original_exec; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); exec_task.fn(exec_task.arg);remote_hook=NULL;assert(aborts==before+1);finish_all(); setup();terminal_frames=0; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); params=exec_task.arg;barrier_name="B07";barrier_action=close_snapshot_joiner; if(ts_ws_op_close_begin(params->op))ts_ws_op_close_finish(params->op,"{\"type\":\"ssh_exec_done\"}"); drive_all();assert(!barrier_action && frames[3]==0 && terminal_frames==2); @@ -298,12 +336,12 @@ static void operation_cross_tests(void){ puts("PASS original cancel ID contract, user disconnecting status and frozen terminal recipient snapshot"); setup();close_peer(1);close_peer(2); - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); params=exec_task.arg;before=allocations;ssh_exec_output_callback("none",4,false,params);assert(allocations==before); exec_task.fn(exec_task.arg);finish_all(); puts("PASS no recipients: no observation JSON/payload allocation; business executes and tickets retire"); - setup();task_create_fail=true;assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==ESP_FAIL);task_create_fail=false;finish_all(); + setup();task_create_fail=true;assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==ESP_FAIL);task_create_fail=false;finish_all(); for(unsigned i=0;i<16;i++) { setup();fail_allocation=allocations+i+1; esp_err_t ret=ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&opts,&id);fail_allocation=0; @@ -311,7 +349,7 @@ static void operation_cross_tests(void){ } puts("PASS task-create and allocation failure sweep: all actual contexts, credentials, output buffers and reservations reclaimed"); for(unsigned i=0;i<48;i++) { - setup();assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); + setup();assert(observed_exec_start("fake",22,"u",NULL,"p","cmd",&id)==0); sent_hook=validate_exec_frame;params=exec_task.arg;fail_allocation=allocations+i+1; ssh_exec_output_callback("encoding",8,false,params);fail_allocation=0; exec_task.fn(exec_task.arg);finish_all(); @@ -336,7 +374,7 @@ static void replace_command_during_exec(void){command_current=false;} static void replace_variable_during_exec(void){++variable_instance;} static void foreground_identity_tests(void) { - ts_webui_ssh_options_t options={.collect_output=true,.extract_pattern="value=(.*)",.var_name="shared",.command_id="command-a",.command_instance=17}; + ts_webui_ssh_options_t options={.owner_session_id=7,.collect_output=true,.extract_pattern="value=(.*)",.var_name="shared",.command_id="command-a",.command_instance=17}; uint32_t id; for(unsigned scenario=0;scenario<4;++scenario){ setup();remote_hook=scenario==1?replace_command_during_exec:scenario==2?replace_variable_during_exec:NULL; @@ -365,7 +403,7 @@ static void full_command_tests(void){ memset(command,'x',length);memcpy(command,"bash -c '\n#",11);command[length-2]='\n';command[length-1]='\'';command[length]=0; memcpy(expected,command,length+1);expected_command=expected; setup();uint32_t id;unsigned submitted=commands_submitted; - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p",command,&id)==ESP_OK); + assert(observed_exec_start("fake",22,"u",NULL,"p",command,&id)==ESP_OK); /* The HTTP request can be freed before the task is scheduled. */ memset(command,'!',length);free(command); exec_task.fn(exec_task.arg);assert(commands_submitted==submitted+1);finish_all(); @@ -373,7 +411,7 @@ static void full_command_tests(void){ } setup();char command[1501];memset(command,'x',1500);command[1500]=0; uint32_t id=0;unsigned submitted=commands_submitted;rejected_allocation_size=sizeof(command); - assert(ts_webui_ssh_exec_start("fake",22,"u",NULL,"p",command,&id)==ESP_ERR_NO_MEM); + assert(observed_exec_start("fake",22,"u",NULL,"p",command,&id)==ESP_ERR_NO_MEM); rejected_allocation_size=0;assert(!id && commands_submitted==submitted);finish_all(); puts("PASS full async commands: 511/512/757/1500 bytes preserved after request release; allocation failure submits nothing and reclaims ownership"); } @@ -405,7 +443,7 @@ static void matching_regressions(void){ for(unsigned n=0;n<10;n++){unsigned scenario=scenarios[n]; setup();terminal_frames=0;matching_status[0]=matching_value[0]=0;matching_callbacks=0;sent_hook=observe_matching; noise[65533]='x';const char *parts[6]={noise,NULL}; - ts_webui_ssh_options_t options={.collect_output=true,.extract_pattern="value=(.*);",.stop_on_match=scenario==4||scenario==6}; + ts_webui_ssh_options_t options={.owner_session_id=7,.collect_output=true,.extract_pattern="value=(.*);",.stop_on_match=scenario==4||scenario==6}; if(scenario==0){options.expect_pattern="READY";parts[1]="READY";} if(scenario==1){options.fail_pattern="ERROR";parts[1]="ERROR";} if(scenario==2)parts[1]="value=42;"; @@ -438,10 +476,10 @@ int main(void){ ssh_send_output(ctx,"out",3);ssh_cleanup();shell_task.fn(shell_task.arg);finish_all();assert(!output_after_terminal); for(int f=0;f<5;f++){setup();terminal_frames=0;unsigned before=connected_frames;task_create_fail=f==0;close_during_create=f==1;remote_failure=f>=2?f-1:0;shell_task.fn=NULL;connect_shell();if(shell_task.fn)shell_task.fn(shell_task.arg);finish_all();assert(connected_frames==before);task_create_fail=close_during_create=false;remote_failure=0;} setup();terminal_frames=0;output_after_terminal=false;uint32_t id; - ts_webui_ssh_options_t opts={.collect_output=true,.timeout_ms=1000,.extract_pattern="value=(.*)",.var_name="fake"}; + ts_webui_ssh_options_t opts={.owner_session_id=7,.collect_output=true,.timeout_ms=1000,.extract_pattern="value=(.*)",.var_name="fake"}; assert(ts_webui_ssh_exec_start_ex("fake",22,"user",NULL,"password","cmd",&opts,&id)==0); exec_task.fn(exec_task.arg);drive_all();assert(terminal_frames==2 && !output_after_terminal && variable_writes);finish_all(); - setup();inline_exec=true;assert(ts_webui_ssh_exec_start("fake",22,"user",NULL,"password","cmd",&id)==0);inline_exec=false;finish_all(); + setup();inline_exec=true;assert(observed_exec_start("fake",22,"user",NULL,"password","cmd",&id)==0);inline_exec=false;finish_all(); for(unsigned i=0;i<10;i++){ setup();connect_shell();unsigned before=caps_deletes; ssh_cleanup();shell_task.fn(shell_task.arg); diff --git a/tests/ws_subscriptions/test_reviewer_http.c b/tests/ws_subscriptions/test_reviewer_http.c index f79434da..07d67c69 100644 --- a/tests/ws_subscriptions/test_reviewer_http.c +++ b/tests/ws_subscriptions/test_reviewer_http.c @@ -1,17 +1,22 @@ #include "platform.h" #define HTTP_GET 0 +#define HTTP_POST 1 +#define HTTP_PUT 2 +#define HTTP_DELETE 3 +#define HTTP_PATCH 4 +#include "ts_http_server.h" #define HTTPD_500_INTERNAL_SERVER_ERROR 500 #define HTTPD_SOCK_ERR_TIMEOUT -3 #define TS_MALLOC_PSRAM malloc static bool s_stopping; static const char *status; static unsigned called,read_body; -typedef struct{httpd_req_t*req;const char*uri;int method;char*body;size_t body_len;}ts_http_request_t; -typedef struct{int(*handler)(ts_http_request_t*,void*);void*user_data;}ts_http_route_t; static int httpd_resp_set_status(httpd_req_t*r,const char*s){(void)r;status=s;return 0;} static int httpd_resp_sendstr(httpd_req_t*r,const char*s){(void)r;(void)s;return 0;} static int httpd_resp_send_err(httpd_req_t*r,int e,const char*s){(void)r;(void)e;(void)s;return 0;} static int httpd_req_recv(httpd_req_t*r,char*b,size_t n){(void)r;(void)b;(void)n;read_body++;return -1;} +int ts_http_send_error(ts_http_request_t*r,int s,const char*m){(void)r;(void)s;(void)m;return 0;} +void ts_httpd_set_body_receive_budget(uint32_t timeout){assert(!timeout);} static int operation(ts_http_request_t*r,void*u){(void)r;(void)u;called++;return 0;} #include "reviewer_http.inc" int main(void){ diff --git a/tests/ws_subscriptions/test_terminal_auth.c b/tests/ws_subscriptions/test_terminal_auth.c index 7a9eb85e..84154aee 100644 --- a/tests/ws_subscriptions/test_terminal_auth.c +++ b/tests/ws_subscriptions/test_terminal_auth.c @@ -49,6 +49,20 @@ static void close_exec(ts_ws_operation_t *op) { } static void identity_and_delivery(void) { + setup();sent_hook=count_private; + admin_level=TS_PERM_NONE; + send_message(1,"{\"type\":\"auth\",\"token\":\"admin-token\"}"); + assert(strstr(payloads[1],"auth_error")&&!ts_ws_peer_authorized(peer(1),TS_PERM_READ)); + /* Even a trusted producer binding a still-valid enrollment session cannot + * deliver queued private data at READ, Admin or Root levels. */ + assert(ts_ws_peer_bind_session(peer(1),8)==ESP_OK); + httpd_ws_frame_t restricted={.type=HTTPD_WS_TYPE_TEXT,.payload=(uint8_t*)"{\"type\":\"output\",\"data\":\"private\"}",.len=0}; + restricted.len=strlen((char *)restricted.payload); + unsigned initial_private=private_frames; + assert(ts_ws_transport_send_private(peer(1),&restricted,TS_PERM_READ)==ESP_ERR_NOT_ALLOWED); + assert(ts_ws_transport_send_private(peer(1),&restricted,TS_PERM_ADMIN)==ESP_ERR_NOT_ALLOWED); + assert(ts_ws_transport_send_private(peer(1),&restricted,TS_PERM_ROOT)==ESP_ERR_NOT_ALLOWED); + finish_all();assert(private_frames==initial_private);admin_level=TS_PERM_ADMIN; setup();sent_hook=count_private; send_message(1,"{\"type\":\"auth\",\"token\":null}"); assert(strstr(payloads[1],"auth_error")&&!ts_ws_peer_authorized(peer(1),TS_PERM_READ)); @@ -58,14 +72,14 @@ static void identity_and_delivery(void) send_message(1,"{\"type\":\"auth\",\"token\":\"root-token\"}");assert(strstr(payloads[1],"auth_error")); send_message(2,"{\"type\":\"auth\",\"token\":\"root-token\"}"); esp_err_t error;ts_ws_operation_t *op=ts_ws_op_create(TS_WS_OP_EXEC,(ts_ws_peer_t){0},&error); - assert(op&&ts_ws_op_open(op));ts_ws_output_ticket_t ticket; - assert(ts_ws_op_output_begin(op,&ticket)&&ticket.count==2); + assert(op);ts_ws_op_set_exec_owner(op,7);assert(ts_ws_op_open(op));ts_ws_output_ticket_t ticket; + assert(ts_ws_op_output_begin(op,&ticket)&&ticket.count==1); unsigned before=private_frames,errors=auth_errors; ts_ws_transport_stats_t tx_before,tx_after;ts_ws_transport_get_stats(&tx_before); ts_ws_op_output_finish(&ticket,"{\"type\":\"ssh_exec_output\",\"data\":\"private\"}"); session_live=false;pump(); ts_ws_op_stats_t stats;ts_ws_op_stats(TS_WS_OP_EXEC,&stats); - assert(!stats.failed&&!stats.unsettled&&private_frames==before&&auth_errors==errors+2); + assert(!stats.failed&&!stats.unsettled&&private_frames==before&&auth_errors==errors+1); ts_ws_transport_get_stats(&tx_after);assert(tx_after.attempts==tx_before.attempts&&tx_after.success==tx_before.success); current=(void*)3;assert(!ts_ws_peer_authorized(peer(1),TS_PERM_READ));current=(void*)1; assert(auth_errors==errors+2); /* only one expiry notice per previous binding */ @@ -85,9 +99,9 @@ static void identity_and_delivery(void) assert(ts_ws_peer_bind_session(fresh,7)==ESP_OK);finish_all(); setup();send_message(1,"{\"type\":\"auth\",\"token\":\"admin-token\"}"); send_message(2,"{\"type\":\"auth\",\"token\":\"root-token\"}"); - op=ts_ws_op_create(TS_WS_OP_EXEC,(ts_ws_peer_t){0},&error);assert(op&&ts_ws_op_open(op)); - assert(ts_ws_op_output_begin(op,&ticket)&&ticket.count==2); - send_fail_fd=1;ts_ws_op_output_finish(&ticket,"{\"type\":\"ssh_exec_output\"}");pump();send_fail_fd=-1; + op=ts_ws_op_create(TS_WS_OP_EXEC,(ts_ws_peer_t){0},&error);assert(op);ts_ws_op_set_exec_owner(op,7);assert(ts_ws_op_open(op)); + assert(ts_ws_op_output_begin(op,&ticket)&&ticket.count==1); + send_fail_fd=2;ts_ws_op_output_finish(&ticket,"{\"type\":\"ssh_exec_output\"}");pump();send_fail_fd=-1; ts_ws_op_stats(TS_WS_OP_EXEC,&stats);assert(stats.failed); close_exec(op); puts("PASS WS token binding/roles, idempotence, one-binding history, queued revocation, public reuse and complete-peer fd reuse"); @@ -100,7 +114,7 @@ static void heartbeat_expiry(void) unsigned errors=auth_errors; admin_level=TS_PERM_READ;send_message(2,"{\"type\":\"ping\"}"); assert(auth_errors==errors&&strstr(payloads[2],"pong")&&ts_ws_peer_authorized(peer(2),TS_PERM_READ));admin_level=TS_PERM_ADMIN; - esp_err_t error;ts_ws_operation_t *op=ts_ws_op_create(TS_WS_OP_EXEC,(ts_ws_peer_t){0},&error);assert(op&&ts_ws_op_open(op)); + esp_err_t error;ts_ws_operation_t *op=ts_ws_op_create(TS_WS_OP_EXEC,(ts_ws_peer_t){0},&error);assert(op);ts_ws_op_set_exec_owner(op,7);assert(ts_ws_op_open(op)); session_live=false;unsigned before=frames[1];ts_ws_output_ticket_t ticket; assert(ts_ws_op_output_begin(op,&ticket)&&ticket.count==0);ts_ws_op_output_finish(&ticket,NULL); assert(frames[1]==before&&auth_errors==errors); /* no empty private message */ @@ -155,22 +169,54 @@ static void zero_observers(void) send_message(2,"{\"type\":\"auth\",\"token\":\"root-token\"}"); } if(observers)admin_level=TS_PERM_READ; - ts_webui_ssh_options_t options={.collect_output=true,.extract_pattern="value=(.*)",.var_name="fake"}; + ts_webui_ssh_options_t options={.owner_session_id=7,.collect_output=true,.extract_pattern="value=(.*)",.var_name="fake"}; unsigned writes=variable_writes,submitted=commands_submitted,before=private_frames,old_aborts=aborts; unsigned anon=private_by_fd[3],admin=private_by_fd[1],root=private_by_fd[2];uint32_t id;stored_extract[0]=0; assert(ts_webui_ssh_exec_start_ex("fake",22,"u",NULL,"p","cmd",&options,&id)==ESP_OK); exec_task.fn(exec_task.arg);finish_all(); assert(variable_writes>writes&&commands_submitted==submitted+1&&aborts==old_aborts&&!strcmp(stored_extract,"42")); assert(private_by_fd[3]==anon); - if(observers)assert(private_by_fd[1]>admin&&private_by_fd[2]>root); + if(observers)assert(private_by_fd[1]==admin&&private_by_fd[2]>root); else assert(private_frames==before); admin_level=TS_PERM_ADMIN; } - puts("PASS anonymous receives no private frames; normal READ/Admin+Root exec and zero observers both match/store 42 and finish without abort"); + puts("PASS anonymous receives no private frames; same-session Root-only exec and zero observers both match/store 42 and finish without abort"); } +static unsigned log_frames_by_fd[32],history_frames_by_fd[32]; +static void observe_logs(httpd_ws_frame_t *frame){ + cJSON *msg=cJSON_ParseWithLength((char*)frame->payload,frame->len);const char *type=cJSON_GetStringValue(cJSON_GetObjectItem(msg,"type")); + if(type&&!strcmp(type,"log"))log_frames_by_fd[sent_fd]++; + if(type&&!strcmp(type,"log_history"))history_frames_by_fd[sent_fd]++; + cJSON_Delete(msg); +} +static void logs_authorization(void){ + setup();session_live=true;admin_level=TS_PERM_ADMIN;sent_hook=observe_logs;open_peer(3); + const char *messages[]={"{\"type\":\"log_subscribe\",\"token\":\"root-token\",\"role\":\"root\"}","{\"type\":\"log_set_level\",\"minLevel\":5}","{\"type\":\"log_get_history\",\"limit\":5}"}; + unsigned before=log_history_reads; + for(unsigned i=0;i<3;i++){send_message(1,messages[i]);assert(strstr(payloads[1],"auth_error"));} + assert(log_history_reads==before&&s_clients[0].type!=WS_CLIENT_TYPE_LOG); + admin_level=TS_PERM_READ;send_message(1,"{\"type\":\"auth\",\"token\":\"admin-token\"}"); + for(unsigned level=TS_PERM_READ;level<=TS_PERM_WRITE;level++){ + admin_level=(ts_perm_level_t)level;for(unsigned i=0;i<3;i++){send_message(1,messages[i]);assert(strstr(payloads[1],"auth_error"));} + } + assert(log_history_reads==before&&s_clients[0].type!=WS_CLIENT_TYPE_LOG); + admin_level=TS_PERM_ADMIN;send_message(1,"{\"type\":\"log_subscribe\",\"minLevel\":5}");assert(strstr(payloads[1],"log_subscribed")); + send_message(1,messages[2]);assert(log_history_reads==before+1&&strstr(payloads[1],"SYNTHETIC PRIVATE LOG")); + send_message(2,"{\"type\":\"auth\",\"token\":\"root-token\"}");send_message(2,"{\"type\":\"log_subscribe\",\"minLevel\":5}");send_message(2,messages[2]);assert(strstr(payloads[2],"SYNTHETIC PRIVATE LOG")); + /* A future producer cannot bypass role checks by setting an anonymous log filter. */ + ts_ws_peer_log_level(peer(3),5);httpd_ws_frame_t log={.type=1,.payload=(uint8_t*)"{\"type\":\"log\",\"message\":\"fixture\"}",.len=strlen("{\"type\":\"log\",\"message\":\"fixture\"}")}; + unsigned admin=log_frames_by_fd[1],root=log_frames_by_fd[2],anon=log_frames_by_fd[3];assert(ts_ws_transport_log(&log,3)==ESP_OK);pump();assert(log_frames_by_fd[1]==admin+1&&log_frames_by_fd[2]==root+1&&log_frames_by_fd[3]==anon); + admin=log_frames_by_fd[1];root=log_frames_by_fd[2];assert(ts_ws_transport_log(&log,3)==ESP_OK);admin_level=TS_PERM_READ;pump();assert(log_frames_by_fd[1]==admin&&log_frames_by_fd[2]==root+1); + admin_level=TS_PERM_ADMIN;admin=log_frames_by_fd[1];root=log_frames_by_fd[2];assert(ts_ws_transport_log(&log,3)==ESP_OK);session_live=false;pump();assert(log_frames_by_fd[1]==admin&&log_frames_by_fd[2]==root); + session_live=true;finish_all(); + setup();sent_hook=observe_logs;send_message(1,"{\"type\":\"auth\",\"token\":\"admin-token\"}");unsigned history=history_frames_by_fd[1];log_history_hook=revoke; + send_message(1,messages[2]);assert(history_frames_by_fd[1]==history);log_history_hook=NULL;session_live=true;finish_all(); + puts("PASS enrollment NONE cannot bind private WS or receive READ/Admin/Root private frames"); + puts("PASS logs: anonymous/READ/WRITE cannot subscribe/filter/read history; Admin/Root keep log UI; queued role downgrade/revocation and expiry during history construction never deliver private logs"); +} int main(void) { cJSON_Hooks hooks={tracked_malloc,tracked_free};cJSON_InitHooks(&hooks); - identity_and_delivery();heartbeat_expiry();terminal_and_shell();zero_observers(); + identity_and_delivery();heartbeat_expiry();terminal_and_shell();zero_observers();logs_authorization(); } diff --git a/tests/ws_subscriptions/test_terminal_jobs.c b/tests/ws_subscriptions/test_terminal_jobs.c index 01ab7ba1..a427c127 100644 --- a/tests/ws_subscriptions/test_terminal_jobs.c +++ b/tests/ws_subscriptions/test_terminal_jobs.c @@ -1,10 +1,27 @@ #define OP_ADAPTER_NO_MAIN #include "test_operation_adapter.c" static int scenario; +static terminal_job_t *snapshot_job; +static char terminal_text[64]; +static void finish_after_snapshot(void) { + terminal_output_cb("tail\n",5,snapshot_job);snapshot_job->finished=true; +} +static void capture_terminal(httpd_ws_frame_t *f) { + cJSON *j=cJSON_ParseWithLength((char*)f->payload,f->len);assert(j); + cJSON *type=cJSON_GetObjectItem(j,"type"),*data=cJSON_GetObjectItem(j,"data"); + if(cJSON_IsString(type)&&!strcmp(type->valuestring,"output")&&cJSON_IsString(data)){ + assert(strlen(terminal_text)+strlen(data->valuestring)valuestring); + }cJSON_Delete(j); +} static void dispatch_terminal(int fd,const char *text){incoming=text;reqs[fd].method=1;current=(void*)3;assert(ws_handler(&reqs[fd])==0);current=(void*)1;incoming=NULL;} static void during_command(const ts_console_exec_context_t *ctx){ assert(ctx->remote); - if(scenario==0){ + if(scenario==2){ + snapshot_job=ctx->user_data;ctx->output("first\n",6,ctx->user_data); + barrier_name="terminal_output_snapshot";barrier_action=finish_after_snapshot; + terminal_job_maintain(snapshot_job); + assert(!barrier_action&&s_terminal_output_len==5&&ts_ws_op_is_open(snapshot_job->op)); + }else if(scenario==0){ assert(!ctx->cancelled(ctx->user_data));ctx->output("ready\n",6,ctx->user_data); dispatch_terminal(2,"{\"type\":\"ping\"}");assert(strstr(payloads[2],"pong")); dispatch_terminal(1,"{\"type\":\"terminal_input\",\"data\":\"second\"}");assert(strstr(payloads[1],"already running")); @@ -18,15 +35,16 @@ static void during_command(const ts_console_exec_context_t *ctx){ } int main(void){ cJSON_Hooks h={tracked_malloc,tracked_free};cJSON_InitHooks(&h); - for(scenario=0;scenario<2;scenario++){ + for(scenario=0;scenario<3;scenario++){ setup();s_terminal_client_fd=-1;s_output_mutex=xSemaphoreCreateMutex();s_terminal_output_buf=tracked_malloc(TERMINAL_OUTPUT_BUF_SIZE);s_terminal_output_len=0; current=(void*)3;assert(start_terminal_session(&reqs[1],NULL)==0);current=(void*)1; dispatch_terminal(1,"{\"type\":\"terminal_input\",\"data\":\"forward-fixture\"}"); - assert(exec_task.fn==terminal_job_task && !((terminal_job_t*)exec_task.arg)->finished);console_exec_hook=during_command; + assert(exec_task.fn==terminal_job_task && !((terminal_job_t*)exec_task.arg)->finished);console_exec_hook=during_command;if(scenario==2){terminal_text[0]=0;sent_hook=capture_terminal;} exec_task.fn(exec_task.arg);console_exec_hook=NULL;drive_all(); - if(!scenario)assert(strstr(payloads[1],"done")&&!ts_ws_op_busy()); + if(scenario==2){assert(!strcmp(terminal_text,"first\ntail\n")&&!ts_ws_op_busy());sent_hook=observe;} + else if(!scenario)assert(strstr(payloads[1],"done")&&!ts_ws_op_busy()); else{assert(!strstr(payloads[1],"must-not-reach"));current=(void*)3;assert(start_terminal_session(&reqs[1],NULL)==0);current=(void*)1;} tracked_free(s_terminal_output_buf);s_terminal_output_buf=NULL;vSemaphoreDelete(s_output_mutex);s_output_mutex=NULL;finish_ws(); } - puts("PASS real terminal worker: request returns before execution; HTTP ping/stop remain available; duplicate command rejected; disconnected/reused fd isolated; new terminal admitted after retirement"); + puts("PASS real terminal worker and completion/output interleaving: request returns before execution; HTTP ping/stop remain available; duplicate command rejected; disconnected/reused fd isolated; new terminal admitted after retirement"); } diff --git a/tests/ws_subscriptions/test_ws_log_privacy.c b/tests/ws_subscriptions/test_ws_log_privacy.c new file mode 100644 index 00000000..8c880af9 --- /dev/null +++ b/tests/ws_subscriptions/test_ws_log_privacy.c @@ -0,0 +1,21 @@ +/* Execute actual start/worker/matcher/variable path; only remote I/O is synthetic. */ +#define OP_ADAPTER_NO_MAIN +#define TEST_CAPTURE_DIAGNOSTICS +#include "test_operation_adapter.c" +int main(void){ + cJSON_Hooks hooks={tracked_malloc,tracked_free};cJSON_InitHooks(&hooks);setup();sent_hook=observe; + diagnostic_used=0;diagnostic_trace[0]=0; + const char *command="echo Synthetic-Command-Credential"; + const char *parts[]={"Synthetic-Extract-Pattern=Synthetic-Private-Result\n",NULL}; + matching_parts=parts;expected_command=command; + ts_webui_ssh_options_t options={.collect_output=true,.expect_pattern="Synthetic-Expect-Pattern",.fail_pattern="Synthetic-Fail-Pattern",.extract_pattern="Synthetic-Extract-Pattern=(.*)",.var_name="private_fixture"}; + unsigned writes=variable_writes,submitted=commands_submitted,old_aborts=aborts;uint32_t id; + assert(ts_webui_ssh_exec_start_ex("fixture.invalid",22,"fixture",NULL,"Synthetic-Authentication-Password",command,&options,&id)==ESP_OK); + exec_task.fn(exec_task.arg);finish_all(); + assert(commands_submitted==submitted+1&&variable_writes>writes&&aborts==old_aborts); + assert(!strcmp(stored_extract,"Synthetic-Private-Result")); + const char *private_values[]={"Synthetic-Command-Credential","Synthetic-Authentication-Password","Synthetic-Expect-Pattern","Synthetic-Fail-Pattern","Synthetic-Extract-Pattern","Synthetic-Private-Result"}; + for(unsigned i=0;i 3 else Path('build')) diff --git a/tools/ci/check_profile.py b/tools/ci/check_profile.py index d6c834ff..82d1eae3 100644 --- a/tools/ci/check_profile.py +++ b/tools/ci/check_profile.py @@ -5,7 +5,7 @@ import re import subprocess -UPSTREAM = 'RMinte-AI/TianshanOS' +UPSTREAM = 'RMinte/TianshanOS' TAG = re.compile(r'v\d+\.\d+\.\d+(?:-[A-Za-z0-9.]+)?') diff --git a/tools/ci/check_release_state.py b/tools/ci/check_release_state.py index 88256e90..90504901 100644 --- a/tools/ci/check_release_state.py +++ b/tools/ci/check_release_state.py @@ -9,7 +9,7 @@ import urllib.request sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from check_release import validate +from check_release import validate, validate_security_artifacts def query(path): @@ -81,6 +81,9 @@ def main(): mode, tag = 'main', 'v' + Path('version.txt').read_text().strip() else: raise ValueError('Preflight invoked without a release route') + identity = validate_security_artifacts(Path(os.environ.get("RELEASE_ARTIFACT_DIR", "firmware"))) + if identity["version"] != version: + raise ValueError("Release artifact version differs from the actual build version") validate(tag, version) commit = os.environ['BUILD_COMMIT'] if subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip() != commit: diff --git a/tools/gen_version.py b/tools/gen_version.py index ed716c68..390553ce 100644 --- a/tools/gen_version.py +++ b/tools/gen_version.py @@ -2,16 +2,14 @@ """ TianShanOS 版本号生成脚本 -在每次构建时生成包含 git hash 和时间戳的版本字符串。 -由 CMake 在构建阶段调用,确保每次构建都有唯一的版本号。 - -输出格式: MAJOR.MINOR.PATCH+HASH.TIMESTAMP -例如: 0.3.1+7fdcca4d.01311234 +生成不包含日期/时间的版本标识:干净检出使用 Git 提交号; +未提交修改或无 Git 的源码副本使用源码指纹区分内容。 +输出示例:0.6.5+7fdcca4d 或 0.6.5+s1a2b3c4d。 """ import subprocess import sys -from datetime import datetime +import hashlib from pathlib import Path @@ -78,6 +76,28 @@ def read_version_file(version_file: Path) -> tuple: return major, minor, patch, prerelease +def source_fingerprint(repo_path: Path) -> str: + """Hash relative source paths/content, excluding clocks and local outputs.""" + files = [repo_path / name for name in ('version.txt', 'CMakeLists.txt', 'Kconfig.projbuild', + 'sdkconfig', 'sdkconfig.defaults', 'partitions.csv', 'dependencies.lock')] + for directory in ('components', 'main', 'cmake', 'tools'): + for path in (repo_path / directory).rglob('*'): + parts = path.relative_to(repo_path / directory).parts + if not path.is_file() or any(p.startswith('.') or p in ('build', '__pycache__', 'node_modules') for p in parts): + continue + if directory != 'tools' or path.suffix in ('.py', '.sh'): + files.append(path) + digest = hashlib.sha256() + for path in sorted(p for p in files if p.is_file()): + content = path.read_bytes() + if path.name == 'sdkconfig': + content = '\n'.join(sorted(line for line in content.decode().splitlines() + if line.startswith('CONFIG_') or line.startswith('# CONFIG_'))).encode() + digest.update(path.relative_to(repo_path).as_posix().encode() + b'\0') + digest.update(hashlib.sha256(content).digest()) + return digest.hexdigest()[:8] + + def generate_version(repo_path: Path) -> str: """生成完整版本字符串""" version_file = repo_path / 'version.txt' @@ -88,16 +108,14 @@ def generate_version(repo_path: Path) -> str: if prerelease: version += f"-{prerelease}" - # 构建元数据: HASH[d].TIMESTAMP git_hash = get_git_hash(repo_path) - dirty_flag = 'd' if is_git_dirty(repo_path) else '' - timestamp = datetime.now().strftime('%m%d%H%M') - - if git_hash: - build_meta = f"{git_hash}{dirty_flag}.{timestamp}" + if git_hash and not is_git_dirty(repo_path): + build_meta = git_hash + elif git_hash: + build_meta = f"{git_hash}d.{source_fingerprint(repo_path)}" else: - build_meta = timestamp - + build_meta = 's' + source_fingerprint(repo_path) + return f"{version}+{build_meta}" diff --git a/tools/make_firmware_manifest.py b/tools/make_firmware_manifest.py index 2dc5d35e..1a4d6869 100644 --- a/tools/make_firmware_manifest.py +++ b/tools/make_firmware_manifest.py @@ -11,7 +11,7 @@ 3. 提交 build/ 的变化。清单里的 source_base_commit 是第 1 步构建的那个提交,镜像随其后的提交一起进入仓库。 清单字段: - version / build_version / idf_version 版本;build_version 形如 0.6.2+HASH.月日时分 + version / build_version / idf_version 版本;build_version 形如 0.6.5+HASH(不含日期/时间) source_base_commit 被构建提交的完整 SHA source_inputs_sha256 参与固件构建的已跟踪源文件的内容哈希:被构建提交中,排除 build/ docs/ tests/ help/ assets/ .github/ 和 README*.md 之外的每个文件,按路径排序,逐个取 diff --git a/tools/minify_web.py b/tools/minify_web.py index e17b9b11..131587c5 100644 --- a/tools/minify_web.py +++ b/tools/minify_web.py @@ -216,8 +216,9 @@ def gzip_directory(web_dir: str) -> None: gz_path = filepath + '.gz' with open(filepath, 'rb') as f_in: - with gzip_module.open(gz_path, 'wb', compresslevel=9) as f_out: - f_out.write(f_in.read()) + with open(gz_path, 'wb') as raw_out: + with gzip_module.GzipFile(filename='', mode='wb', fileobj=raw_out, compresslevel=9, mtime=0) as f_out: + f_out.write(f_in.read()) gz_size = os.path.getsize(gz_path) total_original += original_size diff --git a/tools/prepare_http_transport_polling.py b/tools/prepare_http_transport_polling.py new file mode 100644 index 00000000..a43b8b62 --- /dev/null +++ b/tools/prepare_http_transport_polling.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Prepare build-local SDK HTTP I/O and private diagnostics; never edit ESP-IDF.""" +import argparse +import hashlib +import json +import re +from pathlib import Path + + +def prepare(idf, output, websocket_source): + source_path = Path(idf) / 'components/tcp_transport/transport_ssl.c' + source = source_path.read_text() + if 'esp_transport_set_async_connect_func(tcp_transport, tcp_connect_async);' not in source: + raise ValueError('SDK TCP asynchronous connection support changed; review required') + result = source + for name in ('base_poll_read', 'base_poll_write'): + start = result.index('static int ' + name + '(') + end = result.index('\n}\n', start) + 3 + function = result[start:end] + if function.count(' return ret;') != 1 or 'ret = select(' not in function or re.search(r'^\s*errno\s*=', function, re.M): + raise ValueError('SDK ' + name + ' polling contract changed; review required') + patched = function.replace(' return ret;', ''' /* Zero-timeout polling is nonblocking I/O: no readiness means EAGAIN, + * not a completed/truncated HTTP response. Positive readiness must not + * inherit a prior EAGAIN and hide a subsequent real EOF/write failure. */ + if (timeout_ms == 0 && ret >= 0) errno = ret == 0 ? EAGAIN : 0; + return ret;''') + result = result[:start] + patched + result[end:] + client_source_path = Path(idf) / 'components/esp_http_client/esp_http_client.c' + client_source = client_source_path.read_text() + start = client_source.index('static int esp_http_client_get_data(') + end = client_source.index('\n}\n', start) + 3 + function = client_source[start:end] + if function.count(' return rlen;') != 1 or 'http_parser_execute(client->parser' not in function: + raise ValueError('SDK HTTP EOF parsing contract changed; review required') + patched = function.replace(' return rlen;', ''' /* FIN is a real EOF, unlike a zero-timeout retry. Let the SDK parser + * complete legal close-delimited bodies; incomplete CL/chunks still fail. */ + if (rlen == ERR_TCP_TRANSPORT_CONNECTION_CLOSED_BY_FIN) { + http_parser_execute(client->parser, client->parser_settings, res_buffer->data, 0); + if (HTTP_PARSER_ERRNO(client->parser) == HPE_OK && client->is_chunk_complete) { + errno = 0; + return 0; + } + } + return rlen;''') + client_result = client_source[:start] + patched + client_source[end:] + # Protocol contents must reach their actual caller, never the global log. + # Exact SDK anchors are reviewed with the I/O adaptations; a changed SDK + # cannot silently restore Authorization/cookie/query logging. + private_diagnostics = [ + ('ESP_LOGD(TAG, "HEADER=%s:%s", client->current_header_key, client->current_header_value);', 'ESP_LOGD(TAG, "HTTP response header received");', 1), + ('ESP_LOGD(TAG, "auth_response=%s", auth_response);', 'ESP_LOGD(TAG, "HTTP authorization prepared");', 2), + ('ESP_LOGD(TAG, "Redirect to %s", client->location);', 'ESP_LOGD(TAG, "HTTP redirect received");', 1), + ('ESP_LOGE(TAG, "Error parse url %s", url);', 'ESP_LOGE(TAG, "Invalid HTTP URL");', 1), + ('ESP_LOGD(TAG, "New host assign = %s", client->connection_info.host);', 'ESP_LOGD(TAG, "HTTP host updated");', 1), + ('ESP_LOGD(TAG, "Begin connect to: %s://%s:%d", client->connection_info.scheme, client->connection_info.host, client->connection_info.port);', 'ESP_LOGD(TAG, "Opening HTTP connection");', 1), + ('ESP_LOGD(TAG, "Write header[%d]: %s", client->header_index, client->request->buffer->data);', 'ESP_LOGD(TAG, "Writing HTTP headers (part=%d)", client->header_index);', 1), + ('ESP_LOGD(TAG, "UNAUTHORIZED: %s", auth_header);', 'ESP_LOGD(TAG, "HTTP authentication challenge received");', 1), + ('ESP_LOGE(TAG, "This authentication method is not supported: %s", auth_header);', 'ESP_LOGE(TAG, "Unsupported HTTP authentication method");', 1), + ] + for original, safe, expected in private_diagnostics: + if client_result.count(original) != expected: + raise ValueError('SDK HTTP private diagnostic contract changed; review required') + client_result = client_result.replace(original, safe) + ws_source_path = Path(idf) / 'components/tcp_transport/transport_ws.c' + ws_source = ws_source_path.read_text() + ws_result = ws_source + ws_diagnostics = [ + ('ESP_LOGE(TAG, "Error connecting to host %s:%d", host, port);', 'ESP_LOGE(TAG, "WebSocket transport connection failed");'), + ('ESP_LOGD(TAG, "sub_protocol: %s", ws->sub_protocol);', 'ESP_LOGD(TAG, "WebSocket subprotocol configured");'), + ('ESP_LOGD(TAG, "Authorization: %s", ws->auth);', 'ESP_LOGD(TAG, "WebSocket authorization configured");'), + ('ESP_LOGD(TAG, "headers: %s", ws->headers);', 'ESP_LOGD(TAG, "WebSocket headers configured");'), + ('ESP_LOGD(TAG, "Write upgrade request\\r\\n%s", ws->buffer);', 'ESP_LOGD(TAG, "Writing WebSocket upgrade request");'), + ('ESP_LOGE(TAG, "Error write Upgrade header %s", ws->buffer);', 'ESP_LOGE(TAG, "Writing WebSocket upgrade request failed");'), + ('ESP_LOGD(TAG, "server key=%s, send_key=%s, expected_server_key=%s", (char *)server_key, (char *)client_key, expected_server_key);', 'ESP_LOGD(TAG, "WebSocket handshake response received");'), + ] + websocket_source = Path(websocket_source) + websocket_original = websocket_source.read_text() + websocket_result = websocket_original + websocket_diagnostics = [ + ('ESP_LOGE(TAG, "%s", client->errormsg_buffer);', 'ESP_LOGE(TAG, "WebSocket client error (%d bytes)", needed_size);'), + ('ESP_LOGE(TAG, "Not support this websocket scheme %s, only support %s and %s", client->config->scheme, WS_OVER_TCP_SCHEME, WS_OVER_TLS_SCHEME);', 'ESP_LOGE(TAG, "Unsupported WebSocket scheme; use ws or wss");'), + ('ESP_LOGE(TAG, "Error parse uri = %s", uri);', 'ESP_LOGE(TAG, "Invalid WebSocket URI");'), + ('ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port);', 'ESP_LOGD(TAG, "WebSocket transport connected");'), + ] + for original, safe in ws_diagnostics: + if ws_result.count(original) != 1: + raise ValueError('SDK WebSocket private diagnostic contract changed; review required') + ws_result = ws_result.replace(original, safe) + for original, safe in websocket_diagnostics: + if websocket_result.count(original) != 1: + raise ValueError('Managed WebSocket private diagnostic contract changed; review required') + websocket_result = websocket_result.replace(original, safe) + # The SDK consumes the argument list during sizing. Copy it so private + # application error events retain their exact arguments on every ABI. + original = """ size_t needed_size = vsnprintf(NULL, 0, format, myargs); + needed_size++; // null terminator""" + replacement = """ va_list sizing_args; + va_copy(sizing_args, myargs); + int needed_size = vsnprintf(NULL, 0, format, sizing_args); + va_end(sizing_args); + if (needed_size < 0) { + va_end(myargs); + return ESP_FAIL; + } + size_t allocation_size = (size_t)needed_size + 1;""" + replacements = [ + (original, replacement), + ('if (needed_size > client->errormsg_size)', 'if (allocation_size > client->errormsg_size)'), + ('client->errormsg_buffer = malloc(needed_size);', 'client->errormsg_buffer = malloc(allocation_size);'), + ('client->errormsg_size = needed_size;', 'client->errormsg_size = allocation_size;'), + (' client->errormsg_size = 0;\n ESP_LOGE(TAG, "Failed to allocate...");', ' client->errormsg_size = 0;\n va_end(myargs);\n ESP_LOGE(TAG, "Failed to allocate...");'), + ] + for original, replacement in replacements: + if websocket_result.count(original) != 1: + raise ValueError('Managed WebSocket error formatting contract changed; review required') + websocket_result = websocket_result.replace(original, replacement) + # Publish the running lifetime before the worker can finish. A worker may + # set STOPPED before xTaskCreate returns; clearing it afterwards loses that + # completion and makes stop/destroy wait forever. Failed creation is stopped. + start = websocket_result.index('esp_err_t esp_websocket_client_start(') + end = websocket_result.index('\n}', start) + 2 + body = websocket_result[start:end] + clear = ' xEventGroupClearBits(client->status_bits, STOPPED_BIT | CLOSE_FRAME_SENT_BIT);\n' + create = ' if (xTaskCreate(esp_websocket_client_task,' + failure = ' ESP_LOGE(TAG, "Error create websocket task");\n return ESP_FAIL;' + if body.count(clear) != 1 or body.count(create) != 1 or body.count(failure) != 1: + raise ValueError('Managed WebSocket task publication contract changed; review required') + body = body.replace(clear, '').replace(create, clear + '\n' + create) + body = body.replace(failure, ' xEventGroupSetBits(client->status_bits, STOPPED_BIT);\n' + failure) + websocket_result = websocket_result[:start] + body + websocket_result[end:] + # STOPPED is a publication boundary. The SDK previously touched client + # after setting it, while destroy could already free client/event storage. + # Keep the existing client mutex until SetBits itself has returned; a + # waiting destructor crosses that mutex before freeing any SDK resources. + old_finish = ' xEventGroupSetBits(client->status_bits, STOPPED_BIT);\n client->state = WEBSOCKET_STATE_UNKNOW;\n if (client->selected_for_destroying == true) {\n destroy_and_free_resources(client);\n }' + new_finish = ' xSemaphoreTakeRecursive(client->lock, portMAX_DELAY);\n client->state = WEBSOCKET_STATE_UNKNOW;\n if (client->selected_for_destroying == true) {\n xSemaphoreGiveRecursive(client->lock);\n destroy_and_free_resources(client);\n } else {\n xEventGroupSetBits(client->status_bits, STOPPED_BIT);\n xSemaphoreGiveRecursive(client->lock);\n }' + if websocket_result.count(old_finish) != 1: + raise ValueError('Managed WebSocket finish publication contract changed; review required') + websocket_result = websocket_result.replace(old_finish, new_finish) + start = websocket_result.index('static esp_err_t stop_wait_task(') + end = websocket_result.index('\n}', start) + 2 + body = websocket_result[start:end] + wait = ' xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);\n' + if body.count(wait) != 1: + raise ValueError('Managed WebSocket stop/join contract changed; review required') + body = body.replace(wait, wait + ' xSemaphoreTakeRecursive(client->lock, portMAX_DELAY);\n xSemaphoreGiveRecursive(client->lock);\n') + websocket_result = websocket_result[:start] + body + websocket_result[end:] + start = websocket_result.index('esp_err_t esp_websocket_client_destroy(') + end = websocket_result.index('\n}', start) + 2 + body = websocket_result[start:end] + last = ' }\n\n destroy_and_free_resources(client);' + if body.count(last) != 1: + raise ValueError('Managed WebSocket destructor barrier contract changed; review required') + body = body.replace(last, ' } else if (client->lock) {\n xSemaphoreTakeRecursive(client->lock, portMAX_DELAY);\n xSemaphoreGiveRecursive(client->lock);\n }\n\n destroy_and_free_resources(client);') + websocket_result = websocket_result[:start] + body + websocket_result[end:] + # Public external transports may not expose a socket. The diagnostic's + # bounded close owns teardown; do not bypass it with a raw socket select. + close_poll = ' int ret = esp_transport_ws_poll_connection_closed(client->transport, 1000);' + if websocket_result.count(close_poll) != 1: + raise ValueError('Managed WebSocket close polling contract changed; review required') + websocket_result = websocket_result.replace(close_poll, + ' int ret = client->config->ext_transport ? 1 :\n esp_transport_ws_poll_connection_closed(client->transport, 1000);') + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + target = output / 'transport_ssl.c' + target.write_text(result) + (output / 'esp_http_client.c').write_text(client_result) + (output / 'transport_ws.c').write_text(ws_result) + (output / 'esp_websocket_client.c').write_text(websocket_result) + metadata = {'sdk_source': str(source_path), 'sdk_sha256': hashlib.sha256(source.encode()).hexdigest(), + 'prepared_sha256': hashlib.sha256(result.encode()).hexdigest(), + 'http_sdk_sha256': hashlib.sha256(client_source.encode()).hexdigest(), + 'http_prepared_sha256': hashlib.sha256(client_result.encode()).hexdigest(), + 'ws_sdk_sha256': hashlib.sha256(ws_source.encode()).hexdigest(), + 'ws_prepared_sha256': hashlib.sha256(ws_result.encode()).hexdigest(), + 'websocket_source': str(websocket_source), + 'websocket_sha256': hashlib.sha256(websocket_original.encode()).hexdigest(), + 'websocket_prepared_sha256': hashlib.sha256(websocket_result.encode()).hexdigest(), + 'websocket_private_diagnostic_sites': len(ws_diagnostics) + len(websocket_diagnostics), + 'private_diagnostic_sites': sum(item[2] for item in private_diagnostics), + 'websocket_start_lifecycle': 'running before task creation;stopped on create failure', + 'websocket_finish_lifecycle': 'client mutex protects STOPPED publication and destructor join', + 'websocket_external_close': 'external transport teardown;no raw socket select', + 'scope': 'nonblocking poll/FIN, private diagnostics, WS lifetime publication and opaque external close; no shared SDK edits'} + (output / 'inputs.json').write_text(json.dumps(metadata, indent=2) + '\n') + return metadata + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--idf-dir', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--websocket-source', required=True, type=Path) + args = parser.parse_args() + try: + prepare(args.idf_dir, args.output, args.websocket_source) + except (ValueError, OSError) as error: + parser.exit(1, str(error) + '\n') diff --git a/tools/prepare_httpd_admission.py b/tools/prepare_httpd_admission.py index 6ab3f9a6..ef07cfe7 100644 --- a/tools/prepare_httpd_admission.py +++ b/tools/prepare_httpd_admission.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Build-local ESP-IDF HTTPD policy: never LRU-evict an upgraded WebSocket. +"""Build-local HTTPD admission and HTTPS resource ownership. The SDK installation is read-only. Refuse source drift rather than silently building firmware without the admission policy. Tested with ESP-IDF v5.5.2. @@ -14,6 +14,37 @@ def replace_once(source, old, new): return source.replace(old, new, 1) +def validate_origins(value): + """Fail configuration before firmware generation; never print header values.""" + import ipaddress + import re + from urllib.parse import urlsplit + if not value: + return + entries = value.split(',') + if len(entries) > 4: + raise ValueError('At most four explicit trusted origins are supported') + for entry in entries: + if not entry or len(entry) >= 288 or any(ord(c) <= 32 or ord(c) >= 127 for c in entry): + raise ValueError('Trusted origins must be bounded ASCII origins') + if any(c in entry for c in '@?#%\\*'): + raise ValueError('Trusted origins cannot contain credentials, escapes or wildcards') + parsed = urlsplit(entry) + if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.path or parsed.query or parsed.fragment: + raise ValueError('Trusted origins must contain only HTTP(S) scheme and authority') + if parsed.port == 0 or len(parsed.hostname) > 253 or parsed.netloc.endswith(':'): + raise ValueError('Invalid trusted origin authority or port') + host = parsed.hostname + if ':' in host: + ipaddress.IPv6Address(host) + elif all(c in '0123456789.' for c in host): + ipaddress.IPv4Address(host) + else: + labels = host[:-1].split('.') if host.endswith('.') else host.split('.') + if any(not re.fullmatch(r'[a-zA-Z0-9_-]{1,63}', label) for label in labels): + raise ValueError('Invalid trusted origin DNS labels') + + def prepare(idf, output): src = Path(idf) / 'components/esp_http_server/src' sess = (src / 'httpd_sess.c').read_text() @@ -27,6 +58,9 @@ def prepare(idf, output): sess = replace_once(sess, 'if (!context.session) {\n return ESP_OK;\n }\n ESP_LOGD(TAG, LOG_FMT("Closing session with fd %d"), context.session->fd);', 'if (!context.session) {\n return ESP_ERR_NOT_FOUND;\n }\n ESP_LOGD(TAG, LOG_FMT("Closing session with fd %d"), context.session->fd);') + sess = replace_once(sess, 'esp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session)', + 'static esp_err_t httpd_sess_process_impl(struct httpd_data *hd, struct sock_db *session)') + sess += '\n/* Project-owned receive lifetime; every exit, including parse/handler errors,\n * clears the task-local budget before HTTPD processes another socket. */\nextern void ts_httpd_receive_begin(void);\nextern void ts_httpd_receive_end(void);\nesp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session)\n{\n ts_httpd_receive_begin();\n esp_err_t ret = httpd_sess_process_impl(hd, session);\n ts_httpd_receive_end();\n return ret;\n}\n' main = (src / 'httpd_main.c').read_text() main = replace_once(main, 'return httpd_sess_close_lru(hd);', @@ -42,17 +76,173 @@ def prepare(idf, output): return ESP_OK; } return ret;''') + uri = (src / 'httpd_uri.c').read_text() + uri = replace_once(uri, 'esp_err_t httpd_uri(struct httpd_data *hd)\n{', + 'extern esp_err_t ts_httpd_admit_request(httpd_req_t *req);\n\nesp_err_t httpd_uri(struct httpd_data *hd)\n{') + uri = replace_once(uri, ' httpd_req_t *req = &hd->hd_req;', + ' httpd_req_t *req = &hd->hd_req;\n if (ts_httpd_admit_request(req) != ESP_OK) return ESP_FAIL;') + # A registered WebSocket endpoint is not an ordinary GET resource. The + # application peer owner may run only after SDK upgrade validation/101. + uri = replace_once(uri, ' struct httpd_req_aux *aux = req->aux;', + ' struct httpd_req_aux *aux = req->aux;\n if (uri->is_websocket && !aux->ws_handshake_detect) {\n httpd_req_handle_err(req, HTTPD_400_BAD_REQUEST);\n return ESP_FAIL; /* Also close when a custom error handler returns OK. */\n }') + parse = (src / 'httpd_parse.c').read_text() + parse = replace_once(parse, 'static esp_err_t cb_headers_complete(http_parser *parser)', + '/* TS_CONTENT_LENGTH_BEGIN: reject before size_t truncation or URI dispatch. */\nstatic bool ts_httpd_decode_content_length(uint64_t wire_length, bool present, bool chunked, size_t *length)\n{\n if (chunked) return false; /* SDK does not support chunked request bodies. */\n if (!present) { *length=0;return true; }\n /* Wire budget for the current whole-buffer upload handlers.\n * Authentication and JSON routes select smaller application limits. */\n if (wire_length>16U*1024U*1024U || wire_length>SIZE_MAX) return false;\n *length=(size_t)wire_length;\n return true;\n}\n/* TS_CONTENT_LENGTH_END */\n\nstatic esp_err_t cb_headers_complete(http_parser *parser)') + parse = replace_once(parse, ' /* In absence of body/chunked encoding, http_parser sets content_len to -1 */\n r->content_len = ((int)parser->content_length != -1 ?\n parser->content_length : 0);', " /* The presence flag distinguishes absence from an explicit maximum. Casting to int\n * also mistakes valid low 0xffffffff bits for absence on 32-bit targets. */\n if (!ts_httpd_decode_content_length(parser->content_length, (parser->flags & F_CONTENTLENGTH)!=0, (parser->flags & F_CHUNKED)!=0, &r->content_len)) {\n parser_data->error=(parser->flags & F_CHUNKED)?HTTPD_501_METHOD_NOT_IMPLEMENTED:HTTPD_413_CONTENT_TOO_LARGE;\n parser_data->status=PARSING_FAILED;\n return ESP_FAIL;\n }") + # Validate the private layout owner and lookup anchor instead of changing + # the globally installed SDK. Header memory is valid only before sending. + for anchor in ['esp_err_t httpd_req_get_hdr_value_str(', 'ra->scratch_cur_size = 0;', 'ra->req_hdrs_count = 0;']: + if anchor not in parse: raise ValueError('Unsupported HTTPD header buffer layout') + parse += r""" + +/* Project-only strict security-header access. Duplicate/empty/missing values + * must not collapse to the first matching value or to an absent Origin. */ +esp_err_t ts_httpd_get_single_header(httpd_req_t *r, const char *field, + char *out, size_t capacity) +{ + if (!r || !field || !out || !capacity || !httpd_valid_req(r)) return ESP_ERR_INVALID_ARG; + out[0] = 0; + struct httpd_req_aux *ra = r->aux; + if (!ra || (!ra->scratch && ra->req_hdrs_count)) return ESP_ERR_INVALID_ARG; + if (!ra->req_hdrs_count) return ESP_ERR_NOT_FOUND; + const char *at = ra->scratch, *end = at + ra->scratch_cur_size; + bool found = false; + for (unsigned i = 0; i < ra->req_hdrs_count; ++i) { + while (at < end && !*at) ++at; + if (at == end) return ESP_ERR_INVALID_ARG; + const char *nul = memchr(at, 0, (size_t)(end - at)); + if (!nul) return ESP_ERR_INVALID_ARG; + const char *colon = memchr(at, ':', (size_t)(nul - at)); + if (!colon) return ESP_ERR_INVALID_ARG; + if ((size_t)(colon - at) == strlen(field) && !strncasecmp(at, field, (size_t)(colon - at))) { + if (found) return ESP_ERR_INVALID_ARG; + found = true; + const char *value = colon + 1, *last = nul; + while (value < last && (*value == ' ' || *value == '\t')) ++value; + while (last > value && (last[-1] == ' ' || last[-1] == '\t')) --last; + size_t length = (size_t)(last - value); + if (length >= capacity) return ESP_ERR_HTTPD_RESULT_TRUNC; + memcpy(out, value, length); out[length] = 0; + } + at = nul + 1; + } + return found ? ESP_OK : ESP_ERR_NOT_FOUND; +} +""" + + # Diagnostics feed the shared log ring, including when SDK DEBUG or purge + # logging is enabled. Keep protocol bytes in their owner, never in logs. + txrx = (src / 'httpd_txrx.c').read_text() + ws = (src / 'httpd_ws.c').read_text() + ws = replace_once(ws, ' frame->len = (((uint64_t)length_bytes[0] << 56U) |\n ((uint64_t)length_bytes[1] << 48U) |\n ((uint64_t)length_bytes[2] << 40U) |\n ((uint64_t)length_bytes[3] << 32U) |\n ((uint64_t)length_bytes[4] << 24U) |\n ((uint64_t)length_bytes[5] << 16U) |\n ((uint64_t)length_bytes[6] << 8U) |\n ((uint64_t)length_bytes[7]));', ' uint64_t wide_len = (((uint64_t)length_bytes[0] << 56U) |\n ((uint64_t)length_bytes[1] << 48U) |\n ((uint64_t)length_bytes[2] << 40U) |\n ((uint64_t)length_bytes[3] << 32U) |\n ((uint64_t)length_bytes[4] << 24U) |\n ((uint64_t)length_bytes[5] << 16U) |\n ((uint64_t)length_bytes[6] << 8U) |\n ((uint64_t)length_bytes[7]));\n if (wide_len > SIZE_MAX || wide_len > INT64_MAX) {\n ESP_LOGW(TAG, "WS wire length is not representable");\n return ESP_ERR_INVALID_SIZE;\n }\n frame->len = (size_t)wide_len;') + txrx = replace_once(txrx, 'static const char *TAG = "httpd_txrx";', + '/* TS_RX_BUDGET_BEGIN: task-local, monotonic and independent per listener. */\nstatic _Thread_local uint32_t s_receive_started, s_receive_budget;\nstatic _Thread_local bool s_receive_active, s_receive_body_started;\nstatic bool ts_httpd_receive_expired(void)\n{\n return s_receive_active && (uint32_t)(esp_log_timestamp()-s_receive_started)>=s_receive_budget;\n}\nvoid ts_httpd_receive_begin(void)\n{\n s_receive_started=esp_log_timestamp();s_receive_budget=15000;\n s_receive_active=true;s_receive_body_started=false;\n}\nvoid ts_httpd_receive_end(void)\n{\n s_receive_active=false;s_receive_body_started=false;s_receive_budget=0;\n}\nvoid ts_httpd_set_body_receive_budget(uint32_t milliseconds)\n{\n if (!s_receive_active || s_receive_body_started) return;\n if (!milliseconds) milliseconds=30000;\n if (milliseconds>300000) milliseconds=300000;\n s_receive_started=esp_log_timestamp();s_receive_budget=milliseconds;\n s_receive_body_started=true;\n}\n/* TS_RX_BUDGET_END */\n\nstatic const char *TAG = "httpd_txrx";') + txrx = replace_once(txrx, + 'int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt)\n{', + 'int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt)\n{\n if (ts_httpd_receive_expired()) return HTTPD_SOCK_ERR_TIMEOUT;') + txrx = replace_once(txrx, + 'int ret = ra->sd->recv_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);', + 'int ret = ra->sd->recv_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);\n if (ts_httpd_receive_expired()) return HTTPD_SOCK_ERR_TIMEOUT;\n if (ret == 0) return recv_len; /* EOF must not spin in blocking mode. */') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("received URI = %s"), r->uri);', 'ESP_LOGD(TAG, LOG_FMT("received URI (%"NEWLIB_NANO_COMPAT_FORMAT" bytes)"), NEWLIB_NANO_COMPAT_CAST(length));') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("processing url = %.*s"), (int)length, at);', 'ESP_LOGD(TAG, LOG_FMT("processing URL fragment (%"NEWLIB_NANO_COMPAT_FORMAT" bytes)"), NEWLIB_NANO_COMPAT_CAST(length));') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("processing field = %.*s"), (int)length, at);', 'ESP_LOGD(TAG, LOG_FMT("processing header name (%"NEWLIB_NANO_COMPAT_FORMAT" bytes)"), NEWLIB_NANO_COMPAT_CAST(length));') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("processing value = %.*s"), (int)length, at);', 'ESP_LOGD(TAG, LOG_FMT("processing header value (%"NEWLIB_NANO_COMPAT_FORMAT" bytes)"), NEWLIB_NANO_COMPAT_CAST(length));') + parse = replace_once(parse, 'ESP_LOGW(TAG, LOG_FMT("Upgrade header found but it\'s %s"), ws_upgrade_hdr_val);', 'ESP_LOGW(TAG, LOG_FMT("Unsupported Upgrade header value"));') + parse = replace_once(parse, 'ESP_LOG_BUFFER_HEX_LEVEL(TAG, dummy, recv_len, ESP_LOG_DEBUG);', 'ESP_LOGD(TAG, LOG_FMT("purged payload omitted"));') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("key %s not found"), key);', 'ESP_LOGD(TAG, LOG_FMT("header key not found"));') + parse = replace_once(parse, 'ESP_LOGD(TAG, LOG_FMT("cookie %s not found"), key);', 'ESP_LOGD(TAG, LOG_FMT("cookie key not found"));') + parse = replace_once(parse, 'ESP_LOGW(TAG, "Cookie not found in header uri:[%s]", req->uri);', 'ESP_LOGW(TAG, "Cookie not found in request header");') + uri = replace_once(uri, 'ESP_LOGD(TAG, LOG_FMT("request for %s with type %d"), req->uri, req->method);', 'ESP_LOGD(TAG, LOG_FMT("request method %d"), req->method);') + uri = replace_once(uri, 'ESP_LOGW(TAG, LOG_FMT("URI \'%s\' not found"), req->uri);', 'ESP_LOGW(TAG, LOG_FMT("request route not found"));') + uri = replace_once(uri, 'ESP_LOGW(TAG, LOG_FMT("Method \'%d\' not allowed for URI \'%s\'"),\n req->method, req->uri);', 'ESP_LOGW(TAG, LOG_FMT("Method %d not allowed for request route"), req->method);') + ws = replace_once(ws, 'ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, URI do not support any subprotocols", subprotocol);', 'ESP_LOGW(TAG, "Requested WebSocket subprotocol unsupported: route has none");') + ws = replace_once(ws, 'ESP_LOGD(TAG, "Requested subprotocol supported: %s", s);', 'ESP_LOGD(TAG, "Requested WebSocket subprotocol supported");') + ws = replace_once(ws, 'ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, supported subprotocol is %s", subprotocol, supported_subprotocol);', 'ESP_LOGW(TAG, "Requested WebSocket subprotocol unsupported");') + ws = replace_once(ws, 'ESP_LOGW(TAG, LOG_FMT("\\"Sec-WebSocket-Version\\" is not \\"13\\", it is: %s"), version_val);', 'ESP_LOGW(TAG, LOG_FMT("Unsupported WebSocket version"));') + ws = replace_once(ws, 'ESP_LOGD(TAG, LOG_FMT("Server key before encoding: %s"), server_raw_text);', 'ESP_LOGD(TAG, LOG_FMT("WebSocket handshake digest prepared"));') + ws = replace_once(ws, 'ESP_LOGD(TAG, LOG_FMT("Generated server key: %s"), server_key_encoded);', 'ESP_LOGD(TAG, LOG_FMT("WebSocket handshake digest encoded"));') + ws = replace_once(ws, 'ESP_LOGD(TAG, "subprotocol: %s", subprotocol);', 'ESP_LOGD(TAG, "WebSocket response subprotocol selected");') + txrx = replace_once(txrx, 'ESP_LOGD(TAG, LOG_FMT("new header = %s: %s"), field, value);', + 'ESP_LOGD(TAG, LOG_FMT("response header stored"));') + error_log = 'ESP_LOGW(TAG, LOG_FMT("%s - %s"), status, msg);' + if txrx.count(error_log) != 2: + raise ValueError('Unsupported HTTPD response error diagnostics') + txrx = txrx.replace(error_log, 'ESP_LOGW(TAG, LOG_FMT("HTTP error response"));') + output = Path(output) output.mkdir(parents=True, exist_ok=True) - for name, content in [('httpd_sess.c', sess), ('httpd_main.c', main)]: + for name, content in [('httpd_sess.c', sess), ('httpd_main.c', main), ('httpd_uri.c', uri), ('httpd_parse.c', parse), ('httpd_txrx.c', txrx), ('httpd_ws.c', ws)]: dest = output / name if not dest.exists() or dest.read_text() != content: dest.write_text(content) +def prepare_https(idf, output): + """Keep one owner for copied TLS configuration on partial/startup failure.""" + source = (Path(idf) / 'components/esp_https_server/src/https_server.c').read_text() + old = """ esp_tls_cfg_server_t *cfg = ssl_ctx->tls_cfg; + ESP_LOGI(TAG, "Server shuts down, releasing SSL context"); + if (cfg->cacert_buf) { + free((void *)cfg->cacert_buf); + } + if (cfg->servercert_buf) { + free((void *)cfg->servercert_buf); + } + if (cfg->serverkey_buf) { + free((void *)cfg->serverkey_buf); + } + esp_tls_cfg_server_session_tickets_free(cfg); + free(cfg); + free(ssl_ctx);""" + source = replace_once(source, old, """ ts_httpd_free_tls_config(ssl_ctx->tls_cfg); + free(ssl_ctx);""") + marker = 'static void free_secure_context(void *ctx)' + source = replace_once(source, marker, """/* Copied PEM/ticket material has one cleanup owner, including partial init. */ +static void ts_httpd_free_tls_config(esp_tls_cfg_server_t *cfg) +{ + if (!cfg) return; + free((void *)cfg->cacert_buf); + free((void *)cfg->servercert_buf); + free((void *)cfg->serverkey_buf); + esp_tls_cfg_server_session_tickets_free(cfg); + free(cfg); +} + +""" + marker) + source = replace_once(source, """exit: + if (cfg) { + free((void *) cfg->servercert_buf); + free((void *) cfg->cacert_buf); + } + free(cfg); + return ret;""", """exit: + ts_httpd_free_tls_config(cfg); + return ret;""") + source = replace_once(source, """ ret = httpd_start(&handle, &config->httpd); + if (ret != ESP_OK) { + free(ssl_ctx); + ssl_ctx = NULL; + return ret; + }""", """ ret = httpd_start(&handle, &config->httpd); + if (ret != ESP_OK) { + if (ssl_ctx) free_secure_context(ssl_ctx); + return ret; + }""") + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + dest = output / 'https_server.c' + if not dest.exists() or dest.read_text() != source: + dest.write_text(source) + + if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--idf-dir', required=True) parser.add_argument('--output', required=True) + parser.add_argument('--trusted-origins', default='') + parser.add_argument('--with-https', action='store_true') args = parser.parse_args() + validate_origins(args.trusted_origins) prepare(args.idf_dir, args.output) + if args.with_https: + prepare_https(args.idf_dir, args.output) diff --git a/tools/serial_upgrade.py b/tools/serial_upgrade.py index ca289a55..55e4a4d6 100644 --- a/tools/serial_upgrade.py +++ b/tools/serial_upgrade.py @@ -68,17 +68,18 @@ def package(build, out): end = address + (build / name).stat().st_size if any(address < high and end > low for low, high in protected): raise ValueError('刷写镜像覆盖数据区 / Flash image overlaps a preserved data partition') + public_name = lambda name: 'TianshanOS.bin' if name == app else name out.mkdir(parents=True, exist_ok=False) for name in set(images.values()): - target = out / name + target = out / public_name(name) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(build / name, target) manifest = dict(format=1, build_version=json.loads((build / 'project_description.json').read_text())['project_version'], partition_table=args['partition-table']['file'], partition_table_offset=int(args['partition-table']['offset'], 0), flash_settings=args['write_flash_args'], - images=[dict(offset=address, file=name) for address, name in sorted(images.items())], - files={name: sha256(out / name) for name in sorted(set(images.values()))}) + images=[dict(offset=address, file=public_name(name)) for address, name in sorted(images.items())], + files={public_name(name): sha256(out / public_name(name)) for name in sorted(set(images.values()))}) (out / 'upgrade.json').write_text(json.dumps(manifest, indent=2) + '\n') shutil.copyfile(Path(__file__), out / 'upgrade.py') (out / 'requirements.txt').write_text('esptool==4.11.0\n') @@ -119,7 +120,7 @@ def flash(folder, port, baud): print('刷写完成。请保留原 SD 卡,等待首次配置迁移 / Flash complete. Keep the original SD card inserted for first-start migration.', flush=True) -README = '''# TianShanOS USB/串口升级 +README = '''# TianshanOS USB/串口升级 这是存储方案 v2 的配套包,包含固件、网页、新分区表和引导文件。 请使用厂商确认可交付的包。开发候选包仍须经厂商确认后,才能用于客户机器。 diff --git a/version.txt b/version.txt index d2b13eb6..ef5e4454 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -0.6.4 +0.6.5 From 3bfd828c47df07c5b7bd2dbcb1acfebafbba23a4 Mon Sep 17 00:00:00 2001 From: Alfred Date: Sun, 8 Nov 2026 17:51:14 +0800 Subject: [PATCH 2/4] =?UTF-8?q?ci:=20=E4=BF=AE=E5=A4=8D=E6=B5=8F=E8=A7=88?= =?UTF-8?q?=E5=99=A8SDK=E4=BE=9D=E8=B5=96=E4=B8=8E=E5=AE=BF=E4=B8=BB?= =?UTF-8?q?=E5=9B=9E=E5=BD=92=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 6 +++++ tests/runtime/c_source.py | 24 ++++++++++++++++++++ tests/runtime/dhcp_bindings/test_bindings.c | 1 + tests/runtime/rule_pack/test_crypto.c | 1 + tests/runtime/test_api_context.py | 6 ++--- tests/runtime/test_complete_api_inventory.py | 10 ++++---- tests/runtime/test_default_deny_policy.py | 3 +-- tests/runtime/test_port_forward.py | 3 +++ 8 files changed, 44 insertions(+), 10 deletions(-) create mode 100644 tests/runtime/c_source.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a55ae931..08920030 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,6 +59,12 @@ jobs: - run: npm ci --prefix tests/prompts - run: npm test --prefix tests/prompts - run: python3 tests/release/test_web_minify.py + - name: Fetch matching ESP-IDF sources for browser Origin regression + run: | + export IDF_PATH="$RUNNER_TEMP/web-idf" + echo "IDF_PATH=$IDF_PATH" >> "$GITHUB_ENV" + git clone --depth 1 --branch "$IDF_VERSION" --filter=blob:none --sparse https://github.com/espressif/esp-idf.git "$IDF_PATH" + git -C "$IDF_PATH" sparse-checkout set components/esp_http_server - name: Install Chrome for actual-page regressions working-directory: tests/prompts run: npx playwright install --with-deps chrome diff --git a/tests/runtime/c_source.py b/tests/runtime/c_source.py new file mode 100644 index 00000000..347fe4b6 --- /dev/null +++ b/tests/runtime/c_source.py @@ -0,0 +1,24 @@ +"""C source masking and balanced blocks shared by API registration fixtures.""" +import re + + +def masked(s): + pat = r'//[^\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'' + return re.sub( + pat, + lambda m: ''.join('\n' if c == '\n' else ' ' for c in m[0]) + if m[0].startswith(('/', '"', "'")) else m[0], + s, + ) + + +def endbrace(s, start): + depth = 0 + for i in range(start, len(s)): + if s[i] == '{': + depth += 1 + elif s[i] == '}': + depth -= 1 + if not depth: + return i + 1 + raise ValueError(start) diff --git a/tests/runtime/dhcp_bindings/test_bindings.c b/tests/runtime/dhcp_bindings/test_bindings.c index ccc35ec3..15ab2d4d 100644 --- a/tests/runtime/dhcp_bindings/test_bindings.c +++ b/tests/runtime/dhcp_bindings/test_bindings.c @@ -1,3 +1,4 @@ +#define _DEFAULT_SOURCE #include #include #include diff --git a/tests/runtime/rule_pack/test_crypto.c b/tests/runtime/rule_pack/test_crypto.c index 424adc45..7686f584 100644 --- a/tests/runtime/rule_pack/test_crypto.c +++ b/tests/runtime/rule_pack/test_crypto.c @@ -153,6 +153,7 @@ static void ordinary_identity_cases(const char *dir,const char *certificate_name free(device_key);device_key=strdup(b_key); free(device_cert);device_cert=NULL;assert(ts_config_pack_get_cert_fingerprint(fp,sizeof(fp))!=ESP_OK); ts_api_result_t response={0};assert(api_config_pack_export_cert(NULL,&response)!=ESP_OK&&!response.data); + ts_api_result_free(&response); ordinary_consumers(b_bytes,b_len,TS_CONFIG_PACK_ERR_CERT_CHAIN,content); device_cert=strdup(b_cert); certificate_read_error=ESP_ERR_NO_MEM;assert(ts_config_pack_get_cert_fingerprint(fp,sizeof(fp))==ESP_ERR_NO_MEM); diff --git a/tests/runtime/test_api_context.py b/tests/runtime/test_api_context.py index 1a2a7963..7bccbcf2 100644 --- a/tests/runtime/test_api_context.py +++ b/tests/runtime/test_api_context.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Actual registry and SSH descriptors prove verified C context dispatch, including concurrency.""" from pathlib import Path +from c_source import masked, endbrace from zipfile import ZipFile -import argparse,os,sys,re,subprocess,tempfile,importlib.util +import argparse,os,sys,re,subprocess,tempfile ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() def source(path): @@ -28,9 +29,8 @@ def source(path): atomic_fetch_add(&context_calls,1);ts_api_result_ok(r,NULL);return ESP_OK; } """ -sp=importlib.util.spec_from_file_location('h',ROOT/'audit/api-security-20261103/tools/extract_inventory.py');h=importlib.util.module_from_spec(sp);sp.loader.exec_module(h) s=source('components/ts_api/src/ts_api_ssh.c');m=re.search(r'static const ts_api_endpoint_t ssh_endpoints\[\]\s*=\s*\{',s);assert m -part=s[m.start():h.endbrace(h.masked(s),s.index('{',m.start()))+1] +part=s[m.start():endbrace(masked(s),s.index('{',m.start()))+1] for handler in set(re.findall(r'\.handler\s*=\s*(\w+)',part)):code+='#define '+handler+' legacy_handler\n' for handler in set(re.findall(r'\.session_handler\s*=\s*(\w+)',part)):code+='#define '+handler+' context_handler\n' code+=part+'\n' diff --git a/tests/runtime/test_complete_api_inventory.py b/tests/runtime/test_complete_api_inventory.py index 72911e0c..1ac8c7a7 100644 --- a/tests/runtime/test_complete_api_inventory.py +++ b/tests/runtime/test_complete_api_inventory.py @@ -8,8 +8,9 @@ auth metadata and independent role/method admission are checked for every API. """ from pathlib import Path +from c_source import masked, endbrace from zipfile import ZipFile -import argparse,json,os,sys,re,subprocess,tempfile,importlib.util +import argparse,json,os,sys,re,subprocess,tempfile ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) p=argparse.ArgumentParser();p.add_argument('--source-package');p.add_argument('--write-method-contract', action='store_true');args=p.parse_args() def source(path): @@ -25,7 +26,6 @@ def source(path): ns['source']=source;exec(compile(text[a:b],str(f),'exec'),ns);code=ns['code'];code=code[:code.index('static esp_err_t mutation(')] capacity=int(re.search(r'^CONFIG_TS_API_MAX_ENDPOINTS=(\d+)$', source('sdkconfig'), re.M)[1]) code=f'#define CONFIG_TS_API_MAX_ENDPOINTS {capacity}\n'+code -sp=importlib.util.spec_from_file_location('h',ROOT/'audit/api-security-20261103/tools/extract_inventory.py');h=importlib.util.module_from_spec(sp);sp.loader.exec_module(h) code+='#define ESP_LOGI(...) ((void)0)\n#define ESP_LOGW(...) ((void)0)\n#define ESP_LOGE(...) ((void)0)\nstatic esp_err_t ts_config_pack_init(void){return ESP_OK;}\nstatic esp_err_t ts_ota_init(void){return ESP_OK;}\nstatic void load_ota_server_config(void){}\n' code+='static esp_err_t lpmu_ensure_mutex(void){return ESP_OK;}\nesp_err_t ts_auth_init(void){return ESP_OK;}\n' # Expected values are fixed test data, never derived from ts_api_get_access(). @@ -51,12 +51,12 @@ def source(path): } """ for module in ['auth', 'automation', 'cert', 'config', 'config_pack', 'device', 'dhcp', 'fan', 'gpio', 'hosts', 'key', 'led', 'lpmu_access', 'log', 'monitor', 'nat', 'network', 'ota', 'power', 'service', 'sftp', 'ssh', 'storage', 'system', 'temp', 'time', 'ui', 'wifi']: - source_text=source('components/ts_api/src/ts_api_'+module+'.c');mask=h.masked(source_text) + source_text=source('components/ts_api/src/ts_api_'+module+'.c');mask=masked(source_text) m=re.search(r'^(?:esp_err_t|void) ts_api_'+module+r'_register\(void\)\s*\{',source_text,re.M);assert m,module parts=[] for table in re.finditer(r'static\s+const\s+ts_api_endpoint_t\s+\w+\[\]\s*=\s*\{',source_text[:m.start()]): - parts.append(source_text[table.start():h.endbrace(mask,source_text.index('{',table.start()))+1]) - parts.append(source_text[m.start():h.endbrace(mask,source_text.index('{',m.start()))]);part='\n'.join(parts) + parts.append(source_text[table.start():endbrace(mask,source_text.index('{',table.start()))+1]) + parts.append(source_text[m.start():endbrace(mask,source_text.index('{',m.start()))]);part='\n'.join(parts) for table in re.findall(r'static\s+const\s+ts_api_endpoint_t\s+(\w+)\[\]', '\n'.join(parts[:-1])): part=re.sub(r'\b'+table+r'\b','fixture_'+module+'_'+table,part) sessions=set(re.findall(r'\.session_handler\s*=\s*(\w+)',part)) diff --git a/tests/runtime/test_default_deny_policy.py b/tests/runtime/test_default_deny_policy.py index 69685a6b..f9165162 100644 --- a/tests/runtime/test_default_deny_policy.py +++ b/tests/runtime/test_default_deny_policy.py @@ -2,7 +2,7 @@ """Real management registrations/registry/dispatcher; synthetic business boundary.""" from pathlib import Path from zipfile import ZipFile -import argparse,os,sys,re,subprocess,tempfile,importlib.util +import argparse,os,sys,re,subprocess,tempfile ROOT=Path(__file__).resolve().parents[2];os.chdir(ROOT) p=argparse.ArgumentParser();p.add_argument('--source-package');args=p.parse_args() def source(path): @@ -16,7 +16,6 @@ def source(path): try:exec(compile(text[:a],str(f),'exec'),ns) finally:sys.argv=argv ns['source']=source;exec(compile(text[a:b],str(f),'exec'),ns);code=ns['code'];code=code[:code.index('int main(void)')] -sp=importlib.util.spec_from_file_location('h',ROOT/'audit/api-security-20261103/tools/extract_inventory.py');h=importlib.util.module_from_spec(sp);sp.loader.exec_module(h) # Trigger one trusted registry replacement immediately after the policy/handler # snapshot unlock. Old code performs a second lookup and invokes the new Root # handler under the earlier public policy; new code invokes its copied handler. diff --git a/tests/runtime/test_port_forward.py b/tests/runtime/test_port_forward.py index cff3354a..44533604 100644 --- a/tests/runtime/test_port_forward.py +++ b/tests/runtime/test_port_forward.py @@ -277,6 +277,9 @@ const char *ts_device_state_to_str(ts_device_state_t state) {return state==TS_DEVICE_STATE_ON?"on":"off";} ''' code += body('components/ts_net/src/ts_eth.c','dhcp_start_task') +system = (IDF / 'components/esp_system/include/esp_system.h').read_text() +code += system[system.index('typedef enum {'):system.index('} esp_reset_reason_t;') + len('} esp_reset_reason_t;')] +code += '\nstatic esp_reset_reason_t esp_reset_reason(void) {return ESP_RST_POWERON;}\n' code += body('components/ts_drivers/src/ts_device_ctrl.c','lpmu_startup_detect_task') code += '#include "' + str(root / 'components/ts_automation/include/ts_action_manager.h') + '"\n' action_source=Path('components/ts_automation/src/ts_action_manager.c').read_text() From 72558738dd659493a80de6fe7a8c8dc1b18f0cae Mon Sep 17 00:00:00 2001 From: Alfred Date: Sun, 8 Nov 2026 20:09:00 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90=20SSH=20=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E5=A4=96=E9=83=A8=E8=AF=BB=E5=8F=96=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/ts_storage/src/ts_storage_paths.c | 4 ++-- tests/runtime/test_external_storage_reads.py | 6 ++++-- tests/runtime/test_storage_paths.c | 7 +++++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/components/ts_storage/src/ts_storage_paths.c b/components/ts_storage/src/ts_storage_paths.c index 9cb4fb02..9b5913d5 100644 --- a/components/ts_storage/src/ts_storage_paths.c +++ b/components/ts_storage/src/ts_storage_paths.c @@ -130,10 +130,10 @@ esp_err_t ts_storage_external_read_requires_admin(const char *path, bool *requir char *end = strchr(normalized + 8, '/'); if (end) *end = 0; const char *name = normalized + 8; - if (!strcasecmp(name, "config") || !strcasecmp(name, "pki")) return ESP_OK; + if (!strcasecmp(name, "config") || !strcasecmp(name, "pki") || !strcasecmp(name, "ssh")) return ESP_OK; char resolved[TS_STORAGE_MAX_PATH]; ret = ts_storage_sd_resolve_name(normalized, resolved, sizeof(resolved)); if (ret != ESP_OK && ret != ESP_ERR_NOT_FOUND) return ret; - *requires_admin = ret == ESP_OK && (!strcasecmp(resolved, "config") || !strcasecmp(resolved, "pki")); + *requires_admin = ret == ESP_OK && (!strcasecmp(resolved, "config") || !strcasecmp(resolved, "pki") || !strcasecmp(resolved, "ssh")); return ESP_OK; } diff --git a/tests/runtime/test_external_storage_reads.py b/tests/runtime/test_external_storage_reads.py index 4fe5794f..4fb64095 100644 --- a/tests/runtime/test_external_storage_reads.py +++ b/tests/runtime/test_external_storage_reads.py @@ -51,6 +51,8 @@ def source(path): if(!strcmp(name,"missing"))return FR_NO_FILE; if(!strcmp(name,"CONFID~1")||!strcmp(name,"confıg"))name="config"; if(!strcmp(name,"PKIPRI~1"))name="pki"; + /* Synthetic resolver return tests the shared alias branch, not an on-card SFN claim. */ + if(!strcmp(name,"SSH_ALIAS"))name="ssh"; snprintf(info->fname,sizeof(info->fname),"%s",name);return FR_OK; } """ @@ -94,8 +96,8 @@ def source(path): {"storage.status",0,3,TS_API_ACCESS_PUBLIC},{"storage.mount",3,14,TS_API_ACCESS_ADMIN},{"storage.unmount",3,14,TS_API_ACCESS_ADMIN},{"storage.list",1,3,TS_API_ACCESS_READ},{"storage.delete",3,14,TS_API_ACCESS_ADMIN},{"storage.mkdir",3,14,TS_API_ACCESS_ADMIN},{"storage.rename",3,14,TS_API_ACCESS_ADMIN},{"storage.info",1,3,TS_API_ACCESS_READ},{"storage.read",1,3,TS_API_ACCESS_READ}}; cJSON *names_all=ts_api_list(TS_API_CAT_MAX);check(cJSON_GetArraySize(names_all)==9,"actual nine storage registrations are complete");cJSON_Delete(names_all); for(unsigned i=0;i<9;i++){ts_api_access_t access={0};check(ts_api_get_access(policies[i].name,&access)==ESP_OK,"all storage policies query");check(access.minimum_level==policies[i].level&&access.allowed_methods==policies[i].methods&&access.external_access==policies[i].mode&&access.requires_auth==(policies[i].level>0),"nine independent role/method contracts");} - const char *private_paths[]={"/sdcard/config/network.json","/sdcard/CONFIG/ssh_hosts/a","/sdcard/foo/../config/wifi.json","/sdcard/config. /wifi.json","/sdcard/config\\wifi.json","/sdcard/confıg/wifi.json","/sdcard/CONFID~1/wifi.json","/sdcard/pki/ca-chain.crt","/sdcard/PKIPRI~1/ca-chain.crt","/spiffs/keys","/www/js/app.js","/autocfg/state.json"}; - const char *data_paths[]={"/sdcard","/sdcard/images/pic.png","/sdcard/自定义/file.txt","/sdcard/logs/sys.log","/sdcard/missing/file.txt","/sdcard/config/../images/pic.png","/sdcard/literal%2Fconfig/file"}; + const char *private_paths[]={"/sdcard/ssh","/sdcard/SSH","/sdcard/ssh/sub/sentinel.txt","/sdcard/foo/../ssh/sentinel.txt","/sdcard/ssh. /sentinel.txt","/sdcard/ssh\\sentinel.txt","/sdcard/SSH_ALIAS/sentinel.txt","/sdcard/config/network.json","/sdcard/CONFIG/ssh_hosts/a","/sdcard/foo/../config/wifi.json","/sdcard/config. /wifi.json","/sdcard/config\\wifi.json","/sdcard/confıg/wifi.json","/sdcard/CONFID~1/wifi.json","/sdcard/pki/ca-chain.crt","/sdcard/PKIPRI~1/ca-chain.crt","/spiffs/keys","/www/js/app.js","/autocfg/state.json"}; + const char *data_paths[]={"/sdcard/ssh-other/sentinel.txt","/sdcard/ssh/../images/pic.png","/sdcard","/sdcard/images/pic.png","/sdcard/自定义/file.txt","/sdcard/logs/sys.log","/sdcard/missing/file.txt","/sdcard/config/../images/pic.png","/sdcard/literal%2Fconfig/file"}; const char *invalid_paths[]={"/sdcard-other/a","/spiffs-other/a","/unknown/a","relative","/","/sdcard/config\t/a"}; const char *names[]={"storage.list","storage.info","storage.read"};unsigned identities[]={0,1,2,3,4,5,99}; for(unsigned who=0;who<7;who++){ diff --git a/tests/runtime/test_storage_paths.c b/tests/runtime/test_storage_paths.c index 0c831753..e9934f16 100644 --- a/tests/runtime/test_storage_paths.c +++ b/tests/runtime/test_storage_paths.c @@ -426,6 +426,12 @@ int main(void) assert(!test_mkdir("/sdcard/config/automation",0755));assert(!test_mkdir("/autocfg",0755)); original_file("/sdcard/config/automation/state.json","current"); original_file("/sdcard/config/ordinary.json","ordinary"); + assert(!test_mkdir("/sdcard/ssh",0755)); + original_file("/sdcard/ssh/sentinel.txt","public test sentinel"); + bool ssh_private=false; + assert(ts_storage_external_read_requires_admin("/sdcard/ssh/sentinel.txt",&ssh_private)==ESP_OK&&ssh_private); + has_text("/sdcard/ssh/sentinel.txt","public test sentinel"); + puts("PASS protected SSH sentinel: internal production reader retains original bytes"); original_file("/autocfg/state.json","emergency"); original_code_volume(); @@ -507,6 +513,7 @@ int main(void) recursive_names(); /* Cleanup through the raw test VFS, since the configuration owner is private. */ + assert(!test_unlink("/sdcard/ssh/sentinel.txt"));assert(!test_rmdir("/sdcard/ssh")); assert(!test_unlink("/sdcard/config/ordinary.json"));assert(!test_unlink("/sdcard/config/automation/state.json")); assert(!test_rmdir("/sdcard/config/automation"));assert(!test_rmdir("/sdcard/config")); assert(!test_rmdir("/sdcard"));assert(!test_unlink("/autocfg/state.json")); From ab24b678dfa5c788d70bc7137eab79d646bd04e7 Mon Sep 17 00:00:00 2001 From: Alfred Date: Mon, 9 Nov 2026 00:07:28 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20=E6=81=A2=E5=A4=8D=20Webhook=20?= =?UTF-8?q?=E5=92=8C=20PKI=20=E7=9A=84=E5=8E=9F=E6=9C=89=E9=87=8D=E5=AE=9A?= =?UTF-8?q?=E5=90=91=E8=A1=8C=E4=B8=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ts_automation/src/ts_action_manager.c | 2 +- .../ts_http_fetch/include/ts_http_fetch.h | 4 +- components/ts_http_fetch/src/ts_http_fetch.c | 158 ++++++++++++++---- components/ts_pki_client/src/ts_pki_client.c | 2 +- components/ts_security/include/ts_keystore.h | 4 +- .../http_fetch_stubs/esp_http_client.h | 1 + tests/runtime/test_http_fetch.py | 69 +++++++- tests/runtime/test_pki_http.py | 1 + 8 files changed, 194 insertions(+), 47 deletions(-) diff --git a/components/ts_automation/src/ts_action_manager.c b/components/ts_automation/src/ts_action_manager.c index fee96503..4825e13f 100644 --- a/components/ts_automation/src/ts_action_manager.c +++ b/components/ts_automation/src/ts_action_manager.c @@ -1395,7 +1395,7 @@ static esp_err_t execute_webhook(const ts_auto_action_t *action) ts_http_fetch_config_t request = {.url = action->webhook.url, .method = method, .content_type = method == HTTP_METHOD_POST || method == HTTP_METHOD_PUT ? "application/json" : NULL, .body = action->webhook.body_template[0] ? action->webhook.body_template : NULL, - .timeout_ms = 5000, .maximum_body = 8192, .headers_only = true}; + .timeout_ms = 5000, .maximum_body = 8192, .headers_only = true, .follow_redirects = true}; ts_http_fetch_result_t reply = {0}; esp_err_t ret = ts_http_fetch(&request, &reply); if (ret == ESP_OK && (reply.status < 200 || reply.status >= 300)) ret = ESP_FAIL; diff --git a/components/ts_http_fetch/include/ts_http_fetch.h b/components/ts_http_fetch/include/ts_http_fetch.h index cfa4017c..7c184639 100644 --- a/components/ts_http_fetch/include/ts_http_fetch.h +++ b/components/ts_http_fetch/include/ts_http_fetch.h @@ -22,6 +22,8 @@ typedef struct { size_t maximum_body; /* Webhooks need only a complete HTTP status/header acknowledgment. */ bool headers_only; + /* Only legacy perform consumers opt in; ordinary fetch returns the first hop. */ + bool follow_redirects; bool (*current)(void *); void *context; } ts_http_fetch_config_t; @@ -37,6 +39,6 @@ typedef struct { } ts_http_fetch_result_t; /* Worker entry; callers enforce permission/configuration authority. * Nonblocking SDK polls; no new task or global job. - * DNS, connect, headers and body share one deadline. Redirects are never followed. + * DNS, connect, headers and body share one deadline. Opt-in redirects retain this same owner and deadline. * On success the caller owns body; failure clears it. Release with free(). */ esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_result_t *result); diff --git a/components/ts_http_fetch/src/ts_http_fetch.c b/components/ts_http_fetch/src/ts_http_fetch.c index 2fb80d84..98bda6f5 100644 --- a/components/ts_http_fetch/src/ts_http_fetch.c +++ b/components/ts_http_fetch/src/ts_http_fetch.c @@ -17,8 +17,9 @@ typedef struct { ts_http_fetch_result_t *result; int64_t deadline, started; size_t received; - bool acknowledged; - esp_err_t error; + bool acknowledged, redirected; + char *location, *username, *password; + esp_err_t error, location_error; } fetch_t; static esp_err_t current(fetch_t *owner) @@ -48,7 +49,30 @@ static esp_err_t receive(esp_http_client_event_t *event) * returned; the cumulative wire budget and deadline never reset. */ owner->result->length = 0; if (owner->result->body) owner->result->body[0] = 0; - owner->acknowledged = false; + owner->acknowledged = owner->redirected = false; + free(owner->location); owner->location = NULL; + owner->location_error = ESP_OK; + } else if (event->event_id == HTTP_EVENT_ON_HEADER && owner->request->follow_redirects && + event->header_key && !strcasecmp(event->header_key, "Location")) { + const char *value = event->header_value; + size_t length = value ? strnlen(value, TS_HTTP_URL_LIMIT + 1) : 0; + free(owner->location); owner->location = NULL; + /* SDK publishes the response status after ON_HEADER. Defer any + * Location error until an actual REDIRECT; 2xx Location is ordinary. */ + owner->location_error = ESP_OK; + if (!length || length > TS_HTTP_URL_LIMIT) owner->location_error = ESP_ERR_INVALID_RESPONSE; + else { + owner->location = strndup(value, length); + if (!owner->location) owner->location_error = ESP_ERR_NO_MEM; + } + } else if (event->event_id == HTTP_EVENT_REDIRECT && owner->request->follow_redirects) { + if (owner->location_error != ESP_OK || !owner->location) { + stop(owner, event->client, owner->location_error != ESP_OK ? owner->location_error : ESP_ERR_INVALID_RESPONSE); + return owner->error; + } + owner->redirected = true; + /* End this hop without draining an arbitrary redirect response body. */ + esp_http_client_close(event->client); } else if (event->event_id == HTTP_EVENT_ON_DATA && event->data_len > 0) { owner->result->status = esp_http_client_get_status_code(event->client); if (owner->request->headers_only && owner->result->status >= 200 && owner->result->status < 300) { @@ -109,35 +133,52 @@ static bool headers_valid(const ts_http_fetch_config_t *request) return true; } -esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_result_t *result) +/* SDK set_url keeps credentials when Location omits userinfo. A username-only + * replacement also retains the prior password. Keep that existing contract. */ +static esp_err_t credentials(fetch_t *owner, const char *user_info) +{ + const char *colon = strchr(user_info, ':'); + char *username = colon ? strndup(user_info, (size_t)(colon - user_info)) : strdup(user_info); + char *password = colon ? strdup(colon + 1) : NULL; + if (!username || (colon && !password)) { free(username); free(password); return ESP_ERR_NO_MEM; } + free(owner->username); owner->username = username; + if (colon) { free(owner->password); owner->password = password; } + return ESP_OK; +} + +static esp_err_t redirect_url(const char *base, const char *location, char **next) { - if (!result) return ESP_ERR_INVALID_ARG; - memset(result, 0, sizeof(*result)); - if (!request || !request->timeout_ms || request->timeout_ms > 30000 || - !request->maximum_body || request->maximum_body > FETCH_BODY_LIMIT || - (request->method != HTTP_METHOD_GET && request->method != HTTP_METHOD_POST && - request->method != HTTP_METHOD_PUT && request->method != HTTP_METHOD_DELETE) || - (request->body && strnlen(request->body, FETCH_HEADER_LIMIT + 1) > FETCH_HEADER_LIMIT) || - !headers_valid(request)) return ESP_ERR_INVALID_ARG; struct http_parser_url parsed; - if (!ts_http_url_parse(request->url, &parsed) || - (request->cert_pem && (parsed.field_data[UF_SCHEMA].len != 5 || - strnlen(request->cert_pem, 16385) > 16384))) return ESP_ERR_INVALID_ARG; - int64_t started = esp_timer_get_time(); - fetch_t owner = {.request = request, .result = result, .started = started, - .deadline = started + (int64_t)request->timeout_ms * 1000}; - esp_err_t error = current(&owner); - if (error != ESP_OK) return error; - if (!request->headers_only) { - result->body = heap_caps_malloc(request->maximum_body + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); - if (!result->body) result->body = malloc(request->maximum_body + 1); - if (!result->body) return ESP_ERR_NO_MEM; - result->body[0] = 0; + size_t prefix = 0, length = strlen(location); + if (!ts_http_url_parse(location, &parsed)) { + /* SDK accepts root-relative paths, but rejects bare relative names. + * Preserve the logical authority and query, never the resolved IP URL. */ + if (location[0] != '/') return ESP_ERR_INVALID_ARG; + const char *authority = strstr(base, "://") + 3; + prefix = (size_t)(authority - base) + strcspn(authority, "/?#"); } + if (prefix + length > TS_HTTP_URL_LIMIT) return ESP_ERR_INVALID_SIZE; + char *url = malloc(prefix + length + 1); + if (!url) return ESP_ERR_NO_MEM; + memcpy(url, base, prefix); memcpy(url + prefix, location, length + 1); + if (!ts_http_url_parse(url, &parsed)) { free(url); return ESP_ERR_INVALID_ARG; } + *next = url; + return ESP_OK; +} + +static esp_err_t fetch_hop(fetch_t *owner, const char *url) +{ + const ts_http_fetch_config_t *request = owner->request; + ts_http_fetch_result_t *result = owner->result; + esp_err_t error; + owner->acknowledged = owner->redirected = false; + free(owner->location); owner->location = NULL; + result->length = 0; + if (result->body) result->body[0] = 0; ts_http_target_t target = {0}; - error = ts_http_target_resolve(request->url, owner.deadline, request->current, request->context, &target); + error = ts_http_target_resolve(url, owner->deadline, request->current, request->context, &target); esp_http_client_handle_t client = NULL; - result->dns_time_ms = (esp_timer_get_time() - started) / 1000; + result->dns_time_ms = (esp_timer_get_time() - owner->started) / 1000; if (error != ESP_OK) goto done; result->dns_ok = true; struct http_parser_url numeric; @@ -147,15 +188,17 @@ esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_res } memcpy(result->resolved_ip, target.url + numeric.field_data[UF_HOST].off, numeric.field_data[UF_HOST].len); result->resolved_ip[numeric.field_data[UF_HOST].len] = 0; - char *password = target.user_info ? strchr(target.user_info, ':') : NULL; - if (password) *password++ = 0; + if (target.user_info) { + error = credentials(owner, target.user_info); + if (error != ESP_OK) goto done; + } esp_http_client_config_t config = {.url = target.url, .method = request->method, .is_async = true, .timeout_ms = 1, .disable_auto_redirect = true, .buffer_size = 2048, .buffer_size_tx = 1024, - .event_handler = receive, .user_data = &owner, + .event_handler = receive, .user_data = owner, .cert_pem = request->cert_pem, .common_name = target.secure ? target.hostname : NULL, .crt_bundle_attach = request->cert_pem ? NULL : esp_crt_bundle_attach, - .username = target.user_info, .password = password}; + .username = owner->username, .password = owner->password}; client = esp_http_client_init(&config); if (!client) { error = ESP_ERR_NO_MEM; goto done; } error = esp_http_client_set_header(client, "Host", target.authority); @@ -173,22 +216,65 @@ esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_res error = esp_http_client_set_post_field(client, request->body, (int)strlen(request->body)); if (error == ESP_OK) { do { - error = current(&owner); + error = current(owner); if (error != ESP_OK) break; error = esp_http_client_perform(client); - if (owner.error != ESP_OK) { error = owner.error; break; } - if (request->headers_only && owner.acknowledged) { error = ESP_OK; break; } + if (owner->error != ESP_OK) { error = owner->error; break; } + if (owner->redirected) { error = ESP_OK; break; } + if (request->headers_only && owner->acknowledged) { error = ESP_OK; break; } if (error == ESP_ERR_HTTP_EAGAIN) vTaskDelay(1); } while (error == ESP_ERR_HTTP_EAGAIN); } - if (error == ESP_OK) error = current(&owner); + if (error == ESP_OK) error = current(owner); result->status = esp_http_client_get_status_code(client); result->content_length = esp_http_client_get_content_length(client); - if (error == ESP_OK && !request->headers_only && !esp_http_client_is_complete_data_received(client)) + if (error == ESP_OK && !owner->redirected && !request->headers_only && !esp_http_client_is_complete_data_received(client)) error = ESP_ERR_INVALID_RESPONSE; done: if (client) esp_http_client_cleanup(client); ts_http_target_free(&target); + return error; +} + +esp_err_t ts_http_fetch(const ts_http_fetch_config_t *request, ts_http_fetch_result_t *result) +{ + if (!result) return ESP_ERR_INVALID_ARG; + memset(result, 0, sizeof(*result)); + if (!request || !request->timeout_ms || request->timeout_ms > 30000 || + !request->maximum_body || request->maximum_body > FETCH_BODY_LIMIT || + (request->method != HTTP_METHOD_GET && request->method != HTTP_METHOD_POST && + request->method != HTTP_METHOD_PUT && request->method != HTTP_METHOD_DELETE) || + (request->body && strnlen(request->body, FETCH_HEADER_LIMIT + 1) > FETCH_HEADER_LIMIT) || + !headers_valid(request)) return ESP_ERR_INVALID_ARG; + struct http_parser_url parsed; + if (!ts_http_url_parse(request->url, &parsed) || + (request->cert_pem && (parsed.field_data[UF_SCHEMA].len != 5 || + strnlen(request->cert_pem, 16385) > 16384))) return ESP_ERR_INVALID_ARG; + int64_t started = esp_timer_get_time(); + fetch_t owner = {.request = request, .result = result, .started = started, + .deadline = started + (int64_t)request->timeout_ms * 1000}; + esp_err_t error = current(&owner); + if (error != ESP_OK) return error; + if (!request->headers_only) { + result->body = heap_caps_malloc(request->maximum_body + 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (!result->body) result->body = malloc(request->maximum_body + 1); + if (!result->body) return ESP_ERR_NO_MEM; + result->body[0] = 0; + } + char *redirected_url = NULL; + const char *url = request->url; + for (unsigned redirects = 0;; ++redirects) { + error = current(&owner); + if (error != ESP_OK) break; + error = fetch_hop(&owner, url); + if (error != ESP_OK || !owner.redirected) break; + if (redirects == 10) { error = ESP_ERR_HTTP_MAX_REDIRECT; break; } + char *next = NULL; + error = redirect_url(url, owner.location, &next); + if (error != ESP_OK) break; + free(redirected_url); redirected_url = next; url = next; + } + free(redirected_url); free(owner.location); free(owner.username); free(owner.password); if (error != ESP_OK) { free(result->body); result->body = NULL; result->length = 0; } diff --git a/components/ts_pki_client/src/ts_pki_client.c b/components/ts_pki_client/src/ts_pki_client.c index afd68a53..35d3a988 100644 --- a/components/ts_pki_client/src/ts_pki_client.c +++ b/components/ts_pki_client/src/ts_pki_client.c @@ -672,7 +672,7 @@ static esp_err_t do_http_request(const char *url, esp_http_client_method_t metho ts_http_fetch_config_t request = { .url = url, .method = method, .body = post_data, .content_type = post_data ? "application/json" : NULL, - .timeout_ms = timeout_ms, .maximum_body = HTTP_RESP_BUF_SIZE - 1, + .timeout_ms = timeout_ms, .maximum_body = HTTP_RESP_BUF_SIZE - 1, .follow_redirects = true, .current = request_current, .context = xTaskGetCurrentTaskHandle(), }; ts_http_fetch_result_t reply = {0}; diff --git a/components/ts_security/include/ts_keystore.h b/components/ts_security/include/ts_keystore.h index c93cd1d4..969e247c 100644 --- a/components/ts_security/include/ts_keystore.h +++ b/components/ts_security/include/ts_keystore.h @@ -104,7 +104,7 @@ typedef struct { uint32_t last_used; /**< Last used timestamp */ bool has_public_key; /**< Whether public key is stored */ bool exportable; /**< Whether private key can be exported */ - bool hidden; /**< Whether key ID is hidden from non-Root external readers */ + bool hidden; /**< Whether key ID is hidden from external readers below Admin */ } ts_keystore_key_info_t; /** @@ -114,7 +114,7 @@ typedef struct { bool exportable; /**< Allow private key export (default: false) */ const char *comment; /**< Key comment (optional) */ const char *alias; /**< Display alias (optional, recommended for hidden keys) */ - bool hidden; /**< Hide key ID from non-Root external readers (default: false) */ + bool hidden; /**< Hide key ID from external readers below Admin (default: false) */ } ts_keystore_gen_opts_t; /** Per-call generation outcome. Storage success is independent of HTTP delivery. */ diff --git a/tests/runtime/http_fetch_stubs/esp_http_client.h b/tests/runtime/http_fetch_stubs/esp_http_client.h index 6b7b8687..dacb5adb 100644 --- a/tests/runtime/http_fetch_stubs/esp_http_client.h +++ b/tests/runtime/http_fetch_stubs/esp_http_client.h @@ -3,6 +3,7 @@ #include #include "esp_err.h" #define ESP_ERR_HTTP_EAGAIN 0x7001 +#define ESP_ERR_HTTP_MAX_REDIRECT 0x7002 typedef struct fixture_client *esp_http_client_handle_t; typedef enum {HTTP_METHOD_GET,HTTP_METHOD_POST,HTTP_METHOD_PUT,HTTP_METHOD_DELETE} esp_http_client_method_t; enum {HTTP_EVENT_ON_CONNECTED,HTTP_EVENT_DISCONNECTED,HTTP_EVENT_ERROR,HTTP_EVENT_HEADERS_SENT,HTTP_EVENT_ON_HEADER, diff --git a/tests/runtime/test_http_fetch.py b/tests/runtime/test_http_fetch.py index 6f9844cf..1cbfb8da 100644 --- a/tests/runtime/test_http_fetch.py +++ b/tests/runtime/test_http_fetch.py @@ -1,6 +1,6 @@ """Actual shared HTTP owner and URL/DNS snapshot; SDK events and clock substituted.""" from pathlib import Path -from test_console_lifecycle import IDF, run_native +from test_console_lifecycle import IDF, run_native, body root=Path(__file__).resolve().parents[2] code=r''' @@ -14,12 +14,19 @@ #include "ts_http_url.h" #include "ts_dns.h" static int scenario; -enum {NORMAL,PARTIAL,TOO_BIG,UNKNOWN_BIG,WAIT,CANCEL,DNS_FAIL,DNS_LATE,AUTH_RETRY,REDIRECT,HEADER_ACK,EXPIRE_EVENT}; +enum {NORMAL,PARTIAL,TOO_BIG,UNKNOWN_BIG,WAIT,CANCEL,DNS_FAIL,DNS_LATE,AUTH_RETRY,REDIRECT,HEADER_ACK,EXPIRE_EVENT,FOLLOW,AUTH_REDIRECT,FINAL_LOCATION}; static int64_t clock_us; static bool actor=true,fail_init,fail_header,fail_body,fail_heap; static unsigned dns_calls,clients,cleanups,closes,performs,checks; static char numeric_url[2300],host_header[300],tls_name[260],authorization[100],body_sent[100]; static const char *expected_ca; +static unsigned redirects; +static int redirect_status; +static const char *locations[3]; +static bool cancel_redirect, slow_redirect, redirect_body; +static char username[64],password[64]; +static esp_http_client_method_t observed_method; + static void check(bool value,const char *message){checks++;if(!value){fprintf(stderr,"FAIL %s scenario=%d\n",message,scenario);abort();}} static void *body_malloc(size_t n){return fail_body?NULL:malloc(n);} static void *body_heap(size_t n,unsigned caps){(void)caps;return fail_heap?NULL:body_malloc(n);} @@ -34,13 +41,13 @@ if(scenario==DNS_LATE){clock_us=deadline;return ESP_ERR_TIMEOUT;} return ESP_OK; } -struct fixture_client {esp_http_client_config_t config;int status;int64_t declared;bool complete,closed;}; +struct fixture_client {esp_http_client_config_t config;int status;int64_t declared;bool complete,closed;unsigned hop;}; esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config){ check(config->is_async&&config->disable_auto_redirect&&!config->skip_cert_common_name_check,"async, no redirect forwarding and mandatory names"); check(config->cert_pem==expected_ca&&(expected_ca?!config->crt_bundle_attach:config->crt_bundle_attach!=NULL),"explicit issuer or SDK bundle"); snprintf(numeric_url,sizeof(numeric_url),"%s",config->url);snprintf(tls_name,sizeof(tls_name),"%s",config->common_name?config->common_name:""); if(fail_init)return NULL; - struct fixture_client *client=calloc(1,sizeof(*client));client->config=*config;client->status=200;client->declared=3;clients++;return client; + struct fixture_client *client=calloc(1,sizeof(*client));client->config=*config;client->status=200;client->declared=3;client->hop=++clients;observed_method=config->method;snprintf(username,sizeof(username),"%s",config->username?config->username:"");snprintf(password,sizeof(password),"%s",config->password?config->password:"");return client; } esp_err_t esp_http_client_set_header(esp_http_client_handle_t client,const char *name,const char *value){(void)client; if(fail_header)return ESP_FAIL; @@ -63,7 +70,28 @@ event(client,HTTP_EVENT_HEADERS_SENT,NULL,0); if(scenario==CANCEL)actor=false; if(scenario==EXPIRE_EVENT)clock_us+=10000000; - if(scenario==REDIRECT){client->status=302;client->declared=0;client->complete=true;event(client,HTTP_EVENT_REDIRECT,NULL,0);event(client,HTTP_EVENT_ON_FINISH,NULL,0);return ESP_OK;} + if(scenario==REDIRECT||(scenario==FOLLOW&&client->hop<=redirects)){ + client->status=redirect_status;client->declared=0;client->complete=true; + const char *location=locations[(client->hop-1)%3]; + client->status=-1; /* Real SDK publishes status after its header event. */ + if(location){esp_http_client_event_t h={.client=client,.event_id=HTTP_EVENT_ON_HEADER,.user_data=client->config.user_data,.header_key="Location",.header_value=(char*)location};client->config.event_handler(&h);} + client->status=redirect_status; + if(redirect_body)event(client,HTTP_EVENT_ON_DATA,"0123456789",10); + if(slow_redirect)clock_us+=10000; + event(client,HTTP_EVENT_REDIRECT,NULL,0); + if(cancel_redirect)actor=false; + if(client->closed)return ESP_FAIL; + event(client,HTTP_EVENT_ON_FINISH,NULL,0);return ESP_OK; + } + if(scenario==FOLLOW&&slow_redirect)clock_us+=10000; + if(scenario==AUTH_REDIRECT){ + client->status=-1;esp_http_client_event_t h={.client=client,.event_id=HTTP_EVENT_ON_HEADER,.user_data=client->config.user_data,.header_key="Location",.header_value="/stale"};client->config.event_handler(&h); + client->status=401;event(client,HTTP_EVENT_ON_FINISH,NULL,0);event(client,HTTP_EVENT_HEADERS_SENT,NULL,0); + client->status=302;event(client,HTTP_EVENT_REDIRECT,NULL,0);return ESP_FAIL; + } + if(scenario==FINAL_LOCATION){ + client->status=-1;esp_http_client_event_t h={.client=client,.event_id=HTTP_EVENT_ON_HEADER,.user_data=client->config.user_data,.header_key="Location",.header_value=(char*)locations[0]};client->config.event_handler(&h);client->status=201; + } if(scenario==AUTH_RETRY){client->status=401;event(client,HTTP_EVENT_ON_DATA,"bad",3);event(client,HTTP_EVENT_ON_FINISH,NULL,0);check(!client->closed,"header-only mode cannot suppress authentication retries");event(client,HTTP_EVENT_HEADERS_SENT,NULL,0);client->status=200;} if(scenario==TOO_BIG)client->declared=9999; if(scenario==UNKNOWN_BIG){client->declared=-1;event(client,HTTP_EVENT_ON_DATA,"1234567890",10);event(client,HTTP_EVENT_ON_DATA,"1234567890",10);} @@ -78,10 +106,15 @@ for name in ['ts_http_target.c','ts_http_fetch.c']: code+='#include "'+str(root/'components/ts_http_fetch/src'/name)+'"\n' code+=r''' +#define TS_AUTO_ACT_WEBHOOK 1 +#define ESP_LOGI(...) ((void)0) +typedef struct {int type;struct {char url[256],method[8],body_template[64];}webhook;}ts_auto_action_t; +'''+body(root/'components/ts_automation/src/ts_action_manager.c','execute_webhook') +code+=r''' #undef malloc static ts_http_fetch_config_t request; static ts_http_fetch_result_t reply; -static void reset(int chosen){scenario=chosen;clock_us=0;actor=true;fail_init=fail_header=fail_body=fail_heap=false;dns_calls=clients=cleanups=closes=performs=0;expected_ca=NULL;numeric_url[0]=host_header[0]=tls_name[0]=authorization[0]=body_sent[0]=0;request=(ts_http_fetch_config_t){.url="https://sensor.fixture:8443/read?x=1",.method=HTTP_METHOD_GET,.timeout_ms=20,.maximum_body=16,.current=caller,.context=&actor};memset(&reply,0,sizeof(reply));} +static void reset(int chosen){redirects=1;redirect_status=302;locations[0]=locations[1]=locations[2]="/final?kept=1";cancel_redirect=slow_redirect=redirect_body=false;username[0]=password[0]=0;scenario=chosen;clock_us=0;actor=true;fail_init=fail_header=fail_body=fail_heap=false;dns_calls=clients=cleanups=closes=performs=0;expected_ca=NULL;numeric_url[0]=host_header[0]=tls_name[0]=authorization[0]=body_sent[0]=0;request=(ts_http_fetch_config_t){.url="https://sensor.fixture:8443/read?x=1",.method=HTTP_METHOD_GET,.timeout_ms=20,.maximum_body=16,.current=caller,.context=&actor};memset(&reply,0,sizeof(reply));} static esp_err_t fetch(void){esp_err_t result=ts_http_fetch(&request,&reply);check(clients==cleanups,"every initialized client is cleaned");if(result!=ESP_OK)check(!reply.body&&!reply.length,"failed/truncated samples cannot become partial success");return result;} int main(void){ reset(NORMAL);check(fetch()==ESP_OK&&reply.length==3&&!strcmp(reply.body,"abc"),"normal complete body");check(reply.dns_ok&&reply.connected&&!strcmp(reply.resolved_ip,"192.0.2.10"),"diagnostic phases come from actual resolver and SDK connection event");check(!strcmp(numeric_url,"https://192.0.2.10:8443/read?x=1")&&!strcmp(host_header,"sensor.fixture:8443")&&!strcmp(tls_name,"sensor.fixture"),"resolved address is pinned while Host/SNI retain original authority");free(reply.body); @@ -93,6 +126,30 @@ reset(HEADER_ACK);request.headers_only=true;check(fetch()==ESP_OK&&reply.status==200&&!reply.body&&closes,"webhook needs no body allocation/drain"); reset(EXPIRE_EVENT);check(fetch()==ESP_ERR_TIMEOUT,"callback data cannot arrive after total deadline"); reset(REDIRECT);check(fetch()==ESP_OK&&reply.status==302&&clients==1,"redirect is returned without another target or credential forwarding");free(reply.body); + const int statuses[]={301,302,303,307,308}; + for(unsigned i=0;i<5;i++){ + reset(FOLLOW);redirect_status=statuses[i];request.follow_redirects=true;request.method=(esp_http_client_method_t)(i%3);request.body="{}";request.authorization="Bearer synthetic"; + check(fetch()==ESP_OK&&reply.status==200&&!strcmp(reply.body,"abc")&&clients==2&&dns_calls==2,"opt-in legacy redirect follows with per-hop DNS and final body"); + check(observed_method==request.method&&!strcmp(body_sent,"{}")&&!strcmp(authorization,"Bearer synthetic")&&!strcmp(numeric_url,"https://192.0.2.10:8443/final?kept=1"),"301/302/303/307/308 preserve method/body/headers and query");free(reply.body); + } + reset(FOLLOW);request.follow_redirects=true;request.url="https://alice:first@sensor.fixture:8443/start";redirects=3;locations[1]="https://bob@next.fixture:9443/final?kept=2";locations[2]="https://carol:new@third.fixture/final?kept=3"; + check(fetch()==ESP_OK&&clients==4&&dns_calls==4&&!strcmp(host_header,"third.fixture")&&!strcmp(tls_name,"third.fixture")&&!strcmp(numeric_url,"https://192.0.2.10:443/final?kept=3")&&!strcmp(username,"carol")&&!strcmp(password,"new"),"new authorities re-resolve Host/SNI and explicit URL credentials replace");free(reply.body); + reset(FOLLOW);request.follow_redirects=true;request.url="https://alice:first@sensor.fixture/start";locations[0]="https://bob@next.fixture/final"; + check(fetch()==ESP_OK&&!strcmp(username,"bob")&&!strcmp(password,"first"),"SDK username-only replacement retains prior password");free(reply.body); + reset(FOLLOW);request.follow_redirects=true;request.url="https://alice:first@sensor.fixture/start"; + check(fetch()==ESP_OK&&!strcmp(username,"alice")&&!strcmp(password,"first"),"root-relative redirect retains URL credentials");free(reply.body); + reset(FOLLOW);request.follow_redirects=true;redirects=11;check(fetch()==ESP_ERR_HTTP_MAX_REDIRECT&&clients==11,"only ten redirects, every hop cleaned"); + reset(FOLLOW);request.follow_redirects=true;locations[0]="next";check(fetch()==ESP_ERR_INVALID_ARG&&clients==1,"bare relative Location stays unsupported"); + reset(FOLLOW);request.follow_redirects=true;locations[0]=NULL;check(fetch()==ESP_ERR_INVALID_RESPONSE&&clients==1,"missing Location fails without retry"); + char long_location[2050];memset(long_location,'a',sizeof(long_location));long_location[0]='/';long_location[sizeof(long_location)-1]=0; + reset(FOLLOW);request.follow_redirects=true;locations[0]=long_location;check(fetch()==ESP_ERR_INVALID_RESPONSE&&clients==1,"Location uses the existing bounded URL limit"); + reset(AUTH_REDIRECT);request.follow_redirects=true;check(fetch()==ESP_ERR_INVALID_RESPONSE&&clients==1,"401 retry clears previous Location before a headerless302"); + for(unsigned i=0;i<2;i++){reset(FINAL_LOCATION);request.follow_redirects=true;locations[0]=i?long_location:"";check(fetch()==ESP_OK&&reply.status==201&&!strcmp(reply.body,"abc")&&clients==1,"empty/long Location on201 is ignored,not a new success restriction");free(reply.body);} + reset(FOLLOW);request.follow_redirects=true;slow_redirect=true;check(fetch()==ESP_ERR_TIMEOUT&&clients==2,"deadline never resets on a redirect"); + reset(FOLLOW);request.follow_redirects=true;cancel_redirect=true;check(fetch()==ESP_ERR_INVALID_STATE&&clients==1&&dns_calls==1,"cancelled owner cannot resolve or start the next hop"); + reset(FOLLOW);request.follow_redirects=true;redirect_body=true;request.maximum_body=12;check(fetch()==ESP_ERR_INVALID_SIZE&&clients==2,"redirect and final data share the cumulative body budget"); + reset(FOLLOW);ts_auto_action_t action={.type=TS_AUTO_ACT_WEBHOOK,.webhook={.url="https://sensor.fixture/start",.method="POST",.body_template="{}"}}; + check(execute_webhook(&action)==ESP_OK&&clients==2&&cleanups==2&&observed_method==HTTP_METHOD_POST&&!strcmp(body_sent,"{}"),"actual Webhook opts in and accepts redirected200 without creating configured actions"); reset(NORMAL);fail_init=true;check(fetch()==ESP_ERR_NO_MEM,"client allocation failure releases body and target"); reset(NORMAL);fail_header=true;check(fetch()==ESP_FAIL&&!performs,"request setup failure precedes transport effects"); reset(NORMAL);fail_body=true;check(fetch()==ESP_ERR_NO_MEM&&!dns_calls&&!clients,"body allocation fails before DNS/transport"); diff --git a/tests/runtime/test_pki_http.py b/tests/runtime/test_pki_http.py index 4c8b2302..69748c5c 100644 --- a/tests/runtime/test_pki_http.py +++ b/tests/runtime/test_pki_http.py @@ -69,6 +69,7 @@ bool ts_cert_prerequisites(const ts_cert_pki_status_t *s,bool ca){(void)s;(void)ca;return false;} esp_err_t ts_http_fetch(const ts_http_fetch_config_t *req,ts_http_fetch_result_t *out){ captured_timeout=req->timeout_ms;snprintf(requested_url,sizeof(requested_url),"%s",req->url);requests++;check(req->timeout_ms>0&&req->timeout_ms<=TS_PKI_HTTP_TIMEOUT_MS&&req->maximum_body==8191,"existing PKI 30s total/8KiB reply limit passes to shared owner"); + check(req->follow_redirects,"legacy PKI perform consumer explicitly follows redirects"); check(req->method==HTTP_METHOD_GET||req->method==HTTP_METHOD_POST,"PKI methods retained"); if(req->method==HTTP_METHOD_POST){check(req->content_type&&!strcmp(req->content_type,"application/json")&&req->body,"CSR JSON content type/body retained");int saved_budget=atomic_exchange(&json_budget,-1);cJSON *csr=cJSON_Parse(req->body);check(csr&&cJSON_IsString(cJSON_GetObjectItem(csr,"csr_pem"))&&cJSON_IsString(cJSON_GetObjectItem(csr,"device_id"))&&cJSON_IsString(cJSON_GetObjectItem(csr,"description"))&&cJSON_IsArray(cJSON_GetObjectItem(csr,"suggested_san_ips")),"every transmitted CSR body retains all required fields");cJSON_Delete(csr);json_budget=saved_budget;} if(fixture_error!=ESP_OK)return fixture_error;