diff --git a/.env.example b/.env.example deleted file mode 100644 index 9b218103..00000000 --- a/.env.example +++ /dev/null @@ -1,28 +0,0 @@ -# centrs environment variables -# See docs/CONSTITUTION.md (settings precedence) for the full vocabulary. -# Some names are planned; not all are consumed by the CLI yet. - -# Default target device or group label -CENTRS_DEVICE= -CENTRS_GROUP= - -# Direct target coordinates (override registry lookup) -CENTRS_HOST= -CENTRS_ADDRESS= -CENTRS_MAC= - -# Requested protocol adapter: rest-api | native-api | ssh | snmp | mndp | mac-telnet | romon | winbox-terminal -CENTRS_VIA= - -# Credentials (prefer Keychain or other secret store once implemented) -CENTRS_USERNAME= -CENTRS_PASSWORD= - -# Validation policy: explain | validate | run (run implies validate) -CENTRS_VALIDATE=validate - -# Whether resolved metadata should be persisted to the SQLite cache -CENTRS_CACHE=false - -# Output format: text | json | table -CENTRS_FORMAT=text diff --git a/.gitignore b/.gitignore index 1e8e2c4e..55c9523a 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,6 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json # Node environment variable files .env .env* -!.env.example !.env.test # caches diff --git a/CHANGELOG.md b/CHANGELOG.md index e1b5df5e..09d34aba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,35 @@ The minor bump marks the coming transport-default change (native-api first, with availability-aware fallback; not in these previews yet). Preview builds publish `0.2.0-next.` to `@next`; `@latest` stays on 0.1.10. +### Added + +- **Password files** (#672): `--cdb-password-file` / `CENTRS_CDB_PASSWORD_FILE` + and `--password-file` / `CENTRS_PASSWORD_FILE` read the CDB key and the + target password from a file, such as a container's `/run/secrets/`, + on the CLI, `centrs mcp` and the library (`cdbPasswordFile`, + `passwordFile`). The CDB key file is read on each encrypted-CDB load, so + rotating or deleting it takes effect at the next call. A file that cannot + give a password is `cdb/password-unavailable` or `auth/password-unavailable`; + an unneeded CDB key file is not read, and a missing one is only the + `cdb/password-not-needed` warning. ssh (execute, sftp/scp, terminal) sends + no password, so it reads no password file. Value and file in one tier is + `usage/conflicting-flags`. `meta.settings` reports `{kind:"file", key}`. + Only flags and the process environment may name a file: `settings set` + refuses the keys and the `centrs.env` loader drops them. + ### Changed +- **A working-directory `.env` no longer reaches centrs** (#666). Bun + auto-loads `.env`, `.env.local` and `.env.` into `process.env` and + reads its own startup settings from them; when it did, the CLI and + `centrs mcp` entries now re-launch once under `bun --no-env-file` with the + launch environment, and print `settings/dotenv-ignored` on stderr naming + the `CENTRS_*` keys ignored. On Linux the launch environment is exact; + elsewhere a key a `.env` file names is dropped even if the shell exported + it, except the Windows system variables (`PATHEXT`, `SYSTEMROOT`, `WINDIR`, + `COMSPEC`). A dropped `HOME` falls back to `os.homedir()`, and a named + `PATH` is reset to the system default. `.env.example` is gone. + - **Error codes:** RouterOS's `no such …` answers now split by meaning (#659, CHR 7.25.1 and 7.24.6). A missing item in a menu that exists (native `no such item`, a bare REST HTTP 404, `/execute`'s diff --git a/GLOSSARY.txt b/GLOSSARY.txt index 37128c88..1992e8c8 100644 --- a/GLOSSARY.txt +++ b/GLOSSARY.txt @@ -861,3 +861,11 @@ pids EOPNOTSUPP # operating-system error: the requested operation is not supported ENOSYS # operating-system error: the requested function is not implemented NTFS # Windows filesystem supporting the hard links used by the CDB lock +# Dotenv guard (#666): environment variables the OS always sets, kept on re-launch +SYSTEMROOT # Windows system directory variable +WINDIR # Windows directory variable +PATHEXT # Windows executable extensions variable +COMSPEC # Windows command interpreter variable +Wbem # Windows Management Instrumentation directory in the default Windows PATH +NONBLOCK # O_NONBLOCK open flag: a password file never blocks on a FIFO +mkfifo # POSIX command that makes a named pipe (FIFO), used in tests diff --git a/README.md b/README.md index 7c7b2180..914e6f0e 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,11 @@ CLI/MCP add, set and remove operations and `discover --save` reload and retry. Close WinBox before mutating the same file: external writers do not take the centrs lock. Encrypted-CDB reads and writes work with `--cdb-password` / -`CENTRS_CDB_PASSWORD`; writes decrypt, mutate and re-encrypt with a fresh salt. +`CENTRS_CDB_PASSWORD`, or a file holding the password with +`--cdb-password-file` / `CENTRS_CDB_PASSWORD_FILE` (a container's +`/run/secrets/`); writes decrypt, mutate and re-encrypt with a fresh salt. +A target password can come from a file the same way (`--password-file` / +`CENTRS_PASSWORD_FILE`). `devices init --encrypt` creates an encrypted registry, and `devices encrypt` explicitly converts an existing open CDB. Conversion retains existing backups and warns that plaintext copies remain. The manual WinBox round-trip is still diff --git a/commands/devices/README.md b/commands/devices/README.md index c27ee57b..ead05499 100644 --- a/commands/devices/README.md +++ b/commands/devices/README.md @@ -543,8 +543,11 @@ can edit it too. Precedence is per-field: args → env → device record → Start encrypted with `devices init --encrypt`, or start open for a lab and run `devices encrypt` when moving to production. Both require a non-empty -`--cdb-password` / `CENTRS_CDB_PASSWORD`. A password alone does not change the -mode of initialization or ordinary writes. The library exports +`--cdb-password` / `CENTRS_CDB_PASSWORD`, or a file holding it +(`--cdb-password-file` / `CENTRS_CDB_PASSWORD_FILE`, #672). A password alone, +or a file alone, does not change the mode of initialization or ordinary writes: +with an open CDB the file is not read, and a missing one is only the +`cdb/password-not-needed` warning. The library exports `initCdb({ encrypt: true, cdbPassword, cdbFile })` and `encryptCdb({ cdbPassword, cdbFile })`; both use the shared settings precedence. @@ -575,8 +578,8 @@ warning still applies to them. Without the snapshot, a forgotten password cannot be recovered. `init` and `encrypt` act on the CDB file, not on records: they accept only -`--cdb-file`, `--cdb-password`, `--format`/`--json`, plus `--encrypt` (`init`) -or `--no-backup` (`encrypt`). Any other flag is `input/invalid-command` +`--cdb-file`, `--cdb-password`, `--cdb-password-file`, `--format`/`--json`, +plus `--encrypt` (`init`) or `--no-backup` (`encrypt`). Any other flag is `input/invalid-command` instead of being silently ignored. `devices init --help` and `devices encrypt --help` show only those accepted flags; the same metadata generates their sections in [`docs/CLI.md`](../../docs/CLI.md). diff --git a/commands/mcp/README.md b/commands/mcp/README.md index fd100e1d..04a42425 100644 --- a/commands/mcp/README.md +++ b/commands/mcp/README.md @@ -64,7 +64,12 @@ If `centrs` is already installed on `PATH`, the equivalent command is: } ``` -Use `CENTRS_CDB_PASSWORD` to read or write an encrypted CDB. The write layer +Use `CENTRS_CDB_PASSWORD` to read or write an encrypted CDB, or +`CENTRS_CDB_PASSWORD_FILE` (`--cdb-password-file`) to name a file that holds +it, such as `/run/secrets/`. Then the password is in neither argv nor +the environment, and the file is read on every CDB load: rotating it takes +effect at the next call, and deleting it makes calls fail with +`cdb/password-unavailable` while the server keeps running. The write layer decrypts under the loaded password, mutates the record set, and re-encrypts with a fresh salt before the atomic rename. Prefer an unencrypted throwaway CDB for bench harnesses and CI. @@ -168,7 +173,8 @@ MCP server applies it as a hard allowlist: - **CDB source** follows the constitution: default `~/.config/tikoci/winbox.cdb`, overridden by `CENTRS_CDB_FILE` / `--cdb-file`, or a freshly created CDB the operator hands the server at start. An encrypted - CDB is decrypted with `--cdb-password` (or `CENTRS_CDB_PASSWORD`). With no CDB, + CDB is decrypted with `--cdb-password` (or `CENTRS_CDB_PASSWORD`), or with + the file `--cdb-password-file` (or `CENTRS_CDB_PASSWORD_FILE`) names. With no CDB, the server still serves `centrs_explain` (offline); CDB mutations require a loadable CDB file. - **Credentials live in the CDB and are never returned by MCP.** `centrs_devices diff --git a/commands/retrieve/examples.md b/commands/retrieve/examples.md index 0892afc3..8ab49d83 100644 --- a/commands/retrieve/examples.md +++ b/commands/retrieve/examples.md @@ -251,6 +251,36 @@ Exit 1, `transport/connection-refused`. `meta.via="rest-api"`, and nowhere. `meta.validation` has no `result`; its device stage is `skipped` with `reason: "not reached: transport/connection-refused"` (GH#435). +### 16d. The CDB key from a file (#672) + +`$KEY_FILE` holds the password of the encrypted CDB `$ENC_CDB`, as a +container's `/run/secrets/` does. One trailing newline is ignored. + +```bash +centrs retrieve $R /system/resource --cdb-file $ENC_CDB --cdb-password-file $KEY_FILE --json +CENTRS_CDB_PASSWORD_FILE=$KEY_FILE centrs retrieve $R /system/resource --cdb-file $ENC_CDB --json +``` + +Both succeed with the record's credentials (`meta.settings.password.kind="cdb"`). +The key appears nowhere in the envelope. The file is read on each CDB load, so +after it is deleted the next call fails with `cdb/password-unavailable`. +Giving `--cdb-password` too is `usage/conflicting-flags`. With an open CDB the +file is not read: the run succeeds with a `cdb/password-not-needed` warning +that says whether the file exists. + +### 16e. The router password from a file (#672) + +```bash +centrs retrieve $R /system/resource --username $U --password-file $PW_FILE --json +``` + +`ok: true`; `meta.settings.password={kind:"file",key:"--password-file"}`. Like +`--password` and `CENTRS_PASSWORD`, a password file outranks every CDB record, +and a missing one is `auth/password-unavailable`, never a fall back to the +record. So set `CENTRS_PASSWORD_FILE` per invocation, or keep router +passwords in the CDB; in a container-wide environment it replaces every +record's password. + ### 16c. The gate passed, then a later step failed (GH#435) ```bash diff --git a/commands/settings/README.md b/commands/settings/README.md index 70088eab..76c6b6aa 100644 --- a/commands/settings/README.md +++ b/commands/settings/README.md @@ -58,6 +58,7 @@ matters for what `get`/`set`/`print`/`reset` accept: | --- | --- | --- | | `CENTRS_PASSWORD`, `CENTRS_USERNAME` | Default credentials belong to the `__default__` CDB record, which routes through the `devices` write layer and is redacted from structured output (constitution: identity and CDB). A parallel copy in a plaintext file is a second source of truth for the same secret, one that is never redacted. | `centrs devices add __default__ --user … --password …` | | `CENTRS_CDB_PASSWORD` | This is the CDB's own decryption password. Storing it beside an *encrypted* CDB in a plaintext sibling file defeats the encryption. Security-sensitive surface per `SECURITY.md`. | Pass `--cdb-password` per invocation, export the env var in the calling shell, or use `Bun.secret()` once available — never persist to `centrs.env`. | + | `CENTRS_PASSWORD_FILE`, `CENTRS_CDB_PASSWORD_FILE` | A path, not a secret, but only a flag or the process environment may name one (#672). A `centrs.env` line, or a cloned workspace's file, could otherwise point it at `~/.ssh/id_ed25519` and send that file as a password. The `centrs.env` loader drops these keys too. | `--password-file` / `--cdb-password-file` per invocation, or the launching environment (a container's env, an MCP server's launch config). | | `CENTRS_SKIP_ENV_FILE` | Self-referential: it means "don't load `centrs.env`." Writing it *into* `centrs.env` is a no-op by construction (a file that says "ignore me" is never read to find out). | Export it in the shell or pass `--skip-env-file` per call. | | `CENTRS_RUN_FAST_INTEGRATION` | A CI/test signal, not a user preference. | N/A — set by `bun run test:integration`, never by a human. | @@ -225,6 +226,32 @@ canonical `CENTRS_FORMAT=` line. It is **user-global only** — the single XDG path above; there is no project-local config file discovered from the working directory. +**A working-directory `.env` is not read** (#666). Bun loads `.env`, +`.env.local` and `.env.` from the working directory into `process.env` +for any script it runs, and reads some of its own settings from them at +startup (`BUN_CONFIG_VERBOSE_FETCH` would print a REST Basic credential). +So when Bun loaded one, the CLI and `centrs mcp` entries re-launch once +under `bun --no-env-file` with the environment centrs was started with, and +print `warning [settings/dotenv-ignored]` on stderr naming the `CENTRS_*` +keys ignored (never their values). A cloned repo therefore cannot turn on +`CENTRS_INSECURE`, point `CENTRS_CDB_FILE`, a `*_FILE` key or +`XDG_CONFIG_HOME` somewhere, or switch on Bun's fetch logging. On Linux the +child gets exactly the exec-time environment (`/proc/self/environ`), and the +re-launch happens only when Bun changed it. Elsewhere, every key a Bun `.env` +file names is dropped except the Windows system variables (`PATHEXT`, +`SYSTEMROOT`, `WINDIR`, `COMSPEC`), which Windows always sets. A shell +export of a dropped key is lost too, which fails safe. That includes `HOME`: +it picks `centrs.env`, and a Windows shell often has none, so a dropped +`HOME` falls back to the account's home directory (`os.homedir()`). A named +`PATH` is reset to the system default (the OS's own `bin` and `sbin` +directories, or the `SYSTEMROOT` directories with OpenSSH on Windows): a service may start +Bun with no `PATH`, and the file must not pick which `ssh` runs. Bun also +allows a line break between a key and its `=`, so names are matched across +lines. +The shebang stays `env bun` (no `env -S bun --no-env-file`): BusyBox `env` +(Alpine, `oven/bun:alpine`) has no `-S`. A library caller passes its own +`env`. + **The `config` precedence layer** — `src/resolver/config-file.ts` resolves `${XDG_CONFIG_HOME:-~/.config}/tikoci/centrs.env` (injectable `env` map, mirroring `defaultCdbPath`) and `loadEnvFileDefaults()` parses it into a flat diff --git a/commands/terminal/README.md b/commands/terminal/README.md index 88f23056..740c6bc4 100644 --- a/commands/terminal/README.md +++ b/commands/terminal/README.md @@ -128,7 +128,10 @@ omits `BatchMode=yes` (`interactive: true` in `sshCommonOptions`), so the host `ssh` can prompt on the inherited TTY for an encrypted key's passphrase or a password. centrs does not forward `--password` to ssh — OpenSSH accepts no password on the argv — so password auth is satisfied by that interactive prompt, -not by the centrs-resolved credential. +not by the centrs-resolved credential. For the same reason the ssh terminal +reads no password source: `--password-file` and `CENTRS_PASSWORD_FILE` are +mac-telnet only, so an image-wide file that is missing cannot stop a key or +agent login. Resolved by the sftp transfer client (`src/protocols/sftp.ts`), so they are no longer open for the file path: **host-key verification** rides the unified diff --git a/docs/CLI.md b/docs/CLI.md index 696c67f8..607a1de1 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -52,6 +52,7 @@ Usage: centrs retrieve [flags] | centrs retrieve ` | Override the resolved management port. | | `--username / --user / -u` | `` | RouterOS username (aliases `--user`, `-u`). Falls back to `CENTRS_USERNAME`. | | `--password` | `` | RouterOS password. Falls back to `CENTRS_PASSWORD`. | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--timeout` | <ms\|5s> | Per-request timeout, separate from --wait's overall deadline. REST currently rejects values above 60s. | | `--attribute` | `` | Project one attribute. May be repeated. | | `--attributes` | `` | Project a comma-separated attribute list. | @@ -71,6 +72,7 @@ Usage: centrs retrieve [flags] | centrs retrieve ` | Fail instead of printing output larger than the given byte budget. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | Pick one of several CDB records saved for `` (as `devices show --match`); single target only. | | `--resolve` | <none\|arp> | Resolve a MAC-address target to an IP via the host ARP cache (default none). | | `--validate / --no-validate` | | Enable or disable inspect-backed preflight validation. | @@ -101,10 +103,12 @@ Usage: centrs execute [flags] | centrs execute -- | `--port` | `` | Override the resolved management port. | | `--username / --user / -u` | `` | RouterOS username (aliases `--user`, `-u`). Falls back to `CENTRS_USERNAME`. | | `--password` | `` | RouterOS password. Falls back to `CENTRS_PASSWORD`. | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--ssh-key` | `` | `--via ssh`: explicit private-key path. Falls back to `CENTRS_SSH_KEY` / the `ssh-agent`. | | `--insecure` | | Disable SSH host-key verification (`--via ssh`: accepts changed/impersonated keys, not just new) or accept a self-signed `api-ssl` TLS cert. Default verifies. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | Pick one of several CDB records saved for `` (as `devices show --match`); single target only. | | `--resolve` | <none\|arp> | Resolve a MAC-address target to an IP via the host ARP cache (default none). | | `--timeout` | `` | Per-request timeout (for REST, max 60s). | @@ -151,9 +155,11 @@ Usage: centrs api [flags] | centrs api --host ` | Override the resolved management port. | | `--username / --user / -u` | `` | RouterOS username. Falls back to `CENTRS_USERNAME`. | | `--password` | `` | RouterOS password. Falls back to `CENTRS_PASSWORD`. | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--insecure` | | Accept a self-signed `api-ssl`/REST TLS cert. Default verifies. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | Pick one of several CDB records saved for `` (as `devices show --match`); single target only. | | `--resolve` | <none\|arp> | Resolve a MAC-address target to an IP via the host ARP cache (default none). | | `--timeout` | `` | Per-request timeout (for REST, max 60s). | @@ -194,12 +200,14 @@ Usage: centrs transfer |--host upload [remote] | download | `--port` | `` | Override the resolved management port. | | `--username / --user / -u` | `` | RouterOS username (aliases --user, -u). Falls back to CENTRS_USERNAME. | | `--password` | `` | RouterOS password. Falls back to CENTRS_PASSWORD. | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--timeout` | <ms\|5s> | Operation timeout. REST rejects values above 60s. | | `--format` | <text\|json\|yaml> | Output format. Defaults to text; --json / --yaml shortcuts. | | `--json` | | Shortcut for --format json. | | `--yaml` | | Shortcut for --format yaml. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | Pick one of several CDB records saved for `` (as `devices show --match`); single target only. | | `--validate / --no-validate` | | Enable or disable the existence-probe preflight. | | `--verbose` | | Show the resolved transport in text output, on stderr. | @@ -219,12 +227,14 @@ Usage: centrs terminal [flags] | centrs terminal --host [flags] | `--port` | `` | Override the port: ssh default 22, mac-telnet default 20561. | | `--quickchr` | `` | Open an ssh console to one running quickchr machine; host/port/user/key come from its descriptor. Once only; not with ``, --host, --port, --username, --password, --ssh-key or --match. | | `--username / --user / -u` | `` | RouterOS username (aliases --user, -u). Falls back to CENTRS_USERNAME. | -| `--password` | `` | RouterOS password. Falls back to CENTRS_PASSWORD. | +| `--password` | `` | mac-telnet: RouterOS password. Falls back to CENTRS_PASSWORD. Interactive ssh ignores it; OpenSSH prompts itself. | +| `--password-file` | `` | mac-telnet: read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. Interactive ssh never reads it. | | `--source-mac` | `` | mac-telnet: explicit in-packet source MAC (overrides egress resolution). | | `--ssh-key` | `` | `--via ssh`: explicit private-key path. Falls back to `CENTRS_SSH_KEY` / the `ssh-agent`. | | `--insecure` | | `--via ssh`: disable host-key verification (accepts changed/impersonated keys). Default verifies. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | Pick one of several CDB records saved for `` (as `devices show --match`); single target only. | | `--resolve` | <none\|arp> | `--via ssh` only: turn a MAC target into an IP. CDB-first; `arp` opts into the host ARP cache (default none). The mac-telnet default ignores it. | | `--format` | <text\|json\|yaml> | Error-envelope format on failure. --json / --yaml shortcuts. | @@ -247,9 +257,11 @@ Usage: centrs explain [] '' [flags] | `--port` | `` | Override the resolved management port. | | `--username / --user / -u` | `` | RouterOS username. Falls back to `CENTRS_USERNAME`. | | `--password` | `` | RouterOS password. Falls back to `CENTRS_PASSWORD`. | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--insecure` | | Accept a self-signed `api-ssl`/REST TLS cert. Default verifies. | | `--cdb-file` | `` | Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--resolve` | <none\|arp> | Resolve a MAC-address target to an IP via the host ARP cache (default none). | | `--timeout` | `` | Per-request timeout (for REST, max 60s). | | `-p` | `` | Alias for --password. | @@ -281,6 +293,7 @@ Usage: centrs devices [args] | `--no-backup` | | `encrypt` only — skip the plaintext pre-conversion snapshot. Without that snapshot, a forgotten password cannot be recovered. | | `--cdb-file` | `` | Override the resolved CDB path (default `~/.config/tikoci/winbox.cdb`). | | `--cdb-password` | `` | CDB password for encrypted reads, writes, explicit encrypted initialization and conversion. Falls back to `CENTRS_CDB_PASSWORD`; a password alone never converts an open CDB. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--via` | `` | Resolve and report the protocol source for provenance examples; no network IO is performed. | | `--group` | `` | `list` filter / `add`,`set` first-class group field for the target entry. | | `--where` | `` | `list` only — repeatable device-class filter over CDB facts (AND-combined), e.g. `--where lat=37.7749`. | @@ -322,6 +335,7 @@ Usage: centrs devices init [flags] | `--encrypt` | | `init` only — require encrypted creation with a non-empty CDB password; refuse an existing open CDB. | | `--cdb-file` | `` | Override the resolved CDB path (default `~/.config/tikoci/winbox.cdb`). | | `--cdb-password` | `` | CDB password for encrypted reads, writes, explicit encrypted initialization and conversion. Falls back to `CENTRS_CDB_PASSWORD`; a password alone never converts an open CDB. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--format` | <text\|json\|yaml> | Output format for the CLI response. | | `--json` | | Shortcut for `--format json`. | @@ -338,6 +352,7 @@ Usage: centrs devices encrypt [flags] | `--no-backup` | | `encrypt` only — skip the plaintext pre-conversion snapshot. Without that snapshot, a forgotten password cannot be recovered. | | `--cdb-file` | `` | Override the resolved CDB path (default `~/.config/tikoci/winbox.cdb`). | | `--cdb-password` | `` | CDB password for encrypted reads, writes, explicit encrypted initialization and conversion. Falls back to `CENTRS_CDB_PASSWORD`; a password alone never converts an open CDB. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--format` | <text\|json\|yaml> | Output format for the CLI response. | | `--json` | | Shortcut for `--format json`. | @@ -357,6 +372,7 @@ Usage: centrs discover [--timeout 15s] [--save] [flags] | `--port` | `` | UDP port to bind for MNDP. Default 5678. | | `--cdb-file` | `` | `--save` CDB path override (default `~/.config/tikoci/winbox.cdb`). | | `--cdb-password` | `` | `--save` password for an encrypted CDB. Used to decrypt the existing CDB and re-encrypt on write. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--format` | <text\|json\|yaml> | Output format for the CLI response. | | `--json` | | Shortcut for `--format json`. | @@ -387,9 +403,11 @@ Usage: centrs btest |server> [flags] | `--max-sessions` | `` | (server) Concurrent test cap (1..1000). Default 100. | | `--user / --username / -u` | `` | Credential (aliases --username, -u; falls back to CDB / CENTRS_USERNAME). | | `--password` | `` | Credential (falls back to CDB / CENTRS_PASSWORD). | +| `--password-file` | `` | Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. | | `--port` | `` | Control port. Default 2000. | | `--cdb-file` | `` | (client) Read target credentials from a WinBox CDB file. | | `--cdb-password` | `` | (client) Decrypt an encrypted WinBox CDB file. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--match` | <user=name\|target=addr\|record-type> | (client) Pick one of several CDB records saved for `` (as `devices show --match`); `btest server` rejects it. | | `--format` | <text\|csv\|json\|yaml> | Output format. Default text. | | `--csv` | | Shortcut for `--format csv`. | @@ -406,6 +424,7 @@ Usage: centrs mcp [start] [--cdb-file ] [--allow-adhoc-targets] | ---- | ----- | ----------- | | `--cdb-file` | `` | CDB allowlist path (default `~/.config/tikoci/winbox.cdb`, or CENTRS_CDB_FILE). | | `--cdb-password` | `` | Decrypt password for an encrypted CDB (or CENTRS_CDB_PASSWORD). | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--allow-adhoc-targets` | | Reserved unsafe escape hatch for future inline targets; current tools still use CDB-only targets. | | `--help` | | Show this help. | @@ -422,6 +441,7 @@ Usage: centrs settings [print|get|set|reset] [args] [flags] | `--all` | | `print` only — also list unrecognized CENTRS_* lines found in the file. | | `--cdb-file` | `` | `print` only — CDB to probe for the `__default__` record summary (falls back to normal CDB resolution; never centrs.env). | | `--cdb-password` | `` | `print` only — decrypt password for the probed CDB. | +| `--cdb-password-file` | `` | Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`. | | `--skip-env-file` | | `print` only — note that other commands in this environment would not see centrs.env (settings itself always reads the real file). | | `--format` | <text\|json\|yaml> | Output format for the CLI response. | | `--json` | | Shortcut for `--format json`. | diff --git a/docs/CONSTITUTION.md b/docs/CONSTITUTION.md index ac69fc33..6174e153 100644 --- a/docs/CONSTITUTION.md +++ b/docs/CONSTITUTION.md @@ -278,6 +278,26 @@ Lowest to highest priority: `meta.settings` reports the winning source for each resolved setting. +A working directory's `.env` is not a tier. Bun auto-loads it into +`process.env`, so when it did, the CLI and MCP entries re-launch under +`bun --no-env-file` with the launch environment before resolving anything +(#666; mechanics in `commands/settings/README.md`). + +**Secrets come as a value or a file** (#672). The CDB key +(`--cdb-password` / `CENTRS_CDB_PASSWORD`) and the target password +(`--password` / `CENTRS_PASSWORD`) each also have a file form +(`--cdb-password-file` / `CENTRS_CDB_PASSWORD_FILE`, `--password-file` / +`CENTRS_PASSWORD_FILE`), for a container's `/run/secrets`. Within one tier the +forms are one choice; setting both is `usage/conflicting-flags`, and flags +still outrank the environment. Only a flag or the process environment may +name a `*_FILE` path, never `centrs.env` or a workspace file, so a cloned +config cannot point it at another file. A file is read when its secret is +needed (each encrypted-CDB load; each target password resolution), one +trailing newline stripped as for `--password-stdin`. A file that cannot give +a password is `cdb/password-unavailable` or `auth/password-unavailable`, +naming the path, never the contents; an unneeded CDB key file is not read. +One resolver serves CLI, MCP and the library (`src/resolver/secret-source.ts`). + ### Identity and CDB The `` argument may be an IP, a DNS name, a MAC, or an **identity** diff --git a/docs/MATRIX.md b/docs/MATRIX.md index 9045906c..0e95e1af 100644 --- a/docs/MATRIX.md +++ b/docs/MATRIX.md @@ -321,7 +321,10 @@ that keeps growing is being used as an issue. `centrs.env` or a workspace file, so workspace trust does not bound it. Value, file and a later command are one choice per secret (setting two is a usage error), resolved in one place and read on each CDB load. Removing a - file after import is the host's job, not centrs's. + file after import is the host's job, not centrs's. Key rotation is open: a + rekey that takes the old and new CDB keys from separate sources (each a + value or a file) would let app-t3code follow an `/app` secret change + without re-seeding the CDB (#674 review). - **Absorbed:** #420, #542, #603. ### Batch reads and sessions diff --git a/docs/errors/auth/password-unavailable.md b/docs/errors/auth/password-unavailable.md new file mode 100644 index 00000000..b0ecc039 --- /dev/null +++ b/docs/errors/auth/password-unavailable.md @@ -0,0 +1,34 @@ +# `auth/password-unavailable` + +A RouterOS password file could not supply a password. The file comes from +`--password-file` or `CENTRS_PASSWORD_FILE`. It is missing, unreadable, not +a regular file (a FIFO or a device), empty, or not UTF-8 text. `context.path` and `context.source` name the file +and where it was set; the contents are never shown. + +A password file outranks CDB records, as `--password` and `CENTRS_PASSWORD` +do. So when one is named and cannot be read, centrs stops rather than log in +with the record's password. Paths that send no password read no file: ssh +(`execute --via ssh`, sftp and scp transfers, and the interactive `terminal`), +and `btest server --no-authenticate`. + +## Typical triggers + +- `CENTRS_PASSWORD_FILE` points at a secret that is not mounted in this + container *(code)*. +- The file is not readable by the user centrs runs as *(code)*. +- The file is empty, or was saved with a byte-order mark *(code)*. + +## Fix + +- Check that the file exists, is readable and holds the password as UTF-8. + One trailing newline is ignored. +- To use the CDB record's password instead, unset `CENTRS_PASSWORD_FILE`. + Set it per invocation rather than in a container-wide environment: there it + replaces every record's password. + +## Related + +- [`cdb/password-unavailable`](../cdb/password-unavailable.md): the same for + the CDB key. +- [`transport/auth-failed`](../transport/auth-failed.md): the password was + read, but the router refused it. diff --git a/docs/errors/cdb/decrypt-failed.md b/docs/errors/cdb/decrypt-failed.md index 0e2f5eeb..25e9a768 100644 --- a/docs/errors/cdb/decrypt-failed.md +++ b/docs/errors/cdb/decrypt-failed.md @@ -20,8 +20,7 @@ A missing password is a different code: - Use the password the CDB was saved with: the WinBox address-book password, or the one given to `centrs devices init --encrypt` or `devices encrypt`. -- Check that `CENTRS_CDB_PASSWORD` is not set to an old value, in the shell - or in a `.env` file centrs loads. +- Check that `CENTRS_CDB_PASSWORD` is not set to an old value in the shell. - There is no way to recover a forgotten password. `devices encrypt` keeps a plaintext snapshot unless `--no-backup` was passed. diff --git a/docs/errors/cdb/password-not-needed.md b/docs/errors/cdb/password-not-needed.md index 2da5b446..a9c27c31 100644 --- a/docs/errors/cdb/password-not-needed.md +++ b/docs/errors/cdb/password-not-needed.md @@ -5,17 +5,24 @@ password was ignored. `ok` and `error` say how the command itself went. ## Typical triggers -- `CENTRS_CDB_PASSWORD` left set in the shell or in a `.env` file centrs - loads, after switching to an unencrypted CDB *(code)*. +- `CENTRS_CDB_PASSWORD` left set in the shell after switching to an + unencrypted CDB *(code)*. - `--cdb-password` passed out of habit *(code)*. +- `CENTRS_CDB_PASSWORD_FILE` set image-wide in a container whose CDB is open + or not created yet. The file is not read, and the message says whether it + exists, so a missing secret mount shows up without failing the run *(code)*. ## Fix -- Drop `--cdb-password`, or unset `CENTRS_CDB_PASSWORD`. If a `.env` file - sets it, remove the line there too: Bun loads `.env` again on every run. +- Drop `--cdb-password`, or unset `CENTRS_CDB_PASSWORD`. A file form + (`--cdb-password-file`, `CENTRS_CDB_PASSWORD_FILE`) can stay set where an + encrypted CDB is expected later; it never converts an open CDB. - To encrypt this CDB instead, run `centrs devices encrypt` with the new - password in `--cdb-password` or `CENTRS_CDB_PASSWORD`. It refuses an empty - one with [`cdb/password-required`](password-required.md). + password in `--cdb-password` or `CENTRS_CDB_PASSWORD`, or in the file + `--cdb-password-file` or `CENTRS_CDB_PASSWORD_FILE` names. An empty value + fails with [`cdb/password-required`](password-required.md); an empty file + (or one holding only a newline) fails with + [`cdb/password-unavailable`](password-unavailable.md). ## Related diff --git a/docs/errors/cdb/password-required.md b/docs/errors/cdb/password-required.md index 08a642e9..9b92e388 100644 --- a/docs/errors/cdb/password-required.md +++ b/docs/errors/cdb/password-required.md @@ -4,7 +4,8 @@ A CDB password is required for decryption or explicit encryption. ## Fix -Pass `--cdb-password` or set `CENTRS_CDB_PASSWORD` to the CDB password. +Give the CDB password with `--cdb-password` or `CENTRS_CDB_PASSWORD`, or name +a file holding it with `--cdb-password-file` or `CENTRS_CDB_PASSWORD_FILE`. `devices init --encrypt` and `devices encrypt` require a non-empty password, even when the file is currently open. A password alone never implicitly converts an existing open CDB; use `devices encrypt` explicitly. diff --git a/docs/errors/cdb/password-unavailable.md b/docs/errors/cdb/password-unavailable.md new file mode 100644 index 00000000..83804c69 --- /dev/null +++ b/docs/errors/cdb/password-unavailable.md @@ -0,0 +1,42 @@ +# `cdb/password-unavailable` + +The CDB needed its key, and the file named for it could not supply one. The +file comes from `--cdb-password-file` or `CENTRS_CDB_PASSWORD_FILE`. It is +missing, unreadable, not a regular file (a FIFO or a device), empty, or not +UTF-8 text. `context.path` and +`context.source` name the file and where it was set; the contents are never +shown. + +The key is needed only to load an encrypted CDB, for +`devices init --encrypt` and for `devices encrypt`. With an open CDB, +including one this run created, the file is not read: a missing file there +is the [`cdb/password-not-needed`](password-not-needed.md) warning, not this +error. When no CDB is in play at all (a literal host and no CDB file), the +file is neither read nor mentioned. + +## Typical triggers + +- A container secret that is not mounted: `/run/secrets/` is absent + because the `/app` or Docker definition does not list the secret for this + service *(code)*. +- The file was rotated or removed after the MCP server started. It is read on + every CDB load, so the next call sees the change *(code)*. +- The file is not readable by the user centrs runs as *(code)*. +- The file is empty, or was saved with a byte-order mark *(code)*. + +## Fix + +- Whoever launched centrs set the path: check that the file exists, is + readable by that process and holds the password as UTF-8. One trailing + newline is ignored, as for `--password-stdin`. +- On MCP, fix the server's launch configuration and leave the agent out of it: + the agent cannot supply the key, and should not ask for it. +- To give the key another way, unset the file form and use `--cdb-password` + or `CENTRS_CDB_PASSWORD`. Setting both forms in one place is + `usage/conflicting-flags`. + +## Related + +- [`cdb/password-required`](password-required.md): no key source at all. +- [`cdb/decrypt-failed`](decrypt-failed.md): the file was read, but the key + is wrong. diff --git a/docs/errors/settings/dotenv-ignored.md b/docs/errors/settings/dotenv-ignored.md new file mode 100644 index 00000000..9abc30d0 --- /dev/null +++ b/docs/errors/settings/dotenv-ignored.md @@ -0,0 +1,39 @@ +# `settings/dotenv-ignored` + +A warning, printed on stderr before the command runs: Bun loaded `CENTRS_*` +keys from a `.env` file in the working directory, so centrs re-ran itself +under `bun --no-env-file` with the environment it was started with. The +command then ran as if those keys, and anything else the file set, were +unset. + +centrs reads settings from flags, the process environment, `centrs.env` and +the CDB. A repository's `.env` is none of those, and a cloned repo must not be +able to switch off TLS checks (`CENTRS_INSECURE`), pick the CDB +(`CENTRS_CDB_FILE`) or name a password file (`CENTRS_PASSWORD_FILE`). The +warning names the keys and files, never the values. + +## Typical triggers + +- Running `centrs`, or an agent host starting `centrs mcp`, inside a project + whose `.env`, `.env.local` or `.env.development` sets `CENTRS_*` *(code)*. +- On macOS or Windows, a key the shell exported that a `.env` file also + names. Only Linux can tell the two apart, so elsewhere it is dropped too + *(code)*. Only the Windows system variables are kept. A dropped `HOME` + falls back to the account's home directory, and a named `PATH` is reset to + the system default; the warning then says so. + +## Fix + +- Pass the key's flag for the run that needs it. On Linux, exporting the key + in the shell works too. On macOS and Windows an export is dropped while a + `.env` file names the key, so remove that line from the `.env` first. +- For a lasting preference, use `centrs settings set `, which + writes the user-global `centrs.env`. It refuses credentials and the + password-file keys (`CENTRS_PASSWORD_FILE`, `CENTRS_CDB_PASSWORD_FILE`); + name a file with `--password-file` / `--cdb-password-file`, or export the + key in the shell or container environment. +- Or remove the `CENTRS_*` lines from the project's `.env`. + +## Related + +- [`settings/reserved-key`](reserved-key.md) diff --git a/src/api-fanout.ts b/src/api-fanout.ts index de126f03..0bb0307d 100644 --- a/src/api-fanout.ts +++ b/src/api-fanout.ts @@ -238,6 +238,7 @@ export async function apiFanout( { cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, allowAdhoc: options.allowAdhoc ?? true, }, env, diff --git a/src/api.ts b/src/api.ts index e0910e70..2edad1a6 100644 --- a/src/api.ts +++ b/src/api.ts @@ -157,6 +157,8 @@ export interface ApiRequest { port?: number; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; insecure?: boolean; timeout?: string | number; format?: string; @@ -165,6 +167,7 @@ export interface ApiRequest { verbose?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -948,6 +951,7 @@ export async function resolveApiRequest( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, @@ -1047,7 +1051,11 @@ export async function resolveApiRequest( const auth = connection ? connection.auth : resolveAuth( - { username: request.username, password: request.password }, + { + username: request.username, + password: request.password, + passwordFile: request.passwordFile, + }, env, cdbResolution, config, diff --git a/src/btest.ts b/src/btest.ts index e4f754c5..e227d55a 100644 --- a/src/btest.ts +++ b/src/btest.ts @@ -15,7 +15,11 @@ */ import { createServer } from "node:net"; -import type { CentrsEnvelope, EnvelopeMeta } from "./core/envelope.ts"; +import type { + CentrsEnvelope, + CommonSettingsMeta, + EnvelopeMeta, +} from "./core/envelope.ts"; import { asCentrsError, CentrsError, @@ -38,11 +42,17 @@ import { runBtestClientSession, } from "./protocols/btest-session.ts"; import { + type ResolvedAuth, redactTargetInput, resolveAuth, resolveCdb, resolveTarget, + toCoreSource, } from "./resolver/index.ts"; +import { + chooseSecret, + TARGET_PASSWORD_SECRET, +} from "./resolver/secret-source.ts"; export { BTEST_PORT, BTEST_UDP_PORT_START }; @@ -102,6 +112,8 @@ export interface BtestClientRequest { controlPort?: number; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; durationMs?: number; intervalMs?: number; connectionCount?: number; @@ -113,6 +125,7 @@ export interface BtestClientRequest { natMode?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -240,6 +253,7 @@ export async function btestClient( context?: Record; }[] = []; + let auth: ResolvedAuth | undefined; try { validateClientOptions(request); @@ -270,6 +284,7 @@ export async function btestClient( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, @@ -283,8 +298,12 @@ export async function btestClient( "rest-api", cdbResolution, ); - const auth = resolveAuth( - { username: request.username, password: request.password }, + auth = resolveAuth( + { + username: request.username, + password: request.password, + passwordFile: request.passwordFile, + }, env, cdbResolution, ); @@ -391,10 +410,10 @@ export async function btestClient( data, warnings: warnings.map((w) => ({ ...w })), tips: [], - meta: clientMeta(target.host, controlPort, operation, auth.username), + meta: clientMeta(target.host, controlPort, operation, auth), }; } catch (error) { - return buildClientErrorEnvelope(request, operation, error); + return buildClientErrorEnvelope(request, operation, error, auth); } } @@ -402,24 +421,43 @@ function clientMeta( host: string, port: number, operation: BtestClientOperationMeta, - user?: string, + auth: ResolvedAuth, ): EnvelopeMeta { return { target: { host, port, - ...(user !== undefined ? { user } : {}), + ...(auth.username !== undefined ? { user: auth.username } : {}), }, via: "btest", - settings: {}, + settings: authSettings(auth), operation, }; } +/** + * Where the credential came from (`meta.settings.username` / `.password`), + * never its value; a password file reports `{ kind: "file", key }` (#672). + * Nothing when no credential was resolved (an open server, or a failure + * before resolution). + */ +function authSettings(auth: ResolvedAuth | undefined): CommonSettingsMeta { + if (auth === undefined) return {}; + return { + ...(auth.usernameSource + ? { username: toCoreSource(auth.usernameSource) } + : {}), + ...(auth.passwordSource + ? { password: toCoreSource(auth.passwordSource) } + : {}), + }; +} + function buildClientErrorEnvelope( request: BtestClientRequest, operation: BtestClientOperationMeta, error: unknown, + auth: ResolvedAuth | undefined, ): BtestClientEnvelope { const centrsError = asCentrsError(error, { code: "routeros/btest-protocol", @@ -441,7 +479,7 @@ function buildClientErrorEnvelope( port: operation.controlPort, }, via: "btest", - settings: {}, + settings: authSettings(auth), operation, }, }; @@ -455,6 +493,8 @@ export interface BtestServerRequest { authenticate?: boolean; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; allocateUdpPortsFrom?: number; maxSessions?: number; intervalMs?: number; @@ -551,13 +591,6 @@ export async function btestServer( const authenticate = request.authenticate ?? true; const maxSessions = request.maxSessions ?? DEFAULT_MAX_SESSIONS; const allocateFrom = request.allocateUdpPortsFrom ?? BTEST_UDP_PORT_START; - // Resolve the single accepted credential through the same path as the client - // (flags first, then CENTRS_USERNAME / CENTRS_PASSWORD). No CDB here — the - // server has no target device. - const auth = resolveAuth( - { username: request.username, password: request.password }, - request.env ?? Bun.env, - ); const operation: BtestServerOperationMeta = { command: "btest", mode: "server", @@ -565,12 +598,32 @@ export async function btestServer( port, }; + let auth: ReturnType | undefined; try { validateServerOptions(request); + const env = request.env ?? Bun.env; + const credentials = { + username: request.username, + password: request.password, + passwordFile: request.passwordFile, + }; + // Resolve the single accepted credential through the same path as the + // client (flags first, then CENTRS_USERNAME / CENTRS_PASSWORD and the + // file forms). No CDB here — the server has no target device. Inside the + // envelope boundary: a missing password file or a value/file conflict is + // an error envelope, not a rejected call (#672). An open server uses no + // credential, so it reads no file; a value/file conflict still fails. + if (authenticate) auth = resolveAuth(credentials, env); + else + chooseSecret( + TARGET_PASSWORD_SECRET, + { value: credentials.password, file: credentials.passwordFile }, + env, + ); // authenticate=true (the default) without a credential would bind a server // that rejects every client — fail fast instead. if ( - authenticate && + auth !== undefined && (auth.username === undefined || !auth.passwordProvided) ) { throw optionError( @@ -579,7 +632,7 @@ export async function btestServer( ); } } catch (error) { - return buildServerErrorEnvelope(operation, error); + return buildServerErrorEnvelope(operation, error, auth); } const sessions: BtestSessionRecord[] = []; @@ -624,12 +677,10 @@ export async function btestServer( authenticate, // Only the resolved credential, and only when auth is on (never // leak creds into an unauthenticated handshake). - ...(authenticate && auth.username !== undefined + ...(auth?.username !== undefined ? { username: auth.username } : {}), - ...(authenticate && auth.passwordProvided - ? { password: auth.password } - : {}), + ...(auth?.passwordProvided ? { password: auth.password } : {}), serverUdpPort, udpBindHost: bind === "127.0.0.1" ? "127.0.0.1" : "0.0.0.0", ...(request.intervalMs !== undefined @@ -692,7 +743,11 @@ export async function btestServer( }); }); } catch (error) { - return buildServerErrorEnvelope(operation, listenError(error, bind, port)); + return buildServerErrorEnvelope( + operation, + listenError(error, bind, port), + auth, + ); } await new Promise((resolve) => { @@ -731,7 +786,12 @@ export async function btestServer( }, warnings: warnings.map((w) => ({ ...w })), tips: [], - meta: { target: {}, via: "btest", settings: {}, operation }, + meta: { + target: {}, + via: "btest", + settings: authSettings(auth), + operation, + }, }; } @@ -764,6 +824,7 @@ function listenError(error: unknown, bind: string, port: number): CentrsError { function buildServerErrorEnvelope( operation: BtestServerOperationMeta, error: unknown, + auth: ResolvedAuth | undefined, ): BtestServerEnvelope { const centrsError = asCentrsError(error, { code: "routeros/btest-protocol", @@ -776,7 +837,12 @@ function buildServerErrorEnvelope( error: serializeCentrsError(centrsError), warnings: [], tips: [], - meta: { target: {}, via: "btest", settings: {}, operation }, + meta: { + target: {}, + via: "btest", + settings: authSettings(auth), + operation, + }, }; } diff --git a/src/cli.ts b/src/cli.ts index efa043e2..a921f049 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -16,6 +16,7 @@ import { runVersionCli } from "./cli/version.ts"; import { asCentrsError, formatCentrsErrorText } from "./errors.ts"; import { describeCentrs, implementedSurfaces } from "./index.ts"; import { protocolPlans } from "./protocols/index.ts"; +import { runWithoutDotenv } from "./resolver/dotenv-guard.ts"; /** Every CLI command's metadata, in help/docs order. `scripts/gen-cli-docs.ts` renders `docs/CLI.md` from this. */ export const cliCommands: ReadonlyArray = [ @@ -178,5 +179,7 @@ export async function runCli( } if (import.meta.main) { - process.exitCode = await runCli(); + // #666: a cloned repo's `.env` must not reach centrs through Bun's + // auto-load; when Bun loaded one, re-launch under `--no-env-file`. + process.exitCode = await runWithoutDotenv(() => runCli()); } diff --git a/src/cli/api.ts b/src/cli/api.ts index 0ef239a1..54cd46a6 100644 --- a/src/cli/api.ts +++ b/src/cli/api.ts @@ -156,6 +156,12 @@ export const apiCommand: CliCommandMetadata = { valueName: "", description: "RouterOS password. Falls back to `CENTRS_PASSWORD`.", }, + { + flag: "--password-file", + valueName: "", + description: + "Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`.", + }, { flag: "--insecure", description: @@ -171,6 +177,12 @@ export const apiCommand: CliCommandMetadata = { valueName: "", description: "Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -343,6 +355,14 @@ export function parseApiCliArgs(args: readonly string[]): ApiCliArgs { case "--password": parsed.password = expectValue(args, ++index, arg, apiCommand.options); break; + case "--password-file": + parsed.passwordFile = expectValue( + args, + ++index, + arg, + apiCommand.options, + ); + break; case "--insecure": parsed.insecure = true; break; @@ -357,6 +377,14 @@ export function parseApiCliArgs(args: readonly string[]): ApiCliArgs { apiCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + arg, + apiCommand.options, + ); + break; case "--match": parsed.match = expectValue(args, ++index, arg, apiCommand.options); break; diff --git a/src/cli/btest.ts b/src/cli/btest.ts index dbe6f09f..4f8c68d0 100644 --- a/src/cli/btest.ts +++ b/src/cli/btest.ts @@ -133,6 +133,12 @@ export const btestCommand: CliCommandMetadata = { valueName: "", description: "Credential (falls back to CDB / CENTRS_PASSWORD).", }, + { + flag: "--password-file", + valueName: "", + description: + "Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`.", + }, { flag: "--port", valueName: "", @@ -148,6 +154,12 @@ export const btestCommand: CliCommandMetadata = { valueName: "", description: "(client) Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -316,6 +328,14 @@ export function parseClientArgs(args: readonly string[]): ClientCliArgs { case "--password": request.password = expectValue(args, ++i, arg, btestCommand.options); break; + case "--password-file": + request.passwordFile = expectValue( + args, + ++i, + arg, + btestCommand.options, + ); + break; case "--port": request.controlPort = parseIntFlag( expectValue(args, ++i, arg, btestCommand.options), @@ -328,6 +348,14 @@ export function parseClientArgs(args: readonly string[]): ClientCliArgs { case "--cdb-password": request.cdbPassword = expectValue(args, ++i, arg, btestCommand.options); break; + case "--cdb-password-file": + request.cdbPasswordFile = expectValue( + args, + ++i, + arg, + btestCommand.options, + ); + break; case "--match": request.match = expectValue(args, ++i, arg, btestCommand.options); break; @@ -406,6 +434,14 @@ export function parseServerArgs(args: readonly string[]): ServerCliArgs { case "--password": request.password = expectValue(args, ++i, arg, btestCommand.options); break; + case "--password-file": + request.passwordFile = expectValue( + args, + ++i, + arg, + btestCommand.options, + ); + break; case "--port": request.port = parseIntFlag( expectValue(args, ++i, arg, btestCommand.options), diff --git a/src/cli/devices.ts b/src/cli/devices.ts index baae2784..9147d2ab 100644 --- a/src/cli/devices.ts +++ b/src/cli/devices.ts @@ -4,6 +4,10 @@ * unchanged from the former monolithic `cli.ts`. */ +import { + decodePasswordBytes, + passwordBytesReason, +} from "../core/password-bytes.ts"; import { asCentrsError, CentrsError, @@ -18,6 +22,7 @@ import { type DevicesCommand, type DevicesEnvelope, type DevicesOutputFormat, + type DevicesSettings, type DevicesWhereClause, describeCentrs, devicesOutputFormats, @@ -40,6 +45,7 @@ import { showDevice, winBoxCdbRecordType, } from "../index.ts"; +import { CDB_PASSWORD_SECRET } from "../resolver/secret-source.ts"; import { type CliCommandMetadata, expandEqualsArgs, @@ -57,10 +63,18 @@ import { */ const CDB_FILE_FLAGS: Readonly> = { - init: ["--cdb-file", "--cdb-password", "--format", "--json", "--encrypt"], + init: [ + "--cdb-file", + "--cdb-password", + "--cdb-password-file", + "--format", + "--json", + "--encrypt", + ], encrypt: [ "--cdb-file", "--cdb-password", + "--cdb-password-file", "--format", "--json", "--no-backup", @@ -96,6 +110,12 @@ const devicesMetadata: CliCommandMetadata = { description: "CDB password for encrypted reads, writes, explicit encrypted initialization and conversion. Falls back to `CENTRS_CDB_PASSWORD`; a password alone never converts an open CDB.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--via", valueName: "", @@ -284,6 +304,7 @@ interface DevicesCliArgs { subcommand?: DevicesSubcommand; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; encrypt?: boolean; noBackup?: boolean; group?: string; @@ -374,6 +395,14 @@ export function parseDevicesCliArgs(args: readonly string[]): DevicesCliArgs { devicesCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + arg, + devicesCommand.options, + ); + break; case "--group": parsed.group = expectValue(args, ++index, arg, devicesCommand.options); break; @@ -819,13 +848,6 @@ export interface PasswordStdinSource { read?: () => Promise; } -// `fatal` rejects malformed UTF-8 instead of substituting U+FFFD; `ignoreBOM` -// keeps a leading U+FEFF visible so it can be refused rather than dropped. -const stdinPasswordDecoder = new TextDecoder("utf-8", { - fatal: true, - ignoreBOM: true, -}); - /** * Read a record password for `devices add`/`set --password-stdin` (#582). * @@ -853,14 +875,9 @@ export async function readPasswordStdin( }); } const raw = await (source.read ?? (() => Bun.stdin.bytes()))(); - const end = raw.length; - const trimmed = - end >= 2 && raw[end - 2] === 0x0d && raw[end - 1] === 0x0a - ? raw.subarray(0, end - 2) - : end >= 1 && raw[end - 1] === 0x0a - ? raw.subarray(0, end - 1) - : raw; - if (trimmed.length === 0) { + const decoded = decodePasswordBytes(raw); + if (decoded.ok) return decoded.value; + if (decoded.reason === "empty") { throw new CentrsError({ code: "input/empty-stdin", summary: "`--password-stdin` received an empty password on stdin.", @@ -869,24 +886,13 @@ export async function readPasswordStdin( context: { flag: "--password-stdin" }, }); } - const invalid = (reason: string) => - new CentrsError({ - code: "input/invalid-stdin", - summary: `\`--password-stdin\` received ${reason}.`, - remediation: - "Pipe the password as UTF-8 text with no byte-order mark (e.g. `printf '%s' \"$PW\" | centrs devices set --password-stdin`). Re-save a file written by an editor as UTF-8 without BOM.", - context: { flag: "--password-stdin", byteLength: trimmed.length }, - }); - let value: string; - try { - value = stdinPasswordDecoder.decode(trimmed); - } catch { - throw invalid("bytes that are not valid UTF-8"); - } - if (value.startsWith("\uFEFF")) { - throw invalid("a leading byte-order mark (U+FEFF)"); - } - return value; + throw new CentrsError({ + code: "input/invalid-stdin", + summary: `\`--password-stdin\` received ${passwordBytesReason(decoded.reason)}.`, + remediation: + "Pipe the password as UTF-8 text with no byte-order mark (e.g. `printf '%s' \"$PW\" | centrs devices set --password-stdin`). Re-save a file written by an editor as UTF-8 without BOM.", + context: { flag: "--password-stdin", byteLength: decoded.byteLength }, + }); } /** Run a devices subcommand, replaying eligible mutations after CDB conflicts. */ @@ -915,6 +921,7 @@ export async function runDevicesCli(args: readonly string[]): Promise { const options = { cdbFile: parsed.cdbFile, cdbPassword: parsed.cdbPassword, + cdbPasswordFile: parsed.cdbPasswordFile, env: envSnapshot, }; const envelope = @@ -927,6 +934,7 @@ export async function runDevicesCli(args: readonly string[]): Promise { const loadOptions = { cdbFile: parsed.cdbFile, cdbPassword: parsed.cdbPassword, + cdbPasswordFile: parsed.cdbPasswordFile, env: envSnapshot, }; const reload = () => loadCdb(loadOptions); @@ -1049,11 +1057,12 @@ export async function runDevicesCli(args: readonly string[]): Promise { } catch (error) { const format = parsed?.format ?? inferDevicesFormat(args); const subcommand: DevicesCommand = parsed?.subcommand ?? "list"; - const settings = resolveDevicesSettings({ - cdbFile: parsed?.cdbFile, - cdbPassword: parsed?.cdbPassword, - env: envSnapshot ?? Bun.env, - }); + const settings = errorEnvelopeSettings( + parsed?.cdbFile, + parsed?.cdbPassword, + parsed?.cdbPasswordFile, + envSnapshot ?? Bun.env, + ); const centrsError = asCentrsError(error, { code: "input/invalid-command", summary: error instanceof Error ? error.message : String(error), @@ -1075,6 +1084,34 @@ export async function runDevicesCli(args: readonly string[]): Promise { } } +/** + * The settings an error envelope reports. Choosing the key source can throw + * (value and file together), and the error being reported may be exactly + * that, so a second failure falls back to the settings without a key source. + */ +function errorEnvelopeSettings( + cdbFile: string | undefined, + cdbPassword: string | undefined, + cdbPasswordFile: string | undefined, + env: Record, +): DevicesSettings { + try { + return resolveDevicesSettings({ + cdbFile, + cdbPassword, + cdbPasswordFile, + env, + }); + } catch { + const { + [CDB_PASSWORD_SECRET.envKey]: _value, + [CDB_PASSWORD_SECRET.fileEnvKey]: _file, + ...rest + } = env; + return resolveDevicesSettings({ cdbFile, env: rest }); + } +} + function inferDevicesFormat(args: readonly string[]): DevicesOutputFormat { return inferCliFormat( args, diff --git a/src/cli/discover.ts b/src/cli/discover.ts index 11126869..27037632 100644 --- a/src/cli/discover.ts +++ b/src/cli/discover.ts @@ -63,6 +63,12 @@ export const discoverCommand: CliCommandMetadata = { description: "`--save` password for an encrypted CDB. Used to decrypt the existing CDB and re-encrypt on write.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--format", valueName: `<${discoverOutputFormats.join("|")}>`, @@ -83,6 +89,7 @@ interface DiscoverCliArgs { port?: number; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; format?: DiscoverOutputFormat; } @@ -138,6 +145,14 @@ export function parseDiscoverCliArgs(args: readonly string[]): DiscoverCliArgs { discoverCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + arg, + discoverCommand.options, + ); + break; case "--format": { const value = expectValue(args, ++index, arg, discoverCommand.options); if (!discoverOutputFormats.includes(value as DiscoverOutputFormat)) { @@ -202,6 +217,7 @@ export async function runDiscoverCli(args: readonly string[]): Promise { port: parsed.port, cdbFile: parsed.cdbFile, cdbPassword: parsed.cdbPassword, + cdbPasswordFile: parsed.cdbPasswordFile, env: Bun.env, }; emitDiscoverProgress(options, parsed.format); diff --git a/src/cli/execute.ts b/src/cli/execute.ts index 9f9b65fd..57425204 100644 --- a/src/cli/execute.ts +++ b/src/cli/execute.ts @@ -103,6 +103,12 @@ export const executeCommand: CliCommandMetadata = { valueName: "", description: "RouterOS password. Falls back to `CENTRS_PASSWORD`.", }, + { + flag: "--password-file", + valueName: "", + description: + "Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`.", + }, { flag: "--ssh-key", valueName: "", @@ -124,6 +130,12 @@ export const executeCommand: CliCommandMetadata = { valueName: "", description: "Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -276,6 +288,14 @@ export function parseExecuteCliArgs(args: readonly string[]): ExecuteCliArgs { executeCommand.options, ); break; + case "--password-file": + parsed.passwordFile = expectValue( + args, + ++index, + arg, + executeCommand.options, + ); + break; case "--ssh-key": parsed.sshKey = expectValue(args, ++index, arg, executeCommand.options); break; @@ -298,6 +318,14 @@ export function parseExecuteCliArgs(args: readonly string[]): ExecuteCliArgs { executeCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + arg, + executeCommand.options, + ); + break; case "--match": parsed.match = expectValue(args, ++index, arg, executeCommand.options); break; diff --git a/src/cli/explain.ts b/src/cli/explain.ts index 089137c4..ccdcdd82 100644 --- a/src/cli/explain.ts +++ b/src/cli/explain.ts @@ -80,10 +80,12 @@ export const explainCliCommand: CliCommandMetadata = { "--port", "--username / --user / -u", "--password", + "--password-file", "--timeout", "--insecure", "--cdb-file", "--cdb-password", + "--cdb-password-file", "--resolve", ].includes(o.flag), ), @@ -239,6 +241,14 @@ export function parseExplainCliArgs(args: readonly string[]): ExplainCliArgs { explainCliCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + arg, + explainCliCommand.options, + ); + break; case "--resolve": parsed.resolve = expectValue( args, @@ -255,6 +265,14 @@ export function parseExplainCliArgs(args: readonly string[]): ExplainCliArgs { explainCliCommand.options, ); break; + case "--password-file": + parsed.passwordFile = expectValue( + args, + ++index, + arg, + explainCliCommand.options, + ); + break; case "-p": parsed.password = expectValue( args, @@ -559,11 +577,13 @@ const LIVE_CONNECTION_FLAGS = new Set([ "--user", "-u", "--password", + "--password-file", "-p", "--timeout", "--insecure", "--cdb-file", "--cdb-password", + "--cdb-password-file", "--resolve", ]); diff --git a/src/cli/mcp.ts b/src/cli/mcp.ts index bd6154f7..1491dbcd 100644 --- a/src/cli/mcp.ts +++ b/src/cli/mcp.ts @@ -39,6 +39,12 @@ export const mcpCommand: CliCommandMetadata = { description: "Decrypt password for an encrypted CDB (or CENTRS_CDB_PASSWORD).", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--allow-adhoc-targets", description: @@ -52,6 +58,7 @@ interface McpCliArgs { help?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; allowAdhocTargets?: boolean; } @@ -90,6 +97,14 @@ export function parseMcpCliArgs(args: readonly string[]): McpCliArgs { mcpCommand.options, ); break; + case "--cdb-password-file": + parsed.cdbPasswordFile = expectValue( + args, + ++index, + "--cdb-password-file", + mcpCommand.options, + ); + break; case "--allow-adhoc-targets": parsed.allowAdhocTargets = true; break; @@ -110,6 +125,7 @@ export async function runMcpCli(args: readonly string[]): Promise { const config = resolveMcpConfig({ cdbFile: parsed.cdbFile, cdbPassword: parsed.cdbPassword, + cdbPasswordFile: parsed.cdbPasswordFile, allowAdhocTargets: parsed.allowAdhocTargets, config: await loadEnvFileDefaults(), }); diff --git a/src/cli/retrieve.ts b/src/cli/retrieve.ts index f794ab66..3ed05795 100644 --- a/src/cli/retrieve.ts +++ b/src/cli/retrieve.ts @@ -99,6 +99,12 @@ export const retrieveCommand: CliCommandMetadata = { valueName: "", description: "RouterOS password. Falls back to `CENTRS_PASSWORD`.", }, + { + flag: "--password-file", + valueName: "", + description: + "Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`.", + }, { flag: "--timeout", valueName: "", @@ -202,6 +208,12 @@ export const retrieveCommand: CliCommandMetadata = { valueName: "", description: "Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -515,6 +527,14 @@ export function parseRetrieveCliArgs(args: readonly string[]): RetrieveCliArgs { retrieveCommand.options, ); break; + case "--password-file": + request.passwordFile = expectValue( + args, + ++index, + arg, + retrieveCommand.options, + ); + break; case "--timeout": request.timeout = expectValue( args, @@ -584,6 +604,14 @@ export function parseRetrieveCliArgs(args: readonly string[]): RetrieveCliArgs { retrieveCommand.options, ); break; + case "--cdb-password-file": + request.cdbPasswordFile = expectValue( + args, + ++index, + arg, + retrieveCommand.options, + ); + break; case "--match": request.match = expectValue( args, diff --git a/src/cli/settings.ts b/src/cli/settings.ts index d6ad3c38..d70f9586 100644 --- a/src/cli/settings.ts +++ b/src/cli/settings.ts @@ -57,6 +57,12 @@ export const settingsCommand: CliCommandMetadata = { valueName: "", description: "`print` only — decrypt password for the probed CDB.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--skip-env-file", description: @@ -82,6 +88,7 @@ interface SettingsCliArgs { all?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; skipEnvFile?: boolean; format?: SettingsOutputFormat; } @@ -96,6 +103,7 @@ export function parseSettingsCliArgs(args: readonly string[]): SettingsCliArgs { let all = false; let cdbFile: string | undefined; let cdbPassword: string | undefined; + let cdbPasswordFile: string | undefined; let skipEnvFile = false; let format: SettingsOutputFormat | undefined; @@ -118,6 +126,14 @@ export function parseSettingsCliArgs(args: readonly string[]): SettingsCliArgs { case "--cdb-password": cdbPassword = expectValue(args, ++index, arg, settingsCommand.options); break; + case "--cdb-password-file": + cdbPasswordFile = expectValue( + args, + ++index, + arg, + settingsCommand.options, + ); + break; case "--skip-env-file": skipEnvFile = true; break; @@ -152,6 +168,7 @@ export function parseSettingsCliArgs(args: readonly string[]): SettingsCliArgs { all, cdbFile, cdbPassword, + cdbPasswordFile, skipEnvFile, format, }; @@ -230,6 +247,7 @@ export async function runSettingsCli(args: readonly string[]): Promise { skipEnvFile: parsed.skipEnvFile, cdbFile: parsed.cdbFile, cdbPassword: parsed.cdbPassword, + cdbPasswordFile: parsed.cdbPasswordFile, }); break; case "get": diff --git a/src/cli/terminal.ts b/src/cli/terminal.ts index ab974c51..5de47776 100644 --- a/src/cli/terminal.ts +++ b/src/cli/terminal.ts @@ -77,7 +77,14 @@ export const terminalCommand: CliCommandMetadata = { { flag: "--password", valueName: "", - description: "RouterOS password. Falls back to CENTRS_PASSWORD.", + description: + "mac-telnet: RouterOS password. Falls back to CENTRS_PASSWORD. Interactive ssh ignores it; OpenSSH prompts itself.", + }, + { + flag: "--password-file", + valueName: "", + description: + "mac-telnet: read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`. Interactive ssh never reads it.", }, { flag: "--source-mac", @@ -106,6 +113,12 @@ export const terminalCommand: CliCommandMetadata = { valueName: "", description: "Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -278,6 +291,14 @@ export function parseTerminalCliArgs(args: readonly string[]): ParsedTerminal { terminalCommand.options, ); break; + case "--password-file": + flags.passwordFile = expectValue( + args, + ++index, + arg, + terminalCommand.options, + ); + break; case "--source-mac": flags.sourceMac = expectValue( args, @@ -308,6 +329,14 @@ export function parseTerminalCliArgs(args: readonly string[]): ParsedTerminal { terminalCommand.options, ); break; + case "--cdb-password-file": + flags.cdbPasswordFile = expectValue( + args, + ++index, + arg, + terminalCommand.options, + ); + break; case "--match": flags.match = expectValue(args, ++index, arg, terminalCommand.options); break; diff --git a/src/cli/transfer.ts b/src/cli/transfer.ts index 2daa82c5..2f08eb09 100644 --- a/src/cli/transfer.ts +++ b/src/cli/transfer.ts @@ -149,6 +149,12 @@ export const transferCommand: CliCommandMetadata = { valueName: "", description: "RouterOS password. Falls back to CENTRS_PASSWORD.", }, + { + flag: "--password-file", + valueName: "", + description: + "Read the RouterOS password from a file (one trailing newline ignored). Falls back to `CENTRS_PASSWORD_FILE`; outranks CDB records like `--password`. Conflicts with `--password`.", + }, { flag: "--timeout", valueName: "", @@ -172,6 +178,12 @@ export const transferCommand: CliCommandMetadata = { valueName: "", description: "Decrypt an encrypted WinBox CDB file.", }, + { + flag: "--cdb-password-file", + valueName: "", + description: + "Read the CDB password from a file (one trailing newline ignored), e.g. a container secret under /run/secrets. Read on each CDB load; falls back to `CENTRS_CDB_PASSWORD_FILE`. Conflicts with `--cdb-password`.", + }, { flag: "--match", valueName: "", @@ -410,6 +422,14 @@ export function parseTransferCliArgs( transferCommand.options, ); break; + case "--password-file": + flags.passwordFile = expectValue( + args, + ++index, + arg, + transferCommand.options, + ); + break; case "--ssh-key": flags.sshKey = expectValue(args, ++index, arg, transferCommand.options); break; @@ -472,6 +492,14 @@ export function parseTransferCliArgs( transferCommand.options, ); break; + case "--cdb-password-file": + flags.cdbPasswordFile = expectValue( + args, + ++index, + arg, + transferCommand.options, + ); + break; case "--match": flags.match = expectValue(args, ++index, arg, transferCommand.options); break; diff --git a/src/core/envelope.ts b/src/core/envelope.ts index b2433482..e199481c 100644 --- a/src/core/envelope.ts +++ b/src/core/envelope.ts @@ -44,7 +44,9 @@ export type SettingSourceKind = | "cli" | "cdb" | "arp" - | "provider"; + | "provider" + /** A secret read from a file named by a flag or env key (`key`). */ + | "file"; export interface SettingSource { kind: SettingSourceKind; diff --git a/src/core/error-catalog.ts b/src/core/error-catalog.ts index 0e201a07..72bc9933 100644 --- a/src/core/error-catalog.ts +++ b/src/core/error-catalog.ts @@ -39,6 +39,11 @@ export const errorCatalog: readonly ErrorCatalogEntry[] = [ summary: "Batch SSH authentication failed (execute --via ssh, sftp transfer).", }, + { + code: "auth/password-unavailable", + summary: + "The password file named by --password-file or CENTRS_PASSWORD_FILE is missing, unreadable, empty or not UTF-8.", + }, // cdb/* { @@ -128,6 +133,11 @@ export const errorCatalog: readonly ErrorCatalogEntry[] = [ summary: "A CDB password was given for an unencrypted CDB and was ignored (warning).", }, + { + code: "cdb/password-unavailable", + summary: + "The CDB password file named by --cdb-password-file or CENTRS_CDB_PASSWORD_FILE is missing, unreadable, empty or not UTF-8, and the CDB needed its key.", + }, { code: "cdb/password-required", summary: @@ -555,6 +565,11 @@ export const errorCatalog: readonly ErrorCatalogEntry[] = [ summary: "`settings set` accepted a syntactically valid value with a real, non-obvious consequence (e.g. a global --insecure default, or a transfer-via value gated elsewhere).", }, + { + code: "settings/dotenv-ignored", + summary: + "CENTRS_* keys that Bun loaded from the working directory's .env were ignored (warning, on stderr).", + }, { code: "settings/invalid-boolean", summary: "A boolean-like setting received a non-boolean value.", diff --git a/src/core/password-bytes.ts b/src/core/password-bytes.ts new file mode 100644 index 00000000..99beeb52 --- /dev/null +++ b/src/core/password-bytes.ts @@ -0,0 +1,56 @@ +/** + * The one rule for turning piped or file bytes into a password, shared by + * `devices add|set --password-stdin` (#582) and the `*_FILE` secret sources + * (#672) so the two cannot drift. + * + * Exactly one trailing `\n` or `\r\n` is stripped (at the byte level), so + * `echo pw > file` works; any other whitespace is part of the password. The + * rest must be valid UTF-8 without a leading byte-order mark: the CDB stores + * strings as UTF-8 and drops a leading BOM when it reads them back, so either + * would silently become a credential different from the bytes given. + */ + +export type PasswordBytesResult = + | { ok: true; value: string } + | { ok: false; reason: "empty" | "invalid-utf8" | "bom"; byteLength: number }; + +// `fatal` rejects malformed UTF-8 instead of substituting U+FFFD; `ignoreBOM` +// keeps a leading U+FEFF visible so it can be refused rather than dropped. +const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + +export function decodePasswordBytes(raw: Uint8Array): PasswordBytesResult { + const end = raw.length; + const trimmed = + end >= 2 && raw[end - 2] === 0x0d && raw[end - 1] === 0x0a + ? raw.subarray(0, end - 2) + : end >= 1 && raw[end - 1] === 0x0a + ? raw.subarray(0, end - 1) + : raw; + if (trimmed.length === 0) { + return { ok: false, reason: "empty", byteLength: 0 }; + } + let value: string; + try { + value = decoder.decode(trimmed); + } catch { + return { ok: false, reason: "invalid-utf8", byteLength: trimmed.length }; + } + if (value.startsWith("")) { + return { ok: false, reason: "bom", byteLength: trimmed.length }; + } + return { ok: true, value }; +} + +/** Human wording for a refused {@link PasswordBytesResult} reason. */ +export function passwordBytesReason( + reason: "empty" | "invalid-utf8" | "bom", +): string { + switch (reason) { + case "empty": + return "an empty password"; + case "invalid-utf8": + return "bytes that are not valid UTF-8"; + case "bom": + return "a leading byte-order mark (U+FEFF)"; + } +} diff --git a/src/devices.ts b/src/devices.ts index 1fe43d5c..28a993fa 100644 --- a/src/devices.ts +++ b/src/devices.ts @@ -67,12 +67,27 @@ import { parseLatLon, } from "./resolver/geo.ts"; import { normalizeMac } from "./resolver/mac.ts"; +import { + CDB_PASSWORD_SECRET, + chooseSecret, + readSecretFile, + secretFileExists, +} from "./resolver/secret-source.ts"; export type { SettingSource, SettingSourceKind }; export interface DevicesSettings { cdbFile: { value: string; source: SettingSource }; - cdbPassword: { value: string; source: SettingSource; provided: boolean }; + cdbPassword: { + value: string; + source: SettingSource; + provided: boolean; + /** + * The file the password comes from (#672). `value` stays `""` until a + * load that needs the key reads it (`readCdbPasswordFile`). + */ + file?: string; + }; } export interface DevicesWarning { @@ -170,6 +185,11 @@ function devicesMeta( export interface LoadCdbOptions { cdbFile?: string; cdbPassword?: string; + /** + * `--cdb-password-file`: a file holding the CDB password, read on each load + * that needs it. Conflicts with `cdbPassword` (#672). + */ + cdbPasswordFile?: string; env?: Record; /** * The `centrs.env` config tier (`src/resolver/config-file.ts`). Only @@ -197,7 +217,6 @@ export interface LoadedCdb { const DEFAULT_CDB_RELATIVE = ".config/tikoci/winbox.cdb"; const ENV_HOME = "HOME"; const ENV_CDB_FILE = "CENTRS_CDB_FILE"; -const ENV_CDB_PASSWORD = "CENTRS_CDB_PASSWORD"; export function defaultCdbPath( env?: Record, @@ -227,27 +246,59 @@ export function resolveDevicesSettings( cdbFileSource = { kind: "cli", key: "--cdb-file" }; } - let cdbPassword = ""; - let provided = false; - let cdbPasswordSource: SettingSource = { kind: "default", key: "default" }; - const envCdbPassword = env[ENV_CDB_PASSWORD]; - if (envCdbPassword !== undefined) { - cdbPassword = envCdbPassword; - provided = true; - cdbPasswordSource = { kind: "env", key: ENV_CDB_PASSWORD }; - } - if (options.cdbPassword !== undefined) { - cdbPassword = options.cdbPassword; - provided = true; - cdbPasswordSource = { kind: "cli", key: "--cdb-password" }; - } + const choice = chooseSecret( + CDB_PASSWORD_SECRET, + { value: options.cdbPassword, file: options.cdbPasswordFile }, + env, + ); + const cdbPassword: DevicesSettings["cdbPassword"] = + choice === undefined + ? { + value: "", + source: { kind: "default", key: "default" }, + provided: false, + } + : choice.kind === "value" + ? { value: choice.value, source: choice.source, provided: true } + : { + value: "", + source: choice.source, + provided: true, + file: choice.path, + }; return { cdbFile: { value: cdbFile, source: cdbFileSource }, - cdbPassword: { value: cdbPassword, source: cdbPasswordSource, provided }, + cdbPassword, }; } +/** + * Fill `cdbPassword.value` from its file when the source is a file (#672). + * Called only where the key is needed, so a rotated or deleted file takes + * effect at the next load. Throws `cdb/password-unavailable`. + */ +export function readCdbPasswordFile( + settings: DevicesSettings, +): DevicesSettings { + const { file } = settings.cdbPassword; + if (file === undefined) return settings; + const value = readSecretFile(CDB_PASSWORD_SECRET, { + kind: "file", + path: file, + source: settings.cdbPassword.source, + }); + return { ...settings, cdbPassword: { ...settings.cdbPassword, value } }; +} + +/** Where the CDB password came from, for messages: a flag, env key or file. */ +function cdbPasswordWhere(settings: DevicesSettings): string { + return settings.cdbPassword.source.key ?? "--cdb-password"; +} + +const CDB_PASSWORD_SOURCES = + "--cdb-password, --cdb-password-file, CENTRS_CDB_PASSWORD or CENTRS_CDB_PASSWORD_FILE"; + function isAlreadyExistsError(cause: unknown): boolean { return ( typeof cause === "object" && @@ -323,9 +374,11 @@ export interface InitCdbOptions extends LoadCdbOptions { export async function initCdb( options: InitCdbOptions, ): Promise> { - const settings = resolveDevicesSettings(options); + const resolved = resolveDevicesSettings(options); + const settings = options.encrypt + ? requireEncryptionPassword(resolved) + : resolved; const cdbFile = settings.cdbFile.value; - if (options.encrypt) requireEncryptionPassword(settings); const existingResult = async () => { const existing = await loadCdb(options); if (options.encrypt && !existing.encrypted) { @@ -388,24 +441,33 @@ export async function initCdb( encrypted: options.encrypt === true, recordCount: 0, }, - warnings: [], + // A key given to a plain `init` is unused, as on an open-CDB load. + warnings: + !options.encrypt && settings.cdbPassword.provided + ? [cdbPasswordNotNeeded(settings)] + : [], tips: [], meta: devicesMeta("init", settings), }; } -function requireEncryptionPassword(settings: DevicesSettings): void { - if ( - !settings.cdbPassword.provided || - settings.cdbPassword.value.length === 0 - ) { +function requireEncryptionPassword(unread: DevicesSettings): DevicesSettings { + if (!unread.cdbPassword.provided) { throw new CentrsError({ code: "cdb/password-required", summary: "CDB encryption requires a non-empty password.", - remediation: - "Pass --cdb-password or set CENTRS_CDB_PASSWORD to a non-empty CDB password.", + remediation: `Give a non-empty CDB password with one of ${CDB_PASSWORD_SOURCES}.`, }); } + const settings = readCdbPasswordFile(unread); + if (settings.cdbPassword.value.length === 0) { + throw new CentrsError({ + code: "cdb/password-required", + summary: "CDB encryption requires a non-empty password.", + remediation: `Give a non-empty CDB password with one of ${CDB_PASSWORD_SOURCES}.`, + }); + } + return settings; } export interface EncryptCdbOptions extends LoadCdbOptions { @@ -440,8 +502,7 @@ export interface DevicesEncryptData { export async function encryptCdb( options: EncryptCdbOptions, ): Promise> { - const settings = resolveDevicesSettings(options); - requireEncryptionPassword(settings); + const settings = requireEncryptionPassword(resolveDevicesSettings(options)); const cdbFile = settings.cdbFile.value; // Pin even the default path so conversion never implicitly creates a file. const cdb = await loadCdb({ ...options, cdbFile }); @@ -497,8 +558,32 @@ export async function encryptCdb( }; } +/** + * The open-CDB warning for a configured but unneeded password. A file source + * is not read; the message says whether it exists, so a missing secret mount + * is visible without failing work that needs no key (#672). + */ +function cdbPasswordNotNeeded(settings: DevicesSettings): DevicesWarning { + const { file } = settings.cdbPassword; + const where = cdbPasswordWhere(settings); + if (file === undefined) { + return { + code: "cdb/password-not-needed", + message: `A CDB password was given (${where}) but the CDB is not encrypted; the password was ignored.`, + }; + } + const exists = secretFileExists(file); + return { + code: "cdb/password-not-needed", + message: exists + ? `${where} names ${file}, but the CDB is not encrypted; the file was not read.` + : `${where} names ${file}, which does not exist; the CDB is not encrypted, so no key was needed.`, + context: { source: where, path: file, exists }, + }; +} + export async function loadCdb(options: LoadCdbOptions): Promise { - const settings = resolveDevicesSettings(options); + let settings = resolveDevicesSettings(options); const warnings: DevicesWarning[] = []; const file = Bun.file(settings.cdbFile.value); @@ -564,23 +649,19 @@ export async function loadCdb(options: LoadCdbOptions): Promise { let openBytes: Uint8Array; if (parsed.mode === "open") { if (settings.cdbPassword.provided) { - warnings.push({ - code: "cdb/password-not-needed", - message: - "--cdb-password was provided but the CDB is not encrypted; the password was ignored.", - }); + warnings.push(cdbPasswordNotNeeded(settings)); } openBytes = bytes; } else { if (!settings.cdbPassword.provided) { throw new CentrsError({ code: "cdb/password-required", - summary: "CDB is encrypted; --cdb-password is required.", - remediation: - "Pass --cdb-password or set CENTRS_CDB_PASSWORD to the CDB password.", + summary: "CDB is encrypted; a CDB password is required.", + remediation: `Give the CDB password with one of ${CDB_PASSWORD_SOURCES}.`, context: { cdbFile: settings.cdbFile.value }, }); } + settings = readCdbPasswordFile(settings); try { openBytes = decryptCdb(parsed, settings.cdbPassword.value); } catch (cause) { @@ -589,8 +670,7 @@ export async function loadCdb(options: LoadCdbOptions): Promise { code: "cdb/decrypt-failed", summary: "CDB decryption produced an invalid open-CDB magic; the password is likely wrong.", - remediation: - "Re-check --cdb-password or CENTRS_CDB_PASSWORD against the value used when the CDB was saved.", + remediation: `Re-check the CDB password from ${cdbPasswordWhere(settings)} against the value used when the CDB was saved.`, context: { cdbFile: settings.cdbFile.value }, cause, causeData: { reason: "open-magic-mismatch" }, @@ -602,8 +682,7 @@ export async function loadCdb(options: LoadCdbOptions): Promise { cause instanceof Error ? cause.message : "Failed to decrypt CDB file.", - remediation: - "Verify --cdb-password is correct and the file is a WinBox-encrypted CDB.", + remediation: `Verify the CDB password from ${cdbPasswordWhere(settings)} is correct and the file is a WinBox-encrypted CDB.`, context: { cdbFile: settings.cdbFile.value }, cause, }); diff --git a/src/discover.ts b/src/discover.ts index f23f8789..cc015cd9 100644 --- a/src/discover.ts +++ b/src/discover.ts @@ -18,7 +18,12 @@ */ import { createSocket } from "node:dgram"; -import type { CentrsEnvelope, EnvelopeMeta, Tip } from "./core/envelope.ts"; +import type { + CentrsEnvelope, + EnvelopeMeta, + SettingSource, + Tip, +} from "./core/envelope.ts"; import { buildTip } from "./core/envelope.ts"; import { MNDP_BROADCAST_ADDRESS, @@ -643,6 +648,7 @@ export interface DiscoverOptions { cdbFile?: string; /** CDB password for `--save` against an encrypted CDB. */ cdbPassword?: string; + cdbPasswordFile?: string; /** Environment snapshot for CDB resolution. */ env?: Record; /** Clock injection for the cache and provenance timestamps. */ @@ -663,18 +669,28 @@ function discoverMeta( operation: DiscoverOperationMeta, options: DiscoverOptions, ): EnvelopeMeta { - const settings = resolveDevicesSettings({ - cdbFile: options.cdbFile, - cdbPassword: options.cdbPassword, - env: options.env ?? {}, - }); + // Error envelopes call this too, so it must not throw: an unresolvable CDB + // source (a value/file conflict, #672) leaves the CDB settings out, and the + // error itself says why. + let cdbSettings: Record = {}; + try { + const settings = resolveDevicesSettings({ + cdbFile: options.cdbFile, + cdbPassword: options.cdbPassword, + cdbPasswordFile: options.cdbPasswordFile, + env: options.env ?? {}, + }); + cdbSettings = { + cdbFile: settings.cdbFile.source, + cdbPassword: settings.cdbPassword.source, + }; + } catch {} return { target: {}, via: "mndp", settings: { timeoutMs: { kind: options.timeoutMs !== undefined ? "cli" : "default" }, - cdbFile: settings.cdbFile.source, - cdbPassword: settings.cdbPassword.source, + ...cdbSettings, }, operation, }; @@ -695,6 +711,16 @@ export async function discover( let result: ListenMndpResult; try { + // A `--save` run checks its CDB key sources before listening, so a + // value/file conflict fails fast instead of after the listen window. + if (options.save) { + resolveDevicesSettings({ + cdbFile: options.cdbFile, + cdbPassword: options.cdbPassword, + cdbPasswordFile: options.cdbPasswordFile, + env: options.env ?? {}, + }); + } result = await listen({ timeoutMs, port: options.port, @@ -729,6 +755,7 @@ export async function discover( loadOptions: { cdbFile: options.cdbFile, cdbPassword: options.cdbPassword, + cdbPasswordFile: options.cdbPasswordFile, env: options.env, }, neighbors: entries.map((entry) => entry.neighbor), diff --git a/src/execute-fanout.ts b/src/execute-fanout.ts index b7054e07..15d623c2 100644 --- a/src/execute-fanout.ts +++ b/src/execute-fanout.ts @@ -221,6 +221,7 @@ export async function executeFanout( { cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, allowAdhoc: options.allowAdhoc ?? true, }, env, diff --git a/src/execute.ts b/src/execute.ts index 77eb1e7d..13228ecc 100644 --- a/src/execute.ts +++ b/src/execute.ts @@ -109,6 +109,8 @@ export interface ExecuteRequest { port?: number; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; /** SSH private-key path for `--via ssh` (path only; agent / ~/.ssh used if unset). */ sshKey?: string; /** @@ -126,6 +128,7 @@ export interface ExecuteRequest { maxResultsBytes?: number; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -379,6 +382,7 @@ export async function resolveExecuteRequest( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, @@ -449,7 +453,10 @@ export async function resolveExecuteRequest( { username: request.username, password: request.password, + passwordFile: request.passwordFile, sshKey: request.sshKey, + // Batch ssh (`BatchMode=yes`) sends no password (PR #674). + sendsNoPassword: via.value === "ssh", }, env, cdbResolution, diff --git a/src/explain-live.ts b/src/explain-live.ts index c53a2eb5..42ecd78e 100644 --- a/src/explain-live.ts +++ b/src/explain-live.ts @@ -52,10 +52,12 @@ export interface ExplainLiveRequest | "port" | "username" | "password" + | "passwordFile" | "insecure" | "timeout" | "cdbFile" | "cdbPassword" + | "cdbPasswordFile" | "resolve" >, ExplainLiveFacets { diff --git a/src/mcp.ts b/src/mcp.ts index 39e21a96..ec6d13ac 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -29,5 +29,7 @@ export async function runMcp( } if (import.meta.main) { - process.exitCode = await runMcp(); + // #666, as in `src/cli.ts`: never run with the working directory's `.env`. + const { runWithoutDotenv } = await import("./resolver/dotenv-guard.ts"); + process.exitCode = await runWithoutDotenv(() => runMcp()); } diff --git a/src/mcp/config.ts b/src/mcp/config.ts index bab3df1f..c571352f 100644 --- a/src/mcp/config.ts +++ b/src/mcp/config.ts @@ -9,6 +9,10 @@ */ import { defaultCdbPath } from "../devices.ts"; +import { + CDB_PASSWORD_SECRET, + chooseSecret, +} from "../resolver/secret-source.ts"; /** * Reserved CDB record name (future work, not yet honored) that will supply @@ -23,7 +27,6 @@ export const DEFAULT_DEVICE_NAME = "__default__"; export const ENV_ALLOW_ADHOC = "CENTRS_MCP_ALLOW_ADHOC"; const ENV_CDB_FILE = "CENTRS_CDB_FILE"; -const ENV_CDB_PASSWORD = "CENTRS_CDB_PASSWORD"; export interface CentrsMcpConfig { /** Absolute path to the CDB that is the device allowlist. */ @@ -32,6 +35,13 @@ export interface CentrsMcpConfig { cdbFileExplicit: boolean; /** CDB decrypt password, when the CDB on disk is encrypted. */ cdbPassword?: string; + /** + * A file holding the CDB password (`--cdb-password-file` or + * `CENTRS_CDB_PASSWORD_FILE`). Only the path is kept: every CDB load reads + * it again, so rotating or deleting the file takes effect at the next call + * (#672). Set at most one of this and `cdbPassword`. + */ + cdbPasswordFile?: string; /** * Off-by-default escape hatch reserved for future MCP schemas that accept * inline host+credentials. Phase 1 tools expose only CDB target strings. @@ -44,13 +54,15 @@ export interface CentrsMcpConfig { export interface ResolveMcpConfigArgs { cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; allowAdhocTargets?: boolean; env?: Record; /** * The `centrs.env` config tier (`src/resolver/config-file.ts`), loaded by * the caller — `resolveMcpConfig` itself stays synchronous so it can keep * serving as a default-parameter value (`server.ts`). `CENTRS_CDB_PASSWORD` - * deliberately never reads it, same as `resolveAuth`'s credential fields. + * and `CENTRS_CDB_PASSWORD_FILE` deliberately never read it, same as + * `resolveAuth`'s credential fields. */ config?: Record; } @@ -66,10 +78,18 @@ export function resolveMcpConfig( const allowAdhocTargets = args.allowAdhocTargets ?? (env[ENV_ALLOW_ADHOC] ?? config[ENV_ALLOW_ADHOC]) === "1"; + // Choose the key's source once, so a value-and-file conflict fails at + // startup; a file is only named here and read on each CDB load. + const key = chooseSecret( + CDB_PASSWORD_SECRET, + { value: args.cdbPassword, file: args.cdbPasswordFile }, + env, + ); return { cdbFile, cdbFileExplicit: explicitPath !== undefined, - cdbPassword: args.cdbPassword ?? env[ENV_CDB_PASSWORD] ?? undefined, + ...(key?.kind === "value" ? { cdbPassword: key.value } : {}), + ...(key?.kind === "file" ? { cdbPasswordFile: key.path } : {}), allowAdhocTargets, env, }; diff --git a/src/mcp/safety.ts b/src/mcp/safety.ts index 64961445..460c7f8f 100644 --- a/src/mcp/safety.ts +++ b/src/mcp/safety.ts @@ -53,6 +53,7 @@ export async function loadAllowlistCdb( return loadCdb({ cdbFile: config.cdbFile, cdbPassword: config.cdbPassword, + cdbPasswordFile: config.cdbPasswordFile, env: config.env, }); } diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index 76132cee..d4bed052 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -204,6 +204,7 @@ export async function handleValidate( timeout: args.timeout, cdbFile: config.cdbFile, cdbPassword: config.cdbPassword, + cdbPasswordFile: config.cdbPasswordFile, validate: true, stdinIsTty: false, }, @@ -295,11 +296,13 @@ export async function handleRetrieve( timeout: args.timeout, cdbFile: config.cdbFile, cdbPassword: config.cdbPassword, + cdbPasswordFile: config.cdbPasswordFile, }; - if (args.group === undefined) return await retrieveEnvelope(request); + if (args.group === undefined) + return await retrieveEnvelope(request, config.env); try { - return await retrieveGroup(request); + return await retrieveGroup(request, config.env); } catch (error) { return buildRetrieveFanoutErrorEnvelope(request, error); } @@ -358,6 +361,7 @@ export async function handleExecute( timeout: args.timeout, cdbFile: config.cdbFile, cdbPassword: config.cdbPassword, + cdbPasswordFile: config.cdbPasswordFile, validate: true, yes: args.confirm === true, stdinIsTty: false, @@ -762,6 +766,7 @@ export async function handleDiscover( group: args.group, cdbFile: config.cdbFile, cdbPassword: config.cdbPassword, + cdbPasswordFile: config.cdbPasswordFile, env: config.env, sendRefresh: args.sendRefresh, }); diff --git a/src/resolver/cdb.ts b/src/resolver/cdb.ts index 25e350bb..ae7c30c4 100644 --- a/src/resolver/cdb.ts +++ b/src/resolver/cdb.ts @@ -56,6 +56,40 @@ import { const ENV_CDB_FILE = "CENTRS_CDB_FILE"; const ENV_CDB_PASSWORD = "CENTRS_CDB_PASSWORD"; +const ENV_CDB_PASSWORD_FILE = "CENTRS_CDB_PASSWORD_FILE"; + +/** + * Whether the caller chose a CDB on purpose, so a missing file or a name the + * registry lacks is an error rather than "no CDB in play". Every flag and the + * value/path env keys count, as does a `centrs.env` CDB path. The env key + * file counts only when the CDB exists: it is often an image-wide default + * (#672), which must not make a first start without a CDB fail, but with a + * CDB present it pins the lookup like `CENTRS_CDB_PASSWORD` does. Shared by + * single-target ({@link resolveCdb}) and fan-out (`expandSelection`). + */ +export async function isExplicitCdb( + input: { cdbFile?: string; cdbPassword?: string; cdbPasswordFile?: string }, + env: Record, + config: Record, + cdbPath: string, +): Promise { + if ( + input.cdbFile !== undefined || + input.cdbPassword !== undefined || + input.cdbPasswordFile !== undefined || + env[ENV_CDB_FILE] !== undefined || + env[ENV_CDB_PASSWORD] !== undefined || + config[ENV_CDB_FILE] !== undefined + ) { + return true; + } + const keyFile = env[ENV_CDB_PASSWORD_FILE]; + return ( + keyFile !== undefined && + keyFile !== "" && + (await Bun.file(cdbPath).exists()) + ); +} export interface ResolverWarning { code: string; @@ -144,6 +178,7 @@ export interface CdbResolveInput { targetInput?: string; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` record selector (`user=`, `target=`, or a record * type such as `ipUser`) for a `` several CDB records share — the @@ -220,6 +255,7 @@ export async function resolveCdb( const settings = resolveDevicesSettings({ cdbFile: input.cdbFile, cdbPassword: input.cdbPassword, + cdbPasswordFile: input.cdbPasswordFile, env, config, }); @@ -227,12 +263,12 @@ export async function resolveCdb( // as an env var: it is an intentional choice, not the built-in fallback, // so a missing file there should surface as a real error rather than // silently degrading to "no CDB in play". - const explicitCdb = - input.cdbFile !== undefined || - input.cdbPassword !== undefined || - env[ENV_CDB_FILE] !== undefined || - env[ENV_CDB_PASSWORD] !== undefined || - config[ENV_CDB_FILE] !== undefined; + const explicitCdb = await isExplicitCdb( + input, + env, + config, + settings.cdbFile.value, + ); if (!explicitCdb && !(await Bun.file(settings.cdbFile.value).exists())) { if (input.match !== undefined) { matchWithoutRecord(input, "no CDB file is in play"); @@ -245,6 +281,7 @@ export async function resolveCdb( cdb = await loadCdb({ cdbFile: input.cdbFile, cdbPassword: input.cdbPassword, + cdbPasswordFile: input.cdbPasswordFile, env, config, }); @@ -365,6 +402,7 @@ export interface CdbGroupResolveInput { group: string; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; } /** @@ -383,6 +421,7 @@ export async function expandCdbGroup( const cdb: LoadedCdb = await loadCdb({ cdbFile: input.cdbFile, cdbPassword: input.cdbPassword, + cdbPasswordFile: input.cdbPasswordFile, env, }); diff --git a/src/resolver/dotenv-guard.ts b/src/resolver/dotenv-guard.ts new file mode 100644 index 00000000..353d4656 --- /dev/null +++ b/src/resolver/dotenv-guard.ts @@ -0,0 +1,349 @@ +/** + * Keep a working directory's `.env` out of centrs (#666). + * + * Bun loads `.env` files from the current working directory into + * `process.env` for any script it runs, so the installed `centrs` (a + * `#!/usr/bin/env bun` script) run inside a cloned repo would take that repo's + * settings as if the caller had exported them. Removing the keys in-process + * is not enough, as measured on Bun 1.4.4: + * + * - Bun reads some of its own settings at startup, before any script runs. A + * repo's `BUN_CONFIG_VERBOSE_FETCH=curl` makes every `fetch` print its + * headers, a REST Basic credential included, and deleting the key later + * does not turn that off. + * - Keys outside `CENTRS_*` steer centrs too: `XDG_CONFIG_HOME` picks which + * `centrs.env` is read. + * - A file's `NODE_ENV` changes which other files a later scan would check, + * though Bun had already chosen them; and Bun accepts `KEY: value` and + * CR-only lines. + * + * So the CLI and MCP entries re-launch themselves once with + * `bun --no-env-file`, giving the child the environment centrs was started + * with. `process.execArgv` shows the flag, so the child does not re-launch, + * and a `.env` file cannot fake it. On Linux, `/proc/self/environ` holds the + * exec-time environment, which Bun's load does not touch: the child gets + * exactly that, and the re-launch happens only when the two differ. + * Elsewhere, every key that a `.env` file Bun may load names is dropped, + * except the Windows system variables, which Windows always sets (so the + * shell's value beats the file's). A named `PATH` is reset to the system + * default search path rather than dropped. Keys are matched by name, never + * by parsing values, so no `.env` parser here can drift from Bun's. + * + * A changed shebang (`env -S bun --no-env-file`) would do this without a + * second process, but BusyBox `env` has no `-S` (Alpine, `oven/bun:alpine`), + * and Windows bin shims pick the interpreter from the shebang. + */ + +import { readFileSync } from "node:fs"; +import { constants } from "node:os"; +import { join } from "node:path"; + +const NO_ENV_FILE = "--no-env-file"; + +/** + * Every `.env` file name Bun 1.4.4 may auto-load from the working directory: + * `.env`, `.env.`, `.env..local` and `.env.local`. Bun has three + * modes, `development`, `production` and `test`; any other `NODE_ENV` + * (`staging`) loads the `development` files, never `.env.staging` (measured + * on Bun 1.4.5). All three are scanned, whatever `NODE_ENV` says now: a file + * can change `NODE_ENV` after Bun has picked the set. + */ +export const BUN_DOTENV_FILE_NAMES: readonly string[] = [ + ".env", + ".env.local", + ".env.development", + ".env.development.local", + ".env.production", + ".env.production.local", + ".env.test", + ".env.test.local", +]; + +/** + * Variables a `.env` may name that the fallback still keeps: Windows always + * sets them (so the shell's value wins over the file's), and a Windows child + * may not start without them. Nothing else is kept, not even `HOME`, + * `USERPROFILE` or `APPDATA`: without `/proc` there is no telling a + * launch-time value from a file's, a Windows shell often has no `HOME`, and + * `HOME` picks which `centrs.env` is read. A dropped one falls back to the + * account's home directory (`os.homedir()`). + */ +const KEPT_OS_KEYS: ReadonlySet = new Set([ + "PATHEXT", + "SYSTEMROOT", + "WINDIR", + "COMSPEC", +]); + +/** + * `PATH` is not kept: a service can start Bun by absolute path with no + * `PATH`, and then a repo's `.env` would pick which `ssh` or `sftp` centrs + * runs. Dropping it outright would break those lookups, so a named `PATH` is + * reset to the system default, which has the OS's own `ssh`. + */ +function systemDefaultPath( + platform: NodeJS.Platform, + env: Record, +): string { + if (platform !== "win32") return "/usr/bin:/bin:/usr/sbin:/sbin"; + const root = envValue(env, "SYSTEMROOT", platform) ?? "C:\\Windows"; + return [ + `${root}\\System32`, + root, + `${root}\\System32\\Wbem`, + `${root}\\System32\\WindowsPowerShell\\v1.0\\`, + `${root}\\System32\\OpenSSH\\`, + ].join(";"); +} + +/** Environment names compare case-insensitively on Windows only. */ +function sameKey(a: string, b: string, platform: NodeJS.Platform): boolean { + return platform === "win32" ? a.toUpperCase() === b.toUpperCase() : a === b; +} + +function envValue( + env: Record, + key: string, + platform: NodeJS.Platform, +): string | undefined { + const found = Object.keys(env).find((name) => sameKey(name, key, platform)); + return found === undefined ? undefined : env[found]; +} + +/** + * A key at the start of a line, then its `=` or `:`. Bun allows any + * whitespace before the separator, line breaks and blank lines included + * (`KEY` on one line, `= value` on the next), so the gap may span lines. + * Over-matching (a value line that looks like an assignment) only drops a + * key, which fails safe. + */ +const KEY_ASSIGNMENT = + /(?:^|[\r\n])\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*[=:]/g; + +/** Key names assigned in a dotenv text (`=` or `:`; LF, CRLF or CR lines). */ +export function dotenvKeyNames(text: string): Set { + const keys = new Set(); + for (const match of text.matchAll(KEY_ASSIGNMENT)) { + if (match[1]) keys.add(match[1]); + } + return keys; +} + +/** The exec-time environment from `/proc/self/environ`, or `undefined`. */ +export function readInitialEnviron( + path = "/proc/self/environ", +): Map | undefined { + let raw: string; + try { + raw = readFileSync(path, "utf8"); + } catch { + return undefined; + } + const environ = new Map(); + for (const entry of raw.split("\0")) { + const separator = entry.indexOf("="); + if (separator > 0) { + environ.set(entry.slice(0, separator), entry.slice(separator + 1)); + } + } + return environ; +} + +export interface DotenvGuardOptions { + /** Default: `process.env`. */ + env?: Record; + /** Default: `process.cwd()`. */ + cwd?: string; + /** Default: `process.execArgv`. */ + execArgv?: readonly string[]; + /** The exec-time environment; `null` means unknown. Default: `/proc`. */ + initialEnviron?: Map | null; + /** Default: `process.platform`. */ + platform?: NodeJS.Platform; +} + +export interface DotenvRelaunchPlan { + /** The environment to give the `--no-env-file` child. */ + env: Record; + /** Keys removed or reset, sorted. Never their values. */ + dropped: string[]; +} + +/** + * Decide whether Bun's `.env` auto-load changed the environment, and if so, + * what the re-launched child gets. `undefined`: run in this process. + */ +export function planDotenvRelaunch( + options: DotenvGuardOptions = {}, +): DotenvRelaunchPlan | undefined { + const env = options.env ?? process.env; + const execArgv = options.execArgv ?? process.execArgv; + if (execArgv.includes(NO_ENV_FILE)) return undefined; + const initial = + options.initialEnviron === undefined + ? readInitialEnviron() + : (options.initialEnviron ?? undefined); + + if (initial !== undefined) { + const dropped = Object.keys(env).filter( + (key) => env[key] !== undefined && initial.get(key) !== env[key], + ); + if (dropped.length === 0) return undefined; + return { env: Object.fromEntries(initial), dropped: dropped.sort() }; + } + + const cwd = options.cwd ?? process.cwd(); + const platform = options.platform ?? process.platform; + const named = new Set(); + for (const name of BUN_DOTENV_FILE_NAMES) { + let text: string; + try { + text = readFileSync(join(cwd, name), "utf8"); + } catch { + continue; + } + for (const key of dotenvKeyNames(text)) { + named.add(platform === "win32" ? key.toUpperCase() : key); + } + } + const isNamed = (key: string): boolean => + named.has(platform === "win32" ? key.toUpperCase() : key); + const dropped = Object.keys(env).filter( + (key) => + env[key] !== undefined && + isNamed(key) && + !KEPT_OS_KEYS.has(key.toUpperCase()), + ); + if (dropped.length === 0) return undefined; + const childEnv: Record = {}; + for (const [key, value] of Object.entries(env)) { + if (value !== undefined && !dropped.includes(key)) childEnv[key] = value; + } + if (dropped.some((key) => sameKey(key, "PATH", platform))) { + childEnv["PATH"] = systemDefaultPath(platform, childEnv); + } + return { env: childEnv, dropped: dropped.sort() }; +} + +/** + * The stderr warning for a plan, naming the `CENTRS_*` keys ignored, and + * `PATH` when the fallback reset it. A repo's other keys are normal and not + * centrs's business, so they go unnamed. + */ +export function dotenvGuardWarning( + plan: DotenvRelaunchPlan, +): string | undefined { + const centrs = plan.dropped.filter((key) => key.startsWith("CENTRS_")); + const path = plan.dropped.some((key) => key.toUpperCase() === "PATH"); + if (centrs.length === 0 && !path) return undefined; + const ignored = + centrs.length === 0 + ? "" + : `ignored ${centrs.join(", ")} from the working directory's .env files (Bun loads them; centrs does not read them). Export the key in the shell, pass the flag, or use \`centrs settings\`.`; + const reset = path + ? "PATH is named in the working directory's .env files, so this run uses the system default PATH." + : ""; + return `warning [settings/dotenv-ignored]: ${[ignored, reset].filter(Boolean).join(" ")}`; +} + +/** The message a re-launched child sends when SIGINT reaches it. */ +const SIGINT_SEEN = "centrs:dotenv-guard:sigint"; + +/** + * How long the launcher waits for the child to report a SIGINT before + * passing one on. A terminal's Ctrl-C reaches both processes at once; a + * `kill -INT ` reaches only the launcher. + */ +const SIGINT_RELAY_MS = 150; + +/** + * Re-run this script under `bun --no-env-file` with the plan's environment, + * stdio inherited, and return the child's exit code. SIGTERM and SIGHUP are + * passed on. SIGINT is passed on only when the child did not get it too: + * centrs treats a second Ctrl-C as "exit now", so a doubled one would skip + * a graceful cancel. The child reports its own SIGINT over an IPC channel. + */ +export async function relaunchWithoutDotenv( + plan: DotenvRelaunchPlan, +): Promise { + let childSawSigintAt = Number.NEGATIVE_INFINITY; + const child = Bun.spawn( + [ + process.execPath, + NO_ENV_FILE, + ...process.execArgv, + Bun.main, + ...Bun.argv.slice(2), + ], + { + env: plan.env, + stdio: ["inherit", "inherit", "inherit"], + ipc(message) { + if (message === SIGINT_SEEN) childSawSigintAt = performance.now(); + }, + }, + ); + const relaySigint = (): void => { + const at = performance.now(); + setTimeout(() => { + const running = child.exitCode === null && child.signalCode === null; + if (running && childSawSigintAt < at - SIGINT_RELAY_MS) { + child.kill("SIGINT"); + } + }, SIGINT_RELAY_MS); + }; + const handlers: [NodeJS.Signals, () => void][] = [ + ["SIGINT", relaySigint], + ["SIGTERM", () => child.kill("SIGTERM")], + ["SIGHUP", () => child.kill("SIGHUP")], + ]; + for (const [signal, handler] of handlers) process.on(signal, handler); + try { + const code = await child.exited; + const signal = child.signalCode; + if (signal !== null && signal !== undefined) { + const number = + typeof signal === "number" + ? signal + : constants.signals[signal as NodeJS.Signals]; + return number === undefined ? 1 : 128 + number; + } + return code; + } finally { + for (const [signal, handler] of handlers) process.off(signal, handler); + } +} + +/** + * In a re-launched child: tell the launcher about each SIGINT, so it does not + * pass on a second one. When no other listener handles it, re-raise it so + * the default action (exit by signal) still applies. + */ +function reportSigintToLauncher(): void { + if (typeof process.send !== "function") return; + // The channel must not keep a finished command alive. + (process.channel as { unref?: () => void } | undefined)?.unref?.(); + const onSigint = (): void => { + process.send?.(SIGINT_SEEN); + if (process.listenerCount("SIGINT") === 1) { + process.off("SIGINT", onSigint); + process.kill(process.pid, "SIGINT"); + } + }; + process.on("SIGINT", onSigint); +} + +/** + * The CLI/MCP entry wrapper: re-launch without `.env` when Bun loaded one, + * else run `main` here. + */ +export async function runWithoutDotenv( + main: () => Promise, +): Promise { + if (process.execArgv.includes(NO_ENV_FILE)) reportSigintToLauncher(); + const plan = planDotenvRelaunch(); + if (plan === undefined) return main(); + const warning = dotenvGuardWarning(plan); + if (warning) console.error(warning); + return relaunchWithoutDotenv(plan); +} diff --git a/src/resolver/quickchr-provider.ts b/src/resolver/quickchr-provider.ts index deb2c3b3..bb934893 100644 --- a/src/resolver/quickchr-provider.ts +++ b/src/resolver/quickchr-provider.ts @@ -346,6 +346,7 @@ export function assertNoQuickchrOverrideConflict( port?: number; username?: string; password?: string; + passwordFile?: string; sshKey?: string; /** `--match` picks a CDB record; a quickchr target has none (#583). */ match?: string; @@ -368,6 +369,9 @@ export function assertNoQuickchrOverrideConflict( if (request.password !== undefined) { conflicts.push("--password"); } + if (request.passwordFile !== undefined) { + conflicts.push("--password-file"); + } if (request.sshKey !== undefined) { conflicts.push("--ssh-key"); } diff --git a/src/resolver/secret-source.ts b/src/resolver/secret-source.ts new file mode 100644 index 00000000..28ec3fbe --- /dev/null +++ b/src/resolver/secret-source.ts @@ -0,0 +1,198 @@ +/** + * One resolver for "a secret given as a value or as a file" (#672), shared by + * the CDB key and the target password, on the CLI, MCP and the library. + * + * Each secret has one source per tier. Flags outrank the environment, as for + * every setting. Within one tier the value and the file form are one choice: + * setting both (`--password` with `--password-file`, or `CENTRS_PASSWORD` + * with `CENTRS_PASSWORD_FILE`) is `usage/conflicting-flags`, never a silent + * precedence. The later password-command form becomes one more case here. + * + * A `*_FILE` path comes only from a flag or the process environment, never + * `centrs.env` (its loader drops the keys) or a workspace file; the CLI also + * strips a working-directory `.env`'s keys first (#666). An empty env value + * counts as unset, so an image-wide default can be blanked per run. + * + * The file is read when the secret is needed, not when it is chosen, so a + * rotated or deleted file takes effect on the next CDB load. Errors name the + * path, never the contents. No permission check: `/run/secrets` modes vary, + * and on RouterOS they mean nothing. + */ + +import { + closeSync, + existsSync, + constants as fsConstants, + fstatSync, + openSync, + readFileSync, +} from "node:fs"; +import type { SettingSource } from "../core/envelope.ts"; +import { + decodePasswordBytes, + passwordBytesReason, +} from "../core/password-bytes.ts"; +import { CentrsError, type CentrsErrorCode } from "../errors.ts"; + +/** `O_NONBLOCK` where the platform has it (not on Windows, which has no FIFOs to open). */ +const NONBLOCK = fsConstants.O_NONBLOCK ?? 0; + +export interface SecretSpec { + /** Words for messages: "CDB password", "password". */ + label: string; + valueFlag: string; + fileFlag: string; + envKey: string; + fileEnvKey: string; + /** The error when a chosen file cannot give a password. */ + unavailableCode: CentrsErrorCode; +} + +export const CDB_PASSWORD_SECRET: SecretSpec = { + label: "CDB password", + valueFlag: "--cdb-password", + fileFlag: "--cdb-password-file", + envKey: "CENTRS_CDB_PASSWORD", + fileEnvKey: "CENTRS_CDB_PASSWORD_FILE", + unavailableCode: "cdb/password-unavailable", +}; + +export const TARGET_PASSWORD_SECRET: SecretSpec = { + label: "password", + valueFlag: "--password", + fileFlag: "--password-file", + envKey: "CENTRS_PASSWORD", + fileEnvKey: "CENTRS_PASSWORD_FILE", + unavailableCode: "auth/password-unavailable", +}; + +export type SecretChoice = + | { kind: "value"; value: string; source: SettingSource } + | { kind: "file"; path: string; source: SettingSource }; + +/** + * Pick the secret's source: flags, then the environment. Throws + * `usage/conflicting-flags` when one tier sets both forms. + */ +export function chooseSecret( + spec: SecretSpec, + explicit: { value?: string; file?: string }, + env: Record, +): SecretChoice | undefined { + if (explicit.value !== undefined && explicit.file !== undefined) { + throw conflict(spec, [spec.valueFlag, spec.fileFlag]); + } + if (explicit.file !== undefined) { + return { + kind: "file", + path: explicit.file, + source: { kind: "file", key: spec.fileFlag }, + }; + } + if (explicit.value !== undefined) { + return { + kind: "value", + value: explicit.value, + source: { kind: "cli", key: spec.valueFlag }, + }; + } + const envValue = env[spec.envKey]; + const envFile = env[spec.fileEnvKey]; + const hasEnvFile = envFile !== undefined && envFile !== ""; + if (envValue !== undefined && hasEnvFile) { + throw conflict(spec, [spec.envKey, spec.fileEnvKey]); + } + if (hasEnvFile) { + return { + kind: "file", + path: envFile, + source: { kind: "file", key: spec.fileEnvKey }, + }; + } + if (envValue !== undefined) { + return { + kind: "value", + value: envValue, + source: { kind: "env", key: spec.envKey }, + }; + } + return undefined; +} + +function conflict(spec: SecretSpec, names: [string, string]): CentrsError { + return new CentrsError({ + code: "usage/conflicting-flags", + summary: `${names[0]} and ${names[1]} both set the ${spec.label}; give one.`, + remediation: `Keep one source for the ${spec.label}: the value (${names[0]}) or a file holding it (${names[1]}).`, + context: { flags: names }, + }); +} + +/** True when the path names an existing file (never reads it). */ +export function secretFileExists(path: string): boolean { + return existsSync(path); +} + +/** + * Read a password from the chosen file. Strips one trailing newline, as + * `--password-stdin` does. A missing, unreadable, empty or non-UTF-8 file + * throws the spec's `unavailableCode`, naming the path and never the bytes. + */ +export function readSecretFile( + spec: SecretSpec, + choice: Extract, +): string { + const where = choice.source.key ?? spec.fileFlag; + let raw: Uint8Array; + try { + // Open without blocking and check the opened file: a FIFO with no + // writer, or a device, would otherwise hang or stream forever (PR #674 + // review). A symlink to a mounted secret is followed as usual. + const fd = openSync(choice.path, fsConstants.O_RDONLY | NONBLOCK); + try { + if (!fstatSync(fd).isFile()) { + throw unavailable(spec, choice, where, "is not a regular file", {}); + } + raw = readFileSync(fd); + } finally { + closeSync(fd); + } + } catch (cause) { + if (cause instanceof CentrsError) throw cause; + const errno = + typeof cause === "object" && cause !== null && "code" in cause + ? String((cause as { code: unknown }).code) + : undefined; + throw unavailable( + spec, + choice, + where, + errno === "ENOENT" ? "does not exist" : "could not be read", + { ...(errno ? { errno } : {}) }, + ); + } + const decoded = decodePasswordBytes(raw); + if (decoded.ok) return decoded.value; + throw unavailable( + spec, + choice, + where, + `holds ${passwordBytesReason(decoded.reason)}`, + { byteLength: decoded.byteLength }, + ); +} + +function unavailable( + spec: SecretSpec, + choice: Extract, + where: string, + what: string, + extra: Record, +): CentrsError { + return new CentrsError({ + code: spec.unavailableCode, + summary: `The ${spec.label} file ${choice.path} (from ${where}) ${what}.`, + remediation: `Whoever launched centrs set ${where}: check that ${choice.path} exists, is readable by this process and holds the ${spec.label} as UTF-8 (one trailing newline is ignored), or unset ${where}. On a container, check that the secret is mounted.`, + context: { path: choice.path, source: where, ...extra }, + }); +} diff --git a/src/resolver/selection.ts b/src/resolver/selection.ts index b0e40dfb..d501c2ae 100644 --- a/src/resolver/selection.ts +++ b/src/resolver/selection.ts @@ -38,6 +38,7 @@ import { CentrsError } from "../errors.ts"; import { type CdbResolution, DEFAULT_RECORD_TARGET, + isExplicitCdb, type ResolverWarning, resolutionFromEntry, } from "./cdb.ts"; @@ -88,6 +89,7 @@ export interface TargetSelection { export interface SelectionResolveInput { cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** CLI: true (literal positionals allowed). MCP: false (CDB is the allowlist). */ allowAdhoc: boolean; } @@ -147,9 +149,6 @@ export function isDefaultRecordTarget(target: string): boolean { return target === DEFAULT_RECORD_TARGET; } -const ENV_CDB_FILE = "CENTRS_CDB_FILE"; -const ENV_CDB_PASSWORD = "CENTRS_CDB_PASSWORD"; - /** * Expand a {@link TargetSelection} into N resolved members. The CDB is loaded * once; selectors and positionals union into a record-index set (plus literals), @@ -176,15 +175,16 @@ export async function expandSelection( const settings = resolveDevicesSettings({ cdbFile: input.cdbFile, cdbPassword: input.cdbPassword, + cdbPasswordFile: input.cdbPasswordFile, env, config, }); - const explicitCdb = - input.cdbFile !== undefined || - input.cdbPassword !== undefined || - env[ENV_CDB_FILE] !== undefined || - env[ENV_CDB_PASSWORD] !== undefined || - config[ENV_CDB_FILE] !== undefined; + const explicitCdb = await isExplicitCdb( + input, + env, + config, + settings.cdbFile.value, + ); const emptyCdb = (): LoadedCdb => ({ entries: [], warnings: [], @@ -202,6 +202,7 @@ export async function expandSelection( cdb = await loadCdb({ cdbFile: input.cdbFile, cdbPassword: input.cdbPassword, + cdbPasswordFile: input.cdbPasswordFile, env, config, }); diff --git a/src/resolver/settings.ts b/src/resolver/settings.ts index f5175498..81e959c9 100644 --- a/src/resolver/settings.ts +++ b/src/resolver/settings.ts @@ -61,6 +61,8 @@ export const REFUSED_CONFIG_ENV_KEYS: readonly string[] = [ "CENTRS_PASSWORD", "CENTRS_USERNAME", "CENTRS_CDB_PASSWORD", + "CENTRS_PASSWORD_FILE", + "CENTRS_CDB_PASSWORD_FILE", "CENTRS_SKIP_ENV_FILE", "CENTRS_RUN_FAST_INTEGRATION", ]; diff --git a/src/resolver/target.ts b/src/resolver/target.ts index 54bc8566..36bf3a6f 100644 --- a/src/resolver/target.ts +++ b/src/resolver/target.ts @@ -26,6 +26,11 @@ import { } from "../protocols/native-api.ts"; import type { CdbResolution, CommentKvOverrides } from "./cdb.ts"; import { normalizeMac } from "./mac.ts"; +import { + chooseSecret, + readSecretFile, + TARGET_PASSWORD_SECRET, +} from "./secret-source.ts"; import { type ResolvedSetting, type ResolverSettingSource, @@ -454,7 +459,23 @@ function resolvePortSource( } export function resolveAuth( - credentials: { username?: string; password?: string; sshKey?: string }, + credentials: { + username?: string; + password?: string; + /** `--password-file`; conflicts with `password` (#672). */ + passwordFile?: string; + sshKey?: string; + /** + * The protocol never sends a target password (ssh: batch `execute` + * and sftp/scp run with `BatchMode=yes`; the interactive terminal + * leaves the prompt to OpenSSH). The source is still chosen, so a + * conflict is an error and "a password was given but not sent" tips + * can name it, but a password file is not read: one it cannot read, + * such as an image-wide `CENTRS_PASSWORD_FILE`, cannot stop a key or + * agent login (PR #674 review). + */ + sendsNoPassword?: boolean; + }, env: Record, cdb?: CdbResolution, config: Record = {}, @@ -485,13 +506,38 @@ export function resolveAuth( cdb?.overrides.sshKey, config, ); - const password = resolveStringSetting( - credentials.password, + // Value or file, flag then env (#672). A chosen file outranks CDB records + // like `CENTRS_PASSWORD` does, so a missing one is an error, never a quiet + // fall back to the record's password. + const passwordChoice = chooseSecret( + TARGET_PASSWORD_SECRET, + { value: credentials.password, file: credentials.passwordFile }, env, - "CENTRS_PASSWORD", - undefined, - "password", ); + const password: ResolvedSetting | undefined = + passwordChoice === undefined + ? undefined + : passwordChoice.kind === "file" + ? { + value: + credentials.sendsNoPassword === true + ? "" + : readSecretFile(TARGET_PASSWORD_SECRET, passwordChoice), + source: { + kind: "file", + key: passwordChoice.source.key ?? "--password-file", + }, + } + : { + value: passwordChoice.value, + source: + passwordChoice.source.kind === "cli" + ? { kind: "explicit", key: "password" } + : { + kind: "env", + key: passwordChoice.source.key ?? "CENTRS_PASSWORD", + }, + }; const def = cdb?.defaults; const cdbUsername = username === undefined && cdb?.username diff --git a/src/retrieve-fanout.ts b/src/retrieve-fanout.ts index c80904c3..7733eb67 100644 --- a/src/retrieve-fanout.ts +++ b/src/retrieve-fanout.ts @@ -239,6 +239,7 @@ export async function retrieveFanout( { cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, allowAdhoc: options.allowAdhoc ?? true, }, env, diff --git a/src/retrieve.ts b/src/retrieve.ts index 7f570c0c..236123b2 100644 --- a/src/retrieve.ts +++ b/src/retrieve.ts @@ -91,6 +91,8 @@ export interface RetrieveRequest { port?: number; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; timeout?: string | number; format?: string; validate?: boolean; @@ -106,6 +108,7 @@ export interface RetrieveRequest { maxResultsBytes?: number; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -1246,7 +1249,11 @@ export function buildResolvedRetrieve( const auth = connection ? connection.auth : resolveAuth( - { username: request.username, password: request.password }, + { + username: request.username, + password: request.password, + passwordFile: request.passwordFile, + }, env, cdbResolution, ); @@ -1385,6 +1392,7 @@ export async function resolveRetrieveRequest( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, diff --git a/src/settings.ts b/src/settings.ts index 368e5263..11c95a81 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -352,6 +352,20 @@ export const settingsRefusedKeys: readonly RefusedKeyDef[] = [ remediation: "Pass --cdb-password per invocation, export CENTRS_CDB_PASSWORD in the calling shell, or use Bun.secret() once available — never persist a CDB decrypt password to centrs.env.", }, + { + attr: "password-file", + envKey: "CENTRS_PASSWORD_FILE", + secret: false, + remediation: + "Pass --password-file per invocation or export CENTRS_PASSWORD_FILE in the launching environment. Only a flag or the process environment may name a password file, so a shared or cloned config cannot point it at another file (#672).", + }, + { + attr: "cdb-password-file", + envKey: "CENTRS_CDB_PASSWORD_FILE", + secret: false, + remediation: + "Pass --cdb-password-file per invocation or export CENTRS_CDB_PASSWORD_FILE in the launching environment (a container's env, the MCP server's launch config). Only a flag or the process environment may name a password file (#672).", + }, { attr: "skip-env-file", envKey: "CENTRS_SKIP_ENV_FILE", @@ -540,6 +554,7 @@ export interface SettingsPrintArgs { skipEnvFile?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; } function redactIfSecret( @@ -664,11 +679,16 @@ function collectUnrecognized( * error, unlike `devices list` — settings should never require a CDB to exist. */ async function probeDefaultDevice( - args: Pick, + args: Pick< + SettingsPrintArgs, + "cdbFile" | "cdbPassword" | "cdbPasswordFile" | "env" + >, + warnings: Warning[], ): Promise { const settings = resolveDevicesSettings({ cdbFile: args.cdbFile, cdbPassword: args.cdbPassword, + cdbPasswordFile: args.cdbPasswordFile, env: args.env, }); if (!(await Bun.file(settings.cdbFile.value).exists())) { @@ -677,8 +697,13 @@ async function probeDefaultDevice( const cdb = await loadCdb({ cdbFile: settings.cdbFile.value, cdbPassword: args.cdbPassword, + cdbPasswordFile: args.cdbPasswordFile, env: args.env, }); + // An unneeded or missing key file on an open CDB (#672) is said here too. + for (const warning of cdb.warnings) { + if (warning.code === "cdb/password-not-needed") warnings.push(warning); + } const entry = cdb.entries.find( (candidate) => candidate.target === DEFAULT_RECORD_TARGET, ); @@ -727,7 +752,7 @@ export async function settingsPrint( if (args.all) { data.unrecognized = collectUnrecognized(lines); } - data.defaultDevice = await probeDefaultDevice(args); + data.defaultDevice = await probeDefaultDevice(args, warnings); if (args.skipEnvFile) { warnings.push({ diff --git a/src/terminal.ts b/src/terminal.ts index db80a440..24f9c6d5 100644 --- a/src/terminal.ts +++ b/src/terminal.ts @@ -87,6 +87,8 @@ export interface TerminalRequest { resolve?: string; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; /** Explicit in-packet source MAC (overrides egress-MAC resolution; mac-telnet). */ sourceMac?: string; /** `--via ssh`: private-key path (path only; agent / ~/.ssh used if unset). */ @@ -95,6 +97,7 @@ export interface TerminalRequest { insecure?: boolean; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -195,6 +198,7 @@ export async function resolveTerminalRequest( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, @@ -248,11 +252,15 @@ export async function resolveTerminalRequest( cdb, config, ); + // Interactive ssh never uses a password: OpenSSH takes none on the argv and + // prompts on the TTY itself (PR #674 review). const auth = resolveAuth( { username: request.username, password: request.password, + passwordFile: request.passwordFile, sshKey: request.sshKey, + sendsNoPassword: viaValue === "ssh", }, env, cdb, diff --git a/src/transfer-fanout.ts b/src/transfer-fanout.ts index 7a936f4f..2c1a96ac 100644 --- a/src/transfer-fanout.ts +++ b/src/transfer-fanout.ts @@ -296,6 +296,7 @@ export async function transferFanout( { cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, allowAdhoc: options.allowAdhoc ?? true, }, env, diff --git a/src/transfer.ts b/src/transfer.ts index 9e35bdb3..28e71f7a 100644 --- a/src/transfer.ts +++ b/src/transfer.ts @@ -154,6 +154,8 @@ export interface TransferRequest { port?: number; username?: string; password?: string; + /** A file holding the password (`--password-file`); conflicts with `password` (#672). */ + passwordFile?: string; /** SSH private-key path for sftp/scp (`--ssh-key`). Path only. */ sshKey?: string; /** Accept self-signed TLS / new SSH host keys (`--insecure`). Default false. */ @@ -172,6 +174,7 @@ export interface TransferRequest { name?: string; cdbFile?: string; cdbPassword?: string; + cdbPasswordFile?: string; /** * `--match` selector for a `` several CDB records share * (`user=`, `target=`, or a record type): the same selector @@ -1016,6 +1019,7 @@ export async function resolveTransferRequest( targetInput: request.targetInput, cdbFile: request.cdbFile, cdbPassword: request.cdbPassword, + cdbPasswordFile: request.cdbPasswordFile, match: request.match, }, env, @@ -1092,7 +1096,10 @@ export async function resolveTransferRequest( { username: request.username, password: request.password, + passwordFile: request.passwordFile, sshKey: request.sshKey, + // sftp/scp run batch ssh, which sends no password (PR #674). + sendsNoPassword: protocol === "ssh", }, env, cdbResolution, diff --git a/test/integration/cli-smoke.test.ts b/test/integration/cli-smoke.test.ts index 7ea8e036..c875ac97 100644 --- a/test/integration/cli-smoke.test.ts +++ b/test/integration/cli-smoke.test.ts @@ -423,6 +423,153 @@ describe("CLI smoke (real subprocess, no network)", () => { }); }); + describe("a working-directory .env never reaches centrs (#666)", () => { + const CLI = join(import.meta.dir, "..", "..", "src", "cli.ts"); + // A clean launch environment, so a `.env` value is never shadowed by one + // the test runner happens to export (XDG_CONFIG_HOME, NODE_ENV, …). + async function runIn( + cwd: string, + args: readonly string[], + extra: Record = {}, + ) { + const proc = Bun.spawn(["bun", CLI, ...args], { + cwd, + env: { PATH: process.env["PATH"] ?? "", HOME: cwd, ...extra }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { stdout, stderr, exitCode }; + } + async function workspace(files: Record) { + const cwd = await mkdtemp(join(tmpdir(), "centrs-dotenv-smoke-")); + for (const [name, body] of Object.entries(files)) { + await Bun.write(join(cwd, name), body); + } + return cwd; + } + function settingKind(stdout: string, key: string): string | undefined { + const envelope = JSON.parse(stdout) as { + data: Record; + }; + return envelope.data[key]?.source?.kind; + } + + test("CENTRS_* via .env, a NODE_ENV switch, colon and CR-only lines", async () => { + const cwd = await workspace({ + ".env": + "NODE_ENV=test\nCENTRS_INSECURE=1\nCENTRS_PASSWORD_FILE=/nonexistent/id_ed25519\n", + ".env.development": "CENTRS_FORMAT=json\n", + ".env.local": "CENTRS_VALIDATE: 0\rCENTRS_MAX_RESULTS=5\r", + }); + try { + const res = await runIn(cwd, ["settings", "print", "--json"]); + expect(res.exitCode).toBe(0); + expect(res.stderr).toContain("warning [settings/dotenv-ignored]"); + expect(res.stderr).toContain("CENTRS_PASSWORD_FILE"); + expect(res.stderr).not.toContain("/nonexistent/id_ed25519"); + for (const key of ["format", "insecure", "validate", "max-results"]) { + expect(settingKind(res.stdout, key)).toBe("default"); + } + } finally { + await rm(cwd, { recursive: true, force: true }); + } + }); + + // Only Linux can tell a shell export from a `.env` value + // (`/proc/self/environ`). Elsewhere a key a `.env` names is dropped even + // when exported, by design (commands/settings/README.md). + test.skipIf(process.platform !== "linux")( + "Linux: a shell export of a key the .env also names is kept", + async () => { + const cwd = await workspace({ ".env": "CENTRS_FORMAT=yaml\n" }); + try { + const exported = await runIn(cwd, ["explain", "/ip/route"], { + CENTRS_FORMAT: "json", + }); + expect(exported.exitCode).toBe(0); + const explained = JSON.parse(exported.stdout) as { + meta: { settings: { format?: { kind: string } } }; + }; + expect(explained.meta.settings.format?.kind).toBe("env"); + } finally { + await rm(cwd, { recursive: true, force: true }); + } + }, + ); + + test("a .env cannot move the user-global centrs.env (XDG_CONFIG_HOME)", async () => { + const cwd = await workspace({ + "cfg/tikoci/centrs.env": "CENTRS_FORMAT=json\n", + }); + await Bun.write( + join(cwd, ".env"), + `XDG_CONFIG_HOME=${join(cwd, "cfg")}\n`, + ); + try { + const res = await runIn(cwd, ["settings", "print", "--json"]); + expect(res.exitCode).toBe(0); + expect(settingKind(res.stdout, "format")).toBe("default"); + } finally { + await rm(cwd, { recursive: true, force: true }); + } + }); + + test("Bun's own startup settings from a .env cannot print a credential", async () => { + const user = "dotenv-user"; + const password = "dotenv-password-file-secret"; + const basic = Buffer.from(`${user}:${password}`).toString("base64"); + let sawAuthorization = false; + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request) { + sawAuthorization ||= + request.headers.get("authorization") === `Basic ${basic}`; + return new Response("{}", { status: 401 }); + }, + }); + const cwd = await workspace({ + ".env": "BUN_CONFIG_VERBOSE_FETCH=curl\n", + pw: `${password}\n`, + }); + try { + const res = await runIn(cwd, [ + "retrieve", + `http://127.0.0.1:${server.port}`, + "/system/resource", + "--username", + user, + "--password-file", + join(cwd, "pw"), + "--json", + ]); + expect(sawAuthorization).toBe(true); + expect(res.stderr).not.toContain(basic); + expect(res.stderr).not.toContain(password); + expect(res.stdout).not.toContain(password); + } finally { + server.stop(true); + await rm(cwd, { recursive: true, force: true }); + } + }); + + test("the re-launched run keeps the exit code", async () => { + const cwd = await workspace({ ".env": "CENTRS_INSECURE=1\n" }); + try { + const res = await runIn(cwd, ["no-such-command"]); + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("input/invalid-command"); + } finally { + await rm(cwd, { recursive: true, force: true }); + } + }); + }); + test("explain says out loud when a piped script was NOT the input", async () => { // The positional wins (the arguments asked for it), but the result carries // `usage/stdin-ignored` so the dropped pipe is never silent. Proving the diff --git a/test/integration/dotenv-relaunch-signals.test.ts b/test/integration/dotenv-relaunch-signals.test.ts new file mode 100644 index 00000000..dc8be30c --- /dev/null +++ b/test/integration/dotenv-relaunch-signals.test.ts @@ -0,0 +1,119 @@ +/** + * #666 / PR #674 review: SIGINT through the `.env` re-launch. + * + * Network-free, so it runs in the fast `bun test` gate like the CLI smoke + * tier. A `.env` in the cwd makes the entry re-launch under + * `bun --no-env-file`. A SIGINT sent to the launcher's PID must reach the + * child; one sent to the whole process group (a terminal's Ctrl-C) must reach + * it exactly once, since centrs treats a second Ctrl-C as "exit now". POSIX + * only: Windows has no process groups or SIGINT delivery by `kill`. + */ + +import { afterEach, describe, expect, test } from "bun:test"; +import { type ChildProcess, spawn } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const GUARD = join( + import.meta.dir, + "..", + "..", + "src", + "resolver", + "dotenv-guard.ts", +); + +const FIXTURE = ` +import { runWithoutDotenv } from ${JSON.stringify(GUARD)}; +process.exitCode = await runWithoutDotenv(async () => { + if (process.argv[2] === "count") { + let count = 0; + process.on("SIGINT", () => { count += 1; }); + console.log("ready"); + await Bun.sleep(1500); + console.log("sigint=" + count); + return 0; + } + console.log("ready"); + await Bun.sleep(10_000); + console.log("not interrupted"); + return 0; +}); +`; + +const dirs: string[] = []; +afterEach(async () => { + await Promise.all( + dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +interface Run { + child: ChildProcess; + ready: Promise; + done: Promise<{ code: number | null; stdout: string }>; +} + +async function launch(mode: "count" | "wait"): Promise { + const dir = await mkdtemp(join(tmpdir(), "centrs-dotenv-signals-")); + dirs.push(dir); + await writeFile(join(dir, "fixture.ts"), FIXTURE); + await writeFile(join(dir, ".env"), "CENTRS_DOTENV_SIGNAL_TEST=1\n"); + // detached: the launcher leads its own process group, as a shell job does. + const child = spawn(process.execPath, [join(dir, "fixture.ts"), mode], { + cwd: dir, + detached: true, + env: { PATH: process.env["PATH"] ?? "", HOME: dir }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let markReady: () => void = () => {}; + const ready = new Promise((resolve) => { + markReady = resolve; + }); + child.stdout?.on("data", (chunk: Buffer) => { + stdout += chunk.toString(); + if (stdout.includes("ready")) markReady(); + }); + const done = new Promise<{ code: number | null; stdout: string }>( + (resolve) => { + child.on("exit", (code, signal) => + resolve({ code: signal === null ? code : -1, stdout }), + ); + }, + ); + return { child, ready, done }; +} + +describe.skipIf(process.platform === "win32")( + "SIGINT through the .env re-launch", + () => { + test("a SIGINT sent to the launcher's PID stops the child (130)", async () => { + const run = await launch("wait"); + await run.ready; + process.kill(run.child.pid as number, "SIGINT"); + const { code, stdout } = await run.done; + expect(stdout).not.toContain("not interrupted"); + expect(code).toBe(130); + }, 15_000); + + test("a PID SIGINT reaches a handling child once", async () => { + const run = await launch("count"); + await run.ready; + process.kill(run.child.pid as number, "SIGINT"); + const { code, stdout } = await run.done; + expect(stdout).toContain("sigint=1"); + expect(code).toBe(0); + }, 15_000); + + test("a process-group SIGINT (terminal Ctrl-C) reaches the child once", async () => { + const run = await launch("count"); + await run.ready; + process.kill(-(run.child.pid as number), "SIGINT"); + const { code, stdout } = await run.done; + expect(stdout).toContain("sigint=1"); + expect(code).toBe(0); + }, 15_000); + }, +); diff --git a/test/integration/mcp-stdio-password-file.test.ts b/test/integration/mcp-stdio-password-file.test.ts new file mode 100644 index 00000000..a7bfb687 --- /dev/null +++ b/test/integration/mcp-stdio-password-file.test.ts @@ -0,0 +1,108 @@ +/** + * #672 / #603: `centrs mcp` over real stdio, keyed from a file. + * + * Network-free (no CHR), so it runs in the fast `bun test` gate like the CLI + * smoke tier. The server gets an encrypted throwaway CDB and only the key + * file's path: the key is never in argv or the environment. Deleting the file + * makes the next call return `cdb/password-unavailable`, and the server keeps + * serving. + */ + +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { addDevice, initCdb, loadCdb } from "../../src/devices.ts"; + +const CLI_ENTRY = join(import.meta.dir, "..", "..", "src", "cli.ts"); +const KEY = "mcp-stdio-cdb-key-never-in-argv"; + +const dirs: string[] = []; +afterEach(async () => { + await Promise.all( + dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +interface Envelope { + ok: boolean; + data?: unknown; + error?: { code?: string; context?: Record }; +} + +async function callTool( + client: Client, + name: string, + args: Record, +): Promise<{ envelope: Envelope; text: string }> { + const result = (await client.callTool({ name, arguments: args })) as { + content: Array<{ type: string; text: string }>; + }; + const text = result.content.find((part) => part.type === "text")?.text; + if (text === undefined) throw new Error(`${name} returned no text`); + return { envelope: JSON.parse(text) as Envelope, text }; +} + +describe("centrs mcp keyed from a password file (stdio)", () => { + test("no key in argv or env; a deleted file fails the next call, not the server", async () => { + const dir = await mkdtemp(join(tmpdir(), "centrs-mcp-keyfile-")); + dirs.push(dir); + const cdbFile = join(dir, "winbox.cdb"); + const keyFile = join(dir, "cdb_key"); + await writeFile(keyFile, `${KEY}\n`); + // A repo `.env` in the server's cwd: the entry re-launches under + // `--no-env-file` (#666), so this also proves stdio survives that. + await writeFile(join(dir, ".env"), "CENTRS_INSECURE=1\n"); + await initCdb({ cdbFile, encrypt: true, cdbPasswordFile: keyFile }); + await addDevice({ + cdb: await loadCdb({ cdbFile, cdbPasswordFile: keyFile }), + target: "192.0.2.10", + user: "ops", + password: "router-secret", + comment: "identity=keyfile-lab", + }); + + const args = [CLI_ENTRY, "mcp", "--cdb-file", cdbFile]; + const env: Record = { + PATH: process.env["PATH"] ?? "", + HOME: dir, + XDG_CONFIG_HOME: dir, + CENTRS_CDB_PASSWORD_FILE: keyFile, + }; + expect(args.join(" ")).not.toContain(KEY); + expect(Object.values(env).join(" ")).not.toContain(KEY); + + const transport = new StdioClientTransport({ + command: "bun", + args, + env, + cwd: dir, + stderr: "pipe", + }); + const client = new Client({ name: "password-file-test", version: "0" }); + await client.connect(transport); + try { + const listed = await callTool(client, "centrs_devices", { op: "list" }); + expect(listed.envelope.ok).toBe(true); + expect(listed.text).toContain("keyfile-lab"); + expect(listed.text).not.toContain(KEY); + + await rm(keyFile); + const after = await callTool(client, "centrs_devices", { op: "list" }); + expect(after.envelope.ok).toBe(false); + expect(after.envelope.error?.code).toBe("cdb/password-unavailable"); + expect(after.envelope.error?.context).toMatchObject({ path: keyFile }); + + // The server is still serving: restoring the file works again. + await writeFile(keyFile, KEY); + const restored = await callTool(client, "centrs_devices", { + op: "list", + }); + expect(restored.envelope.ok).toBe(true); + } finally { + await client.close(); + } + }, 30_000); +}); diff --git a/test/integration/password-file-types.test.ts b/test/integration/password-file-types.test.ts new file mode 100644 index 00000000..1daeefe8 --- /dev/null +++ b/test/integration/password-file-types.test.ts @@ -0,0 +1,61 @@ +/** + * #672 / PR #674 review: a password-file path that is not a regular file. + * + * Network-free, so it runs in the fast `bun test` gate like the CLI smoke + * tier. POSIX only (it makes a FIFO with `mkfifo` and reads `/dev/zero`), + * which is why it lives here and not in `test/unit/`. A FIFO with no writer + * used to block the synchronous read, stalling a whole MCP process, and a + * device would stream forever. Both are refused without reading. + */ + +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { CentrsError } from "../../src/errors.ts"; +import { + CDB_PASSWORD_SECRET, + readSecretFile, + TARGET_PASSWORD_SECRET, +} from "../../src/resolver/secret-source.ts"; + +const dirs: string[] = []; +afterEach(async () => { + await Promise.all( + dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +describe.skipIf(process.platform === "win32")( + "password files that are not regular files", + () => { + test("a FIFO or a device is refused at once, not read", async () => { + const dir = await mkdtemp(join(tmpdir(), "centrs-password-types-")); + dirs.push(dir); + const fifo = join(dir, "fifo"); + expect(Bun.spawnSync(["mkfifo", fifo]).exitCode).toBe(0); + for (const [spec, code] of [ + [CDB_PASSWORD_SECRET, "cdb/password-unavailable"], + [TARGET_PASSWORD_SECRET, "auth/password-unavailable"], + ] as const) { + for (const path of [fifo, "/dev/zero"]) { + let error: unknown; + try { + readSecretFile(spec, { + kind: "file", + path, + source: { kind: "file", key: spec.fileEnvKey }, + }); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(CentrsError); + expect((error as CentrsError).code).toBe(code); + expect((error as CentrsError).summary).toContain( + "is not a regular file", + ); + } + } + }, 5_000); + }, +); diff --git a/test/integration/rest-retrieve.test.ts b/test/integration/rest-retrieve.test.ts index 7a36486f..b8ee8715 100644 --- a/test/integration/rest-retrieve.test.ts +++ b/test/integration/rest-retrieve.test.ts @@ -8,6 +8,7 @@ import { encodeOpenWinBoxCdb, winBoxCdbRecordType, } from "../../src/data/winbox-cdb.ts"; +import { encryptCdb } from "../../src/devices.ts"; import { exampleIds, isChrIntegrationEnabled, @@ -543,6 +544,77 @@ describeFast("REST retrieve against CHR", () => { "not reached: transport/connection-refused", ); + // 16d. The CDB key from a file (#672): an encrypted CDB, unlocked by + // --cdb-password-file and then by CENTRS_CDB_PASSWORD_FILE. + const secretsDir = await mkdtemp(join(tmpdir(), "centrs-retrieve-key-")); + const keyFile = join(secretsDir, "cdb_key"); + const cdbKey = "retrieve-cdb-key-from-file"; + await writeFile(keyFile, `${cdbKey}\n`); + const encryptedCdb = join(secretsDir, "winbox.cdb"); + await writeFile(encryptedCdb, await Bun.file(cdbPath).bytes()); + await encryptCdb({ cdbFile: encryptedCdb, cdbPasswordFile: keyFile }); + const keyedByFlag = await expectRetrieveSuccess(consoleCapture, [ + "retrieve", + chr.restUrl, + "/system/resource", + "--cdb-file", + encryptedCdb, + "--cdb-password-file", + keyFile, + ]); + expect(keyedByFlag.meta.settings.password?.kind).toBe("cdb"); + expect(JSON.stringify(keyedByFlag)).not.toContain(cdbKey); + const previousKeyFile = process.env["CENTRS_CDB_PASSWORD_FILE"]; + process.env["CENTRS_CDB_PASSWORD_FILE"] = keyFile; + try { + const keyedByEnv = await expectRetrieveSuccess(consoleCapture, [ + "retrieve", + chr.restUrl, + "/system/resource", + "--cdb-file", + encryptedCdb, + ]); + expect(keyedByEnv.meta.target.source?.kind).toBe("cdb"); + } finally { + if (previousKeyFile === undefined) + delete process.env["CENTRS_CDB_PASSWORD_FILE"]; + else process.env["CENTRS_CDB_PASSWORD_FILE"] = previousKeyFile; + } + + // 16e. The router password from a file (#672), with no CDB. The lab's + // admin password may be empty, which a password file refuses, so read + // as a dedicated user that has one. + const fileUser = "file-reader"; + const filePassword = "routeros-pw-from-file"; + const addUser = await fetch(`${chr.restUrl}/rest/user`, { + method: "PUT", + headers: { + authorization: `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + name: fileUser, + group: "read", + password: filePassword, + }), + }); + expect(addUser.ok).toBe(true); + const passwordFile = join(secretsDir, "routeros_pw"); + await writeFile(passwordFile, `${filePassword}\n`); + const passwordByFile = await expectRetrieveSuccess(consoleCapture, [ + "retrieve", + chr.restUrl, + "/system/resource", + "--username", + fileUser, + "--password-file", + passwordFile, + ]); + expect(passwordByFile.meta.settings.password).toMatchObject({ + kind: "file", + }); + expect(JSON.stringify(passwordByFile)).not.toContain(filePassword); + // 16c. The gate passed and a later step failed (GH#435): a byte budget // smaller than the answer fails after a validated read, and the // envelope reports the gate that passed. @@ -644,7 +716,7 @@ describeFast("REST retrieve against CHR", () => { quickChrName: chr.name, requestedChannel: started.requestedChannel, requestedVersion: started.requestedVersion, - exampleIds: [...exampleIds(20), "16b", "16c"], + exampleIds: [...exampleIds(20), "16b", "16c", "16d", "16e"], }); } finally { consoleCapture.restore(); diff --git a/test/unit/dotenv-guard.test.ts b/test/unit/dotenv-guard.test.ts new file mode 100644 index 00000000..6094d0bc --- /dev/null +++ b/test/unit/dotenv-guard.test.ts @@ -0,0 +1,208 @@ +/** + * #666: a working directory's `.env` never reaches centrs. When Bun loaded + * one, the entry re-launches under `bun --no-env-file` with the environment + * it was started with (`planDotenvRelaunch`). Subprocess coverage, including + * Bun's own startup settings, is in `test/integration/cli-smoke.test.ts`. + */ + +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + dotenvGuardWarning, + dotenvKeyNames, + planDotenvRelaunch, +} from "../../src/resolver/dotenv-guard.ts"; + +let dir: string; + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "centrs-dotenv-")); +}); + +afterEach(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +describe("dotenvKeyNames", () => { + test("reads names only: export, spaces, colon form, CR-only lines", () => { + const keys = dotenvKeyNames( + '# CENTRS_COMMENTED=1\nexport CENTRS_A=1\n CENTRS_B = "x y"\r\nCENTRS_C: colon\rCENTRS_D=cr\rnot a line\n', + ); + expect([...keys].sort()).toEqual([ + "CENTRS_A", + "CENTRS_B", + "CENTRS_C", + "CENTRS_D", + ]); + }); +}); + +describe("planDotenvRelaunch with the exec-time environment (Linux)", () => { + test("any key Bun added or changed is dropped; the child gets the launch env", () => { + const plan = planDotenvRelaunch({ + env: { + PATH: "/bin", + CENTRS_INSECURE: "1", + XDG_CONFIG_HOME: "/repo/cfg", + BUN_CONFIG_VERBOSE_FETCH: "curl", + NODE_ENV: "test", + }, + execArgv: [], + initialEnviron: new Map([["PATH", "/bin"]]), + }); + expect(plan?.env).toEqual({ PATH: "/bin" }); + expect(plan?.dropped).toEqual([ + "BUN_CONFIG_VERBOSE_FETCH", + "CENTRS_INSECURE", + "NODE_ENV", + "XDG_CONFIG_HOME", + ]); + }); + + test("an unchanged environment runs in place", () => { + expect( + planDotenvRelaunch({ + env: { CENTRS_INSECURE: "0" }, + execArgv: [], + initialEnviron: new Map([["CENTRS_INSECURE", "0"]]), + }), + ).toBeUndefined(); + }); + + test("an already --no-env-file process never re-launches", () => { + expect( + planDotenvRelaunch({ + env: { CENTRS_INSECURE: "1" }, + execArgv: ["--no-env-file"], + initialEnviron: new Map(), + }), + ).toBeUndefined(); + }); +}); + +describe("planDotenvRelaunch without it (macOS, Windows)", () => { + test("keys any Bun .env file names are dropped, whatever NODE_ENV says now", async () => { + await writeFile(join(dir, ".env"), "NODE_ENV=test\nPATH=/evil\n"); + await writeFile( + join(dir, ".env.development"), + "CENTRS_FORMAT=json\nXDG_CONFIG_HOME=/repo\n", + ); + await writeFile( + join(dir, ".env.local"), + "BUN_CONFIG_VERBOSE_FETCH: curl\r", + ); + const plan = planDotenvRelaunch({ + env: { + PATH: "/usr/bin", + NODE_ENV: "test", + CENTRS_FORMAT: "json", + XDG_CONFIG_HOME: "/repo", + BUN_CONFIG_VERBOSE_FETCH: "curl", + CENTRS_VIA: "ssh", + }, + cwd: dir, + execArgv: [], + initialEnviron: null, + platform: "darwin", + }); + expect(plan?.dropped).toEqual([ + "BUN_CONFIG_VERBOSE_FETCH", + "CENTRS_FORMAT", + "NODE_ENV", + "PATH", + "XDG_CONFIG_HOME", + ]); + // A named PATH may be the file's (a launch with no PATH): it becomes + // the system default, never the file's value. + expect(plan?.env).toEqual({ + PATH: "/usr/bin:/bin:/usr/sbin:/sbin", + CENTRS_VIA: "ssh", + }); + }); + + // PR #674 review: Bun allows a line break, even a blank line, between a + // key and its `=` or `:`. + test("a key whose separator is on a later line is still named", async () => { + await writeFile(join(dir, ".env"), "CENTRS_FORMAT\n\n= json\nNOPE\nB=1\n"); + const plan = planDotenvRelaunch({ + env: { CENTRS_FORMAT: "json", B: "1", NOPE: "shell" }, + cwd: dir, + execArgv: [], + initialEnviron: null, + }); + expect(plan?.dropped).toEqual(["B", "CENTRS_FORMAT"]); + }); + + test("Windows: names match case-insensitively; PATH resets under SystemRoot", async () => { + await writeFile(join(dir, ".env"), "path=C:\\evil\nCentrs_Insecure=1\n"); + const plan = planDotenvRelaunch({ + env: { + Path: "C:\\evil", + CENTRS_INSECURE: "1", + SystemRoot: "D:\\Win", + }, + cwd: dir, + execArgv: [], + initialEnviron: null, + platform: "win32", + }); + expect(plan?.dropped).toEqual(["CENTRS_INSECURE", "Path"]); + expect(plan?.env["SystemRoot"]).toBe("D:\\Win"); + expect(plan?.env["PATH"]).toStartWith("D:\\Win\\System32;D:\\Win;"); + expect(plan?.env["PATH"]).toContain("D:\\Win\\System32\\OpenSSH\\"); + expect(plan?.env["Path"]).toBeUndefined(); + }); + + // PR #674 review: `HOME` picks `centrs.env`, and a Windows shell often has + // none, so a repo's `HOME=.` plus `.config/tikoci/centrs.env` must not + // steer it. Without `/proc` a launch `HOME` looks the same, so it goes + // too, and the child falls back to the account's home (`os.homedir()`). + test("a .env HOME is dropped, with or without a launch HOME", async () => { + await writeFile(join(dir, ".env"), "HOME=.\nAPPDATA=.\n"); + for (const launchHome of [undefined, "/Users/ops"]) { + const plan = planDotenvRelaunch({ + env: { + PATH: "/usr/bin", + HOME: launchHome ?? ".", + APPDATA: ".", + }, + cwd: dir, + execArgv: [], + initialEnviron: null, + }); + expect(plan?.dropped).toEqual(["APPDATA", "HOME"]); + expect(plan?.env).toEqual({ PATH: "/usr/bin" }); + } + }); + + test("no .env files: run in place", () => { + expect( + planDotenvRelaunch({ + env: { CENTRS_INSECURE: "1" }, + cwd: dir, + execArgv: [], + initialEnviron: null, + }), + ).toBeUndefined(); + }); +}); + +describe("dotenvGuardWarning", () => { + test("names CENTRS_* keys only, never values; silent otherwise", () => { + const line = dotenvGuardWarning({ + env: {}, + dropped: ["CENTRS_CDB_PASSWORD_FILE", "DATABASE_URL"], + }); + expect(line).toStartWith("warning [settings/dotenv-ignored]: "); + expect(line).toContain("CENTRS_CDB_PASSWORD_FILE"); + expect(line).not.toContain("DATABASE_URL"); + expect(dotenvGuardWarning({ env: {}, dropped: ["PATH"] })).toContain( + "system default PATH", + ); + expect( + dotenvGuardWarning({ env: {}, dropped: ["DATABASE_URL"] }), + ).toBeUndefined(); + }); +}); diff --git a/test/unit/password-files.test.ts b/test/unit/password-files.test.ts new file mode 100644 index 00000000..00ee3176 --- /dev/null +++ b/test/unit/password-files.test.ts @@ -0,0 +1,588 @@ +/** + * #672: the CDB key and the target password read from a file + * (`--cdb-password-file` / `CENTRS_CDB_PASSWORD_FILE`, + * `--password-file` / `CENTRS_PASSWORD_FILE`), as `/run/secrets` provides. + */ + +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { btestServer } from "../../src/btest.ts"; +import { runDevicesCli } from "../../src/cli/devices.ts"; +import { parseExplainCliArgs } from "../../src/cli/explain.ts"; +import { discover } from "../../src/discover.ts"; +import { CentrsError } from "../../src/errors.ts"; +import { resolveExecuteRequest } from "../../src/execute.ts"; +import { + addDevice, + initCdb, + listDevices, + loadCdb, + resolveAuth, + resolveCdb, + retrieveEnvelope, +} from "../../src/index.ts"; +import { resolveMcpConfig } from "../../src/mcp/config.ts"; +import { loadAllowlistCdb } from "../../src/mcp/safety.ts"; +import { handleRetrieve } from "../../src/mcp/tools.ts"; +import { loadEnvFileDefaults } from "../../src/resolver/config-file.ts"; +import { + CDB_PASSWORD_SECRET, + chooseSecret, + readSecretFile, + TARGET_PASSWORD_SECRET, +} from "../../src/resolver/secret-source.ts"; +import { settingsPrint } from "../../src/settings.ts"; +import { resolveTransferRequest } from "../../src/transfer.ts"; +import { closedPort } from "./closed-port.ts"; +import { HERMETIC_ENV } from "./hermetic-env.ts"; + +const KEY = "cdb-key-Zq81-never-printed"; +const ROUTER_PW = "router-pw-Lk22-never-printed"; + +const dirs: string[] = []; +afterEach(async () => { + await Promise.all( + dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +async function sandbox(): Promise { + const dir = await mkdtemp(join(tmpdir(), "centrs-password-files-")); + dirs.push(dir); + return dir; +} + +async function caught(run: () => unknown): Promise { + try { + await run(); + } catch (error) { + if (error instanceof CentrsError) return error; + throw error; + } + throw new Error("expected a CentrsError"); +} + +describe("chooseSecret", () => { + test("value and file in one tier conflict; flags outrank env", () => { + expect(() => + chooseSecret(CDB_PASSWORD_SECRET, { value: "a", file: "/f" }, {}), + ).toThrow(expect.objectContaining({ code: "usage/conflicting-flags" })); + expect(() => + chooseSecret( + TARGET_PASSWORD_SECRET, + {}, + { CENTRS_PASSWORD: "a", CENTRS_PASSWORD_FILE: "/f" }, + ), + ).toThrow(expect.objectContaining({ code: "usage/conflicting-flags" })); + // A flag beats an image-wide env default without a conflict. + expect( + chooseSecret( + CDB_PASSWORD_SECRET, + { value: "a" }, + { CENTRS_CDB_PASSWORD_FILE: "/run/secrets/k" }, + ), + ).toMatchObject({ kind: "value", source: { kind: "cli" } }); + expect( + chooseSecret( + CDB_PASSWORD_SECRET, + { file: "/f" }, + { CENTRS_CDB_PASSWORD: "a" }, + ), + ).toMatchObject({ + kind: "file", + path: "/f", + source: { kind: "file", key: "--cdb-password-file" }, + }); + }); + + test("an empty *_FILE env value counts as unset", () => { + expect( + chooseSecret( + CDB_PASSWORD_SECRET, + {}, + { CENTRS_CDB_PASSWORD_FILE: "", CENTRS_CDB_PASSWORD: "v" }, + ), + ).toMatchObject({ kind: "value", value: "v" }); + }); +}); + +describe("readSecretFile", () => { + test("strips one trailing newline, like --password-stdin", async () => { + const dir = await sandbox(); + const read = (path: string) => + readSecretFile(CDB_PASSWORD_SECRET, { + kind: "file", + path, + source: { kind: "file", key: "CENTRS_CDB_PASSWORD_FILE" }, + }); + for (const [body, expected] of [ + [`${KEY}\n`, KEY], + [`${KEY}\r\n`, KEY], + [`${KEY}\n\n`, `${KEY}\n`], + [` ${KEY} `, ` ${KEY} `], + ] as const) { + const path = join(dir, "k"); + await writeFile(path, body); + expect(read(path)).toBe(expected); + } + }); + + test("missing, empty and BOM files are unavailable; errors name the path only", async () => { + const dir = await sandbox(); + const missing = join(dir, "missing"); + const empty = join(dir, "empty"); + const bom = join(dir, "bom"); + await writeFile(empty, "\n"); + await writeFile(bom, `${KEY}`); + for (const path of [missing, empty, bom]) { + const error = await caught(() => + readSecretFile(TARGET_PASSWORD_SECRET, { + kind: "file", + path, + source: { kind: "file", key: "CENTRS_PASSWORD_FILE" }, + }), + ); + expect(error.code).toBe("auth/password-unavailable"); + expect(error.context).toMatchObject({ + path, + source: "CENTRS_PASSWORD_FILE", + }); + expect(JSON.stringify(error.toJSON?.() ?? error)).not.toContain(KEY); + } + }); +}); + +describe("CDB key from a file", () => { + async function encryptedCdb() { + const dir = await sandbox(); + const cdbFile = join(dir, "winbox.cdb"); + const keyFile = join(dir, "cdb_key"); + await writeFile(keyFile, `${KEY}\n`); + await initCdb({ cdbFile, encrypt: true, cdbPasswordFile: keyFile }); + const cdb = await loadCdb({ cdbFile, cdbPasswordFile: keyFile }); + await addDevice({ + cdb, + target: "10.9.9.9", + user: "ops", + password: ROUTER_PW, + }); + return { dir, cdbFile, keyFile }; + } + + test("init --encrypt, load and write use the file; meta shows the source, never the key", async () => { + const { cdbFile, keyFile } = await encryptedCdb(); + const cdb = await loadCdb({ + cdbFile, + env: { CENTRS_CDB_PASSWORD_FILE: keyFile }, + }); + expect(cdb.encrypted).toBe(true); + expect(cdb.entries.map((entry) => entry.target)).toEqual(["10.9.9.9"]); + const envelope = listDevices({ cdb }); + expect(envelope.meta.settings["cdbPassword"]).toEqual({ + kind: "file", + key: "CENTRS_CDB_PASSWORD_FILE", + }); + const text = JSON.stringify(envelope); + expect(text).not.toContain(KEY); + expect(text).not.toContain(ROUTER_PW); + }); + + test("the file is read on each load: deleting it fails the next load", async () => { + const { cdbFile, keyFile } = await encryptedCdb(); + const env = { CENTRS_CDB_PASSWORD_FILE: keyFile }; + await loadCdb({ cdbFile, env }); + await rm(keyFile); + const error = await caught(() => loadCdb({ cdbFile, env })); + expect(error.code).toBe("cdb/password-unavailable"); + expect(error.context).toMatchObject({ path: keyFile }); + }); + + test("a missing key file with an open or absent CDB is a warning, not an error", async () => { + const dir = await sandbox(); + const missing = join(dir, "not-mounted"); + const env = { HOME: dir, CENTRS_CDB_PASSWORD_FILE: missing }; + // Absent default CDB: created open, and the run succeeds. + const created = await loadCdb({ env }); + expect(created.encrypted).toBe(false); + const warning = created.warnings.find( + (entry) => entry.code === "cdb/password-not-needed", + ); + expect(warning?.context).toMatchObject({ path: missing, exists: false }); + // Open CDB, file present: not read, still the same warning. + const present = join(dir, "present"); + await writeFile(present, KEY); + const open = await loadCdb({ + env: { HOME: dir, CENTRS_CDB_PASSWORD_FILE: present }, + }); + expect(open.encrypted).toBe(false); + expect( + open.warnings.find((entry) => entry.code === "cdb/password-not-needed") + ?.context, + ).toMatchObject({ exists: true }); + expect(JSON.stringify(open.warnings)).not.toContain(KEY); + }); + + test("a blanked image-wide key file (empty value) is unset: no warning", async () => { + // app-t3code blanks `CENTRS_CDB_PASSWORD_FILE=` on Docker without the + // secret mounted; an open CDB must then load quietly. + const dir = await sandbox(); + const cdb = await loadCdb({ + env: { HOME: dir, CENTRS_CDB_PASSWORD_FILE: "" }, + }); + expect(cdb.encrypted).toBe(false); + expect(cdb.settings.cdbPassword.provided).toBe(false); + expect( + cdb.warnings.filter((entry) => entry.code === "cdb/password-not-needed"), + ).toEqual([]); + }); + + test("an encrypted CDB with a missing key file is cdb/password-unavailable", async () => { + const { dir, cdbFile } = await encryptedCdb(); + const error = await caught(() => + loadCdb({ cdbFile, cdbPasswordFile: join(dir, "gone") }), + ); + expect(error.code).toBe("cdb/password-unavailable"); + expect(error.remediation).not.toMatch(/ask the user/i); + }); + + test("centrs.env never supplies a *_FILE path", async () => { + const dir = await sandbox(); + await Bun.write( + join(dir, "tikoci", "centrs.env"), + "CENTRS_CDB_PASSWORD_FILE=/home/u/.ssh/id_ed25519\nCENTRS_PASSWORD_FILE=/x\nCENTRS_FORMAT=json\n", + ); + const config = await loadEnvFileDefaults({ XDG_CONFIG_HOME: dir }); + expect(config).toEqual({ CENTRS_FORMAT: "json" }); + }); +}); + +describe("target password from a file", () => { + const record = { + target: "10.9.9.9", + identity: "r1", + username: "ops", + password: "record-pw", + recordIndex: 0, + overrides: {}, + warnings: [], + }; + + test("outranks the CDB record and reports a file source", async () => { + const dir = await sandbox(); + const file = join(dir, "pw"); + await writeFile(file, `${ROUTER_PW}\n`); + const auth = resolveAuth({}, { CENTRS_PASSWORD_FILE: file }, record); + expect(auth.password).toBe(ROUTER_PW); + expect(auth.passwordSource).toEqual({ + kind: "file", + key: "CENTRS_PASSWORD_FILE", + }); + }); + + test("a missing file is an error, never a fall back to the record", async () => { + const dir = await sandbox(); + const error = await caught(() => + resolveAuth({ passwordFile: join(dir, "nope") }, {}, record), + ); + expect(error.code).toBe("auth/password-unavailable"); + }); + + test("the password never appears in a retrieve envelope", async () => { + const dir = await sandbox(); + const file = join(dir, "pw"); + await writeFile(file, ROUTER_PW); + const port = closedPort(); + const envelope = await retrieveEnvelope( + { + targetInput: `http://127.0.0.1:${port}`, + path: "/system/resource", + username: "admin", + passwordFile: file, + }, + HERMETIC_ENV, + ); + expect(envelope.ok).toBe(false); + expect(envelope.meta.settings["password"]).toEqual({ + kind: "file", + key: "--password-file", + }); + expect(JSON.stringify(envelope)).not.toContain(ROUTER_PW); + }); +}); + +describe("centrs mcp", () => { + test("keeps the key file's path, not its contents, and re-reads it per load", async () => { + const dir = await sandbox(); + const cdbFile = join(dir, "winbox.cdb"); + const keyFile = join(dir, "cdb_key"); + await writeFile(keyFile, KEY); + await initCdb({ cdbFile, encrypt: true, cdbPasswordFile: keyFile }); + const config = resolveMcpConfig({ + cdbFile, + env: { CENTRS_CDB_PASSWORD_FILE: keyFile }, + }); + expect(config.cdbPassword).toBeUndefined(); + expect(config.cdbPasswordFile).toBe(keyFile); + expect(JSON.stringify(config)).not.toContain(KEY); + expect((await loadAllowlistCdb(config)).encrypted).toBe(true); + await rm(keyFile); + const error = await caught(() => loadAllowlistCdb(config)); + expect(error.code).toBe("cdb/password-unavailable"); + }); + + // PR #674 review: retrieve ignored the server's configured env and read + // the process-wide one, so it could pick another password file. + test("retrieve (single and group) reads the password file from config.env", async () => { + const dir = await sandbox(); + const cdbFile = join(dir, "winbox.cdb"); + await initCdb({ cdbFile }); + await addDevice({ + cdb: await loadCdb({ cdbFile }), + target: `http://127.0.0.1:${closedPort()}`, + user: "ops", + comment: "identity=lab", + group: "labs", + }); + const missing = join(dir, "configured-not-mounted"); + const config = resolveMcpConfig({ + cdbFile, + env: { ...HERMETIC_ENV, CENTRS_PASSWORD_FILE: missing }, + }); + for (const args of [ + { target: "lab", path: "/system/resource" }, + { group: "labs", path: "/system/resource" }, + ]) { + const text = JSON.stringify( + await handleRetrieve({ ...args, timeout: "2s" }, config), + ); + expect(text).toContain("auth/password-unavailable"); + // As it appears inside JSON (Windows backslashes are escaped). + expect(text).toContain(JSON.stringify(missing).slice(1, -1)); + } + }); + + test("value and file both set is a startup usage error", () => { + expect(() => + resolveMcpConfig({ + env: { + CENTRS_CDB_PASSWORD: "v", + CENTRS_CDB_PASSWORD_FILE: "/run/secrets/k", + }, + }), + ).toThrow(expect.objectContaining({ code: "usage/conflicting-flags" })); + }); +}); + +describe("review follow-ups (#674)", () => { + test("btest server: a missing file or a conflict is an error envelope", async () => { + const dir = await sandbox(); + const missing = await btestServer({ + username: "u", + passwordFile: join(dir, "nope"), + env: {}, + }); + expect(missing.ok).toBe(false); + if (!missing.ok) { + expect(missing.error.code).toBe("auth/password-unavailable"); + } + const conflict = await btestServer({ + username: "u", + password: "p", + passwordFile: join(dir, "nope"), + env: {}, + }); + expect(conflict.ok).toBe(false); + if (!conflict.ok) + expect(conflict.error.code).toBe("usage/conflicting-flags"); + }); + + // PR #674 review: btest reported `meta.settings: {}` on every path. + test("btest server reports the password file's source, never its value", async () => { + const dir = await sandbox(); + const file = join(dir, "pw"); + await writeFile(file, `${ROUTER_PW}\n`); + const envelope = await btestServer({ + username: "ops", + passwordFile: file, + bind: "127.0.0.1", + port: 0, + durationMs: 10, + env: {}, + }); + expect(envelope.ok).toBe(true); + expect(envelope.meta.settings["password"]).toEqual({ + kind: "file", + key: "--password-file", + }); + expect(envelope.meta.settings["username"]).toBeDefined(); + expect(JSON.stringify(envelope)).not.toContain(ROUTER_PW); + const open = await btestServer({ + authenticate: false, + bind: "127.0.0.1", + port: 0, + durationMs: 10, + env: {}, + }); + expect(open.meta.settings).toEqual({}); + }); + + // PR #674 review: an open server uses no credential, so an image-wide + // password file it cannot read must not stop it. + test("btest server --no-authenticate reads no password file", async () => { + const dir = await sandbox(); + const envelope = await btestServer({ + authenticate: false, + bind: "127.0.0.1", + port: 0, + durationMs: 10, + env: { CENTRS_PASSWORD_FILE: join(dir, "not-mounted") }, + }); + expect(envelope.ok).toBe(true); + }); + + test("discover --save: a key-source conflict is an envelope, before listening", async () => { + let listened = false; + const envelope = await discover({ + save: true, + cdbPassword: "v", + cdbPasswordFile: "/run/secrets/k", + env: {}, + listen: async () => { + listened = true; + throw new Error("must not listen"); + }, + }); + expect(listened).toBe(false); + expect(envelope.ok).toBe(false); + if (!envelope.ok) + expect(envelope.error.code).toBe("usage/conflicting-flags"); + }); + + test("an env key file pins the lookup only when the CDB exists", async () => { + const home = await sandbox(); + const keyFile = join(home, "cdb_key"); + await writeFile(keyFile, KEY); + const env = { HOME: home, CENTRS_CDB_PASSWORD_FILE: keyFile }; + const input = { targetInput: "router.example.net" }; + // No CDB: literal host, nothing created (an image-wide default is safe). + expect(await resolveCdb(input, env)).toBeUndefined(); + const cdbFile = join(home, ".config", "tikoci", "winbox.cdb"); + expect(await Bun.file(cdbFile).exists()).toBe(false); + // Encrypted CDB present: a name it lacks is a miss, as with CENTRS_CDB_PASSWORD. + await mkdir(join(home, ".config", "tikoci"), { recursive: true }); + await initCdb({ cdbFile, encrypt: true, cdbPasswordFile: keyFile }); + const error = await caught(() => resolveCdb(input, env)); + expect(error.code).toBe("cdb/not-found-target"); + }); + + test("offline explain treats both file flags as live-only", () => { + expect( + parseExplainCliArgs(["/ip/route", "--password-file", "/x"]), + ).toMatchObject({ connectionFlag: "--password-file" }); + expect( + parseExplainCliArgs(["/ip/route", "--cdb-password-file", "/x"]), + ).toMatchObject({ connectionFlag: "--cdb-password-file" }); + }); + + test("settings print and a plain devices init say a key file was not needed", async () => { + const dir = await sandbox(); + const cdbFile = join(dir, "winbox.cdb"); + const missing = join(dir, "not-mounted"); + const init = await initCdb({ cdbFile, cdbPasswordFile: missing }); + expect(init.warnings).toEqual([ + expect.objectContaining({ + code: "cdb/password-not-needed", + context: expect.objectContaining({ exists: false }), + }), + ]); + const printed = await settingsPrint({ + cdbFile, + cdbPasswordFile: missing, + env: { XDG_CONFIG_HOME: dir, HOME: dir }, + }); + expect(printed.warnings.map((warning) => warning.code)).toContain( + "cdb/password-not-needed", + ); + }); + + test("devices: a key-source conflict still prints a JSON envelope", async () => { + const dir = await sandbox(); + const errors: string[] = []; + const spy = spyOn(console, "error").mockImplementation((line) => { + errors.push(String(line)); + }); + try { + const code = await runDevicesCli([ + "list", + "--cdb-file", + join(dir, "winbox.cdb"), + "--cdb-password", + "v", + "--cdb-password-file", + join(dir, "k"), + "--format", + "json", + ]); + expect(code).toBe(1); + } finally { + spy.mockRestore(); + } + const envelope = JSON.parse(errors.join("\n")) as { + ok: boolean; + error: { code: string }; + }; + expect(envelope.ok).toBe(false); + expect(envelope.error.code).toBe("usage/conflicting-flags"); + }); +}); + +// PR #674 review: batch ssh (`execute --via ssh`, sftp/scp transfers) never +// sends a password, so a password file it cannot read must not stop a key +// login. The source is still named (the "password not sent" tips use it); +// a password transport still fails on the missing file. +describe("batch ssh reads no password file", () => { + const env = { + ...HERMETIC_ENV, + CENTRS_USERNAME: "admin", + CENTRS_PASSWORD_FILE: "/nonexistent/centrs-batch-ssh-pw", + }; + + test("execute --via ssh resolves; --via rest-api fails on the file", async () => { + const request = { + targetInput: "192.0.2.10", + command: "/system/identity/print", + }; + const ssh = await resolveExecuteRequest({ ...request, via: "ssh" }, env, { + config: {}, + }); + expect(ssh.auth.passwordProvided).toBe(true); + expect(ssh.auth.passwordSource).toEqual({ + kind: "file", + key: "CENTRS_PASSWORD_FILE", + }); + await expect( + resolveExecuteRequest({ ...request, via: "rest-api" }, env, { + config: {}, + }), + ).rejects.toMatchObject({ code: "auth/password-unavailable" }); + }); + + test("sftp transfer resolves; a rest transfer fails on the file", async () => { + const request = { + verb: "download" as const, + targetInput: "192.0.2.10", + remote: "flash/x.rsc", + local: "-", + }; + const sftp = await resolveTransferRequest({ ...request, via: "sftp" }, env); + expect(sftp.auth.passwordSource).toEqual({ + kind: "file", + key: "CENTRS_PASSWORD_FILE", + }); + await expect( + resolveTransferRequest({ ...request, via: "rest" }, env), + ).rejects.toMatchObject({ code: "auth/password-unavailable" }); + }); +}); diff --git a/test/unit/settings-registry.test.ts b/test/unit/settings-registry.test.ts index 306263c9..c12331fd 100644 --- a/test/unit/settings-registry.test.ts +++ b/test/unit/settings-registry.test.ts @@ -73,11 +73,13 @@ describe("settingsManagedKeys registry", () => { }); describe("settingsRefusedKeys registry", () => { - test("covers exactly the 5 refused keys", () => { + test("covers exactly the 7 refused keys", () => { expect(settingsRefusedKeys.map((def) => def.attr).sort()).toEqual( [ "cdb-password", + "cdb-password-file", "password", + "password-file", "run-fast-integration", "skip-env-file", "username", diff --git a/test/unit/terminal.test.ts b/test/unit/terminal.test.ts index 74a88a9b..917b8b24 100644 --- a/test/unit/terminal.test.ts +++ b/test/unit/terminal.test.ts @@ -361,6 +361,31 @@ describe("resolveTerminalRequest transport gate", () => { ).rejects.toMatchObject({ code: "settings/invalid-via" }); }); + // PR #674 review: interactive ssh never uses a password, so a password + // file it cannot read must not stop an agent or key login. mac-telnet, + // which does use it, still fails on the missing file. + test("ssh reads no password file; mac-telnet does", async () => { + const env = { + ...noEnv, + CENTRS_USERNAME: "admin", + CENTRS_PASSWORD_FILE: "/nonexistent/centrs-terminal-pw", + }; + const ssh = await resolveTerminalRequest( + { targetInput: "192.0.2.10", via: "ssh" }, + env, + ); + expect(ssh.via).toBe("ssh"); + await expect( + resolveTerminalRequest( + { targetInput: "192.0.2.10", via: "ssh", passwordFile: "/nope" }, + noEnv, + ), + ).resolves.toMatchObject({ via: "ssh" }); + await expect( + resolveTerminalRequest({ targetInput: MAC, via: "mac-telnet" }, env), + ).rejects.toMatchObject({ code: "auth/password-unavailable" }); + }); + test("CENTRS_VIA=rest-api is gated the same way", async () => { await expect( resolveTerminalRequest({ targetInput: MAC }, { CENTRS_VIA: "rest-api" }),