fix(security): require an operator credential to export stored credentials (#16680)

* fix(security): require an operator credential to export stored credentials

GET /api/settings/export-json returns every provider connection decrypted plus
the raw API keys, and GET /api/db-backups/export and /api/db-backups/exportAll
ship the whole SQLite database. All three accepted any credential that passed
isAuthenticated(), so an API key with the `manage` (or `admin`) scope could
download every stored secret.

They now go through requireOperatorCredential() and accept only the instance
operator: a signed-in dashboard session, the local CLI subject (pipeline-
stamped or validated on loopback), or an instance with login disabled. API
keys of any scope and `oma_` access tokens get 403; no credential is still 401.

The operator check already existed twice (sync token issuance and admin CLI
token minting). requireOperatorCredential() in src/lib/api/operatorCredential.ts
now wraps the management-auth step plus resolveOperatorCredential(), and the
sync token issuer is rebuilt on it (with the internal-service token opt-in it
already accepted), so issuance keeps the same issuer kinds and messages.

Imports (import-json, db-backups import/restore) are unchanged.

* docs(changelog): number the credential-export fragment

* docs(changelog): link the credential-export fragment to its PR
This commit is contained in:
Diego Rodrigues de Sa e Souza
2026-10-15 09:41:59 -03:00
committed by GitHub
parent 8772b05299
commit 94159e1b75
11 changed files with 315 additions and 58 deletions

View File

@@ -0,0 +1 @@
- **fix(security):** exporting stored credentials now needs the instance operator. `GET /api/settings/export-json`, `GET /api/db-backups/export` and `GET /api/db-backups/exportAll` accept a signed-in dashboard session, the local CLI, or an instance with login disabled; API keys of any scope (including `manage`) and `oma_` access tokens get `403`. The check is the same one that guards sync token issuance and admin CLI token minting (`requireOperatorCredential()` in `src/lib/api/operatorCredential.ts`) ([#16680](https://github.com/diegosouzapw/OmniRoute/pull/16680)).

View File

@@ -101,6 +101,14 @@ supplemented:
| `CLIENT_API` | Model-serving endpoints — `/api/v1/*`, `/api/v1beta/*`, plus aliases `/v1/*`, `/v1beta/*`, `/chat/completions`, `/responses`, `/models`, `/codex/*`. | Bearer key when the effective `REQUIRE_API_KEY` feature flag is enabled |
| `MANAGEMENT` | Dashboard pages, settings, providers, keys, admin and diagnostics endpoints. | Dashboard session OR Bearer with `manage` scope |
A few `MANAGEMENT` actions are **operator-only**: a `manage` key is not enough. Exporting stored
credentials (`GET /api/settings/export-json`, `GET /api/db-backups/export`,
`GET /api/db-backups/exportAll`), issuing a sync token (`POST /api/sync/tokens`) and minting an
`admin` CLI access token (`POST /api/cli/tokens`) require a dashboard session, the local CLI
subject, or login disabled; API keys of any scope and `oma_` access tokens get `403`. The check
lives in `src/lib/api/operatorCredential.ts` (`resolveOperatorCredential()` /
`requireOperatorCredential()`).
## Pipeline
```

View File

@@ -9939,6 +9939,11 @@ paths:
responses:
"200":
description: OK
"403":
description: >-
Machine credential refused. Exports carry every stored credential, so they require
the dashboard session or the local CLI (or login disabled); API keys of any scope
and `oma_` access tokens get 403.
/api/db-backups/exportAll:
get:
tags:
@@ -9948,6 +9953,11 @@ paths:
responses:
"200":
description: OK
"403":
description: >-
Machine credential refused. Exports carry every stored credential, so they require
the dashboard session or the local CLI (or login disabled); API keys of any scope
and `oma_` access tokens get 403.
/api/db-backups/import:
post:
tags:
@@ -11894,6 +11904,11 @@ paths:
responses:
"200":
description: OK
"403":
description: >-
Machine credential refused. Exports carry every stored credential, so they require
the dashboard session or the local CLI (or login disabled); API keys of any scope
and `oma_` access tokens get 403.
/api/settings/favicon:
get:
tags:

View File

@@ -1117,6 +1117,10 @@ curl -X PATCH "$OMNIROUTE_URL/api/keys/$KEY_ID" \
| `/api/db-backups/import` | POST | Upload .sqlite file to replace database |
| `/api/db-backups/exportAll` | GET | Download full backup as .tar.gz archive |
`/api/db-backups/export`, `/api/db-backups/exportAll` and `/api/settings/export-json` hand out
every stored credential, so they require the dashboard session or the local CLI (or login
disabled). API keys of any scope and `oma_` access tokens get `403`.
### Cloud Sync
| Endpoint | Method | Description |

View File

@@ -187,6 +187,17 @@ the Obsidian REST API token. GHSA-62vw only masked the `GET` password reveal; th
still on the fail-open tier (GHSA-7pq4-8pvv-rx7r). `enableObsidianVaultSync()` additionally
refuses a vault that is, sits inside, or contains the data directory.
#### Credential exports are operator-only
The tier above only decides whether _some_ credential is required. The routes that download
stored credentials add a second check in the handler: `GET /api/settings/export-json` (decrypted
provider connections and raw API keys), `GET /api/db-backups/export` (the SQLite file) and
`GET /api/db-backups/exportAll` (the full archive) call `requireOperatorCredential()`
(`src/lib/api/operatorCredential.ts`). It accepts a dashboard session, the local CLI subject, or
an instance with login disabled, and answers `403` to API keys of any scope (including `manage`
and `admin`) and to `oma_` access tokens. Sync token issuance (`POST /api/sync/tokens`) uses the
same helper, plus the trusted loopback internal-service token.
### Fresh-install bootstrap is loopback-only — by real peer, not `Host`
With no management password configured (and no `INITIAL_PASSWORD`), `isAuthRequired()` in

View File

@@ -3,7 +3,10 @@ import path from "path";
import fs from "fs";
import os from "os";
import { getDbInstance, SQLITE_FILE } from "@/lib/db/core";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
import {
CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
requireOperatorCredential,
} from "@/lib/api/operatorCredential";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
/**
@@ -12,14 +15,16 @@ import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
* Uses SQLite's native backup API to create a consistent snapshot,
* then streams it as a downloadable attachment.
*
* 🔒 Auth-guarded: requires JWT cookie or Bearer API key (finding #258-2).
* 🔒 Operator-only: dashboard session, local CLI, or login disabled. API keys (any scope)
* and `oma_` access tokens get 403 — the file carries every stored credential.
*/
export async function GET(request: Request) {
if (await isAuthRequired(request)) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
// Hands out every stored credential: operator only (dashboard session, local CLI, or login
// disabled). API keys of any scope and `oma_` access tokens get 403.
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
try {
if (!SQLITE_FILE || !fs.existsSync(SQLITE_FILE)) {
return NextResponse.json({ error: "Database file not found" }, { status: 404 });

View File

@@ -6,18 +6,30 @@ import fs from "fs";
import path from "path";
import os from "os";
import { execFileSync } from "node:child_process";
import { isAuthenticated } from "@/shared/utils/apiAuth";
import {
CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
requireOperatorCredential,
} from "@/lib/api/operatorCredential";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
/**
* GET /api/db-backups/exportAll
* Exports the entire database + settings as a ZIP archive
* Security: Requires admin authentication.
* Security: operator-only (dashboard session, local CLI, or login disabled); API keys
* and `oma_` access tokens get 403.
*/
export async function GET(request: NextRequest) {
if (!(await isAuthenticated(request)))
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Hands out every stored credential: operator only (dashboard session, local CLI, or login
// disabled). API keys of any scope and `oma_` access tokens get 403.
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
return buildFullExportResponse();
}
async function buildFullExportResponse(): Promise<Response> {
try {
if (!SQLITE_FILE) {
return NextResponse.json(

View File

@@ -4,7 +4,10 @@ import { getProviderConnections } from "@/lib/db/providers";
import { getCachedProviderNodes } from "@/lib/db/readCache";
import { getCombos } from "@/lib/db/combos";
import { getApiKeys } from "@/lib/db/apiKeys";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
import {
CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
requireOperatorCredential,
} from "@/lib/api/operatorCredential";
import {
getAllUsageHistory,
getAllDomainCostHistory,
@@ -47,11 +50,12 @@ export function filterPaidComboSteps<T extends { models?: unknown }>(combos: T[]
* Exports a legacy OmniRoute-compatible JSON backup.
*/
export async function GET(request: Request) {
if (await isAuthRequired(request)) {
if (!(await isAuthenticated(request))) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
// Hands out every stored credential: operator only (dashboard session, local CLI, or login
// disabled). API keys of any scope and `oma_` access tokens get 403.
const operatorVerdict = await requireOperatorCredential(request, {
forbiddenMessage: CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
});
if (operatorVerdict.ok === false) return operatorVerdict.response;
try {
const url = new URL(request.url);

View File

@@ -1,8 +1,20 @@
import { createErrorResponse } from "@/lib/api/errorResponse";
import { isTrustedLoopbackInternalServiceRequest } from "@/lib/api/internalServiceAuth";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { isCliTokenAuthValid } from "@/lib/middleware/cliTokenAuth";
import { AUTHZ_HEADER_AUTH_KIND, AUTHZ_HEADER_AUTH_LABEL } from "@/server/authz/headers";
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
export type OperatorCredentialKind = "open_instance" | "dashboard_session" | "local_cli";
export type OperatorCredentialKind =
"open_instance" | "dashboard_session" | "internal_service" | "local_cli";
export interface OperatorCredentialOptions {
/**
* Also accept the trusted loopback internal-service token. Off by default: only surfaces
* an internal service actually calls (sync token issuance) should opt in.
*/
allowInternalService?: boolean;
}
/**
* Is the caller the instance operator, as opposed to a machine credential?
@@ -11,7 +23,8 @@ export type OperatorCredentialKind = "open_instance" | "dashboard_session" | "lo
* - an instance with login disabled (every management surface is already open),
* - an authenticated dashboard session (password / OIDC login),
* - the machine-bound local CLI credential — the subject stamped by the authz pipeline,
* or validated here (loopback-only) for raw callers that skip the pipeline.
* or validated here (loopback-only) for raw callers that skip the pipeline,
* - optionally (`allowInternalService`), the trusted loopback internal-service token.
*
* API keys (whatever their scope) and `oma_` access tokens are machine credentials: they
* can be handed to automation, so actions that hand out top-level privilege must not be
@@ -20,10 +33,14 @@ export type OperatorCredentialKind = "open_instance" | "dashboard_session" | "lo
* Throws when the auth backend fails — callers map that to a 503, never to an allow.
*/
export async function resolveOperatorCredential(
request: Request
request: Request,
options: OperatorCredentialOptions = {}
): Promise<OperatorCredentialKind | null> {
if (!(await isAuthRequired(request, { ignorePublicRoute: true }))) return "open_instance";
if (await isDashboardSessionAuthenticated(request)) return "dashboard_session";
if (options.allowInternalService && isTrustedLoopbackInternalServiceRequest(request)) {
return "internal_service";
}
if (
request.headers.get(AUTHZ_HEADER_AUTH_KIND) === "management_key" &&
request.headers.get(AUTHZ_HEADER_AUTH_LABEL) === "local-cli-token"
@@ -33,3 +50,51 @@ export async function resolveOperatorCredential(
if (await isCliTokenAuthValid(request)) return "local_cli";
return null;
}
export type OperatorAuthVerdict =
{ ok: true; operator: OperatorCredentialKind } | { ok: false; response: Response };
/**
* Route guard for operator-only management actions (issuing a sync token, exporting stored
* credentials). Runs the regular management auth first — so a missing credential is still a
* 401 and an invalid one keeps its usual status — then refuses machine credentials (API keys
* of any scope, `oma_` access tokens) with a 403 carrying `forbiddenMessage`.
*/
export async function requireOperatorCredential(
request: Request,
options: OperatorCredentialOptions & { forbiddenMessage: string }
): Promise<OperatorAuthVerdict> {
const authError = await requireManagementAuth(request);
if (authError) return { ok: false, response: authError };
let operator: OperatorCredentialKind | null;
try {
operator = await resolveOperatorCredential(request, {
allowInternalService: options.allowInternalService,
});
} catch {
return {
ok: false,
response: createErrorResponse({
status: 503,
message: "Service temporarily unavailable",
type: "server_error",
}),
};
}
if (operator) return { ok: true, operator };
return {
ok: false,
response: createErrorResponse({
status: 403,
message: options.forbiddenMessage,
type: "invalid_request",
}),
};
}
/** 403 message shared by every route that downloads stored credentials or a database copy. */
export const CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE =
"Exporting stored credentials requires a signed-in dashboard session or the local CLI; API keys and access tokens cannot download backups.";

View File

@@ -1,9 +1,7 @@
import { createErrorResponse } from "@/lib/api/errorResponse";
import { isTrustedLoopbackInternalServiceRequest } from "@/lib/api/internalServiceAuth";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { isCliTokenAuthValid } from "@/lib/middleware/cliTokenAuth";
import { AUTHZ_HEADER_AUTH_KIND, AUTHZ_HEADER_AUTH_LABEL } from "@/server/authz/headers";
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
import {
requireOperatorCredential,
type OperatorCredentialKind,
} from "@/lib/api/operatorCredential";
/**
* Who may issue a sync token.
@@ -26,37 +24,19 @@ export type SyncTokenIssuer = "session" | "cli" | "internal" | "open";
export type SyncTokenIssuerVerdict =
{ ok: true; issuer: SyncTokenIssuer } | { ok: false; response: Response };
const ISSUER_BY_OPERATOR: Record<OperatorCredentialKind, SyncTokenIssuer> = {
open_instance: "open",
dashboard_session: "session",
internal_service: "internal",
local_cli: "cli",
};
export async function authorizeSyncTokenIssuer(request: Request): Promise<SyncTokenIssuerVerdict> {
const authError = await requireManagementAuth(request);
if (authError) return { ok: false, response: authError };
if (!(await isAuthRequired(request, { ignorePublicRoute: true }))) {
return { ok: true, issuer: "open" };
}
if (await isDashboardSessionAuthenticated(request)) {
return { ok: true, issuer: "session" };
}
if (isTrustedLoopbackInternalServiceRequest(request)) {
return { ok: true, issuer: "internal" };
}
if (
(request.headers.get(AUTHZ_HEADER_AUTH_KIND) === "management_key" &&
request.headers.get(AUTHZ_HEADER_AUTH_LABEL) === "local-cli-token") ||
(await isCliTokenAuthValid(request))
) {
return { ok: true, issuer: "cli" };
}
return {
ok: false,
response: createErrorResponse({
status: 403,
message:
"Sync tokens can only be issued from a signed-in dashboard session or the local CLI.",
type: "invalid_request",
}),
};
const verdict = await requireOperatorCredential(request, {
allowInternalService: true,
forbiddenMessage:
"Sync tokens can only be issued from a signed-in dashboard session or the local CLI.",
});
if (verdict.ok === false) return verdict;
return { ok: true, issuer: ISSUER_BY_OPERATOR[verdict.operator] };
}

View File

@@ -0,0 +1,152 @@
// Credential exports hand the caller every stored secret: GET /api/settings/export-json
// returns decrypted provider connections plus raw API keys, and the two backup downloads
// (/api/db-backups/export, /api/db-backups/exportAll) ship the whole SQLite database. They
// must be reachable only by the instance operator:
// - a signed-in dashboard session, or the machine-bound local CLI subject → allowed;
// - an API key of any scope (manage / admin) or an `oma_` access token → 403;
// - no credential → 401;
// - login disabled (open instance) → allowed, same as every operator-only surface.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-credential-export-"));
const ORIGINAL_ENV = {
DATA_DIR: process.env.DATA_DIR,
API_KEY_SECRET: process.env.API_KEY_SECRET,
JWT_SECRET: process.env.JWT_SECRET,
INITIAL_PASSWORD: process.env.INITIAL_PASSWORD,
};
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "credential-export-api-key-secret";
process.env.JWT_SECRET = "credential-export-jwt-secret";
process.env.INITIAL_PASSWORD = "credential-export-password";
const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const accessTokensDb = await import("../../src/lib/db/accessTokens.ts");
const { updateSettings } = await import("../../src/lib/db/settings.ts");
const exportJsonRoute = await import("../../src/app/api/settings/export-json/route.ts");
const dbExportRoute = await import("../../src/app/api/db-backups/export/route.ts");
const dbExportAllRoute = await import("../../src/app/api/db-backups/exportAll/route.ts");
await updateSettings({ requireLogin: true });
const manageKey = await apiKeysDb.createApiKey("manage-automation", "machine-export", ["manage"]);
const adminScopedKey = await apiKeysDb.createApiKey("admin-automation", "machine-export", [
"admin",
]);
const adminAccessToken = accessTokensDb.createAccessToken({ name: "remote-cli", scope: "admin" });
test.after(() => {
apiKeysDb.resetApiKeyState();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
type ExportRoute = { GET: (request: Request) => Promise<Response> };
const ENDPOINTS: Array<{ name: string; url: string; route: ExportRoute }> = [
{
name: "GET /api/settings/export-json",
url: "http://localhost:20128/api/settings/export-json",
route: exportJsonRoute as unknown as ExportRoute,
},
{
name: "GET /api/db-backups/export",
url: "http://localhost:20128/api/db-backups/export",
route: dbExportRoute as unknown as ExportRoute,
},
{
name: "GET /api/db-backups/exportAll",
url: "http://localhost:20128/api/db-backups/exportAll",
route: dbExportAllRoute as unknown as ExportRoute,
},
];
function requestWith(url: string, headers: Record<string, string> = {}): Request {
return new Request(url, { method: "GET", headers });
}
async function drain(response: Response): Promise<void> {
// The backup downloads stream a temp file; consume the body so the temp dir is cleaned up.
await response.arrayBuffer().catch(() => undefined);
}
for (const { name, url, route } of ENDPOINTS) {
test(`${name}: a manage-scoped API key is refused with 403`, async () => {
const response = await route.GET(
requestWith(url, { authorization: `Bearer ${manageKey.key}` })
);
const body = await response.json();
assert.equal(response.status, 403);
assert.match(JSON.stringify(body), /dashboard session/i);
assert.ok(!JSON.stringify(body).includes(manageKey.key), "403 body must not echo the key");
});
test(`${name}: an admin-scoped API key is refused with 403`, async () => {
const response = await route.GET(
requestWith(url, { authorization: `Bearer ${adminScopedKey.key}` })
);
await drain(response);
assert.equal(response.status, 403);
});
test(`${name}: an admin oma_ access token is refused with 403`, async () => {
const response = await route.GET(
requestWith(url, { authorization: `Bearer ${adminAccessToken.secret}` })
);
await drain(response);
assert.equal(response.status, 403);
});
test(`${name}: a dashboard session can still export`, async () => {
const response = await route.GET(await makeManagementSessionRequest(url));
await drain(response);
assert.equal(response.status, 200);
});
test(`${name}: a dashboard session wins over a manage key sent alongside it`, async () => {
const response = await route.GET(
await makeManagementSessionRequest(url, { token: manageKey.key })
);
await drain(response);
assert.equal(response.status, 200);
});
test(`${name}: the pipeline-stamped local CLI subject can export`, async () => {
const response = await route.GET(
requestWith(url, {
"x-omniroute-auth-kind": "management_key",
"x-omniroute-auth-label": "local-cli-token",
})
);
await drain(response);
assert.equal(response.status, 200);
});
test(`${name}: unauthenticated callers get 401`, async () => {
const response = await route.GET(requestWith(url));
const body = await response.json();
assert.equal(response.status, 401);
assert.ok(!JSON.stringify(body).includes("at /"), "401 body must not leak a stack trace");
});
test(`${name}: with login disabled the instance is open and export works`, async () => {
await updateSettings({ requireLogin: false });
try {
const response = await route.GET(requestWith(url));
await drain(response);
assert.equal(response.status, 200);
} finally {
await updateSettings({ requireLogin: true });
}
});
}