Skip to content

Add authenticated HTTPS to the existing target 6 HTTP interface - #936

Draft
araxis wants to merge 74 commits into
GideonZ:masterfrom
araxis:feature/https-client
Draft

araxis wants to merge 74 commits into
GideonZ:masterfrom
araxis:feature/https-client

Conversation

@araxis

@araxis araxis commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Goal

Add authenticated HTTPS to the existing command-target 6 HTTP interface. Callers use the same HTTP operations and choose http:// or https:// in the URL. The transport is separated from the TLS provider so the backend can be replaced without changing that interface.

Status: draft. Controller versions 1.38 (default) and 1.39 (HTTPS provider) are provisional. The default firmware leaves the provider disabled. Confirm version allocation and merge order before installation. Hardware validation and recovery qualification remain open.

Implemented in this revision

  • Replaced the prototype-specific transport with a replaceable secure provider and a single-owner TLS session on the controller.

  • Connected native and ESP32 components with validated identity, capability negotiation, session ownership and bounded requests.

  • Added fail-closed handling for authentication failures, unavailable trust/time/entropy, expired deadlines, cancellation and restart invalidation.

  • Included the current upstream Wi-Fi reply checks and CA store, and retained plain HTTP regression coverage.

  • Fixed application-provider linkage in the U64-II factory target and parser preparation in reused submodule checkouts, with regressions for both failures.

  • Integrated the controlled HTTPS campaign with run-tests: explicit-only selection, offline preparation, gated execution, independent peer-log audit and standard reports. Ordinary profiles cannot start it, and unaudited execution cannot report a pass.

  • Moved boot-identity generation after successful Wi-Fi RF startup, removing application SARADC entropy manipulation. Failed starts and zero identities fail closed; reconnects retain the same boot identity.

  • Merged upstream Wi-Fi changes. Opening the AP scan list now preserves an active HTTPS session; disabling Wi-Fi or losing the link still cancels it. Added coverage in the upstream Wi-Fi host harnesses.

  • Integrated #1043: plain HTTP sends the entire request to a slow reader and times out if the peer stops making progress. An interrupted partial write resumes at the first unsent byte. HTTPS still uses its provider and its own deadlines.

  • Integrated #1072 and #1073. HTTP and HTTPS exchanges run on the network worker. If the C64 aborts while the worker’s reply is being prepared, that reply is discarded and the next command can run.

The independent HTTP fixes were split out and merged in #955, #956, #957 and #958. This branch retains those changes and focuses on the HTTPS integration.

Validation

After merging upstream 40188c7d, both controller images were rebuilt against the updated 112-root certificate bundle. The embedded bundle checks passed on both images. All 86 HTTP/HTTPS host-suite steps and all four reconnect and restart probes passed locally at e32d5c69.

Owner recovery at a3f6ee38 builds on JC-000’s reconnect fix. A matching Busy during cleanup keeps HTTPS unavailable. The owner retries initialization on the same offer for up to 1.5 seconds and admits work only after a matching success. If a control reply times out, the old session is retired. A fresh handshake requires a different ESP32 boot identity and cancellation of the old provider lifetime.

Both cases failed on 220e052ea and passed with this change. All 86 host-suite steps passed, including 184 RSA/ECDSA loopback cases (7,620 checks). Physical reconnect and reboot validation is still pending. Before-and-after traces and full host results

At 45f1119a, the read-cancellation test waits until TLS has authenticated and the client starts reading the HTTP response. With a 250 ms handshake delay, the old fixture cancelled at 164 ms without sending HTTP. The fixed fixture cancelled during the read at 292 ms; the peer received the exact request and the next request succeeded. The 750 ms limit is unchanged.

All 82 host stages passed: 18,971 assertions, 37 parser tests, and 184 RSA/ECDSA cases with 184 recovery exchanges. These include 34 read-cancellation cases. Download the before/after logs, peer records and audit. SHA-256: 8ede116e9f4a7575ba931a92034302893df5e7eb2a35fe839254d35b99a79f95. Build passed; HTTPS host validation passed.

Previous firmware and host validation: 13a2a1bb, including upstream 700c7f2f. Download build logs, host results and peer records. SHA-256: 0dfb630ba09b56833d22d07a2ffd793ab615c2976549c800f09855974940f784.

Checks at 13a2a1b Result
HTTPS host validation 82 stages; 18,937 assertions, 37 parser tests and 184 RSA/ECDSA cases. Independent audit verified peer traffic and rejected all seven altered/missing evidence samples.
HTTP and command regressions 95 dispatcher checks, 135 HTTP worker checks, 17 slow-server checks and 296 network-target checks passed. Coverage includes abort during reply preparation, rejection of a late reply and successful execution of the next command.
Firmware and upstream host tests U64-II default, journal and factory builds, U2/U2+L applications, both IDF 5.3.1 controller variants and their recovery trust bundles passed. U64-II packaging passed for 50T and 100T with the default controller. Upstream make host_tests passed.
Hosted CI HTTPS host validation passed; Build passed.

Earlier results below retain their original revisions. This merge does not include the separate IDF 6 migration or new hardware results.

Environment Recorded result
Previous merge at 85a3335 85a33354, including upstream 303af3a9. Download the build logs, host results and peer records. SHA-256: 2590628d79e7774960a943ba9bf26f2ccdb8fbd16b0a6a22ff7b1d97a6bb4b5a. HTTPS host validation passed; Build passed.
Previous merge at 6c09980 6c099801, including upstream b57d894a. Download the build logs, host results and peer records. SHA-256: af204e2765a8e482d95466752616a4f84aff6436b5db8dfa5b65017657d6222a. Build passed; HTTPS host validation passed.
Hosted CI at 7355a3e Full firmware build and HTTPS host validation passed.
Local host regression At d11f5e9: 82 stages passed serially, with 18,865 assertions, 37 parser tests and 184 RSA/ECDSA TLS cases with recovery. Four new startup tests are counted separately. The raw-log/peer audit and all seven evidence rejection controls passed.
Earlier native/build isolation checks Default and enabled native/ESP32 builds; corrected U64-II factory, default and journal-enabled builds; sanitized normal/factory/recovery command tests passed.
Controller startup/versioning at d11f5e9 Four focused regressions pass after old-source failures; three deliberately reintroduced defects rejected. Default/provider modules build on IDF 5.3.1 and 5.3.6; binary labels, configuration, artifact hashes and boot-object dependencies audited.
IDF 6 compatibility New boot API compiles against IDF 6.0.3. TLS and recovery probes fail on removed crypto APIs; PSA/UART migration remains. No complete IDF 6 build or runtime qualification claimed.
Parser preparation All 14 regression tests passed; both workflows run this regression.
Embedded QEMU fixture 644 checks across 48 attempts passed. This is emulator evidence.
Evidence validation Audits rejected all seven host and 24 embedded missing/altered evidence examples.
Runner integration at 10948ad Six entry-policy tests, seven controller contracts (including 12 synthetic evidence mutations), 122 framework checks, registry/lint/documentation checks passed in the publication checkout. Default 6502 agent assembly is byte-identical to the parent; the opt-in cancellation variant assembles.
Host-only runner loopback 43 real HTTP/TLS exchanges, 131 simulated UCI transactions and 180.146 seconds of idle; complete evidence passed independent audit and stopped evidence was rejected. No 6502, controller or ESP32 firmware executes in this substitute transport.
Reporting regression 115 cases, no failures, three documented video-related skips; ordinary 1528-line golden report unchanged.
Physical hardware, current HTTPS revision Not yet qualified. Earlier prototype hardware results are preserved in published history and are not counted as passes for this revision.

Remaining before ready for review

  • Qualify the C64U recovery procedure and controller image verification before installation. The open question is the exact ESP32 USB power and boot sequence; see the recovery question.
  • Connect the controlled bring-up matrix to the current run-tests framework and validate the entry, safeguards, reporting and loopback audit locally. Physical execution is still pending.
  • Validate revised-firmware HTTPS on physical hardware, including native UART behavior, resource use, cancellation, restart and cleanup.
  • Agree shared UART allocation and compatibility with the other TLS proposals.
  • Coordinate the PSA/UART/SDK migration with #1028 and reconcile controller version numbers before merge.
  • Verify that read cancellation occurs after authentication, including when the handshake takes longer than the old timer.

The ordinary updater retains upstream behavior. The separate experimental paired updater and RAM diagnostic remain under review and are not installation-ready artifacts. Passing host, build and emulator tests does not establish hardware readiness.

Documentation and evidence

Raw evidence archives and SHA-256 checksums
Resolved build failures and retained evidence

The first combined dispatcher failed an abort-during-publication test: it accepted an empty command before the abort was handled. The fix keeps the interrupt masked until the reply is accepted or abort cleanup resets it. The evidence includes the failing and passing runs.

The first #1043 merge passed the real socket tests, but the routing test used a fake descriptor with the real socket timeout call. The updated harness checks both timeout settings and verifies that rejecting either closes the socket without sending. The new evidence archive retains the failed and passing results.

The factory-test build failed at bf5c7b0 because the command-only target linked an application provider hook. A fresh build reproduced the failure. The corrected target excludes that hook; the regression fails without the fix, and the corrected builds and host suite pass. The factory-build archive above retains both outcomes.

A subsequent hosted build stopped before compilation during parser preparation. A forced submodule checkout had restored tracked files while retaining a patch-created test. The helper now accepts that file only when its contents match the reviewed hash, and still rejects unexpected edits. The parser-preparation archive retains the failure and passing reruns. Hosted CI subsequently passed at 7355a3e.

The startup evidence also retains a connected ECDSA command-read-cancel peer-check failure: its 150 ms timer fired before authentication completed. The unchanged suite subsequently passed serially; the timing race is reproduced and fixed in 45f1119a (see Validation). Initial test-harness and Windows export line-ending failures are retained too. No acceptance check or production deadline was relaxed.

These archives preserve earlier failures and limitations; repeated full-suite runs are not added together to inflate the test totals.

@chrisgleissner

chrisgleissner commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Hi @araxis,

Thanks for your PR.

The tests you added do not follow the established directory structure for E2E tests.

Also, your PR description is very difficult to follow and does not clearly state the problem which your PR addresses, how it addresses it, and which E2E tests you ran against which devices. We normally expect runs at least against an Ultimate 64, but ideally also against an Ultimate II cartridge

Thanks for improving the PR further. As reference, please have a look at PR #929 or other recently merged PRs.

Thanks

@araxis

araxis commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Hi @chrisgleissner, thanks for taking the time to review this and for pointing me to #929. I've moved the tests into the established E2E/soak directory structure and revised the description to clarify the goal, implementation, and tests run on each device. I've also made the remaining hardware coverage gaps explicit. I hope the update makes the PR easier to review. Thanks again!

@chrisgleissner

chrisgleissner commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for these amendments @araxis. It is appreciated. I see you used a 'Commodore 64 Ultimate, Slimline BASIC Beige, pinned retail v14 candidate' for testing. May I ask how you managed to acquire a slimline C64U given their shipment has not yet started as far as I know (I ordered one myself), and what v14 means?

@barryw, I know you have done a lot of work to support HTTPS. Could you please review this PR? Thanks

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, @araxis. I built the branch for u64, u64ii, u2, u2plus and u2plus_L. I then ran the new suites, plus a set of target 6 checks against a local HTTP server, on master and on this branch. The devices were an Ultimate 64 Elite and an Ultimate II+L in a C64 Ultimate. Details are in the inline comments; this is the summary.

Blocking

  1. A clean checkout does not compile. HTTP_RESPONSE_STRICT exists only in a patch that CI applies to the httpd submodule.
  2. HTTPS is built only for the Ultimate 64 Elite II and the C64 Ultimate. On the Ultimate 64 and the U2+L, https:// returns 503. The TLS worker also fits in the flash of both of their ESP firmwares, so this is a scope decision rather than a hardware limit. Either way, the description should say so.
  3. The strict parser returns 503 for plain HTTP responses with more than 20 header fields, which master handled. That includes small API responses such as those from api.github.com.

Plain HTTP fixes that already work

I measured each of these failing on master and passing on this branch, on both devices:

  • Raw bodies over 895 bytes: on master, a reply block of 896 bytes never clears DATA_AV, so the client hangs.
  • Raw headers of 256 bytes or more: master returns an empty status.
  • #771: on master, REST stopped answering within 20 refused connects. On this branch, target 6 and REST still worked after 40.
  • Handles are now released on a C64 reset.
  • Close-delimited bodies: master returns them empty.
  • A crash on the Ultimate 64 when the server closes before a complete header. On master, an https:// URL is sent as plain HTTP to port 443, which triggers the same crash.

None of these needs the TLS work, so a separate small PR could be merged quickly. The description should also list them; at the moment it mentions only #771.

Tests

On both devices, every device suite fails on this branch too. The HTTP parts pass and the HTTPS parts get 503; the repetition suite scored 40/40 on HTTP and 0/40 on HTTPS. Three suites stop at the telemetry preflight. The suites also leave the Command Interface setting disabled and refuse u2@c64u (see inline). On master, the lifecycle suite fails its 895-byte assertion and the smoke suite crashes the Ultimate 64, so the HTTP assertions catch what they target. The device-free https-harness passes.

TLS support and security

The certificate handling is right. It requires verification, checks the host name and sends SNI, and checks validity dates against SNTP time no more than 24 hours old. It requires TLS 1.2 or newer and never falls back to plain text.

I checked 36 public HTTPS endpoints with OpenSSL set up like the ESP: TLS 1.2 only, no ChaCha20, and the ESP-IDF 5.3 certificate bundle as the only trust store. Every endpoint that uses a host name and was up (34 of them) completed the handshake and verified. TLS itself therefore does not limit reachability today. The limits are:

  • There is no TLS 1.3, so servers that require it will fail.
  • The trust store is fixed in the ESP image. Servers with a private or self-signed CA cannot be reached, and changes to the root CAs need an ESP update.
  • HTTPS is unavailable until SNTP has synchronised.
  • Static RSA and static ECDH key exchange, and CBC suites, are offered (see inline).

Design

TLS on the ESP with TCP on the main CPU is a sound split. It works over Ethernet as well as WiFi, it uses the ESP's hardware RNG, and it keeps mbedTLS out of an application with little space left. My concerns are about scope:

  • unused client code
  • telemetry exposed as REST API
  • an epoch persisted in /flash
  • the retail C64U build recipe, and about 2,000 lines of evidence documents (tools/c64u_https, doc/https-*, https-host.yml) that describe this PR's process rather than the firmware

The hardware results in the description come from that retail 1.1.0 backport, not from this branch. The new C and C++ code is also much denser than the rest of the tree, which makes it hard to merge by hand.

Comment thread software/network/http_request.cc Outdated
if (socket_fd >= 0 || secure_connection) return -1;
InitReqMessage(&this->response);
this->response.usedAsResponseFromServer = 1;
this->response.usedAsResponseFromServer = HTTP_RESPONSE_STRICT;

@chrisgleissner chrisgleissner Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTTP_RESPONSE_STRICT is not defined in the pinned httpd submodule (ad73d32). It exists only in tools/c64u_https/httpd-response.patch, which the workflows apply before they build. A normal checkout therefore fails on every target that compiles this file: u2, u2plus, u2plus_L, u64 and u64ii. On u64:

software/network/http_request.cc:23:47: error: 'HTTP_RESPONSE_STRICT' was not declared in this scope

software/httpd is a submodule of https://github.com/GideonZ/MicroHttpServer, and ad73d32 is that repository's current master. Changes to the parser go through a PR there, as with GideonZ/MicroHttpServer#4 to #6. This repository then bumps the submodule pointer. We do not patch the submodule from a script or in CI. Could you open a PR against MicroHttpServer with the changes in httpd-response.patch? Once it is merged, this PR can bump the submodule and drop httpd-response.patch, httpd_patch.py and the workflow steps that apply it.

Comment thread software/network/http_request.cc Outdated
body = (t_BufferedBody *)response.userContext;
if (body && body->overflow) return fail("http_body_overflow", body->size);
}
if (!body || body->overflow || response.protocol_state == eReq_HeaderTooBig ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth stating in the description: this !body check also fixes a crash. On master, when the server closes before sending a complete header, recv_response() writes body->offset = 0 through a NULL body. On the Ultimate 64 that overwrites the instruction at address 0, and the device drops off the network. JTAG shows the UCI task looping on call 0x0 at address 0. On master, an https:// URL is sent as plain HTTP to port 443, and that crashes the Ultimate 64 the same way. With this branch both cases return 503 and the device keeps running. The U2+L on master did not crash; it returned an empty reply.

Comment thread target/u64ii/riscv/ultimate/Makefile Outdated
PATH_INC = $(addprefix -I, $(VPATH))
OPTIONS = -march=$(MARCH) -mabi=$(MABI) $(EFFORT) -ffunction-sections -fdata-sections -nostartfiles -mno-div
OPTIONS += -gdwarf-2 -Os -DRISCV -DU64=2 -DUSB2513 -DOS -DIOBASE=0x10000000 -DU2P_IO_BASE=0x10100000 -DCLOCK_FREQ=100000000 -Wno-write-strings -DFP_SUPPORT=1
OPTIONS += -DULTIMATE_HTTPS

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only target that gets HTTPS. On the Ultimate 64 and the U2+L, an https:// URL returns 503 at once (measured on both). For those devices, "no physical E2E run yet" in the description therefore means "not implemented".

Both boards have an ESP32 with the same raw bridge (raw_u64, raw_c3). As a quick check I added your TLS worker to both. Only the dispatch hook and my_uart_try_transmit_packet were needed:

  • raw_u64 grew from 825,504 to 955,408 bytes.
  • raw_c3 grew from 862,480 to 998,896 bytes.

Both still fit the 1 MB app partition. I did not measure runtime heap.

On those boards the ESP runs only while WiFi is enabled, because wifi.cc enables it unconditionally only for U64 == 2. That would matter for HTTPS over Ethernet. If these boards stay out of scope, please say in the description and the docs that HTTPS is for the U64 Elite II and the C64 Ultimate only.

{
taskENTER_CRITICAL();
detected_major=major; detected_minor=minor;
controller_ready=major==1 && minor>=16;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This minimum version comes from the u64ctrl numbering, which was at 1.14 before this PR. raw_u64 and raw_c3 have their own sequence, currently at 1.6, so this check cannot carry over to the other boards. An explicit capability would avoid tying the feature to one module's version number, for example a flag in the identify reply.

Comment thread tools/c64u_https/httpd-response.patch Outdated
+ line = end + 2;
+ while (*line != '\r') {
+ end = strstr(line, "\r\n");
+ if (!end || hdr->FieldCount == MAX_HEADER_FIELDS) return 0;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fails the whole response when it has more than MAX_HEADER_FIELDS (20) fields. The legacy parser stops storing fields at 20 and carries on. The client now uses strict mode for plain HTTP too, so this is a regression on every target.

With a local server, master returned the body for responses with 21 and with 30 fields; this branch returned 503. I measured the same on the u64 and on the U2+L. Real APIs often send more than 20 fields. When I requested them, api.github.com sent 22, raw.githubusercontent.com 23, discord.com/api 21, jsonplaceholder.typicode.com 27 and api.coinbase.com 33.

I suggest parsing every line for Content-Length and Transfer-Encoding, and simply no longer storing fields after the twentieth, instead of failing.

rest = RestClient(args.host, password=args.password, timeout=args.timeout)
heap = json.loads(rest.expect('GET', '/v1/machine:heap'))
checked_metrics({'values': heap})
if heap['https_bridge']['controller_minor'] != 18:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires bridge minor 18 exactly, so the suite will fail as soon as the bridge moves to 1.19. A feature check would last longer, as https_diagnostic_test.py does with last_tls_failure.

More generally, every suite fails on a device without the HTTPS provider, such as the Ultimate 64 or the U2+L. The HTTP parts pass and the HTTPS parts get 503. https-response, https-diagnostic and https-timed stop at preflight because machine:heap has no esp32 object. A capability check that skips would make the suites safe to run on every product. This suite also spends about 18 s probing httpbingo.org and httpbin.org before it checks whether the device can run it at all.

Comment thread software/network/https/tls_stream.c Outdated
s->code = s->port.trust(s->port.context, &s->config);
if (s->code) return s->status = HTTPS_TLS_ERROR;
mbedtls_ssl_conf_authmode(&s->config, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_min_tls_version(&s->config, MBEDTLS_SSL_VERSION_TLS1_2);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core settings here are right: verification required, host name set, TLS 1.2 minimum. Two things to consider:

  • The u64ctrl sdkconfig leaves CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 unset, so servers that accept only TLS 1.3 will fail.
  • The sdkconfig compiles in static RSA key exchange, static ECDH key exchange and CBC suites, and MBEDTLS_SSL_PRESET_DEFAULT offers all of them. A mbedtls_ssl_conf_ciphersuites() call limited to ECDHE with AES-GCM would stop a server from choosing a suite without forward secrecy. Every server in my sample chose ECDHE with AES-GCM anyway.

Comment thread software/network/https/https_client.c Outdated
return HTTPS_OK;
}

https_status https_fetch(const https_request *r, https_response *out, const https_transport *t)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https_fetch(), https_transport and https_response are not called by the firmware. Only https_request_valid() is used, by tls_stream.c and UartTlsConnection::open(). Unless a user is planned, removing them and test_https_client.c would take a few hundred lines out of the review.


/* Private monotonic state, outside exported configuration. Never truncate an
* existing slot: keeping its allocation reduces metadata changes at boot. */
static const char *epoch_files[2]={".https-epoch-a",".https-epoch-b"};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The epoch is stored in two files in the root of /flash. The first HTTPS request after every boot writes and syncs one of them, so the files are visible over FTP and the flash takes a write on every boot. The epoch only has to differ from the previous boot's, so that late ESP replies are rejected. A random 64-bit value per boot would do the same without persistent state, if the service compared epochs for inequality rather than order. This is not a blocker, but it is worth weighing against the extra code.

Comment thread software/api/route_machine.cc Outdated
resp->json->add("min_ever_free", (int)xPortGetMinimumEverFreeHeapSize());
resp->json->add("total", (int)configTOTAL_HEAP_SIZE);
#if defined(ULTIMATE_HTTPS)
https_management_add_metrics(resp->json);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This adds the ESP telemetry and the bridge failure record to machine:heap and to both OpenAPI documents, including internal stage numbers and mbedTLS error codes. In addition, publish_metrics() in the ESP worker loop sends a telemetry packet every second, whether or not HTTPS is in use. That is useful during development, but as REST API it is something upstream would have to keep stable. The U2 document now also describes fields that no U2 build produces. I suggest leaving this out of the PR, or putting it behind a debug build option.

@barryw

barryw commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Thanks @araxis, and thanks @chrisgleissner for the ping. Chris's review already covers the build failure, the 20-field limit, HEAD, the version gate, the suites and the scope, and I reproduced the build failure independently (fresh worktree of fc14989, CI-matched Quartus 18.1 / RISC-V GCC 10.2.0 / ESP-IDF 5.3.1). Below are only the things his review doesn't mention.

1. The epoch can lock HTTPS out until a power cycle

Chris raised the /flash epoch as a design cost. It is also a failure mode:

  • tls_service.c:42 accepts a RESERVE only if epoch > s->epoch, and the ESP32 is not reset when the application reboots (wifi.cc: on the U64-II "the module is already running before the FPGA even loads"), so it keeps the highest epoch it has seen.
  • tls_epoch.c starts again from boot 1 when both /flash/.https-epoch-a and -b are missing.
  • So after formatting the Flash disk, or deleting those two files over FTP, every https:// request fails until the unit loses power (or until it has rebooted more times than it had before the files were lost).
  • If only one of the two files is deleted, tls_epoch_advance() returns false on every boot and HTTPS stays at "epoch_storage_failed" permanently.
  • https_management.cc:85-92 sets attempted before calling tls_epoch_advance(), so a single transient /flash error on the first request also disables HTTPS until the next reboot.

This is from reading the code, not measured. Chris's suggestion (a random per-boot epoch compared for inequality) removes all three.

2. Weak entropy when WiFi is disabled

Chris noted that the design uses the ESP's hardware RNG. One caveat: tls_stream.c:113 seeds CTR-DRBG from mbedtls_entropy_func, i.e. that hardware RNG, for every session. Espressif's RNG documentation for the ESP32-S3 says it produces true random numbers only while the RF subsystem is on, or after bootloader_random_enable(). Otherwise "the output of the RNG should be considered as pseudo-random only".

On the U64-II, "Disable WiFi" (network_esp32.cc, wifi.RadioOff()) sends CMD_WIFI_DISABLE, which calls esp_wifi_stop() (wifi_modem.c:766) while the ESP32 keeps running. Nothing in tls_uart.c checks for that state, and because TCP runs on the main CPU, HTTPS keeps working over Ethernet (by code reading; not measured). The ECDHE keys and client randoms of every session would then come from a pseudo-random seed. That is the likely setup for a wired-only user. Either enable the SAR-ADC entropy source (bootloader_random_enable()) only while WiFi is stopped (the IDF header warns it is not safe while anything else uses the RF subsystem or the ADC), or refuse to open a session while WiFi is stopped.

3. Plain HTTP bodies over 16 KB now fail completely

On master, attachment_to_buffer() drops blocks that don't fit, and the program still gets up to 16 KB of the body. On this branch, overflow makes recv_response() fail (http_request.cc:103), so the whole exchange returns 503. That affects every product, including programs that only read the start of a large page. It may be the right behaviour, but it is a change, so the description should say so.

4. The per-second telemetry reaches images that don't expect it

Chris mentioned the once-a-second telemetry. One consequence: only an application built with ULTIMATE_HTTPS intercepts it (wifi_cmd.cc:20). The U64-II updater (target/u64ii/riscv/update), the factory test (target/u64ii/riscv/factorytest) and any older application image will queue these packets as ordinary RX. I haven't measured it, but the updater relies on wifi_detect() replies to decide whether to reflash the module, so it is worth checking that unsolicited packets can't crowd those replies out. Sending metrics only on request would avoid the question.

5. Local failures look like a server 503

Master already reports connect failures as 503. With TLS, the local causes multiply: certificate rejection, DNS failure, timeout, framing error and overflow all return the same "503 SERVICE UNAVAILABLE" a real server would send (http_target.cc:890-908). A C64 program cannot tell "the certificate was rejected" from "the server is down". Only the REST diagnostics can. A distinct local status would help program authors.

6. Smaller points

  • dma_uart.cc: the ISR now re-arms BufReq after every RX callback. The code comment ties this to the TLS/telemetry ISR consumers, but it ships on the Ultimate 64 too, where those consumers are absent. Please say in the description whether it fixes anything there, and what check_rx_rearm.py demonstrates.
  • uci_agent.asm:138/151: inc SEQ now happens before sta GO. The uci-net-target suite (deep profile) loads the same agent through uci_native.py. The window is only a few cycles, but the original order (clear GO, then bump SEQ) can't lose a command.
  • tls_uart.c: the 560-byte frame in tls_uart_receive() sits on the 3 KB dispatcher stack (make it static, as https_management.cc already does), and the static sequence in publish_metrics() shadows the file-level sequence the tunnel uses.

@araxis

araxis commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @chrisgleissner and @barryw,

Thank you both for the detailed review and testing. I really appreciate the time you’ve put into this.

First, a correction: after checking the physical machine, it is a Commodore 64 Ultimate, Breadbin, BASIC Beige. My company provided it for fun, knowing I had a Commodore as a teenager, so I wasn’t involved in ordering it. “v14” is simply my internal test-build label, not an official Commodore firmware version.

Your feedback gives me a clearer path forward. I plan to:

  • Extract the independent HTTP fixes and their regression tests into smaller, focused PRs.
  • Submit the necessary parser changes to MicroHttpServer separately, then update the submodule instead of applying a patch during builds.
  • Reduce the HTTPS PR’s scope and address the remaining findings, particularly entropy with Wi-Fi disabled, session recovery, HTTP compatibility, telemetry, and test portability.
  • Clearly distinguish implemented hardware support from missing validation, and test the revised code from a clean checkout with results tied to the exact firmware revision.

I expect to start working through these changes this weekend. In the meantime, I wanted to acknowledge the findings and explain the approach I intend to take. I’ll keep this PR in draft while working through them.

Thanks again for the thorough and constructive feedback.

@chrisgleissner

Copy link
Copy Markdown
Collaborator

Many thanks @barryw for the very thorough review. Much appreciated.

@chrisgleissner

chrisgleissner commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Hi @araxis , you are very welcome in regards to the review. The ability to use HTTPS has been mentioned frequently as something that would be very beneficial - thus your PR is definitely of high interest.

Also, thanks for clarifying that your comments about the C64U Slimline.

Looking forward to all suggestions by @barryw and myself being on-boarded. If you use AI-enhanced engineering, I can highly recommend Opus 5.5 High, and to perform very extensive E2E red/green testing, then clearly documenting all results. I would also strongly advise to perform your own adversarial reviews and pay special attention to code consistency and low churn, i.e. focusing changes only on what is strictly needed whilst ensuring the resulting change is highly maintainable, defensible, and exceptionally well tested.

I own an Ultimate 64 Elite I as well as a C64U Breadbin like you, as well as an Ultimate II+L - so happy to rerun your E2E tests once done and perform another review.

Given the size of this change and the security impact of HTTPS, it could easily take some review loops to get it all 100% right and merge-ready.

@barryw

barryw commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

I'd also add that we should break big changes like this up into the smallest pieces that add incremental value. I'm notoriously bad at this, but I've been trying to get better. I know that it may be hard with things like HTTPS since a lot needs to change to make it work, but we can build on our changes as we debug and validate them.

@GideonZ

GideonZ commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Let's not integrate this at all, until it is completely stable in a test project that doesn't have anything ultimate related. Just FreeRTOS, lwIP and the TLS additions, combined with an outgoing request and possibly an incoming server. This helps tremendously in isolating issues, do performance measurements and all. You won't need any communication with the ESP32 either, and it can be tested and benchmarked on all platforms.

@barryw

barryw commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

@GideonZ we should create a beta release channel so that we can soak changes like this to a crowd that doesnt mind pain, and when it's bug-free, we can ship it on the release channel - to people who want the pain-free experience. What do you think?

@GideonZ

GideonZ commented Sep 28, 2026

Copy link
Copy Markdown
Owner

@barryw Did you see my remark from 3 hours ago?

@chrisgleissner

chrisgleissner commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

@barryw The idea of a beta channel is good in principle, but how would this work in practice? We want to use a trunk-based development model with master always release-ready and no other long-running branches. Having a separate beta long-running branch would deviate from this again and potentially recreate the merge complexities we are trying to avoid. Please also consider that we are not many firmware devs and I am concerned the beta channel would create additional overhead.

I agree that this PR needs a lot more testing, including extensive soak and stress tests. We already have an automated infrastructure for this which I used to find and fix various issues in the network surface. We could re-purpose some of the existing tooling, or at the very least reuse the concept of soak and stress tests and integrate these tests neatly and consistently with the run-tests facade. This way, the tests are not just a manual one-off, to be discarded once done, but can be run also in future if any changes are needed to HTTPS code.

And once the PR is thoroughly, exhaustively tested (as should be standard for any PR) and it demonstrates this via red/green tests and test evidence, it is ready to be merged to master.

@barryw

barryw commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

@GideonZ Yes, sorry, I should have been clearer. I actually agree with you: a standalone FreeRTOS + lwIP + TLS project is exactly the first layer I had in mind. I've been fighting with my own HTTPS attempt, and even plain encrypted sockets were hard enough to get right that isolating them first makes a lot of sense.

My worry is only about what comes after. Even with good tests, something as wide as HTTPS will have edge cases that only show up on real networks with real servers, and I'd like a way for willing users to try it before everyone gets it.

@chrisgleissner That's fair. A long-running beta branch would bring back exactly the drift we just got rid of, and there aren't many of us to maintain it. What about keeping trunk-based development and gating it instead? HTTPS lands on master behind an "Experimental" setting that is off by default, so master stays releasable and people who want to help test can switch it on. Tests grow as bugs turn up, so nothing regresses.

I don't want to derail @araxis's PR with process talk, so I'm happy to move this to its own issue if it's worth discussing further.

@GideonZ

GideonZ commented Sep 29, 2026

Copy link
Copy Markdown
Owner

I am not sure how difficult this really is. I would personally opt for the mbedtls library and not try to create anything ourselves. @barryw

@UltimateC64Ultimate64fan

UltimateC64Ultimate64fan commented Sep 29, 2026 •

Copy link
Copy Markdown

Since @GideonZ is already taking ownership of cleaning up the network architecture with a standalone FreeRTOS + lwIP + mbedTLS foundation, this is the perfect opportunity to align that work with a broader security-by-default roadmap.

Because Commodore International sells the Ultimate 64 commercially across the EU, the firmware will soon face mandatory EU Cyber Resilience Act (CRA) requirements. Transitioning legacy daemons (Telnet, FTP) to opt-in, replacing plaintext ftpfs with HTTPS WebDAV, and terminating HTTPS on the REST API solves both technical debt and Commodore's commercial compliance in one unified architectural stroke.

@GideonZ

GideonZ commented Sep 29, 2026

Copy link
Copy Markdown
Owner

Since @GideonZ is already taking ownership of cleaning up the network architecture with a standalone FreeRTOS + lwIP + mbedTLS foundation,

I never said that.

@JC-000

JC-000 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@araxis, the current heads of #936 and #997 now cover the same ground from two sides: your target 6 HTTP layer and our TLS sockets on target 3, both with TLS on the ESP32. A trial merge of the two heads conflicts in seven files, mostly on the control module: the dispatcher, the radio start/stop code, the UART pool reset and the module version.

Your HttpConnection boundary looks like the right place to join them. Would you be open to an HTTPS backend that runs over the module's TLS session API from #997? Target 6 would then work on the U64 and over Ethernet as well, and the control module would carry one TLS engine instead of two. That engine runs on ESP-IDF 6 with PSA, and it is fed by the shared CA file, SNTP and the radio-off entropy from #953. We already have it building for the control module (u64ctrl) on a branch, so the C64 Ultimate and Elite II side would not start from zero. Your lease and restart-identity checks would be valuable in that module protocol.

Two smaller items: could we record the reserved thread bytes (yours 0xFD to 0xFF, ours 0xFC) and the TLS RPC range in one shared header? And could we gate TLS on a capability bit in IDENTIFY rather than on version numbers, and leave the numbers to the maintainer at merge?

Two questions: do you need TCP on the ESP32 for a reason we're missing? And would you be happy for us to bring the control-module engine into that shared plan while you keep the HTTP and parser side?

Written with Claude Opus 5.5 in Claude Code.

@araxis

araxis commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@JC-000, it's okay to bring the u64ctrl TLS engine into a shared backend while we keep target 6 and the HTTP/parser side.

On your TCP question: no, we don't need TCP on the ESP32. The current provider keeps socket and TLS ownership together, but main-CPU TCP with ESP32 TLS is a viable alternative behind HttpConnection.

Commit 70926016 in #997 was reviewed, and its host tests were run: 68 RPC/channel checks and 352 network-target checks passed. Before switching, we should preserve CA/hostname/date verification, one request-wide deadline, bounded cancellation and remote cleanup, and boot/session identity checks that reject stale replies. Both targets also need shared session allocation.

Agreed on a shared header for the reserved thread bytes/RPCs, capability-based detection, and maintainer-assigned versions. Could you share the u64ctrl branch/commit? We can then agree the session contract and validate one target-6 HTTPS request through it before replacing the current backend.

@JC-000

JC-000 commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

@araxis, thanks. The engine is in #1095 (c64u-tls-offload, head 1d182c9), stacked on #997.

One correction to how I framed it last time: in #997 and #1095 the Ultimate already owns TCP. DNS, socket and connect run in lwIP on the main CPU, and the module only runs TLS on the ciphertext it is handed over the UART (CMD_TLS_* open/step/close). So the switch needs no TCP work on the module. It needs an Ultimate-side HttpConnection that drives open/step/close; today that loop sits inside the target-3 handler and has to come out of it.

Your list against 1d182c9:

  • CA, hostname, date. Verification is required, SNI is required, and OPEN is refused without a valid clock. For time we accept SNTP, from the module or from the Ultimate, never earlier than the build date. Your policy says SNTP completion alone is not enough: what check do you want at each use, a maximum age since sync, a drift bound, or both? We can add it on the module.
  • One request-wide deadline. Every call takes a timeout and a cancel check, so the adapter can carry one deadline through all of them.
  • Cancellation and remote cleanup. Cancel is polled at least every 100 ms and CLOSE is bounded, but there is no lease: a session outlives an Ultimate that goes silent. We will add an idle/lease timeout on the module and a CLOSE whose completion the Ultimate can wait for.
  • Boot/session identity. Replies are matched on command and sequence, and replies queued before a UART reset are dropped. STEP and CLOSE replies do not echo the slot or tag, though, and the module has no boot ID. We will add a per-boot random nonce to IDENTIFY and OPEN and echo slot and tag on STEP and CLOSE. A durable flash-backed epoch looks like more than stale-reply rejection needs; would a per-boot nonce plus the Ultimate's UART generation meet your bar?
  • Shared session allocation. Missing today. Target 3 owns the slot table and its reset sends CLOSE_ALL, which would take target-6 sessions with it. We will move allocation out of the network target, close per owner, and share the dedicated thread fairly between the two targets.

On the header: thread bytes 0xFC to 0xFF and the CMD_TLS_* range in one file. 0xFF is also master's event/no-reply thread (wifi.cc), so the header should say so.

On the capability bit: controller_identity_parse rejects an IDENTIFY reply with anything after the name string beyond the padding, so a flags field appended there would break it. Would you relax the parser to ignore trailing bytes so we can add a flags word after the string, or would you rather have a separate capability query?

Proposed order:

  1. A minimal adapter on a fork branch with Add authenticated HTTPS to the existing target 6 HTTP interface #936 merged onto TLS client sockets for the Elite II and C64 Ultimate #1095: an HttpConnection over open/step/close, bundle trust, one deadline and your cancellation token. One target-6 HTTPS GET on the C64 Ultimate.
  2. The session-contract items above as new commits on TLS client sockets for the Elite II and C64 Ultimate #1095. I'll put the contract in that branch as a short doc for you to mark up.

Written with Claude Opus 5.5 in Claude Code.

@JC-000

JC-000 commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

@araxis, step 1 works on a C64 Ultimate. Branch: adapter936-target6-module-tls (head 5fb1f18). It is #936 at 45f1119 merged onto #1095, plus the adapter. Your provider code is still in the tree, with its CONFIG_ULTIMATE_PROVIDER_* switches off.

  • ModuleTlsHttpProvider (software/network/module_tls_http.{h,cc}) implements your HttpConnection over the module's open/step/close. It is installed through provider_https_factory() on U64 == 2 builds only.
  • One 30 s deadline starts at open and bounds DNS, connect, every module call and every ciphertext wait. Your cancellation token is polled in all of them. Cleanup ignores the token, has a 1 s budget, and always releases the socket and the session.
  • Trust is the CA bundle and SNI is the URL host. A literal IP host is refused. The module refuses OPEN without a trusted clock. There is no plaintext path.
  • If TCP ends without close_notify on a body that has no Content-Length, the exchange fails rather than completing as 200.
  • Target 6 borrows one of the module's two TLS slots exclusively, with its own tag range. Target 3 skips a borrowed slot. Both targets retry a busy module link until their own deadline, so neither starves the other.

Host tests: 72 adapter checks against a fake module and a fake TCP peer, run under ASan/UBSan, plus 20 slot-sharing checks. Target 3's existing suites keep their counts. Your HTTP target and session suites pass unchanged.

On a C64 Ultimate, with the image loaded into RAM and the module firmware already flashed:

  • GET https://example.com/ through target 6 returned HTTP/1.1 200 OK (chunked), 577 bytes, in 2.3 s.
  • https://wrong.host.badssl.com/ failed in 0.5 s with 503 and no body.

Two things I'd like your view on:

  • Is 503 the status you want for a failed certificate check, or should target 6 report something more specific?
  • The build has to run tools/prepare_http_parser.py until MicroHttpServer#7 lands.

Next are the session-contract items from my last comment, as commits on #1095. Your answers on the clock check, the boot nonce and the capability field decide their shape.

Written with Claude Opus 5.5 in Claude Code.

@araxis

araxis commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

@JC-000, thanks for the adapter and the C64 Ultimate results. The main-CPU TCP / module TLS split works with HttpConnection; there is no requirement to move TCP onto the ESP32.

Adapter commit 5fb1f183 and #1095 at 6bfbbfba were reviewed locally. The adapter's 72 checks pass under ASan/UBSan, and the 20 slot-sharing checks pass for both platform configurations. Three additional probes reproduced gaps to address in the next step: buffered reads return bytes after cancellation or deadline expiry, and an exhausted CLOSE retry returns the slot while the simulated module still holds the session. These are below HttpTarget; its final cancellation check does not make the connection contract correct.

Answers to your questions:

  • Clock: both age and drift. Our current production policy qualifies a sync for two hours and checks UTC against monotonic elapsed time with a five-second tolerance at use. Requalification/revocation invalidates existing session policy generations. A separate sync check rejects jumps over 300 seconds relative to the previous sample and latches closed until boot. These bounds do not make ordinary SNTP authenticated. Please carry equivalent freshness, discontinuity and active-session revocation checks into the shared backend, rather than relying only on SNTP presence and the build date. The recovery downloader's unknown-clock exception must not apply to target-6 HTTPS.
  • Identity: a flash-backed epoch is not mandatory, but the proposed module nonce plus local UART generation is not sufficient by itself. A nonzero, entropy-backed 128-bit module boot nonce is a reasonable part of the contract. We also need a fresh native-owner incarnation when only the main CPU restarts and the module survives. Bind requests and validated replies to that owner, module boot, session/slot/tag and request sequence, with defined wrap handling. A negotiated owner token can replace durable storage if it provides those properties. Old owners must not be able to operate on a newly allocated session.
  • Capabilities: prefer a separate, versioned query with bounded lengths and explicit required features. Keep the existing IDENTIFY parser strict; do not accept arbitrary trailing data. Older modules should continue identifying normally while HTTPS remains unavailable when the required contract is absent. Firmware update versions remain separate and maintainer-coordinated.
  • Certificate failure: keep 503 SERVICE UNAVAILABLE with an empty body for now. That preserves target 6's interface. Keep the precise certificate/clock/entropy failure internally for diagnostics; never retry using HTTP or weaker verification.
  • Parser: agreed for this prototype. MicroHttpServer #7 is still open. Retain the verified preparation step until it lands, then pin the merged parser commit and remove the temporary patch/preparation dependency. EOF completion must remain explicit: an unframed body needs authenticated TLS closure, while a complete Content-Length response does not require waiting for close_notify.

Agreed on one shared thread/RPC registry, including 0xFF's existing event/no-reply meaning. The shared allocator needs owner-specific reset/close and bounded access; retrying a busy link alone does not establish fairness. The adapter still reaches target 3's CLOSE_ALL reset path. For cleanup, a missing acknowledgement must quarantine the slot until release is confirmed or enforced by a module lease. Include CLOSE, close_notify and local socket disposal in the stated cleanup bound, and recheck cancellation/deadlines before returning buffered or late results.

One host integration issue also surfaced: the all-target HTTPS build fails in DmaUART::ClearRxBuffer() because the UART test stubs lack vTaskSuspendAll / xTaskResumeAll. The test needs to model scheduler suspension and callback serialization, not just add empty functions.

Your adapter-first, contract-next order makes sense. Keep this as an integration prototype until the restart, lease, cleanup and policy cases pass; then we can switch the backend without weakening the HTTP behavior. The hardware GETs you reported are useful smoke tests, but do not yet establish those guarantees.

@JC-000

JC-000 commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

@araxis, your three probes, the CLOSE_ALL path, the cleanup bound and the build break are fixed on adapter936-target6-module-tls, 5fb1f183a..4a9b12725. Each fix has a host test that fails with the fix reverted:

  • Buffered or late bytes after cancel or deadline: 737b39edc, 414a4f27d.
  • Exhausted CLOSE: 947fd9e84, 4a9b12725. The slot is withheld until the module confirms; the CLOSE is resent on a C64 reset, when target 3 runs out of slots, and on the next request.
  • CLOSE_ALL: ff22a8073, 4a9b12725. None is sent while a slot is lent; a reset blocks lending until its last CLOSE is out.
  • Cleanup bound covers CLOSE, close_notify and socket disposal: 652d5bc2b.
  • UART stubs model scheduler suspension; the loss notice is in a critical section against the ISR: f00d3bc7f, b6b38b254.

Host suites pass, also under ASan/UBSan: test_module_tls_http 119, nettls 360 and netlend 59 under both product configs, test_uart_loss 19. A withheld slot is still freed only by a module-confirmed CLOSE; the module lease below removes that limit.

The session contract goes on a fork branch stacked on #1095, so #997 and #1095 stay as reviewed:

  • v2 opcodes 0x36–0x3B on their own thread, 0xFB. Target 3's v1 bytes are unchanged. What it does see: a v1 OPEN onto a v2 slot is refused, CLOSE_ALL closes legacy sessions only, a v1 OPEN sets no clock while a v2 session is open, one CLOSE_ALL is sent at init, its worst queue wait is longer, and TLS can hold 5 of the module's 12 receive buffers instead of 3.
  • A separate versioned CAPS query: exact sizes, required-feature bits. IDENTIFY is untouched; an old module leaves HTTPS unavailable.
  • A 128-bit module boot nonce drawn through the entropy gate, plus a HELLO-minted owner token. Token, request sequence and session id are bound in every request and reply; an old owner cannot reach a new session.
  • A 40 s module lease from arrival, quarantine on an unconfirmed CLOSE, and an owner-specific RELEASE.
  • Per-class queue caps for fairness.
  • Clock: age 2 h, a 300 s jump latch until boot, generation revocation of live sessions, drift checked at use on the module. Target 6 never uses the recovery unknown-clock path.
  • 503 with an empty body plus an internal cause; no fallback.

The bounds depend on one TLS step's duration, which we will measure on both devices before stating numbers.

  1. @araxis: is a module-minted, boot-scoped 128-bit owner token echoed in every reply, with the boot nonce only in CAPS/HELLO, acceptable as the module-boot binding?
  2. @araxis: main-CPU UTC is the SNTP sample plus the tick, so there we enforce age (2 h), the 300 s latch and generation revocation. The module checks drift at use (each step and certificate check) against its monotonic timer with 5 s tolerance, and against its own SNTP when under 2 h old. Is that the equivalent you want?
  3. @GideonZ: the module's two sessions are first come; target 6 gets 503 when target 3 holds both, never preempting it. OK, or reserve one for target 6?
  4. @GideonZ: opcodes 0x36–0x3B on thread 0xFB, TLS queue depth 4 with a legacy cap of 2, target 3 stays on v1 with the changes listed above. OK?

Written with Claude Opus 5.5 in Claude Code.

@araxis

araxis commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@JC-000, thanks for the fixes. Revision 4a9b12725 was reviewed locally. All three original failure probes now pass. The adapter's 119 checks, nettls 360 and netlend 59 in both configurations, and UART loss 19 pass under ASan/UBSan. The complete HTTPS host build also passes, along with the HTTP regressions and the original provider's RSA/ECDSA tests (21 cases, 611 checks each). These are host results, not device validation of the module adapter.

Two smaller issues surfaced in the expanded checks:

  • If cancellation or expiry occurs as the final handshake send returns, open() still returns success. Both probes fail on this revision and pass with a final stop check before setting opened_. The next write is rejected and no HTTP request is sent in these probes.
  • The separate low-level RPC suite stops under UBSan in wifi_tls.cc:423: STEP calls memcpy with a null input and zero length. This code predates the fixes above. Guarding both input copies by length makes all 68 RPC checks pass under the same sanitizers in both configurations.

Answers to your two questions:

  1. Yes, the owner token can provide the boot binding without repeating the boot nonce in every frame. It needs to be fresh for each native-owner incarnation, including a main-CPU-only restart, and must not recur across module boots. Bind and validate it with session identity and request sequence in both directions. Please also make CAPS/HELLO reject stale handshake replies, define counter exhaustion, and fail closed when entropy is unavailable. An old HELLO response must not reinstall an old owner. Owner-specific release and the lease still matter.

  2. Yes, that division can provide the clock policy we need, with the original qualification age preserved across the link. OPEN or renewal must not restart a sample's two-hour lifetime. Carry its age or remaining validity conservatively, including queue time, and bind the UTC/monotonic anchor and policy generation to the session. Revoke before clock changes and recheck before releasing results after a blocking step. Keep the 300-second latch and reject monotonic rollback/overflow. Please make the behavior for stale/unavailable module SNTP or disagreement explicit; a second source must not silently clear a rejection. The five-second check remains a consistency check, not authenticated time.

Keeping the v2 contract on a separate branch stacked on #1095 makes sense. Slot reservation and opcode/queue allocation remain Gideon's decisions. Once the contract is implemented, the next checks are stale HELLO/replies, native-only and module-only restarts, lease expiry, clock revocation during an operation and target-3 coexistence. The proposed guarantees still need that evidence before switching backends.

@JC-000

JC-000 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

@araxis, both are fixed on adapter936-target6-module-tls, 4a9b12725..a8be15b2d:

  • open() checks for a stop once more before it reports success (1c8cb5a11). Your two probes, cancel and deadline as the final handshake send returns, are in 950921771. They fail without the check and pass with it.
  • Both STEP input copies are guarded by length (a8be15b2d, the same change as on TLS client sockets for the U64, through its ESP32 #997). The output copies always get a buffer from their callers.

Host suites under ASan/UBSan: test_module_tls_http 125, the RPC suite 68, nettls 360 and netlend 59 in both product configs, test_uart_loss 19.

The v2 contract takes your conditions as follows.

Owner:

  • The module draws a new 128-bit token through the entropy gate on every HELLO and never stores or reuses it. The main CPU sends HELLO on every start, so a main-only restart gets a fresh token.
  • CAPS and HELLO each carry a nonce the reply must echo. The HELLO reply must also match the module boot id from the accepted CAPS. The main CPU drops its old token when it sends HELLO and accepts exactly one reply, so an old HELLO reply cannot reinstall an owner.
  • Request sequence and session id have defined end values; at exhaustion the main CPU closes, releases and starts a new HELLO.
  • Without entropy, no nonce or token is made and HTTPS stays unavailable.

Clock:

  • OPEN carries the sample's remaining validity, computed at send time. The module counts it from the request's arrival, so queue time is spent, and nothing renews it.
  • Each session is bound to the clock it actually uses and to the policy generation on both sides.
  • Every module clock write goes through one setter that revokes live sessions first. Both sides recheck after every blocking step before releasing a result.
  • Monotonic rollback and overflow latch until boot, and the 300 s latch stays.
  • Module SNTP:
    • missing or older than 2 h: the main sample is used alone;
    • fresh: it must agree with the main sample, with queue time compensated;
    • a disagreement refuses the OPEN and latches on the main CPU against that sample's generation, so only a newer main sample clears it, never a module resync or reboot;
    • a module SNTP jump of more than 300 s disables the module's own source until boot.
  • The consistency check is stated as a consistency check, not authenticated time. An accepted SNTP update on either side ends any HTTPS request in progress.

Evidence: each item on your list has a host test that fails without the corresponding rule. On hardware, main-only restarts (counted only when the module boot id is unchanged), lease expiry, clock revocation during a slow GET and target-3 coexistence are planned. A module-only restart needs a bench tool that restarts the ESP32 alone, which we are adding.

One thing we found in the expanded checks: with CONFIG_ULTIMATE_PROVIDER_SOURCES=y, the strong sntp_sync_time in u64ctrl sntp.c calls the app's time_sync_notification_cb, not the callback esp_netif_sntp registered, so sync_sem is never given and obtain_time waits the full 30 s on every GOT_IP before the module reports its address. The v2 setter polls the sync status instead.

Two questions:

  1. Our consistency window is one-sided, -5 s to +7.5 s: the main CPU's sample can only run late, by whole-second truncation of the sample and of the sent time, and by the send-to-arrival bound. Queue time is compensated exactly. Is that within your five-second check?
  2. Following your SntpClock, a gap of more than 24 h between module SNTP samples fails the module's source until boot, so a day-long SNTP outage disables HTTPS until the module restarts. Keep that, or should a gap re-seed the module's source and leave the main CPU's age and latch as the only gate?

Written with Claude Opus 5.5 in Claude Code.

@araxis

araxis commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks,@JC-000. At a8be15b2d, both final-handshake probes now pass. Cancellation and deadline each make open and the next write fail, with zero HTTP request bytes sent. The adapter passed 125 checks, and the STEP sanitizer finding is gone in both product configurations.

  1. Clock window. I would keep five seconds as the final consistency limit. Assuming the main timestamp can lag by 0–2.5 s, your −5 to +7.5 s window is correct as a first filter. An observed +6 s could still be a real +6 s if the bias happened to be zero. With module minus main as the sign convention, the possible offset is [observed − 2.5, observed], so only observations from −2.5 to +5 s guarantee agreement within five seconds under that bound. Can we carry more precision or bound transit per exchange? The same transit time also counts against the validity remaining when OPEN was sent.
  2. 24-hour gap. I'd allow the optional module source to re-seed after a gap alone. Our current code accepts exactly 24 h and latches on the first returning sample beyond it. For v2, a still-qualified main sample can cover the outage. On return, require agreement with a fresh main sample and revoke live sessions before writing the clock. Keep the >300 s jump, monotonic rollback/overflow and main-generation disagreement latches. A module resync must never clear them.

I also reproduced the IP-report delay in a host fixture using the GOT_IP handler and IDF 6.0.3 callbacks. Even an immediately accepted sample left the semaphore unsignalled, giving 15 two-second waits per report on two consecutive events.
I'd send the acquired IP immediately and gate HTTPS separately on qualified time. Polling sync status alone also leaves the SDK time-sync event undelivered.

@JC-000

JC-000 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Thanks, @araxis. We take both answers.

Clock: with module minus main, the main's time can be late by up to L and early by up to E. An OPEN is accepted only for d in [-5 s + L, +5 s - E]. Between that and the [-5 s - E, +5 s + L] filter it fails without a latch, and only d outside the filter latches.

Precision: yes. The main switches to SNTP_SET_SYSTEM_TIME_US and OPEN2 carries milliseconds, so the 2 s of truncation goes. L is now the 500 ms transit limit for an OPEN plus 10 ms, plus the main oscillator's drift since its last NTP sample (at most about 0.7 s at 100 ppm and 2 h). E is 10 ms plus the same drift. The module's own sample adds its drift the same way.

Transit: bounded per exchange. The module reports how long it held the OPEN, and the main takes RTT minus that. A session is used only when its transit is within the 500 ms limit; otherwise it is discarded and retried once. The expiry therefore stays within the validity left at OPEN. Any clock write the OPEN decides waits for that session's first STEP, which the main sends only after this check.

Gap: a sample after more than 24 h is held and live sessions are revoked. It is written only after it agrees with a qualified main time from an OPEN that arrives after it returned. The 300 s, monotonic and main-generation latches stay, and a resync clears none of them. With provider sources on, SntpClock needs the same change.

IP report: agreed. GOT_IP is reported first and then only starts SNTP, and HTTPS gates on time separately. Our SNTP hook posts NETIF_SNTP_TIME_SYNC itself, without blocking.

Did "fresh main sample" mean an OPEN that arrives after the module's sample returns, or a new main NTP sample?

Q3 and Q4 are still with Gideon.

Written with Claude Opus 5.5 in Claude Code.

@JC-000

JC-000 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Should target 6 accept pinned, self-signed hosts at all? Today it cannot name one: every request uses the bundle, and your usage doc says applications do not send certificates. If yes, should the pin come from a setting per host, which leaves the request format alone, or with each request?

If pinning goes in, we propose that a pinned OPEN carries no time. The module's PIN mode checks only the SHA-256 of the leaf's SubjectPublicKeyInfo and already ignores the certificate's dates, chain and name, so the clock changes no verify result. The contract would still refuse a pinned OPEN whenever time is not qualified or the clocks disagree, for example during an NTP outage.

A pinned OPEN would neither need a qualified clock nor set, latch or revoke anything on it. Entropy, cancel and the deadline still apply, and other sessions keep every clock rule.

Written with Claude Opus 5.5 in Claude Code.

@araxis

araxis commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@JC-000, a new OPEN after the module’s SNTP sample returns is enough if the main CPU’s sample is less than two hours old, its generation is still valid, and the two clocks agree. If the main sample has expired or a previous disagreement latched its generation, the main CPU needs a new, qualified NTP sample before the module can re-seed.

For #936, let’s keep target 6 on the existing certificate bundle and leave public-key pinning for a separate proposal.

@JC-000

JC-000 commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

@araxis Thanks, that answers both questions.

The re-seed rule works for us: a new OPEN after the module's SNTP sample, as long as the main CPU's sample is under two hours old, still valid and in agreement; otherwise a fresh qualified NTP sample comes first.

Agreed on pinning: target 6 stays on the certificate bundle for #936, and pinning can be a separate proposal if a use for it comes up.

Written with Claude Opus 5.5 in Claude Code.

@JC-000

JC-000 commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

After the first Wi-Fi disconnect, HTTPS stays unavailable until reboot. EVENT_DISCONNECTED (wifi.cc:739) calls InvalidateProvider(), which cancels the provider lifetime and the manager link. ManagerRunner::step then fails on generation_.cancelled() (provider_manager_runner.cc:30), ProviderManagerTask::run() publishes Failed and returns (provider_manager_task.cc:90, :94), and the entry deletes the task. Nothing starts another one: start() is gated by attempted_ (:15) and provider_journal_start_owner by owner_attempted (provider_native_startup.cc:87). The only caller, eWifi_AppDetected (wifi.cc:519), runs once per module start, not on a reconnect.

The reconnect case I added to test_provider_startup reproduces it. It drives the native owner to Active, drops the link, restores it, and requires the secure provider (HttpSecureProvider, http_connection.h:25) to report available() again with a fresh lifetime(). At 45f1119 it fails with FAIL owner serves again after a Wi-Fi disconnect and reconnect.

The fix keeps the owner task and renegotiates, because the task cannot be rebuilt: WiFi keeps the UART binding to the existing ProviderManagerUart, and construction consumed the boot's journal identity. When the runner fails after the provider lifetime was cancelled, run() fails pending data requests, stops the runner, returns to WaitingForBoot and negotiates again from the next ProviderSnapshot. That also covers a DmaUART loss, whose loss callback reaches ProviderLinkLoss (wifi.cc:243). The 1500 ms bootstrap timeout still bounds only the first identity wait. Three cases needed more than that, and each has its own startup case that failed first:

  • A connection open at the drop: its close_session submitted a Close that the waiting owner refuses, and the failed Close retired the owner. The Close is now skipped once the data lifetime is cancelled.
  • A data reply to a pre-drop request arriving while the owner waits: the data channel was open again, so it was accepted and would have answered the first new Open. The channel is drained when the new session first becomes Active.
  • A second drop between ProviderSnapshot and runner_.start: the failed offer was final. It now waits for the next snapshot.

Still terminal: a ManagerDelivery queue overflow (provider_manager_delivery.cc:21), a reply or lease timeout, a send failure, a disabled runner and request_stop().

Known limits, not covered. The ESP answers Initialize with Busy while the previous resource drains (provider_control.cc:130, provider_session_owner.cc:76), and the runner treats that as final, so a reconnect that negotiates before cleanup finishes still fails. The contract says initialization waits for confirmed cleanup (https-session-contract.md:33); the owner does not yet wait. An ESP restart is not covered either: the 250 ms reply timeout (provider_native_startup.cc:93) can fire before the identity probe notices the restart, which is a reply timeout and so terminal.

Branch fix/936-owner-restart on top of 45f1119, five commits (test, fix, test, fix, docs):

git fetch https://github.com/JC-000/1541ultimate fix/936-owner-restart
git cherry-pick 76e842633 4e6a14850 e15a436ed 2cfe1f4ab 220e052ea

tools/test_https_host.py passes in full with ASan and UBSan, including the new startup-reconnect, startup-held, startup-flap and startup-stale steps. test_provider_task.cc had two cases that asserted the old exit on a lifetime cancel; they now assert WaitingForBoot and then stop the owner. Not run on hardware.

Written with Claude Sonnet 5.5 in Claude Code.

@araxis

araxis commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @JC-000. Your Wi-Fi reconnect test failed on 45f1119a8 and passed on 220e052ea. All 86 steps of the host suite passed on your branch.

I also reproduced both limits you flagged. If reconnect happens while the ESP32 is still cleaning up, Initialize returns Busy and the owner exits. HTTPS stays unavailable even after cleanup finishes. If the ESP32 restarts during a renewal and its new boot ID arrives after the 250 ms reply timeout, the owner has already exited and HTTPS stays unavailable.

Are you already working on those two cases, or would you like me to take them on #936?

@JC-000

JC-000 commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

@araxis Thanks for verifying it. Please take both cases on #936: they turn on how the contract treats Busy during cleanup and when a restart is detected against the reply timeout, and those are your design calls. I'm going to be traveling and not sure I'll get much work done. We're glad to review the change and run it on hardware once it's in.

Written with Claude Opus 5.5 in Claude Code.

JC-000 and others added 6 commits November 22, 2026 10:02
The startup test drives the native owner to Active, drops and restores the
Wi-Fi link, and requires the factory to become available again with a fresh
lifetime. It fails today: the owner task exits after the first link loss and
the one-shot start paths never create another.
A Wi-Fi disconnect cancels the provider lifetime. The owner treated the
resulting runner failure as final, published Failed and let its task exit.
Both start paths are one-shot, so HTTPS stayed unavailable until reboot.

When the failure follows a cancelled provider lifetime, the task now retires
the old negotiation, fails pending requests and waits for the next provider
snapshot, then negotiates again. Every other failure is still final, and the
bootstrap timeout still bounds only the first identity wait.
…open

Add startup cases for a connection that is open at the drop, a data reply
for a pre-drop request that arrives while the owner is disconnected, and a
second drop between the provider snapshot and the offer. Each must end with
the owner serving again, and none does yet. The reconnect case no longer
calls provider_journal_start_owner again: only module start calls it.
Three ways a link loss still ended the owner for good:

- A connection open at the drop submitted a Close that the waiting owner
  refused, and the failed Close retired the owner. Skip the Close once the
  data lifetime is cancelled, and do not retire on a Close that fails
  because the link was lost under it.
- A data reply to a request from before the drop could arrive while the
  owner waited, because the data channel was open again. Drain the channel
  when the renegotiated session first becomes Active, before admitting
  requests; the UART is ordered, so every stale frame precedes the Offer
  reply.
- A second drop between the provider snapshot and the offer made the failed
  offer final. Wait for the next snapshot when the lifetime just taken is
  already cancelled.

The contract row now lists what stays terminal.
@araxis

araxis commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@JC-000 Thanks for the reconnect fix. Both cases you flagged are addressed in a3f6ee38.

When initialization returns Busy during cleanup, the owner waits 50 ms before trying again on the same offer. The 1.5 s offer deadline still applies. In the host trace, the ESP32 returned Busy twice, then accepted initialization after the old resource was released.

When the ESP32 restarted during renewal, the owner retired the old session at the 250 ms reply deadline. The new boot identity arrived 110 ms later, and the same owner task negotiated a fresh session. Reconnecting with the same boot identity after that timeout kept HTTPS unavailable.

Both probes failed before the fix and passed afterward. All 86 host-suite steps passed. When you have hardware time, a reconnect during cleanup and a reboot during renewal would be the most useful cases to check. Traces and host results

@chrisgleissner

Copy link
Copy Markdown
Collaborator

Hi @araxis and @JC-000 , many thanks for all your work on supporting TLS. It is much appreciated indeed.

One question - would you mind writing up very concisely where we are on the journey towards TLS, and whether this covers outgoing calls, incoming calls, or both?

There are a lot of PRs and some issues related to this, and it is a bit hard to keep track.

Thank you.

@JC-000

JC-000 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@chrisgleissner, our side in short.

Outgoing only. Our PRs make the Ultimate a TLS client for C64 programs: through the network command target, a program opens a TLS socket (OPEN_TLS, $21), then uses the existing READ_SOCKET, WRITE_SOCKET and CLOSE_SOCKET on it. The server is always authenticated (Mozilla roots, an uploaded CA, or a pinned key). The only firmware service touched is the control module's existing HTTPS network recovery. None of our PRs adds incoming TLS: web UI, REST API and FTP stay plain.

Where. The ESP32 module runs TLS; TCP stays in lwIP on the main CPU, and the C64 sees plaintext. U64 and U64 Elite in #997, Elite II and C64 Ultimate in #1095.

PR Purpose State Needs
#1028 Control module on ESP-IDF 6.1.1 open
#996 U64 WiFi module on ESP-IDF 6.1.1 draft #1028
#1029 U2+L module on ESP-IDF 6.1.1, build only draft #996
#953 GET_RANDOM: hardware random bytes open #1029
#997 TLS sockets, U64 / U64 Elite draft #953, go-ahead on #995
#1095 Same, Elite II / C64 Ultimate open #997

All six have master merged in as of 23 November, which is what your reviews of 10 November asked for, and have no conflicts. Merged already: #1027, #1041, #1034, #1097 (the root list the engine shares). Plan: #952.

#936 is also outgoing, despite the title: "target 6" is the HTTP command target, where a C64 program has the Ultimate fetch a URL, and the PR lets that URL be https://. It has its own provider on the same module; whether one engine serves both is open there. No open PR adds HTTPS to the REST API or the web UI.

Next. Merge in table order, starting with #1028. From the maintainers: a review of #1028, a yes or no on #995, one engine or two, and module versions at merge.

Written with Claude Opus 5.5 and Claude Fable 5.2 in Claude Code.

@JC-000

JC-000 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@araxis Thanks for a3f6ee3.

We ran your full host suite in a Linux container at a3f6ee3 and again at the current head e32d5c6: all 86 steps passed both times, exit 0. busy_initialization and restart_after_timeout cover the two cases. That is host evidence only.

The hardware run needs a C64 Ultimate with your module firmware flashed on the ESP32-S3, which I cannot do remotely. We will run both cases when I am back at the bench in a week or so: a reconnect while cleanup still returns Busy, and an ESP32 reboot during renewal.

One question on the reply timeout. A Renew reply later than 250 ms (provider_native_startup.cc:92) moves the owner to WaitingForRestart (provider_manager.cc:32, provider_manager_task.cc:59). It leaves that state only when the ESP32 presents a different boot identity (provider_manager_task.cc:87). The contract allows this (https-session-contract.md:47). But if the ESP32 is alive and only slow, HTTPS stays unavailable until the module reboots, with no deadline and nothing logged. The module answers a Renew during a session only from Worker::service, through the TLS backend's cancellation poll (provider_tls_backend.cc:27). Can a long handshake step delay that reply past 250 ms? If it can, should WaitingForRestart have its own deadline, or a path back to a fresh offer when the same boot keeps answering?

Written with Claude Opus 5.5 in Claude Code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.16 Targeted for release 3.16. enhancement New functionality or an improvement to existing behavior, including formats and developer tooling. network Networking and remote services: REST, Socket DMA, FTP, Telnet, and online access. uci C64-side Ultimate Command Interface, command targets, and Ultimate DOS commands; REST is network.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants