Skip to content

fix(agents): preserve blank local custom-provider API keys after onboarding - #45631

Merged
frankekn merged 6 commits into
mainfrom
fix/pr-43118-local-auth-replacement
Mar 14, 2026
Merged

frankekn merged 6 commits into
mainfrom
fix/pr-43118-local-auth-replacement

Conversation

@frankekn

Copy link
Copy Markdown
Contributor

Summary

  • Problem: loopback OpenAI-compatible custom providers still break when onboarding leaves the API key blank, and the synthetic local marker can degrade into a fake bearer Authorization header.
  • Why it matters: the onboarding contract explicitly says the key can be left blank for local servers, so llama.cpp, vLLM, and LocalAI setups should not fail or silently send bogus auth.
  • What changed: this clean replacement replays the original loopback detection/auth fallback work, then adds runtime Authorization clearing plus guards so explicit apiKey and token/oauth configs are not silently downgraded.
  • What did NOT change: remote endpoints still require real credentials, and explicit non-api-key auth modes still do not auto-fallback.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Original contributor: @xinhuagu.
This PR is a clean maintainer replacement for #43118 after that contributor branch was auto-closed as dirty during maintainer prep.

User-visible / Behavior Changes

  • Local OpenAI-compatible custom providers can keep the API key blank after onboarding when the base URL is loopback.
  • Explicit apiKey config still behaves like an explicit credential requirement.
  • Explicit auth: token / auth: oauth config is no longer silently downgraded into synthetic api-key auth.
  • Loopback OpenAI-compatible calls now clear the synthetic Authorization header instead of sending Bearer custom-local.

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) Yes
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation:
    • This changes auth-header handling for loopback OpenAI-compatible custom providers only. The mitigation is explicit scoping: only loopback/custom providers with no explicit apiKey config and no explicit token/oauth override get the synthetic no-auth path.

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local pnpm workspace
  • Model/provider: custom openai-completions provider with loopback baseUrl
  • Integration/channel (if any): none
  • Relevant config (redacted): models.providers.<id>.baseUrl=http://127.0.0.1:11434/v1, blank apiKey

Steps

  1. Configure a custom OpenAI-compatible provider with a loopback baseUrl and no API key.
  2. Resolve provider auth for that model path.
  3. Exercise the OpenAI-compatible runtime path with the synthetic local marker.

Expected

  • Loopback custom providers keep working with blank API keys.
  • No fake bearer Authorization header is sent.
  • Explicit apiKey or token/oauth config keeps its normal failure behavior when credentials are missing.

Actual

  • Verified by tests below.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
    • pnpm exec vitest run src/agents/model-auth.test.ts -> 24 passed
    • pnpm build -> passed
  • Edge cases checked:
    • explicit apiKey config does not synthesize local auth
    • explicit token/oauth override does not synthesize local auth
    • built-in Bedrock local baseUrl still keeps AWS SDK auth fallback
    • synthetic local OpenAI-compatible auth clears Authorization while preserving other headers
  • What you did not verify:
    • full pnpm check currently fails on existing main typing debt unrelated to this PR (src/cli/daemon-cli/status.test.ts, src/commands/onboard-non-interactive.gateway.test.ts, src/commands/onboard-non-interactive/local.ts, src/infra/outbound/deliver.lifecycle.test.ts, src/infra/outbound/deliver.test-helpers.ts, src/infra/outbound/deliver.test.ts). The latest main CI run (23077863921) fails on the same set.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly:
    • Revert this PR or set an explicit apiKey/auth mode for the custom provider.
  • Files/config to restore:
    • src/agents/model-auth.ts
    • src/agents/model-auth.test.ts
    • src/agents/pi-embedded-runner/run.ts
    • src/agents/pi-embedded-runner/compact.ts
  • Known bad symptoms reviewers should watch for:
    • fake Bearer custom-local headers on loopback requests
    • explicit token/oauth custom providers silently falling back to api-key auth

Risks and Mitigations

  • Risk: loopback detection could widen synthetic no-auth behavior too far.
    • Mitigation: restricted to custom providers with loopback base URLs, no explicit apiKey config, and no explicit non-api-key auth override.
  • Risk: OpenAI-compatible header override could strip unrelated request headers.
    • Mitigation: regression test verifies Authorization is cleared while preserving existing custom headers.

@aisle-research-bot

aisle-research-bot Bot commented Mar 14, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🔵 Low Synthetic no-auth for loopback custom providers enables config-driven localhost SSRF/data exfiltration

1. 🔵 Synthetic no-auth for loopback custom providers enables config-driven localhost SSRF/data exfiltration

Property Value
Severity Low
CWE CWE-918
Location src/agents/model-auth.ts:158-205

Description

The new synthetic auth behavior for custom providers can make OpenClaw send model prompts/transcripts to a loopback HTTP service even when the user did not configure any credentials, which meaningfully weakens the prior “missing API key blocks requests” safeguard.

Why this is a security issue (when configuration is not fully trusted):

  • resolveSyntheticLocalProviderAuth() now returns CUSTOM_LOCAL_AUTH_MARKER for any custom provider that:
    • has models.providers.<name>.baseUrl pointing to a loopback-ish hostname (localhost/127.0.0.1/0.0.0.0/IPv6 loopback)
    • has no explicit apiKey configured
    • uses api: "openai-completions"
  • applyLocalNoAuthHeaderOverride() then removes the Authorization header for that marker.
  • As a result, a configuration that sets a custom provider baseUrl to http://127.0.0.1:<port>/v1 can cause OpenClaw to transmit potentially sensitive prompts/code/tool outputs to whatever is listening on that local port.

This becomes materially exploitable if an attacker can influence configuration (examples grounded in repo):

  • OpenClaw loads dotenv from the current working directory (dotenv.config()), before config is read (src/index.ts, src/cli/run-main.ts, src/infra/dotenv.ts).
    • A malicious repo can include a .env that sets OPENCLAW_CONFIG_PATH / OPENCLAW_STATE_DIR, causing OpenClaw to load attacker-controlled config when the user runs the CLI in that repo.
  • Once an attacker-controlled config is loaded, it can set models.providers.<attacker>.baseUrl to loopback and set agent default model to that provider/model, causing runtime to send data to localhost without an API key.

Vulnerable code (new behavior):

if (providerConfig.baseUrl && isLocalBaseUrl(providerConfig.baseUrl)) {
  return {
    apiKey: CUSTOM_LOCAL_AUTH_MARKER,
    source: `models.providers.${params.provider} (synthetic local key)`,
    mode: "api-key",
  };
}

and later:

const headers = {
  ...model.headers,
  Authorization: null,
} as unknown as Record<string, string>;

Impact:

  • Information disclosure: sensitive conversation / code context can be sent to an unintended local service.
  • SSRF-style local targeting: depending on how the OpenAI-compatible client constructs paths, this can hit local HTTP services that were never meant to receive such payloads (or may have side effects when they do).

Precondition:

  • Attacker must be able to influence OpenClawConfig (e.g., via repo-provided .env affecting OPENCLAW_CONFIG_PATH / state dir, or any other external config injection path).

Recommendation

Require explicit opt-in before sending any model traffic to loopback endpoints without credentials.

Suggested approaches (choose one):

  1. Add an explicit auth mode such as auth: "none" for providers and only allow this behavior when set.

  2. Add an explicit boolean flag on providers, e.g. models.providers.<name>.allowLocalUnauthenticated: true, and gate the synthetic marker behind it.

  3. If you keep the automatic behavior, emit a prominent warning and require a one-time acknowledgement persisted in config.

Also consider hardening config trust:

  • Avoid implicitly honoring repo-local .env values for OPENCLAW_CONFIG_PATH/OPENCLAW_STATE_DIR unless the user explicitly enables it (or at minimum warn when config path is outside the default state dir).

Example gating (conceptual):

if (
  providerConfig.baseUrl &&
  isLocalBaseUrl(providerConfig.baseUrl) &&
  providerConfig.allowLocalUnauthenticated === true
) {
  return { apiKey: CUSTOM_LOCAL_AUTH_MARKER, source: ..., mode: "api-key" };
}

This preserves UX for intentional local LLM setups while preventing silent enablement from attacker-influenced configuration.


Analyzed PR: #45631 at commit 57393e1

Last updated on: 2026-03-14T03:37:34Z

@greptile-apps

greptile-apps Bot commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes loopback OpenAI-compatible custom providers so that a blank API key left during onboarding does not cause auth failures or send a bogus Authorization: Bearer custom-local header. It extends the existing synthetic-local-auth pattern (previously Ollama-only) to any custom provider whose baseUrl resolves to a loopback address, while correctly guarding against degrading explicit apiKey or oauth/token configs.

Key changes:

  • model-auth-markers.ts: New CUSTOM_LOCAL_AUTH_MARKER = "custom-local" constant, registered as a non-secret marker alongside OLLAMA_LOCAL_AUTH_MARKER.
  • model-auth.ts: resolveSyntheticLocalProviderAuth is extended beyond Ollama with loopback detection (isLocalBaseUrl), explicit-apiKey guard (hasExplicitProviderApiKeyConfig), and auth-override guard. New exported applyLocalNoAuthHeaderOverride patches the model's headers with Authorization: null so the OpenAI SDK does not inject a fake bearer token on loopback requests.
  • compact.ts / run.ts: applyLocalNoAuthHeaderOverride is called at both embedded runner entry points, mirroring the pattern symmetrically.
  • Tests: 24 new cases cover loopback synthesis for multiple address forms, remote provider rejection, explicit-config guards, the Bedrock aws-sdk fallback, and header clearing.

Issues found:

  • CHANGELOG.md line 60 contains an unresolved <<<<<<< HEAD git conflict marker that must be removed before merging.
  • isLocalBaseUrl includes three non-bracketed IPv6 host comparisons ("::1", "::ffff:7f00:1", "::ffff:127.0.0.1") that can never match — Node.js's WHATWG URL parser always serializes IPv6 hostnames with brackets.
  • applyLocalNoAuthHeaderOverride sets Authorization: null via an as unknown as Record<string, string> cast. Whether null clears the header or causes a runtime error depends on @mariozechner/pi-ai's internal header-building behaviour; deleting the key would be safer and type-correct.

Confidence Score: 3/5

  • PR should not be merged as-is due to an unresolved git conflict marker in CHANGELOG.md; core logic is sound once that is fixed.
  • The auth logic itself is well-structured and the test suite is thorough. However, the unresolved <<<<<<< HEAD conflict marker in CHANGELOG.md is a blocking issue that would ship corrupted content. The Authorization: null cast and redundant IPv6 checks are lower-severity concerns but add fragility and technical debt.
  • CHANGELOG.md requires resolution of the conflict marker before merge. src/agents/model-auth.ts warrants a second look at the Authorization: null header override pattern.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: CHANGELOG.md
Line: 60

Comment:
**Unresolved git conflict marker in CHANGELOG**

Line 60 contains a bare `<<<<<<< HEAD` conflict marker that was never resolved. This means the merge conflict between the `macOS/voice wake` entry and the new `Agents/custom providers` entry was left in a broken state. As-is, this line would appear verbatim in the published changelog and would corrupt any tooling that parses the file.

The `<<<<<<< HEAD` should be removed, and only one of the two orderings of the two entries should be kept (both entries appear to be valid changes that belong in the changelog).

```suggestion
- macOS/voice wake: stop crashing wake-word command extraction when speech segment ranges come from a different transcript instance.
- Agents/custom providers: preserve blank API keys for loopback OpenAI-compatible custom providers by clearing the synthetic Authorization header at runtime, while keeping explicit apiKey and oauth/token config from silently downgrading into fake bearer auth. (#43118) Thanks @xinhuagu.
```

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

---

This is a comment left during a code review.
Path: src/agents/model-auth.ts
Line: 126-141

Comment:
**Dead-code IPv6 host comparisons (non-bracketed forms never match)**

When `new URL(...)` parses an IPv6 address, Node.js serializes the hostname **with** the surrounding brackets per the WHATWG URL spec. For example:

```
new URL("http://[::1]:8080/v1").hostname // → "[::1]"
new URL("http://[::ffff:127.0.0.1]:8080/v1").hostname // → "[::ffff:127.0.0.1]"
```

This means the three non-bracketed variants — `"::1"`, `"::ffff:7f00:1"`, and `"::ffff:127.0.0.1"` — can never be matched through this code path. The bracketed counterparts (`"[::1]"`, `"[::ffff:7f00:1]"`, `"[::ffff:127.0.0.1]"`) are sufficient and already present.

Consider removing the dead entries to avoid false confidence that both forms are covered:

```suggestion
  try {
    const host = new URL(baseUrl).hostname.toLowerCase();
    return (
      host === "localhost" ||
      host === "127.0.0.1" ||
      host === "0.0.0.0" ||
      host === "[::1]" ||
      host === "[::ffff:7f00:1]" ||
      host === "[::ffff:127.0.0.1]"
    );
  } catch {
    return false;
  }
```

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

---

This is a comment left during a code review.
Path: src/agents/model-auth.ts
Line: 515-518

Comment:
**Unsafe `null` header cast may silently fail to clear `Authorization`**

The object `{ ...model.headers, Authorization: null }` is cast `as unknown as Record<string, string>` to satisfy TypeScript. At runtime, whether `null` actually removes the `Authorization` header depends entirely on how `@mariozechner/pi-ai` processes the `headers` map before passing it to the Fetch API. The Node.js `Headers` constructor rejects `null` values (`TypeError: Header value can't be null or undefined`), so if `pi-ai` does a naïve `new Headers(model.headers)`, the call will throw rather than clear the header.

The test intercepts `globalThis.fetch` *after* the SDK's own header-building step, so it validates the end-to-end outcome when the SDK handles `null` correctly, but it doesn't prevent a future SDK update from breaking this silently.

A safer and more explicit approach would be to delete the key rather than set it to `null`:

```suggestion
  const { Authorization: _drop, ...restHeaders } = model.headers ?? {};
  const headers = restHeaders as Record<string, string>;
```

This avoids the cast entirely and is unambiguous regardless of how the downstream library handles the headers object.

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

Last reviewed commit: ab8629e

Comment thread CHANGELOG.md Resolved
Comment thread src/agents/model-auth.ts Resolved
Comment thread src/agents/model-auth.ts Resolved
xinhuagu and others added 6 commits March 14, 2026 10:51
…t base URLs

Custom providers with local base URLs (127.0.0.1, localhost, ::1, etc.)
no longer fail with 'No API key found' when the user leaves the API key
blank during onboarding. The auth resolver now synthesizes a local auth
marker for these providers, matching the existing behavior for Ollama.

Fixes #42890
…127.0.0.1 coverage

Address review feedback from ademczuk and Aisle:
- Remove .local (mDNS/Bonjour) from isLocalBaseUrl — these resolve to
  LAN machines, not necessarily localhost (CWE-287)
- Add ::ffff:127.0.0.1 (IPv4-mapped IPv6 loopback) support
- Add test for ::ffff:127.0.0.1 path
@frankekn
frankekn force-pushed the fix/pr-43118-local-auth-replacement branch from 1c8fdc5 to 57393e1 Compare March 14, 2026 02:52
@davidemanuelDEV

Copy link
Copy Markdown
Contributor

Review: ✅ LGTM

Thorough fix for custom providers with local loopback URLs and no API key. Key things done right:

  1. isLocalBaseUrl covers all loopback variants (localhost, 127.0.0.1, 0.0.0.0, ::1, ::ffff:127.0.0.1)
  2. CUSTOM_LOCAL_AUTH_MARKER follows the established pattern (Ollama marker)
  3. applyLocalNoAuthHeaderOverride strips the synthetic Authorization header at request time so local servers (llama.cpp, vLLM, LocalAI) that do not require auth work cleanly
  4. Does NOT synthesize auth when apiKey is explicitly configured, when auth mode is oauth, or for built-in providers (preserves aws-sdk fallback for Bedrock)
  5. Excellent test coverage — 8 tests covering all loopback variants, remote URLs, explicit apiKey, oauth mode, and the actual fetch header stripping

CHANGELOG entry included. Well-structured, backwards compatible.

@frankekn
frankekn merged commit 01674c5 into main Mar 14, 2026
24 of 31 checks passed
@frankekn
frankekn deleted the fix/pr-43118-local-auth-replacement branch March 14, 2026 03:08
@frankekn

frankekn commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Custom Provider doesn't work after Onbording with error: No API key found for provider

3 participants