Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix: harden OpenLit security (#1167)

Aman Agarwal0aee832c03e9
diff --git a/docs/latest/openlit/configuration.mdx b/docs/latest/openlit/configuration.mdx
index 7ad488a6..580c7c6b 100644
--- a/docs/latest/openlit/configuration.mdx
+++ b/docs/latest/openlit/configuration.mdx
@@ -124,6 +124,52 @@ For detailed OAuth setup instructions, see the [OAuth Authentication Setup](/lat
```
</ResponseField>
+## Security variables
+
+OpenLIT enables stricter API protections by default, including security response headers, CSRF checks for browser session API requests, vault secret encryption, and restricted CORS for the vault secrets API.
+
+<ResponseField name="OPENLIT_VAULT_ENCRYPTION_KEY">
+ Secret used to encrypt Vault values at rest with AES-256-GCM. If this is not set, OpenLIT falls back to `NEXTAUTH_SECRET`.
+
+ Use a stable, high-entropy value and keep it unchanged across restarts. Changing this value after secrets are encrypted prevents existing Vault values from being decrypted.
+
+ **Generate with**:
+ ```bash
+ openssl rand -base64 32
+ ```
+
+ **Example**:
+ ```yaml
+ export OPENLIT_VAULT_ENCRYPTION_KEY=your-vault-encryption-key
+ ```
+</ResponseField>
+
+<ResponseField name="OPENLIT_ALLOWED_CORS_ORIGINS">
+ Comma-separated list of browser origins that are allowed to call API-key authenticated Vault secret retrieval from another domain.
+
+ Configure this when a browser application hosted on a different origin needs to call `POST /api/vault/get-secrets`. Server-to-server SDK or REST calls usually do not need this because they do not send a browser `Origin` header.
+
+ Specify complete origins, including scheme and host. Do not use `*`.
+
+ **Example**:
+ ```yaml
+ export OPENLIT_ALLOWED_CORS_ORIGINS=https://app.example.com,https://admin.example.com
+ ```
+</ResponseField>
+
+<ResponseField name="OPENLIT_ALLOWED_ORIGINS">
+ Backward-compatible alias for `OPENLIT_ALLOWED_CORS_ORIGINS`.
+
+ **Example**:
+ ```yaml
+ export OPENLIT_ALLOWED_ORIGINS=https://app.example.com
+ ```
+</ResponseField>
+
+<Note>
+ `NEXTAUTH_URL` is also treated as an allowed same-site origin for Vault CORS checks. Browser requests from other domains must be listed in `OPENLIT_ALLOWED_CORS_ORIGINS` or `OPENLIT_ALLOWED_ORIGINS`.
+</Note>
+
## Environment file placement
Environment variables can be configured in multiple ways depending on your deployment method:
@@ -181,6 +227,10 @@ GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"
+
+# Security Configuration (Optional)
+OPENLIT_VAULT_ENCRYPTION_KEY="your-vault-encryption-key"
+OPENLIT_ALLOWED_CORS_ORIGINS="https://app.example.com,https://admin.example.com"
```
---
@@ -202,4 +252,4 @@ GITHUB_CLIENT_SECRET="your-github-client-secret"
href="/latest/controller/overview"
>
Discover and instrument LLM traffic across Kubernetes, Docker, and Linux using eBPF — no code changes required.
- </Card>
\ No newline at end of file
+ </Card>
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/vault/get.mdx b/docs/latest/openlit/developer-resources/api-reference/endpoint/vault/get.mdx
index 6e5dbea9..f367fbd3 100644
--- a/docs/latest/openlit/developer-resources/api-reference/endpoint/vault/get.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/vault/get.mdx
@@ -1,4 +1,22 @@
---
title: 'Get Secret(s)'
openapi: 'POST /api/vault/get-secrets'
----
\ No newline at end of file
+---
+
+## Cross-origin browser requests
+
+`POST /api/vault/get-secrets` is an API-key authenticated endpoint for retrieving Vault secrets. Browser requests from a different origin are blocked unless the calling origin is explicitly allowed.
+
+To allow a browser application hosted on another domain, configure the OpenLIT deployment with a comma-separated origin allowlist:
+
+```bash
+OPENLIT_ALLOWED_CORS_ORIGINS="https://app.example.com,https://admin.example.com"
+```
+
+`OPENLIT_ALLOWED_ORIGINS` is also supported as a backward-compatible alias. `NEXTAUTH_URL` is automatically treated as an allowed same-site origin.
+
+Use complete origins such as `https://app.example.com`. Do not configure wildcard origins for this endpoint.
+
+<Note>
+ Server-to-server SDK or REST requests usually do not need CORS configuration because CORS is enforced by browsers.
+</Note>
diff --git a/docs/latest/openlit/developer-resources/vault.mdx b/docs/latest/openlit/developer-resources/vault.mdx
index b8f59073..75a2cf35 100644
--- a/docs/latest/openlit/developer-resources/vault.mdx
+++ b/docs/latest/openlit/developer-resources/vault.mdx
@@ -9,6 +9,29 @@ Vault is designed to securely store and access sensitive information, such as AP
- **Secrets Management**: Seamlessly create, edit, and monitor the secrets associated with your applications.
- **Secure Access**: Retrieve secrets based on keys or tags, and safely integrate them into your Node.js or Python environments.
+- **Encrypted Storage**: Vault values are encrypted at rest with AES-256-GCM before they are stored.
+
+## Security and cross-origin access
+
+Vault secret retrieval uses API-key authentication and can be called from SDKs, REST clients, and server-side applications. Browser-based cross-origin calls are additionally restricted by CORS.
+
+If your application is hosted on a different domain from OpenLIT and calls `POST /api/vault/get-secrets` from the browser, add the application origin to `OPENLIT_ALLOWED_CORS_ORIGINS`:
+
+```bash
+OPENLIT_ALLOWED_CORS_ORIGINS="https://app.example.com"
+```
+
+Multiple origins can be comma-separated:
+
+```bash
+OPENLIT_ALLOWED_CORS_ORIGINS="https://app.example.com,https://admin.example.com"
+```
+
+Server-to-server SDK and REST calls usually do not require CORS configuration because CORS is enforced by browsers. Do not use wildcard origins for secret retrieval endpoints.
+
+<Note>
+ Vault values are encrypted with `OPENLIT_VAULT_ENCRYPTION_KEY`, or `NEXTAUTH_SECRET` if no dedicated Vault key is set. Keep the encryption key stable so existing secrets remain decryptable.
+</Note>
## Get started
@@ -129,4 +152,4 @@ Vault is designed to securely store and access sensitive information, such as AP
<Card title="LLM playground" href="/latest/openlit/prompts-experiments/openground" icon='flask'>
Compare cost, duration, and response tokens across different LLMs to find the most efficient model
</Card>
-</CardGroup>
\ No newline at end of file
+</CardGroup>
diff --git a/src/client/next.config.js b/src/client/next.config.js
index 5a6561b5..804469c6 100644
--- a/src/client/next.config.js
+++ b/src/client/next.config.js
@@ -1,6 +1,20 @@
/** @type {import('next').NextConfig} */
+const contentSecurityPolicy = [
+ "default-src 'self'",
+ "base-uri 'self'",
+ "object-src 'none'",
+ "frame-ancestors 'none'",
+ "form-action 'self'",
+ "img-src 'self' data: blob: https:",
+ "font-src 'self' data:",
+ "style-src 'self' 'unsafe-inline'",
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval'",
+ "connect-src 'self' https: wss:",
+].join("; ");
+
const nextConfig = {
output: "standalone",
+ poweredByHeader: false,
images: {
remotePatterns: [
{
@@ -17,6 +31,39 @@ const nextConfig = {
experimental: {
instrumentationHook: true,
},
+ async headers() {
+ return [
+ {
+ source: "/(.*)",
+ headers: [
+ {
+ key: "X-Content-Type-Options",
+ value: "nosniff",
+ },
+ {
+ key: "X-Frame-Options",
+ value: "DENY",
+ },
+ {
+ key: "Referrer-Policy",
+ value: "strict-origin-when-cross-origin",
+ },
+ {
+ key: "Permissions-Policy",
+ value: "camera=(), microphone=(), geolocation=()",
+ },
+ {
+ key: "X-XSS-Protection",
+ value: "1; mode=block",
+ },
+ {
+ key: "Content-Security-Policy",
+ value: contentSecurityPolicy,
+ },
+ ],
+ },
+ ];
+ },
};
module.exports = nextConfig;
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index fdc1f2e6..ecfe9674 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openlit",
- "version": "1.19.0",
+ "version": "1.19.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openlit",
- "version": "1.19.0",
+ "version": "1.19.1",
"dependencies": {
"@ai-sdk/anthropic": "^3.0.6",
"@ai-sdk/cohere": "^3.0.3",
diff --git a/src/client/package.json b/src/client/package.json
index c2406658..5b0fa34a 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -1,6 +1,6 @@
{
"name": "openlit",
- "version": "1.19.0",
+ "version": "1.19.1",
"private": true,
"scripts": {
"dev": "next dev",
diff --git a/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts b/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts
new file mode 100644
index 00000000..eac35b33
--- /dev/null
+++ b/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts
@@ -0,0 +1,153 @@
+jest.mock("@/lib/platform/vault", () => ({
+ getSecretsFromDatabaseId: jest.fn(),
+}));
+jest.mock("@/lib/posthog", () => ({
+ __esModule: true,
+ default: {
+ fireEvent: jest.fn(),
+ },
+}));
+jest.mock("@/constants/messages", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ NO_API_KEY: "No API key",
+ })),
+}));
+jest.mock("@/utils/asaw", () => jest.fn());
+
+import { OPTIONS, POST } from "@/app/api/vault/get-secrets/route";
+import { getSecretsFromDatabaseId } from "@/lib/platform/vault";
+import asaw from "@/utils/asaw";
+
+class TestHeaders {
+ private values = new Map<string, string>();
+
+ constructor(headers?: Record<string, string>) {
+ Object.entries(headers || {}).forEach(([key, value]) => {
+ this.values.set(key.toLowerCase(), value);
+ });
+ }
+
+ get(key: string) {
+ return this.values.get(key.toLowerCase()) ?? null;
+ }
+}
+
+class TestResponse {
+ status: number;
+ headers: TestHeaders;
+ private body: unknown;
+
+ constructor(body?: unknown, init?: { status?: number; headers?: Record<string, string> }) {
+ this.body = body;
+ this.status = init?.status ?? 200;
+ this.headers = new TestHeaders(init?.headers);
+ }
+
+ static json(body: unknown, init?: { status?: number; headers?: Record<string, string> }) {
+ return new TestResponse(body, init);
+ }
+
+ async json() {
+ return this.body;
+ }
+}
+
+(global as any).Response = TestResponse;
+
+function makeRequest({
+ origin,
+ host = "app.openlit.local",
+ authorization = "Bearer openlit-test",
+ body = {},
+}: {
+ origin?: string;
+ host?: string;
+ authorization?: string;
+ body?: Record<string, unknown>;
+}) {
+ const headers: Record<string, string> = {
+ host,
+ "content-type": "application/json",
+ };
+
+ if (origin) headers.origin = origin;
+ if (authorization) headers.authorization = authorization;
+
+ return {
+ headers: {
+ get: (key: string) => headers[key.toLowerCase()] ?? null,
+ },
+ json: jest.fn().mockResolvedValue(body),
+ } as unknown as Request;
+}
+
+describe("/api/vault/get-secrets CORS", () => {
+ const originalEnv = process.env;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ process.env = { ...originalEnv };
+ delete process.env.OPENLIT_ALLOWED_CORS_ORIGINS;
+ delete process.env.OPENLIT_ALLOWED_ORIGINS;
+ delete process.env.NEXTAUTH_URL;
+ });
+
+ afterAll(() => {
+ process.env = originalEnv;
+ });
+
+ it("rejects evil.com preflight requests", async () => {
+ const response = await OPTIONS(
+ makeRequest({ origin: "https://evil.com" })
+ );
+
+ expect(response.status).toBe(403);
+ expect(response.headers.get("Access-Control-Allow-Origin")).toBeNull();
+ });
+
+ it("allows same-origin preflight requests without wildcard CORS", async () => {
+ const response = await OPTIONS(
+ makeRequest({ origin: "https://app.openlit.local" })
+ );
+
+ expect(response.status).toBe(204);
+ expect(response.headers.get("Access-Control-Allow-Origin")).toBe(
+ "https://app.openlit.local"
+ );
+ expect(response.headers.get("Access-Control-Allow-Origin")).not.toBe("*");
+ expect(response.headers.get("Vary")).toBe("Origin");
+ });
+
+ it("allows configured trusted origins", async () => {
+ process.env.OPENLIT_ALLOWED_CORS_ORIGINS =
+ "https://trusted.example.com,https://docs.example.com";
+
+ const response = await OPTIONS(
+ makeRequest({ origin: "https://trusted.example.com" })
+ );
+
+ expect(response.status).toBe(204);
+ expect(response.headers.get("Access-Control-Allow-Origin")).toBe(
+ "https://trusted.example.com"
+ );
+ });
+
+ it("does not block no-Origin API key clients", async () => {
+ (asaw as jest.Mock).mockResolvedValue([null, { OPENAI_API_KEY: "sk-test" }]);
+
+ const response = await POST(makeRequest({ body: { key: "OPENAI_API_KEY" } }));
+ const body = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(getSecretsFromDatabaseId).toHaveBeenCalledWith({
+ apiKey: "openlit-test",
+ key: "OPENAI_API_KEY",
+ tags: undefined,
+ });
+ expect(body).toEqual({
+ err: null,
+ res: { OPENAI_API_KEY: "sk-test" },
+ });
+ });
+});
diff --git a/src/client/src/__tests__/clickhouse/migrations/encrypt-vault-values-migration.test.ts b/src/client/src/__tests__/clickhouse/migrations/encrypt-vault-values-migration.test.ts
new file mode 100644
index 00000000..8bea0e90
--- /dev/null
+++ b/src/client/src/__tests__/clickhouse/migrations/encrypt-vault-values-migration.test.ts
@@ -0,0 +1,63 @@
+jest.mock("@/lib/platform/vault/table-details", () => ({
+ OPENLIT_VAULT_TABLE_NAME: "openlit_vault",
+}));
+
+jest.mock("@/lib/platform/common", () => ({
+ dataCollector: jest.fn(),
+}));
+
+jest.mock("@/utils/crypto", () => ({
+ encryptValue: jest.fn((value: string) => `enc:v1:${value}`),
+ isEncrypted: jest.fn((value: string) => value.startsWith("enc:v1:")),
+}));
+
+jest.mock("@/lib/db-config", () => ({
+ getDBConfigById: jest.fn(),
+ getDBConfigByUser: jest.fn(),
+}));
+
+jest.mock("@/lib/prisma", () => ({
+ __esModule: true,
+ default: {
+ clickhouseMigrations: {
+ findFirst: jest.fn(),
+ create: jest.fn(),
+ },
+ },
+}));
+
+jest.mock("@/utils/log", () => ({
+ consoleLog: jest.fn(),
+}));
+
+import EncryptVaultValuesMigration from "@/clickhouse/migrations/encrypt-vault-values-migration";
+import { dataCollector } from "@/lib/platform/common";
+import { getDBConfigByUser } from "@/lib/db-config";
+import prisma from "@/lib/prisma";
+
+describe("EncryptVaultValuesMigration", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (getDBConfigByUser as jest.Mock).mockResolvedValue({ id: "db-1" });
+ (prisma.clickhouseMigrations.findFirst as jest.Mock).mockResolvedValue(null);
+ (prisma.clickhouseMigrations.create as jest.Mock).mockResolvedValue({ id: "migration-1" });
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ id: "secret\\1", value: "plain\\value'secret" }],
+ err: null,
+ })
+ .mockResolvedValueOnce({ err: null });
+ });
+
+ it("escapes backslashes before quotes in generated update queries", async () => {
+ await EncryptVaultValuesMigration();
+
+ expect(dataCollector).toHaveBeenCalledTimes(2);
+ const [{ query }, mode, databaseConfigId] = (dataCollector as jest.Mock).mock.calls[1];
+
+ expect(mode).toBe("exec");
+ expect(databaseConfigId).toBe("db-1");
+ expect(query).toContain("UPDATE value = 'enc:v1:plain\\\\value\\'secret'");
+ expect(query).toContain("WHERE id = 'secret\\\\1'");
+ });
+});
diff --git a/src/client/src/__tests__/helpers/server/platform.test.ts b/src/client/src/__tests__/helpers/server/platform.test.ts
index ecf3a6ec..7ebb4bcf 100644
--- a/src/client/src/__tests__/helpers/server/platform.test.ts
+++ b/src/client/src/__tests__/helpers/server/platform.test.ts
@@ -246,18 +246,31 @@ describe('getFilterWhereCondition', () => {
expect(result).toContain("'production'");
});
- it('adds SpanAttributes custom filter (covers lines 250-252)', () => {
- const result = getFilterWhereCondition(
- {
- timeLimit: { start: new Date('2024-01-01'), end: new Date('2024-01-31') },
- selectedConfig: {
+ it('adds SpanAttributes custom filter (covers lines 250-252)', () => {
+ const result = getFilterWhereCondition(
+ {
+ timeLimit: { start: new Date('2024-01-01'), end: new Date('2024-01-31') },
+ selectedConfig: {
customFilters: [{ attributeType: 'SpanAttributes', key: 'gen_ai.system', value: 'openai' }],
},
} as any,
true
- );
- expect(result).toContain("SpanAttributes['gen_ai.system'] = 'openai'");
- });
+ );
+ expect(result).toContain("SpanAttributes['gen_ai.system'] = 'openai'");
+ });
+
+ it('escapes backslashes before quotes in custom attribute filters', () => {
+ const result = getFilterWhereCondition(
+ {
+ timeLimit: { start: new Date('2024-01-01'), end: new Date('2024-01-31') },
+ selectedConfig: {
+ customFilters: [{ attributeType: 'SpanAttributes', key: "gen\\ai.system", value: "open\\ai's" }],
+ },
+ } as any,
+ true
+ );
+ expect(result).toContain("SpanAttributes['gen\\\\ai.system'] = 'open\\\\ai\\'s'");
+ });
it('adds ResourceAttributes custom filter (covers lines 253-255)', () => {
const result = getFilterWhereCondition(
@@ -325,7 +338,7 @@ describe('getFilterWhereCondition', () => {
} as any,
true
);
- expect(result).toContain("= 'it''s'");
+ expect(result).toContain("= 'it\\'s'");
});
it('adds notOrEmpty conditions', () => {
diff --git a/src/client/src/__tests__/helpers/server/widget.test.ts b/src/client/src/__tests__/helpers/server/widget.test.ts
index 48461d01..fd1607ec 100644
--- a/src/client/src/__tests__/helpers/server/widget.test.ts
+++ b/src/client/src/__tests__/helpers/server/widget.test.ts
@@ -15,8 +15,8 @@ import {
} from '@/helpers/server/widget';
describe('escapeSingleQuotes', () => {
- it('wraps single-quoted substrings in double single-quotes', () => {
- expect(escapeSingleQuotes("hello 'world'")).toBe("hello ''world''");
+ it('escapes single quotes for ClickHouse string literals', () => {
+ expect(escapeSingleQuotes("hello 'world'")).toBe("hello \\'world\\'");
});
it('returns the string unchanged when there are no single quotes', () => {
@@ -28,13 +28,11 @@ describe('escapeSingleQuotes', () => {
});
it('handles multiple quoted substrings', () => {
- expect(escapeSingleQuotes("'foo' and 'bar'")).toBe("''foo'' and ''bar''");
+ expect(escapeSingleQuotes("'foo' and 'bar'")).toBe("\\'foo\\' and \\'bar\\'");
});
- it('doubles already-doubled adjacent single quotes', () => {
- // The regex matches each '' pair and replaces it with ''''
- const input = "it''s fine";
- expect(escapeSingleQuotes(input)).toBe("it''''s fine");
+ it('escapes backslashes before single quotes', () => {
+ expect(escapeSingleQuotes("a\\b'c")).toBe("a\\\\b\\'c");
});
});
diff --git a/src/client/src/__tests__/lib/db-config.test.ts b/src/client/src/__tests__/lib/db-config.test.ts
index 32bd5fd0..6fff6eb3 100644
--- a/src/client/src/__tests__/lib/db-config.test.ts
+++ b/src/client/src/__tests__/lib/db-config.test.ts
@@ -73,7 +73,7 @@ const mockOrg = { id: 'org1', name: 'Test Org' };
const mockDbConfig = {
id: 'db1',
name: 'Test DB',
- host: 'localhost',
+ host: 'clickhouse.example.com',
port: '8123',
username: 'admin',
password: 'pass',
@@ -173,7 +173,7 @@ describe('upsertDBConfig', () => {
const validConfig = {
name: 'My DB',
username: 'admin',
- host: 'localhost',
+ host: 'clickhouse.example.com',
port: '8123',
database: 'default',
};
@@ -413,6 +413,14 @@ describe('shareDBConfig', () => {
});
expect(result[0][1]).toEqual({ success: false });
});
+
+ it('throws when user lacks share permission', async () => {
+ (asaw as jest.Mock).mockResolvedValueOnce([null, { canShare: false }]);
+
+ await expect(
+ shareDBConfig({ id: 'db1', shareArray: [{ email: '[email protected]' }] })
+ ).rejects.toThrow("User doesn't have permission to share the database config");
+ });
});
describe('moveSharedDBConfigToDBUser', () => {
diff --git a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
index 3b6a45bc..3aa5d466 100644
--- a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
+++ b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
@@ -6,6 +6,7 @@ jest.mock('@/lib/prisma', () => ({
findFirst: jest.fn(),
findMany: jest.fn(),
update: jest.fn(),
+ count: jest.fn(),
},
},
}));
@@ -29,7 +30,7 @@ jest.mock('@/constants/messages', () => ({
})),
}));
-import { generateAPIKey, getAPIKeyInfo, getAllAPIKeys, deleteAPIKey } from '@/lib/platform/api-keys/index';
+import { deleteAPIKey, generateAPIKey, getAllAPIKeys, getAPIKeyInfo, hasAnyAPIKeys } from '@/lib/platform/api-keys/index';
import { getCurrentUser } from '@/lib/session';
import { getDBConfigByUser } from '@/lib/db-config';
import asaw from '@/utils/asaw';
@@ -61,6 +62,13 @@ describe('generateAPIKey', () => {
(asaw as jest.Mock).mockResolvedValue([null, null]);
await expect(generateAPIKey('key')).rejects.toThrow('DB config not found');
});
+
+ it('throws when db config lookup fails', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });
+ (asaw as jest.Mock).mockResolvedValue([new Error('lookup failed'), null]);
+
+ await expect(generateAPIKey('key')).rejects.toThrow('lookup failed');
+ });
});
describe('getAPIKeyInfo', () => {
@@ -83,22 +91,83 @@ describe('getAllAPIKeys', () => {
const result = await getAllAPIKeys();
expect(prisma.aPIKeys.findMany).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([{ name: 'key1', apiKey: 'openlit-abc' }]);
});
it('throws when dbConfig is not found', async () => {
(asaw as jest.Mock).mockResolvedValueOnce([null, null]);
await expect(getAllAPIKeys()).rejects.toThrow('DB config not found');
});
+
+ it('throws when db config lookup returns an error', async () => {
+ (asaw as jest.Mock).mockResolvedValueOnce([new Error('db failed'), null]);
+ await expect(getAllAPIKeys()).rejects.toThrow('db failed');
+ });
});
describe('deleteAPIKey', () => {
it('marks API key as deleted', async () => {
- (asaw as jest.Mock).mockResolvedValue([null, {}]);
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });
+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);
+ (prisma.aPIKeys.findFirst as jest.Mock).mockResolvedValue({ id: 'key-id-1' });
(prisma.aPIKeys.update as jest.Mock).mockResolvedValue({});
await deleteAPIKey('key-id-1');
+ expect(prisma.aPIKeys.findFirst).toHaveBeenCalledWith({
+ where: {
+ id: 'key-id-1',
+ databaseConfigId: 'db-1',
+ isDeleted: false,
+ },
+ });
expect(prisma.aPIKeys.update).toHaveBeenCalledWith({
where: { id: 'key-id-1' },
data: { isDeleted: true },
});
});
+
+ it('rejects deleting an API key outside the current db config', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });
+ (asaw as jest.Mock).mockResolvedValue([null, { id: 'db-1' }]);
+ (prisma.aPIKeys.findFirst as jest.Mock).mockResolvedValue(null);
+
+ await expect(deleteAPIKey('key-id-2')).rejects.toThrow('API key not found');
+ expect(prisma.aPIKeys.update).not.toHaveBeenCalled();
+ });
+
+ it('throws when user is not authenticated', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ await expect(deleteAPIKey('key-id-1')).rejects.toThrow('Unauthorized');
+ });
+
+ it('throws when db config lookup fails', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });
+ (asaw as jest.Mock).mockResolvedValue([new Error('db failed'), null]);
+
+ await expect(deleteAPIKey('key-id-1')).rejects.toThrow('db failed');
+ });
+
+ it('throws when dbConfig is not found', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: 'user-1' });
+ (asaw as jest.Mock).mockResolvedValue([null, null]);
+
+ await expect(deleteAPIKey('key-id-1')).rejects.toThrow('DB config not found');
+ });
+});
+
+describe('hasAnyAPIKeys', () => {
+ it('returns true when any non-deleted API key exists', async () => {
+ (prisma.aPIKeys.count as jest.Mock).mockResolvedValue(1);
+
+ await expect(hasAnyAPIKeys()).resolves.toBe(true);
+ expect(prisma.aPIKeys.count).toHaveBeenCalledWith({
+ where: { isDeleted: false },
+ });
+ });
+
+ it('returns false when no non-deleted API keys exist', async () => {
+ (prisma.aPIKeys.count as jest.Mock).mockResolvedValue(0);
+
+ await expect(hasAnyAPIKeys()).resolves.toBe(false);
+ });
});
diff --git a/src/client/src/__tests__/lib/platform/chat/conversation.test.ts b/src/client/src/__tests__/lib/platform/chat/conversation.test.ts
index c4e602a5..0eee2ad9 100644
--- a/src/client/src/__tests__/lib/platform/chat/conversation.test.ts
+++ b/src/client/src/__tests__/lib/platform/chat/conversation.test.ts
@@ -49,6 +49,62 @@ describe('getConversations', () => {
await getConversations('db-1');
expect(dataCollector).toHaveBeenCalledWith(expect.any(Object), 'query', 'db-1');
});
+
+ it('returns errors from dataCollector', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: 'query failed' });
+ await expect(getConversations()).resolves.toEqual({ err: 'query failed' });
+ });
+});
+
+describe('getConversationWithMessages', () => {
+ it('returns a conversation with ordered messages', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ data: [{ id: 'c1', title: 'Chat' }] })
+ .mockResolvedValueOnce({ data: [{ id: 'm1', role: 'user', content: 'Hi' }] });
+
+ const { data } = await getConversationWithMessages('c1', 'db-1');
+
+ expect(data).toEqual({
+ conversation: { id: 'c1', title: 'Chat' },
+ messages: [{ id: 'm1', role: 'user', content: 'Hi' }],
+ });
+ expect(dataCollector).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ query: expect.stringContaining("WHERE id = 'c1'") }),
+ 'query',
+ 'db-1'
+ );
+ expect(dataCollector).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ query: expect.stringContaining("WHERE conversation_id = 'c1'") }),
+ 'query',
+ 'db-1'
+ );
+ });
+
+ it('returns conversation query errors', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: 'conversation failed' });
+ await expect(getConversationWithMessages('c1')).resolves.toEqual({
+ err: 'conversation failed',
+ });
+ });
+
+ it('returns not found when no conversation exists', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [] });
+ await expect(getConversationWithMessages('missing')).resolves.toEqual({
+ err: 'Conversation not found',
+ });
+ });
+
+ it('returns message query errors', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ data: [{ id: 'c1' }] })
+ .mockResolvedValueOnce({ err: 'messages failed' });
+
+ await expect(getConversationWithMessages('c1')).resolves.toEqual({
+ err: 'messages failed',
+ });
+ });
});
describe('createConversation', () => {
@@ -65,6 +121,16 @@ describe('createConversation', () => {
const { err } = await createConversation('Test', 'openai', 'gpt-4');
expect(err).toBe('fail');
});
+
+ it('returns latest select errors after insert succeeds', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ err: null, data: {} })
+ .mockResolvedValueOnce({ err: 'latest failed' });
+
+ await expect(createConversation('Test', 'openai', 'gpt-4')).resolves.toEqual({
+ err: 'latest failed',
+ });
+ });
});
describe('deleteConversation', () => {
@@ -77,6 +143,25 @@ describe('deleteConversation', () => {
const secondCall = (dataCollector as jest.Mock).mock.calls[1][0].query;
expect(secondCall).toContain('openlit_chat_conversation');
});
+
+ it('stops when deleting messages fails', async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({ err: 'message delete failed' });
+
+ await expect(deleteConversation('c1')).resolves.toEqual({
+ err: 'message delete failed',
+ });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns conversation delete errors', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ err: null })
+ .mockResolvedValueOnce({ err: 'conversation delete failed' });
+
+ await expect(deleteConversation('c1')).resolves.toEqual({
+ err: 'conversation delete failed',
+ });
+ });
});
describe('addMessage', () => {
@@ -98,6 +183,46 @@ describe('addMessage', () => {
expect(insertCall[0].values[0].role).toBe('user');
expect(insertCall[0].values[0].prompt_tokens).toBe(10);
});
+
+ it('defaults optional message fields', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ err: null, data: {} })
+ .mockResolvedValueOnce({ data: [] });
+
+ const { data } = await addMessage({
+ conversationId: 'c1',
+ role: 'assistant',
+ content: 'Hello',
+ });
+
+ expect(data).toBeUndefined();
+ expect(dataCollector).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ values: [
+ expect.objectContaining({
+ sql_query: '',
+ query_result: '',
+ widget_type: '',
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ cost: 0,
+ }),
+ ],
+ }),
+ 'insert',
+ undefined
+ );
+ });
+
+ it('returns insert errors', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: 'insert failed' });
+ await expect(addMessage({
+ conversationId: 'c1',
+ role: 'user',
+ content: 'Hello',
+ })).resolves.toEqual({ err: 'insert failed' });
+ });
});
describe('updateMessage', () => {
@@ -110,6 +235,17 @@ describe('updateMessage', () => {
expect(query).toContain('query_rows_read = 5');
});
+ it('updates execution time and bytes read', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: null });
+ await updateMessage('msg-1', {
+ queryExecutionTimeMs: 12,
+ queryBytesRead: 4096,
+ });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain('query_execution_time_ms = 12');
+ expect(query).toContain('query_bytes_read = 4096');
+ });
+
it('skips update when no fields provided', async () => {
await updateMessage('msg-1', {});
expect(dataCollector).not.toHaveBeenCalled();
@@ -156,4 +292,11 @@ describe('getConversationMessages', () => {
const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
expect(query).toContain('LIMIT 5');
});
+
+ it('returns errors from dataCollector', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: 'messages failed' });
+ await expect(getConversationMessages('c1')).resolves.toEqual({
+ err: 'messages failed',
+ });
+ });
});
diff --git a/src/client/src/__tests__/lib/platform/chat/stream.test.ts b/src/client/src/__tests__/lib/platform/chat/stream.test.ts
index 79e9405b..7b27db6c 100644
--- a/src/client/src/__tests__/lib/platform/chat/stream.test.ts
+++ b/src/client/src/__tests__/lib/platform/chat/stream.test.ts
@@ -7,7 +7,7 @@ jest.mock('ai', () => ({
jsonSchema: jest.fn((s: any) => s),
}));
-import { getModelInstance, formatStreamError, buildConversationMessages } from '@/lib/platform/chat/stream';
+import { getModelInstance, formatStreamError, buildConversationMessages, streamChatMessage } from '@/lib/platform/chat/stream';
// Mock external dependencies
jest.mock('@ai-sdk/openai', () => ({
@@ -44,7 +44,16 @@ jest.mock('@/lib/platform/chat/tools', () => ({
getChatTools: jest.fn(() => ({})),
}));
-import { getConversationMessages } from '@/lib/platform/chat/conversation';
+import { streamText, generateText } from 'ai';
+import { dataCollector } from '@/lib/platform/common';
+import { addMessage, getConversationMessages, updateConversation } from '@/lib/platform/chat/conversation';
+import { extractSQLFromResponse, validateSQL } from '@/lib/platform/chat/sql-validator';
+
+async function* streamParts(parts: any[]) {
+ for (const part of parts) {
+ yield part;
+ }
+}
describe('getModelInstance', () => {
it('creates OpenAI model instance', () => {
@@ -164,3 +173,269 @@ describe('buildConversationMessages', () => {
expect(messages).toHaveLength(1);
});
});
+
+describe('streamChatMessage', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (addMessage as jest.Mock).mockResolvedValue({ data: 'msg-id' });
+ (updateConversation as jest.Mock).mockResolvedValue({ err: null });
+ (getConversationMessages as jest.Mock).mockResolvedValue({
+ data: [
+ { role: 'user', content: 'Earlier question' },
+ { role: 'user', content: 'Show traces' },
+ ],
+ });
+ (extractSQLFromResponse as jest.Mock).mockReturnValue([]);
+ (validateSQL as jest.Mock).mockReturnValue({ valid: false });
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });
+ (generateText as jest.Mock).mockResolvedValue({ text: 'Trace Summary' });
+ });
+
+ it('streams text, enriches SQL query results, and saves assistant stats', async () => {
+ const response = 'Here is SQL:\n```sql\nSELECT 1\n```';
+ (extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);
+ (validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ one: 1 }], err: null });
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: response,
+ usage: { inputTokens: 100, outputTokens: 20 },
+ steps: [],
+ });
+ return {
+ fullStream: streamParts([
+ { type: 'text-delta', text: 'Here is SQL:\n' },
+ { type: 'text-delta', text: '```sql\nSELECT 1\n```' },
+ ]),
+ };
+ });
+
+ const result = await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Show traces',
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ expect(result.streamError).toBeNull();
+ expect(result.responseText).toContain('```query-result');
+ expect(result.responseText).toContain('"one":1');
+ expect(dataCollector).toHaveBeenCalledWith({
+ query: 'SELECT 1',
+ enable_readonly: true,
+ });
+ expect(updateConversation).toHaveBeenCalledWith('c1', {
+ addPromptTokens: 100,
+ addCompletionTokens: 20,
+ addCost: 0.0006,
+ incrementMessages: true,
+ });
+ expect(addMessage).toHaveBeenLastCalledWith({
+ conversationId: 'c1',
+ role: 'assistant',
+ content: expect.stringContaining('```query-result'),
+ promptTokens: 100,
+ completionTokens: 20,
+ cost: 0.0006,
+ });
+ });
+
+ it('saves a sanitized error response when streaming fails before text arrives', async () => {
+ (streamText as jest.Mock).mockImplementation(({ onError }) => {
+ onError({ error: { statusCode: 401 } });
+ return { fullStream: streamParts([]) };
+ });
+
+ const result = await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Hello',
+ provider: 'openai',
+ apiKey: 'bad-key',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ expect(result.responseText).toContain('Invalid API key');
+ expect(addMessage).toHaveBeenLastCalledWith({
+ conversationId: 'c1',
+ role: 'assistant',
+ content: expect.stringContaining('Invalid API key'),
+ });
+ });
+
+ it('uses tool-result fallback content when no text deltas are streamed', async () => {
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: '',
+ usage: { inputTokens: 0, outputTokens: 0 },
+ steps: [],
+ });
+ return {
+ fullStream: streamParts([
+ {
+ type: 'tool-result',
+ result: { success: true, message: 'Secret stored', details: 'Key: API_KEY' },
+ },
+ ]),
+ };
+ });
+
+ const result = await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Store secret',
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ expect(result.responseText).toContain('**Secret stored**');
+ expect(result.responseText).toContain('Key: API_KEY');
+ });
+
+ it('generates a title for the first message using onFinish tool summaries', async () => {
+ (getConversationMessages as jest.Mock).mockResolvedValue({
+ data: [{ role: 'user', content: 'Create a rule' }],
+ });
+ (generateText as jest.Mock).mockResolvedValue({ text: '"Rule Created"' });
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: '',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ steps: [
+ {
+ toolResults: [
+ { result: { success: true, message: 'Rule created', details: 'ID: rule-1' } },
+ { result: { success: false, error: 'secondary warning' } },
+ ],
+ },
+ ],
+ });
+ return {
+ fullStream: streamParts([
+ {
+ type: 'tool-result',
+ result: { success: true, message: 'Rule created', details: 'ID: rule-1' },
+ },
+ ]),
+ };
+ });
+
+ await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Create a rule',
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(generateText).toHaveBeenCalledWith(
+ expect.objectContaining({
+ prompt: expect.stringContaining('Rule created'),
+ maxOutputTokens: 20,
+ })
+ );
+ expect(updateConversation).toHaveBeenCalledWith('c1', {
+ title: 'Rule Created',
+ });
+ });
+
+ it('falls back to a truncated title when title generation fails', async () => {
+ const longPrompt = 'Explain the longest running trace in the current project';
+ (getConversationMessages as jest.Mock).mockResolvedValue({
+ data: [{ role: 'user', content: longPrompt }],
+ });
+ (generateText as jest.Mock).mockRejectedValue(new Error('title failed'));
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: 'Trace analysis',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ steps: [],
+ });
+ return {
+ fullStream: streamParts([{ type: 'text-delta', text: 'Trace analysis' }]),
+ };
+ });
+
+ await streamChatMessage({
+ conversationId: 'c1',
+ content: longPrompt,
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(updateConversation).toHaveBeenCalledWith('c1', {
+ title: `${longPrompt.slice(0, 50)}...`,
+ });
+ });
+
+ it('appends query results when a SQL block cannot be replaced exactly', async () => {
+ (extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);
+ (validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ one: 1 }], err: null });
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: 'Run SELECT 1',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ steps: [],
+ });
+ return {
+ fullStream: streamParts([{ type: 'text-delta', text: 'Run SELECT 1' }]),
+ };
+ });
+
+ const result = await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Run SQL',
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ expect(result.responseText).toBe('Run SELECT 1\n\n```query-result\n[{"one":1}]\n```');
+ });
+
+ it('continues when SQL execution throws', async () => {
+ (extractSQLFromResponse as jest.Mock).mockReturnValue(['SELECT 1']);
+ (validateSQL as jest.Mock).mockReturnValue({ valid: true, query: 'SELECT 1' });
+ (dataCollector as jest.Mock).mockRejectedValue(new Error('db unavailable'));
+ (streamText as jest.Mock).mockImplementation(({ onFinish }) => {
+ onFinish({
+ text: '```sql\nSELECT 1\n```',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ steps: [],
+ });
+ return {
+ fullStream: streamParts([{ type: 'text-delta', text: '```sql\nSELECT 1\n```' }]),
+ };
+ });
+
+ const result = await streamChatMessage({
+ conversationId: 'c1',
+ content: 'Run SQL',
+ provider: 'openai',
+ apiKey: 'sk-test',
+ model: 'gpt-4o',
+ userId: 'u1',
+ dbConfigId: 'db1',
+ });
+
+ expect(result.responseText).toBe('```sql\nSELECT 1\n```');
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/chat/table-details.test.ts b/src/client/src/__tests__/lib/platform/chat/table-details.test.ts
new file mode 100644
index 00000000..ec97d2c4
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/chat/table-details.test.ts
@@ -0,0 +1,13 @@
+import {
+ OPENLIT_CHAT_CONFIG_TABLE,
+ OPENLIT_CHAT_CONVERSATION_TABLE,
+ OPENLIT_CHAT_MESSAGE_TABLE,
+} from "@/lib/platform/chat/table-details";
+
+describe("chat table details", () => {
+ it("exports chat table names", () => {
+ expect(OPENLIT_CHAT_CONFIG_TABLE).toBe("openlit_chat_config");
+ expect(OPENLIT_CHAT_CONVERSATION_TABLE).toBe("openlit_chat_conversation");
+ expect(OPENLIT_CHAT_MESSAGE_TABLE).toBe("openlit_chat_message");
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/chat/tools.test.ts b/src/client/src/__tests__/lib/platform/chat/tools.test.ts
new file mode 100644
index 00000000..825ddf33
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/chat/tools.test.ts
@@ -0,0 +1,454 @@
+jest.mock("ai", () => ({
+ tool: jest.fn((config) => config),
+ jsonSchema: jest.fn((schema) => schema),
+}));
+
+jest.mock("@/lib/platform/rule-engine", () => ({
+ createRule: jest.fn(),
+ updateRule: jest.fn(),
+ deleteRule: jest.fn(),
+ getRules: jest.fn(),
+ getRuleById: jest.fn(),
+ addConditionGroupsToRule: jest.fn(),
+ addRuleEntity: jest.fn(),
+ deleteRuleEntity: jest.fn(),
+ getRuleEntities: jest.fn(),
+}));
+
+jest.mock("@/lib/platform/context", () => ({
+ createContext: jest.fn(),
+ updateContext: jest.fn(),
+ deleteContext: jest.fn(),
+ getContexts: jest.fn(),
+}));
+
+jest.mock("@/lib/platform/prompt", () => ({
+ createPrompt: jest.fn(),
+ getPrompts: jest.fn(),
+ deletePrompt: jest.fn(),
+}));
+
+jest.mock("@/lib/platform/prompt/version", () => ({
+ upsertPromptVersion: jest.fn(),
+}));
+
+jest.mock("@/lib/platform/vault", () => ({
+ upsertSecret: jest.fn(),
+ deleteSecret: jest.fn(),
+ getSecrets: jest.fn(),
+}));
+
+jest.mock("@/lib/platform/providers/models-service", () => ({
+ createCustomModel: jest.fn(),
+ updateCustomModel: jest.fn(),
+ deleteCustomModel: jest.fn(),
+ getCustomModels: jest.fn(),
+}));
+
+import { getChatTools } from "@/lib/platform/chat/tools";
+import {
+ addRuleEntity,
+ createRule,
+ deleteRule,
+ deleteRuleEntity,
+ getRuleById,
+ getRuleEntities,
+ getRules,
+ updateRule,
+} from "@/lib/platform/rule-engine";
+import {
+ createContext,
+ deleteContext,
+ getContexts,
+ updateContext,
+} from "@/lib/platform/context";
+import { createPrompt, deletePrompt, getPrompts } from "@/lib/platform/prompt";
+import { upsertPromptVersion } from "@/lib/platform/prompt/version";
+import { deleteSecret, getSecrets, upsertSecret } from "@/lib/platform/vault";
+import {
+ createCustomModel,
+ deleteCustomModel,
+ getCustomModels,
+ updateCustomModel,
+} from "@/lib/platform/providers/models-service";
+
+describe("getChatTools", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("builds the expected tool set", () => {
+ const tools = getChatTools("user-1", "db-1");
+
+ expect(Object.keys(tools)).toEqual(
+ expect.arrayContaining([
+ "create_rule",
+ "list_rules",
+ "create_context",
+ "create_prompt",
+ "create_vault_secret",
+ "create_custom_model",
+ "list_custom_models",
+ ])
+ );
+ expect(tools.create_rule.inputSchema.required).toEqual(["name"]);
+ expect(tools.create_vault_secret.inputSchema.required).toEqual([
+ "key",
+ "value",
+ ]);
+ });
+
+ it("creates a rule and adds condition groups when provided", async () => {
+ (createRule as jest.Mock).mockResolvedValue({ id: "rule-1" });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.create_rule.execute({
+ name: "Latency rule",
+ condition_groups: [{ conditions: [] }],
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ success: true,
+ message: "Rule created",
+ })
+ );
+ expect(createRule).toHaveBeenCalledWith({
+ name: "Latency rule",
+ description: "",
+ group_operator: "AND",
+ status: "ACTIVE",
+ });
+ });
+
+ it("returns rule operation errors without throwing", async () => {
+ (deleteRule as jest.Mock).mockResolvedValue(["delete failed"]);
+ (getRules as jest.Mock).mockResolvedValue({ err: "list failed" });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(tools.delete_rule.execute({ id: "rule-1" })).resolves.toEqual({
+ success: false,
+ error: "delete failed",
+ });
+ await expect(tools.list_rules.execute({})).resolves.toEqual({
+ success: false,
+ error: "list failed",
+ });
+ });
+
+ it("normalizes vault keys before storing secrets", async () => {
+ (upsertSecret as jest.Mock).mockResolvedValue(undefined);
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.create_vault_secret.execute({
+ key: "OpenAI API.key",
+ value: "sk-test",
+ tags: ["llm"],
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ success: true,
+ details: expect.stringContaining('Key: "OPEN_AI_API_KEY"'),
+ })
+ );
+ expect(upsertSecret).toHaveBeenCalledWith({
+ key: "OPEN_AI_API_KEY",
+ value: "sk-test",
+ tags: ["llm"],
+ });
+ });
+
+ it("passes user and database config ids to custom model operations", async () => {
+ (createCustomModel as jest.Mock).mockResolvedValue({
+ data: { id: "model-1" },
+ });
+ (getCustomModels as jest.Mock).mockResolvedValue({
+ data: [{ id: "model-1", model_id: "custom-model", provider: "openai" }],
+ });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.create_custom_model.execute({
+ provider: "openai",
+ model_id: "custom-model",
+ display_name: "Custom Model",
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ success: true,
+ id: "model-1",
+ })
+ );
+ expect(createCustomModel).toHaveBeenCalledWith(
+ "user-1",
+ "db-1",
+ expect.objectContaining({
+ provider: "openai",
+ model_id: "custom-model",
+ displayName: "Custom Model",
+ modelType: "chat",
+ contextWindow: 4096,
+ })
+ );
+
+ await expect(
+ tools.list_custom_models.execute({ provider: "openai" })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ success: true,
+ count: 1,
+ })
+ );
+ expect(getCustomModels).toHaveBeenCalledWith("user-1", "db-1", "openai");
+ });
+
+ it("executes rule read, update, link, unlink, and list entity tools", async () => {
+ (updateRule as jest.Mock).mockResolvedValue(undefined);
+ (getRuleById as jest.Mock).mockResolvedValue({ data: { id: "rule-1" } });
+ (addRuleEntity as jest.Mock).mockResolvedValue(undefined);
+ (deleteRuleEntity as jest.Mock).mockResolvedValue([null]);
+ (getRuleEntities as jest.Mock).mockResolvedValue({
+ data: [{ id: "entity-1" }],
+ err: null,
+ });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.update_rule.execute({ id: "rule-1", name: "Updated" })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(tools.get_rule.execute({ id: "rule-1" })).resolves.toEqual({
+ success: true,
+ rule: { id: "rule-1" },
+ });
+ await expect(
+ tools.link_entity_to_rule.execute({
+ rule_id: "rule-1",
+ entity_type: "context",
+ entity_id: "ctx-1",
+ })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(
+ tools.unlink_entity_from_rule.execute({ id: "link-1" })
+ ).resolves.toEqual({ success: true, message: "Entity unlinked from rule" });
+ await expect(
+ tools.list_rule_entities.execute({ rule_id: "rule-1" })
+ ).resolves.toEqual({
+ success: true,
+ entities: [{ id: "entity-1" }],
+ });
+
+ expect(updateRule).toHaveBeenCalledWith("rule-1", {
+ name: "Updated",
+ description: undefined,
+ group_operator: undefined,
+ status: undefined,
+ });
+ expect(addRuleEntity).toHaveBeenCalledWith({
+ rule_id: "rule-1",
+ entity_type: "context",
+ entity_id: "ctx-1",
+ });
+ });
+
+ it("executes context tools and serializes tags", async () => {
+ (createContext as jest.Mock).mockResolvedValue({ id: "ctx-1" });
+ (updateContext as jest.Mock).mockResolvedValue(undefined);
+ (deleteContext as jest.Mock).mockResolvedValue([null]);
+ (getContexts as jest.Mock).mockResolvedValue({
+ data: [{ id: "ctx-1", name: "Policy", status: "ACTIVE" }],
+ err: null,
+ });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.create_context.execute({
+ name: "Policy",
+ content: "Use policy",
+ tags: ["security"],
+ })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(
+ tools.update_context.execute({
+ id: "ctx-1",
+ description: "",
+ tags: ["security", "prod"],
+ })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(tools.delete_context.execute({ id: "ctx-1" })).resolves.toEqual({
+ success: true,
+ message: "Context deleted",
+ });
+ await expect(tools.list_contexts.execute({})).resolves.toEqual({
+ success: true,
+ count: 1,
+ contexts: [
+ {
+ id: "ctx-1",
+ name: "Policy",
+ status: "ACTIVE",
+ description: undefined,
+ },
+ ],
+ });
+
+ expect(createContext).toHaveBeenCalledWith(
+ expect.objectContaining({ tags: '["security"]' })
+ );
+ expect(updateContext).toHaveBeenCalledWith("ctx-1", {
+ description: "",
+ tags: '["security","prod"]',
+ });
+ });
+
+ it("executes prompt tools", async () => {
+ (createPrompt as jest.Mock).mockResolvedValue({
+ data: { promptId: "prompt-1" },
+ });
+ (upsertPromptVersion as jest.Mock).mockResolvedValue(undefined);
+ (deletePrompt as jest.Mock).mockResolvedValue([null]);
+ (getPrompts as jest.Mock).mockResolvedValue({
+ data: [{ id: "prompt-1", name: "Prompt", totalVersions: 2 }],
+ err: null,
+ });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.create_prompt.execute({ name: "Prompt", prompt: "Hello {{name}}" })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(
+ tools.update_prompt_version.execute({
+ prompt_id: "prompt-1",
+ version_id: "version-1",
+ version: "2.0.0",
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({
+ success: true,
+ message: "Prompt version updated",
+ })
+ );
+ await expect(tools.delete_prompt.execute({ id: "prompt-1" })).resolves.toEqual({
+ success: true,
+ message: "Prompt deleted",
+ });
+ await expect(tools.list_prompts.execute({})).resolves.toEqual({
+ success: true,
+ count: 1,
+ prompts: [
+ {
+ id: "prompt-1",
+ name: "Prompt",
+ totalVersions: 2,
+ latestVersion: undefined,
+ },
+ ],
+ });
+ expect(createPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ version: "1.0.0",
+ status: "DRAFT",
+ metaProperties: {},
+ })
+ );
+ });
+
+ it("executes vault update, delete, and list tools", async () => {
+ (upsertSecret as jest.Mock).mockResolvedValue(undefined);
+ (deleteSecret as jest.Mock).mockResolvedValue([null]);
+ (getSecrets as jest.Mock).mockResolvedValue({
+ data: [{ id: "secret-1", key: "API_KEY", tags: ["llm"] }],
+ err: null,
+ });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.update_vault_secret.execute({
+ id: "secret-1",
+ key: "Api Key",
+ value: "secret",
+ tags: ["llm"],
+ })
+ ).resolves.toEqual(expect.objectContaining({ success: true }));
+ await expect(
+ tools.delete_vault_secret.execute({ id: "secret-1" })
+ ).resolves.toEqual({ success: true, message: "Secret deleted" });
+ await expect(tools.list_vault_secrets.execute({})).resolves.toEqual({
+ success: true,
+ count: 1,
+ secrets: [
+ {
+ id: "secret-1",
+ key: "API_KEY",
+ tags: ["llm"],
+ created_at: undefined,
+ },
+ ],
+ });
+ expect(upsertSecret).toHaveBeenCalledWith({
+ id: "secret-1",
+ key: "API_KEY",
+ value: "secret",
+ tags: ["llm"],
+ });
+ });
+
+ it("executes custom model update and delete tools", async () => {
+ (updateCustomModel as jest.Mock).mockResolvedValue({ err: null });
+ (deleteCustomModel as jest.Mock).mockResolvedValue({ err: null });
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(
+ tools.update_custom_model.execute({
+ id: "model-1",
+ display_name: "Updated Model",
+ context_window: 8192,
+ input_price_per_m_tokens: 1.5,
+ output_price_per_m_tokens: 2.5,
+ capabilities: ["chat"],
+ })
+ ).resolves.toEqual(
+ expect.objectContaining({ success: true, id: "model-1" })
+ );
+ await expect(
+ tools.delete_custom_model.execute({ id: "model-1" })
+ ).resolves.toEqual({ success: true, message: "Model deleted" });
+ expect(updateCustomModel).toHaveBeenCalledWith("user-1", "db-1", "model-1", {
+ displayName: "Updated Model",
+ contextWindow: 8192,
+ inputPricePerMToken: 1.5,
+ outputPricePerMToken: 2.5,
+ capabilities: ["chat"],
+ });
+ });
+
+ it("returns caught errors from representative tools", async () => {
+ (updateRule as jest.Mock).mockRejectedValue(new Error("update failed"));
+ (createContext as jest.Mock).mockRejectedValue(new Error("context failed"));
+ (createPrompt as jest.Mock).mockRejectedValue(new Error("prompt failed"));
+ (upsertSecret as jest.Mock).mockRejectedValue(new Error("secret failed"));
+ (createCustomModel as jest.Mock).mockRejectedValue(new Error("model failed"));
+ const tools = getChatTools("user-1", "db-1");
+
+ await expect(tools.update_rule.execute({ id: "rule-1" })).resolves.toEqual({
+ success: false,
+ error: "update failed",
+ });
+ await expect(
+ tools.create_context.execute({ name: "Ctx", content: "Body" })
+ ).resolves.toEqual({ success: false, error: "context failed" });
+ await expect(
+ tools.create_prompt.execute({ name: "Prompt", prompt: "Hi" })
+ ).resolves.toEqual({ success: false, error: "prompt failed" });
+ await expect(
+ tools.create_vault_secret.execute({ key: "Key", value: "secret" })
+ ).resolves.toEqual({ success: false, error: "secret failed" });
+ await expect(
+ tools.create_custom_model.execute({
+ provider: "openai",
+ model_id: "m",
+ display_name: "Model",
+ })
+ ).resolves.toEqual({ success: false, error: "model failed" });
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts b/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts
new file mode 100644
index 00000000..7b27edea
--- /dev/null
+++ b/src/client/src/__tests__/lib/platform/manage-dashboard/widget.test.ts
@@ -0,0 +1,147 @@
+jest.mock("@/lib/platform/common", () => ({
+ dataCollector: jest.fn(),
+}));
+jest.mock("@/lib/platform/manage-dashboard/table-details", () => ({
+ OPENLIT_WIDGET_TABLE_NAME: "openlit_widgets",
+ OPENLIT_BOARD_WIDGET_TABLE_NAME: "openlit_board_widgets",
+}));
+jest.mock("@/constants/messages", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ WIDGET_FETCH_FAILED: "Widget fetch failed",
+ WIDGET_RUN_FAILED: "Widget run failed",
+ })),
+}));
+jest.mock("@/utils/sanitizer", () => ({
+ __esModule: true,
+ default: {
+ sanitizeValue: jest.fn((value: string) => value),
+ },
+}));
+jest.mock("@/helpers/server/widget", () => {
+ const escapeClickHouseTestString = (value: string) =>
+ JSON.stringify(value).slice(1, -1).split("'").join("\\'");
+
+ return {
+ normalizeWidgetToClient: jest.fn((widget: any) => ({
+ ...widget,
+ config:
+ typeof widget?.config === "string"
+ ? JSON.parse(widget.config)
+ : widget?.config,
+ })),
+ sanitizeWidget: jest.fn((widget: any) => widget),
+ escapeSingleQuotes: jest.fn(escapeClickHouseTestString),
+ };
+});
+
+import { runWidgetQuery } from "@/lib/platform/manage-dashboard/widget";
+import { dataCollector } from "@/lib/platform/common";
+import { escapeSingleQuotes } from "@/helpers/server/widget";
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [], err: null });
+});
+
+describe("runWidgetQuery", () => {
+ it("blocks non-SELECT user queries", async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "DROP TABLE otel_traces",
+ filter: {} as any,
+ });
+
+ expect(result).toEqual({ err: "Only SELECT queries are allowed" });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it("blocks dangerous ClickHouse functions in user queries", async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "SELECT * FROM url('https://example.com')",
+ filter: {} as any,
+ });
+
+ expect(result).toEqual({ err: "Query contains disallowed functions" });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects system table names injected through Mustache filter values', async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "SELECT * FROM {{filter.tbl}}",
+ filter: { tbl: "system.users" } as any,
+ });
+
+ expect(result).toEqual({ err: "Access to system tables is not allowed" });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects information_schema table access", async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "SELECT * FROM information_schema.schemata",
+ filter: {} as any,
+ });
+
+ expect(result).toEqual({
+ err: "Access to information_schema tables is not allowed",
+ });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it("validates the rendered query after Mustache expansion", async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "SELECT * FROM {{filter.prefix}}{{filter.suffix}}",
+ filter: { prefix: "syst", suffix: "em.users" } as any,
+ });
+
+ expect(result).toEqual({ err: "Access to system tables is not allowed" });
+ expect(dataCollector).toHaveBeenCalledTimes(1);
+ });
+
+ it("runs allowed SELECT user queries in readonly mode", async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({
+ data: [{ id: "w1", config: JSON.stringify({ query: "SELECT 1" }) }],
+ err: null,
+ })
+ .mockResolvedValueOnce({ data: [{ count: 1 }], err: null });
+
+ const result = await runWidgetQuery("w1", {
+ userQuery: "SELECT count() FROM otel_traces",
+ filter: {} as any,
+ });
+
+ expect(result).toEqual({ data: [{ count: 1 }] });
+ expect(dataCollector).toHaveBeenLastCalledWith(
+ { query: "SELECT count() FROM otel_traces", enable_readonly: true }
+ );
+ });
+
+ it("mock escapeSingleQuotes escapes backslashes before quotes", () => {
+ expect(escapeSingleQuotes("a\\b'c")).toBe("a\\\\b\\'c");
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.ts
index 4c3896a8..b82e98b4 100644
--- a/src/client/src/__tests__/lib/platform/request/request.test.ts
+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts
@@ -4,6 +4,7 @@ jest.mock('@/lib/platform/common', () => ({
}));
import {
+ getGroupByExpression,
getRequestPerTime,
getTotalRequests,
getAverageRequestDuration,
@@ -187,6 +188,27 @@ describe('getHeirarchyViaSpanId', () => {
expect(dataCollector).toHaveBeenCalledTimes(2);
expect(result.err).toBeTruthy();
});
+
+ it('returns error when trace id is missing from the span row', async () => {
+ (dataCollector as jest.Mock).mockResolvedValueOnce({ data: [{}], err: null });
+
+ const result = await getHeirarchyViaSpanId('span-1');
+
+ expect(result).toEqual({ err: 'TraceId not found for span', record: {} });
+ });
+
+ it('returns error when hierarchy cannot be built', async () => {
+ (dataCollector as jest.Mock)
+ .mockResolvedValueOnce({ data: [{ TraceId: 't1' }], err: null })
+ .mockResolvedValueOnce({
+ data: [{ SpanId: 'orphan', ParentSpanId: 'missing-parent', TraceId: 't1' }],
+ err: null,
+ });
+
+ const result = await getHeirarchyViaSpanId('orphan');
+
+ expect(result).toEqual({ err: 'Error building hierarchy', record: {} });
+ });
});
describe('getRequestExist', () => {
@@ -244,6 +266,18 @@ describe('getAttributeKeys', () => {
});
describe('getGroupedRequests', () => {
+ it('returns predefined and attribute group expressions', () => {
+ expect(getGroupByExpression('model')).toBe("SpanAttributes['gen_ai.request.model']");
+ expect(getGroupByExpression('provider')).toBe("SpanAttributes['gen_ai.system']");
+ expect(getGroupByExpression('applicationName')).toBe("ResourceAttributes['service.name']");
+ expect(getGroupByExpression('custom.attribute')).toBe("SpanAttributes['custom.attribute']");
+ expect(getGroupByExpression('ResourceAttributes:service.namespace')).toBe(
+ "ResourceAttributes['service.namespace']"
+ );
+ expect(getGroupByExpression('')).toBeNull();
+ expect(getGroupByExpression('Field:NotAllowed')).toBeNull();
+ });
+
it('returns an error and skips querying for an invalid Field groupBy', async () => {
const result = await getGroupedRequests(baseParams as any, 'Field:!!!');
@@ -261,4 +295,13 @@ describe('getGroupedRequests', () => {
const { query } = (dataCollector as jest.Mock).mock.calls[0][0];
expect(query).toContain('SpanName AS group_value');
});
+
+ it('escapes backslashes before quotes in attribute groupBy values', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ data: [{ group_value: 'ok' }], err: null });
+
+ await getGroupedRequests(baseParams as any, "SpanAttributes:gen\\ai.system's");
+
+ const { query } = (dataCollector as jest.Mock).mock.calls[0][0];
+ expect(query).toContain("SpanAttributes['gen\\\\ai.system\\'s'] AS group_value");
+ });
});
diff --git a/src/client/src/__tests__/lib/platform/vault/vault.test.ts b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
index bfab80e2..ed72180c 100644
--- a/src/client/src/__tests__/lib/platform/vault/vault.test.ts
+++ b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
@@ -42,6 +42,11 @@ jest.mock('@/utils/json', () => ({
jest.mock('@/lib/platform/api-keys', () => ({
getAPIKeyInfo: jest.fn(),
}));
+jest.mock('@/utils/crypto', () => ({
+ encryptValue: jest.fn((value: string) => `enc:v1:${value}`),
+ decryptValue: jest.fn((value: string) => value.replace(/^enc:v1:/, '')),
+ isEncrypted: jest.fn((value: string) => value.startsWith('enc:v1:')),
+}));
import { getSecretByName, checkNameValidity, deleteSecret, getSecrets, getSecretById, upsertSecret, getSecretsFromDatabaseId } from '@/lib/platform/vault/index';
import { dataCollector } from '@/lib/platform/common';
@@ -90,11 +95,12 @@ describe('deleteSecret', () => {
(dataCollector as jest.Mock).mockResolvedValue({ err: null });
const result = await deleteSecret('secret-id-1');
expect(dataCollector).toHaveBeenCalledTimes(1);
- const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
- expect(query).toContain('DELETE FROM');
- expect(query).toContain('secret-id-1');
- expect(result[0]).toBeUndefined(); // no error
- });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain('DELETE FROM');
+ expect(query).toContain('secret-id-1');
+ expect(query).toContain("created_by = '[email protected]'");
+ expect(result[0]).toBeUndefined(); // no error
+ });
it('throws when user is not authenticated', async () => {
(getCurrentUser as jest.Mock).mockResolvedValue(null);
@@ -112,16 +118,23 @@ describe('getSecrets', () => {
it('calls dataCollector with SELECT query', async () => {
await getSecrets({});
expect(dataCollector).toHaveBeenCalledTimes(1);
- const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
- expect(query).toContain('SELECT');
- expect(query).toContain('openlit_vault');
- });
-
- it('adds WHERE clause when key filter is provided', async () => {
- await getSecrets({ key: 'my-key' });
- const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
- expect(query).toContain("v.key = 'my-key'");
- });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain('SELECT');
+ expect(query).toContain('openlit_vault');
+ expect(query).toContain("v.created_by = '[email protected]'");
+ });
+
+ it('adds WHERE clause when key filter is provided', async () => {
+ await getSecrets({ key: 'my-key' });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain("v.key = 'my-key'");
+ });
+
+ it('escapes backslashes before quotes in key filters', async () => {
+ await getSecrets({ key: "a\\b'c" });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain("v.key = 'a\\\\b\\'c'");
+ });
it('adds hasAny tags filter when tags are provided (covers lines 133-135)', async () => {
await getSecrets({ tags: ['tagA', 'tagB'] });
@@ -148,11 +161,17 @@ describe('getSecrets', () => {
await expect(getSecrets({ key: 'my-key' })).rejects.toThrow('Unauthorized');
});
- it('bypasses auth check when databaseConfigId is provided', async () => {
- await expect(getSecrets({ databaseConfigId: 'db-1' })).resolves.toBeDefined();
- expect(getCurrentUser).not.toHaveBeenCalled();
- });
-});
+ it('bypasses auth check when databaseConfigId is provided', async () => {
+ await expect(getSecrets({ databaseConfigId: 'db-1' })).resolves.toBeDefined();
+ expect(getCurrentUser).not.toHaveBeenCalled();
+ });
+
+ it('does not add session ownership filters for databaseConfigId API-key reads', async () => {
+ await getSecrets({ databaseConfigId: 'db-1' });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).not.toContain('created_by');
+ });
+ });
describe('getSecretById', () => {
it('calls dataCollector with id filter', async () => {
@@ -185,7 +204,7 @@ describe('upsertSecret', () => {
const [insertParams, insertMode] = (dataCollector as jest.Mock).mock.calls[1];
expect(insertMode).toBe('insert');
expect(insertParams.table).toBe('openlit_vault');
- expect(insertParams.values[0]).toMatchObject({ key: 'MY_SECRET', value: 'abc123' });
+ expect(insertParams.values[0]).toMatchObject({ key: 'MY_SECRET', value: 'enc:v1:abc123' });
expect(result).toEqual({ data: {}, message: 'Secret saved!' });
});
@@ -243,25 +262,33 @@ describe('upsertSecret', () => {
expect(dataCollector).toHaveBeenCalledTimes(1);
const [{ query }, mode] = (dataCollector as jest.Mock).mock.calls[0];
expect(mode).toBe('exec');
- expect(query).toContain('ALTER TABLE');
- expect(query).toContain('openlit_vault');
- expect(query).toContain("WHERE id = 'secret-id-1'");
- expect(query).toContain("updated_by = '[email protected]'");
- expect(result).toBe('Secret saved!');
- });
-
- it('includes key in UPDATE set clause when key is provided', async () => {
- (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });
- await upsertSecret({ id: 'sid', key: 'UPDATED_KEY' });
- const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
- expect(query).toContain("key = 'UPDATED_KEY'");
- });
+ expect(query).toContain('ALTER TABLE');
+ expect(query).toContain('openlit_vault');
+ expect(query).toContain("WHERE id = 'secret-id-1' AND created_by = '[email protected]'");
+ expect(query).toContain("updated_by = '[email protected]'");
+ expect(result).toBe('Secret saved!');
+ });
+
+ it('includes key in UPDATE set clause when key is provided', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });
+ await upsertSecret({ id: 'sid', key: 'UPDATED_KEY' });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain("key = 'UPDATED_KEY'");
+ });
+
+ it('escapes backslashes before quotes in UPDATE set values', async () => {
+ (dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });
+ await upsertSecret({ id: "sid\\1", key: "a\\b'c" });
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain("key = 'a\\\\b\\'c'");
+ expect(query).toContain("WHERE id = 'sid\\\\1'");
+ });
it('includes value in UPDATE set clause when value is provided', async () => {
(dataCollector as jest.Mock).mockResolvedValue({ err: null, data: { query_id: 'qid-1' } });
await upsertSecret({ id: 'sid', value: 'new-value' });
const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
- expect(query).toContain("value = 'new-value'");
+ expect(query).toContain("value = 'enc:v1:new-value'");
});
it('includes tags in UPDATE set clause when tags are provided', async () => {
diff --git a/src/client/src/__tests__/lib/user.test.ts b/src/client/src/__tests__/lib/user.test.ts
index d9bde51d..d95f4262 100644
--- a/src/client/src/__tests__/lib/user.test.ts
+++ b/src/client/src/__tests__/lib/user.test.ts
@@ -63,7 +63,7 @@ describe('getUserByEmail', () => {
it('throws when user not found', async () => {
(prisma.user.findUnique as jest.Mock).mockResolvedValue(null);
await expect(getUserByEmail({ email: '[email protected]' })).rejects.toThrow(
- 'No user with this email exists'
+ 'Invalid email or password'
);
});
@@ -108,7 +108,7 @@ describe('createNewUser', () => {
const createdUser = { id: 'u1', email: '[email protected]', password: 'hashed' };
(prisma.user.create as jest.Mock).mockResolvedValue(createdUser);
- const result = await createNewUser({ email: '[email protected]', password: 'pass123' });
+ const result = await createNewUser({ email: '[email protected]', password: 'Pass1234' });
expect(prisma.user.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
@@ -123,17 +123,27 @@ describe('createNewUser', () => {
it('throws when user already exists', async () => {
(asaw as jest.Mock).mockResolvedValue([null, { id: 'u1', email: '[email protected]' }]);
await expect(
- createNewUser({ email: '[email protected]', password: 'pass' })
+ createNewUser({ email: '[email protected]', password: 'Pass1234' })
).rejects.toThrow('User already exists');
});
it('throws when prisma.user.create returns no id', async () => {
(asaw as jest.Mock).mockResolvedValue([null, null]);
(prisma.user.create as jest.Mock).mockResolvedValue({ id: null });
- await expect(createNewUser({ email: '[email protected]', password: 'pass' })).rejects.toThrow(
+ await expect(createNewUser({ email: '[email protected]', password: 'Pass1234' })).rejects.toThrow(
'Cannot create a user!'
);
});
+
+ it('rejects HTML/script-bearing registration email before storing it', async () => {
+ await expect(
+ createNewUser({
+ email: '"><img src=x onerror=alert(1)>@test.com',
+ password: 'Pass1234',
+ })
+ ).rejects.toThrow('Email contains invalid characters');
+ expect(prisma.user.create).not.toHaveBeenCalled();
+ });
});
describe('updateUser', () => {
@@ -179,7 +189,7 @@ describe('updateUserProfile', () => {
(compare as jest.Mock).mockResolvedValue(true);
(prisma.user.update as jest.Mock).mockResolvedValue({ id: 'u1' });
- await updateUserProfile({ currentPassword: 'old', newPassword: 'new' });
+ await updateUserProfile({ currentPassword: 'old', newPassword: 'Newpass1' });
expect(prisma.user.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ password: expect.any(String) }) })
);
@@ -190,7 +200,7 @@ describe('updateUserProfile', () => {
(compare as jest.Mock).mockResolvedValue(false);
await expect(
- updateUserProfile({ currentPassword: 'wrong', newPassword: 'new' })
+ updateUserProfile({ currentPassword: 'wrong', newPassword: 'Newpass1' })
).rejects.toThrow('Wrong current password!');
});
});
diff --git a/src/client/src/__tests__/middleware/check-csrf.test.ts b/src/client/src/__tests__/middleware/check-csrf.test.ts
new file mode 100644
index 00000000..38149336
--- /dev/null
+++ b/src/client/src/__tests__/middleware/check-csrf.test.ts
@@ -0,0 +1,94 @@
+import { NextResponse } from "next/server";
+
+jest.mock("next/server", () => ({
+ NextResponse: {
+ json: jest.fn((body, init) => ({ body, init })),
+ },
+}));
+
+import checkCsrf from "@/middleware/check-csrf";
+
+const makeRequest = (
+ method: string,
+ pathname: string,
+ headers: Record<string, string | undefined> = {}
+) => ({
+ method,
+ nextUrl: { pathname },
+ headers: {
+ get: (key: string) => headers[key.toLowerCase()],
+ },
+});
+
+const makeFetchEvent = () => ({} as any);
+
+describe("checkCsrf", () => {
+ const nextHandler = jest.fn();
+ let middleware: ReturnType<typeof checkCsrf>;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ middleware = checkCsrf(nextHandler);
+ });
+
+ it("blocks state-changing API requests from a different origin", async () => {
+ const req = makeRequest("POST", "/api/db-config", {
+ origin: "https://evil.example.com",
+ host: "app.example.com",
+ });
+
+ const result = await middleware(req as any, makeFetchEvent());
+
+ expect(NextResponse.json).toHaveBeenCalledWith("Forbidden", {
+ status: 403,
+ });
+ expect(result).toEqual({ body: "Forbidden", init: { status: 403 } });
+ expect(nextHandler).not.toHaveBeenCalled();
+ });
+
+ it("blocks protected state-changing API requests without an Origin header", async () => {
+ const req = makeRequest("POST", "/api/db-config", {
+ host: "app.example.com",
+ });
+
+ const result = await middleware(req as any, makeFetchEvent());
+
+ expect(NextResponse.json).toHaveBeenCalledWith("Forbidden", {
+ status: 403,
+ });
+ expect(result).toEqual({ body: "Forbidden", init: { status: 403 } });
+ expect(nextHandler).not.toHaveBeenCalled();
+ });
+
+ it("allows state-changing API requests from the same origin", async () => {
+ const req = makeRequest("DELETE", "/api/api-key/key-1", {
+ origin: "https://app.example.com",
+ host: "app.example.com",
+ });
+
+ await middleware(req as any, makeFetchEvent());
+
+ expect(nextHandler).toHaveBeenCalledWith(req, expect.anything());
+ });
+
+ it("skips Origin enforcement for token-auth API routes", async () => {
+ const req = makeRequest("POST", "/api/vault/get-secrets", {
+ host: "app.example.com",
+ });
+
+ await middleware(req as any, makeFetchEvent());
+
+ expect(nextHandler).toHaveBeenCalledWith(req, expect.anything());
+ });
+
+ it("skips token-auth API routes", async () => {
+ const req = makeRequest("POST", "/api/rule-engine/evaluate", {
+ origin: "https://evil.example.com",
+ host: "app.example.com",
+ });
+
+ await middleware(req as any, makeFetchEvent());
+
+ expect(nextHandler).toHaveBeenCalledWith(req, expect.anything());
+ });
+});
diff --git a/src/client/src/__tests__/middleware/middleware.test.ts b/src/client/src/__tests__/middleware/middleware.test.ts
index 2183ae33..cde55dee 100644
--- a/src/client/src/__tests__/middleware/middleware.test.ts
+++ b/src/client/src/__tests__/middleware/middleware.test.ts
@@ -9,17 +9,22 @@ jest.mock('@/middleware/check-demo-account', () => ({
__esModule: true,
default: jest.fn(),
}));
+jest.mock('@/middleware/check-csrf', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
import { chain } from '@/middleware/chain';
import checkAuth from '@/middleware/check-auth';
import checkDemoAccount from '@/middleware/check-demo-account';
+import checkCsrf from '@/middleware/check-csrf';
// Re-import middleware module after mocks are registered
import { middleware, config } from '@/middleware';
describe('middleware', () => {
- it('composes checkDemoAccount and checkAuth via chain', () => {
- expect(chain).toHaveBeenCalledWith([checkDemoAccount, checkAuth]);
+ it('composes security and auth middleware via chain', () => {
+ expect(chain).toHaveBeenCalledWith([checkCsrf, checkDemoAccount, checkAuth]);
});
it('exports a middleware function', () => {
diff --git a/src/client/src/__tests__/selectors/chat.test.ts b/src/client/src/__tests__/selectors/chat.test.ts
new file mode 100644
index 00000000..45f53181
--- /dev/null
+++ b/src/client/src/__tests__/selectors/chat.test.ts
@@ -0,0 +1,79 @@
+import {
+ getChatActions,
+ getChatActiveId,
+ getChatConfigInfo,
+ getChatConversations,
+ getChatHasConfig,
+ getChatIsLoadingConfig,
+ getChatIsLoadingConversations,
+ getChatIsStreaming,
+ getChatMessages,
+} from "@/selectors/chat";
+
+const makeState = (overrides: Record<string, any> = {}) =>
+ ({
+ chat: {
+ conversations: [{ id: "c1", title: "Conversation" }],
+ activeConversationId: "c1",
+ messages: [{ role: "user", content: "hello" }],
+ hasConfig: true,
+ configInfo: { providerName: "openai", modelName: "gpt-4o" },
+ isLoadingConversations: false,
+ isLoadingConfig: false,
+ isStreaming: true,
+ setConversations: jest.fn(),
+ setActiveConversationId: jest.fn(),
+ setMessages: jest.fn(),
+ updateLastMessage: jest.fn(),
+ addMessage: jest.fn(),
+ setHasConfig: jest.fn(),
+ setConfigInfo: jest.fn(),
+ setIsLoadingConversations: jest.fn(),
+ setIsLoadingConfig: jest.fn(),
+ setIsStreaming: jest.fn(),
+ updateConversation: jest.fn(),
+ addConversation: jest.fn(),
+ removeConversation: jest.fn(),
+ reset: jest.fn(),
+ ...overrides,
+ },
+ } as any);
+
+describe("chat selectors", () => {
+ it("returns chat state values", () => {
+ const state = makeState();
+
+ expect(getChatConversations(state)).toBe(state.chat.conversations);
+ expect(getChatActiveId(state)).toBe("c1");
+ expect(getChatMessages(state)).toBe(state.chat.messages);
+ expect(getChatHasConfig(state)).toBe(true);
+ expect(getChatConfigInfo(state)).toEqual({
+ providerName: "openai",
+ modelName: "gpt-4o",
+ });
+ expect(getChatIsLoadingConversations(state)).toBe(false);
+ expect(getChatIsLoadingConfig(state)).toBe(false);
+ expect(getChatIsStreaming(state)).toBe(true);
+ });
+
+ it("returns chat action references", () => {
+ const state = makeState();
+
+ expect(getChatActions(state)).toEqual({
+ setConversations: state.chat.setConversations,
+ setActiveConversationId: state.chat.setActiveConversationId,
+ setMessages: state.chat.setMessages,
+ updateLastMessage: state.chat.updateLastMessage,
+ addMessage: state.chat.addMessage,
+ setHasConfig: state.chat.setHasConfig,
+ setConfigInfo: state.chat.setConfigInfo,
+ setIsLoadingConversations: state.chat.setIsLoadingConversations,
+ setIsLoadingConfig: state.chat.setIsLoadingConfig,
+ setIsStreaming: state.chat.setIsStreaming,
+ updateConversation: state.chat.updateConversation,
+ addConversation: state.chat.addConversation,
+ removeConversation: state.chat.removeConversation,
+ reset: state.chat.reset,
+ });
+ });
+});
diff --git a/src/client/src/__tests__/store/chat.test.ts b/src/client/src/__tests__/store/chat.test.ts
new file mode 100644
index 00000000..bc5ca728
--- /dev/null
+++ b/src/client/src/__tests__/store/chat.test.ts
@@ -0,0 +1,127 @@
+import { create } from "zustand";
+import { withLenses } from "@dhmk/zustand-lens";
+import { chatStoreSlice } from "@/store/chat";
+import { ChatConversation, ChatMessage } from "@/types/store/chat";
+
+const createStore = () => create<any>()(withLenses({ chat: chatStoreSlice }));
+
+const conversation = (
+ id: string,
+ overrides: Partial<ChatConversation> = {}
+): ChatConversation => ({
+ id,
+ title: `Conversation ${id}`,
+ totalCost: 0,
+ totalMessages: 1,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ ...overrides,
+});
+
+const message = (
+ role: ChatMessage["role"],
+ content: string
+): ChatMessage => ({
+ role,
+ content,
+});
+
+describe("chatStoreSlice", () => {
+ let store: ReturnType<typeof createStore>;
+
+ beforeEach(() => {
+ store = createStore();
+ });
+
+ it("starts with the expected initial state", () => {
+ expect(store.getState().chat.conversations).toEqual([]);
+ expect(store.getState().chat.activeConversationId).toBeNull();
+ expect(store.getState().chat.messages).toEqual([]);
+ expect(store.getState().chat.hasConfig).toBe(false);
+ expect(store.getState().chat.configInfo).toBeNull();
+ expect(store.getState().chat.isLoadingConversations).toBe(true);
+ expect(store.getState().chat.isLoadingConfig).toBe(true);
+ expect(store.getState().chat.isStreaming).toBe(false);
+ });
+
+ it("sets conversations, active id, messages, config, and loading flags", () => {
+ const conversations = [conversation("c1")];
+ const messages = [message("user", "show traces")];
+ const configInfo = { providerName: "openai", modelName: "gpt-4o" };
+
+ store.getState().chat.setConversations(conversations);
+ store.getState().chat.setActiveConversationId("c1");
+ store.getState().chat.setMessages(messages);
+ store.getState().chat.setHasConfig(true);
+ store.getState().chat.setConfigInfo(configInfo);
+ store.getState().chat.setIsLoadingConversations(false);
+ store.getState().chat.setIsLoadingConfig(false);
+ store.getState().chat.setIsStreaming(true);
+
+ expect(store.getState().chat.conversations).toEqual(conversations);
+ expect(store.getState().chat.activeConversationId).toBe("c1");
+ expect(store.getState().chat.messages).toEqual(messages);
+ expect(store.getState().chat.hasConfig).toBe(true);
+ expect(store.getState().chat.configInfo).toEqual(configInfo);
+ expect(store.getState().chat.isLoadingConversations).toBe(false);
+ expect(store.getState().chat.isLoadingConfig).toBe(false);
+ expect(store.getState().chat.isStreaming).toBe(true);
+ });
+
+ it("adds messages and only updates the last assistant message", () => {
+ store.getState().chat.addMessage(message("user", "question"));
+ store.getState().chat.updateLastMessage("ignored");
+
+ expect(store.getState().chat.messages).toEqual([
+ message("user", "question"),
+ ]);
+
+ store.getState().chat.addMessage(message("assistant", "partial"));
+ store.getState().chat.updateLastMessage("complete");
+
+ expect(store.getState().chat.messages).toEqual([
+ message("user", "question"),
+ message("assistant", "complete"),
+ ]);
+ });
+
+ it("adds, updates, and removes conversations", () => {
+ store.getState().chat.setConversations([
+ conversation("c1", { title: "Old" }),
+ ]);
+
+ store.getState().chat.addConversation(conversation("c2"));
+ store.getState().chat.updateConversation("c1", {
+ title: "New",
+ totalMessages: 3,
+ });
+ store.getState().chat.removeConversation("c2");
+
+ expect(store.getState().chat.conversations).toEqual([
+ conversation("c1", { title: "New", totalMessages: 3 }),
+ ]);
+ });
+
+ it("reset restores the initial state", () => {
+ store.getState().chat.setConversations([conversation("c1")]);
+ store.getState().chat.setActiveConversationId("c1");
+ store.getState().chat.addMessage(message("assistant", "answer"));
+ store.getState().chat.setHasConfig(true);
+ store.getState().chat.setConfigInfo({ modelId: "model-1" });
+ store.getState().chat.setIsLoadingConversations(false);
+ store.getState().chat.setIsLoadingConfig(false);
+ store.getState().chat.setIsStreaming(true);
+
+ store.getState().chat.reset();
+
+ expect(store.getState().chat).toMatchObject({
+ conversations: [],
+ activeConversationId: null,
+ messages: [],
+ hasConfig: false,
+ configInfo: null,
+ isLoadingConversations: true,
+ isLoadingConfig: true,
+ isStreaming: false,
+ });
+ });
+});
diff --git a/src/client/src/__tests__/utils/api-response.test.ts b/src/client/src/__tests__/utils/api-response.test.ts
new file mode 100644
index 00000000..daa2d5cc
--- /dev/null
+++ b/src/client/src/__tests__/utils/api-response.test.ts
@@ -0,0 +1,50 @@
+jest.mock("@/utils/validation", () => ({
+ sanitizeErrorMessage: jest.fn((err: unknown, fallback: string) =>
+ err instanceof Error ? fallback : String(err || fallback)
+ ),
+}));
+
+import { errorResponse } from "@/utils/api-response";
+import { sanitizeErrorMessage } from "@/utils/validation";
+
+class TestResponse {
+ status: number;
+ private body: unknown;
+
+ constructor(body: unknown, init?: { status?: number }) {
+ this.body = body;
+ this.status = init?.status || 200;
+ }
+
+ static json(body: unknown, init?: { status?: number }) {
+ return new TestResponse(body, init);
+ }
+
+ async json() {
+ return this.body;
+ }
+}
+
+describe("errorResponse", () => {
+ beforeAll(() => {
+ (global as any).Response = TestResponse;
+ });
+
+ it("returns a sanitized JSON error response with the provided status", async () => {
+ const response = errorResponse(new Error("db trace"), "Safe error", 503);
+
+ expect(sanitizeErrorMessage).toHaveBeenCalledWith(
+ expect.any(Error),
+ "Safe error"
+ );
+ expect(response.status).toBe(503);
+ await expect(response.json()).resolves.toBe("Safe error");
+ });
+
+ it("uses default fallback and status", async () => {
+ const response = errorResponse(undefined);
+
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toBe("An unexpected error occurred");
+ });
+});
diff --git a/src/client/src/__tests__/utils/crypto.test.ts b/src/client/src/__tests__/utils/crypto.test.ts
new file mode 100644
index 00000000..67729664
--- /dev/null
+++ b/src/client/src/__tests__/utils/crypto.test.ts
@@ -0,0 +1,79 @@
+import { decryptValue, encryptValue, isEncrypted } from "@/utils/crypto";
+
+const ORIGINAL_ENV = process.env;
+
+describe("vault crypto utilities", () => {
+ beforeEach(() => {
+ process.env = { ...ORIGINAL_ENV };
+ process.env.OPENLIT_VAULT_ENCRYPTION_KEY = "test-vault-key";
+ delete process.env.NEXTAUTH_SECRET;
+ jest.restoreAllMocks();
+ });
+
+ afterAll(() => {
+ process.env = ORIGINAL_ENV;
+ });
+
+ it("encrypts plaintext values with the encrypted prefix", () => {
+ const encrypted = encryptValue("secret-value");
+
+ expect(encrypted).toMatch(/^enc:v1:/);
+ expect(encrypted).not.toContain("secret-value");
+ expect(isEncrypted(encrypted)).toBe(true);
+ });
+
+ it("decrypts values encrypted with the same key", () => {
+ const encrypted = encryptValue("secret-value");
+
+ expect(decryptValue(encrypted)).toBe("secret-value");
+ });
+
+ it("returns empty and already encrypted values unchanged", () => {
+ expect(encryptValue("")).toBe("");
+ expect(decryptValue("")).toBe("");
+ expect(encryptValue("enc:v1:already")).toBe("enc:v1:already");
+ });
+
+ it("falls back to NEXTAUTH_SECRET when no dedicated vault key is set", () => {
+ delete process.env.OPENLIT_VAULT_ENCRYPTION_KEY;
+ process.env.NEXTAUTH_SECRET = "nextauth-secret";
+
+ const encrypted = encryptValue("fallback-secret");
+
+ expect(decryptValue(encrypted)).toBe("fallback-secret");
+ });
+
+ it("throws when no encryption key is configured", () => {
+ delete process.env.OPENLIT_VAULT_ENCRYPTION_KEY;
+ delete process.env.NEXTAUTH_SECRET;
+
+ expect(() => encryptValue("weakly-keyed-secret")).toThrow(
+ "No encryption key configured. Set OPENLIT_VAULT_ENCRYPTION_KEY or NEXTAUTH_SECRET."
+ );
+ });
+
+ it("returns raw values that are not encrypted", () => {
+ expect(decryptValue("plain-value")).toBe("plain-value");
+ expect(isEncrypted("plain-value")).toBe(false);
+ expect(isEncrypted("")).toBe(false);
+ });
+
+ it("returns malformed encrypted values unchanged", () => {
+ const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
+
+ expect(decryptValue("enc:v1:malformed")).toBe("enc:v1:malformed");
+ expect(errorSpy).toHaveBeenCalledWith("Invalid encrypted value format");
+ });
+
+ it("returns tampered encrypted values unchanged when decryption fails", () => {
+ const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
+ const encrypted = encryptValue("secret-value");
+ const tampered = encrypted.replace(/.$/, "x");
+
+ expect(decryptValue(tampered)).toBe(tampered);
+ expect(errorSpy).toHaveBeenCalledWith(
+ "Decryption failed, returning raw value:",
+ expect.anything()
+ );
+ });
+});
diff --git a/src/client/src/__tests__/utils/date.test.ts b/src/client/src/__tests__/utils/date.test.ts
index 4ee24f37..8e3fdacf 100644
--- a/src/client/src/__tests__/utils/date.test.ts
+++ b/src/client/src/__tests__/utils/date.test.ts
@@ -1,4 +1,4 @@
-import { formatDate } from '@/utils/date';
+import { formatBrowserDateTime, formatDate } from '@/utils/date';
describe('formatDate', () => {
const isoDate = '2024-06-15T10:30:00Z';
@@ -33,4 +33,35 @@ describe('formatDate', () => {
const result = formatDate('2020-01-01');
expect(result).toMatch(/2020/);
});
+
+ it('returns fallback for invalid or empty date strings', () => {
+ expect(formatDate('not-a-date')).toBe('-');
+ expect(formatDate('')).toBe('-');
+ });
+
+ it('normalizes date strings that use a space separator', () => {
+ const result = formatDate('2024-06-15 10:30:00', { time: true });
+
+ expect(result).toMatch(/Jun/i);
+ expect(result).toMatch(/2024/);
+ expect(result).toMatch(/:/);
+ });
+});
+
+describe('formatBrowserDateTime', () => {
+ it('formats valid browser date time strings', () => {
+ const result = formatBrowserDateTime('2024-06-15T10:30:00Z');
+
+ expect(result).toMatch(/2024/);
+ });
+
+ it('uses the default fallback for missing or invalid dates', () => {
+ expect(formatBrowserDateTime(null)).toBe('-');
+ expect(formatBrowserDateTime(undefined)).toBe('-');
+ expect(formatBrowserDateTime('not-a-date')).toBe('-');
+ });
+
+ it('uses a custom fallback when provided', () => {
+ expect(formatBrowserDateTime('', 'No date')).toBe('No date');
+ });
});
diff --git a/src/client/src/__tests__/utils/string.test.ts b/src/client/src/__tests__/utils/string.test.ts
index 2a1d7c13..3775904d 100644
--- a/src/client/src/__tests__/utils/string.test.ts
+++ b/src/client/src/__tests__/utils/string.test.ts
@@ -1,4 +1,9 @@
-import { unescapeString, convertToTitleCase } from '@/utils/string';
+import {
+ unescapeString,
+ convertToTitleCase,
+ escapeHtml,
+ escapeEmailForDisplay,
+} from '@/utils/string';
describe('unescapeString', () => {
it('replaces \\n escape sequences with actual newlines', () => {
@@ -51,3 +56,23 @@ describe('convertToTitleCase', () => {
expect(convertToTitleCase('open_telemetry_sdk')).toBe('Open Telemetry Sdk');
});
});
+
+describe('escapeHtml', () => {
+ it('escapes HTML-sensitive characters', () => {
+ expect(escapeHtml(`<script>alert('x')</script>&"`)).toBe(
+ '&lt;script&gt;alert(&#39;x&#39;)&lt;/script&gt;&amp;&quot;'
+ );
+ });
+});
+
+describe('escapeEmailForDisplay', () => {
+ it('escapes unsafe email display text', () => {
+ expect(escapeEmailForDisplay('"><img src=x onerror=alert(1)>@test.com')).toBe(
+ '&quot;&gt;&lt;img src=x onerror=alert(1)&gt;@test.com'
+ );
+ });
+
+ it('returns an empty string for missing email', () => {
+ expect(escapeEmailForDisplay(null)).toBe('');
+ });
+});
diff --git a/src/client/src/__tests__/utils/validation.test.ts b/src/client/src/__tests__/utils/validation.test.ts
new file mode 100644
index 00000000..a9fc0e92
--- /dev/null
+++ b/src/client/src/__tests__/utils/validation.test.ts
@@ -0,0 +1,143 @@
+import {
+ sanitizeErrorMessage,
+ validateDatabaseHost,
+ validateEmail,
+ validatePasswordComplexity,
+ validateProfileName,
+} from "@/utils/validation";
+
+describe("validateEmail", () => {
+ it("accepts a normal RFC 5321 dot-atom email", () => {
+ expect(validateEmail("[email protected]").valid).toBe(true);
+ });
+
+ it("rejects HTML/script-bearing email strings", () => {
+ const result = validateEmail('"><img src=x onerror=alert(1)>@test.com');
+
+ expect(result).toEqual({
+ valid: false,
+ error: "Email contains invalid characters",
+ });
+ });
+
+ it("rejects malformed local parts", () => {
+ expect(validateEmail("@test.com").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ });
+
+ it("rejects malformed domains", () => {
+ expect(validateEmail("user@example").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ expect(validateEmail("[email protected]").valid).toBe(false);
+ });
+});
+
+describe("validateDatabaseHost", () => {
+ it("accepts public hostnames and public IPv4 addresses", () => {
+ expect(validateDatabaseHost("clickhouse.example.com").valid).toBe(true);
+ expect(validateDatabaseHost("8.8.8.8:8123").valid).toBe(true);
+ });
+
+ it("rejects schemes and encoded IP variants used for SSRF bypasses", () => {
+ expect(validateDatabaseHost("http://clickhouse.example.com")).toEqual({
+ valid: false,
+ error: "Host must not contain a URL scheme",
+ });
+ expect(validateDatabaseHost("2130706433").valid).toBe(false);
+ expect(validateDatabaseHost("0x7f000001").valid).toBe(false);
+ expect(validateDatabaseHost("0177.0.0.1").valid).toBe(false);
+ });
+
+ it("rejects private, loopback, link-local, and metadata hosts", () => {
+ expect(validateDatabaseHost("127.0.0.1").valid).toBe(false);
+ expect(validateDatabaseHost("10.0.0.1").valid).toBe(false);
+ expect(validateDatabaseHost("172.16.0.1").valid).toBe(false);
+ expect(validateDatabaseHost("192.168.1.1").valid).toBe(false);
+ expect(validateDatabaseHost("169.254.169.254").valid).toBe(false);
+ expect(validateDatabaseHost("localhost").valid).toBe(false);
+ expect(validateDatabaseHost("metadata.google.internal").valid).toBe(false);
+ });
+
+ it("rejects private IPv6 and invalid host characters", () => {
+ expect(validateDatabaseHost("[::1]").valid).toBe(false);
+ expect(validateDatabaseHost("[fe80::1]").valid).toBe(false);
+ expect(validateDatabaseHost("[fc00::1]").valid).toBe(false);
+ expect(validateDatabaseHost("host$name").valid).toBe(false);
+ });
+});
+
+describe("validateProfileName", () => {
+ it("accepts normal names", () => {
+ expect(validateProfileName("Ada Lovelace")).toEqual({ valid: true });
+ });
+
+ it("rejects missing, long, and HTML-bearing names", () => {
+ expect(validateProfileName("")).toEqual({
+ valid: false,
+ error: "Name is required",
+ });
+ expect(validateProfileName("a".repeat(101))).toEqual({
+ valid: false,
+ error: "Name must be 100 characters or fewer",
+ });
+ expect(validateProfileName("<script>alert(1)</script>")).toEqual({
+ valid: false,
+ error: "Name must not contain HTML tags",
+ });
+ });
+});
+
+describe("validatePasswordComplexity", () => {
+ it("accepts complex passwords", () => {
+ expect(validatePasswordComplexity("ValidPass1")).toEqual({ valid: true });
+ });
+
+ it("rejects missing, short, long, and incomplete passwords", () => {
+ expect(validatePasswordComplexity("").valid).toBe(false);
+ expect(validatePasswordComplexity("Short1").valid).toBe(false);
+ expect(validatePasswordComplexity(`${"A".repeat(129)}a1`).valid).toBe(false);
+ expect(validatePasswordComplexity("lowercase1").valid).toBe(false);
+ expect(validatePasswordComplexity("UPPERCASE1").valid).toBe(false);
+ expect(validatePasswordComplexity("NoNumbers").valid).toBe(false);
+ });
+});
+
+describe("sanitizeErrorMessage", () => {
+ it("returns the fallback for empty or internal framework errors", () => {
+ expect(sanitizeErrorMessage(undefined, "Safe fallback")).toBe("Safe fallback");
+ expect(sanitizeErrorMessage(new Error("PrismaClientKnownRequestError"))).toBe(
+ "An unexpected error occurred"
+ );
+ expect(sanitizeErrorMessage("prisma.user.findMany invocation:")).toBe(
+ "An unexpected error occurred"
+ );
+ expect(sanitizeErrorMessage("TypeError: Cannot read properties")).toBe(
+ "An unexpected error occurred"
+ );
+ expect(sanitizeErrorMessage("Error\n at /app/server.js:1")).toBe(
+ "An unexpected error occurred"
+ );
+ });
+
+ it("hides ClickHouse and local path details", () => {
+ expect(sanitizeErrorMessage("/etc/clickhouse/config.xml failed")).toBe(
+ "Database connection error"
+ );
+ expect(sanitizeErrorMessage("clickhouse-server password is incorrect")).toBe(
+ "Database connection error"
+ );
+ expect(sanitizeErrorMessage("/Users/dev/project/file.ts")).toBe(
+ "An unexpected error occurred"
+ );
+ expect(sanitizeErrorMessage("/home/app/file.ts")).toBe(
+ "An unexpected error occurred"
+ );
+ });
+
+ it("keeps safe user-facing messages", () => {
+ expect(sanitizeErrorMessage("Invalid input")).toBe("Invalid input");
+ });
+});
diff --git a/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx b/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx
index 92fb3b18..8a692499 100644
--- a/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx
+++ b/src/client/src/app/(playground)/settings/database-config/share-dialog.tsx
@@ -26,6 +26,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { set } from "lodash";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import { DatabaseConfigPermissions } from "@/constants/dbConfig";
+import { escapeEmailForDisplay } from "@/utils/string";
const validateEmail = (email: string) => {
return String(email)
@@ -158,11 +159,11 @@ export default function ShareDialog({
{shareArray.map((shareObj, index) => (
<TableRow key={shareObj.email}>
<TableCell className="font-medium text-stone-500">
- {shareObj.email}
+ {escapeEmailForDisplay(shareObj.email)}
</TableCell>
<TableCell className="text-center p-0">
<Checkbox
- name={`${shareObj.email}.permission.canEdit`}
+ name={`share-${index}.permission.canEdit`}
checked={shareObj.permissions.canEdit}
onCheckedChange={(checked: boolean) =>
onChangePermission(
@@ -175,7 +176,7 @@ export default function ShareDialog({
</TableCell>
<TableCell className="text-center p-0">
<Checkbox
- name={`${shareObj.email}.permission.canDelete`}
+ name={`share-${index}.permission.canDelete`}
checked={shareObj.permissions.canDelete}
onCheckedChange={(checked: boolean) =>
onChangePermission(
@@ -188,7 +189,7 @@ export default function ShareDialog({
</TableCell>
<TableCell className="text-center p-0">
<Checkbox
- name={`${shareObj.email}.permission.canShare`}
+ name={`share-${index}.permission.canShare`}
checked={shareObj.permissions.canShare}
onCheckedChange={(checked: boolean) =>
onChangePermission(
diff --git a/src/client/src/app/(playground)/settings/organisation/page.tsx b/src/client/src/app/(playground)/settings/organisation/page.tsx
index 914e5a8e..97f13825 100644
--- a/src/client/src/app/(playground)/settings/organisation/page.tsx
+++ b/src/client/src/app/(playground)/settings/organisation/page.tsx
@@ -87,6 +87,7 @@ import {
} from "@/components/ui/alert-dialog";
import CreateOrganisationDialog from "@/components/(playground)/sidebar/create-organisation-dialog";
import getMessage from "@/constants/messages";
+import { escapeEmailForDisplay } from "@/utils/string";
interface Member {
id: string;
@@ -132,6 +133,7 @@ export default function OrganisationSettingsPage() {
const currentUserMember = members.find(m => m.id === currentUserId);
const currentUserRole = currentUserMember?.role;
const hasAdminPermissions = currentUserRole === 'owner' || currentUserRole === 'admin';
+ const displayEmail = (email: string) => escapeEmailForDisplay(email);
useEffect(() => {
posthog?.capture(CLIENT_EVENTS.SETTINGS_ORGANISATION_PAGE_VISITED);
@@ -479,11 +481,11 @@ export default function OrganisationSettingsPage() {
<TableCell className="py-2 pl-2">
<div>
<p className="font-medium">
- {member.name || member.email}
+ {member.name || displayEmail(member.email)}
</p>
{member.name && (
<p className="text-xs text-muted-foreground">
- {member.email}
+ {displayEmail(member.email)}
</p>
)}
</div>
@@ -616,7 +618,9 @@ export default function OrganisationSettingsPage() {
<TableBody>
{orgPendingInvites.map((invite) => (
<TableRow key={invite.id} className="text-sm">
- <TableCell className="py-2 pl-2">{invite.email}</TableCell>
+ <TableCell className="py-2 pl-2">
+ {displayEmail(invite.email)}
+ </TableCell>
<TableCell className="py-2 text-xs text-muted-foreground">
{new Date(invite.invitedAt).toLocaleDateString()}
</TableCell>
diff --git a/src/client/src/app/api/db-config/route.ts b/src/client/src/app/api/db-config/route.ts
index a9f9e2ae..da651165 100644
--- a/src/client/src/app/api/db-config/route.ts
+++ b/src/client/src/app/api/db-config/route.ts
@@ -1,15 +1,25 @@
import { getDBConfigByUser, upsertDBConfig } from "@/lib/db-config";
import asaw from "@/utils/asaw";
import { DatabaseConfig } from "@prisma/client";
+import { errorResponse } from "@/utils/api-response";
+
+function stripSensitiveDbFields(config: any) {
+ if (!config) return config;
+
+ const { password, ...rest } = config;
+ return { ...rest, password: password ? "****" : "" };
+}
export async function GET() {
const [err, res]: any = await asaw(getDBConfigByUser());
if (err)
- return Response.json(err, {
- status: 400,
- });
+ return errorResponse(err, "Failed to fetch database configurations");
- return Response.json(res);
+ const sanitized = Array.isArray(res)
+ ? res.map(stripSensitiveDbFields)
+ : stripSensitiveDbFields(res);
+
+ return Response.json(sanitized);
}
export async function POST(request: Request) {
@@ -30,9 +40,7 @@ export async function POST(request: Request) {
const [err, res]: any = await asaw(upsertDBConfig(dbConfig, id));
if (err)
- return Response.json(err, {
- status: 400,
- });
+ return errorResponse(err, "Failed to save database configuration");
return Response.json(res);
}
diff --git a/src/client/src/app/api/user/profile/route.ts b/src/client/src/app/api/user/profile/route.ts
index 664cdd37..ab51ab04 100644
--- a/src/client/src/app/api/user/profile/route.ts
+++ b/src/client/src/app/api/user/profile/route.ts
@@ -3,6 +3,15 @@ import { updateUserProfile } from "@/lib/user";
import { SERVER_EVENTS } from "@/constants/events";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+import { errorResponse } from "@/utils/api-response";
+import { validateProfileName } from "@/utils/validation";
+
+function stripPasswordFromUser(user: any) {
+ if (!user) return user;
+
+ const { password, ...rest } = user;
+ return rest;
+}
export async function GET() {
const user: any = await getCurrentUser();
@@ -12,12 +21,20 @@ export async function GET() {
status: 401,
});
- return Response.json(user);
+ return Response.json(stripPasswordFromUser(user));
}
export async function POST(request: Request) {
const startTimestamp = Date.now();
const formData = await request.json();
+
+ if (formData.name) {
+ const nameValidation = validateProfileName(formData.name);
+ if (!nameValidation.valid) {
+ return Response.json(nameValidation.error, { status: 400 });
+ }
+ }
+
const formObject = {
currentPassword: formData.currentPassword,
newPassword: formData.newPassword,
@@ -31,14 +48,12 @@ export async function POST(request: Request) {
event: SERVER_EVENTS.USER_PROFILE_UPDATE_FAILURE,
startTimestamp,
});
- return Response.json(err, {
- status: 400,
- });
+ return errorResponse(err, "Failed to update profile");
}
PostHogServer.fireEvent({
event: SERVER_EVENTS.USER_PROFILE_UPDATE_SUCCESS,
startTimestamp,
});
- return Response.json(res);
+ return Response.json(stripPasswordFromUser(res));
}
diff --git a/src/client/src/app/api/vault/get-secrets/route.ts b/src/client/src/app/api/vault/get-secrets/route.ts
index c57cf688..deb46031 100644
--- a/src/client/src/app/api/vault/get-secrets/route.ts
+++ b/src/client/src/app/api/vault/get-secrets/route.ts
@@ -5,8 +5,59 @@ import { getSecretsFromDatabaseId } from "@/lib/platform/vault";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+const CORS_METHODS = "POST, OPTIONS";
+const CORS_HEADERS = "Content-Type, Authorization";
+
+function getConfiguredAllowedOrigins() {
+ return [
+ process.env.OPENLIT_ALLOWED_CORS_ORIGINS,
+ process.env.OPENLIT_ALLOWED_ORIGINS,
+ process.env.NEXTAUTH_URL,
+ ]
+ .filter(Boolean)
+ .flatMap((originList) => originList!.split(","))
+ .map((origin) => origin.trim())
+ .filter(Boolean);
+}
+
+function getAllowedCorsOrigin(request: Request) {
+ const origin = request.headers.get("Origin");
+ if (!origin) return null;
+
+ const host = request.headers.get("Host");
+ try {
+ const originUrl = new URL(origin);
+ if (host && originUrl.host === host) {
+ return origin;
+ }
+ } catch {
+ return null;
+ }
+
+ return getConfiguredAllowedOrigins().includes(origin) ? origin : null;
+}
+
+function getCorsHeaders(origin: string) {
+ return {
+ "Access-Control-Allow-Origin": origin,
+ "Access-Control-Allow-Methods": CORS_METHODS,
+ "Access-Control-Allow-Headers": CORS_HEADERS,
+ "Vary": "Origin",
+ };
+}
+
export async function POST(request: Request) {
const startTimestamp = Date.now();
+ const corsOrigin = getAllowedCorsOrigin(request);
+ const requestOrigin = request.headers.get("Origin");
+
+ if (requestOrigin && !corsOrigin) {
+ return Response.json(
+ { err: "Origin not allowed", res: null },
+ { status: 403 }
+ );
+ }
+
const authorizationHeader = request.headers.get("Authorization") || "";
let apiKey: string = "";
if (authorizationHeader.startsWith("Bearer ")) {
@@ -37,19 +88,25 @@ export async function POST(request: Request) {
startTimestamp,
});
- return Response.json({
- err,
- res: data,
- });
+ return Response.json(
+ {
+ err,
+ res: data,
+ },
+ {
+ headers: corsOrigin ? getCorsHeaders(corsOrigin) : undefined,
+ }
+ );
}
-export async function OPTIONS() {
+export async function OPTIONS(request: Request) {
+ const corsOrigin = getAllowedCorsOrigin(request);
+ if (!corsOrigin) {
+ return new Response(null, { status: 403 });
+ }
+
return new Response(null, {
- status: 200,
- headers: {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
- },
+ status: 204,
+ headers: getCorsHeaders(corsOrigin),
});
}
diff --git a/src/client/src/clickhouse/migrations/encrypt-vault-values-migration.ts b/src/client/src/clickhouse/migrations/encrypt-vault-values-migration.ts
new file mode 100644
index 00000000..af9c3d04
--- /dev/null
+++ b/src/client/src/clickhouse/migrations/encrypt-vault-values-migration.ts
@@ -0,0 +1,113 @@
+import { OPENLIT_VAULT_TABLE_NAME } from "@/lib/platform/vault/table-details";
+import { dataCollector } from "@/lib/platform/common";
+import { encryptValue, isEncrypted } from "@/utils/crypto";
+import { getDBConfigById, getDBConfigByUser } from "@/lib/db-config";
+import asaw from "@/utils/asaw";
+import prisma from "@/lib/prisma";
+import { consoleLog } from "@/utils/log";
+
+const MIGRATION_ID = "encrypt-vault-values";
+
+function escapeClickHouseString(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+export default async function EncryptVaultValuesMigration(
+ databaseConfigId?: string
+) {
+ let err, dbConfig;
+ if (databaseConfigId) {
+ [err, dbConfig] = await asaw(getDBConfigById({ id: databaseConfigId }));
+ } else {
+ [err, dbConfig] = await asaw(getDBConfigByUser(true));
+ }
+
+ if (err || !dbConfig?.id) return { migrationExist: false, queriesRun: false };
+
+ const [, migrationExist] = await asaw(
+ prisma.clickhouseMigrations.findFirst({
+ where: {
+ AND: {
+ databaseConfigId: dbConfig.id as string,
+ clickhouseMigrationId: MIGRATION_ID,
+ },
+ },
+ })
+ );
+
+ if (migrationExist?.id) {
+ return { migrationExist: true, queriesRun: false };
+ }
+
+ try {
+ const { data, err: readErr } = await dataCollector(
+ {
+ query: `SELECT id, value FROM ${OPENLIT_VAULT_TABLE_NAME}`,
+ },
+ "query",
+ dbConfig.id
+ );
+
+ if (readErr || !data || !Array.isArray(data)) {
+ consoleLog(
+ `Vault encryption migration: no data to migrate or error: ${readErr}`
+ );
+ await markMigrationComplete(dbConfig.id);
+ return { migrationExist: false, queriesRun: true };
+ }
+
+ const plaintextSecrets = (data as any[]).filter(
+ (secret) => secret.value && !isEncrypted(secret.value)
+ );
+
+ if (plaintextSecrets.length === 0) {
+ consoleLog("Vault encryption migration: all values already encrypted");
+ await markMigrationComplete(dbConfig.id);
+ return { migrationExist: false, queriesRun: true };
+ }
+
+ for (const secret of plaintextSecrets) {
+ const encrypted = escapeClickHouseString(encryptValue(secret.value));
+ const secretId = escapeClickHouseString(secret.id);
+ const updateQuery = `
+ ALTER TABLE ${OPENLIT_VAULT_TABLE_NAME}
+ UPDATE value = '${encrypted}'
+ WHERE id = '${secretId}'
+ `;
+
+ const { err: updateErr } = await dataCollector(
+ { query: updateQuery },
+ "exec",
+ dbConfig.id
+ );
+
+ if (updateErr) {
+ consoleLog(
+ `Vault encryption migration: failed to encrypt secret ${secret.id}: ${updateErr}`
+ );
+ }
+ }
+
+ consoleLog(
+ `Vault encryption migration: encrypted ${plaintextSecrets.length} secrets`
+ );
+
+ await markMigrationComplete(dbConfig.id);
+
+ return { migrationExist: false, queriesRun: true };
+ } catch (migrationError) {
+ consoleLog(`Vault encryption migration error: ${migrationError}`);
+ return { migrationExist: false, queriesRun: false };
+ }
+}
+
+async function markMigrationComplete(databaseConfigId: string) {
+ await asaw(
+ prisma.clickhouseMigrations.create({
+ data: {
+ databaseConfigId,
+ clickhouseMigrationId: MIGRATION_ID,
+ },
+ })
+ );
+}
diff --git a/src/client/src/clickhouse/migrations/index.ts b/src/client/src/clickhouse/migrations/index.ts
index 9385780f..bcbd9571 100644
--- a/src/client/src/clickhouse/migrations/index.ts
+++ b/src/client/src/clickhouse/migrations/index.ts
@@ -21,6 +21,7 @@ import CreateChatMigration from "./create-chat-migration";
import CreateProvidersMigration from "./create-providers-migration";
import CreateProviderMetadataMigration from "./create-provider-metadata-migration";
import DropLegacyOpengroundTablesMigration from "./drop-legacy-openground-tables-migration";
+import EncryptVaultValuesMigration from "./encrypt-vault-values-migration";
import AddControllerSkippingIndexesMigration from "./add-controller-skipping-indexes-migration";
export default async function migrations(databaseConfigId?: string) {
@@ -58,4 +59,6 @@ export default async function migrations(databaseConfigId?: string) {
CreateProviderMetadataMigration(databaseConfigId),
DropLegacyOpengroundTablesMigration(databaseConfigId),
]);
+
+ await EncryptVaultValuesMigration(databaseConfigId);
}
diff --git a/src/client/src/components/(playground)/api-keys/manage.tsx b/src/client/src/components/(playground)/api-keys/manage.tsx
index 4f8d22af..51b5e6c3 100644
--- a/src/client/src/components/(playground)/api-keys/manage.tsx
+++ b/src/client/src/components/(playground)/api-keys/manage.tsx
@@ -13,6 +13,7 @@ import Generate from "./generate";
import { ApiKey } from "@/types/api-key";
import { Columns } from "@/components/data-table/columns";
import DataTable from "@/components/data-table/table";
+import { escapeEmailForDisplay } from "@/utils/string";
const columns: Columns<string, ApiKey> = {
name: {
@@ -32,7 +33,7 @@ const columns: Columns<string, ApiKey> = {
createdBy: {
header: () => "Created By",
cell: ({ row }) => {
- return row.createdByUser.email;
+ return escapeEmailForDisplay(row.createdByUser.email);
},
},
createdAt: {
diff --git a/src/client/src/components/(playground)/sidebar/user-actions.tsx b/src/client/src/components/(playground)/sidebar/user-actions.tsx
index cc3ca7a6..9460723e 100644
--- a/src/client/src/components/(playground)/sidebar/user-actions.tsx
+++ b/src/client/src/components/(playground)/sidebar/user-actions.tsx
@@ -9,6 +9,7 @@ import Link from "next/link";
import { usePostHog } from "posthog-js/react";
import { useEffect } from "react";
import getMessage from "@/constants/messages";
+import { escapeEmailForDisplay } from "@/utils/string";
const DROPDOWN_MENU_ITEM_CLASS = "flex w-full text-xs gap-2 hover:bg-primary/10 dark:hover:bg-primary/10 px-2 py-1.5";
const DROPDOWN_MENU_ICON_CLASS = "w-4 h-4";
@@ -31,6 +32,7 @@ export default function UserActions() {
}, [user]);
if (!user) return null;
+ const displayEmail = escapeEmailForDisplay(user.email);
return (
<DropdownMenu>
@@ -38,11 +40,11 @@ export default function UserActions() {
<Button variant="outline" className="flex gap-2 justify-start group-data-[state=close]:justify-center p-[calc(0.625rem-1px)] overflow-hidden text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white font-normal w-full">
<Avatar className={"h-5 w-5 rounded-lg"}>
<AvatarImage className="rounded-full" src={user!.image || ""} alt={user!.name || ""} />
- <AvatarFallback className="rounded-lg bg-transparent dark:bg-transparent">{user!.name?.substring(0, 2) || user!.email?.substring(0, 2)}</AvatarFallback>
+ <AvatarFallback className="rounded-lg bg-transparent dark:bg-transparent">{user!.name?.substring(0, 2) || displayEmail.substring(0, 2)}</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-xs leading-tight group-data-[state=close]:hidden text-ellipsis overflow-hidden whitespace-nowrap">
<span className="truncate font-medium">{user!.name}</span>
- <span className="truncate text-xs">{user!.email}</span>
+ <span className="truncate text-xs">{displayEmail}</span>
</div>
<ChevronsUpDown className={`size-4 block group-data-[state=close]:hidden shrink-0 self-center`} />
</Button>
@@ -57,11 +59,11 @@ export default function UserActions() {
<div className="flex items-center gap-2 px-1 text-left text-sm">
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage src={user!.image || ""} alt={user!.name || ""} />
- <AvatarFallback className="rounded-lg">{user!.name?.substring(0, 2) || user!.email?.substring(0, 2)}</AvatarFallback>
+ <AvatarFallback className="rounded-lg">{user!.name?.substring(0, 2) || displayEmail.substring(0, 2)}</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-xs leading-tight text-ellipsis overflow-hidden whitespace-nowrap">
<span className="truncate font-medium">{user!.name}</span>
- <span className="truncate text-xs">{user!.email}</span>
+ <span className="truncate text-xs">{displayEmail}</span>
</div>
</div>
</DropdownMenuLabel>
@@ -84,4 +86,4 @@ export default function UserActions() {
</DropdownMenuContent>
</DropdownMenu>
)
-}
\ No newline at end of file
+}
diff --git a/src/client/src/helpers/server/platform.ts b/src/client/src/helpers/server/platform.ts
index 903f5b83..095287af 100644
--- a/src/client/src/helpers/server/platform.ts
+++ b/src/client/src/helpers/server/platform.ts
@@ -9,6 +9,10 @@ import {
import { getTraceMappingKeyFullPath } from "../server/trace";
import { FilterWhereConditionType } from "@/types/platform";
+function escapeClickHouseString(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
export const validateMetricsRequestType = {
// Request
REQUEST_PER_TIME: "REQUEST_PER_TIME",
@@ -254,12 +258,12 @@ export const getFilterWhereCondition = (
if (filter.selectedConfig.customFilters?.length) {
filter.selectedConfig.customFilters.forEach(({ attributeType, key, value }) => {
if (key && value) {
- const safeValue = value.replace(/'/g, "''");
+ const safeValue = escapeClickHouseString(value);
if (attributeType === "SpanAttributes") {
- const safeKey = key.replace(/'/g, "''");
+ const safeKey = escapeClickHouseString(key);
whereArray.push(`SpanAttributes['${safeKey}'] = '${safeValue}'`);
} else if (attributeType === "ResourceAttributes") {
- const safeKey = key.replace(/'/g, "''");
+ const safeKey = escapeClickHouseString(key);
whereArray.push(`ResourceAttributes['${safeKey}'] = '${safeValue}'`);
} else if (attributeType === "Field") {
// Direct column — key must be an identifier, strip anything non-alphanumeric/underscore
diff --git a/src/client/src/helpers/server/widget.ts b/src/client/src/helpers/server/widget.ts
index 3da90c6e..89ce6f80 100644
--- a/src/client/src/helpers/server/widget.ts
+++ b/src/client/src/helpers/server/widget.ts
@@ -47,5 +47,5 @@ export function sanitizeWidget(widget: Widget) {
}
export function escapeSingleQuotes(input: string) {
- return input.replace(/'([^']*)'/g, "''$1''");
-}
\ No newline at end of file
+ return input.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
diff --git a/src/client/src/lib/db-config.ts b/src/client/src/lib/db-config.ts
index 40c9df3e..45ca3e4f 100644
--- a/src/client/src/lib/db-config.ts
+++ b/src/client/src/lib/db-config.ts
@@ -7,6 +7,7 @@ import getMessage from "@/constants/messages";
import { throwIfError } from "@/utils/error";
import { consoleLog } from "@/utils/log";
import { getCurrentOrganisation } from "./organisation";
+import { validateDatabaseHost } from "@/utils/validation";
export const getDBConfigByUser = async (currentOnly?: boolean) => {
const user = await getCurrentUser();
@@ -128,6 +129,15 @@ export const upsertDBConfig = async (
if (!dbConfig.port) throw new Error("No port provided");
if (!dbConfig.database) throw new Error("No database provided");
+ const hostValidation = validateDatabaseHost(dbConfig.host);
+ if (!hostValidation.valid) {
+ throw new Error(hostValidation.error || "Invalid host");
+ }
+
+ if (typeof dbConfig.port !== "string") {
+ dbConfig.port = String(dbConfig.port);
+ }
+
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -515,7 +525,7 @@ async function checkPermissionForDbAction(
"User doesn't have permission to edit the database config"
);
break;
- case "EDIT":
+ case "SHARE":
if (!dbUserConfig.canShare)
throw new Error(
"User doesn't have permission to share the database config"
diff --git a/src/client/src/lib/platform/api-keys/index.ts b/src/client/src/lib/platform/api-keys/index.ts
index 7b3cdca9..aa43a671 100644
--- a/src/client/src/lib/platform/api-keys/index.ts
+++ b/src/client/src/lib/platform/api-keys/index.ts
@@ -96,9 +96,30 @@ export async function getAllAPIKeys() {
}
export async function deleteAPIKey(id: string) {
- return await asaw(
- prisma.aPIKeys.update({ where: { id }, data: { isDeleted: true } })
+ const user = await getCurrentUser();
+ throwIfError(!user, getMessage().UNAUTHORIZED_USER);
+
+ const [err, dbConfig] = await asaw(getDBConfigByUser(true));
+ throwIfError(err, err);
+ throwIfError(!dbConfig?.id, getMessage().DATABASE_CONFIG_NOT_FOUND);
+
+ const apiKey = await prisma.aPIKeys.findFirst({
+ where: {
+ id,
+ databaseConfigId: dbConfig.id,
+ isDeleted: false,
+ },
+ });
+
+ if (!apiKey) {
+ throw new Error("API key not found");
+ }
+
+ await prisma.aPIKeys.update(
+ { where: { id }, data: { isDeleted: true } }
);
+
+ return [null, { success: true }];
}
export async function hasAnyAPIKeys(): Promise<boolean> {
diff --git a/src/client/src/lib/platform/manage-dashboard/widget.ts b/src/client/src/lib/platform/manage-dashboard/widget.ts
index 33e0e65d..861b0901 100644
--- a/src/client/src/lib/platform/manage-dashboard/widget.ts
+++ b/src/client/src/lib/platform/manage-dashboard/widget.ts
@@ -155,6 +155,65 @@ export function deleteWidget(id: string) {
return dataCollector({ query }, "exec");
}
+function validateQuery(query: string): { valid: boolean; error?: string } {
+ const trimmed = query.trim();
+
+ if (!/^SELECT\b/i.test(trimmed)) {
+ return { valid: false, error: "Only SELECT queries are allowed" };
+ }
+
+ return validateSafeQueryContent(trimmed);
+}
+
+function validateSafeQueryContent(value: string): { valid: boolean; error?: string } {
+ if (/\bsystem\./i.test(value)) {
+ return { valid: false, error: "Access to system tables is not allowed" };
+ }
+
+ if (/\binformation_schema\./i.test(value)) {
+ return {
+ valid: false,
+ error: "Access to information_schema tables is not allowed",
+ };
+ }
+
+ const dangerousFunctions =
+ /\b(url|file|remote|mysql|jdbc|s3|hdfs|input|numbers_mt|generateRandom|clusterAllReplicas)\s*\(/i;
+ if (dangerousFunctions.test(value)) {
+ return { valid: false, error: "Query contains disallowed functions" };
+ }
+
+ const dangerousKeywords =
+ /\b(DROP|ALTER|TRUNCATE|INSERT|UPDATE|DELETE|CREATE|GRANT|REVOKE|INTO\s+OUTFILE|ATTACH|DETACH|RENAME|OPTIMIZE|SYSTEM)\b/i;
+ if (dangerousKeywords.test(value)) {
+ return { valid: false, error: "Query contains disallowed operations" };
+ }
+
+ return { valid: true };
+}
+
+function validateFilterValues(value: unknown): { valid: boolean; error?: string } {
+ if (typeof value === "string") {
+ return validateSafeQueryContent(value);
+ }
+
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const validation = validateFilterValues(item);
+ if (!validation.valid) return validation;
+ }
+ }
+
+ if (value && typeof value === "object") {
+ for (const item of Object.values(value)) {
+ const validation = validateFilterValues(item);
+ if (!validation.valid) return validation;
+ }
+ }
+
+ return { valid: true };
+}
+
export async function runWidgetQuery(
widgetId: string,
{
@@ -175,12 +234,22 @@ export async function runWidgetQuery(
? userQuery
: widget.config?.query || "";
+ const filterValidation = validateFilterValues(filter);
+ if (!filterValidation.valid) {
+ return { err: filterValidation.error || "Invalid filter" };
+ }
+
const exactQuery = mustache.render(query, { filter });
+ const validation = validateQuery(exactQuery);
+ if (!validation.valid) {
+ return { err: validation.error || "Invalid query" };
+ }
+
const { data, err } = await dataCollector({ query: exactQuery, enable_readonly: true });
if (err) {
- return { err: err || getMessage().WIDGET_RUN_FAILED };
+ return { err: "Query execution failed" };
}
return { data };
diff --git a/src/client/src/lib/platform/openground-clickhouse/migrate-data.ts b/src/client/src/lib/platform/openground-clickhouse/migrate-data.ts
index 8afabd62..b51cc5aa 100644
--- a/src/client/src/lib/platform/openground-clickhouse/migrate-data.ts
+++ b/src/client/src/lib/platform/openground-clickhouse/migrate-data.ts
@@ -94,8 +94,9 @@ export async function migrateOpengroundDataToClickhouse(
);
const stats: Stats = JSON.parse(record.stats);
- // Escape single quotes in string values for SQL
- const escapeString = (str: string) => str.replace(/'/g, "''");
+ // Escape string values before embedding them in ClickHouse literals.
+ const escapeString = (str: string) =>
+ str.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const promptEscaped = escapeString(requestMeta.prompt);
const createdAt = record.createdAt.toISOString().replace("T", " ").slice(0, 19);
@@ -192,7 +193,7 @@ export async function migrateOpengroundDataToClickhouse(
const providerName = escapeString(provider.provider);
const model = escapeString(evaluationData?.model || provider.config?.model || "unknown");
- const config = JSON.stringify(provider.config || {}).replace(/'/g, "''");
+ const config = escapeString(JSON.stringify(provider.config || {}));
const responseText = escapeString(evaluationData?.response || "");
const errorText = escapeString(error || "");
const cost = evaluationData?.cost || 0;
@@ -201,7 +202,7 @@ export async function migrateOpengroundDataToClickhouse(
const totalTokens = evaluationData?.totalTokens || (promptTokens + completionTokens);
const responseTime = evaluationData?.responseTime || 0;
const finishReason = escapeString(evaluationData?.finishReason || "");
- const providerResponse = JSON.stringify(response || {}).replace(/'/g, "''");
+ const providerResponse = escapeString(JSON.stringify(response || {}));
const providerInsertQuery = `
INSERT INTO ${OPENLIT_OPENGROUND_PROVIDERS_TABLE_NAME} (
diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.ts
index 168738e6..c0db6292 100644
--- a/src/client/src/lib/platform/request/index.ts
+++ b/src/client/src/lib/platform/request/index.ts
@@ -32,16 +32,20 @@ const ALLOWED_FIELD_GROUP_BY = new Set([
"StatusMessage",
]);
+function escapeClickHouseString(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
export function getGroupByExpression(groupBy: string): string | null {
if (groupBy in PREDEFINED_GROUP_BY) return PREDEFINED_GROUP_BY[groupBy];
const sep = groupBy.indexOf(":");
if (sep === -1) {
- const sanitized = groupBy.replace(/'/g, "''").trim();
+ const sanitized = escapeClickHouseString(groupBy).trim();
if (!sanitized) return null;
return `SpanAttributes['${sanitized}']`;
}
const attrType = groupBy.slice(0, sep);
- const key = groupBy.slice(sep + 1).replace(/'/g, "''").trim();
+ const key = escapeClickHouseString(groupBy.slice(sep + 1)).trim();
if (!key) return null;
if (attrType === "ResourceAttributes") return `ResourceAttributes['${key}']`;
if (attrType === "Field") {
diff --git a/src/client/src/lib/platform/vault/index.ts b/src/client/src/lib/platform/vault/index.ts
index 965513a1..fbfdb0f3 100644
--- a/src/client/src/lib/platform/vault/index.ts
+++ b/src/client/src/lib/platform/vault/index.ts
@@ -12,20 +12,57 @@ import { OPENLIT_VAULT_TABLE_NAME } from "./table-details";
import { dataCollector } from "../common";
import { jsonStringify } from "@/utils/json";
import { getAPIKeyInfo } from "../api-keys";
+import { decryptValue, encryptValue } from "@/utils/crypto";
+
+function escapeClickHouseString(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
+}
+
+function getOwnerEmailCondition(user: { email?: string | null }, alias?: string) {
+ const column = alias ? `${alias}.created_by` : "created_by";
+ return `${column} = '${escapeClickHouseString(user.email || "")}'`;
+}
+
+function decryptSecrets<T extends Record<string, any>>(secrets: T[]): T[] {
+ return secrets.map((secret) => ({
+ ...secret,
+ value:
+ typeof secret.value === "string"
+ ? decryptValue(secret.value)
+ : secret.value,
+ }));
+}
+
+export async function getSecretByName({
+ key,
+ createdBy,
+}: {
+ key: string;
+ createdBy?: string;
+}) {
+ const conditions = [
+ `key='${escapeClickHouseString(Sanitizer.sanitizeValue(key))}'`,
+ createdBy
+ ? `created_by = '${escapeClickHouseString(Sanitizer.sanitizeValue(createdBy))}'`
+ : "",
+ ].filter(Boolean);
-export async function getSecretByName({ key }: { key: string }) {
const query = `
- SELECT * FROM ${OPENLIT_VAULT_TABLE_NAME} WHERE key='${Sanitizer.sanitizeValue(
- key
- )}';
- `;
+ SELECT * FROM ${OPENLIT_VAULT_TABLE_NAME} WHERE ${conditions.join(" AND ")};
+ `;
const { data }: { data?: any } = await dataCollector({ query });
return data?.[0];
}
-export async function checkNameValidity({ key }: { key: string }) {
- const data = await getSecretByName({ key });
+export async function checkNameValidity({
+ key,
+ createdBy,
+}: {
+ key: string;
+ createdBy?: string;
+}) {
+ const data = await getSecretByName({ key, createdBy });
return { isValid: !data?.id };
}
@@ -39,23 +76,41 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {
const verifiedSecretObj = verifySecretInput(secretInput);
throwIfError(!verifiedSecretObj.success, verifiedSecretObj.err!);
+ const encryptedValue = secretInput.value
+ ? escapeClickHouseString(encryptValue(secretInput.value))
+ : undefined;
+ const ownerCondition = getOwnerEmailCondition(user!);
+ const ownerEmail = escapeClickHouseString(user!.email || "");
+
if (!secretInputParams.id) {
- const { isValid } = await checkNameValidity({ key: secretInput.key || "" });
+ const { isValid } = await checkNameValidity({
+ key: secretInput.key || "",
+ createdBy: user!.email || "",
+ });
throwIfError(!isValid, getMessage().SECRET_NAME_TAKEN);
}
if (secretInputParams.id) {
+ const secretId = escapeClickHouseString(
+ Sanitizer.sanitizeValue(secretInput.id || "")
+ );
const updateValues = [
- `updated_by = '${user!.email}'`,
- secretInput.key && "key = '" + secretInput.key + "'",
- secretInput.value && "value = '" + secretInput.value + "'",
- secretInput.tags && "tags = '" + jsonStringify(secretInput.tags) + "'",
+ `updated_by = '${ownerEmail}'`,
+ secretInput.key &&
+ "key = '" +
+ escapeClickHouseString(Sanitizer.sanitizeValue(secretInput.key)) +
+ "'",
+ encryptedValue && "value = '" + encryptedValue + "'",
+ secretInput.tags &&
+ "tags = '" +
+ escapeClickHouseString(jsonStringify(secretInput.tags)) +
+ "'",
];
const updateQuery = `
- ALTER TABLE ${OPENLIT_VAULT_TABLE_NAME}
- UPDATE
- ${updateValues.filter((e) => e).join(" , ")}
- WHERE id = '${secretInput.id}'`;
+ ALTER TABLE ${OPENLIT_VAULT_TABLE_NAME}
+ UPDATE
+ ${updateValues.filter((e) => e).join(" , ")}
+ WHERE id = '${secretId}' AND ${ownerCondition}`;
const { err, data } = await dataCollector(
{
query: updateQuery,
@@ -77,7 +132,7 @@ export async function upsertSecret(secretInputParams: Partial<SecretInput>) {
values: [
{
key: secretInput.key,
- value: secretInput.value,
+ value: encryptedValue || "",
tags: secretInput.tags,
created_by: user!.email,
},
@@ -103,10 +158,11 @@ export async function deleteSecret(secretIdParam: string) {
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
const secretId = Sanitizer.sanitizeValue(secretIdParam);
+ const ownerCondition = getOwnerEmailCondition(user!);
const { err } = await dataCollector(
{
- query: `DELETE FROM ${OPENLIT_VAULT_TABLE_NAME} WHERE id = '${secretId}';`,
+ query: `DELETE FROM ${OPENLIT_VAULT_TABLE_NAME} WHERE id = '${escapeClickHouseString(secretId)}' AND ${ownerCondition};`,
},
"exec"
);
@@ -122,16 +178,24 @@ export async function getSecrets(
filters: SecretGetFilters,
{ selectValue }: { selectValue?: boolean } = {}
) {
+ let user: Awaited<ReturnType<typeof getCurrentUser>> | null = null;
if (!filters.databaseConfigId) {
- const user = await getCurrentUser();
+ user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
}
const filteredConditions: string[] = [
- filters.key ? "v.key = '" + filters.key + "'" : "",
+ user ? getOwnerEmailCondition(user, "v") : "",
+ filters.key
+ ? "v.key = '" +
+ escapeClickHouseString(Sanitizer.sanitizeValue(filters.key)) +
+ "'"
+ : "",
filters.tags && filters.tags.length > 0
? `hasAny(JSONExtractArrayRaw(v.tags), ['"` +
- filters.tags.join(`"' , '"`) +
+ filters.tags
+ .map((tag) => escapeClickHouseString(Sanitizer.sanitizeValue(tag)))
+ .join(`"' , '"`) +
`"'])`
: "",
].filter((e) => !!e);
@@ -148,7 +212,16 @@ export async function getSecrets(
v.created_at DESC;
`;
- return await dataCollector({ query }, "query", filters.databaseConfigId);
+ const result = await dataCollector({ query }, "query", filters.databaseConfigId);
+
+ if (selectValue && result.data && Array.isArray(result.data)) {
+ return {
+ ...result,
+ data: decryptSecrets(result.data as any[]),
+ };
+ }
+
+ return result;
}
export async function getSecretsFromDatabaseId(
@@ -188,5 +261,14 @@ export async function getSecretById(
!!excludeVaultValue ? "EXCEPT value" : ""
} FROM ${OPENLIT_VAULT_TABLE_NAME} v WHERE v.id = '${id}';`;
- return await dataCollector({ query }, "query", databaseConfigId);
+ const result = await dataCollector({ query }, "query", databaseConfigId);
+
+ if (!excludeVaultValue && result.data && Array.isArray(result.data)) {
+ return {
+ ...result,
+ data: decryptSecrets(result.data as any[]),
+ };
+ }
+
+ return result;
}
diff --git a/src/client/src/lib/user.ts b/src/client/src/lib/user.ts
index 5c2d8634..c048c492 100644
--- a/src/client/src/lib/user.ts
+++ b/src/client/src/lib/user.ts
@@ -6,6 +6,11 @@ import { User } from "@prisma/client";
import { moveSharedDBConfigToDBUser } from "./db-config";
import { moveInvitationsToMembership } from "./organisation";
import getMessage from "@/constants/messages";
+import {
+ validateEmail,
+ validatePasswordComplexity,
+ validateProfileName,
+} from "@/utils/validation";
function exclude<User extends Record<string, unknown>, K extends keyof User>(
user: User,
@@ -36,7 +41,7 @@ export const getUserByEmail = async ({
},
});
- if (!user) throw new Error("No user with this email exists");
+ if (!user) throw new Error("Invalid email or password");
return exclude(user, selectPassword ? [] : undefined);
};
@@ -70,9 +75,18 @@ export const createNewUser = async (
},
options?: { selectPassword?: boolean }
) => {
- // Normalize email to lowercase for case-insensitive comparison
const normalizedEmail = email.toLowerCase().trim();
-
+
+ const emailValidation = validateEmail(normalizedEmail);
+ if (!emailValidation.valid) {
+ throw new Error(emailValidation.error || "Invalid email");
+ }
+
+ const passwordValidation = validatePasswordComplexity(password);
+ if (!passwordValidation.valid) {
+ throw new Error(passwordValidation.error || "Password too weak");
+ }
+
const [, existingUser] = await asaw(getUserByEmail({ email: normalizedEmail }));
if (existingUser) throw new Error("User already exists! Please signin!");
@@ -128,6 +142,11 @@ export const updateUserProfile = async ({
if (newPassword) {
if (!currentPassword)
throw new Error("Provide current password to update it to new one!");
+
+ const passwordValidation = validatePasswordComplexity(newPassword);
+ if (!passwordValidation.valid)
+ throw new Error(passwordValidation.error || "Password too weak");
+
const passwordsMatch = await doesPasswordMatches(
currentPassword,
user.password || ""
@@ -137,6 +156,10 @@ export const updateUserProfile = async ({
}
if (name) {
+ const nameValidation = validateProfileName(name);
+ if (!nameValidation.valid)
+ throw new Error(nameValidation.error || "Invalid name");
+
updatedUserObject.name = name;
}
diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.ts
index 5cafaa29..8cb1165d 100644
--- a/src/client/src/middleware.ts
+++ b/src/client/src/middleware.ts
@@ -1,8 +1,10 @@
import { chain } from "@/middleware/chain";
import checkAuth from "@/middleware/check-auth";
+import checkCsrf from "@/middleware/check-csrf";
import checkDemoAccount from "@/middleware/check-demo-account";
export const middleware = chain([
+ checkCsrf,
checkDemoAccount,
// @ts-expect-error Type 'NextMiddlewareWithAuth' is not assignable to type 'NextMiddleware'.
checkAuth,
diff --git a/src/client/src/middleware/check-csrf.ts b/src/client/src/middleware/check-csrf.ts
new file mode 100644
index 00000000..649c9de8
--- /dev/null
+++ b/src/client/src/middleware/check-csrf.ts
@@ -0,0 +1,50 @@
+import { NextFetchEvent, NextMiddleware, NextResponse } from "next/server";
+import type { NextRequest } from "next/server";
+import {
+ ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN,
+ ALLOWED_OPENLIT_ROUTE_PREFIXES_WITHOUT_TOKEN,
+ CRON_JOB_ROUTES,
+} from "@/constants/route";
+
+const STATE_CHANGING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
+
+function isExemptPath(pathname: string) {
+ return (
+ pathname.startsWith("/api/auth/") ||
+ ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN.includes(pathname) ||
+ ALLOWED_OPENLIT_ROUTE_PREFIXES_WITHOUT_TOKEN.some((prefix) =>
+ pathname.startsWith(prefix)
+ ) ||
+ CRON_JOB_ROUTES.includes(pathname)
+ );
+}
+
+function isSameOrigin(request: NextRequest) {
+ const origin = request.headers.get("origin");
+ const host = request.headers.get("host");
+
+ if (!origin || !host) return false;
+
+ try {
+ return new URL(origin).host === host;
+ } catch {
+ return false;
+ }
+}
+
+export default function checkCsrf(next: NextMiddleware) {
+ return async (request: NextRequest, event: NextFetchEvent) => {
+ const { pathname } = request.nextUrl;
+
+ if (
+ STATE_CHANGING_METHODS.has(request.method.toUpperCase()) &&
+ pathname.startsWith("/api/") &&
+ !isExemptPath(pathname) &&
+ !isSameOrigin(request)
+ ) {
+ return NextResponse.json("Forbidden", { status: 403 });
+ }
+
+ return next(request, event);
+ };
+}
diff --git a/src/client/src/utils/api-response.ts b/src/client/src/utils/api-response.ts
new file mode 100644
index 00000000..e59f616f
--- /dev/null
+++ b/src/client/src/utils/api-response.ts
@@ -0,0 +1,9 @@
+import { sanitizeErrorMessage } from "@/utils/validation";
+
+export function errorResponse(
+ err: unknown,
+ fallback: string = "An unexpected error occurred",
+ status: number = 400
+): Response {
+ return Response.json(sanitizeErrorMessage(err, fallback), { status });
+}
diff --git a/src/client/src/utils/crypto.ts b/src/client/src/utils/crypto.ts
new file mode 100644
index 00000000..f8523855
--- /dev/null
+++ b/src/client/src/utils/crypto.ts
@@ -0,0 +1,81 @@
+import {
+ createHash,
+ randomBytes,
+ createCipheriv,
+ createDecipheriv,
+ type CipherGCMTypes,
+} from "crypto";
+
+const ALGORITHM: CipherGCMTypes = "aes-256-gcm";
+const IV_LENGTH = 16;
+const ENCRYPTED_PREFIX = "enc:v1:";
+
+function getEncryptionKey(): Uint8Array {
+ const secret =
+ process.env.OPENLIT_VAULT_ENCRYPTION_KEY ||
+ process.env.NEXTAUTH_SECRET;
+
+ if (!secret) {
+ throw new Error(
+ "No encryption key configured. Set OPENLIT_VAULT_ENCRYPTION_KEY or NEXTAUTH_SECRET."
+ );
+ }
+
+ const buf = createHash("sha256").update(secret).digest();
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+}
+
+function toUint8Array(buf: Buffer): Uint8Array {
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+}
+
+export function encryptValue(plaintext: string): string {
+ if (!plaintext) return plaintext;
+ if (plaintext.startsWith(ENCRYPTED_PREFIX)) return plaintext;
+
+ const key = getEncryptionKey();
+ const ivBuf = randomBytes(IV_LENGTH);
+ const cipher = createCipheriv(ALGORITHM, key, toUint8Array(ivBuf));
+
+ let encrypted = cipher.update(plaintext, "utf8", "base64");
+ encrypted += cipher.final("base64");
+
+ const authTag = cipher.getAuthTag();
+
+ return `${ENCRYPTED_PREFIX}${ivBuf.toString("base64")}:${authTag.toString("base64")}:${encrypted}`;
+}
+
+export function decryptValue(encryptedValue: string): string {
+ if (!encryptedValue) return encryptedValue;
+ if (!encryptedValue.startsWith(ENCRYPTED_PREFIX)) return encryptedValue;
+
+ try {
+ const withoutPrefix = encryptedValue.slice(ENCRYPTED_PREFIX.length);
+ const parts = withoutPrefix.split(":");
+
+ if (parts.length !== 3) {
+ console.error("Invalid encrypted value format");
+ return encryptedValue;
+ }
+
+ const [ivBase64, authTagBase64, ciphertextBase64] = parts;
+ const decipher = createDecipheriv(
+ ALGORITHM,
+ getEncryptionKey(),
+ toUint8Array(Buffer.from(ivBase64, "base64"))
+ );
+ decipher.setAuthTag(toUint8Array(Buffer.from(authTagBase64, "base64")));
+
+ let decrypted = decipher.update(ciphertextBase64, "base64", "utf8");
+ decrypted += decipher.final("utf8");
+
+ return decrypted;
+ } catch (error) {
+ console.error("Decryption failed, returning raw value:", error);
+ return encryptedValue;
+ }
+}
+
+export function isEncrypted(value: string): boolean {
+ return !!value && value.startsWith(ENCRYPTED_PREFIX);
+}
diff --git a/src/client/src/utils/string.ts b/src/client/src/utils/string.ts
index e11f7c74..7c4416ed 100644
--- a/src/client/src/utils/string.ts
+++ b/src/client/src/utils/string.ts
@@ -1,3 +1,26 @@
export const unescapeString = (str: string) => str.replace(/\\n/g, "\n");
export const convertToTitleCase = (str: string) => str.replace(/_|-/g, " ").replace(/\b\w/g, char => char.toUpperCase());
+
+export const escapeHtml = (str: string) =>
+ str.replace(/[&<>"'`]/g, (char) => {
+ switch (char) {
+ case "&":
+ return "&amp;";
+ case "<":
+ return "&lt;";
+ case ">":
+ return "&gt;";
+ case '"':
+ return "&quot;";
+ case "'":
+ return "&#39;";
+ case "`":
+ return "&#96;";
+ default:
+ return char;
+ }
+ });
+
+export const escapeEmailForDisplay = (email?: string | null) =>
+ email ? escapeHtml(email) : "";
diff --git a/src/client/src/utils/validation.ts b/src/client/src/utils/validation.ts
new file mode 100644
index 00000000..3a0a4808
--- /dev/null
+++ b/src/client/src/utils/validation.ts
@@ -0,0 +1,241 @@
+import net from "net";
+
+export function validateDatabaseHost(host: string): {
+ valid: boolean;
+ error?: string;
+} {
+ if (!host || typeof host !== "string") {
+ return { valid: false, error: "Host is required" };
+ }
+
+ const trimmed = host.trim();
+
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
+ return { valid: false, error: "Host must not contain a URL scheme" };
+ }
+
+ if (/^\d+$/.test(trimmed) && !trimmed.includes(".")) {
+ return { valid: false, error: "Numeric IP encoding is not allowed" };
+ }
+
+ if (/^0x[0-9a-fA-F]+$/i.test(trimmed)) {
+ return { valid: false, error: "Hex-encoded IP addresses are not allowed" };
+ }
+
+ if (/^0\d+\./.test(trimmed)) {
+ return {
+ valid: false,
+ error: "Octal-encoded IP addresses are not allowed",
+ };
+ }
+
+ const hostPart = trimmed.replace(/:\d+$/, "");
+
+ if (net.isIP(hostPart)) {
+ if (!isAllowedIP(hostPart)) {
+ return {
+ valid: false,
+ error: "Private, loopback, and link-local IP addresses are not allowed",
+ };
+ }
+
+ return { valid: true };
+ }
+
+ if (/^\[.*\]/.test(hostPart)) {
+ const ipv6 = hostPart.slice(1, hostPart.indexOf("]")).toLowerCase();
+ if (
+ ipv6 === "::1" ||
+ ipv6.startsWith("fe80:") ||
+ ipv6.startsWith("fc00:") ||
+ ipv6.startsWith("fd")
+ ) {
+ return {
+ valid: false,
+ error: "Private, loopback, and link-local IP addresses are not allowed",
+ };
+ }
+ }
+
+ const lowerHost = hostPart.toLowerCase();
+ const blockedHosts = [
+ "localhost",
+ "metadata.google.internal",
+ "169.254.169.254",
+ ];
+
+ if (blockedHosts.includes(lowerHost)) {
+ return { valid: false, error: `Host "${hostPart}" is not allowed` };
+ }
+
+ if (!/^[a-zA-Z0-9._\[\]:-]+$/.test(trimmed)) {
+ return { valid: false, error: "Host contains invalid characters" };
+ }
+
+ return { valid: true };
+}
+
+function isAllowedIP(ip: string): boolean {
+ const parts = ip.split(".").map(Number);
+ if (parts.length !== 4) return true;
+
+ if (parts[0] === 127) return false;
+ if (parts[0] === 10) return false;
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return false;
+ if (parts[0] === 192 && parts[1] === 168) return false;
+ if (parts[0] === 169 && parts[1] === 254) return false;
+ if (parts.every((part) => part === 0)) return false;
+
+ return true;
+}
+
+export function validateProfileName(name: string): {
+ valid: boolean;
+ error?: string;
+} {
+ if (!name || typeof name !== "string") {
+ return { valid: false, error: "Name is required" };
+ }
+
+ if (name.length > 100) {
+ return { valid: false, error: "Name must be 100 characters or fewer" };
+ }
+
+ if (/<[^>]*>/.test(name)) {
+ return { valid: false, error: "Name must not contain HTML tags" };
+ }
+
+ return { valid: true };
+}
+
+export function validateEmail(email: string): {
+ valid: boolean;
+ error?: string;
+} {
+ if (!email || typeof email !== "string") {
+ return { valid: false, error: "Email is required" };
+ }
+
+ const trimmed = email.trim();
+
+ if (trimmed.length > 254) {
+ return { valid: false, error: "Email is too long" };
+ }
+
+ if (/[<>"'`&]/.test(trimmed)) {
+ return { valid: false, error: "Email contains invalid characters" };
+ }
+
+ const parts = trimmed.split("@");
+ if (parts.length !== 2) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ const [localPart, domain] = parts;
+
+ if (
+ localPart.length === 0 ||
+ localPart.length > 64 ||
+ localPart.startsWith(".") ||
+ localPart.endsWith(".") ||
+ localPart.includes("..")
+ ) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ if (!/^[A-Za-z0-9.!#$%*+/=?^_{|}~-]+$/.test(localPart)) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ if (domain.length === 0 || domain.length > 253 || domain.includes("..")) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ const labels = domain.split(".");
+ if (labels.length < 2) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ const labelRegex = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
+ if (!labels.every((label) => labelRegex.test(label))) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ const tld = labels[labels.length - 1];
+ if (!/^[A-Za-z]{2,63}$/.test(tld)) {
+ return { valid: false, error: "Invalid email format" };
+ }
+
+ return { valid: true };
+}
+
+export function validatePasswordComplexity(password: string): {
+ valid: boolean;
+ error?: string;
+} {
+ if (!password || typeof password !== "string") {
+ return { valid: false, error: "Password is required" };
+ }
+
+ if (password.length < 8) {
+ return { valid: false, error: "Password must be at least 8 characters long" };
+ }
+
+ if (password.length > 128) {
+ return { valid: false, error: "Password must be 128 characters or fewer" };
+ }
+
+ if (!/[A-Z]/.test(password)) {
+ return { valid: false, error: "Password must contain at least one uppercase letter" };
+ }
+
+ if (!/[a-z]/.test(password)) {
+ return { valid: false, error: "Password must contain at least one lowercase letter" };
+ }
+
+ if (!/[0-9]/.test(password)) {
+ return { valid: false, error: "Password must contain at least one number" };
+ }
+
+ return { valid: true };
+}
+
+export function sanitizeErrorMessage(
+ err: unknown,
+ fallback: string = "An unexpected error occurred"
+): string {
+ if (!err) return fallback;
+
+ const message = typeof err === "string" ? err : (err as Error)?.message;
+ if (!message) return fallback;
+
+ if (
+ message.includes("PrismaClient") ||
+ message.includes("prisma.") ||
+ message.includes("invocation:")
+ ) {
+ return fallback;
+ }
+
+ if (
+ message.includes("/etc/clickhouse") ||
+ message.includes("clickhouse-server") ||
+ message.includes("password is incorrect")
+ ) {
+ return "Database connection error";
+ }
+
+ if (message.includes(" at ") || message.includes("TypeError:")) {
+ return fallback;
+ }
+
+ if (
+ message.includes("/Users/") ||
+ message.includes("/home/") ||
+ message.includes("/etc/")
+ ) {
+ return fallback;
+ }
+
+ return message;
+}