Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

Remove Vault plaintext create surfaces (#736)

Call Whitef595eb903f19
diff --git a/docs/plans/avault-custody-core.md b/docs/plans/avault-custody-core.md
index a4a44c52c..59f5000eb 100644
--- a/docs/plans/avault-custody-core.md
+++ b/docs/plans/avault-custody-core.md
@@ -37,7 +37,7 @@ Two **trust roots**, chosen per secret:
P0 ships the **standard tier** in Python:
- Envelope encryption in `storage/vault_crypto.py`: a random per-secret DEK encrypts the value (AES-256-GCM); the DEK is wrapped under a 32-byte **machine key** at `~/.avibe/state/vault/machine.key` (mode 0600).
-- Short-lived CLI processes (`vibe vault set/list/run/fetch/request/export/inject/key`) do direct-DB + direct-crypto; no daemon.
+- Short-lived CLI processes (`vibe vault list/run/fetch/request/export/inject/key`) do direct-DB + direct-crypto; no daemon. The old agent-facing `vibe vault set` plaintext-create command has been removed; create now enters through browser-side sealed/blind-box payloads.
- Delivery modes: `run` (child env) and `fetch` (brokered HTTP); `export`/`inject` are help-only.
- The core invariant: **the model handles secret _names_; the platform handles secret _values_.** `$<NAME>` dynamic-ask wakes the agent with a name only; `vault_secrets` is denylisted in `data query`.
@@ -153,7 +153,8 @@ This makes "does a byte touch Python?" the wrong question. Python carries only b
| Standard deliver | — | the DB ciphertext | unwrap with machine key → inject → returns **exit code** |
| Protected deliver | passkey unlock → releases the per-record **DEK**, sealed to `avault` | a blind box | open → decrypt DB ciphertext → deliver → returns **result** |
-In every row Python holds only ciphertext or a blind box. (The standard-create row can instead accept a transient plaintext POST; see §11.3.)
+In every row Python holds only ciphertext or a blind box. Standard create no longer
+accepts a plaintext POST in Avibe; browser blind-box create is the product boundary.
---
@@ -325,9 +326,13 @@ For a **long-lived master key** every one of these is exposed for the whole daem
`Zeroizing<…>` buffers wiped on deterministic `Drop`; constant-time comparison (`subtle`); `mlock` + `PR_SET_DUMPABLE(0)` on the key pages; tight control over copies. `avault` holds keys for the minimum window and wipes them.
-### 11.3 The honest residual on standard-create
+### 11.3 Removed residual on standard-create
-If standard-create takes a **plaintext POST** (no blind box), the value exists as one transient `bytes` in one Python request — un-zeroizable, briefly swappable. It is bounded (single value, single request, not reused) and the daemon is **in-boundary for the standard tier anyway** (it can ask `avault` to decrypt any standard secret). So it is an acceptable, minimized residual — or eliminated entirely by the **blind-box create** (§7.1), which is the recommended default.
+The older plan allowed standard-create to accept a transient plaintext POST and
+pipe it into `avault`. That path has been removed from Avibe. Standard create now
+requires the browser to seal a blind box to `avault`'s public key; text and
+file-backed secrets are both read and sealed in the browser. If the payload
+contains a plaintext `value` field, the API rejects it before invoking `avault`.
### 11.4 The other honest caveat — pubkey integrity
@@ -352,7 +357,9 @@ The blind box assumes the browser gets `avault`'s **genuine** public key. A full
1. **CLI one-shot (P1):** the daemon spawns `avault seal/open/...`; it reads the master key, uses it, wipes it on `Drop`, exits. The common path is `askill`-shaped, and the per-op window already gets Rust hygiene.
2. **Resident agent (P2):** `avault agent` listens on a unix socket, holds the grant DEK-set for the TTL, and is the signing oracle. The daemon authorizes via `SO_PEERCRED`. Only grant-caching and signing pay this cost.
-**Ingest without Python reading plaintext:** for the CLI `set` path, pass stdin's **file descriptor** straight to the `avault` subprocess (Python never `read()`s the bytes). For the web path, the browser uses the blind box (§7.1).
+**Ingest without Python reading plaintext:** the browser uses the blind box (§7.1).
+The old agent-facing CLI `set` ingest path has been removed instead of being kept
+as an fd-forwarding special case.
---
@@ -429,7 +436,8 @@ All settled; the authoritative record is **`avault/docs/DESIGN.md` §16**. Summa
## 17. Honest residuals (collected)
-- **Standard-create transient plaintext** in Python if not using the blind box — bounded, acceptable, or eliminated by blind-box create (§11.3).
+- **Standard-create transient plaintext** — removed from Avibe; standard create
+ requires browser blind-box payloads (§11.3).
- **`avault` pubkey distribution integrity** — in-boundary for standard; needs pin/attest for protected (§11.4).
- **Standard tier ≠ machine-compromise resistance** — it is at-rest + use-gating + no-LLM-exposure, not "safe if the box is owned" (§4.1).
- **Browser JS hygiene** is best-effort (wipeable typed arrays, non-extractable WebCrypto keys), not a secure enclave; exposure is one operation while the user is present (§8.3).
@@ -447,8 +455,8 @@ Every standard-tier crypto call lives in two modules — and **the long-lived da
| Path | Code | Crypto today | Plaintext destination |
|---|---|---|---|
-| Create (REST) | `vibe/api.py:create_vault_secret` → `vault_service.create_secret` → `seal_standard` | seal (daemon) | — (stores ciphertext) |
-| Create (CLI) | `cmd_vault_set` → `create_secret` → `seal_standard` | seal | — |
+| Create (REST) | `vibe/api.py:create_vault_secret` → browser blind-box → `avault seal --blind-box` → `vault_service.create_secret` | blind-box seal (avault) | avault subprocess only |
+| Create (CLI) | removed from the agent-facing CLI | — | — |
| Rotate | `vault_service.rotate_secret` → `seal_standard` | seal | — (unused in P0) |
| Run | `cmd_vault_run` → `resolve` → `subprocess.Popen(env=…)` | open ×N | child env (1 child, N vars) |
| Export | `cmd_vault_export` → `resolve` → stdout | open ×N | shell (`eval $(…)`) |
@@ -480,7 +488,10 @@ All keep the invariant: plaintext flows only *into* avault; out comes an exit co
### 18.4 The Avibe rework (after P1.1)
-- **`vault_service.create_secret` / `rotate_secret`** → spawn `avault seal --name <N>`, value on **stdin** (the daemon's transient POST plaintext piped straight through; never logged/persisted), parse `{ciphertext,nonce,wrap_meta}`, store. **Removes the daemon's only crypto + its only `machine.key` read.**
+- **`vault_service.create_secret` / `rotate_secret`** → create receives an already
+ sealed browser blind box and spawns `avault seal --blind-box`; protected create
+ receives a browser-sealed envelope. No Avibe product endpoint accepts a
+ plaintext `value` field for create.
- **`cmd_vault_run`** → `avault deliver run` (multi-secret); envelopes from the DB on stdin. Drop `resolve()` + `Popen` here.
- **`cmd_vault_export` / `cmd_vault_inject`** → `avault deliver export|inject`.
- **`cmd_vault_fetch`** → `avault deliver fetch` (policy/host-allowlist check stays in Python *before* the call).
diff --git a/docs/plans/vaults-p0-implementation.md b/docs/plans/vaults-p0-implementation.md
index f73b0e56f..334316318 100644
--- a/docs/plans/vaults-p0-implementation.md
+++ b/docs/plans/vaults-p0-implementation.md
@@ -185,7 +185,8 @@ value ops must go through the daemon.)
## 6. CLI — `vibe/cli.py` (argparse `vault` subparser)
```
-vibe vault set NAME [--group G] [--tag t]... [--protected(P1)] --stdin | --from-file f
+# Removed: the agent-facing CLI no longer accepts plaintext create (`vibe vault set`).
+# Create flows enter through browser-side sealed/blind-box payloads.
vibe vault list [--group G] [--skill S(P1)] [--json]
vibe vault rm NAME
vibe vault run --env NAME[,N2] [--env LOCAL=NAME] [--env-skill S(P1)] -- cmd... # M1, promoted
@@ -196,8 +197,9 @@ vibe vault export --env NAME[,N2]
vibe vault inject --keys A,B --out f [--format dotenv|json|yaml|toml] [--ttl 10m] # M2
```
-`set` rejects argv values (shell history / agent context) — `--stdin`/`--from-file`
-only. No `vibe vault get`; no command prints a value.
+`set` has been removed from the agent-facing CLI. Create flows enter through the
+browser, which sends sealed/blind-box payloads instead of plaintext values. No
+`vibe vault get`; no command prints a value.
## 7. Reply enhancer — `core/reply_enhancer.py`
@@ -234,11 +236,12 @@ stay queryable.
1. `feat(vault): schema + machine-key crypto + data query denylist`. **[done — 58832ae3]**
2. `feat(vault): data service` — `storage/vault_service.py` (CRUD + standard-tier
resolve + provision + audit). **[done — 7093ad5c]**
-3. `feat(vault): CLI set/list/rm/run/request` — direct-DB + direct-crypto (standard
- tier; UDS deferred to P1, §5). End-to-end verified: `run` injects to child env with
- **no stdout leak**. **[done — 2026-06-21]**
-3b. `feat(vault): fetch` — M4 brokered HTTP + domain binding (`set --allow-host` +
- `--auth-header`/`--auth-query`; secret attached at egress, refused for non-allowed
+3. `feat(vault): CLI list/rm/run/request` — direct-DB + direct-crypto (standard
+ tier; UDS deferred to P1, §5). The original P0 CLI create path was later removed:
+ agent-facing CLI commands no longer accept plaintext create. End-to-end verified:
+ `run` injects to child env with **no stdout leak**. **[done — 2026-06-21]**
+3b. `feat(vault): fetch` — M4 brokered HTTP + domain binding (browser-created
+ `allowed_hosts` + `auth` policy; secret attached at egress, refused for non-allowed
hosts before decrypt; response body passed through, never the secret).
**[done — 2026-06-21]**
3c. `feat(vault): export/inject delivery` — help-only `export` (eval stream) +
@@ -260,8 +263,9 @@ stay queryable.
- **Unit**: crypto round-trip + wrong-key auth-fail; name regex; `data query`
denylist (assert `SELECT * FROM vault_secrets` is denied, others allowed);
reply_enhancer `$<NAME>` extraction + fence guard.
-- **CLI**: `set` (stdin) → `run` injects env to child, value absent from stdout;
- `request --wait` blocks then returns on fulfill.
+- **CLI**: create/set is intentionally absent from agent-facing commands; `run`
+ injects env to child with value absent from stdout; `request --wait` blocks then
+ returns on fulfill.
- **API**: reads return masked previews, never plaintext; CSRF on mutations.
- **Scenario** (`tests/scenarios/`): agent emits `$<KEY>` → card → fulfill →
name-only wake-up → `vault run` succeeds. Surface a scenario ID.
diff --git a/docs/plans/vaults.md b/docs/plans/vaults.md
index c7b34d10b..acb40a305 100644
--- a/docs/plans/vaults.md
+++ b/docs/plans/vaults.md
@@ -456,8 +456,8 @@ approval with `{group, gmk, ttl, session_binding}` / revoke; §9.5),
Internal UDS `/internal/vault/*`: `resolve`, `provision`, `sign`, `fetch`,
`requests/{id}/wait`.
-CLI `vibe vault …`: `set NAME [--protected] [--group G] [--tag t] --stdin|--from-file f`
-· `list [--skill S] [--group G] [--tag t] [--json]` · `rm` · `run` (promoted) ·
+CLI `vibe vault …`: create/set is intentionally not exposed to agents; values
+enter through browser-side sealed/blind-box payloads. `list [--skill S] [--group G] [--tag t] [--json]` · `rm` · `run` (promoted) ·
`fetch` (promoted) · `sign` (promoted) · `request` · `link/unlink --skill S NAME` ·
`audit` · `key export/import` · `import 1password [--vault V]` (§13.5) · `export` /
`inject` (help-only, not promoted). No `vibe vault get`; no command prints a value.
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index 988d27a55..e4dacf1bb 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -97,18 +97,82 @@ def test_create_list_delete_roundtrip(monkeypatch):
assert api.get_vault_secrets()["secrets"] == []
-def test_standard_rest_create_uses_plaintext_fallback_when_pinned_avault_lacks_blind_box(monkeypatch):
+def test_standard_rest_create_rejects_plaintext_value(monkeypatch):
from unittest.mock import Mock
- seal = Mock(return_value=_sealed("fallback"))
- blind_box = Mock(side_effect=api.AvaultError(f"blind-box seal requires avault >= {api.AVAULT_P2_MIN_VERSION}"))
- monkeypatch.setattr(api, "avault_seal", seal)
+ blind_box = Mock()
monkeypatch.setattr(api, "avault_seal_blind_box", blind_box)
- created = api.create_vault_secret({"name": "OPENAI_API_KEY", "value": "secret"})
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({"name": "OPENAI_API_KEY", "value": "secret"})
- assert created["secret"]["name"] == "OPENAI_API_KEY"
- seal.assert_called_once_with("OPENAI_API_KEY", b"secret")
+ assert exc.value.code == "plaintext_value_rejected"
+ blind_box.assert_not_called()
+
+
+def test_create_rejects_plaintext_value_even_with_sealed_payload(monkeypatch):
+ from unittest.mock import Mock
+
+ blind_box = Mock()
+ monkeypatch.setattr(api, "avault_seal_blind_box", blind_box)
+
+ with pytest.raises(api.VaultApiError) as standard_exc:
+ api.create_vault_secret(
+ {
+ "name": "MIXED_KEY",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "value": "secret",
+ }
+ )
+ assert standard_exc.value.code == "plaintext_value_rejected"
+
+ with pytest.raises(api.VaultApiError) as protected_exc:
+ api.create_vault_secret(
+ {
+ "name": "PROTECTED_MIXED",
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},
+ "value": "secret",
+ }
+ )
+ assert protected_exc.value.code == "plaintext_value_rejected"
+ blind_box.assert_not_called()
+
+
+def test_create_rejects_nested_plaintext_value_fields(monkeypatch):
+ from unittest.mock import Mock
+
+ blind_box = Mock()
+ monkeypatch.setattr(api, "avault_seal_blind_box", blind_box)
+
+ with pytest.raises(api.VaultApiError) as standard_exc:
+ api.create_vault_secret(
+ {
+ "name": "NESTED_STANDARD",
+ "blind_box": {
+ "scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1",
+ "enc": "enc",
+ "ct": "ct",
+ "value": "secret",
+ },
+ }
+ )
+ assert standard_exc.value.code == "plaintext_value_rejected"
+
+ with pytest.raises(api.VaultApiError) as protected_exc:
+ api.create_vault_secret(
+ {
+ "name": "NESTED_PROTECTED",
+ "protection": "protected",
+ "sealed": {
+ "ciphertext": "ct",
+ "nonce": "n",
+ "wrap_meta": "wm",
+ "value": "secret",
+ },
+ }
+ )
+ assert protected_exc.value.code == "plaintext_value_rejected"
blind_box.assert_not_called()
@@ -156,7 +220,7 @@ def test_rest_plaintext_value_rejected_before_avault(monkeypatch):
monkeypatch.setattr(api, "avault_seal_blind_box", seal)
with pytest.raises(api.VaultApiError) as exc:
api.create_vault_secret({"name": "NO_PLAINTEXT", "protection": "protected", "value": "secret"})
- assert exc.value.code == "invalid_envelope"
+ assert exc.value.code == "plaintext_value_rejected"
seal.assert_not_called()
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index 28b6dd51c..8691be9b5 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -59,16 +59,9 @@ PROTECTED_SIGNING_PUBLIC_META = {
}
-def _set_secret(name: str, value: str, tmp_path, monkeypatch, capfd, *, sealed: Sealed | None = None):
- from vibe import api
-
- vf = tmp_path / f"{name}.txt"
- vf.write_text(value)
- seal_mock = Mock(return_value=sealed or _sealed())
- monkeypatch.setattr(api, "avault_seal", seal_mock)
- assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf))) == 0
- capfd.readouterr()
- return seal_mock
+def _create_standard_secret(name: str, *, sealed: Sealed | None = None, **kwargs):
+ with cli._open_vault_engine().begin() as conn:
+ return vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(), **kwargs)
def _set_protected_grant(name: str, *, session_id: str | None = None) -> dict:
@@ -169,30 +162,14 @@ def test_parse_env_specs(specs, expected):
assert cli._parse_env_specs(specs) == expected
-def test_set_seals_with_avault_without_value_derived_metadata(tmp_path, capfd, monkeypatch):
- from unittest.mock import Mock
-
- from vibe import api
-
- vf = tmp_path / "value.txt"
- vf.write_text("sk-ant-abcd1234")
- seal = Mock(return_value=_sealed("saved"))
- monkeypatch.setattr(api, "avault_seal", seal)
-
- assert cli.cmd_vault_set(_ns(name="OPENAI_API_KEY", from_file=str(vf), description="key")) == 0
- payload = json.loads(capfd.readouterr().out)
- secret = payload["secret"]
- assert secret["name"] == "OPENAI_API_KEY"
- assert "preview" not in secret
- assert "sk-ant-abcd1234" not in json.dumps(payload)
- assert "1234" not in json.dumps(payload)
- seal.assert_called_once_with("OPENAI_API_KEY", b"sk-ant-abcd1234")
- with cli._open_vault_engine().connect() as conn:
- assert vault_service.get_envelope(conn, "OPENAI_API_KEY") == _sealed("saved")
+def test_vault_parser_does_not_expose_plaintext_set_command():
+ parser = cli.build_parser()
+ with pytest.raises(SystemExit):
+ parser.parse_args(["vault", "set", "OPENAI_API_KEY", "--stdin"])
def test_discover_reports_value_free_capabilities(tmp_path, capfd, monkeypatch):
- _set_secret("STANDARD_KEY", "secret", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("STANDARD_KEY")
with cli._open_vault_engine().begin() as conn:
vault_service.create_secret(
conn,
@@ -244,7 +221,7 @@ def test_discover_reports_value_free_capabilities(tmp_path, capfd, monkeypatch):
def test_access_request_cli_uses_caller_session(tmp_path, capfd, monkeypatch):
- _set_secret("STANDARD_KEY", "secret", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("STANDARD_KEY")
monkeypatch.setenv("AVIBE_SESSION_ID", "ses_cli")
assert cli.cmd_vault_access(_ns(name="STANDARD_KEY", command="python sync.py")) == 0
@@ -391,51 +368,12 @@ def test_vault_await_wait_keeps_waiting_from_signing_status(capfd, monkeypatch):
assert payload["result"] == {"type": "signature", "signature": {"signature": "ab" * 64, "recovery_id": 1}}
-def test_set_rejects_invalid_name_before_avault(tmp_path, capfd, monkeypatch):
- from unittest.mock import Mock
-
- from vibe import api
-
- vf = tmp_path / "v.txt"
- vf.write_text("x")
- seal = Mock(return_value=_sealed())
- monkeypatch.setattr(api, "avault_seal", seal)
-
- code = cli.cmd_vault_set(_ns(name="lower_bad", from_file=str(vf)))
- captured = capfd.readouterr()
- assert code == 1
- assert json.loads(captured.err)["code"] == "invalid_name"
- seal.assert_not_called()
-
-
-def test_set_requires_one_value_source(capfd):
- code = cli.cmd_vault_set(_ns(name="NO_SOURCE"))
- captured = capfd.readouterr()
- assert code == 1
- assert json.loads(captured.err)["code"] == "missing_value_source"
-
-
-def test_set_maps_avault_failure(tmp_path, capfd, monkeypatch):
- from unittest.mock import Mock
-
- from vibe import api
-
- vf = tmp_path / "v.txt"
- vf.write_text("x")
- monkeypatch.setattr(api, "avault_seal", Mock(side_effect=api.AvaultError("boom")))
-
- code = cli.cmd_vault_set(_ns(name="FAIL_KEY", from_file=str(vf)))
- captured = capfd.readouterr()
- assert code == 1
- assert json.loads(captured.err)["code"] == "avault_failed"
-
-
def test_run_calls_avault_with_env_mapping_and_records_delivery(tmp_path, capfd, monkeypatch):
from unittest.mock import Mock
from vibe import api
- _set_secret("SRC_KEY", "secret-RUNVAL-42", tmp_path, monkeypatch, capfd, sealed=_sealed("run"))
+ _create_standard_secret("SRC_KEY", sealed=_sealed("run"))
deliver = Mock(return_value=0)
monkeypatch.setattr(api, "avault_deliver_run", deliver)
@@ -1131,7 +1069,7 @@ def test_expire_agent_grant_after_missing_does_not_reserve_replacement_grant(tmp
def test_run_rejects_mixed_tiers_before_creating_approval(tmp_path, capfd, monkeypatch):
- _set_secret("STANDARD_KEY", "standard", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("STANDARD_KEY")
with cli._open_vault_engine().begin() as conn:
vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
@@ -1277,7 +1215,7 @@ def test_run_records_delivery_when_legacy_avault_returns_70(tmp_path, capfd, mon
from vibe import api
- _set_secret("NODELIVER_KEY", "secret", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("NODELIVER_KEY")
monkeypatch.setattr(api, "avault_deliver_run", Mock(return_value=70))
assert cli.cmd_vault_run(_ns(env=["NODELIVER_KEY"], command_argv=["python3", "-c", "pass"])) == 70
@@ -1308,7 +1246,7 @@ def test_run_bad_command_does_not_call_avault_or_deliver(tmp_path, capfd, monkey
from vibe import api
- _set_secret("NODELIVER_KEY", "v", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("NODELIVER_KEY")
deliver = Mock(return_value=0)
monkeypatch.setattr(api, "avault_deliver_run", deliver)
@@ -1357,31 +1295,11 @@ def test_request_creates_pending(capfd):
def test_request_for_existing_secret_returns_fulfilled(tmp_path, capfd, monkeypatch):
- _set_secret("HAVE_KEY", "v", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("HAVE_KEY")
assert cli.cmd_vault_request(_ns(name="HAVE_KEY", wait=30)) == 0
assert json.loads(capfd.readouterr().out)["status"] == "fulfilled"
-def test_from_file_preserves_trailing_newline(tmp_path):
- vf = tmp_path / "key.pem"
- vf.write_text("-----BEGIN-----\nabc\n-----END-----\n")
- value = cli._read_secret_value(_ns(from_file=str(vf)), help_command="x")
- assert value == "-----BEGIN-----\nabc\n-----END-----\n"
-
-
-def test_from_file_preserves_crlf(tmp_path):
- vf = tmp_path / "win.pem"
- vf.write_bytes(b"line1\r\nline2\r\n")
- assert cli._read_secret_value(_ns(from_file=str(vf)), help_command="x") == "line1\r\nline2\r\n"
-
-
-def test_stdin_strips_only_one_trailing_newline(monkeypatch):
- monkeypatch.setattr("sys.stdin", io.StringIO("tok\n"))
- assert cli._read_secret_value(_ns(stdin=True), help_command="x") == "tok"
- monkeypatch.setattr("sys.stdin", io.StringIO("tok\n\n"))
- assert cli._read_secret_value(_ns(stdin=True), help_command="x") == "tok\n"
-
-
def test_key_export_calls_avault_and_audits(tmp_path, capfd, monkeypatch):
from unittest.mock import Mock
diff --git a/tests/test_vault_export_inject.py b/tests/test_vault_export_inject.py
index b2c9073a7..9e6c01de0 100644
--- a/tests/test_vault_export_inject.py
+++ b/tests/test_vault_export_inject.py
@@ -37,16 +37,9 @@ def _sealed(suffix: str = "1") -> Sealed:
return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
-def _set(name, value, tmp_path, monkeypatch, capfd, *, sealed: Sealed | None = None):
- from unittest.mock import Mock
-
- from vibe import api
-
- vf = tmp_path / f"{name}.txt"
- vf.write_text(value)
- monkeypatch.setattr(api, "avault_seal", Mock(return_value=sealed or _sealed(name.lower())))
- assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf))) == 0
- capfd.readouterr()
+def _create_standard_secret(name: str, *, sealed: Sealed | None = None):
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name=name, sealed=sealed or _sealed(name.lower()))
def _set_protected_grant(name: str, *, session_id: str | None = None) -> dict:
@@ -82,8 +75,8 @@ def test_inject_calls_avault_and_records_delivery(tmp_path, capfd, monkeypatch,
from vibe import api
- _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd, sealed=_sealed("a"))
- _set("B_KEY", "beta-2", tmp_path, monkeypatch, capfd, sealed=_sealed("b"))
+ _create_standard_secret("A_KEY", sealed=_sealed("a"))
+ _create_standard_secret("B_KEY", sealed=_sealed("b"))
inject = Mock(return_value=None)
monkeypatch.setattr(api, "avault_deliver_inject", inject)
out = tmp_path / f"secrets.{fmt}"
@@ -210,7 +203,7 @@ def test_inject_rejects_unavailable_formats_before_avault(tmp_path, capfd, monke
from vibe import api
- _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("A_KEY")
inject = Mock(return_value=None)
monkeypatch.setattr(api, "avault_deliver_inject", inject)
@@ -226,7 +219,7 @@ def test_inject_unknown_format_rejected_before_avault(tmp_path, capfd, monkeypat
from vibe import api
- _set("K", "v", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("K")
inject = Mock(return_value=None)
monkeypatch.setattr(api, "avault_deliver_inject", inject)
@@ -241,7 +234,7 @@ def test_inject_dedupes_repeated_keys(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd, sealed=_sealed("a"))
+ _create_standard_secret("A_KEY", sealed=_sealed("a"))
inject = Mock(return_value=None)
monkeypatch.setattr(api, "avault_deliver_inject", inject)
@@ -258,7 +251,7 @@ def test_inject_payload_does_not_leak_value(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("SECRET_KEY", "topsecret-INJECT", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("SECRET_KEY")
monkeypatch.setattr(api, "avault_deliver_inject", Mock(return_value=None))
cli.cmd_vault_inject(_ns(keys="SECRET_KEY", out=str(tmp_path / "s.env"), format="dotenv"))
@@ -271,7 +264,7 @@ def test_inject_does_not_record_delivery_when_avault_fails(tmp_path, capfd, monk
from vibe import api
- _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("A_KEY")
monkeypatch.setattr(api, "avault_deliver_inject", Mock(side_effect=api.AvaultError("boom")))
code = cli.cmd_vault_inject(_ns(keys="A_KEY", out=str(tmp_path / "fail.env"), format="dotenv"))
@@ -287,7 +280,7 @@ def test_inject_succeeds_even_if_audit_fails(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("A_KEY")
monkeypatch.setattr(api, "avault_deliver_inject", Mock(return_value=None))
def _boom(*a, **k):
diff --git a/tests/test_vault_fetch.py b/tests/test_vault_fetch.py
index 6b21438e4..aa5f908c2 100644
--- a/tests/test_vault_fetch.py
+++ b/tests/test_vault_fetch.py
@@ -44,16 +44,27 @@ def _sealed(suffix: str = "1") -> Sealed:
return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
-def _set(name, value, tmp_path, monkeypatch, capfd, **kw):
- from unittest.mock import Mock
-
- from vibe import api
-
- vf = tmp_path / f"{name}.txt"
- vf.write_text(value)
- monkeypatch.setattr(api, "avault_seal", Mock(return_value=_sealed(name.lower())))
- assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf), **kw)) == 0
- capfd.readouterr()
+def _create_standard_secret(
+ name: str,
+ *,
+ allow_host: list[str] | None = None,
+ auth_header: str | None = None,
+ auth_query: str | None = None,
+) -> None:
+ policy: dict = {}
+ if allow_host:
+ policy["allowed_hosts"] = allow_host
+ if auth_header:
+ policy["auth"] = {"type": "header", "name": auth_header}
+ elif auth_query:
+ policy["auth"] = {"type": "query", "name": auth_query}
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name=name,
+ sealed=_sealed(name.lower()),
+ policy=policy or None,
+ )
def _set_protected_grant(name: str, *, allow_host: list[str], session_id: str | None = None) -> dict:
@@ -107,7 +118,7 @@ def test_fetch_passes_bearer_request_to_avault_and_writes_stdout(tmp_path, capfd
from vibe import api
- _set("GH_PAT", "ghp-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.github.com"])
+ _create_standard_secret("GH_PAT", allow_host=["api.github.com"])
fetch = Mock(return_value={"status": 200, "headers": {"content-type": "application/json"}, "body": '{"ok":true}'})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -204,7 +215,7 @@ def test_fetch_header_auth_request_shape(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("SVC_KEY", "apikey-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"], auth_header="X-Api-Key")
+ _create_standard_secret("SVC_KEY", allow_host=["api.example.com"], auth_header="X-Api-Key")
fetch = Mock(return_value={"status": 204, "headers": {}, "body": ""})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -218,7 +229,7 @@ def test_fetch_query_auth_request_shape(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("QUERY_KEY", "query-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"], auth_query="api_key")
+ _create_standard_secret("QUERY_KEY", allow_host=["api.example.com"], auth_query="api_key")
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -232,7 +243,7 @@ def test_fetch_post_body_and_headers_pass_to_avault(tmp_path, capfd, monkeypatch
from vibe import api
- _set("POST_KEY", "k", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("POST_KEY", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 201, "headers": {}, "body": "created"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -256,7 +267,7 @@ def test_fetch_writes_mocked_response_to_output_file(tmp_path, capfd, monkeypatc
from vibe import api
- _set("OUT_KEY", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("OUT_KEY", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "file body"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
out = tmp_path / "resp.txt"
@@ -278,7 +289,7 @@ def test_fetch_preflights_reject_before_avault(tmp_path, capfd, monkeypatch, url
from vibe import api
- _set("BOUND_KEY", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("BOUND_KEY", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -295,7 +306,7 @@ def test_fetch_refuses_unbound_secret_before_avault(tmp_path, capfd, monkeypatch
from vibe import api
- _set("UNBOUND_KEY", "secret", tmp_path, monkeypatch, capfd)
+ _create_standard_secret("UNBOUND_KEY")
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -311,7 +322,7 @@ def test_fetch_rejects_trace_method_before_avault(tmp_path, capfd, monkeypatch):
from vibe import api
- _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("GH_PAT", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -327,7 +338,7 @@ def test_fetch_rejects_host_header_override_before_avault(tmp_path, capfd, monke
from vibe import api
- _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("GH_PAT", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -338,21 +349,20 @@ def test_fetch_rejects_host_header_override_before_avault(tmp_path, capfd, monke
fetch.assert_not_called()
-def test_set_rejects_host_auth_header_before_avault(tmp_path, capfd, monkeypatch):
+def test_fetch_rejects_stored_host_auth_policy_before_avault(capfd, monkeypatch):
from unittest.mock import Mock
from vibe import api
- vf = tmp_path / "v.txt"
- vf.write_text("tok")
- seal = Mock(return_value=_sealed())
- monkeypatch.setattr(api, "avault_seal", seal)
+ _create_standard_secret("HOST_AUTH_KEY", allow_host=["api.example.com"], auth_header="Host")
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
- code = cli.cmd_vault_set(_ns(name="HOST_AUTH_KEY", from_file=str(vf), allow_host=["api.example.com"], auth_header="Host"))
+ code = cli.cmd_vault_fetch(_ns(auth="HOST_AUTH_KEY", url="https://api.example.com/x"))
captured = capfd.readouterr()
assert code == 1
assert json.loads(captured.err)["code"] == "forbidden_header"
- seal.assert_not_called()
+ fetch.assert_not_called()
def test_fetch_output_unwritable_is_preflighted_before_avault(tmp_path, capfd, monkeypatch):
@@ -360,7 +370,7 @@ def test_fetch_output_unwritable_is_preflighted_before_avault(tmp_path, capfd, m
from vibe import api
- _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("GH_PAT", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
@@ -377,7 +387,7 @@ def test_fetch_returns_response_even_if_audit_fails(tmp_path, capfd, monkeypatch
from vibe import api
- _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ _create_standard_secret("GH_PAT", allow_host=["api.example.com"])
fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
diff --git a/tests/test_vault_rest.py b/tests/test_vault_rest.py
index a81361f0a..8a0cfa50b 100644
--- a/tests/test_vault_rest.py
+++ b/tests/test_vault_rest.py
@@ -30,7 +30,7 @@ def test_rest_create_rejects_protected_plaintext_value(monkeypatch):
)
assert response.status_code == 400
- assert response.get_json()["code"] == "invalid_envelope"
+ assert response.get_json()["code"] == "plaintext_value_rejected"
seal.assert_not_called()
@@ -51,9 +51,9 @@ def test_rest_create_accepts_blind_box(monkeypatch):
seal.assert_called_once_with("REST_KEY", blind_box)
-def test_rest_create_accepts_standard_value_fallback(monkeypatch):
- seal = Mock(return_value=_sealed("rest-fallback"))
- monkeypatch.setattr(api, "avault_seal", seal)
+def test_rest_create_rejects_standard_plaintext_value(monkeypatch):
+ seal = Mock()
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
client = app.test_client()
response = client.post(
@@ -62,9 +62,81 @@ def test_rest_create_accepts_standard_value_fallback(monkeypatch):
headers=csrf_headers(client),
)
- assert response.status_code == 200
- assert response.get_json()["secret"]["name"] == "REST_FALLBACK"
- seal.assert_called_once_with("REST_FALLBACK", b"secret")
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "plaintext_value_rejected"
+ seal.assert_not_called()
+
+
+def test_rest_create_rejects_plaintext_value_in_mixed_payloads(monkeypatch):
+ seal = Mock()
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
+ client = app.test_client()
+
+ standard = client.post(
+ "/api/vault/secrets",
+ json={
+ "name": "MIXED_REST",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "value": "secret",
+ },
+ headers=csrf_headers(client),
+ )
+ protected = client.post(
+ "/api/vault/secrets",
+ json={
+ "name": "MIXED_PROTECTED_REST",
+ "protection": "protected",
+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},
+ "value": "secret",
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert standard.status_code == 400
+ assert standard.get_json()["code"] == "plaintext_value_rejected"
+ assert protected.status_code == 400
+ assert protected.get_json()["code"] == "plaintext_value_rejected"
+ seal.assert_not_called()
+
+
+def test_rest_create_rejects_nested_plaintext_value_fields(monkeypatch):
+ seal = Mock()
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
+ client = app.test_client()
+
+ standard = client.post(
+ "/api/vault/secrets",
+ json={
+ "name": "NESTED_REST",
+ "blind_box": {
+ "scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1",
+ "enc": "enc",
+ "ct": "ct",
+ "value": "secret",
+ },
+ },
+ headers=csrf_headers(client),
+ )
+ protected = client.post(
+ "/api/vault/secrets",
+ json={
+ "name": "NESTED_PROTECTED_REST",
+ "protection": "protected",
+ "sealed": {
+ "ciphertext": "ct",
+ "nonce": "n",
+ "wrap_meta": "wm",
+ "value": "secret",
+ },
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert standard.status_code == 400
+ assert standard.get_json()["code"] == "plaintext_value_rejected"
+ assert protected.status_code == 400
+ assert protected.get_json()["code"] == "plaintext_value_rejected"
+ seal.assert_not_called()
def test_rest_agent_pubkey_route(monkeypatch):
diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsx
index aeede44fc..5fc9a4f24 100644
--- a/ui/src/components/ui/vault-secret-form.tsx
+++ b/ui/src/components/ui/vault-secret-form.tsx
@@ -6,11 +6,14 @@ import {
Copy,
Eye,
EyeOff,
+ FileText,
Loader2,
RefreshCw,
Server,
ShieldCheck,
SlidersHorizontal,
+ UploadCloud,
+ X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -31,12 +34,18 @@ import { Combobox } from './combobox';
import { Input } from './input';
import { SegmentedRadio } from './segmented';
import { TagInput } from './tag-input';
+import { Textarea } from './textarea';
import { VaultProtectedUnlock } from './vault-protected-unlock';
type VaultKind = 'static' | 'keypair';
+type FetchAuthMode = 'bearer' | 'header' | 'query';
+type StaticSecretSource = 'text' | 'file';
const AVAULT_P2_MIN_VERSION = '0.1.3';
const DEFAULT_GROUP = 'default';
+const MAX_SECRET_FILE_BYTES = 1024 * 1024;
+const HTTP_HEADER_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+const QUERY_PARAM_RE = /^[A-Za-z0-9._~-]+$/;
// Accept only what the brokered fetch matcher (`_host_allowed` in vibe/cli.py) can
// actually match against `urlsplit(url).hostname`: a bare hostname (`api.example.com`,
@@ -60,6 +69,12 @@ function normalizeHost(raw: string): string | null {
}
type VaultProtection = 'standard' | 'protected';
+function humanSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
+
function versionAtLeast(current: string | null | undefined, minimum: string): boolean {
if (!current) return false;
const parse = (value: string) =>
@@ -86,10 +101,6 @@ function avaultP2Ready(dep: DependencyItem | null): boolean {
return dep?.status === 'ready' && versionAtLeast(dep.version, AVAULT_P2_MIN_VERSION);
}
-function avaultInstalled(dep: DependencyItem | null): boolean {
- return Boolean(dep?.installed);
-}
-
/** Shared field label — 13px medium, matches design.pen create-dialog field labels. */
const FIELD_LABEL = 'text-[13px] font-medium text-foreground';
@@ -114,6 +125,8 @@ export const VaultSecretForm: React.FC<{
const api = useApi();
const [name, setName] = useState(fixedName ?? '');
const [value, setValue] = useState('');
+ const [staticSource, setStaticSource] = useState<StaticSecretSource>('text');
+ const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [kind, setKind] = useState<VaultKind>('static');
const [signingSource, setSigningSource] = useState<'generate' | 'import'>('generate');
const [importHex, setImportHex] = useState('');
@@ -124,6 +137,8 @@ export const VaultSecretForm: React.FC<{
const [tags, setTags] = useState<string[]>([]);
const [description, setDescription] = useState('');
const [allowHosts, setAllowHosts] = useState<string[]>([]);
+ const [fetchAuthMode, setFetchAuthMode] = useState<FetchAuthMode>('bearer');
+ const [fetchAuthName, setFetchAuthName] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const [tagsPending, setTagsPending] = useState(false);
const [hostsPending, setHostsPending] = useState(false);
@@ -163,11 +178,11 @@ export const VaultSecretForm: React.FC<{
}, [protection]);
const p2Ready = useMemo(() => avaultP2Ready(avaultDep), [avaultDep]);
- const standardCreateReady = useMemo(() => avaultInstalled(avaultDep), [avaultDep]);
const secretName = (fixedName ?? name).trim().toUpperCase();
const protectedCreateReady = protectedVault.status === 'unlocked';
const isKeypair = kind === 'keypair';
const isProvision = Boolean(fixedName);
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
// Hold the latest key material in a ref too, so the unmount cleanup can zero
// the *current* private key (a [] effect would capture a stale value).
@@ -193,16 +208,12 @@ export const VaultSecretForm: React.FC<{
[],
);
- const valueReady = isKeypair ? signingKey != null : Boolean(value);
- // Standard signing keys are blind-boxed to avault, so they need the P2 surface;
- // protected signing keys are sealed under the browser VMK and signed locally, so they
- // only need the vault unlocked (gated below via protectedCreateReady).
- const keypairRequirementsMet = !isKeypair || protection === 'protected' || p2Ready;
+ const staticValueReady = staticSource === 'file' ? selectedFile != null && selectedFile.size > 0 : Boolean(value);
+ const valueReady = isKeypair ? signingKey != null : staticValueReady;
const canSubmit =
Boolean(secretName && valueReady) &&
- keypairRequirementsMet &&
!submitting &&
- ((protection === 'standard' && standardCreateReady) || (protection === 'protected' && protectedCreateReady));
+ ((protection === 'standard' && p2Ready) || (protection === 'protected' && protectedCreateReady));
const handleExistingSecret = () => {
if (treatExistingAsFulfilled) {
@@ -213,9 +224,46 @@ export const VaultSecretForm: React.FC<{
setError(t('vaults.dialog.errors.secretExists'));
};
+ const clearSelectedFile = () => {
+ setSelectedFile(null);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ };
+
+ const chooseFile = (file: File | null) => {
+ if (!file) {
+ clearSelectedFile();
+ return;
+ }
+ if (file.size === 0) {
+ clearSelectedFile();
+ setError(t('vaults.dialog.errors.fileEmpty'));
+ return;
+ }
+ if (file.size > MAX_SECRET_FILE_BYTES) {
+ clearSelectedFile();
+ setError(t('vaults.dialog.errors.fileTooLarge', { size: humanSize(MAX_SECRET_FILE_BYTES) }));
+ return;
+ }
+ setError(null);
+ setSelectedFile(file);
+ setValue('');
+ };
+
+ const switchStaticSource = (next: StaticSecretSource) => {
+ if (next === staticSource) return;
+ setStaticSource(next);
+ setError(null);
+ if (next === 'file') {
+ setValue('');
+ } else {
+ clearSelectedFile();
+ }
+ };
+
const onSubmit = async (event: FormEvent) => {
event.preventDefault();
if (!canSubmit) return;
+ let fileBytesToWipe: Uint8Array | null = null;
// Don't silently drop a half-typed tag/host chip the user can still see. Tags live in the
// create-mode Advanced collapsible; the allowed-hosts input is in Advanced (create) and
// always visible in provision mode — guard whichever is on screen. Collapsing Advanced
@@ -225,6 +273,31 @@ export const VaultSecretForm: React.FC<{
setError(t('vaults.dialog.errors.pendingDraft'));
return;
}
+ const normalizedFetchAuthName = fetchAuthName.trim();
+ if (fetchAuthMode === 'header') {
+ if (!normalizedFetchAuthName) {
+ setError(t('vaults.dialog.errors.authNameRequired'));
+ return;
+ }
+ if (!HTTP_HEADER_TOKEN_RE.test(normalizedFetchAuthName)) {
+ setError(t('vaults.dialog.errors.authHeaderInvalid'));
+ return;
+ }
+ if (normalizedFetchAuthName.toLowerCase() === 'host') {
+ setError(t('vaults.dialog.errors.authHeaderForbidden'));
+ return;
+ }
+ }
+ if (fetchAuthMode === 'query') {
+ if (!normalizedFetchAuthName) {
+ setError(t('vaults.dialog.errors.authNameRequired'));
+ return;
+ }
+ if (!QUERY_PARAM_RE.test(normalizedFetchAuthName)) {
+ setError(t('vaults.dialog.errors.authQueryInvalid'));
+ return;
+ }
+ }
setSubmitting(true);
setError(null);
try {
@@ -233,6 +306,11 @@ export const VaultSecretForm: React.FC<{
// it; protected-tier rejects it). It returns once backend support lands (PR #722).
const policy: Record<string, unknown> = {};
if (allowHosts.length) policy.allowed_hosts = allowHosts;
+ if (fetchAuthMode === 'header') {
+ policy.auth = { type: 'header', name: normalizedFetchAuthName };
+ } else if (fetchAuthMode === 'query') {
+ policy.auth = { type: 'query', name: normalizedFetchAuthName };
+ }
const base = {
name: secretName,
protection,
@@ -253,11 +331,22 @@ export const VaultSecretForm: React.FC<{
// For a signing key the sealed value is the raw 32-byte private key (avault
// opens it back into a 32-byte signing key); for a static secret it is the
// entered string.
- const plaintext: Uint8Array | string = isKeypair && signingKey ? signingKey.privateKey : value;
+ let plaintext: Uint8Array | string;
+ if (isKeypair && signingKey) {
+ plaintext = signingKey.privateKey;
+ } else if (staticSource === 'file' && selectedFile) {
+ try {
+ fileBytesToWipe = new Uint8Array(await selectedFile.arrayBuffer());
+ } catch (err) {
+ throw new Error(t('vaults.dialog.errors.fileReadFailed'), { cause: err });
+ }
+ plaintext = fileBytesToWipe;
+ } else {
+ plaintext = value;
+ }
let cryptoFields:
| { sealed: ProtectedRecordEnvelope }
- | { blind_box: Awaited<ReturnType<typeof sealBlindBox>> }
- | { value: string };
+ | { blind_box: Awaited<ReturnType<typeof sealBlindBox>> };
let establishingVmk = false;
if (protection === 'protected') {
// Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no
@@ -265,13 +354,9 @@ export const VaultSecretForm: React.FC<{
const sealed = await protectedVault.sealValue(secretName, plaintext);
cryptoFields = { sealed: sealed.envelope };
establishingVmk = sealed.establishingVmk;
- } else if (p2Ready) {
+ } else {
const pubkey = await api.getVaultPubkey();
cryptoFields = { blind_box: await sealBlindBox(plaintext, pubkey, standardCreateBlindBoxContext(secretName)) };
- } else {
- // Plain-value fallback exists only for static secrets; signing keys require
- // the avault P2 surface (gated by canSubmit), so plaintext is a string here.
- cryptoFields = { value };
}
const created = await api.createVaultSecret(
{ ...base, ...cryptoFields, ...(establishingVmk ? { establishing_vmk: true } : {}) },
@@ -293,8 +378,12 @@ export const VaultSecretForm: React.FC<{
}
if (protection === 'protected') protectedVault.afterCreated();
setValue('');
+ setStaticSource('text');
+ clearSelectedFile();
applySigningKey(null);
setImportHex('');
+ setFetchAuthMode('bearer');
+ setFetchAuthName('');
onCreated(secretName, 'created');
} catch (err: unknown) {
if (err instanceof Error && err.message.includes('fingerprint mismatch')) {
@@ -309,30 +398,122 @@ export const VaultSecretForm: React.FC<{
setError(err instanceof Error ? err.message : String(err));
}
} finally {
+ fileBytesToWipe?.fill(0);
setSubmitting(false);
}
};
const valueField = (
- <div className="flex items-center gap-2">
- <Input
- type={showValue ? 'text' : 'password'}
- value={value}
- onChange={(event) => setValue(event.target.value)}
- placeholder={t('vaults.dialog.valuePlaceholder')}
- autoFocus={isProvision}
- required
- className="min-w-0 flex-1 font-mono"
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- onClick={() => setShowValue((current) => !current)}
- aria-label={showValue ? t('vaults.dialog.hideValue') : t('vaults.dialog.showValue')}
- >
- {showValue ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
- </Button>
+ <div className="flex flex-col gap-2">
+ <div className="self-start">
+ <SegmentedRadio<StaticSecretSource>
+ value={staticSource}
+ onChange={switchStaticSource}
+ disabled={submitting}
+ ariaLabel={t('vaults.dialog.valueSource')}
+ options={[
+ { id: 'text', label: t('vaults.dialog.valueSourceText') },
+ { id: 'file', label: t('vaults.dialog.valueSourceFile') },
+ ]}
+ />
+ </div>
+ {staticSource === 'text' ? (
+ <div className="flex items-start gap-2">
+ {showValue ? (
+ <Textarea
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ placeholder={t('vaults.dialog.valuePlaceholder')}
+ autoFocus={isProvision}
+ required
+ spellCheck={false}
+ autoComplete="off"
+ className="min-h-[96px] min-w-0 flex-1 resize-y font-mono text-xs leading-relaxed"
+ />
+ ) : (
+ <Input
+ type="password"
+ value={value}
+ onChange={(event) => setValue(event.target.value)}
+ placeholder={t('vaults.dialog.valuePlaceholder')}
+ autoFocus={isProvision}
+ required
+ spellCheck={false}
+ autoComplete="off"
+ className="h-24 min-w-0 flex-1 font-mono text-xs"
+ />
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => setShowValue((current) => !current)}
+ aria-label={showValue ? t('vaults.dialog.hideValue') : t('vaults.dialog.showValue')}
+ >
+ {showValue ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
+ </Button>
+ </div>
+ ) : (
+ <div className="rounded-[10px] border border-dashed border-border-strong bg-surface p-3">
+ <input
+ ref={fileInputRef}
+ type="file"
+ className="hidden"
+ onChange={(event) => chooseFile(event.target.files?.[0] ?? null)}
+ />
+ {selectedFile ? (
+ <div className="flex items-center gap-2.5">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-mint/40 bg-mint-soft text-mint">
+ <FileText className="size-4" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate font-mono text-[12px] text-foreground">{selectedFile.name}</span>
+ <span className="text-[10.5px] text-muted">{humanSize(selectedFile.size)}</span>
+ </div>
+ <Button type="button" variant="ghost" size="icon" onClick={() => fileInputRef.current?.click()} aria-label={t('vaults.dialog.replaceSecretFile')}>
+ <RefreshCw className="size-4" />
+ </Button>
+ <Button type="button" variant="ghost" size="icon" onClick={clearSelectedFile} aria-label={t('vaults.dialog.clearSecretFile')}>
+ <X className="size-4" />
+ </Button>
+ </div>
+ ) : (
+ <button type="button" onClick={() => fileInputRef.current?.click()} className="flex w-full flex-col items-center gap-1.5 py-3 text-center">
+ <UploadCloud className="size-6 text-muted" />
+ <span className="text-[12px] text-muted">{t('vaults.dialog.chooseSecretFile')}</span>
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+
+ const fetchAuthPolicyFields = (
+ <div className="flex flex-col gap-1.5">
+ <span className={FIELD_LABEL}>{t('vaults.dialog.fetchAuth')}</span>
+ <div className="flex flex-col gap-2">
+ <SegmentedRadio<FetchAuthMode>
+ value={fetchAuthMode}
+ onChange={setFetchAuthMode}
+ disabled={submitting}
+ ariaLabel={t('vaults.dialog.fetchAuth')}
+ options={[
+ { id: 'bearer', label: t('vaults.dialog.fetchAuthBearer') },
+ { id: 'header', label: t('vaults.dialog.fetchAuthHeader') },
+ { id: 'query', label: t('vaults.dialog.fetchAuthQuery') },
+ ]}
+ />
+ {fetchAuthMode !== 'bearer' && (
+ <Input
+ value={fetchAuthName}
+ onChange={(event) => setFetchAuthName(event.target.value)}
+ placeholder={t('vaults.dialog.fetchAuthNamePlaceholder')}
+ autoComplete="off"
+ disabled={submitting}
+ />
+ )}
+ </div>
+ <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.fetchAuthHelp')}</span>
</div>
);
@@ -385,17 +566,12 @@ export const VaultSecretForm: React.FC<{
{t('vaults.dialog.checkingAvault')}
</div>
)}
- {protection === 'standard' && !isKeypair && !checkingAvault && !p2Ready && (
+ {protection === 'standard' && !checkingAvault && !p2Ready && (
<div className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning">
- {standardCreateReady
- ? t('vaults.dialog.p2UnavailableStandardFallback', {
- version: AVAULT_P2_MIN_VERSION,
- installed: avaultDep?.version ?? 'unknown',
- })
- : t('vaults.dialog.p2Unavailable', {
- version: AVAULT_P2_MIN_VERSION,
- installed: avaultDep?.version ?? 'unknown',
- })}
+ {t('vaults.dialog.p2Unavailable', {
+ version: AVAULT_P2_MIN_VERSION,
+ installed: avaultDep?.version ?? 'unknown',
+ })}
</div>
)}
{error && (
@@ -458,6 +634,7 @@ export const VaultSecretForm: React.FC<{
/>
<span className="text-[11px] text-muted-foreground">{t('vaults.dialog.allowHostsHelp')}</span>
</div>
+ {fetchAuthPolicyFields}
{gatingNotices}
@@ -490,6 +667,9 @@ export const VaultSecretForm: React.FC<{
applySigningKey(null);
setImportHex('');
setSigningError(null);
+ } else {
+ setValue('');
+ clearSelectedFile();
}
}}
disabled={submitting}
@@ -663,7 +843,7 @@ export const VaultSecretForm: React.FC<{
>
<SlidersHorizontal className="size-3.5 text-muted" />
<span className="flex-1 text-xs font-semibold text-foreground">{t('vaults.dialog.advanced')}</span>
- {!advancedOpen && (description || tags.length > 0 || allowHosts.length > 0) && (
+ {!advancedOpen && (description || tags.length > 0 || allowHosts.length > 0 || fetchAuthMode !== 'bearer') && (
<span className="size-1.5 rounded-full bg-mint" aria-hidden />
)}
</button>
@@ -707,6 +887,7 @@ export const VaultSecretForm: React.FC<{
/>
<span className="text-[11px] text-muted-foreground">{t('vaults.dialog.allowHostsHelp')}</span>
</div>
+ {fetchAuthPolicyFields}
</div>
)}
</div>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fdaa78749..b46f272af 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2284,6 +2284,12 @@
"name": "Name",
"value": "Value",
"valuePlaceholder": "Paste the secret value",
+ "valueSource": "Value source",
+ "valueSourceText": "Text",
+ "valueSourceFile": "File",
+ "chooseSecretFile": "Choose a file",
+ "replaceSecretFile": "Replace file",
+ "clearSecretFile": "Clear file",
"provisionValueHelp": "Submitted over TLS — never enters the chat or the model context",
"storeAs": "Store as",
"showValue": "Show value",
@@ -2306,8 +2312,7 @@
"signingPublicKeyHint": "Share this public key freely. The private key never leaves your vault, and the chain and signature scheme are chosen at signing time.",
"signingNeedsAvault": "Signing keys need avault {{version}} or newer installed.",
"checkingAvault": "Checking avault…",
- "p2Unavailable": "Browser-side vault create requires avault {{version}} or newer. Installed: {{installed}}. Use the CLI stdin/file path until a compatible avault release is installed.",
- "p2UnavailableStandardFallback": "Browser-side sealing requires avault {{version}} or newer. Installed: {{installed}}. Standard secrets can still be saved through the local avault seal fallback.",
+ "p2Unavailable": "Browser-side vault create requires avault {{version}} or newer. Installed: {{installed}}. Install a compatible avault release before saving standard secrets.",
"browserSealingPending": "Browser-side sealing requires a compatible avault release. This UI never sends plaintext values to Python.",
"group": "Group",
"groupPlaceholder": "Pick or create a group",
@@ -2322,6 +2327,12 @@
"allowHosts": "Allowed hosts (for proxy fetch)",
"allowHostsPlaceholder": "api.github.com, .example.com",
"allowHostsHelp": "Only needed when this secret is used through the brokered HTTP proxy; '.example.com' matches subdomains.",
+ "fetchAuth": "Fetch auth placement",
+ "fetchAuthBearer": "Bearer",
+ "fetchAuthHeader": "Header",
+ "fetchAuthQuery": "Query",
+ "fetchAuthNamePlaceholder": "X-Api-Key or api_key",
+ "fetchAuthHelp": "Defaults to Authorization: Bearer <value>. Use Header or Query for APIs that expect another credential placement.",
"alwaysAsk": "Always ask before each use",
"alwaysAskHelp": "Never granted in advance, even per-key",
"tags": "Tags",
@@ -2343,6 +2354,13 @@
"invalidPrivateKey": "That isn't a valid secp256k1 private key. It must be 32 bytes (64 hex characters).",
"fingerprintMismatch": "The avault public key fingerprint changed. Verify the local avault install before saving this secret.",
"pendingDraft": "Press Enter to add the value in the input, or clear it, before saving.",
+ "authNameRequired": "Enter a header or query parameter name.",
+ "authHeaderInvalid": "Enter a valid HTTP header name.",
+ "authHeaderForbidden": "Host cannot be used as the credential header.",
+ "authQueryInvalid": "Enter a valid query parameter name.",
+ "fileEmpty": "Choose a non-empty file.",
+ "fileTooLarge": "Choose a file up to {{size}}.",
+ "fileReadFailed": "Couldn't read that file.",
"secretExists": "A secret with this name already exists."
}
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ec3498080..9aaedbd4d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2283,6 +2283,12 @@
"name": "名称",
"value": "值",
"valuePlaceholder": "粘贴密钥值",
+ "valueSource": "值来源",
+ "valueSourceText": "文本",
+ "valueSourceFile": "文件",
+ "chooseSecretFile": "选择文件",
+ "replaceSecretFile": "替换文件",
+ "clearSecretFile": "清除文件",
"provisionValueHelp": "通过 TLS 提交——绝不会进入聊天或模型上下文",
"storeAs": "存储为",
"showValue": "显示值",
@@ -2305,8 +2311,7 @@
"signingPublicKeyHint": "公钥可以放心分享。私钥始终留在你的保险库里;用哪条链、哪种签名方案,在签名时再定。",
"signingNeedsAvault": "签名密钥需要安装 avault {{version}} 或更新版本。",
"checkingAvault": "正在检查 avault…",
- "p2Unavailable": "浏览器侧保险库创建需要 avault {{version}} 或更新版本。当前安装:{{installed}}。在兼容的 avault 发布版安装前,请使用 CLI stdin/file 路径。",
- "p2UnavailableStandardFallback": "浏览器侧封装需要 avault {{version}} 或更新版本。当前安装:{{installed}}。标准密钥仍可通过本机 avault seal fallback 保存。",
+ "p2Unavailable": "浏览器侧保险库创建需要 avault {{version}} 或更新版本。当前安装:{{installed}}。请先安装兼容的 avault 发布版,再保存标准密钥。",
"browserSealingPending": "浏览器侧封箱需要兼容的 avault 发布版。这个 UI 永远不会把明文值发送给 Python。",
"group": "分组",
"groupPlaceholder": "选择或新建分组",
@@ -2321,6 +2326,12 @@
"allowHosts": "允许的域名(用于代理 fetch)",
"allowHostsPlaceholder": "api.github.com, .example.com",
"allowHostsHelp": "仅当该密钥通过认证 HTTP 代理使用时才需要;'.example.com' 匹配子域。",
+ "fetchAuth": "Fetch 认证位置",
+ "fetchAuthBearer": "Bearer",
+ "fetchAuthHeader": "Header",
+ "fetchAuthQuery": "Query",
+ "fetchAuthNamePlaceholder": "X-Api-Key 或 api_key",
+ "fetchAuthHelp": "默认使用 Authorization: Bearer <value>。如果目标 API 要求其他位置,可改用 Header 或 Query。",
"alwaysAsk": "每次使用都询问",
"alwaysAskHelp": "绝不预先授权,连按密钥也不行",
"tags": "标签",
@@ -2342,6 +2353,13 @@
"invalidPrivateKey": "这不是有效的 secp256k1 私钥,必须是 32 字节(64 个十六进制字符)。",
"fingerprintMismatch": "avault 公钥指纹已变化。请先确认本机 avault 安装可信,再保存该密钥。",
"pendingDraft": "请先按回车把输入框里的内容加进去,或清空它,再保存。",
+ "authNameRequired": "请输入 Header 名称或 Query 参数名。",
+ "authHeaderInvalid": "请输入有效的 HTTP Header 名称。",
+ "authHeaderForbidden": "不能把 Host 用作认证 Header。",
+ "authQueryInvalid": "请输入有效的 Query 参数名。",
+ "fileEmpty": "请选择非空文件。",
+ "fileTooLarge": "请选择不超过 {{size}} 的文件。",
+ "fileReadFailed": "读取文件失败。",
"secretExists": "同名密钥已存在。"
}
},
diff --git a/vibe/api.py b/vibe/api.py
index 918f65ac2..cc29e3f3f 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1363,6 +1363,20 @@ def get_vault_vmk() -> dict:
return {"ok": True, "exists": wrap_meta is not None, "wrap_meta": wrap_meta}
+def _reject_plaintext_value_fields(payload: object) -> None:
+ if isinstance(payload, dict):
+ if "value" in payload:
+ raise VaultApiError(
+ "vault create does not accept plaintext value fields",
+ code="plaintext_value_rejected",
+ )
+ for item in payload.values():
+ _reject_plaintext_value_fields(item)
+ elif isinstance(payload, list):
+ for item in payload:
+ _reject_plaintext_value_fields(item)
+
+
def _sealed_from_payload(payload: dict):
from storage.vault_crypto import Sealed
@@ -1390,6 +1404,7 @@ def create_vault_secret(payload: dict) -> dict:
if not isinstance(payload, dict):
raise VaultApiError("payload must be an object", code="invalid_payload")
+ _reject_plaintext_value_fields(payload)
name = str(payload.get("name") or "").strip()
if not vault_crypto.is_valid_secret_name(name):
raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")
@@ -1404,20 +1419,14 @@ def create_vault_secret(payload: dict) -> dict:
signer_kind = str(signer_kind)
if protection == "standard":
blind_box = payload.get("blind_box")
- value = payload.get("value")
if isinstance(blind_box, dict):
try:
sealed = avault_seal_blind_box(name, blind_box)
except AvaultError as exc:
raise VaultApiError(f"avault blind-box seal failed: {exc}", code="avault_failed") from exc
- elif isinstance(value, str) and value:
- try:
- sealed = avault_seal(name, value.encode("utf-8"))
- except AvaultError as exc:
- raise VaultApiError(f"avault seal failed: {exc}", code="avault_failed") from exc
else:
raise VaultApiError(
- "standard create requires a browser blind_box or value fallback",
+ "standard create requires a browser blind_box",
code="blind_box_required",
)
elif protection == "protected":
@@ -5077,27 +5086,6 @@ def _envelope_payload(sealed) -> dict:
return {"ciphertext": sealed.ciphertext, "nonce": sealed.nonce, "wrap_meta": sealed.wrap_meta}
-def avault_seal(name: str, value: bytes):
- """Seal a value under the machine key via avault; return a :class:`Sealed`.
-
- ``value`` is piped straight to avault's stdin and never persisted or logged here.
- """
- from storage.vault_crypto import Sealed
-
- proc = _run_avault(["seal", "--name", name], stdin=value)
- if proc.returncode != 0:
- raise AvaultError(_avault_detail(proc) or "avault seal failed")
- try:
- payload = json.loads(proc.stdout)
- return Sealed(
- ciphertext=payload["ciphertext"],
- nonce=payload["nonce"],
- wrap_meta=payload["wrap_meta"],
- )
- except (ValueError, KeyError, TypeError) as exc:
- raise AvaultError("avault seal returned malformed output") from exc
-
-
def avault_pubkey() -> dict:
"""Return avault's blind-box public key + fingerprint."""
_require_avault_p2_surface("blind-box pubkey")
diff --git a/vibe/cli.py b/vibe/cli.py
index f17f97c54..f1bcc014e 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -4131,11 +4131,8 @@ def cmd_session_update(args):
# ----- vault: secret management (design: docs/plans/vaults.md) -----
-# P0 standard-tier ops run direct-DB + direct-crypto here, matching sibling CLI
-# commands (session/task/data): the machine key is a local file, so the CLI reading
-# it is the same trust boundary as the daemon, and there is no approval to
-# orchestrate. Protected-tier resolve/sign (P1) will route through the daemon UDS,
-# because that is where the unlock factor, approval, and in-memory grants live.
+# The agent-facing CLI is value-free: it can discover, request, approve/wait, and
+# deliver existing vault material, but it never accepts plaintext secrets for create.
def _open_vault_engine():
@@ -4220,79 +4217,6 @@ def _parse_env_specs(specs) -> dict:
return mapping
-def _read_secret_value(args, *, help_command: str) -> str:
- """Read a secret value from --stdin or --from-file. Argv values are rejected by
- design (shell history / agent-context leakage)."""
- from_file = getattr(args, "from_file", None)
- use_stdin = bool(getattr(args, "stdin", False))
- if bool(from_file) == use_stdin: # neither, or both
- raise TaskCliError(
- "provide the value via exactly one of --stdin or --from-file",
- code="missing_value_source",
- help_command=help_command,
- )
- if from_file:
- try:
- # Stored byte-exact: read bytes and decode (NOT read_text, which does universal
- # newline translation). A trailing newline and CRLF/CR endings are significant for
- # Windows-created PEM/SSH keys and many tokens, so --from-file is preserved verbatim.
- value = Path(from_file).read_bytes().decode("utf-8")
- except OSError as exc:
- raise TaskCliError(f"cannot read --from-file: {exc}", code="value_file_unreadable", help_command=help_command) from exc
- else:
- # Interactive/piped stdin: drop a single trailing newline (the Enter keypress / heredoc
- # terminator) the user didn't intend as part of the secret.
- value = sys.stdin.read()
- if value.endswith("\n"):
- value = value[:-1]
- if not value:
- raise TaskCliError("secret value is empty", code="empty_value", help_command=help_command)
- return value
-
-
-def cmd_vault_set(args):
- from storage import vault_crypto, vault_service
- from vibe import api
-
- help_command = "vibe vault set --help"
- try:
- value = _read_secret_value(args, help_command=help_command)
- # Validate the name before sealing so an invalid name doesn't spend an avault call.
- if not vault_crypto.is_valid_secret_name(args.name):
- raise vault_service.InvalidSecretNameError(args.name)
- tags = list(getattr(args, "tag", None) or []) or None
- policy = _build_secret_policy(args)
- # Seal via avault BEFORE opening a DB transaction (never hold a txn across a subprocess).
- # The plaintext goes only to avault's stdin; Avibe keeps only the ciphertext envelope
- # and non-value-derived metadata.
- sealed = api.avault_seal(args.name, value.encode("utf-8"))
- engine = _open_vault_engine()
- with engine.begin() as conn:
- meta = vault_service.create_secret(
- conn,
- name=args.name,
- sealed=sealed,
- group=getattr(args, "group", None) or vault_service.DEFAULT_GROUP,
- tags=tags,
- description=getattr(args, "description", None),
- policy=policy,
- )
- _print_cli_payload("vault_secret", saved=True, secret=meta)
- return 0
- except vault_service.InvalidSecretNameError:
- _print_task_error(TaskCliError(f"invalid secret name: {args.name!r} (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name", help_command=help_command))
- return 1
- except vault_service.SecretExistsError:
- _print_task_error(TaskCliError(f"secret '{args.name}' already exists (remove it first to replace)", code="secret_exists", help_command=help_command))
- return 1
- except api.AvaultError as exc:
- _print_task_error(TaskCliError(f"avault seal failed: {exc}", code="avault_failed", help_command=help_command))
- return 1
- except Exception as exc:
- _print_task_error(exc, help_command=help_command)
- return 1
-
-
def cmd_vault_list(args):
from storage import vault_service
@@ -5390,28 +5314,6 @@ def cmd_vault_await(args):
return 1
-def _build_secret_policy(args) -> dict | None:
- """Assemble the non-secret policy (allowed hosts + auth scheme) for the brokered
- ``fetch`` mode from ``set`` flags. Returns None when nothing is configured."""
- policy: dict = {}
- hosts = [h.strip() for h in (getattr(args, "allow_host", None) or []) if h.strip()]
- if hosts:
- policy["allowed_hosts"] = hosts
- auth_header = getattr(args, "auth_header", None)
- auth_query = getattr(args, "auth_query", None)
- if auth_header and auth_query:
- raise TaskCliError("use at most one of --auth-header / --auth-query", code="invalid_auth", help_command="vibe vault set --help")
- if auth_header:
- # A stored auth-header policy is applied at fetch egress, so it must obey the same
- # authority-override guard as --header (otherwise --auth-header Host bypasses it).
- _reject_forbidden_header(auth_header, help_command="vibe vault set --help")
- policy["auth"] = {"type": "header", "name": auth_header}
- elif auth_query:
- policy["auth"] = {"type": "query", "name": auth_query}
- # No auth key => fetch defaults to Authorization: Bearer <value>.
- return policy or None
-
-
def _host_allowed(host, allowed) -> bool:
"""Exact host match, or a leading-dot entry (``.github.com``) matching subdomains.
@@ -5552,7 +5454,7 @@ def cmd_vault_fetch(args):
if not allowed:
raise TaskCliError(
f"secret '{name}' has no allowed_hosts; it cannot be used via fetch "
- f"(set them with: vibe vault set {name} --allow-host <host>)",
+ "(configure allowed hosts in the Vaults UI)",
code="proxy_unbound",
help_command=help_command,
)
@@ -8813,33 +8715,10 @@ def build_parser():
)
vault_subparsers = vault_parser.add_subparsers(
dest="vault_command",
- metavar="{set,list,discover,rm,run,fetch,access,sign,await,request,export,inject,key}",
+ metavar="{list,discover,rm,run,fetch,access,sign,await,request,export,inject,key}",
)
vault_subparsers.required = True
- vault_set_parser = vault_subparsers.add_parser(
- "set",
- help="Store a secret (value from --stdin or --from-file, never argv)",
- description="Create a secret. The value is read from --stdin or --from-file so it never lands in shell history or an agent's argv.",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- error_help_command="vibe vault set --help",
- )
- vault_set_parser.add_argument("name", help="Secret name, ENV-style (^[A-Z][A-Z0-9_]*$)")
- vault_set_parser.add_argument("--stdin", action="store_true", help="Read the value from standard input")
- vault_set_parser.add_argument("--from-file", help="Read the value from this file")
- vault_set_parser.add_argument("--group", help="Group (organizational label). Defaults to 'default'.")
- vault_set_parser.add_argument("--tag", action="append", help="Tag for filtering (repeatable)")
- vault_set_parser.add_argument("--description", help="Human description shown in the Vaults page")
- vault_set_parser.add_argument(
- "--allow-host",
- action="append",
- metavar="HOST",
- help="Allow this host for 'vibe vault fetch' (repeatable; '.example.com' matches subdomains). Required to use the secret via fetch.",
- )
- vault_set_parser.add_argument("--auth-header", metavar="NAME", help="For fetch: attach the value as this header (default: Authorization: Bearer <value>)")
- vault_set_parser.add_argument("--auth-query", metavar="NAME", help="For fetch: attach the value as this query parameter")
- _add_json_noop(vault_set_parser)
-
vault_list_parser = vault_subparsers.add_parser(
"list",
help="List secrets (names + masked metadata; never values)",
@@ -9781,8 +9660,6 @@ def main():
sys.exit(cmd_session_update(args))
parser.error("session command is required")
if args.command == "vault":
- if args.vault_command == "set":
- sys.exit(cmd_vault_set(args))
if args.vault_command == "list":
sys.exit(cmd_vault_list(args))
if args.vault_command == "discover":