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:
mainat3edef9ca(2026-12-02). Line numbers below are from that commit. - Amends:
- ADR 0046 §1 and Q4 (
is_allowed_kind): allowsItemKind::DatabaseinSecretRequestProposal(default secret fieldurl), and adds optionalenv_link: Option<EnvLinkProposal>on local (non-sandbox) proposals so a person can link a saved secret into a projectEnvironmentwithin the same presence approval.
- ADR 0046 §1 and Q4 (
- Builds on and does not replace:
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:
- No database or connection item kind exists.
ItemKind(crates/klav-core/src/model/item.rs:91-120) has onlylogin,card,identity,ssh_key,file,totp,note,api_key,environment, and three system kinds (generator_history,preferences,agent_labels). Inrequest_secret(crates/klav-core/src/secret_request.rs:205-210) andklav mcp(crates/klav-cli/src/mcp.rs:1047-1054,:1220), agents only seeapi_key,login,note,ssh_key, andtotp. Because a database connection string containsuser:password@host, agents reach forlogin— even thoughloginis for website and app autofill. - 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, butrequest_secrethas no field to propose linking the newly saved item into an environment variable such asDATABASE_URL. - 1Password database items degrade to notes on import.
crates/klav-import/src/onepux.rs:419-425maps"001" | "005"toLogin,"112"toApiKey,"114"toSshKey, and falls through"102"(1Password's Database category) toItemKind::Note. - Postgres proxy profiles (ADR 0052) cannot read connection metadata from a first-class database item. Today
klav proxy pg addasks the operator to pass--host,--port,--database,--user, and--itemseparately 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
Overviewkeepsv: 1and adds zero new fields. Adatabaseitem's overview carrieskind: "database",title,username(from theusernamefield, if non-empty),tags, andurls: [].host,port,database,engine, andssl_modestay inside the encrypted item details, never inOverview, solist-only views do not expose internal database hosts or topologies.url(Concealed) andpassword(Password) are secret fields and never appear inOverview, logs, orDebugoutput.- No browser autofill (
urlsforbidden ondatabase).Item::validate/SecretRequestProposal::validatereject non-emptyurlsonItemKind::Database(matchingapi_keyinsecret_request.rs:606), andsuggest/autofillnever considerItemKind::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), normalizingpostgresql→postgres,rediss→redis(withssl_mode = "require"),mariadb→mysql,mongodb+srv→mongodb(withssl_mode = "require"). - Extracts percent-decoded
username,password(wrapped inZeroizing<String>),host,port(explicit, or omitted if default not given),database(leading/stripped), andssl_modefrom query parameters (sslmode,ssl,tls). - Never modifies or strips query parameters from the canonical
urlfield: the exact string the person pasted is preserved inurlso 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.
- Recognizes standard database URI schemes (
compose_connection_url(parts: &DatabaseParts) -> Option<Zeroizing<String>>:- Builds a percent-encoded URI from structured fields when
urlis empty (or when the user clicks "Build URL" in UI / passes--build-urlin CLI).
- Builds a percent-encoded URI from structured fields when
- Auto-fill on paste:
- When a person pastes a connection URL into
urlin the Mac/iOS editor, in arequest_secretfulfillment sheet (kind: database, field: url), or viaklav 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 inurl. - When fulfilling a
request_secretinupdatemode onfield: url(e.g. rotating a database URL), the parsed structured fields (host,port,database,username,password,ssl_mode) are refreshed alongsideurland shown in the card summary before saving.
- When a person pastes a connection URL into
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:
- Allow
ItemKind::Databaseinis_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 forItemKind::Databaseis"url"(andpasswordis also accepted). urlsandbase_urlare forbidden whenkind == Some(ItemKind::Database).
- Permitted kinds become
- Optional
env_link: Option<EnvLinkProposal>onSecretRequestProposal:#[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-corewithvalidate_environment_nameandvalidate_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 vaultEnvironmentitems and operates exclusively through proxy profiles (ADR 0036, ADR 0053).validate_for_sandboxrejects any proposal carryingenv_link. - Allowed for local (non-sandbox) agents in both
createandupdatemodes (for any allowedItemKind, includingdatabaseandapi_key).
- Validated in
- Person's approval card and ADR 0032 protection invariant:
- The fulfillment card on Mac, iPhone, extension, and CLI renders
env_linkas 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, oris_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.
- Unchecked by default if the target environment is protected (ADR 0032 §3:
- Atomic presence approval: saving the item (new or updated) and updating the
Environmentitem to setvariable → 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):SecretRequestDecisionkeeps its existing fields; optionalenv_linked: Option<EnvLinkDecision>({ environment, variable }) is included only whenin_grant == trueand the person actually linked the variable inside the agent's granted project. Ifin_grant == falseor the person unchecked the link,env_linkedisNone(never revealing whether that environment exists or holds other variables).
- The fulfillment card on Mac, iPhone, extension, and CLI renders
- Agent instructions and MCP tool guidance:
- Update
klav mcp(create_item,request_secret,INSTRUCTIONS),klav-forward mcp, andskill/SKILL.mdto state explicitly:- Use
databasefor database and cache connection URLs / credentials (Postgres, MySQL, Redis, MongoDB, etc.), neverlogin. - Use
api_keyfor API tokens and service keys. - Use
loginonly for website and application logins. - When a project needs
DATABASE_URL(or another.envvariable) from the person, callrequest_secretwithkind: "database"(orapi_key) andenv_link: { environment: "development", variable: "DATABASE_URL" }so the person pastes it once into a hidden field and wires it into the project environment automatically.
- Use
- Update
4. Integration with ADR 0052 Postgres profiles (klav proxy pg)
klav proxy pg addaccepts--item <database-item>without requiring--host,--port,--database, or--userwhen those fields are present on theItemKind::Databaseitem (explicit CLI flags override item fields if supplied;--fielddefaults topasswordwhen--itemis aDatabaseitem).- Existing
klav proxy pg addinvocations referencingapi_key/note/loginitems continue to work unchanged.
5. Importer support (klav-import)
- In
crates/klav-import/src/onepux.rs, map 1Password category"102"(Database) toItemKind::Databaseand map standard 1Password database fields (type→engine,server→host,port→port,database→database,username→username,password→password), composingurlwhen all required parts are present and no explicit URL field exists.
6. Backwards compatibility
- Vault items:
ItemKindis a closed enum serialized as snake_case. Older clients (<= 0.13.1) cannot deserializekind: "database"on that single item and report a per-itemitem_open_warningwhile every other item in the vault opens normally (identical to how ADR 0032 introducedItemKind::Environment). - Secret requests:
SecretRequestProposalomitsenv_linkwhenNone, andSecretRequestDecisionomitsenv_linkedwhenNone. Proposals withoutenv_linkand with existingItemKindvalues produce byte-identical JSON to ADR 0046 / ADR 0053. Older devices that receive a proposal withkind: "database"orenv_linkfail closed with a parse/unsupported error on that card without affecting other cards. - No new server DB migrations required:
klav-serverstores encrypted item blobs and HPKE-sealedproposal_blobs opaquely; the only server-side check to update (if any) is confirming no closedItemKindwhitelist inklav-serverrejects"database"(checked in Layer 2).
7. Threats (threat model §5.31)
- T312 — Database URL leaked into
Overviewor logs:urlisFieldKind::ConcealedandpasswordisFieldKind::Password;Overviewnever includes either,parse_connection_urlwraps passwords inZeroizing<String>, and tests assertOverviewserialization contains neither password nor URL and noDebugimpl exists on secret wrappers. - T313 — Database credential autofilled into a malicious web page:
ItemKind::Databaseforbidsurlsand is excluded fromsuggest/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_linktargeting a protected orproduction/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
Environments viaenv_link:SecretRequestProposal::validate_for_sandboxrejects any proposal wheresandbox_id.is_some()andenv_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_linkedis omitted (None), revealing nothing about environments outside the grant. - T317 — Malicious connection URL smuggling control/bidi characters into structured fields or notes:
parse_connection_urlrejects 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::Connectioninstead ofItemKind::Database: Rejected (Omar chosedatabase): databases and caches are the concrete daily pain point (especially alongside ADR 0052's Postgres SQL guard), andDatabaseis immediately recognizable in the vault sidebar, 1Password imports, and agent tool schemas. - Exposing
engineandhostinOverview: Rejected (Omar chose minimalOverview): avoids leaking internal infrastructure hostnames intolist-only views and keepsOverviewatv: 1without schema churn. - Separate agent MCP tool
set_environment_variable: Rejected for v1: letting agents proposeenv_linkinsiderequest_secretreuses 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_URLasLoginitems and can request database credentials cleanly with one-stepEnvironmentwiring. - Humans get paste-a-URL convenience (auto-filling
host,port,database,username,password,ssl_mode) while preserving exact query strings inurl. klav proxy pg addbecomes ergonomic with--item <database-item>.- 1Password database exports import as native
Databaseitems instead of generic notes. - Every UI surface (Mac, iOS, extension, CLI, FFI) adds one new user-facing
ItemKind::Databasewith English and Spanish labels (Database/Base de datos).
Plan in layers
- Layer 0 (merged): ADR 0054 (
docs/decisiones/0054-database-items.md) anddocs/decisiones/README.md. - Layer 1 (
klav-core+ vectors + spec) — implemented in this PR:ItemKind::Database,template(ItemKind::Database),model::databaseURL parser/composer,EnvLinkProposal/EnvLinkDecisiononSecretRequestProposal/SecretRequestDecision, validation rules (T312–T317), crypto/serialization vectors, and updates todocs/especificacion-cripto.md,docs/modelo-de-amenazas.md, anddocs/glossary.md. - Layer 2 (
klav-client+klav-daemon+klav-sdk+klav-import) — implemented in this PR: fulfillment support forDatabaseauto-parse and atomicenv_linkwiring (with protected-environment checks and presence verification),klav proxy pgderiving structured fields fromItemKind::Database, SDK exposure ofenv_link/env_linked, and the 1Password"102"Database importer mapping. - Layer 3 (
klav-cli+klav-mcp+klav-forward+skill/SKILL.md) — implemented in this PR:klav item add database [--from-url],klav mcpcreate_item/request_secret(kind: "database"+env_link), updated agent instructions/skill, pure FFI database URL helpers for Layer 4, andklav proxy pgderiving a profile from a database item. - Layer 4 (
klav-ffi+ Mac & iOS apps) — implemented (#113):ItemKind::Databasein FFI, sidebar/filter (Database/Base de datos), item editor with paste-URL auto-parse,RequestCardsfulfillment UI fordatabase+env_link(with protected-environment warning and unchecked default), andLocalizable.xcstrings(en/es). - Layer 5 (Browser extension + public docs + roadmap) — implemented:
apps/extensionDatabaseitem rendering/filter +env_linksupport on secret request cards +_locales/{en,es},apps/docsupdates,docs/features.md, anddocs/roadmap.md. The popup has a "Databases" tab and names the template fields in English and Spanish; the content script has no form group fordatabase, so neither the menu nor an agent fill ever types one into a page (T313). The secret request card names the kind and showsenv_linkas 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 withenvironment; protected when the lookup fails) when the person changes the destination project or the environment name.env_linkis 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
Overviewserialization changes for any existingItemKindor leaksurl/password. - Stop if any
suggest/autofilltest or path can match anItemKind::Databaseitem. - Stop if a sandboxed secret request (
sandbox_id.is_some()) can carryenv_link. - Stop if linking into a protected environment defaults to checked or skips presence verification.
Omar's answers (2026-12-02)
- Item kind & fields:
database(ItemKind::Database) withurl(Concealed) + structured fields (engine,host,port,database,username,password,ssl_mode) and auto-parse on paste. - Environment integration: Included in ADR 0054 — allow agents to propose linking a requested secret into a project
Environmentvariable (e.g.DATABASE_URL → klav://.../url) within the same Touch ID approval. Overviewmetadata: MinimalOverview— no new fields (kind: "database",title,username,tags;urlsempty so browser autofill never matches;host/port/database/engine/ssl_modestay inside encrypted details).