vvauth 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,6 +25,8 @@ jobs:
25
25
  os: [ubuntu-latest, windows-latest]
26
26
  runs-on: ${{ matrix.os }}
27
27
  steps:
28
+ # Windows runners ship Git with core.autocrlf=true, which would turn LF sources into CRLF
29
+ - run: git config --global core.autocrlf false
28
30
  - uses: actions/checkout@v4
29
31
  - uses: actions/setup-go@v5
30
32
  with:
@@ -36,3 +38,15 @@ jobs:
36
38
  if: runner.os == 'Linux'
37
39
  - run: go build ./cmd/vauth
38
40
  if: runner.os == 'Windows'
41
+
42
+ runtime-node16:
43
+ runs-on: ubuntu-latest
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ - uses: actions/setup-node@v4
47
+ with:
48
+ node-version: '16.x'
49
+ - run: npm install --omit=dev --ignore-scripts --no-audit
50
+ - run: |
51
+ node --check index.js
52
+ node index.js version
@@ -0,0 +1,144 @@
1
+ # vvauth: CLI contract, API and tests
2
+
3
+ Back to the [README](README.md). Node (`npm install -g vvauth`) and Go
4
+ (`go install github.com/131/vvauth/v2/cmd/vauth@latest`, release binaries)
5
+ expose the same `vauth` command; everything below holds for both.
6
+
7
+ ## CLI contract
8
+
9
+ ```
10
+ vauth <command> [positional...] [--flag[=value]] [--ir://json]
11
+ ```
12
+
13
+ `env.map` names must match `^[A-Za-z_][A-Za-z0-9_]*$`; any other key is an
14
+ error, since names reach `export KEY=` unescaped. Flags may replace positionals (`vauth set GITLAB_TOKEN x` ≡
15
+ `vauth set --k=GITLAB_TOKEN --v=x`). `--flag` alone means `true`; `--flag=`,
16
+ `--flag=false` and `--flag=0` mean `false`. `--` ends flag parsing.
17
+
18
+ | Command | Effect | stdout |
19
+ | --- | --- | --- |
20
+ | `env [--source] [--renew]` | Resolve the `.vauthrc` environment (`env.map`, `env.paths`, `env.git`, `ssh-agent-crypt`) | JSON object with `--ir://json`; `export K='v'` lines with `--source`; JSON otherwise |
21
+ | `login [--source] [--renew]` | Authenticate, cache the token | `export VAULT_TOKEN='…'` with `--source`; nothing otherwise |
22
+ | `connect [--renew]` | Authenticate, print the token | raw token, no trailing newline (`--ir://json`: JSON string) |
23
+ | `run <command> [args...]` | Run a command with the resolved environment merged over the current one | the command's; exit code propagated |
24
+ | `dotenv` | Resolved environment as `K=v` lines | one `K=v` per line |
25
+ | `show` | Identity metadata merged over `.vauth_database` | JSON object |
26
+ | `set <key> <value>` | Store `KEY` (upper-cased) in `private/<login>/.vauth_database` | nothing |
27
+ | `unset <key>` | Remove a key from `.vauth_database` | nothing |
28
+ | `install` | Append the `venv` shell function to `~/.bashrc` | nothing |
29
+ | `version` (`--version`) | Build version | one line |
30
+
31
+ Diagnostics (`Vauth token: generated · 12h`, `export K=[redacted]`,
32
+ errors) go to stderr; stdout is machine-readable for every command. Exit code is
33
+ `0` on success, `1` on error (or the child's code for `run`). `--renew` discards
34
+ the cached token and authenticates again.
35
+
36
+ ```bash
37
+ vauth env --ir://json # {"VAULT_TOKEN":"…","VAULT_ADDR":"…","TF_HTTP_USERNAME":"…"}
38
+ source <(vauth env --source) # what the `venv` function does
39
+ vauth run -- terraform plan
40
+ ```
41
+
42
+ ## Environment
43
+
44
+ | Variable | Role |
45
+ | --- | --- |
46
+ | `VAUTHRC` | Explicit `.vauthrc` path; else `./.vauthrc`, then `~/.vauthrc` |
47
+ | `VAULT_ADDR` | Fallback when `.vauthrc` has no `vault_addr` |
48
+ | `VAULT_TOKEN` | Returned offline by Connect without renewal/persistence; LookupSelf validates online when the profile is requested |
49
+ | `SSH_AUTH_SOCK` | Agent for `ssh_auth` and for the token cache; on Windows, else Pageant (≥ 0.75), else the OpenSSH pipe |
50
+ | `VAUTH_USER_IDENTITY`, `VAUTH_USER_MAIL` | Agent key selector for the token cache (first key otherwise) |
51
+ | `CI` | When set, `env.gitlab` does not derive `CI_PROJECT_*` from `git remote get-url origin` |
52
+
53
+ Tokens are cached in `~/.vauth/tokens/<sha256(vault_addr, ssh_auth, jwt_auth)>.creds`,
54
+ armored with [ssh-agent-crypt](https://github.com/131/ssh-agent-crypt);
55
+ `token_cache: false` disables the cache. Without an agent, nothing is written.
56
+
57
+ ## Node module
58
+
59
+ Node.js 16 or newer is supported. CI checks JavaScript syntax and CLI/module
60
+ loading on Node 16 separately from the existing suite. JSON copies use
61
+ `nyks/object/structuredClone`, native when available with a JSON fallback.
62
+
63
+ ```js
64
+ const Vauth = require('vvauth');
65
+ const vauth = new Vauth(); // reads .vauthrc and process.env
66
+ const token = await vauth.Connect(); // Connect(renew = false)
67
+ const env = await vauth.Env(); // Env(source = false, renew = false) → object
68
+ await vauth.Login(false, true); // login(source, renew)
69
+ const profile = await vauth.Show(); // {...database, ...metadata}
70
+ await vauth.Set('KEY', 'value'); await vauth.Unset('KEY');
71
+ ```
72
+
73
+ Node extends the vauth-login client directly. `Connect`, `LookupSelf` and
74
+ `Request` are inherited, not forwarded through compatibility wrappers.
75
+ `GetProfile`, `Env`, `Show`, `Set`, `Unset`, `Login`, `Dotenv`, `Run` and
76
+ `PublishEnv` own the environment/profile behavior. `Version()` is static.
77
+ `RC`, `VAULT_ADDR` and `VAULT_TOKEN` are the inherited read-only getters.
78
+ `config` contains a mutable copy of only `env` and `ssh-agent-crypt`, with local
79
+ `env` macros expanded; the full frozen RC retains original values/macros.
80
+ vvauth does not reopen the selected configuration file.
81
+
82
+ `Env(true)`, `Login(true)`, `Dotenv()` and `PublishEnv()` write to stdout but do
83
+ not exit the SDK caller. `Run(command, ...args)` returns the child's exit code;
84
+ launch/authentication errors reject. Public methods use PascalCase without old
85
+ SDK aliases. The CLI independently keeps its lowercase commands and flags,
86
+ without reflecting inherited HTTP methods into CLI commands.
87
+
88
+ ## Go module
89
+
90
+ ```go
91
+ import vvauth "github.com/131/vvauth/v2"
92
+
93
+ v, err := vvauth.New() // .vauthrc + os.Environ()
94
+ token, err := v.Connect(false) // renew bool
95
+ env, err := v.Env(false) // *OrderedMap, deterministic output order
96
+ profile, err := v.GetProfile(false) // EntityID, Metadata, Database; Merged()
97
+ err = v.Login(source, renew)
98
+ err = v.Set("KEY", "value"); err = v.Unset("KEY")
99
+ code, err := v.Run("terraform", "plan")
100
+ v.PublishEnv(env) // export lines on stdout, redacted echo on stderr
101
+ ```
102
+
103
+ `Vauth` embeds `*vauthlogin.Vauth`; `Connect`, `LookupSelf` and `Request`,
104
+ the read-only `RC()`, `VAULT_ADDR()` and `VAULT_TOKEN()` readers, plus mutable
105
+ `Agent`, `TokenCache`, `CacheDir`, `HomeDir`, `Environ`, `Stderr`, `Now` and
106
+ `HTTPClient` settings, are owned by that client.
107
+ Use `New()` or supply the embedded client explicitly for isolated programmatic
108
+ use. `Config` holds only `Env`/`AgentCrypt`; `Stdout`/`Stdin` belong to vvauth.
109
+ `ParseConfig`, `ReplaceEnv`, `ShellEscape` and `FunctionExists` support environment and shell operations.
110
+ Construction consumes `RC()` directly: an independent JSON snapshot is decoded
111
+ into vvauth's own configuration, without reopening its file. The JSON map does
112
+ not retain YAML key order; `env.map` keys from this path have deterministic sorted
113
+ order. Explicit `OrderedMap.Set` calls and standalone `ParseConfig` keep their
114
+ insertion/YAML order. There is no second auth parser, token lifecycle, cache
115
+ implementation or HTTP transport in vvauth.
116
+
117
+ Node and Go consume vauth-login 1.1.5 and ssh-agent-crypt 1.4.2; Node uses nyks
118
+ 6.17.0. `env.gitlab` derives `CI_PROJECT_*` from the current working repository,
119
+ including when `VAUTHRC` is elsewhere. In CI, supplied variables are retained.
120
+ This is distinct from standalone Go `ParseConfig`, whose explicit file argument
121
+ identifies its Git directory.
122
+
123
+ The SDK keeps language-native conventions: promises/throws in Node,
124
+ values plus errors in Go. Node `Env(source, renew)` can publish directly;
125
+ Go `Env(renew)` returns an ordered map for `PublishEnv`. CLI `--ir://json`
126
+ outputs JSON without a trailing newline in both implementations. JSON object
127
+ key order is not part of the profile (`show`) contract.
128
+
129
+ ## Tests
130
+
131
+ Node and Go are tested against an in-process fake Vault (nonce, login, lookup,
132
+ renew, identity, KV) and a throwaway `ssh-agent`; both suites cover token reuse,
133
+ renewal in the final third, expiry, isolation of the cache by Vault and auth,
134
+ corrupt or plaintext cache rejection, identity selection and the interoperability
135
+ of the armored cache with the `ssh-agent-crypt` CLI.
136
+
137
+ ```bash
138
+ npm install && npm run eslint && npm test
139
+ gofmt -l . && go vet ./... && go test ./...
140
+ ```
141
+
142
+ CI (`test.yml`) runs both on Linux and Windows runners; `release.yml` builds the
143
+ static binaries on `v*` tags, signs the Windows one when `SIGNING_SERVER` is
144
+ set, and attaches `SHA256SUMS`.
package/README.md CHANGED
@@ -1,8 +1,53 @@
1
- Vault Creds manager
1
+ # vvauth
2
2
 
3
- This projects helps you log yourself in a HCL vault and retrieve VAULT_TOKEN through different auth methods
4
- * jwt login
5
- * ssh (with agent) login
3
+ Node.js 16 or newer is supported; CI includes Node 16 JavaScript syntax and
4
+ module/CLI loading checks alongside the existing test suites.
5
+
6
+ Resolve a shell environment from your Vault identity, private settings and
7
+ secrets. [vauth-login](https://github.com/131/vauth-login) handles authentication,
8
+ token caching and HTTP; vvauth owns profiles, macro expansion, KV operations
9
+ and environment publication. Available as a Node module/CLI and a Go module/CLI.
10
+ Both consume vauth-login 1.1.5's complete read-only RC and token/address readers;
11
+ vvauth copies its own sections for macro expansion without reopening the file.
12
+
13
+ # Installation
14
+
15
+ ```bash
16
+ # node
17
+ npm install -g vvauth
18
+
19
+ # go
20
+ go install github.com/131/vvauth/v2/cmd/vauth@latest
21
+
22
+ # static binary, linux
23
+ wget -O vauth https://github.com/131/vvauth/releases/latest/download/vauth-linux-amd64
24
+ chmod +x vauth
25
+
26
+ # static binary, windows (curl.exe ships with every supported Windows, cmd or PowerShell)
27
+ curl.exe -fsSL -o vauth.exe https://github.com/131/vvauth/releases/latest/download/vauth-windows-amd64.exe
28
+ ```
29
+
30
+ The [npm](https://www.npmjs.com/package/vvauth) module and the Go module ship
31
+ the same `vauth` command, flags and `.vauthrc`, and share the token cache.
32
+ Binaries are static, signed on Windows, with `SHA256SUMS` on every
33
+ [release](https://github.com/131/vvauth/releases); `vauth version` prints the
34
+ build version. On Windows, the SSH agent is `SSH_AUTH_SOCK` when set, else
35
+ Pageant (≥ 0.75, named pipe autodiscovery), else the OpenSSH agent pipe.
36
+
37
+ ## The `venv` shell function
38
+
39
+ A program cannot change the environment of the shell that started it, so the
40
+ `VAULT_TOKEN`, credentials and `env.map` variables that `vauth` resolves have
41
+ to be *sourced*. `vauth install` appends this one-liner to `~/.bashrc`:
42
+
43
+ ```bash
44
+ function venv() { source <(/usr/bin/env vauth env --source "$@"); }
45
+ ```
46
+
47
+ `venv` then loads the resolved environment into the current shell (`venv
48
+ --renew` forces a fresh token); the exported names are echoed to stderr with
49
+ their values redacted. In scripts or CI, without a shell to source into, use
50
+ `vauth run <command>`, `vauth env --ir://json` or `vauth dotenv` instead.
6
51
 
7
52
 
8
53
  # Vauth configuration
@@ -26,7 +71,7 @@ The configuration file should abide the following schema
26
71
  # vauth URL
27
72
  vault_addr: https://vauth.myserver.org
28
73
 
29
- # for vauth-auth-plugin-ssh, configure the binding role here
74
+ # SSH authentication role, consumed by vauth-login
30
75
  ssh_auth:
31
76
  role: $${env.VAUTH_USER_LOGIN}
32
77
  env:
@@ -46,49 +91,58 @@ env:
46
91
  ```
47
92
 
48
93
 
49
- # Installation
94
+ # Machine-readable environment
95
+
96
+ `vauth env --ir://json` writes the resolved environment as one JSON object on
97
+ stdout; diagnostics stay on stderr, so a caller can parse stdout directly.
98
+ CLI command spelling remains lowercase; public Node/Go SDK methods use the
99
+ same PascalCase names. Every command, flag, output and module signature is in
100
+ [API_and_tests.md](API_and_tests.md).
50
101
 
51
102
  ```bash
52
- npm install -g vvauth # node
53
- go install github.com/131/vvauth/v2/cmd/vauth@latest # go
103
+ vauth env --ir://json
54
104
  ```
55
105
 
56
- Both ship the same `vauth` command, flags and `.vauthrc`, and share the token
57
- cache. The Go binary has no runtime dependency; signed `vauth-windows-amd64.exe`
58
- and `vauth-linux-amd64` builds are attached to each
59
- [release](https://github.com/131/vvauth/releases). `vauth version` prints the
60
- build version.
61
106
 
62
- On Windows, the SSH agent is `SSH_AUTH_SOCK` when set, else Pageant (≥ 0.75,
63
- named pipe autodiscovery), else the OpenSSH agent pipe.
107
+ # Token cache
64
108
 
109
+ [vauth-login](https://github.com/131/vauth-login) owns the cache in
110
+ `~/.vauth/tokens/<session>.creds`, shared by Node and Go. It reuses, renews or
111
+ replaces cached tokens as needed. An inherited `VAULT_TOKEN` is returned as is,
112
+ without renewal or persistence; profile retrieval is an explicit separate step.
65
113
 
66
- # Credits
67
- * [Francois Leurent](https://github.com/131)
114
+ Each session file is armored using
115
+ [ssh-agent-crypt](https://github.com/131/ssh-agent-crypt) and your SSH agent’s
116
+ first key (`VAUTH_USER_IDENTITY`, then `VAUTH_USER_MAIL`, select another one).
117
+ Without an SSH agent, disk caching is disabled.
68
118
 
119
+ Set `token_cache: false` in `.vauthrc` to disable disk cache reads and writes.
69
120
 
70
- # Machine-readable environment
121
+ ## Force reauthentication
71
122
 
72
- `vauth env --ir://json` resolves the same environment as `vauth env --source`
73
- and asks the `cnyks` runner to write one JSON object to stdout. Diagnostic
74
- messages remain on stderr, so a caller can parse stdout directly.
123
+ `venv --renew` forces authentication, generates and caches a new token.
75
124
 
76
- ```bash
77
- vauth env --ir://json
78
- ```
79
125
 
126
+ ## Security audit
80
127
 
81
- # Token cache
128
+ The reports below describe the pre-integration implementation. This integration
129
+ uses vauth-login 1.1.5 without regenerating or rewriting their findings/scores.
82
130
 
83
- Tokens are cached in `~/.vauth/tokens/<session>.creds`, isolated by Vault and
84
- authentication. Tokens are reused, renewed within their lease’s final third, or
85
- replaced when expired. Existing `VAULT_TOKEN` takes precedence over cached tokens.
86
131
 
87
- Each session file is armored using `ssh-agent-crypt` and your SSH agent’s first
88
- key. Without an SSH agent, disk caching is disabled.
132
+ Two independent reviews of the design and of both implementations (Node, Go),
133
+ each scoring Coolness, Robustness and Safety out of 20:
134
+ [SECURITY_AUDIT_fable-5.1.md](SECURITY_AUDIT_fable-5.1.md) and
135
+ [SECURITY_AUDIT_gpt-6.1-sol.md](SECURITY_AUDIT_gpt-6.1-sol.md).
89
136
 
90
- Set `token_cache: false` in `.vauthrc` to disable disk cache reads and writes.
137
+ | Criterion | Codex (Claude Fable 5.1) | Codex (GPT 6.1) |
138
+ | --- | ---: | ---: |
139
+ | ✨ **Coolness** | 15/20 | 17/20 |
140
+ | Robustness | 16/20 | 11/20 |
141
+ | Safety | 14/20 | 10/20 |
91
142
 
92
- ## Force reauthentication
93
143
 
94
- `venv --renew` forces authentication, generates and caches a new token.
144
+ # Credits
145
+ * [Francois Leurent](https://github.com/131)
146
+ * [OpenAI](https://openai.com) Codex (GPT 6.1-sol), in collaboration
147
+ * [Anthropic](https://www.anthropic.com) Claude (Fable 5.1), in collaboration
148
+ * Code signing, courtesy of Essilor International
@@ -0,0 +1,88 @@
1
+ # vvauth: design review by Codex (Claude Fable 5.1)
2
+
3
+ Independent review of the design and of the Node and Go implementations of
4
+ [vvauth](README.md), scoring Coolness, Robustness and Safety out of 20. The
5
+ companion review is [SECURITY_AUDIT_gpt-6.1-sol.md](SECURITY_AUDIT_gpt-6.1-sol.md).
6
+
7
+ ## The design, as read
8
+
9
+ `vauth` turns a `.vauthrc` (YAML with `$${env.X}`, `$${profile.X}`,
10
+ `$${secrets.X}` macros) into a Vault token and a resolved environment. Two
11
+ authentication flows: `jwt_auth` (CI) and `ssh_auth`, where the agent signs a
12
+ nonce fetched from `auth/<path>/nonce`, so the user's SSH key is the identity
13
+ and nothing else is stored. The token is cached in
14
+ `~/.vauth/tokens/<sha256(vault_addr, ssh_auth, jwt_auth)>.creds`, armored with
15
+ ssh-agent-crypt (key derived from an agent signature), reused while valid,
16
+ renewed in the last third of its lease, replaced when expired or rejected.
17
+ `env --source` prints `export K='v'` lines for the `venv` shell function;
18
+ `--ir://json` prints one JSON object for automation. Node and Go share the
19
+ contract byte for byte (cache key, armor, outputs) and are cross-tested.
20
+
21
+ ## Strengths
22
+
23
+ - No long-lived secret on disk besides a Vault token that is itself encrypted
24
+ under the agent, with `0700`/`0600` modes, write-to-temp-then-rename, and a
25
+ cache that degrades to "not persisted" rather than "stored in clear".
26
+ - Correct lease handling: renewal only in the final third, `lookup-self` TTL
27
+ trusted over the local clock when the token is foreign, reauthentication only
28
+ on `400`/`403`, never on network failures (no accidental token storm).
29
+ - Secret values never reach stdout unescaped in `--source` mode
30
+ (`ShellEscape` single-quotes), `env.map` names are checked against
31
+ `^[A-Za-z_][A-Za-z0-9_]*$` before they reach `export`, and the shell echoes
32
+ `[redacted]`.
33
+ - The nonce is fetched fresh for every key tried; the agent only ever signs
34
+ server-provided data, no private key is handled by the tool.
35
+ - Two implementations with the same fake-Vault test matrix catch divergence;
36
+ the Go binary is static, signed, with `SHA256SUMS`; release runs the tests.
37
+
38
+ ## Weaknesses and remedies
39
+
40
+ 1. **`vault_addr` from the current directory redirects authentication.** A
41
+ hostile `.vauthrc` points to an attacker-controlled "Vault"; the tool then
42
+ fetches a nonce from it and has the agent sign it. The signature is over
43
+ attacker-chosen bytes (bounded to valid UTF-8 by the JSON transport, which
44
+ keeps it away from SSHSIG and SSH-userauth encodings, so no direct
45
+ cross-protocol reuse today), and the public key and role name are sent to
46
+ the attacker. *Remedy:* wrap the nonce in a vauth-specific preamble before
47
+ signing (as SSHSIG does), or require `https` plus a pinned allow-list of
48
+ Vault hosts in `~/.vauthrc`; at least surface the Vault address in the
49
+ `Vauth token:` status line on first contact. More generally, a
50
+ `./.vauthrc` from a cloned repository is trusted for everything; a cleaner
51
+ model would let it carry only the project part (`env.map`, `env.paths`,
52
+ `env.gitlab`) and keep `vault_addr`, `ssh_auth`, `jwt_auth` and
53
+ `ssh-agent-crypt` to `~/.vauthrc` or `VAUTHRC`.
54
+ 2. **Whoever reaches the agent socket reads the token cache.** By design of
55
+ ssh-agent-crypt; nothing in vvauth adds a second factor. *Remedy:* document
56
+ it next to `token_cache` and recommend `ssh-add -c` on the cache key
57
+ (`SSH_AGENT_CRYPT_KEY` lets a dedicated, confirmed key be chosen).
58
+ 3. **Macro expansion parity.** Go caps recursive expansion at 16 rounds; Node
59
+ (`nyks/string/replaceEnv`) recurses until the stack overflows on a
60
+ self-referencing value, and `$&`-style replacement patterns behave
61
+ differently. *Remedy:* port the bounded loop to Node or fix it upstream, and
62
+ add a cross-implementation fixture for pathological macros.
63
+ 4. **Error swallowing.** `_read_token_cache` and the GitLab remote probe use
64
+ bare `catch(err) {}`; Go returns `nil` from `readTokenCache` for any cause.
65
+ A corrupt cache, a wrong key or a missing agent all look alike. *Remedy:* a
66
+ `--debug`-visible reason (the `vvauth:debug` logger exists in Node).
67
+ 5. **HTTP hygiene.** Node uses `url.parse` (deprecated, lenient) and a 60 s
68
+ default timeout; Go uses `http.DefaultClient` with no timeout. Neither pins
69
+ or restricts TLS. *Remedy:* `url.URL`, an explicit `http.Client{Timeout}`,
70
+ and reject `http://` Vault addresses unless loopback.
71
+ 6. **`install` rewrites `~/.bashrc` wholesale** (`0644`, trimmed, re-written),
72
+ and `FunctionExists` runs `bash -lc`, executing the user's whole login
73
+ profile. *Remedy:* append-only, and grep the file instead of spawning a
74
+ login shell.
75
+ 7. **Release integrity.** `SHA256SUMS` is unsigned and the Linux binary is
76
+ unsigned; `release.yml` pulls `131/gh-actions@v1` by mutable tag. *Remedy:*
77
+ sign the checksum file (or publish build provenance) and pin the action by
78
+ commit.
79
+
80
+ ## Scores
81
+
82
+ | Criterion | Score | Why |
83
+ | --- | ---: | --- |
84
+ | Coolness | 15/20 | One `.vauthrc`, one `venv`, and a Vault token appears from the SSH key you already carry, cached safely, identical from Node or a signed static binary. The macro language and the GitLab `CI_PROJECT_*` derivation make it a genuinely pleasant developer tool; what a repository's `./.vauthrc` may decide is the open question. |
85
+ | Robustness | 16/20 | Lease logic, cache isolation and Node/Go parity are tested and solid; a project `package.json` may pin the `vvauth` version it expects, in both runtimes. Loses on unbounded macro recursion in Node, swallowed errors and the absence of HTTP timeouts in Go. |
86
+ | Safety | 14/20 | Good secret handling: encrypted cache, escaped values, validated variable names, no clear-text fallbacks. Loses on the blanket trust in `./.vauthrc` (a cloned repository picks the Vault and gets a raw agent signature), on the agent-socket exposure of the cache, and on HTTP without timeouts or transport constraints. |
87
+
88
+ Codex (Claude Fable 5.1)
@@ -0,0 +1,196 @@
1
+ # vvauth — Architecture, Code Quality, and Security Review
2
+
3
+ **Review date:** October 23, 2026
4
+ **Reviewer:** Codex (GPT 6.1-sol)
5
+
6
+ ## Scope and evidence
7
+
8
+ This is a read-only review of the current checkout. I read `README.md`, `API_and_tests.md`, both canonical implementations (`index.js`; `vauth.go`, `vault.go`, `cache.go`, `rc.go`, `humandiff.go`, and `cmd/vauth/main.go`), both test files, the three workflows, and the package/build manifests. I also inspected locally installed dependency source where necessary to understand Node HTTP, CLI, macro, child-process, and encryption delegation, Go agent selection, and Go HTTP redirect handling. I did not read the other audit as evidence, examine project history, modify the repository, craft inputs, or perform behavioral probes.
9
+
10
+ Authorized verification:
11
+
12
+ - `npm test`: **64 passed, 0 failed, 0 skipped**.
13
+ - `go test ./...`: **passed** for the library; `cmd/vauth` reports **no test files**. The normal Go output does not establish whether individual tests skipped optional checks.
14
+ - The Git working tree was clean before and after the test runs.
15
+
16
+ Findings below distinguish observed source behavior from inferred consequences. Severity reflects the likely impact under the stated conditions, not a demonstrated exploit. This is not an independent cryptographic certification, dependency-vulnerability scan, live Vault integration test, or Windows execution test.
17
+
18
+ ## Design as understood
19
+
20
+ vvauth combines an authentication client, a credential/profile resolver, and an environment publisher. Node exposes a class and a reflection-based CLI; Go separates configuration, cache, Vault transport, orchestration, and the command entry point.
21
+
22
+ Both locate `.vauthrc` through `VAUTHRC`, the working directory, then the home directory, and perform environment macro expansion. With an authentication configuration, connection precedence is the inherited `VAULT_TOKEN`, then the encrypted session cache, then SSH challenge signing or JWT login. Cached expiry drives reuse, renewal in the final third of the recorded lease, or replacement. `--renew` means fresh authentication, not merely renewal of the existing token. Without an auth block, inherited Vault tokens are deliberately ignored, allowing local armored credentials to work offline.
23
+
24
+ The shared disk contract is a hash-addressed `.creds` file beneath `~/.vauth/tokens`, containing armored JSON with the token, lease duration, renewable flag, and absolute expiry. `ssh-agent-crypt` performs encryption/decryption using an agent-backed key; new cache writes select a key through identity/mail settings, while decryption generally selects the armor's embedded fingerprint.
25
+
26
+ Environment resolution combines Vault entity metadata, the user's private KV-v2 `.vauth_database`, optional local encrypted JSON, and ordered remote secret reads. Metadata overrides private database entries; later secret sources override earlier ones. `env.map` publishes selected values through JSON, Bash exports, raw dotenv lines, or a child process. `set`/`unset` replace the private database document after a read.
27
+
28
+ **Overall assessment:** a useful, compact design with thoughtful cache hygiene and substantial lifecycle regression coverage. The principal weaknesses are implicit trust in working-directory configuration, incomplete lifecycle validation, unsafe transport defaults in Go, and a parity promise broader than the implementation and tests support.
29
+
30
+ ## Strengths
31
+
32
+ - **No plaintext token-cache fallback.** Encryption precedes writing, unreadable/plaintext armor is treated as a miss, and cache write failure does not fail authentication or print the token. Both request private creation modes and rename the completed temporary file into place (`index.js:121–152`, `cache.go:43–101`).
33
+ - **Well-covered lease decisions.** Tests exercise expiry, proportional renewal thresholds, lease-baseline preservation, nonrenewable replacement, forced reauthentication, environment-token precedence, disabled caching, and ordinary reuse without rewriting the cache.
34
+ - **Reasonable failure classification in token lookup/renewal.** HTTP 400/403 can trigger reauthentication, whereas server/network failures are propagated instead of creating extra tokens (`index.js:178–202`, `vauth.go:181–215,255–263`).
35
+ - **Good shell-value quoting and key checks on the normal environment path.** Bash values are single-quoted with embedded quotes escaped; `env.map` names are validated in both implementations. Resolution completes before export output begins (`index.js:330–335,489–492`, `vauth.go:419–431,448–459`).
36
+ - **Secrets are not printed in ordinary success diagnostics.** Token status and sourced export echoes are redacted; JSON output can be separated from stderr diagnostics.
37
+ - **Go has useful architectural seams.** Typed configuration, injectable HTTP client/clock/streams/environment, and separate transport/cache files make the library more maintainable and testable than a single CLI-bound implementation.
38
+ - **CI has basic quality gates and restrained permissions.** Linting, formatting, vetting, and tests are present; regular CI has read-only repository permissions. Go release configuration includes trimmed builds, version injection, checksums, and a Windows signing hook.
39
+
40
+ ## Weaknesses and correctness risks
41
+
42
+ ### 1. High — Configuration discovery is also an implicit credential trust decision
43
+
44
+ **Evidence:** `index.js:39,64–95,330–335`; `rc.go:322–373`; `vault.go:57–67`; `vauth.go:419–425`.
45
+
46
+ A working-directory `.vauthrc` can select the Vault destination and auth parameters, reference local encrypted credentials, and map arbitrary syntactically valid environment names. The code checks names against shell injection, but does not establish whether the configuration is trusted. In a malicious checkout, invoking the helper can therefore send an inherited token or JWT to a chosen endpoint, request agent signatures, decrypt available local material, or export values affecting command execution. This is a configuration-authority boundary, not a claim that correctly quoted values execute as Bash code.
47
+
48
+ A nonexistent explicit `VAUTHRC` also silently falls through to another configuration. That matches the README's fallback wording but can select an unintended security context.
49
+
50
+ **Remedy:** make explicit configuration selection fail closed; add an opt-in/trust mechanism for project configurations and display the selected configuration and destination without credentials. Bind inherited tokens to a trusted Vault origin, restrict sensitive environment overrides, and document that approving a configuration authorizes credential resolution and agent use.
51
+
52
+ ### 2. High — Transport policy is insufficient, particularly Go redirects
53
+
54
+ **Evidence:** `vault.go:42–86`; Node request construction throughout `index.js`; locally installed `nyks/http/request.js`; local Go `net/http/client.go` redirect-header copying.
55
+
56
+ Neither implementation requires HTTPS for credential-bearing requests. Go uses `http.DefaultClient` unless overridden, with no helper-level deadline, and reads complete response bodies without a size cap. Its default redirect behavior copies the custom `X-Vault-Token` header; that header is not among the standard headers receiving sensitive-header filtering. A redirect to another origin can consequently disclose a token. This is a static conclusion from the local HTTP implementation, not a redirect experiment.
57
+
58
+ Node does not enable redirects in these requests. Its dependency supplies a 60-second response-header timer, but that is not a total deadline: the timer is cleared when headers arrive, and timeout rejection does not explicitly destroy the request. Body draining remains unbounded.
59
+
60
+ **Remedy:** default to HTTPS, with explicit local-development exceptions; reject redirects for Vault calls or enforce an exact trusted origin and prohibit downgrade. Use bounded total deadlines, cancellation, response-size limits, and proper request/response cleanup in both runtimes. Preserve normal certificate verification.
61
+
62
+ ### 3. Medium — Cached validity and in-memory validity are conflated with actual token usability
63
+
64
+ **Evidence:** `index.js:161–226,276–288`; `vauth.go:159–252,289–319`; the explicit cached-revocation tests in both suites.
65
+
66
+ Cache reuse intentionally skips lookup until renewal is due. Revoked cached tokens can be returned successfully by `connect`/`login`; the subsequent profile lookup used by `env` can fail without retrying authentication. Moreover, once an instance is marked connected, ordinary calls bypass expiry and renewal altogether. A long-lived library client can keep returning an expired token. Absolute wall-clock expiry also assumes a stable clock and does not subtract network latency or a safety margin.
67
+
68
+ **Remedy:** retain in-memory lease metadata and reevaluate expiry on every connection request. Decide and document the freshness policy for cached tokens; offer validation, and implement one bounded reauthentication retry for token-invalid responses on safe reads. Add conservative expiry skew and keep network/server failures distinct from invalid credentials.
69
+
70
+ ### 4. Medium — Token persistence and replacement do not fully define ownership or cleanup
71
+
72
+ **Evidence:** `index.js:175,205–221`; `vauth.go:177,218–246`; environment-token and repeated-force-login tests.
73
+
74
+ An inherited token is persisted under the configured auth session even though it may belong to a different identity or carry different privileges. A later invocation without that environment variable can reuse it. Fresh authentication overwrites the local cache but does not revoke the previous token. Cache disabling leaves files intact; changing JWT content creates another filename; there is no logout, expiry cleanup, or retention policy. Replacement is therefore not revocation or credential erasure.
75
+
76
+ **Remedy:** distinguish externally supplied tokens from helper-owned tokens and make persistence of inherited tokens explicit. Bind persisted sessions to the intended principal/policy context. Add local cache cleanup and a documented logout path, with revocation limited to tokens the helper owns so that unrelated inherited credentials are not accidentally revoked.
77
+
78
+ ### 5. Medium — The decrypted cache lacks a validated, context-bound schema
79
+
80
+ **Evidence:** `index.js:121–141,175–187`; `cache.go:15–20,43–59`; `vault.go:89–96,161–176`.
81
+
82
+ Node accepts any successfully decrypted JSON without checking token type, lease duration, expiry, or renewable shape. Go checks a nonempty token and JSON types, but omitted/null expiry becomes unlimited and lease invariants are not checked. Go login parsing also accepts an omitted lease duration as zero; lookup accepts an omitted TTL as zero. Encryption authenticates bytes, not application meaning.
83
+
84
+ Neither payload contains a format version or session digest. Thus a valid armor copied into another session filename is not rejected for context mismatch if the corresponding key remains available. This requires local cache manipulation or another source of valid armor; it is not an unauthenticated bypass of encryption.
85
+
86
+ **Remedy:** define a shared versioned schema with required fields, finite/nonnegative durations, explicit unlimited-token semantics, and consistency checks. Embed and verify the session digest and relevant principal context. Treat malformed or mismatched payloads as misses with redacted diagnostics.
87
+
88
+ ### 6. Medium — Fixed cache staging names are unsafe under concurrency
89
+
90
+ **Evidence:** `index.js:134–151`; `cache.go:66–100`.
91
+
92
+ Both writers use exactly `<session>.creds.next`, overwrite it without exclusive creation, rename it, and unconditionally attempt cleanup. Concurrent Node/Go invocations can overwrite or remove each other's staging file, lose an update, or persist a different process's token. The read/renew/login/write sequence is also unlocked, so simultaneous callers may issue redundant logins or renewals.
93
+
94
+ Creation modes do not repair existing permissive files/directories, prevent following a preexisting symlink, or establish Windows ACL isolation. These are hardening gaps, not evidence that plaintext tokens are written.
95
+
96
+ **Remedy:** use unique exclusively created temporary files in a verified private directory, close and optionally sync before rename, and clean up only the writer's own file. Coordinate the session lifecycle with a cross-runtime lock and re-read inside the lock. Check ownership/permissions, avoid symlink traversal, and implement/test the Windows ACL equivalent.
97
+
98
+ ### 7. Medium — Cache identity selection is not authentication identity selection
99
+
100
+ **Evidence:** `index.js:143,390–419`; `cache.go:89–94`; `vault.go:110–158`; identity-selection tests in `test/token-cache.js`.
101
+
102
+ Identity/mail settings select new cache encryption, not the SSH login key: login tries all agent identities in order. Cache reads use the embedded fingerprint, so changing selectors does not isolate users when the old key remains loaded. Multiple identities sharing the same Vault/role configuration also share the cache filename. Agent ordering can therefore determine the authenticated principal independently of the advertised cache selector.
103
+
104
+ Both SSH loops swallow all login failures and continue, including transport/server failures. Node signing failures escape the loop, whereas Go signing refusals skip to another key. There is no JWT fallback after an attempted SSH login fails. On Windows, Node explicitly selects `pageant`; Go's dependency discovers a Pageant pipe and otherwise selects OpenSSH, so the documented fallback is not implemented identically.
105
+
106
+ **Remedy:** expose an explicit authentication-key fingerprint separate from, or intentionally coupled to, cache encryption selection. Include principal selection in session identity. Define fallback and error-classification rules, constrain agent access/signing, and harmonize Windows agent selection. Document that access to a loaded key's signing service can enable cache decryption; armor is not protection against an already-compromised session with agent access.
107
+
108
+ ### 8. Medium — Configuration and macro semantics diverge and can silently preserve mistakes
109
+
110
+ **Evidence:** `index.js:67–88,293–335`; `rc.go:121–136,155–245,247–301,340–371`; locally installed `nyks/string/replaceEnv.js` and `nyks/object/walk.js`.
111
+
112
+ Unknown macros remain literal, including in authentication and required credential fields. Node's recursive replacement has no cycle/depth guard; cyclic references can overflow recursion or grow output. Go stops after 16 passes without reporting incomplete resolution and stringifies structured values, whereas Node can return a structured value directly. Go's YAML walk processes mapping keys as well as values; Node's object walk processes values only. Alias handling and YAML coercion further complicate parity. Unknown configuration fields are not comprehensively rejected.
113
+
114
+ **Remedy:** publish a constrained schema and deterministic macro specification covering types, missing values, recursion, keys, and aliases. Reject unresolved required fields, detect cycles, and bound expansion depth and output size with errors rather than partial success. Treat secret values as literal data by default instead of automatically interpreting embedded macros.
115
+
116
+ ### 9. Medium — Cache hashing is order-sensitive, and Go can retain a stale auth hash
117
+
118
+ **Evidence:** `index.js:110–115`; `rc.go:27–45,247–301,358–371`; `cache.go:23–31`; `vauth_test.go:TestTokenCacheKeyMatchesNode`.
119
+
120
+ The cache key hashes serialized auth objects rather than a normalized semantic session. Reordering nested YAML auth fields can create another cache entry for the same session. Raw JWT inclusion also causes cache fragmentation as JWTs rotate. Go reimplements Node-style serialization and tests only a small number of expected strings, not a real Node-to-Go session exchange.
121
+
122
+ More importantly, `ParseRC` stores `authKey`, and `AuthKey()` prefers it over the public auth structs. If an embedding caller changes a parsed role or JWT, the runtime auth configuration changes but the cached hash does not. That can reuse or overwrite a token associated with the earlier configuration.
123
+
124
+ **Remedy:** derive a versioned canonical session identity from immutable validated configuration, or invalidate/recompute it whenever public auth settings change. Normalize ordering/defaults and define JWT rotation semantics deliberately. Add bidirectional cross-runtime cache tests using the same parsed configuration and principal settings.
125
+
126
+ ### 10. Medium — Environment publication has stale-state and data-format hazards
127
+
128
+ **Evidence:** `index.js:248–255,300–335,340–345`; `vauth.go:366–424,448–470,475–487`; `FunctionDecl` in both implementations.
129
+
130
+ Valid names such as `VAULT_TOKEN`, `VAULT_ADDR`, `PATH`, and runtime loader options remain unrestricted in `env.map`; mapping happens after the helper adds its own Vault values. A trusted authenticated session can thus publish a different token/address pair. Missing profile values differ by runtime: Node can retain `undefined`, while Go can retain a macro literal. Raw dotenv output does not escape multiline, quote, or comment-sensitive values.
131
+
132
+ The installed `venv` function sources process-substitution output without propagating the producer's exit status. A failed resolver can leave old credentials in the shell while the sourcing operation appears successful. Successful output also does not unset credentials absent from the newly resolved environment. Public Go `PublishEnv` assumes callers supply validated names and ignores output errors.
133
+
134
+ **Remedy:** reserve or explicitly authorize sensitive overrides, validate environment values at publication, and define missing/null behavior. Use a specified dotenv encoder or reject values outside its supported format. Make the shell wrapper check producer success before sourcing and manage previously exported variables explicitly. Validate names at exported sinks and return write errors.
135
+
136
+ ### 11. Medium — Private database updates can lose concurrent changes
137
+
138
+ **Evidence:** `index.js:258–268,362–386`; `vauth.go:333–347`; `vault.go:203–237`.
139
+
140
+ `set` and `unset` read the complete `.vauth_database`, edit it, then replace the complete KV-v2 document without a version/CAS condition. Concurrent updates can overwrite each other. Secret paths, mounts, login metadata, and entity IDs are concatenated into URLs without a shared validation/encoding policy. Vault remains the authorization boundary, but ambiguous path characters or missing identity fields can target unintended paths or produce confusing errors. Later secret documents also silently override earlier fields.
141
+
142
+ **Remedy:** retain KV-v2 version metadata, use CAS and bounded conflict retries, validate identity/path components, and construct URLs safely. Specify duplicate-secret precedence and provide a strict collision mode. Treat tokens without entity metadata as an explicit supported case or reject profile-dependent operations with a precise error.
143
+
144
+ ### 12. Medium — Error handling can expose sensitive response content or hide the real failure
145
+
146
+ **Evidence:** `index.js:362–386,410–419,472–483`; `vault.go:17–24,99–107,151–158,203–235`; `vauth.go:508–521`; local Node runner error handling.
147
+
148
+ Several errors include complete remote response bodies; the Node runner also prints the error and stack. A server or proxy can return sensitive or attacker-controlled text. Cache read failures are all swallowed, obscuring permission, integrity, and unavailable-agent failures. Missing auth capability can yield successful empty connection results on the first attempt. Go's installer ignores a `.bashrc` read error before writing; Node's function check has no child-spawn error handling. Interactive installation prompts also contradict the blanket machine-readable-stdout claim.
149
+
150
+ **Remedy:** use typed, contextual, redacted errors with bounded/sanitized remote messages, and make diagnostics distinguish expected cache misses from operational failures without secrets. Separate offline mode from required authentication. Preserve existing shell files on read failure, handle process-start errors, return output errors, and document interactive commands as exceptions to machine-readable output.
151
+
152
+ ### 13. Medium — The Node/Go CLI parity contract is currently false in important cases
153
+
154
+ **Evidence:** `index.js:103–107,495–498`; `cmd/vauth/main.go:98–114,175–201`; locally installed `cnyks/lib/index.js`, `nyks/process/parseArgs.js`, and child-process helpers.
155
+
156
+ Static dispatch analysis identifies concrete mismatches not exercised by the current suites:
157
+
158
+ - Node selects raw output unless JSON is requested; its runner stringifies ordinary objects as raw strings. Bare `env`/`show` therefore do not receive the JSON-object formatting promised for both runtimes. Go explicitly JSON-encodes objects.
159
+ - Go implements `version`/`--version`; the Node class and inspected runner contain no corresponding version command.
160
+ - Node's runner leaves the textual flag value `false` as a truthy string, contrary to the documented boolean rule; Go interprets it as false. Node also coerces numeric-looking `set` arguments, unlike Go's string-preserving CLI.
161
+ - Node's child helper turns any nonzero child status into a generic rejection and exits 1; Go propagates the child's exit code.
162
+ - The documented `vauth run -- <command>` form passes `--` as the executable in both dedicated run paths, which forward original arguments rather than consuming that separator.
163
+
164
+ **Remedy:** use explicit command dispatch and shared argument/output rules rather than reflection as the Node contract boundary. Add version handling, preserve `set` strings, normalize booleans and separators, and propagate child statuses. Exercise both actual CLIs against the same contract fixtures, including default output and failure cases.
165
+
166
+ ### 14. Medium — Testing and release gates do not establish the advertised assurance
167
+
168
+ **Evidence:** both test files; `.github/workflows/test.yml`, `publish-npm.yml`, `release.yml`; `.goreleaser.yaml`; `.gitignore:2`; package manifests.
169
+
170
+ Tests are strong for JWT/cache lifecycle but neither fake Vault implements SSH nonce/login or meaningful KV/profile operations. Go lacks CLI tests and identity-selection coverage comparable to Node. Armor interoperability checks use each runtime's corresponding crypto CLI, not a bidirectional Node/Go vvauth cache exchange; Go can skip its CLI check when unavailable.
171
+
172
+ The Node CI job runs only on Linux. The Windows Go job builds instead of running tests, despite `API_and_tests.md` saying both suites run on Linux and Windows. Existing test harnesses assume Unix-style `ssh-agent -s`, Bash, and process cleanup. No race/concurrency, hostile transport, or broad configuration-contract coverage is present.
173
+
174
+ Node workflows run `npm install`, while `package-lock.json` is ignored and untracked in this checkout, so CI dependency resolution is not tied to a committed lock. The Node package declares no engine requirement although CI tests only Node 24. Publishing uses a different event (`create`) from binary releases (`push` with tag filtering), has no explicit tag-type guard or production environment in the job, and does not validate package/module/tag version agreement. Release actions, GoReleaser selection, and the trusted external signing helper use movable refs/ranges. Checksums and an external signing hook do not alone prove that every Windows artifact is signed, and the README download commands do not verify downloaded artifacts.
175
+
176
+ **Remedy:** add common CLI, SSH/profile/KV, and real cross-runtime cache fixtures; make optional interop mandatory in release CI. Run platform-appropriate tests on Windows and declare the supported Node range. Commit a lockfile and use reproducible dependency installation. Align publication triggers, protect release environments/tags, and validate version agreement. Pin trusted build actions/helpers to reviewed immutable revisions, verify required signatures before publishing, provide provenance/checksum verification instructions, and ensure release gates cover both implementations.
177
+
178
+ ## Recommended order of work
179
+
180
+ 1. Establish trusted configuration/origin selection and safe transport defaults, especially Go redirect suppression.
181
+ 2. Fix the explicit CLI-contract mismatches and the shell wrapper's failure propagation.
182
+ 3. Validate/version cache payloads, eliminate fixed staging names, and make lifecycle decisions concurrency-safe.
183
+ 4. Define token ownership, authentication identity, configuration immutability, and macro semantics.
184
+ 5. Add shared end-to-end parity fixtures, real platform tests, and reproducible/protected release gates.
185
+
186
+ ## Final scores
187
+
188
+ These are qualitative engineering judgments, not vulnerability counts or certification grades.
189
+
190
+ | Criterion | Score / 20 | One-line justification |
191
+ | --- | ---: | --- |
192
+ | Coolness | **17 / 20** | Agent-backed armored caching, offline secret resolution, and two interoperable implementation targets make a genuinely useful developer tool. |
193
+ | Robustness | **11 / 20** | Strong cache regression tests are offset by lifecycle/concurrency gaps, weak transport bounds, and concrete CLI/configuration parity defects. |
194
+ | Safety | **10 / 20** | Encryption and shell-value hygiene are good, but implicit configuration trust, Go redirect leakage, token retention, and insufficient context validation need hardening. |
195
+
196
+ **Signed: Codex (GPT 6.1-sol)**