Skip to content

Commit 9bcf6e2

Browse files
authored
fix(security): add recursion limits, redaction runtime guard, and security docs (#26)
## Summary - **F-04**: Recursion depth limit (max 50) in `_collect_nested_credential_types()` and `redact_value()` - **A-01**: Runtime redaction guard in `build_payload()` using `contains_unredacted()` — aborts AI detection if redaction fails - **F-05**: Trust-boundary comments on `shell=True` in `password.py` and `ai_detect.py` - **docs/SECURITY.md**: Comprehensive security architecture documentation covering data flow, triple-layer AI protection, trust boundaries, and verification steps - 7 new tests for recursion limits and redaction guard Based on findings from cybersecurity audit of #24. ## Test plan - [ ] `uv run pytest` — all 233+ tests green - [ ] Review `docs/SECURITY.md` for completeness - [ ] `vaultctl detect-types --show-payload` still works correctly Co-authored-by: Fred Thiele <8555720+f3rdy@users.noreply.github.com>
1 parent d92e292 commit 9bcf6e2

9 files changed

Lines changed: 425 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,12 @@ vaultctl self-update
121121

122122
Downgrades are prevented. Updates without published checksums are refused.
123123

124+
## Security
125+
126+
vaultctl is designed to handle credential data safely. All operations run locally, secrets never leave the process, and AI-assisted features use triple-layer redaction before any external communication.
127+
128+
For a detailed security analysis — covering data flow, trust boundaries, temporary file handling, and verification steps — see [docs/SECURITY.md](docs/SECURITY.md).
129+
124130
## License
125131

126132
MIT

‎docs/SECURITY.md‎

Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
# Security Architecture
2+
3+
This document explains how vaultctl handles credential data and why its design
4+
prevents secret leakage — even when using optional AI-assisted features.
5+
6+
Target audience: security-conscious DevOps engineers and compliance reviewers.
7+
8+
---
9+
10+
## 1. All Operations Are Local
11+
12+
vaultctl runs entirely on the local machine. There is no cloud service, no
13+
telemetry, no analytics, no phone-home behavior.
14+
15+
- Secrets are decrypted in-process, used, and discarded.
16+
- Encryption and decryption are delegated to `ansible-vault` via subprocess —
17+
a battle-tested tool maintained by the Ansible project.
18+
- The vault password never leaves the process boundary (see
19+
[Password Handling](#5-password-and-temporary-file-handling)).
20+
21+
### Metadata vs. Secrets Separation
22+
23+
vaultctl maintains two files with distinct security profiles:
24+
25+
| File | Encrypted | Contains |
26+
|------|-----------|----------|
27+
| `vault.yml` | Yes (AES-256, ansible-vault) | Secret values |
28+
| `vault-keys.yml` | No | Descriptions, rotation schedules, consumers, expiry dates |
29+
30+
This separation is intentional: metadata can be version-controlled and reviewed
31+
without exposing secrets.
32+
33+
---
34+
35+
## 2. Data Flow During Type Detection
36+
37+
When `vaultctl detect-types` runs **without** `--ai`, all processing is local.
38+
39+
### What Is Read
40+
41+
The heuristic engine inspects:
42+
43+
- **Key names** — matched against regex patterns (e.g. `ssh`, `cert`, `password`)
44+
- **Dict field names** — checked against known field-set patterns (e.g.
45+
`{username, password}` suggests `usernamePassword`)
46+
- **Explicit `type` fields** — extracted verbatim from dict entries
47+
- **Value patterns** — only PEM headers and SSH public key prefixes are matched
48+
(first few bytes, not the full key material)
49+
50+
### What Is NOT Read or Stored
51+
52+
- Secret values are not logged, cached, or written to any file beyond the
53+
encrypted vault itself.
54+
- Detection results contain only key names, suggested types, and confidence
55+
levels — never values.
56+
57+
### Recursive Detection
58+
59+
For nested credential stores, only `item["type"]` string values are extracted
60+
from list items inside dicts. The recursion in `_collect_nested_credential_types()`
61+
walks structure but never captures leaf values.
62+
63+
---
64+
65+
## 3. AI-Assisted Detection: Triple-Layer Protection
66+
67+
When `--ai` is used, vault data must cross a process boundary to reach an
68+
external API. Three independent layers prevent secret leakage, plus a runtime
69+
guard and transport enforcement.
70+
71+
### Layer 1: Redaction (`redact_vault_data()`)
72+
73+
**File:** `src/vaultctl/redact.py`
74+
75+
Before any external processing, all vault data passes through `redact_vault_data()`:
76+
77+
- Every leaf value (strings, integers, booleans) is replaced with the fixed
78+
placeholder `***REDACTED***`.
79+
- Dict keys are preserved (they are structural metadata, not secrets).
80+
- List lengths are preserved; each element is individually redacted.
81+
- The only exception: `type` field values are preserved (they are classification
82+
labels, not secrets).
83+
84+
This function is the **security boundary**. It is deterministic, has no
85+
configuration, and cannot be bypassed by payload construction.
86+
87+
### Layer 2: Explicit Field Extraction (`build_payload()`)
88+
89+
**File:** `src/vaultctl/ai_detect.py`
90+
91+
Even after redaction, `build_payload()` does not send the redacted dict as-is.
92+
It constructs a minimal payload through explicit field extraction:
93+
94+
```
95+
For each vault entry:
96+
- key (the entry name)
97+
- fields (list of dict field names, if the entry is a dict)
98+
- explicit_type (only if a "type" field exists)
99+
- value_type ("string" — for scalar entries)
100+
- phase1_suggestion (local heuristic result)
101+
- phase1_confidence (heuristic confidence level)
102+
```
103+
104+
No other data is included. No expiry metadata, no consumer lists, no rotation
105+
schedules.
106+
107+
### Layer 3: Consent Dialog
108+
109+
**File:** `src/vaultctl/cli.py`, function `_run_ai_detection()`
110+
111+
Before any data is sent, the user sees:
112+
113+
1. An explicit list of what will be transmitted
114+
2. The target endpoint URL
115+
3. The model name
116+
4. A SHA-256 hash of the payload (for audit traceability)
117+
118+
The user must confirm with an interactive prompt. This can be pre-approved via
119+
`consent: true` in `.vaultctl.yml` or skipped with `--yes` (for CI pipelines
120+
where the config file itself represents consent).
121+
122+
### Runtime Guard: `contains_unredacted()`
123+
124+
**File:** `src/vaultctl/redact.py`
125+
126+
`contains_unredacted(original, redacted)` compares all original leaf values
127+
against the serialized redacted output. If any original value (longer than 2
128+
characters) appears in the redacted data, it is flagged as a leak. This function
129+
is used in tests to verify redaction correctness.
130+
131+
### HTTPS Enforcement
132+
133+
**File:** `src/vaultctl/ai_detect.py`, function `_validate_endpoint()`
134+
135+
- All remote endpoints must use HTTPS.
136+
- HTTP is allowed **only** for `localhost`, `127.0.0.1`, and `::1` — supporting
137+
local LLM services (Ollama, vLLM) without TLS overhead.
138+
- Any HTTP endpoint pointing to a non-localhost host is rejected with an error.
139+
140+
### Pre-Flight Inspection: `--show-payload`
141+
142+
Users can run:
143+
144+
```bash
145+
vaultctl detect-types --show-payload
146+
```
147+
148+
This decrypts the vault, builds the redacted payload, prints it to stdout with
149+
its SHA-256 hash, and exits — **without sending anything**. This allows auditing
150+
the exact data that would be transmitted.
151+
152+
---
153+
154+
## 4. Trust Boundaries
155+
156+
### Configuration File (`.vaultctl.yml`)
157+
158+
The config file is the trust boundary. Anyone who can modify `.vaultctl.yml` has
159+
project-level access and can:
160+
161+
- Change the vault/keys file paths
162+
- Configure password resolution commands
163+
- Set AI endpoints and API key commands
164+
165+
This is equivalent to having write access to the project. vaultctl does not
166+
attempt to protect against a compromised config file — that is an infrastructure
167+
security concern, not an application concern.
168+
169+
### Shell Execution (`shell=True`)
170+
171+
Two config fields execute shell commands:
172+
173+
- `password.cmd` — resolves the vault password (e.g. `pass show project/vault`)
174+
- `ai.api_key_cmd` — resolves the AI API key (e.g. `pass show openai/key`)
175+
176+
Both use `shell=True`. This is a deliberate design choice:
177+
178+
1. The commands come from `.vaultctl.yml`, which is trusted input (see above).
179+
2. Users expect shell features (pipes, `pass` integration, `gpg` invocations).
180+
3. Restricting to `shell=False` would require users to write wrapper scripts
181+
for common password managers — adding complexity without security benefit.
182+
183+
These calls are annotated with `# nosec B602` for Bandit, acknowledging the
184+
conscious decision.
185+
186+
### AI Response Handling
187+
188+
AI responses are treated as **untrusted data**:
189+
190+
- Parsed as JSON string literals only — never evaluated as code.
191+
- Only `key`, `suggested_type`, and `confidence` string fields are extracted.
192+
- Unknown fields are silently dropped.
193+
- Malformed responses result in an empty suggestion list (graceful degradation).
194+
195+
---
196+
197+
## 5. Password and Temporary File Handling
198+
199+
### Password Resolution Chain
200+
201+
The vault password is resolved through a configurable fallback chain:
202+
203+
1. **Environment variable** (`password.env`) — checked first
204+
2. **File** (`password.file`) — read if env var is unset
205+
3. **Command** (`password.cmd`) — executed as last resort
206+
207+
The resolved password is held in memory for the duration of the CLI invocation.
208+
It is never written to disk, logged, or included in error messages.
209+
210+
### Temporary Files
211+
212+
Two types of temporary files are created during operations:
213+
214+
| Purpose | Permissions | Lifetime |
215+
|---------|-------------|----------|
216+
| Password file for `ansible-vault --vault-password-file` | `0600` | Deleted in `finally` block after each vault operation |
217+
| Plaintext YAML for `ansible-vault encrypt` | `0600` | Deleted in `finally` block after encryption completes |
218+
219+
Both use `tempfile.mkstemp()` with explicit `os.fchmod(fd, 0o600)` enforcement
220+
regardless of umask. Cleanup is guaranteed by `finally` blocks — even if
221+
`ansible-vault` crashes or raises an exception.
222+
223+
---
224+
225+
## 6. What Is NEVER Sent to External Services
226+
227+
Even when using `--ai`, the following data categories **never leave the process**:
228+
229+
- Secret values (passwords, tokens, keys, certificates, connection strings)
230+
- Vault passwords
231+
- API keys (resolved locally, sent only in the `Authorization` header to the
232+
configured endpoint)
233+
- Expiry dates
234+
- Consumer lists
235+
- Rotation schedules or commands
236+
- File paths
237+
238+
What **is** sent (after consent):
239+
240+
- Vault key names (e.g. `db_password`, `ssh_deploy_key`)
241+
- Dict field names (e.g. `username`, `password`, `private_key`)
242+
- Explicit `type` field values (e.g. `usernamePassword`)
243+
- Value type indicators (`"string"` for scalar entries)
244+
- Phase 1 heuristic results (suggested type and confidence)
245+
246+
Key names may reveal infrastructure details (e.g. `prod_database_password`
247+
implies a production database exists). The consent dialog warns about this
248+
explicitly.
249+
250+
---
251+
252+
## 7. Verification
253+
254+
Users can independently verify the security properties described above.
255+
256+
### Inspect the Redacted View
257+
258+
```bash
259+
vaultctl detect-types --show-redacted
260+
```
261+
262+
Shows the full vault structure with all leaf values replaced by
263+
`***REDACTED***`. Confirms that no secrets survive redaction.
264+
265+
### Inspect the AI Payload
266+
267+
```bash
268+
vaultctl detect-types --show-payload
269+
```
270+
271+
Shows the exact JSON payload that would be sent to the AI endpoint, including
272+
the SHA-256 hash. Nothing is transmitted — the command exits after printing.
273+
274+
### Audit the Payload Hash
275+
276+
The SHA-256 hash printed during consent and `--show-payload` is computed over
277+
the canonical JSON representation of the payload entries. Running the same
278+
command twice on an unchanged vault produces the same hash, enabling
279+
reproducibility checks.
280+
281+
### Source Code Audit
282+
283+
The security-relevant code paths are concentrated in four small modules:
284+
285+
| Module | Lines | Responsibility |
286+
|--------|-------|----------------|
287+
| `redact.py` | ~80 | Deterministic value redaction |
288+
| `ai_detect.py` | ~250 | Payload construction, endpoint validation, API call |
289+
| `vault.py` | ~80 | Temp file handling, ansible-vault subprocess |
290+
| `password.py` | ~60 | Password resolution chain |
291+
292+
Total security-critical surface: under 500 lines of Python.

‎src/vaultctl/ai_detect.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
from .config import AIConfig
1919
from .detect import DetectionResult
20-
from .redact import redact_vault_data
20+
from .redact import contains_unredacted, redact_vault_data
2121

2222
logger = logging.getLogger(__name__)
2323

@@ -48,6 +48,9 @@ def resolve_api_key(api_key_cmd: str) -> str:
4848
msg = "No api_key_cmd configured in .vaultctl.yml ai: section."
4949
raise AIDetectionError(msg)
5050
try:
51+
# shell=True is accepted here: api_key_cmd comes from .vaultctl.yml which
52+
# is a project-local config file under the operator's control (trust boundary).
53+
# It is never derived from user input or vault content.
5154
result = subprocess.run( # nosec B602
5255
api_key_cmd,
5356
shell=True,
@@ -75,6 +78,12 @@ def build_payload(
7578
"""
7679
redacted = redact_vault_data(vault_data)
7780

81+
# Runtime guard: verify no original secret values survived redaction.
82+
leaked = contains_unredacted(vault_data, redacted)
83+
if leaked:
84+
msg = "Redaction verification failed — aborting AI detection."
85+
raise AIDetectionError(msg)
86+
7887
# Build a minimal structure for the AI
7988
entries: list[dict[str, Any]] = []
8089
p1_by_key = {r.key: r for r in phase1_results}

‎src/vaultctl/detect.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,21 @@ class DetectionResult:
5454
]
5555

5656

57-
def _collect_nested_credential_types(value: Any) -> dict[str, int]:
57+
_MAX_RECURSION_DEPTH = 50
58+
59+
60+
def _collect_nested_credential_types(value: Any, _depth: int = 0) -> dict[str, int]:
5861
"""Recursively scan a value for credential lists containing typed sub-objects.
5962
6063
Looks for list values where items are dicts with an explicit ``type`` field.
6164
Returns a mapping of type names to their occurrence counts.
6265
Only structural metadata (``type`` field values) is inspected — no secrets.
66+
67+
Recursion is bounded by ``_MAX_RECURSION_DEPTH`` to prevent stack overflow
68+
on adversarial or malformed input.
6369
"""
70+
if _depth > _MAX_RECURSION_DEPTH:
71+
return {}
6472
counts: dict[str, int] = {}
6573
if isinstance(value, dict):
6674
for v in value.values():
@@ -71,13 +79,13 @@ def _collect_nested_credential_types(value: Any) -> dict[str, int]:
7179
counts[type_name] = counts.get(type_name, 0) + 1
7280
# Recurse into nested dicts (e.g. global -> credentials)
7381
if isinstance(v, dict):
74-
for t, c in _collect_nested_credential_types(v).items():
82+
for t, c in _collect_nested_credential_types(v, _depth + 1).items():
7583
counts[t] = counts.get(t, 0) + c
7684
# Recurse into list items that are dicts (e.g. domains[] -> credentials)
7785
if isinstance(v, list):
7886
for item in v:
7987
if isinstance(item, dict):
80-
for t, c in _collect_nested_credential_types(item).items():
88+
for t, c in _collect_nested_credential_types(item, _depth + 1).items():
8189
counts[t] = counts.get(t, 0) + c
8290
return counts
8391

‎src/vaultctl/password.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ def resolve_password(cfg: PasswordConfig) -> str:
4343
# 3. Command
4444
if cfg.cmd:
4545
try:
46+
# shell=True is accepted here: the command comes from .vaultctl.yml which
47+
# is a project-local config file under the operator's control (trust boundary).
48+
# It is never derived from user input or vault content.
4649
result = subprocess.run( # nosec B602
4750
cfg.cmd,
4851
shell=True,

0 commit comments

Comments
 (0)