v0.0.26 - Add mnemonic-stdin and mnemonic-fd startup input modes with tests/docs
This commit is contained in:
253
plans/embedded_nsigner_spawn.md
Normal file
253
plans/embedded_nsigner_spawn.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# Plan (future): Host programs that embed and spawn `n_signer`
|
||||
|
||||
Status: design only. Do not implement until [`plans/mnemonic_startup_input.md`](mnemonic_startup_input.md) has landed and been used in at least one host program.
|
||||
|
||||
This plan describes how a host program (for example `~/lt/nostr_terminal`, future Bitcoin or SSH frontends) can embed the `nsigner` binary into itself and launch it in a new visible terminal window with the mnemonic pre-loaded and pre-approvals declared, without any new on-disk artifact for `nsigner`.
|
||||
|
||||
## 1. Why embed at all
|
||||
|
||||
Goals motivating this plan:
|
||||
|
||||
1. **Single-binary deployment.** A user installs `nostr_terminal` and gets `nsigner` for free; no separate package manager step, no `$PATH` confusion, no version skew.
|
||||
2. **Version pinning.** The host always launches the exact `nsigner` it was tested against.
|
||||
3. **Zero filesystem footprint preserved.** Spawning `nsigner` does not put a copy of the binary anywhere persistent; it runs out of an anonymous in-kernel memory object.
|
||||
4. **Same security boundary.** `nsigner` continues to run as a separate process with its own address space, mlock'd pages, and approval prompt loop. The host does not become the signer; it merely launches it.
|
||||
5. **Reusable across host programs.** Any program in the user's `~/lt/*` ecosystem can adopt the same helper.
|
||||
|
||||
Non-goals (explicit):
|
||||
|
||||
- Running `nsigner` *inside* the host process. That collapses the security boundary and is rejected. See [`documents/SECURITY.md`](../documents/SECURITY.md) "One process. One terminal. One human."
|
||||
- Hiding the `nsigner` window. The TUI is the trust anchor; it must be visible and attended.
|
||||
- Making `nsigner` a daemon. Same reason.
|
||||
|
||||
## 2. Architecture overview
|
||||
|
||||
```text
|
||||
+----------------------------------------------------------------+
|
||||
| host program (e.g. nostr_terminal) |
|
||||
| |
|
||||
| +-- embedded blob ---------------------------------+ |
|
||||
| | _binary_nsigner_start ... _binary_nsigner_end | |
|
||||
| | (the full statically-linked nsigner ELF) | |
|
||||
| +--------------------------------------------------+ |
|
||||
| |
|
||||
| user types mnemonic into host's TUI |
|
||||
| | |
|
||||
| v |
|
||||
| nsigner_spawn_embedded(...) |
|
||||
| | |
|
||||
| | 1. memfd_create(MFD_CLOEXEC) |
|
||||
| | 2. write(memfd, blob, blob_len) |
|
||||
| | 3. pipe2(stdin_pipe, O_CLOEXEC) |
|
||||
| | 4. fork() terminal emulator wrapper |
|
||||
| | child: dup2 stdin_pipe[0] -> 0 |
|
||||
| | execvp("kitty","-e","/proc/self/fd/<memfd>"|
|
||||
| | --listen unix --name <chosen> |
|
||||
| | --mnemonic-stdin |
|
||||
| | --preapprove ...) |
|
||||
| | 5. parent: write(stdin_pipe[1], mnemonic); close + wipe |
|
||||
| | 6. return chosen socket name to caller |
|
||||
+----------------------------------------------------------------+
|
||||
|
|
||||
v (new graphical terminal window)
|
||||
+----------------------------------------------------------------+
|
||||
| nsigner (separate process) |
|
||||
| - reads mnemonic from FD 0, closes FD 0 |
|
||||
| - binds @nsigner_<chosen> abstract unix socket |
|
||||
| - shows status TUI |
|
||||
| - applies pre-approvals from --preapprove |
|
||||
+----------------------------------------------------------------+
|
||||
^
|
||||
| (host can now connect)
|
||||
+----------------------------------------------------------------+
|
||||
| host re-uses client/nsigner_client.{c,h} to issue requests |
|
||||
+----------------------------------------------------------------+
|
||||
```
|
||||
|
||||
## 3. Build-time integration
|
||||
|
||||
### 3.1 Producing the blob
|
||||
|
||||
Add a Makefile rule (in `n_signer`'s Makefile) that exposes the binary as a relocatable object usable by other projects:
|
||||
|
||||
```make
|
||||
nsigner_blob.o: nsigner
|
||||
$(LD) -r -b binary -o $@ $<
|
||||
# results in symbols:
|
||||
# _binary_nsigner_start
|
||||
# _binary_nsigner_end
|
||||
# _binary_nsigner_size
|
||||
```
|
||||
|
||||
Alternatives considered:
|
||||
|
||||
- `xxd -i nsigner > nsigner_blob.h` — produces a C header with a `unsigned char` array. Works, but adds compile time linear in blob size and blocks ccache usefulness.
|
||||
- `objcopy -I binary -O elf64-x86-64 -B i386 nsigner nsigner_blob.o` — same effect as `ld -r -b binary` on most toolchains. Either is fine.
|
||||
|
||||
### 3.2 Embedding into the host
|
||||
|
||||
The host program adds these lines to its build:
|
||||
|
||||
```make
|
||||
HOST_OBJS += nsigner_blob.o nsigner_spawn.o
|
||||
```
|
||||
|
||||
and links them into its final executable. The blob lives in `.data` (read-only on most toolchains) and adds roughly the size of the `nsigner` binary to the host (currently ~1–3 MB for the musl static build).
|
||||
|
||||
### 3.3 Symbol declaration
|
||||
|
||||
```c
|
||||
extern const unsigned char _binary_nsigner_start[];
|
||||
extern const unsigned char _binary_nsigner_end[];
|
||||
/* size = _binary_nsigner_end - _binary_nsigner_start */
|
||||
```
|
||||
|
||||
## 4. Runtime spawn helper API
|
||||
|
||||
New file pair: `client/nsigner_spawn.h` and `client/nsigner_spawn.c`.
|
||||
|
||||
### 4.1 Public API sketch
|
||||
|
||||
```c
|
||||
typedef struct {
|
||||
/* required */
|
||||
const char *mnemonic; /* will be written to child stdin pipe and then wiped */
|
||||
size_t mnemonic_len;
|
||||
|
||||
/* optional */
|
||||
const char *const *preapprove_specs; /* array of "caller=...,nostr_index=N" strings */
|
||||
size_t preapprove_count;
|
||||
|
||||
const char *socket_name; /* if NULL, helper picks a random BIP-39 pair */
|
||||
const char *terminal_hint; /* "kitty"|"foot"|"alacritty"|"xterm"|... or NULL = autodetect */
|
||||
|
||||
/* outputs */
|
||||
char *out_socket_name; /* caller-supplied buffer */
|
||||
size_t out_socket_name_size;
|
||||
|
||||
pid_t *out_terminal_pid; /* may be NULL */
|
||||
} nsigner_spawn_opts_t;
|
||||
|
||||
/* Returns 0 on success, negative on error. On success, the embedded nsigner
|
||||
* binary has been written to a memfd, the terminal window has been launched,
|
||||
* the mnemonic has been written into the child's stdin pipe, and the local
|
||||
* `mnemonic` buffer has been zeroized.
|
||||
*
|
||||
* After return, the host can connect to the socket using
|
||||
* client/nsigner_client.{c,h}
|
||||
* with the chosen socket name in opts->out_socket_name.
|
||||
*/
|
||||
int nsigner_spawn_embedded(nsigner_spawn_opts_t *opts);
|
||||
```
|
||||
|
||||
Optional readiness primitive (post-MVP): a `nsigner_spawn_wait_ready()` call that polls the abstract socket until it accepts a connection or until a timeout, so the host doesn't race the child's bind step.
|
||||
|
||||
### 4.2 Internal pipeline
|
||||
|
||||
1. Validate inputs: non-empty mnemonic, sane buffer sizes, `out_socket_name` non-NULL.
|
||||
2. Pick a socket name: random BIP-39 word pair if not provided. Reuses the same name-generation routine that `nsigner` itself uses; consider extracting it into a shared header `src/socket_name.h` already exists ([`src/socket_name.c`](../src/socket_name.c:1)) and exposing the generator publicly.
|
||||
3. Create memfd: `memfd_create("nsigner", MFD_CLOEXEC)`. On older kernels (no `memfd_create`), return an error rather than falling back to disk — the whole point is no filesystem footprint. (Linux 3.17+ has memfd; the project's deployment targets all qualify.)
|
||||
4. Write the embedded blob to the memfd. `lseek` back to zero is unnecessary because `fexecve`/`execveat` does not care about offset.
|
||||
5. Create stdin pipe: `pipe2(stdin_pipe, O_CLOEXEC)`. Mark only the read end as inheritable in the child (clear `FD_CLOEXEC` on the read end after `fork`).
|
||||
6. Pick a terminal emulator. Detection order: `$NSIGNER_TERMINAL` env override, then `terminal_hint`, then a built-in priority list:
|
||||
|
||||
| Emulator | Run-this flag | Notes |
|
||||
|---|---|---|
|
||||
| `kitty` | `--detach -- <argv>` | preserves stdin |
|
||||
| `foot` | `-- <argv>` | preserves stdin |
|
||||
| `alacritty` | `-e <argv>` | preserves stdin |
|
||||
| `wezterm` | `start -- <argv>` | preserves stdin |
|
||||
| `xterm` | `-e <argv>` | preserves stdin (legacy reliable) |
|
||||
| `gnome-terminal` | **avoided** | dbus-launches, drops stdin/FDs |
|
||||
| `konsole` | `-e <argv>` | mostly preserves stdin |
|
||||
|
||||
If none found, return an error and let the host print a hint to install one.
|
||||
7. Build child argv:
|
||||
- `[0] = chosen_terminal`
|
||||
- `[1..]` = the terminal's "exec" flag(s) and separator
|
||||
- then `[N+0] = "/proc/self/fd/<memfd>"` (path the kernel exposes for the memfd, valid only inside the child's process tree — no on-disk file is created)
|
||||
- then `--listen unix --name <chosen> --mnemonic-stdin`
|
||||
- then each `--preapprove <spec>` pair
|
||||
8. `fork()`. In the child:
|
||||
- `dup2(stdin_pipe[0], 0)` (replace stdin with the read end)
|
||||
- `close(stdin_pipe[1])`
|
||||
- clear `FD_CLOEXEC` on the memfd so `/proc/self/fd/<memfd>` resolves after `execvp` runs the terminal — the terminal then runs `nsigner` via the inherited memfd path
|
||||
- `execvp(chosen_terminal, child_argv)`
|
||||
9. In the parent:
|
||||
- `close(stdin_pipe[0])`
|
||||
- `write(stdin_pipe[1], mnemonic, mnemonic_len)`
|
||||
- `write(stdin_pipe[1], "\n", 1)`
|
||||
- `close(stdin_pipe[1])`
|
||||
- `secure_memzero` over the host's mnemonic buffer
|
||||
- close the memfd in the parent (the child kernel reference keeps it alive)
|
||||
- copy the chosen socket name into `out_socket_name`
|
||||
- return 0
|
||||
|
||||
### 4.3 Failure modes and cleanup
|
||||
|
||||
Every failure path must:
|
||||
|
||||
- close any FDs already opened (memfd, both pipe ends)
|
||||
- zeroize the mnemonic buffer if it was already copied locally
|
||||
- not leave a child process behind: if `fork` succeeded but a later step failed, `waitpid` the child after `kill(SIGTERM)`
|
||||
|
||||
A short error-string accessor (`const char *nsigner_spawn_strerror(int)`) keeps callers from needing to know the internal codes.
|
||||
|
||||
## 5. Security review (to perform before implementation)
|
||||
|
||||
These items are flagged now so the implementation phase doesn't drift:
|
||||
|
||||
1. **Confirm memfd contents are not exposed to other processes.** `/proc/self/fd/<memfd>` is per-process; another process cannot dereference another's `/proc/self/fd/N`. Document that fact in the code comments and in [`documents/SECURITY.md`](../documents/SECURITY.md).
|
||||
2. **Confirm `MFD_CLOEXEC` actually closes on the *outer* exec.** We need the memfd open across `fork`+`execvp(terminal)` but want it gone from the terminal emulator's children that aren't `nsigner`. Tested behavior: clear `FD_CLOEXEC` only on this one FD before `execvp` so the terminal inherits it; the terminal itself doesn't close arbitrary FDs in its child by default but a few do. Document the matrix.
|
||||
3. **Sealing.** Optionally `fcntl(memfd, F_ADD_SEALS, F_SEAL_WRITE | F_SEAL_SHRINK | F_SEAL_GROW)` before exec, so even a compromised child cannot rewrite the binary it is about to execute.
|
||||
4. **Pre-approval defaults.** The helper must NOT silently inject a default `--preapprove` for the host's uid. The host must declare every approval explicitly. This keeps the `documents/SECURITY.md` "deny by default" guarantee intact.
|
||||
5. **Mnemonic in pipe buffer.** The kernel pipe buffer (4 KiB) holds the mnemonic for the moment between parent's `write` and child's `read`. This is in-kernel anonymous memory, comparable to a `mlock`'d page in lifetime, and is freed when both ends close. Acceptable.
|
||||
6. **Mnemonic in environment of the host.** The helper does not put the mnemonic in `envp`. It only goes through the pipe.
|
||||
7. **Host trust elevation.** When the host calls this helper, the host program joins the trust chain (it already had the mnemonic). Document that in [`documents/SECURITY.md`](../documents/SECURITY.md) §2.3 trust-anchors table.
|
||||
8. **Terminal emulator trust.** The chosen terminal emulator is now part of the trust chain (it sees stdin and could capture it). Document; recommend `kitty`/`foot`/`alacritty`/`xterm` and warn against modifying via plugins/config that record stdin.
|
||||
|
||||
## 6. Documentation deliverables
|
||||
|
||||
- `documents/SPAWN.md`: how host programs embed `nsigner_blob.o` and use `nsigner_spawn.{c,h}`.
|
||||
- Update [`documents/SECURITY.md`](../documents/SECURITY.md) §2.3 with the host-program and terminal-emulator trust-chain rows.
|
||||
- Update [`README.md`](../README.md) §3.1 with a one-paragraph "Running embedded inside a host program" note pointing here.
|
||||
- New worked example `examples/spawn_and_sign.c`: takes a mnemonic from its own argv (for the example only — clearly labeled "EXAMPLE: argv mnemonic, not for production"), spawns `nsigner` via the helper, then issues `get_public_key` over the resulting socket and prints the result. This demonstrates the full pattern in ~80 lines.
|
||||
|
||||
## 7. Testing strategy
|
||||
|
||||
Tests are inherently more involved because they require spawning a real terminal emulator. Recommended approach:
|
||||
|
||||
1. **Unit tests for the helper** (`tests/test_spawn_unit.c`):
|
||||
- argv builder produces the expected list given a fixture options struct.
|
||||
- terminal autodetect returns the correct emulator given a fake `$PATH`.
|
||||
- the memfd write produces a payload whose first 4 bytes are `\x7fELF` (sanity).
|
||||
2. **Integration test under a headless terminal** (`tests/test_spawn_integration.c`):
|
||||
- use `xvfb-run` plus `xterm -e` (or `foot --headless`-ish modes if available) so CI can spawn a window without a display server.
|
||||
- the test passes a known mnemonic, waits for the abstract socket to appear, calls `get_public_key`, asserts the returned pubkey matches the BIP-39 vector for that mnemonic.
|
||||
- this test is gated on a build flag because not every CI environment has a usable headless emulator; `make test-spawn` rather than the default `make test`.
|
||||
3. **Manual smoke checklist** in `documents/SPAWN.md` covering the four supported emulators.
|
||||
|
||||
## 8. Open questions to resolve before implementation
|
||||
|
||||
- Should the helper live in `client/` (next to `nsigner_client.{c,h}`) or in a new top-level `embed/` directory? Recommendation: `client/` keeps related host-side code together.
|
||||
- Should the embedded blob be compressed (e.g. zstd-decompress on the fly into the memfd)? Probably not for the first version — extra dependency, marginal size benefit on already-small statically-linked `nsigner`.
|
||||
- How does this interact with code signing on platforms that enforce it (Windows, macOS, signed Linux distros)? Linux generally allows `fexecve` of memfd content; macOS would require a different path. The plan is Linux-only for now; document that.
|
||||
- Should `nsigner` itself learn a `--print-socket-name-on-startup` flag (one line to a designated FD) so the spawn helper doesn't have to choose the name? Useful future addition; keep it as a follow-up after the memfd path proves out.
|
||||
|
||||
## 9. Acceptance criteria (when the time comes to implement)
|
||||
|
||||
- [ ] `make nsigner_blob.o` produces a relocatable object usable by host projects.
|
||||
- [ ] `client/nsigner_spawn.{c,h}` compiles cleanly and links into a host program with no extra dependencies.
|
||||
- [ ] `examples/spawn_and_sign.c` runs end-to-end and prints a valid pubkey.
|
||||
- [ ] No file is created on disk during a successful spawn (verified by `lsof` snapshot or `inotifywait` on `/tmp`, `/run/user/$UID`, `$HOME`).
|
||||
- [ ] Host's mnemonic buffer is wiped on the path to `execvp`.
|
||||
- [ ] Pre-approvals declared by the host appear in the spawned `nsigner`'s policy table without prompting.
|
||||
- [ ] Documentation updates landed in `documents/SPAWN.md`, [`documents/SECURITY.md`](../documents/SECURITY.md), and [`README.md`](../README.md).
|
||||
- [ ] Tests in `tests/test_spawn_unit.c` pass on plain CI; `tests/test_spawn_integration.c` passes under `xvfb-run` on the spawn-CI lane.
|
||||
|
||||
## 10. Relationship to other plans
|
||||
|
||||
- Builds on [`plans/mnemonic_startup_input.md`](mnemonic_startup_input.md) — the embedded helper consumes `--mnemonic-stdin`.
|
||||
- Compatible with [`plans/deny_by_default_approvals.md`](deny_by_default_approvals.md) — every host-issued approval still goes through `--preapprove`.
|
||||
- Compatible with [`plans/caller_token_identity.md`](caller_token_identity.md) — host identity is conveyed via `unix_peer` over the abstract socket like any other client.
|
||||
- Companion to [`plans/auth_envelope_other_transports.md`](auth_envelope_other_transports.md): a host that spawns `nsigner` may also wish to forward authenticated requests on its behalf; out of scope here.
|
||||
195
plans/mnemonic_startup_input.md
Normal file
195
plans/mnemonic_startup_input.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# Plan: Non-interactive mnemonic input at startup (`--mnemonic-stdin`, `--mnemonic-fd`)
|
||||
|
||||
Status: ready to implement.
|
||||
Related: [`documents/SECURITY.md`](../documents/SECURITY.md), [`src/main.c`](../src/main.c:1006), [`src/mnemonic.c`](../src/mnemonic.c:1).
|
||||
Companion plan (future work): [`plans/embedded_nsigner_spawn.md`](embedded_nsigner_spawn.md).
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Allow `n_signer` to receive its mnemonic from a parent process at startup, without the human re-typing it, while preserving the project's existing security posture:
|
||||
|
||||
- nothing on the filesystem
|
||||
- nothing in argv (no `--mnemonic <phrase>` flag)
|
||||
- nothing in environment (no `NSIGNER_MNEMONIC` env var) for production use
|
||||
- the mnemonic source is wiped from process memory immediately after a successful load
|
||||
|
||||
Two new CLI flags are added:
|
||||
|
||||
- `--mnemonic-stdin` — read one line from stdin during the unlock phase, treat that line as the mnemonic, then continue to the normal status display. Stdin is closed (or replaced with `/dev/null`) before the running phase begins so the listener loop and TUI hotkeys keep working.
|
||||
- `--mnemonic-fd N` — read one line from file descriptor `N`, then close it. Intended to be wired by parent processes to a `pipe2(O_CLOEXEC)` write end or a `memfd_create(2)` region. **No filesystem path is involved** — `N` is an inherited FD number, equivalent to stdin in lifecycle but separable so it can coexist with `--listen stdio`.
|
||||
|
||||
The existing interactive TUI prompt remains the default when neither flag is given.
|
||||
|
||||
## 2. Why no `--mnemonic <phrase>` argv flag
|
||||
|
||||
Listed only to make the rejection explicit and discoverable in `git log`:
|
||||
|
||||
- visible to every same-uid process via `/proc/<pid>/cmdline`
|
||||
- captured by `ps auxww`
|
||||
- captured by shell history (`bash`/`zsh` `HISTFILE`)
|
||||
- captured by audit subsystems (`auditd`, sysmon-like agents)
|
||||
- captured by container/VM platform telemetry that records launch commands
|
||||
|
||||
Stdin and inherited FDs do not appear in any of those surfaces. They are the right primitive.
|
||||
|
||||
Likewise no `NSIGNER_MNEMONIC` environment variable, because envp is exposed via `/proc/<pid>/environ` to same-uid readers. Any future env-based override should be opt-in for testing only and named `NSIGNER_TEST_*` like the existing test hooks.
|
||||
|
||||
## 3. CLI surface changes
|
||||
|
||||
### 3.1 New flags (in [`src/main.c`](../src/main.c:1187))
|
||||
|
||||
| Flag | Argument | Behavior |
|
||||
|---|---|---|
|
||||
| `--mnemonic-stdin` | none | read mnemonic from FD 0, then close FD 0 and reopen as `/dev/null` |
|
||||
| `--mnemonic-fd <N>` | int | read mnemonic from FD `N`, then close FD `N` |
|
||||
|
||||
Both flags are mutually exclusive with each other.
|
||||
|
||||
### 3.2 Compatibility with `--listen` modes
|
||||
|
||||
| Listen mode | `--mnemonic-stdin` | `--mnemonic-fd` |
|
||||
|---|---|---|
|
||||
| `unix` (default) | OK | OK |
|
||||
| `tcp:HOST:PORT` | OK | OK |
|
||||
| `stdio` | **rejected** (stdin is the request transport) | OK (FD must not be 0/1) |
|
||||
| `qrexec` | **rejected** (stdio is the request transport) | OK (FD must not be 0/1) |
|
||||
|
||||
If both `--mnemonic-stdin` and `--listen stdio`/`qrexec` are passed, `n_signer` exits with a clear error before doing anything else.
|
||||
|
||||
`--mnemonic-fd` rejects `N == 0` if `--listen stdio`/`qrexec` is also passed, and rejects `N == 1` always (stdout is reserved for response framing in stdio/qrexec modes and for the TUI in unix/tcp modes).
|
||||
|
||||
### 3.3 Updated `print_usage()`
|
||||
|
||||
Two new lines added under the existing options section:
|
||||
|
||||
```
|
||||
--mnemonic-stdin Read mnemonic from stdin (one line). Default unlock prompt is skipped.
|
||||
--mnemonic-fd N Read mnemonic from inherited FD N (anonymous, no filesystem). Same-line semantics.
|
||||
```
|
||||
|
||||
### 3.4 `--help` discoverability
|
||||
|
||||
The current `print_usage()` block in [`src/main.c`](../src/main.c:615) already lists the other flags in tabular form; the two new lines slot in next to `--auth`. No structural change.
|
||||
|
||||
## 4. Behavioral spec
|
||||
|
||||
### 4.1 `prompt_load_mnemonic` becomes `load_mnemonic`
|
||||
|
||||
The existing function [`prompt_load_mnemonic()`](../src/main.c:1006) is renamed/refactored to `load_mnemonic(mnemonic_state_t*, mnemonic_source_t)` where:
|
||||
|
||||
```c
|
||||
typedef enum {
|
||||
MNEMONIC_SRC_TUI_PROMPT = 0, /* current default behavior */
|
||||
MNEMONIC_SRC_STDIN, /* --mnemonic-stdin */
|
||||
MNEMONIC_SRC_FD, /* --mnemonic-fd N */
|
||||
} mnemonic_source_kind_t;
|
||||
|
||||
typedef struct {
|
||||
mnemonic_source_kind_t kind;
|
||||
int fd; /* used for SRC_STDIN (=0) and SRC_FD */
|
||||
} mnemonic_source_t;
|
||||
```
|
||||
|
||||
For `SRC_STDIN` and `SRC_FD`:
|
||||
|
||||
1. Read up to `MNEMONIC_MAX_LEN` bytes from the FD using a small bounded read loop (`read(2)`), stopping at the first `\n` or EOF.
|
||||
2. Trim a single trailing `\n` and any single trailing `\r` (handle Windows-style line endings just in case).
|
||||
3. Reject input containing any embedded `\0` (defensive; mnemonic is text).
|
||||
4. Reject input that ends without seeing EOF or `\n` after `MNEMONIC_MAX_LEN` bytes (caller is misbehaving).
|
||||
5. Pass the buffer to [`mnemonic_load()`](../src/mnemonic.c:1) which already validates word count.
|
||||
6. Zeroize the local read buffer with `secure_memzero` regardless of success/failure.
|
||||
7. On success, close the source FD. For `SRC_STDIN`, also `dup2()` `/dev/null` onto FD 0 so subsequent `read()`s on FD 0 don't accidentally consume bytes meant for nothing.
|
||||
8. On failure (read error, validation error), exit non-zero. There is **no retry loop** in non-interactive mode — the parent should fix its input and re-spawn; silently retrying could mask a serious bug like leaked mnemonic-passing logic.
|
||||
|
||||
For `SRC_TUI_PROMPT`: unchanged, current behavior preserved verbatim, including the existing 10-attempt retry loop.
|
||||
|
||||
### 4.2 Lock/unlock keystroke (`l` hotkey)
|
||||
|
||||
Currently the `l` hotkey calls [`prompt_load_mnemonic()`](../src/main.c:1527) again interactively. After this change:
|
||||
|
||||
- If the original startup used the TUI prompt: `l` re-runs the TUI prompt (unchanged).
|
||||
- If the original startup used `--mnemonic-stdin` or `--mnemonic-fd`: the source FD has already been closed and zeroized, so re-locking would have no source to re-read from. Two options:
|
||||
- **Option A (chosen):** the `l` hotkey falls back to the TUI prompt on re-unlock, regardless of how the original unlock happened. The user is at the terminal, so the TUI prompt is always available.
|
||||
- Option B: disable `l` entirely if non-interactive source was used. Rejected — too restrictive.
|
||||
|
||||
Implementation: track the original source kind in a `static` in main.c; when the user presses `l` after non-interactive startup, log a one-line notice ("re-unlock via terminal prompt") and call the TUI variant.
|
||||
|
||||
### 4.3 Trim/normalize rules
|
||||
|
||||
The mnemonic line is treated as ASCII text. Allowed transformations before validation:
|
||||
|
||||
- strip a single trailing `\r\n` or `\n`
|
||||
- strip leading and trailing ASCII whitespace (space, tab)
|
||||
- collapse internal runs of whitespace? **No** — `mnemonic_load()` already tokenizes on whitespace; passing the trimmed string through unchanged is simpler and matches typed-mnemonic behavior.
|
||||
|
||||
### 4.4 Error messages
|
||||
|
||||
All errors go to stderr (not the TUI), prefixed `nsigner:`, and exit with status 1:
|
||||
|
||||
- `nsigner: --mnemonic-stdin and --mnemonic-fd are mutually exclusive`
|
||||
- `nsigner: --mnemonic-stdin requires --listen unix or --listen tcp:...`
|
||||
- `nsigner: --mnemonic-fd N: invalid FD value`
|
||||
- `nsigner: --mnemonic-fd N: read failed: <strerror>`
|
||||
- `nsigner: mnemonic input exceeded maximum length`
|
||||
- `nsigner: mnemonic validation failed`
|
||||
|
||||
The actual mnemonic content is **never** printed in any error message. The generic "validation failed" message is intentional.
|
||||
|
||||
## 5. Security review checklist
|
||||
|
||||
Items the implementer should verify before merging:
|
||||
|
||||
1. The stack buffer used for the read is wiped with `secure_memzero` on every exit path, including early-error returns.
|
||||
2. If an `mlock`-backed temporary buffer is used instead of a stack buffer, it must be `secure_buf_alloc`'d and `secure_buf_free`'d.
|
||||
3. The source FD is `close(2)`'d after read, before `mnemonic_load` returns control to `main()`. Close happens even on failure paths.
|
||||
4. For `--mnemonic-stdin`, FD 0 is replaced with `/dev/null` (`open("/dev/null", O_RDONLY)` then `dup2`) so later code paths cannot read leftover bytes.
|
||||
5. The new flags are documented in [`README.md`](../README.md) §3.1 (Startup phase) with an explicit note that they are intended for parent-process spawning and that the parent is responsible for FD hygiene.
|
||||
6. The new flags are documented in [`documents/SECURITY.md`](../documents/SECURITY.md) under §2 ("trust anchors") — the parent process now joins the trust chain when these flags are used.
|
||||
7. No new path is added that prints the mnemonic to logs, the activity buffer, or any debug output.
|
||||
8. `man`-style banner / help output never echoes the mnemonic.
|
||||
|
||||
## 6. Testing plan
|
||||
|
||||
New tests:
|
||||
|
||||
- `tests/test_mnemonic_input.c` (new file) covering:
|
||||
1. `--mnemonic-stdin` happy path: spawn `nsigner` with a pipe, write a valid 12-word mnemonic + `\n`, expect successful unlock.
|
||||
2. `--mnemonic-stdin` invalid mnemonic: write garbage, expect non-zero exit.
|
||||
3. `--mnemonic-stdin` no newline before EOF: write valid mnemonic without `\n`, close pipe, expect success.
|
||||
4. `--mnemonic-stdin` line too long: write 1024 bytes, expect non-zero exit with the length error.
|
||||
5. `--mnemonic-fd 3` happy path: parent opens an `O_CLOEXEC=0` pipe, dups its write end as FD 3 in the child via `posix_spawn_file_actions_*`, writes mnemonic, expects success.
|
||||
6. Mutually-exclusive flag combinations: `--mnemonic-stdin --mnemonic-fd 3`, `--mnemonic-stdin --listen stdio`, `--mnemonic-fd 0 --listen stdio` — all expected to exit 1 with the matching error string.
|
||||
7. Lock-then-reunlock after `--mnemonic-stdin` startup: verify the TUI prompt path still works (using `NSIGNER_TEST_HOTKEYS` and `NSIGNER_TEST_NONINTERACTIVE_PROMPT` test hooks).
|
||||
|
||||
Existing tests must continue to pass:
|
||||
|
||||
- [`tests/test_mnemonic.c`](../tests/test_mnemonic.c) (mnemonic library unit tests — unchanged surface)
|
||||
- [`tests/test_integration.c`](../tests/test_integration.c) (default TUI-prompt path)
|
||||
- [`tests/test.sh`](../tests/test.sh) wrapper.
|
||||
|
||||
Add a row to `Makefile` `test` target for the new test binary.
|
||||
|
||||
## 7. Documentation updates
|
||||
|
||||
- [`README.md`](../README.md) §3.1: add a paragraph at the end noting the two new flags and pointing to this plan.
|
||||
- [`documents/SECURITY.md`](../documents/SECURITY.md) §2.3: add a row to the trust-anchors table for "the parent process when `--mnemonic-stdin`/`--mnemonic-fd` is used".
|
||||
- [`documents/CLIENT_IMPLEMENTATION.md`](../documents/CLIENT_IMPLEMENTATION.md): no changes (client wire protocol unaffected).
|
||||
- New section in [`README.md`](../README.md) under "Operating modes" pointing readers to the future spawning plan once that lands.
|
||||
|
||||
## 8. Out of scope (handled by companion plan)
|
||||
|
||||
- Embedding the `nsigner` binary into a host program via `objcopy` blob + `memfd_create` + `fexecve`. See [`plans/embedded_nsigner_spawn.md`](embedded_nsigner_spawn.md).
|
||||
- Reusable C client helper that picks a terminal emulator and wires the pipe. Same companion plan.
|
||||
- `examples/spawn_and_sign.c`. Same companion plan.
|
||||
|
||||
## 9. Acceptance criteria
|
||||
|
||||
- [ ] `nsigner --mnemonic-stdin` reads one line, validates, and proceeds to status display without prompting.
|
||||
- [ ] `nsigner --mnemonic-fd 3` (with FD 3 inherited from a parent test harness) does the same.
|
||||
- [ ] Invalid mnemonics exit non-zero with the generic validation message; mnemonic content is never printed.
|
||||
- [ ] Mutually exclusive flag combinations are rejected at argument-parse time.
|
||||
- [ ] `--listen stdio` and `--mnemonic-stdin` are mutually exclusive.
|
||||
- [ ] After non-interactive unlock, pressing `l` falls back to the TUI prompt for re-unlock and the running phase otherwise behaves identically.
|
||||
- [ ] The mnemonic source FD is closed and the source buffer is zeroized on every path.
|
||||
- [ ] All existing tests still pass; new tests in `tests/test_mnemonic_input.c` pass.
|
||||
- [ ] [`README.md`](../README.md) and [`documents/SECURITY.md`](../documents/SECURITY.md) are updated.
|
||||
101
plans/tui_continuous_integration.md
Normal file
101
plans/tui_continuous_integration.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# tui_continuous integration plan for n_signer
|
||||
|
||||
## Goal
|
||||
|
||||
Adopt the `tui_continuous` style from `/home/user/lt/aesthetics` with minimal-risk restructuring:
|
||||
|
||||
- keep caller-owned poll loop and line-input model
|
||||
- avoid ncurses/event-loop inversion
|
||||
- preserve non-interactive behavior and test compatibility
|
||||
|
||||
## Scope
|
||||
|
||||
### 1) Vendor and wire library
|
||||
|
||||
- Vendor `tui_continuous.c/.h` into this repository under a stable path (planned: `resources/tui_continuous/`).
|
||||
- Add include path and source wiring to:
|
||||
- `Makefile` dev build
|
||||
- targets that link `src/main.c` (notably integration path)
|
||||
- static build flow (`build_static.sh`, Alpine musl path)
|
||||
|
||||
### 2) Main-screen TUI adapter in `src/main.c`
|
||||
|
||||
- Introduce a small adapter layer that owns:
|
||||
- persistent `TuiFrame` (`app_name=nsigner`, `app_version=NSIGNER_VERSION`, breadcrumb)
|
||||
- hotkey menu definitions matching existing behavior (`q/x`, `l`, `r`, `A`)
|
||||
- status text composition (`locked/unlocked`, words, socket, derived, auto-approve)
|
||||
|
||||
### 3) Replace legacy `render_status()` with `tui_continuous`
|
||||
|
||||
- Use `tui_render_screen()` for top framing/menu/status strip.
|
||||
- Render roles with `tui_render_table()` using columns:
|
||||
- role name
|
||||
- purpose
|
||||
- curve
|
||||
- selector
|
||||
- Render activity log (latest first) via `tui_print()`.
|
||||
- Keep prompt anchoring stable with `tui_anchor_prompt()`.
|
||||
|
||||
### 4) Resize behavior
|
||||
|
||||
- Install SIGWINCH handler with `tui_install_resize_handler()` before unix interactive loop.
|
||||
- On each poll tick, if `tui_resize_pending()` is set, repaint current view.
|
||||
|
||||
### 5) Approval flow refactor (`src/server.c` + `src/main.c`)
|
||||
|
||||
- Add server approval callback API in `server.c`:
|
||||
- callback typedef
|
||||
- registration function (`server_set_approval_cb(...)`)
|
||||
- compact request payload struct (caller/method/role/purpose/derivation + optional peer display)
|
||||
- Keep default callback behavior equivalent to existing stdio prompt output for non-TUI and tests.
|
||||
- In `main.c` unix interactive mode, register a TUI-aware callback that:
|
||||
- paints an approval content screen
|
||||
- shows `[y]/[n]/[e]/[a]` options
|
||||
- reads line input (fgets-compatible behavior)
|
||||
- returns policy decision enums
|
||||
- repaints main status screen after decision
|
||||
|
||||
### 6) Mnemonic prompt styling
|
||||
|
||||
- Keep `fgets` input path intact for paste reliability.
|
||||
- Re-style startup and lock/reunlock prompts using `tui_render_content_screen()` + `tui_print()`.
|
||||
|
||||
### 7) Output safety boundaries
|
||||
|
||||
- Keep machine-readable output untouched (client JSON-RPC responses remain raw).
|
||||
- Restrict style updates for non-interactive surfaces to human-facing usage/banner text only.
|
||||
|
||||
### 8) Validation
|
||||
|
||||
- Run/build validation for:
|
||||
- normal dev build
|
||||
- static build flow
|
||||
- existing prompt-related test paths (`NSIGNER_TEST_FORCE_PROMPT`, `NSIGNER_TEST_NONINTERACTIVE_PROMPT`)
|
||||
- Manual visual checks:
|
||||
- narrow/normal/wide terminal widths
|
||||
- live resize behavior
|
||||
- approval prompt arriving during idle and proper redraw afterwards
|
||||
|
||||
### 9) Documentation updates
|
||||
|
||||
- Update `README.md` and security docs where relevant to mention:
|
||||
- adopted TUI style source (`aesthetics/TUI.md`)
|
||||
- vendored `tui_continuous` component/version
|
||||
|
||||
## Execution order
|
||||
|
||||
1. Vendor library and wire build
|
||||
2. Implement main screen adapter + rendering
|
||||
3. Add resize repaint
|
||||
4. Refactor approval callback plumbing
|
||||
5. Add TUI approval view in main
|
||||
6. Re-style mnemonic prompts
|
||||
7. Validate tests/builds + manual UX checks
|
||||
8. Update docs
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No ncurses integration
|
||||
- No event loop ownership changes
|
||||
- No changes to transport semantics (`unix`, `stdio`, `qrexec`, `tcp`)
|
||||
- No machine-readable output format changes
|
||||
Reference in New Issue
Block a user