Skip to content

Clean up after Ctrl-C, keep --deploy JSON clean, and match the branded update-tool error - #34

Merged
joshk merged 5 commits into
mainfrom
fix/firmware-archive-bugs
Nov 24, 2026
Merged

joshk merged 5 commits into
mainfrom
fix/firmware-archive-bugs

Conversation

@joshk

@joshk joshk commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes three bugs in the firmware and product commands and adds process-wide signal handling. The fourth reported bug, nh archive upload requiring meta-product, turned out not to be a bug. Server references are to nerves_hub_web upstream/main at a7c5c5e44.

1. Ctrl-C while signing left the decrypted key in $TMPDIR

signFirmware writes the plaintext Ed25519 key to nh-key-*.priv for fwup -s and removes it with a defer. Execute didn't handle signals, so SIGINT ended nh at once and the defer never ran. That left both the key and the nh-signed-* copy behind, for firmware upload and archive upload alike.

The fix. Execute now runs the command under a new internal/interrupt package:

  • First SIGINT or SIGTERM: it cancels the command's context. fwup and espsecure were already started with exec.CommandContext(cmd.Context()), so they are killed and the defers run. mix eval used context.Background(), so mix.SetContext now gives it nh's context.
  • Work that never sees the context: a prompt blocked in term.ReadPassword or ReadString is one example. nh gives up on it after 1s, or at once on a second Ctrl-C. Before exiting it removes the files registered with interrupt.RemoveOnExit (the key file and the signed copies), and restores the terminal state saved at startup, because term.ReadPassword leaves echo off when interrupted. Before this change, Ctrl-C at the signing-key password prompt also left the terminal without echo.
  • Exit status: 130 for SIGINT and 143 for SIGTERM when the interrupted command fails. A command that turns Ctrl-C into a clean finish still exits 0.
  • Waiting on pipes: fwup and espsecure signing set WaitDelay, so a child process holding the output pipe after the kill doesn't hold up the key file's removal.

Known leftover: Ctrl-C during a mix eval lookup makes mix.Org() return "", so the command reports a missing org before exiting 130. Fixing the message means changing requireOrg/requireProduct, which have about 90 callers across files other PRs own.

I used signal.Notify with WithCancelCause rather than plain signal.NotifyContext, so nh knows which signal arrived (for the exit code) and can tell a second signal from the first.

What else this changes. Please check these:

  • device logs --follow and device metrics --follow keep their own signal.NotifyContext(cmd.Context(), os.Interrupt). Both handlers get Ctrl-C, the loop returns nil, and nh exits 0 as before. Their own handler is now redundant but harmless, and I left those files alone because another PR owns them.
  • device console and device iroh console, by reading the code only, not run against a device. In raw mode, term.MakeRaw clears ISIG, so Ctrl-C arrives as byte 0x03 and consoleWriteLoop disconnects as before. No signal is raised. Two things differ:
    • Ctrl-C before raw mode (while dialling or joining) used to kill nh at once. Now it cancels the dial or join, and nh prints Error: … context canceled and exits 130.
    • SIGTERM during a session used to kill nh with the terminal still in raw mode. Now it cancels the context, the read loop ends, and the terminal is restored.
  • Prompts, including nh login code entry and confirmations, read stdin without a context. Ctrl-C at a prompt now takes up to 1s to exit, or is instant on a second Ctrl-C. Making cmd/prompt.go context-aware would make the first press instant too. That file is outside this PR.

Tests:

  • TestFirmwareUploadInterruptedRemovesKey runs the test binary as nh firmware upload with a fwup stub that hangs on --sign. It checks that the key is in $TMPDIR, sends a real SIGINT, and asserts exit 130 and no nh-* files left. Against the old Execute it fails: the exit is signal: interrupt, and both nh-key-*.priv and nh-signed-*.fw are left behind.
  • TestSignFirmwareCancelledRemovesTempFiles checks that a cancelled context kills fwup and removes both temporary files.
  • internal/interrupt has tests for context cancellation, giving up on stuck work after the grace period, the second signal, the file registry and exit codes.
  • internal/mix has a test that a cancelled base context stops mix eval without reporting a timeout.

2. firmware upload/publish --deploy <group> -o json wrote text into the JSON

deployFirmware printed Updated deployment group … to stdout before the JSON. A failed deployment returned before any JSON was written, so a script lost the UUID of firmware that had uploaded.

The fix. In JSON mode the progress lines go to stderr. On a deployment error, nh still writes the upload's JSON, with deployed listing the groups that were updated, and then returns the error, which exits 1. This is client-side only; the server behaviour doesn't change.

Tests: TestFirmwareUploadDeployJSONKeepsStdoutClean and TestFirmwareUploadDeployFailureStillPrintsJSON. Both fail against the old code.

3. nh product update --allow-tool: the disabled-tool hint never appeared

explainUpdateToolError looked for not enabled on this NervesHub instance:. The server now says "not enabled on #{NervesHub.Branding.friendly_platform_name()}: …":

  • lib/nerves_hub/products/product.ex:144-148 produces that message.
  • lib/nerves_hub/branding.ex:12-17 returns the configured name, or NervesHub when none is set. NervesCloud is one such configured name.

The fix. nh now matches the not enabled on prefix and takes the tool list after the last ": ". The brief said the first. The configured name is free text and could contain ": ", but the tool names, joined with ", ", never do. The hint also names the instance now: "an administrator must enable the format on NervesCloud first".

Tests: the fixtures in internal/api/product_update_test.go and cmd/product_update_test.go now use the server's real strings, for both NervesHub and NervesCloud. A new table test, TestNotEnabledTools, includes a name that contains ": ".

Not changed: nh archive upload requiring meta-product

The review read Archive.create_changeset (lib/nerves_hub/archives/archive.ex:52-73), which neither casts nor requires product, and concluded that nh was stricter than the server. It isn't. The API path never reaches that changeset without product:

  1. lib/nerves_hub_web/controllers/api/archive_controller.ex:58 calls Archives.create/2.
  2. lib/nerves_hub/archives.ex:336 reads the file with Fwup.metadata/1 before building the changeset.
  3. lib/nerves_hub/fwup.ex:48-53 builds struct!(Metadata, …) and rescues to {:error, :invalid_metadata}.
  4. lib/nerves_hub/firmwares/update_tool.ex:39 lists :product in that struct's @enforce_keys.
  5. lib/nerves_hub_web/controllers/api/fallback_controller.ex:97-102 answers 422: "The file's metadata must include meta-product, …".

So dropping product from nh's check would only move the refusal to the server, after signing and uploading. I kept the check and its help text, and rewrote the comment on archiveRequiredMeta to cite this path.

Checks

  • go test ./... passes.
  • go vet ./... is clean, and so is GOOS=windows go vet ./....
  • gofmt -l . lists nothing.
  • go test -race passes for internal/interrupt, internal/mix and the new cmd tests.

🤖 Generated with Claude Code

joshk and others added 5 commits November 24, 2026 13:17
nh had no process-wide signal handling, so SIGINT or SIGTERM ended it at
once and no deferred cleanup ran. Interrupting `nh firmware upload` or
`nh archive upload` while fwup was signing left the decrypted Ed25519
key (nh-key-*.priv) and the signed copy (nh-signed-*) in $TMPDIR.

Execute now runs the command under internal/interrupt: the first signal
cancels the command's context, which kills fwup, espsecure and mix eval
and lets the defers run. Work that never sees the context, such as a
prompt blocked on the terminal, is given up on after a second, or at
once on a second Ctrl-C: the registered temporary files are removed,
the terminal state is restored (term.ReadPassword leaves echo off), and
nh exits with 130 or 143. A command that turns Ctrl-C into a clean
finish, as `device logs --follow` does, still exits 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deployFirmware printed "Updated deployment group ..." to stdout ahead
of the JSON, and a failed deployment returned before any JSON was
written, so a script lost the UUID of firmware that had uploaded.

In JSON mode the progress lines now go to stderr, and the JSON for the
upload, with the groups that were updated, is written before the
deployment error is returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The hint for an update tool the instance has turned off looked for
"not enabled on this NervesHub instance:", but the server now says
"not enabled on <friendly platform name>: <tools>", such as
"not enabled on NervesCloud: rauc", so the hint never appeared.

Match the "not enabled on " prefix and take the tools after the last
": ", since a configured instance name may itself contain one, and name
the instance in the hint. The test fixtures now use the server's real
strings, for both the default and a branded name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Archive.create_changeset does not require product, which reads as if
nh's archive check were stricter than the server. It is not:
Archives.create reads the file with NervesHub.Fwup.metadata/1 first,
whose UpdateTool.Metadata struct enforces product, and a missing key is
a 422. Say so where the required keys are listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Don't abandon work that returned just as the grace period ran out:
  select picks among ready cases at random, so check done once more.
- End the line after an abandoned prompt, since exiting with 130 rather
  than dying of SIGINT gets no newline from the shell.
- Set WaitDelay on fwup and espsecure signing, so a child holding the
  output pipe after the kill doesn't delay removing the key file.
- Word the disabled-tool hint "an administrator must enable the format
  on <instance> first", which reads right for NervesHub, NervesCloud and
  older servers' "this NervesHub instance".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@joshk
joshk merged commit ec9c2ae into main Nov 24, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant