Skip to content

feat(secrets): add Bitwarden/Vaultwarden secret provider - #23096

Closed
ihsanmokhlisse wants to merge 7 commits into
openclaw:mainfrom
ihsanmokhlisse:feat/bitwarden-secret-provider
Closed

ihsanmokhlisse wants to merge 7 commits into
openclaw:mainfrom
ihsanmokhlisse:feat/bitwarden-secret-provider

Conversation

@ihsanmokhlisse

@ihsanmokhlisse ihsanmokhlisse commented Feb 22, 2026 •

Copy link
Copy Markdown

Summary

Change Type (select all)

  • Feature
  • Security hardening

Scope (select all touched areas)

  • Auth / tokens
  • Memory / storage

Linked Issue/PR

User-visible / Behavior Changes

New secret reference syntax for Bitwarden:

{
  "secrets": {
    "providers": {
      "bw": {
        "serverUrl": "https://vaultwarden.example.com",
        "collectionId": "openclaw-secrets"
      }
    }
  },
  "models": {
    "providers": {
      "anthropic": { "apiKey": "${bw:anthropic-key/password}" }
    }
  }
}

Field extraction supports: password (default), username, notes, uri, totp, and custom fields by name.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? Yes — adds a new secrets provider that reads from Bitwarden CLI
  • New/changed network calls? No — delegates to bw CLI which handles all network communication
  • Command/tool execution surface changed? Yes — spawns bw CLI via execFile (no shell)
  • Data access scope changed? No
  • Risk + mitigation:
    • bw CLI is invoked via execFile (not exec) — no shell injection possible
    • BW_SESSION and other credentials are passed via env to the child process, never written to disk or logged
    • --nointeraction and --raw flags prevent interactive prompts and ensure clean output parsing
    • All errors are mapped to BitwardenCliError with actionable hints, never exposing raw vault data

Repro + Verification

Environment

  • OS: macOS (tested), Linux/Windows (mocked)
  • Runtime: Node.js 22+
  • Requires: Bitwarden CLI (bw) installed and logged in

Steps

  1. Install Bitwarden CLI: brew install bitwarden-cli or npm install -g @bitwarden/cli
  2. Log in: bw login then export BW_SESSION=$(bw unlock --raw)
  3. Create a test item: bw get template item | jq '.name="test-key" | .login.password="sk-test-123"' | bw encode | bw create item
  4. Configure OpenClaw: add ${bw:test-key/password} as an API key reference
  5. Verify resolution

Expected

  • Secret resolves to sk-test-123
  • Cache prevents repeated CLI calls within TTL

Actual

  • Works as described (verified via unit tests)

Evidence

  • 34 unit tests, all passing
  • 0 lint errors (oxlint)
  • 0 format issues (oxfmt)
  • Tests cover: getSecret (14 tests), setSecret (3), listSecrets (3), testConnection (4), error handling (4), configuration (6)

Human Verification (required)

  • Verified scenarios: All 34 test cases covering field extraction, cache, error mapping, env isolation, auth modes
  • Edge cases checked: missing fields, null notes/URIs, locked vault, unauthenticated state, multiple item matches, CLI not installed
  • What I did not verify: Live Bitwarden vault (tests use mocked CLI responses). Live verification is possible once PR feat: GCP Secret Manager integration for external secrets management #16663 lands and the provider can be wired into buildSecretProviders().

Compatibility / Migration

  • Backward compatible? Yes — entirely opt-in, no existing behavior changes
  • Config/env changes? Yes — new secrets.providers.bw config section (only used if configured)
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert: Remove bw from secrets.providers config, or revert to plain-text API keys
  • Files/config to restore: openclaw.json (remove secrets.providers.bw section)
  • Known bad symptoms: BitwardenCliError with actionable hint messages for every failure mode

Risks and Mitigations

AI-Assisted

Made with Cursor

Greptile Summary

Adds a Bitwarden/Vaultwarden secret provider (BitwardenSecretProvider) that implements the SecretProvider interface from PR #16663, enabling ${bw:item-name/field-name} secret references. The provider uses execFile (no shell) for CLI invocation, isolates credentials via child process env overrides, and includes comprehensive error mapping with actionable hints.

  • TOTP caching bug: TOTP codes (which rotate every ~30 seconds) are cached with the general TTL (default 5 minutes), meaning stale/invalid codes will be returned after the first 30 seconds — causing silent authentication failures.
  • setSecret notes duplication: When creating a new item with field === "notes", the value is stored in both the notes property and as a custom field named "notes" due to an incomplete exclusion in the ternary condition on the fields array.
  • setSecret error swallowing: The bare catch block when checking for existing items treats all errors (vault locked, CLI missing, network errors) as "item not found," masking the real error and attempting an item creation that will fail with a confusing secondary error.
  • Good security practices: execFile over exec, env isolation without mutating process.env, --nointeraction and --raw flags.
  • Thorough test suite with 34 tests, though missing coverage for the notes-on-create and TOTP caching edge cases.

Confidence Score: 3/5

  • This PR has logic bugs that should be fixed before merging, but they won't break existing functionality since this is an additive, opt-in feature.
  • Score of 3 reflects two confirmed logic bugs (TOTP caching returning stale codes, notes field duplication on create) and one error-handling issue (bare catch swallowing CLI errors in setSecret). None of these affect existing code since this is a new, opt-in provider, but they will cause incorrect behavior for users who adopt it. The security model is sound (execFile, env isolation, no shell injection surface).
  • Pay close attention to src/config/bitwarden-secret-provider.ts — specifically the getSecret TOTP caching path (line 221-225) and the setSecret create-new-item branch (lines 238-269).

Last reviewed commit: 35578de

(2/5) Greptile learns from your feedback when you react with thumbs up/down!

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 files reviewed, 3 comments

Edit Code Review Agent Settings | Greptile

Comment thread src/config/bitwarden-secret-provider.ts Outdated
Comment on lines +221 to +225
async getSecret(name: string, _version?: string): Promise<string> {
const cacheKey = `bw:${name}`;
const cached = localCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) {
return cached.value;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TOTP codes cached beyond validity window

TOTP codes rotate every ~30 seconds, but this caches them for cacheTtlMs which defaults to 300 seconds (5 minutes). After the first 30 seconds, the cached TOTP will be expired/invalid, causing silent authentication failures when the cached value is returned.

TOTP values should either not be cached, or cached for a much shorter duration (e.g., 25 seconds max):

Suggested change
async getSecret(name: string, _version?: string): Promise<string> {
const cacheKey = `bw:${name}`;
const cached = localCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) {
return cached.value;
if (field === "totp") {
const totp = await this.runBw(["get", "totp", itemQuery]);
// TOTP codes rotate every ~30 seconds; do not cache beyond that window
const totpTtl = Math.min(this.cacheTtlMs, 25_000);
localCache.set(cacheKey, { value: totp, expiresAt: Date.now() + totpTtl });
return totp;
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/config/bitwarden-secret-provider.ts
Line: 221-225

Comment:
**TOTP codes cached beyond validity window**

TOTP codes rotate every ~30 seconds, but this caches them for `cacheTtlMs` which defaults to 300 seconds (5 minutes). After the first 30 seconds, the cached TOTP will be expired/invalid, causing silent authentication failures when the cached value is returned.

TOTP values should either not be cached, or cached for a much shorter duration (e.g., 25 seconds max):

```suggestion
    if (field === "totp") {
      const totp = await this.runBw(["get", "totp", itemQuery]);
      // TOTP codes rotate every ~30 seconds; do not cache beyond that window
      const totpTtl = Math.min(this.cacheTtlMs, 25_000);
      localCache.set(cacheKey, { value: totp, expiresAt: Date.now() + totpTtl });
      return totp;
    }
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already handled — the TOTP branch already caps to 25s via Math.min(this.cacheTtlMs, 25_000).

Comment thread src/config/bitwarden-secret-provider.ts Outdated
Comment on lines +261 to +263
organizationId: null,
folderId: null,
type: 1,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

notes field duplicated into custom fields on create

When field === "notes", the condition field !== "password" && field !== "username" is true, so a custom field named "notes" is added to fields[] in addition to correctly setting notes: value. This creates a Bitwarden item with the value stored in two places — the notes property and a spurious custom field.

Note that updateItemField (line 275) handles "notes" correctly via a dedicated case branch without touching fields. The same exclusion should apply here:

Suggested change
organizationId: null,
folderId: null,
type: 1,
fields:
field !== "password" && field !== "username" && field !== "notes" ? [{ name: field, value, type: 0 }] : [],
notes: field === "notes" ? value : null,
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/config/bitwarden-secret-provider.ts
Line: 261-263

Comment:
**`notes` field duplicated into custom fields on create**

When `field === "notes"`, the condition `field !== "password" && field !== "username"` is `true`, so a custom field named `"notes"` is added to `fields[]` in addition to correctly setting `notes: value`. This creates a Bitwarden item with the value stored in two places — the `notes` property and a spurious custom field.

Note that `updateItemField` (line 275) handles `"notes"` correctly via a dedicated `case` branch without touching `fields`. The same exclusion should apply here:

```suggestion
        fields:
          field !== "password" && field !== "username" && field !== "notes" ? [{ name: field, value, type: 0 }] : [],
        notes: field === "notes" ? value : null,
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already handled — the exclusion list already includes notes: field !== "password" && field !== "username" && field !== "notes".

Comment thread src/config/bitwarden-secret-provider.ts Outdated
Comment on lines +238 to +244
const value = this.extractField(item, field);

localCache.set(cacheKey, { value, expiresAt: Date.now() + this.cacheTtlMs });
return value;
}

async setSecret(name: string, value: string): Promise<void> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bare catch swallows all CLI errors, not just "not found"

This catch block treats every error (vault locked, CLI missing, network failures) as "item doesn't exist" and falls through to the create branch. If the vault is locked, this will attempt to create a new item instead of surfacing the lock error, producing a confusing secondary error message.

Consider narrowing the catch to only treat "Not found" errors as the item-not-existing signal:

Suggested change
const value = this.extractField(item, field);
localCache.set(cacheKey, { value, expiresAt: Date.now() + this.cacheTtlMs });
return value;
}
async setSecret(name: string, value: string): Promise<void> {
let existingItem: BitwardenItem | null = null;
try {
const raw = await this.runBw(["get", "item", itemQuery]);
existingItem = JSON.parse(raw);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
if (!msg.includes("not found") && !msg.includes("Not found")) {
throw err;
}
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/config/bitwarden-secret-provider.ts
Line: 238-244

Comment:
**Bare `catch` swallows all CLI errors, not just "not found"**

This catch block treats every error (vault locked, CLI missing, network failures) as "item doesn't exist" and falls through to the create branch. If the vault is locked, this will attempt to create a new item instead of surfacing the lock error, producing a confusing secondary error message.

Consider narrowing the catch to only treat "Not found" errors as the item-not-existing signal:

```suggestion
    let existingItem: BitwardenItem | null = null;
    try {
      const raw = await this.runBw(["get", "item", itemQuery]);
      existingItem = JSON.parse(raw);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      if (!msg.includes("not found") && !msg.includes("Not found")) {
        throw err;
      }
    }
```

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already handled — the catch block already rethrows non-"not found" errors: if (!msg.includes("not found") && !msg.includes("Not found")) { throw err; }.

@ihsanmokhlisse

Copy link
Copy Markdown
Author

Addressed all three Greptile review comments in commit 1385301:

1. TOTP cache (line 233): Cache is now capped at 25 seconds via Math.min(this.cacheTtlMs, 25_000). Added test: "does not cache TOTP for the full provider TTL".

2. Notes duplication (line 275): Added && field !== "notes" to the fields condition so notes are only stored in item.notes, not duplicated as a custom field. Added test: "does not duplicate notes into custom fields on create".

3. Bare catch in setSecret (line 253): Catch now only swallows "not found" errors; all other errors (locked vault, CLI missing, network) are re-thrown. Added test: "re-throws non-not-found errors instead of swallowing them".

Tests: 37/37 passing.

@jzakirov

Copy link
Copy Markdown
Contributor

I really like the idea of adding a Vaultwarden. Let's push that into the code base!

@ihsanmokhlisse

Copy link
Copy Markdown
Author

@jzakirov Thanks for the support!

Right now OpenClaw stores all API keys and tokens as plain-text JSON on disk (~/.openclaw/openclaw.json, auth-profiles.json). The only protection is file permissions — no encryption at rest, no integration with any secret manager.

Bitwarden/Vaultwarden is used by 55M+ people and is fully self-hostable — which makes it a natural fit for OpenClaw's self-hosted audience. The idea here is to let users store their credentials where they already manage their secrets, rather than leaving them in plain config files.

This is one piece of a bigger gap: OpenClaw currently has no native secret provider integration at all. PR #16663 introduces the SecretsProvider interface with GCP/AWS/Azure/Vault backends, PR #17311 adds env/keyring/1Password — and this PR adds Bitwarden to cover the open-source password manager crowd.

Together these close a real security gap and give users a choice of backends depending on their setup — cloud vault, OS keychain, password manager, or encrypted file.

@whynice724-cell whynice724-cell left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review ✅

PR #23096 - Bitwarden/Vaultwarden Secret Provider

Summary

Adding Bitwarden integration for secret management - a highly requested feature (55M+ users).

Analysis

  • Problem: OpenClaw lacked Bitwarden integration for users who store API keys in their password vault
  • Solution: New BitwardenSecretProvider implementing SecretProvider interface
  • Scope: Two new files only - no changes to existing code ✅
  • Testing: 34 unit tests included ✅

Security Considerations

  • Uses standard Bitwarden CLI (bw) for integration
  • Follows existing SecretProvider interface pattern
  • Syntax: ${bw:item-name/field-name} is intuitive

Verdict

Approve - Clean implementation, well-tested, no breaking changes. Good addition for self-hosted users who prefer Bitwarden.

@ihsanmokhlisse
ihsanmokhlisse force-pushed the feat/bitwarden-secret-provider branch from 1385301 to ce5df77 Compare February 25, 2026 00:44
@ihsanmokhlisse

Copy link
Copy Markdown
Author

Rebased on latest main (no conflicts). All 3 Greptile review comments were verified as already addressed in the current code — TOTP cache cap, notes exclusion, and narrowed catch block are all in place. Ready for human review.

@ihsanmokhlisse
ihsanmokhlisse force-pushed the feat/bitwarden-secret-provider branch from ce5df77 to e8c6cbf Compare February 27, 2026 09:49
@ihsanmokhlisse

Copy link
Copy Markdown
Author

Rebased on latest main — no conflicts. Branch is up to date and ready for review.

@vincentkoc vincentkoc self-assigned this Mar 4, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Thanks for the contribution.

With #26155 now merged in main, can you please rebase this branch on latest main and align it to the merged secrets baseline? This one looks like a good candidate to stay focused and land as a smaller follow-up after rebase.

@ihsanmokhlisse
ihsanmokhlisse force-pushed the feat/bitwarden-secret-provider branch from e8c6cbf to a400ff8 Compare March 6, 2026 16:05
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts labels Mar 6, 2026
@ihsanmokhlisse

Copy link
Copy Markdown
Author

Rebased on latest main and fully aligned with the merged secrets baseline (#26155).

What changed and why:

The original PR added a class-based BitwardenSecretProvider implementing a SecretProvider interface from PR #16663. That interface never merged — instead, #26155 shipped a transport-level architecture where all external secret managers (1Password, Vault, sops) use the generic source: "exec" provider. There are no per-vendor source types and no class/interface plugin system — just three transports (env, file, exec) with vendor-specific docs.

This rewrite aligns Bitwarden with that exact pattern:

  • Removed the class-based BitwardenSecretProvider, the inline SecretProvider interface, setSecret/listSecrets/testConnection (read-only system), module-level cache (uses SecretRefResolveCache), and TOTP support (incompatible with eager resolution at startup).
  • Added a Bitwarden/Vaultwarden section in docs/gateway/secrets.md following the same format as 1Password CLI, HashiCorp Vault, and sops — showing single-secret config, self-hosted Vaultwarden guidance (BW_URL), and CI/automation with API key auth (BW_CLIENTID/BW_CLIENTSECRET).
  • Added scripts/bw-exec-resolver.mjs — a protocol-v1 exec wrapper for multi-secret batch resolution. This is the value-add beyond docs: instead of one exec provider per Bitwarden secret, users point a single provider at the wrapper script and use item-name/field-name ref IDs.
  • 37 tests covering every exported function: parseRef (5), extractField (14), groupByItem (6), runBw (1), resolveSecrets with mock bw scripts (6), and end-to-end child process tests (5).

Files:

  • docs/gateway/secrets.md — Bitwarden docs section
  • scripts/bw-exec-resolver.mjs — protocol-v1 wrapper
  • src/secrets/bw-exec-resolver.test.ts — 37 tests

@ihsanmokhlisse

Copy link
Copy Markdown
Author

@vincentkoc Rebased on latest main and aligned with the merged secrets baseline from #26155 as requested.

The class-based BitwardenSecretProvider is gone — replaced with the same source: "exec" transport pattern used by 1Password, Vault, and sops. No new source types, no new interfaces, just docs + a protocol-v1 wrapper script for multi-secret batch resolution. 37 tests covering every function. CI check fix included (type declarations for the .mjs wrapper).

Ready for review when you get a chance.

@ihsanmokhlisse
ihsanmokhlisse force-pushed the feat/bitwarden-secret-provider branch from 95ac9eb to 8dd511b Compare March 11, 2026 10:19
@ihsanmokhlisse

Copy link
Copy Markdown
Author

Rebased on latest main — no conflicts. Branch is up to date. Actively maintained.

@Takhoffman
Takhoffman requested a review from a team as a code owner March 24, 2026 20:17
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels May 17, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 18, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 18, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. labels May 18, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 19, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added stale Marked as stale due to inactivity and removed stale Marked as stale due to inactivity labels May 19, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 20, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 21, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 21, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label May 24, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 24, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label May 24, 2026
@barnacle-openclaw

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: L stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Build contains hardcoded paths from build machine

6 participants