<!-- docs/decisiones/0054-database-items.md at 034e81b52d1b693c65ff95181cd555c6734bc8e8 · https://github.com/OmarAlex24/klav/blob/034e81b52d1b693c65ff95181cd555c6734bc8e8/docs/decisiones/0054-database-items.md · status: stale -->

# 0054 · Database items (`ItemKind::Database`) and agent-proposed environment links

- Status: accepted (2026-12-02). Omar answered every design question with the recommended option (recorded under "Omar's answers" below).
- Date: 2026-12-02
- Read on: `main` at `3edef9ca` (2026-12-02). Line numbers below are from that commit.
- Amends:
  - [ADR 0046](0046-agent-secret-requests.md) §1 and Q4 (`is_allowed_kind`): allows `ItemKind::Database` in `SecretRequestProposal` (default secret field `url`), and adds optional `env_link: Option<EnvLinkProposal>` on local (non-sandbox) proposals so a person can link a saved secret into a project `Environment` within the same presence approval.
- Builds on and does not replace:
  - `ItemKind` and `Overview` ([`crates/klav-core/src/model/item.rs`](../../crates/klav-core/src/model/item.rs)),
  - Environments per repository and protected-environment rules ([ADR 0032](0032-entornos-por-repositorio.md)),
  - Agent secret requests ([ADR 0046](0046-agent-secret-requests.md)),
  - Postgres credential proxy and SQL guard ([ADR 0052](0052-websocket-tunnels-and-postgres-sql-guard.md)),
  - Sandbox MCP ([ADR 0053](0053-sandbox-mcp.md)),
  - 1Password `.1pux` importer ([ADR 0024](0024-importadores.md)).

## Context

### What happened in practice (2026-12-02)
An agent needed to store a `DATABASE_URL` in Omar's vault and saved it as `ItemKind::Login`. That happened for two concrete reasons in the current design:

1. **No database or connection item kind exists.** `ItemKind` (`crates/klav-core/src/model/item.rs:91-120`) has only `login`, `card`, `identity`, `ssh_key`, `file`, `totp`, `note`, `api_key`, `environment`, and three system kinds (`generator_history`, `preferences`, `agent_labels`). In `request_secret` (`crates/klav-core/src/secret_request.rs:205-210`) and `klav mcp` (`crates/klav-cli/src/mcp.rs:1047-1054`, `:1220`), agents only see `api_key`, `login`, `note`, `ssh_key`, and `totp`. Because a database connection string contains `user:password@host`, agents reach for `login` — even though `login` is for website and app autofill.
2. **Agents have no way to propose wiring a secret into an `Environment`.** `ItemKind::Environment` (ADR 0032) already exists to group project variables (`development`, `staging`, `production`) as references (`klav://<vault>/<project>/<item>/<field>`) or inline values, but `request_secret` has no field to propose linking the newly saved item into an environment variable such as `DATABASE_URL`.
3. **1Password database items degrade to notes on import.** `crates/klav-import/src/onepux.rs:419-425` maps `"001" | "005"` to `Login`, `"112"` to `ApiKey`, `"114"` to `SshKey`, and falls through `"102"` (1Password's Database category) to `ItemKind::Note`.
4. **Postgres proxy profiles (ADR 0052) cannot read connection metadata from a first-class database item.** Today `klav proxy pg add` asks the operator to pass `--host`, `--port`, `--database`, `--user`, and `--item` separately because Klav has no structured database item holding those fields alongside the password.

## Decision

### 1. New item kind: `ItemKind::Database` (`"database"`)
Add `Database` to `ItemKind` (`crates/klav-core/src/model/item.rs`), serialized in snake_case as `"database"`.

#### 1.1 Template fields
`template(ItemKind::Database)` defines eight standard fields in order:

| Field `name` | Label | `FieldKind` | Secret (`is_secret()`) | Purpose |
|---|---|---|---|---|
| `url` | `Connection URL` | `Concealed` | **Yes** | Canonical full connection string (e.g. `postgres://…`, `redis://…`, `mongodb+srv://…`), including query parameters. Primary field for `klav://…/url` and default field for `request_secret`. |
| `engine` | `Engine` | `Text` | No | Normalized engine token (`postgres`, `mysql`, `redis`, `mongodb`, `clickhouse`, `sqlite`, `mssql`, `libsql`, `other`). |
| `host` | `Host` | `Text` | No | Hostname or IP address. |
| `port` | `Port` | `Text` | No | TCP port as decimal string (e.g. `5432`, `6379`). |
| `database` | `Database` | `Text` | No | Database name or Redis DB index. |
| `username` | `Username` | `Username` | No | Database role / username (populates `Overview::username` as with other kinds). |
| `password` | `Password` | `Password` | **Yes** | Database password (integrates with password history `0x16` and ADR 0052 SCRAM auth). |
| `ssl_mode` | `SSL mode` | `Text` | No | TLS mode (`require`, `verify-full`, `verify-ca`, `prefer`, `disable`, etc.). |

#### 1.2 Minimal `Overview` and zero autofill exposure
- **`Overview` keeps `v: 1` and adds zero new fields.** A `database` item's overview carries `kind: "database"`, `title`, `username` (from the `username` field, if non-empty), `tags`, and `urls: []`.
- **`host`, `port`, `database`, `engine`, and `ssl_mode` stay inside the encrypted item details**, never in `Overview`, so `list`-only views do not expose internal database hosts or topologies.
- **`url` (`Concealed`) and `password` (`Password`) are secret fields** and never appear in `Overview`, logs, or `Debug` output.
- **No browser autofill (`urls` forbidden on `database`).** `Item::validate` / `SecretRequestProposal::validate` reject non-empty `urls` on `ItemKind::Database` (matching `api_key` in `secret_request.rs:606`), and `suggest`/`autofill` never consider `ItemKind::Database`. A database credential is never offered to a browser login form.

### 2. Connection URL parsing and composition in `klav-core`
Add a pure, dependency-free module `crates/klav-core/src/model/database.rs` (using the existing `url` crate already in `klav-core`; zero new cryptographic or third-party dependencies):

- **`parse_connection_url(raw: &str) -> Option<ParsedDatabaseUrl>`:**
  - Recognizes standard database URI schemes (`postgres`, `postgresql`, `mysql`, `mariadb`, `redis`, `rediss`, `mongodb`, `mongodb+srv`, `clickhouse`, `libsql`, `mssql`, `sqlserver`), normalizing `postgresql` → `postgres`, `rediss` → `redis` (with `ssl_mode = "require"`), `mariadb` → `mysql`, `mongodb+srv` → `mongodb` (with `ssl_mode = "require"`).
  - Extracts percent-decoded `username`, `password` (wrapped in `Zeroizing<String>`), `host`, `port` (explicit, or omitted if default not given), `database` (leading `/` stripped), and `ssl_mode` from query parameters (`sslmode`, `ssl`, `tls`).
  - Never modifies or strips query parameters from the canonical `url` field: the exact string the person pasted is preserved in `url` so provider-specific parameters (`pgbouncer=true`, `channel_binding=require`, `connection_limit=5`, etc.) are never lost.
  - Rejects control or hidden formatting characters (`crate::text::is_hidden`) in parsed metadata fields.
- **`compose_connection_url(parts: &DatabaseParts) -> Option<Zeroizing<String>>`:**
  - Builds a percent-encoded URI from structured fields when `url` is empty (or when the user clicks "Build URL" in UI / passes `--build-url` in CLI).
- **Auto-fill on paste:**
  - When a person pastes a connection URL into `url` in the Mac/iOS editor, in a `request_secret` fulfillment sheet (`kind: database, field: url`), or via `klav item add database --from-url`, Klav parses the URL in memory and fills any empty structured fields (`engine`, `host`, `port`, `database`, `username`, `password`, `ssl_mode`) automatically while keeping the exact pasted URL in `url`.
  - When fulfilling a `request_secret` in `update` mode on `field: url` (e.g. rotating a database URL), the parsed structured fields (`host`, `port`, `database`, `username`, `password`, `ssl_mode`) are refreshed alongside `url` and shown in the card summary before saving.

### 3. Agent secret requests (`request_secret`) and proposed environment links
Extend `SecretRequestProposal` (`crates/klav-core/src/secret_request.rs:498-551`) while keeping `v: 1` byte-compatible when the new optional field is absent:

1. **Allow `ItemKind::Database` in `is_allowed_kind`:**
   - Permitted kinds become `api_key`, `database`, `login`, `note`, `ssh_key`, `totp`.
   - In `klav mcp` (`crates/klav-cli/src/mcp.rs:1081`), default secret field for `ItemKind::Database` is `"url"` (and `password` is also accepted).
   - `urls` and `base_url` are forbidden when `kind == Some(ItemKind::Database)`.
2. **Optional `env_link: Option<EnvLinkProposal>` on `SecretRequestProposal`:**
   ```rust
   #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
   #[serde(deny_unknown_fields)]
   pub struct EnvLinkProposal {
       /// Environment item name (`[a-z0-9][a-z0-9_-]{0,63}`, e.g. `"development"`).
       pub environment: String,
       /// Environment variable name (`[A-Za-z_][A-Za-z0-9_]{0,127}`, e.g. `"DATABASE_URL"`).
       pub variable: String,
   }
   ```
   - Validated in `klav-core` with `validate_environment_name` and `validate_variable_name` (`crates/klav-core/src/model/environment.rs:35-53`).
   - **Forbidden for sandbox secret requests (`sandbox_id.is_some()`):** a sandbox has no access to vault `Environment` items and operates exclusively through proxy profiles (ADR 0036, ADR 0053). `validate_for_sandbox` rejects any proposal carrying `env_link`.
   - **Allowed for local (non-sandbox) agents** in both `create` and `update` modes (for any allowed `ItemKind`, including `database` and `api_key`).
3. **Person's approval card and ADR 0032 protection invariant:**
   - The fulfillment card on Mac, iPhone, extension, and CLI renders `env_link` as an explicit section: *"Also link as `<VARIABLE>` in `<environment>`"* with editable environment selector (existing environments in the target project, or creating a new unprotected environment if confirmed) and editable variable name.
   - **Default toggle state:**
     - **Unchecked by default** if the target environment is **protected** (ADR 0032 §3: `effective_protected == true`, or `is_production_name(&environment)` for a not-yet-created environment), accompanied by a prominent warning badge (*"Protected environment — linking this item makes it require Touch ID every time"*).
     - **Checked by default** (and clearly visible) for non-protected environments such as `development`, only when the target project matches the item's destination project; changing the destination project resets the target environment picker so an item is never silently linked across projects.
   - **Atomic presence approval:** saving the item (new or updated) and updating the `Environment` item to set `variable → VariableSource::Ref(klav://<vault_id>/<project_id>/<item_id>/<field_id>)` (storing four UUIDs per ADR 0032 §1) happen under the person's single Touch ID / Face ID / master-password confirmation.
   - **No value or cross-project leakage in `SecretRequestDecision` (T236):**
     - `SecretRequestDecision` keeps its existing fields; optional `env_linked: Option<EnvLinkDecision>` (`{ environment, variable }`) is included **only** when `in_grant == true` and the person actually linked the variable inside the agent's granted project. If `in_grant == false` or the person unchecked the link, `env_linked` is `None` (never revealing whether that environment exists or holds other variables).
4. **Agent instructions and MCP tool guidance:**
   - Update `klav mcp` (`create_item`, `request_secret`, `INSTRUCTIONS`), `klav-forward mcp`, and `skill/SKILL.md` to state explicitly:
     - Use `database` for database and cache connection URLs / credentials (Postgres, MySQL, Redis, MongoDB, etc.), never `login`.
     - Use `api_key` for API tokens and service keys.
     - Use `login` **only** for website and application logins.
     - When a project needs `DATABASE_URL` (or another `.env` variable) from the person, call `request_secret` with `kind: "database"` (or `api_key`) and `env_link: { environment: "development", variable: "DATABASE_URL" }` so the person pastes it once into a hidden field and wires it into the project environment automatically.

### 4. Integration with ADR 0052 Postgres profiles (`klav proxy pg`)
- `klav proxy pg add` accepts `--item <database-item>` without requiring `--host`, `--port`, `--database`, or `--user` when those fields are present on the `ItemKind::Database` item (explicit CLI flags override item fields if supplied; `--field` defaults to `password` when `--item` is a `Database` item).
- Existing `klav proxy pg add` invocations referencing `api_key` / `note` / `login` items continue to work unchanged.

### 5. Importer support (`klav-import`)
- In `crates/klav-import/src/onepux.rs`, map 1Password category `"102"` (Database) to `ItemKind::Database` and map standard 1Password database fields (`type` → `engine`, `server` → `host`, `port` → `port`, `database` → `database`, `username` → `username`, `password` → `password`), composing `url` when all required parts are present and no explicit URL field exists.

### 6. Backwards compatibility
- **Vault items:** `ItemKind` is a closed enum serialized as snake_case. Older clients (`<= 0.13.1`) cannot deserialize `kind: "database"` on that single item and report a per-item `item_open_warning` while every other item in the vault opens normally (identical to how ADR 0032 introduced `ItemKind::Environment`).
- **Secret requests:** `SecretRequestProposal` omits `env_link` when `None`, and `SecretRequestDecision` omits `env_linked` when `None`. Proposals without `env_link` and with existing `ItemKind` values produce byte-identical JSON to ADR 0046 / ADR 0053. Older devices that receive a proposal with `kind: "database"` or `env_link` fail closed with a parse/unsupported error on that card without affecting other cards.
- **No new server DB migrations required:** `klav-server` stores encrypted item blobs and HPKE-sealed `proposal_blob`s opaquely; the only server-side check to update (if any) is confirming no closed `ItemKind` whitelist in `klav-server` rejects `"database"` (checked in Layer 2).

### 7. Threats (threat model §5.31)
- **T312 — Database URL leaked into `Overview` or logs:** `url` is `FieldKind::Concealed` and `password` is `FieldKind::Password`; `Overview` never includes either, `parse_connection_url` wraps passwords in `Zeroizing<String>`, and tests assert `Overview` serialization contains neither password nor URL and no `Debug` impl exists on secret wrappers.
- **T313 — Database credential autofilled into a malicious web page:** `ItemKind::Database` forbids `urls` and is excluded from `suggest`/`autofill`, so a browser extension or iOS AutoFill never offers a database credential on any website.
- **T314 — Agent tricks person into linking a secret into a protected (`production`) environment:** `env_link` targeting a protected or `production`/`prod`-named environment is **unchecked by default** with an explicit warning badge, and linking requires the person's presence approval; furthermore, per ADR 0032 §3.1, linking an item into a protected environment makes that item itself require presence every time (fail-closed protection inheritance).
- **T315 — Sandbox agent tries to probe or mutate vault `Environment`s via `env_link`:** `SecretRequestProposal::validate_for_sandbox` rejects any proposal where `sandbox_id.is_some()` and `env_link.is_some()`.
- **T316 — Cross-project environment existence oracle via `SecretRequestDecision`:** mirroring T236, if the person fulfills outside the agent's granted project (`in_grant == false`), `env_linked` is omitted (`None`), revealing nothing about environments outside the grant.
- **T317 — Malicious connection URL smuggling control/bidi characters into structured fields or notes:** `parse_connection_url` rejects hidden/control characters (`crate::text::is_hidden`) in all parsed metadata fields (`engine`, `host`, `port`, `database`, `username`, `ssl_mode`) and enforces length caps before populating UI or item fields.

## Rejected alternatives

- **General `ItemKind::Connection` instead of `ItemKind::Database`:** Rejected (Omar chose `database`): databases and caches are the concrete daily pain point (especially alongside ADR 0052's Postgres SQL guard), and `Database` is immediately recognizable in the vault sidebar, 1Password imports, and agent tool schemas.
- **Exposing `engine` and `host` in `Overview`:** Rejected (Omar chose minimal `Overview`): avoids leaking internal infrastructure hostnames into `list`-only views and keeps `Overview` at `v: 1` without schema churn.
- **Separate agent MCP tool `set_environment_variable`:** Rejected for v1: letting agents propose `env_link` inside `request_secret` reuses the existing HPKE-sealed proposal, anti-phishing validation, Touch ID fulfillment card, and T236 privacy rules without creating a second approval flow.

## Consequences

- Agents stop misclassifying `DATABASE_URL` as `Login` items and can request database credentials cleanly with one-step `Environment` wiring.
- Humans get paste-a-URL convenience (auto-filling `host`, `port`, `database`, `username`, `password`, `ssl_mode`) while preserving exact query strings in `url`.
- `klav proxy pg add` becomes ergonomic with `--item <database-item>`.
- 1Password database exports import as native `Database` items instead of generic notes.
- Every UI surface (Mac, iOS, extension, CLI, FFI) adds one new user-facing `ItemKind::Database` with English and Spanish labels (`Database` / `Base de datos`).

## Plan in layers

1. **Layer 0 (merged):** ADR 0054 (`docs/decisiones/0054-database-items.md`) and `docs/decisiones/README.md`.
2. **Layer 1 (`klav-core` + vectors + spec) — implemented in this PR:** `ItemKind::Database`, `template(ItemKind::Database)`, `model::database` URL parser/composer, `EnvLinkProposal` / `EnvLinkDecision` on `SecretRequestProposal` / `SecretRequestDecision`, validation rules (T312–T317), crypto/serialization vectors, and updates to `docs/especificacion-cripto.md`, `docs/modelo-de-amenazas.md`, and `docs/glossary.md`.
3. **Layer 2 (`klav-client` + `klav-daemon` + `klav-sdk` + `klav-import`) — implemented in this PR:** fulfillment support for `Database` auto-parse and atomic `env_link` wiring (with protected-environment checks and presence verification), `klav proxy pg` deriving structured fields from `ItemKind::Database`, SDK exposure of `env_link`/`env_linked`, and the 1Password `"102"` Database importer mapping.
4. **Layer 3 (`klav-cli` + `klav-mcp` + `klav-forward` + `skill/SKILL.md`) — implemented in this PR:** `klav item add database [--from-url]`, `klav mcp` `create_item` / `request_secret` (`kind: "database"` + `env_link`), updated agent instructions/skill, pure FFI database URL helpers for Layer 4, and `klav proxy pg` deriving a profile from a database item.
5. **Layer 4 (`klav-ffi` + Mac & iOS apps) — implemented (#113):** `ItemKind::Database` in FFI, sidebar/filter (`Database` / `Base de datos`), item editor with paste-URL auto-parse, `RequestCards` fulfillment UI for `database` + `env_link` (with protected-environment warning and unchecked default), and `Localizable.xcstrings` (en/es).
6. **Layer 5 (Browser extension + public docs + roadmap) — implemented:** `apps/extension` `Database` item rendering/filter + `env_link` support on secret request cards + `_locales/{en,es}`, `apps/docs` updates, `docs/features.md`, and `docs/roadmap.md`. The popup has a "Databases" tab and names the template fields in English and Spanish; the content script has no form group for `database`, so neither the menu nor an agent fill ever types one into a page (T313). The secret request card names the kind and shows `env_link` as a toggle with the environment and variable editable: unchecked behind a warning for a protected environment (T314), checked for an unprotected one only in the project klavd resolved it in, and recomputed (off, then looked up with `environment`; protected when the lookup fails) when the person changes the destination project or the environment name. `env_link` is sent only while checked, never from a sandbox's card (T315), and goes through the presence form (Touch ID, or the master password where Touch ID is unavailable).

## Stop rules

- Stop if `Overview` serialization changes for any existing `ItemKind` or leaks `url`/`password`.
- Stop if any `suggest`/`autofill` test or path can match an `ItemKind::Database` item.
- Stop if a sandboxed secret request (`sandbox_id.is_some()`) can carry `env_link`.
- Stop if linking into a protected environment defaults to checked or skips presence verification.

## Omar's answers (2026-12-02)

1. **Item kind & fields:** `database` (`ItemKind::Database`) with `url` (`Concealed`) + structured fields (`engine`, `host`, `port`, `database`, `username`, `password`, `ssl_mode`) and auto-parse on paste.
2. **Environment integration:** Included in ADR 0054 — allow agents to propose linking a requested secret into a project `Environment` variable (e.g. `DATABASE_URL → klav://.../url`) within the same Touch ID approval.
3. **`Overview` metadata:** Minimal `Overview` — no new fields (`kind: "database"`, `title`, `username`, `tags`; `urls` empty so browser autofill never matches; `host`/`port`/`database`/`engine`/`ssl_mode` stay inside encrypted details).
