Skip to content

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

feat(client): add API key feature-access extension points (#1699)

Aman Agarwalbed4fdb9f0be
diff --git a/docs/docs.json b/docs/docs.json
index 8aff6277..2ec3d2a5 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -311,6 +311,7 @@
"pages": [
"latest/openlit/developer-resources/api-reference/endpoint/api-keys/create",
"latest/openlit/developer-resources/api-reference/endpoint/api-keys/get",
+ "latest/openlit/developer-resources/api-reference/endpoint/api-keys/update",
"latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete"
]
},
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/api-keys.yml b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/api-keys.yml
new file mode 100644
index 00000000..475f7e3d
--- /dev/null
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/api-keys.yml
@@ -0,0 +1,261 @@
+openapi: 3.0.0
+info:
+ title: API Keys API
+ description: >-
+ Create, list, update the feature access of, and delete OpenLIT API keys.
+ These endpoints require a signed-in OpenLIT session; Bearer API keys are
+ rejected with `403`, so a key can't list, create, change, or delete keys.
+ version: 1.0.0
+servers:
+ - url: http://localhost:3000
+paths:
+ /api/api-key:
+ get:
+ summary: List API Keys
+ description: >-
+ Lists the API keys for the current database configuration. Only a
+ preview of each key is returned.
+ operationId: listApiKeys
+ responses:
+ '200':
+ description: API keys for the database configuration.
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/ApiKey'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ security:
+ - sessionAuth: []
+ post:
+ summary: Create API Key
+ description: >-
+ Creates an API key for the current database configuration. The full key
+ is returned only in this response. Omit `scopes` for a full-access key.
+ Restricting a key with `scopes` requires OpenLIT Enterprise with
+ role-based access control; the community edition ignores `scopes` and
+ always creates full-access keys. Requires a signed-in session.
+ operationId: createApiKey
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - name
+ properties:
+ name:
+ type: string
+ minLength: 3
+ example: production-sdk
+ scopes:
+ description: >-
+ Features the key may use. Omit for full access. Must contain
+ at least one feature when provided.
+ type: array
+ minItems: 1
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ example: ["ingest", "prompts"]
+ responses:
+ '200':
+ description: The created key, including the secret value.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: string
+ example: cmuybwm0s0051dmipjv6jd3hm
+ apiKey:
+ type: string
+ description: The secret key. Shown only once.
+ example: openlit-3kJ9…
+ databaseConfigId:
+ type: string
+ organisationId:
+ type: string
+ nullable: true
+ projectId:
+ type: string
+ nullable: true
+ environment:
+ type: string
+ example: production
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ security:
+ - sessionAuth: []
+ /api/api-key/{id}:
+ patch:
+ summary: Update API Key Access
+ description: >-
+ Changes which features an existing key can use. Send `scopes: null` for
+ full access or a list of features to restrict the key. Changes apply to
+ API requests immediately. Requires OpenLIT Enterprise with role-based
+ access control and a signed-in session; an API key cannot change its own
+ access. The community edition responds with `403`.
+ operationId: updateApiKeyAccess
+ parameters:
+ - $ref: '#/components/parameters/ApiKeyId'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - scopes
+ properties:
+ scopes:
+ description: '`null` for full access, or the features the key may use.'
+ type: array
+ nullable: true
+ minItems: 1
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ example: ["prompts", "vault"]
+ responses:
+ '200':
+ description: The key's updated access.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: string
+ scopes:
+ type: array
+ nullable: true
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ description: No signed-in user. Key access can't be changed with an API key.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '404':
+ description: No such key in the current database configuration.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ security:
+ - sessionAuth: []
+ delete:
+ summary: Delete API Key
+ description: >-
+ Revokes an API key. Applications using it stop authenticating
+ immediately. Requires a signed-in session.
+ operationId: deleteApiKey
+ parameters:
+ - $ref: '#/components/parameters/ApiKeyId'
+ responses:
+ '200':
+ description: The key was deleted.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ security:
+ - sessionAuth: []
+components:
+ parameters:
+ ApiKeyId:
+ name: id
+ in: path
+ required: true
+ description: The API key ID (not the secret value).
+ schema:
+ type: string
+ schemas:
+ ApiKeyScope:
+ type: string
+ description: >-
+ A feature an API key can use: `ingest` (OTLP telemetry ingestion),
+ `telemetry` (`/api/telemetry/*`, `/api/metrics/*`), `prompts`
+ (`/api/prompt/*`), `vault` (`/api/vault/*`), `rule_engine`
+ (`/api/rule-engine/*`), `evaluation` (`/api/evaluation/*`), `chat`
+ (`/api/chat/*`), `controller` (`/api/controller/*`), `db_config`
+ (`/api/db-config*`).
+ enum:
+ - ingest
+ - telemetry
+ - prompts
+ - vault
+ - rule_engine
+ - evaluation
+ - chat
+ - controller
+ - db_config
+ ApiKey:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ apiKeyPreview:
+ type: string
+ example: openlit-3kJ9…x7Qp2A
+ createdAt:
+ type: string
+ format: date-time
+ createdByUser:
+ type: object
+ properties:
+ email:
+ type: string
+ scopes:
+ description: '`null` for full access, otherwise the features the key may use.'
+ type: array
+ nullable: true
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ Error:
+ type: object
+ properties:
+ error:
+ type: string
+ responses:
+ BadRequest:
+ description: Invalid JSON, an invalid name, or an invalid list of features.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ Forbidden:
+ description: >-
+ The request used a Bearer API key, the caller lacks the required
+ permission, the edition or license doesn't support restricting keys, or
+ the caller's role doesn't include a requested feature.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ securitySchemes:
+ sessionAuth:
+ type: apiKey
+ in: cookie
+ name: next-auth.session-token
+ description: Signed-in OpenLIT browser session.
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create.mdx b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create.mdx
index cce6cecf..aafdec24 100644
--- a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create.mdx
@@ -1,4 +1,5 @@
---
title: 'Create API Key'
-openapi: 'POST /api/keys'
----
\ No newline at end of file
+description: 'Create an OpenLIT API key, optionally restricted to specific features in OpenLIT Enterprise.'
+openapi: 'POST /api/api-key'
+---
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete.mdx b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete.mdx
index fbb9e963..fcd74e7d 100644
--- a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete.mdx
@@ -1,4 +1,5 @@
---
title: 'Delete API Key'
-openapi: 'DELETE /api/keys'
----
\ No newline at end of file
+description: 'Revoke an OpenLIT API key.'
+openapi: 'DELETE /api/api-key/{id}'
+---
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/get.mdx b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/get.mdx
index 0652d29d..cce9b995 100644
--- a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/get.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/get.mdx
@@ -1,4 +1,5 @@
---
-title: 'Get API Key'
-openapi: 'GET /api/keys'
+title: 'List API Keys'
+description: 'List the API keys for the current database configuration, with each key's access.'
+openapi: 'GET /api/api-key'
---
diff --git a/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/update.mdx b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/update.mdx
new file mode 100644
index 00000000..fb08f8ec
--- /dev/null
+++ b/docs/latest/openlit/developer-resources/api-reference/endpoint/api-keys/update.mdx
@@ -0,0 +1,5 @@
+---
+title: 'Update API Key Access'
+description: 'Change which features an API key can use (OpenLIT Enterprise).'
+openapi: 'PATCH /api/api-key/{id}'
+---
diff --git a/docs/latest/openlit/developer-resources/api-reference/introduction.mdx b/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
index 88defe79..8f58d692 100644
--- a/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
@@ -33,6 +33,12 @@ description: 'OpenAPI specification for API Endpoints in OpenLIT'
href="/latest/openlit/developer-resources/api-reference/endpoint/scanners/scan"
>
</Card>
+ <Card
+ title="API Keys API"
+ icon="key"
+ href="/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create"
+ >
+ </Card>
</CardGroup>
## Product surfaces
@@ -74,3 +80,24 @@ Authorization: Bearer <api-key>
```
[Manage Models](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/models) UI pages also accept a signed-in OpenLIT session in the browser. The [public pricing export](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/public-pricing) requires no auth.
+
+## API key access
+
+Create and manage keys under **Settings → API Keys**. Each key shows its access in the **Access** column.
+
+- **Community edition:** every API key has full access to every endpoint that accepts API keys.
+- **OpenLIT Enterprise:** with role-based access control, a key can be restricted to specific features when it's created, or later with **Edit access**. A restricted key gets a `403` (`This API key does not have access to this feature`) on endpoints outside its features, and OTLP ingestion needs the **Telemetry ingestion** feature.
+
+| Feature | Endpoints |
+| --- | --- |
+| Telemetry ingestion (`ingest`) | OTLP `/v1/traces`, `/v1/metrics`, `/v1/logs` |
+| Telemetry & metrics read (`telemetry`) | `/api/telemetry/*`, `/api/metrics/*` |
+| Prompt Hub (`prompts`) | `/api/prompt/*` |
+| Vault (`vault`) | `/api/vault/*` |
+| Rule engine (`rule_engine`) | `/api/rule-engine/*` |
+| Evaluations (`evaluation`) | `/api/evaluation/*` |
+| Otter chat (`chat`) | `/api/chat/*` |
+| Controller (`controller`) | `/api/controller/*` |
+| Database config (`db_config`) | `/api/db-config*` |
+
+Use [Create API Key](/latest/openlit/developer-resources/api-reference/endpoint/api-keys/create) and [Update API Key Access](/latest/openlit/developer-resources/api-reference/endpoint/api-keys/update) to manage access programmatically. API key management (`/api/api-key`) requires a signed-in session, so an API key can't list, create, change, or delete keys, including its own.
diff --git a/src/client/public/openapi.yaml b/src/client/public/openapi.yaml
index 53ec8203..82773a55 100644
--- a/src/client/public/openapi.yaml
+++ b/src/client/public/openapi.yaml
@@ -30,7 +30,9 @@ info:
## Authentication
- All documented endpoints require Bearer API key auth (`ApiKeyAuth`).
+ All documented endpoints require Bearer API key auth (`ApiKeyAuth`), except
+ API key management (`/api/api-key`), which requires a signed-in session
+ (`SessionAuth`) so a key can't list, create, change, or delete keys.
version: 1.29.0
servers:
- url: http://localhost:3000
@@ -617,13 +619,12 @@ paths:
tags:
- API Keys
summary: List all API Keys
- description: Retrieve all API keys associated with the user's active database configuration.
+ description: >-
+ Retrieve the API keys for the user's active database configuration,
+ with a preview of each key and its access. Requires a signed-in
+ session; Bearer API keys are rejected with `403`.
security:
- - ApiKeyAuth: []
- parameters:
- - $ref: '#/components/parameters/OpenLitOrganisationId'
- - $ref: '#/components/parameters/OpenLitProjectId'
- - $ref: '#/components/parameters/OpenLitEnvironment'
+ - SessionAuth: []
responses:
'200':
description: A list of API Keys.
@@ -633,17 +634,20 @@ paths:
type: array
items:
$ref: '#/components/schemas/ApiKey'
+ '403':
+ description: Bearer API keys can't manage API keys, or the user lacks permission.
post:
tags:
- API Keys
summary: Generate an API Key
- description: Create a new API key prefixed with `openlit-` linked to the active database configuration.
+ description: >-
+ Create a new API key prefixed with `openlit-` linked to the active
+ database configuration. Omit `scopes` for full access. Restricting a
+ key with `scopes` requires OpenLIT Enterprise with role-based access
+ control; the community edition ignores `scopes`. Requires a signed-in
+ session.
security:
- - ApiKeyAuth: []
- parameters:
- - $ref: '#/components/parameters/OpenLitOrganisationId'
- - $ref: '#/components/parameters/OpenLitProjectId'
- - $ref: '#/components/parameters/OpenLitEnvironment'
+ - SessionAuth: []
requestBody:
required: true
content:
@@ -656,35 +660,112 @@ paths:
name:
type: string
example: my-sdk-key
+ scopes:
+ description: Features the key may use. Omit for full access.
+ type: array
+ minItems: 1
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ example: ["ingest", "prompts"]
responses:
'200':
- description: API key created successfully.
+ description: API key created successfully. The key is shown only once.
content:
application/json:
schema:
type: object
properties:
+ id:
+ type: string
apiKey:
type: string
example: openlit-uHpx834Jsa...
databaseConfigId:
type: string
example: db-config-id
+ organisationId:
+ type: string
+ nullable: true
+ projectId:
+ type: string
+ nullable: true
+ environment:
+ type: string
+ example: production
'400':
- description: Bad Request.
+ description: Invalid JSON, an invalid name, or an invalid list of features.
+ '403':
+ description: >-
+ Bearer API keys can't manage API keys, the user lacks permission, or
+ the edition/license or the user's role doesn't allow the requested access.
/api/api-key/{id}:
+ patch:
+ tags:
+ - API Keys
+ summary: Update API Key access
+ description: >-
+ Change which features an existing key can use. Send `scopes: null` for
+ full access or a list of features to restrict the key. Requires OpenLIT
+ Enterprise with role-based access control and a signed-in session; the
+ community edition responds with `403`.
+ security:
+ - SessionAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Path parameter. API key ID to update.
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - scopes
+ properties:
+ scopes:
+ description: '`null` for full access, or the features the key may use.'
+ type: array
+ nullable: true
+ minItems: 1
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ example: ["prompts", "vault"]
+ responses:
+ '200':
+ description: The key's updated access.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: string
+ scopes:
+ type: array
+ nullable: true
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+ '400':
+ description: Invalid JSON or an invalid list of features.
+ '401':
+ description: No signed-in user.
+ '403':
+ description: Not available in this edition or license, or the user lacks permission.
+ '404':
+ description: No such key in the active database configuration.
delete:
tags:
- API Keys
summary: Delete an API Key
- description: Mark an API key as deleted.
+ description: Mark an API key as deleted. Requires a signed-in session.
security:
- - ApiKeyAuth: []
+ - SessionAuth: []
parameters:
- - $ref: '#/components/parameters/OpenLitOrganisationId'
- - $ref: '#/components/parameters/OpenLitProjectId'
- - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
@@ -1601,6 +1682,11 @@ components:
Required. Bearer token format (`Authorization: Bearer openlit-...`).
The key binds a database configuration; clients do not need to send
`x-openlit-database-config-id`.
+ SessionAuth:
+ type: apiKey
+ in: cookie
+ name: next-auth.session-token
+ description: Signed-in OpenLIT browser session.
schemas:
TimeLimit:
@@ -1714,11 +1800,43 @@ components:
type: string
name:
type: string
- apiKey:
+ apiKeyPreview:
type: string
+ example: openlit-uHpx…x7Qp2A
createdAt:
type: string
format: date-time
+ createdByUser:
+ type: object
+ properties:
+ email:
+ type: string
+ scopes:
+ description: '`null` for full access, otherwise the features the key may use.'
+ type: array
+ nullable: true
+ items:
+ $ref: '#/components/schemas/ApiKeyScope'
+
+ ApiKeyScope:
+ type: string
+ description: >-
+ A feature an API key can use: `ingest` (OTLP telemetry ingestion),
+ `telemetry` (`/api/telemetry/*`, `/api/metrics/*`), `prompts`
+ (`/api/prompt/*`), `vault` (`/api/vault/*`), `rule_engine`
+ (`/api/rule-engine/*`), `evaluation` (`/api/evaluation/*`), `chat`
+ (`/api/chat/*`), `controller` (`/api/controller/*`), `db_config`
+ (`/api/db-config*`).
+ enum:
+ - ingest
+ - telemetry
+ - prompts
+ - vault
+ - rule_engine
+ - evaluation
+ - chat
+ - controller
+ - db_config
OfflineEvaluationInput:
type: object
diff --git a/src/client/src/__tests__/app/api/api-key/route.test.ts b/src/client/src/__tests__/app/api/api-key/route.test.ts
new file mode 100644
index 00000000..78afbb41
--- /dev/null
+++ b/src/client/src/__tests__/app/api/api-key/route.test.ts
@@ -0,0 +1,45 @@
+jest.mock("@/lib/platform/api-keys/index", () => ({
+ generateAPIKey: jest.fn(),
+ getAllAPIKeys: jest.fn(),
+ deleteAPIKey: jest.fn(),
+}));
+
+import { POST } from "@/app/api/api-key/route";
+import { PATCH } from "@/app/api/api-key/[id]/route";
+import { generateAPIKey } from "@/lib/platform/api-keys/index";
+
+function jsonRequest(body: unknown) {
+ const raw = typeof body === "string" ? body : JSON.stringify(body);
+ return { json: async () => JSON.parse(raw) } as unknown as Request;
+}
+
+describe("API key routes (community edition)", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (generateAPIKey as jest.Mock).mockResolvedValue({ id: "key-1" });
+ });
+
+ it("rejects invalid JSON on create", async () => {
+ const res = await POST(jsonRequest("{not json"));
+ expect(res.status).toBe(400);
+ expect(generateAPIKey).not.toHaveBeenCalled();
+ });
+
+ it("creates a full-access key and ignores requested scopes", async () => {
+ const res = await POST(jsonRequest({ name: "sdk", scopes: ["prompts"] }));
+ expect(res.status).toBe(200);
+ expect(generateAPIKey).toHaveBeenCalledWith("sdk", {});
+ });
+
+ it("does not support editing key access", async () => {
+ const res = await PATCH(jsonRequest({ scopes: ["prompts"] }), {
+ params: { id: "key-1" },
+ });
+ expect(res.status).toBe(403);
+ });
+
+ it("rejects invalid JSON on access update", async () => {
+ const res = await PATCH(jsonRequest("{not json"), { params: { id: "key-1" } });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/client/src/__tests__/app/api/auth/verify-key/route.test.ts b/src/client/src/__tests__/app/api/auth/verify-key/route.test.ts
index 9b7d8038..e5e1f3a7 100644
--- a/src/client/src/__tests__/app/api/auth/verify-key/route.test.ts
+++ b/src/client/src/__tests__/app/api/auth/verify-key/route.test.ts
@@ -11,8 +11,13 @@ jest.mock("@/lib/platform/api-keys", () => ({
getAPIKeyInfo: jest.fn(),
}));
+jest.mock("@/lib/platform/api-key-access/server", () => ({
+ getApiKeyScopes: jest.fn(async () => null),
+}));
+
import { GET } from "@/app/api/auth/verify-key/route";
import { getAPIKeyInfo } from "@/lib/platform/api-keys";
+import { getApiKeyScopes } from "@/lib/platform/api-key-access/server";
function makeRequest(headers: Record<string, string> = {}) {
return {
@@ -54,6 +59,24 @@ describe("GET /api/auth/verify-key", () => {
organisationId: "org-1",
projectId: "proj-1",
environment: "staging",
+ scopes: null,
+ });
+ });
+
+ it("returns the key's feature scopes when it is restricted", async () => {
+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([
+ null,
+ { id: "key-1", databaseConfigId: "db-1" },
+ ]);
+ (getApiKeyScopes as jest.Mock).mockResolvedValueOnce(["prompts"]);
+
+ const res = await GET(
+ makeRequest({ Authorization: "Bearer openlit-test" })
+ );
+ expect(getApiKeyScopes).toHaveBeenCalledWith("key-1");
+ await expect(res.json()).resolves.toMatchObject({
+ valid: true,
+ scopes: ["prompts"],
});
});
diff --git a/src/client/src/__tests__/constants/route.test.ts b/src/client/src/__tests__/constants/route.test.ts
index a8b9902e..ac33f9da 100644
--- a/src/client/src/__tests__/constants/route.test.ts
+++ b/src/client/src/__tests__/constants/route.test.ts
@@ -30,13 +30,15 @@ describe('ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN', () => {
});
describe('ALLOWED_OPENLIT_ROUTES_WITH_TOKEN', () => {
- it('includes API key and db-config routes for Bearer auth', () => {
- expect(ALLOWED_OPENLIT_ROUTES_WITH_TOKEN).toContain('/api/api-key');
+ it('includes the db-config route for Bearer auth', () => {
expect(ALLOWED_OPENLIT_ROUTES_WITH_TOKEN).toContain('/api/db-config');
});
- it('includes API key prefix for delete-by-id', () => {
- expect(ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN).toContain('/api/api-key/');
+ // API key management is session-only: a Bearer key must not list,
+ // create, change, or delete keys (including its own).
+ it('does not allow Bearer auth on API key management routes', () => {
+ expect(ALLOWED_OPENLIT_ROUTES_WITH_TOKEN).not.toContain('/api/api-key');
+ expect(ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN).not.toContain('/api/api-key/');
});
it('allows Bearer poll but not unauthenticated poll or a controller prefix', () => {
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 0fd22fbd..a0dbafe1 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
@@ -25,6 +25,9 @@ jest.mock('@/lib/organisation', () => ({
jest.mock('@/lib/billing/usage-recorder', () => ({
recordOrganisationUsageEvent: jest.fn(),
}));
+jest.mock('@/lib/platform/api-key-access/server', () => ({
+ getApiKeyScopesByIds: jest.fn(async () => ({})),
+}));
jest.mock('@/utils/asaw', () => jest.fn());
jest.mock('@/utils/error', () => ({
throwIfError: jest.fn((condition: boolean, msg: string) => {
@@ -135,7 +138,7 @@ describe('getAllAPIKeys', () => {
const result = await getAllAPIKeys();
expect(prisma.aPIKeys.findMany).toHaveBeenCalledTimes(1);
expect(result).toEqual([
- { name: 'key1', apiKeyPreview: 'openlit-abcd…yyyyyy' },
+ { name: 'key1', apiKeyPreview: 'openlit-abcd…yyyyyy', scopes: null },
]);
expect(result[0].apiKey).toBeUndefined();
});
diff --git a/src/client/src/__tests__/middleware/check-auth.test.ts b/src/client/src/__tests__/middleware/check-auth.test.ts
index a361653e..81c69d09 100644
--- a/src/client/src/__tests__/middleware/check-auth.test.ts
+++ b/src/client/src/__tests__/middleware/check-auth.test.ts
@@ -88,6 +88,24 @@ describe('checkAuth', () => {
expect(nextHandler).not.toHaveBeenCalled();
});
+ it('rejects a Bearer token on API key management routes', async () => {
+ for (const [method, path] of [
+ ['GET', '/api/api-key'],
+ ['POST', '/api/api-key'],
+ ['PATCH', '/api/api-key/key-1'],
+ ['DELETE', '/api/api-key/key-1'],
+ ]) {
+ (NextResponse.json as jest.Mock).mockClear();
+ const req = makeRequest(method, path, '', { Authorization: 'Bearer abc123' });
+ await middleware(req as any, makeFetchEvent());
+ expect(NextResponse.json).toHaveBeenCalledWith(
+ { error: 'Forbidden' },
+ { status: 403 }
+ );
+ }
+ expect(nextHandler).not.toHaveBeenCalled();
+ });
+
it('rejects an empty API key', async () => {
const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer ' });
await middleware(req as any, makeFetchEvent());
@@ -142,6 +160,20 @@ describe('checkAuth', () => {
expect(forwardedRequest.headers.get('x-openlit-environment')).toBe('staging');
});
+ const mockVerifiedKey = (scopes: string[] | null) => {
+ (global as any).fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ valid: true, databaseConfigId: 'db-config-1', scopes }),
+ });
+ };
+
+ it('ignores API key scopes in the community edition', async () => {
+ mockVerifiedKey(['prompts']);
+ const req = makeRequest('GET', '/api/vault/get-secrets', '', { Authorization: 'Bearer key-1' });
+ await middleware(req as any, makeFetchEvent());
+ expect(nextHandler).toHaveBeenCalled();
+ });
+
it('strips a client-supplied x-database-config-id on session API requests', async () => {
(getToken as jest.Mock).mockResolvedValue({ hasCompletedOnboarding: true });
const headers = new Headers({ 'x-database-config-id': 'victim-db' });
diff --git a/src/client/src/app/api/api-key/[id]/route.ts b/src/client/src/app/api/api-key/[id]/route.ts
index d67806aa..d08a10f0 100644
--- a/src/client/src/app/api/api-key/[id]/route.ts
+++ b/src/client/src/app/api/api-key/[id]/route.ts
@@ -1,7 +1,10 @@
-import { withAudit } from "@/lib/audit/route";
-import { withCurrentOrganisationPermission } from "@/lib/rbac/current";
+import { withApiKeyAccess, withApiKeyAudit } from "@/lib/access/api-key-route";
import { deleteAPIKey } from "@/lib/platform/api-keys/index";
-import asaw from "@/utils/asaw";
+import {
+ apiKeyAccessErrorResponse,
+ updateApiKeyScopes,
+} from "@/lib/platform/api-key-access/server";
+import getMessage from "@/constants/messages";
async function DELETEHandler(_: Request, context: any) {
const { id } = context.params;
@@ -15,6 +18,25 @@ async function DELETEHandler(_: Request, context: any) {
return Response.json(res);
}
-export const DELETE = withAudit(
- withCurrentOrganisationPermission("api_key:delete", DELETEHandler)
-);
+async function PATCHHandler(request: Request, context: any) {
+ const { id } = context.params;
+ // Never fall back to `{}`: a missing `scopes` means full access.
+ const body = await request.json().catch(() => null);
+ if (!body || typeof body !== "object" || !("scopes" in body)) {
+ return Response.json(
+ { error: getMessage().API_KEY_INVALID_JSON },
+ { status: 400 }
+ );
+ }
+ try {
+ return Response.json(await updateApiKeyScopes(id, body?.scopes));
+ } catch (err) {
+ return (
+ apiKeyAccessErrorResponse(err) ??
+ Response.json(String(err), { status: 400 })
+ );
+ }
+}
+
+export const DELETE = withApiKeyAudit(withApiKeyAccess("delete", DELETEHandler));
+export const PATCH = withApiKeyAudit(withApiKeyAccess("update", PATCHHandler));
diff --git a/src/client/src/app/api/api-key/route.ts b/src/client/src/app/api/api-key/route.ts
index 32428b35..fb721cb5 100644
--- a/src/client/src/app/api/api-key/route.ts
+++ b/src/client/src/app/api/api-key/route.ts
@@ -1,18 +1,42 @@
-import { withAudit } from "@/lib/audit/route";
-import { withCurrentOrganisationPermission } from "@/lib/rbac/current";
+import { withApiKeyAccess, withApiKeyAudit } from "@/lib/access/api-key-route";
import { generateAPIKey, getAllAPIKeys } from "@/lib/platform/api-keys";
+import {
+ apiKeyAccessErrorResponse,
+ resolveApiKeyScopeData,
+} from "@/lib/platform/api-key-access/server";
import asaw from "@/utils/asaw";
+import getMessage from "@/constants/messages";
+// Session-only: the auth middleware rejects Bearer API keys on this route, so
+// one key can't enumerate the others' names, previews, and creators.
async function GETHandler() {
const res: any = await getAllAPIKeys();
return Response.json(res);
}
async function POSTHandler(request: Request) {
- const formData = await request.json();
+ const formData = await request.json().catch(() => null);
+ if (!formData || typeof formData !== "object") {
+ return Response.json(
+ { error: getMessage().API_KEY_INVALID_JSON },
+ { status: 400 }
+ );
+ }
const name = formData.name;
- const [err, res]: any = await asaw(generateAPIKey(name));
+ // Validate requested feature access before the key exists. Not via asaw:
+ // it stringifies errors and would drop the access error's status.
+ let scopeData: Record<string, unknown>;
+ try {
+ scopeData = await resolveApiKeyScopeData(formData.scopes);
+ } catch (scopeErr) {
+ return (
+ apiKeyAccessErrorResponse(scopeErr) ??
+ Response.json(String(scopeErr), { status: 400 })
+ );
+ }
+
+ const [err, res]: any = await asaw(generateAPIKey(name, scopeData));
if (err) {
return Response.json(err, {
@@ -23,10 +47,5 @@ async function POSTHandler(request: Request) {
return Response.json(res);
}
-export const GET = withCurrentOrganisationPermission(
- "api_key:read",
- GETHandler
-);
-export const POST = withAudit(
- withCurrentOrganisationPermission("api_key:create", POSTHandler)
-);
+export const GET = withApiKeyAccess("read", GETHandler);
+export const POST = withApiKeyAudit(withApiKeyAccess("create", POSTHandler));
diff --git a/src/client/src/app/api/auth/verify-key/route.ts b/src/client/src/app/api/auth/verify-key/route.ts
index 39f0904e..0970f996 100644
--- a/src/client/src/app/api/auth/verify-key/route.ts
+++ b/src/client/src/app/api/auth/verify-key/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
import { getAPIKeyInfo } from "@/lib/platform/api-keys";
+import { getApiKeyScopes } from "@/lib/platform/api-key-access/server";
export async function GET(request: NextRequest) {
const authHeader = request.headers.get("Authorization") || "";
@@ -22,6 +23,8 @@ export async function GET(request: NextRequest) {
organisationId: apiInfo.organisationId || null,
projectId: apiInfo.projectId || null,
environment: apiInfo.environment || "production",
+ // null = full access; an array restricts the key to those features.
+ scopes: await getApiKeyScopes(apiInfo.id),
});
}
} catch (e) {
diff --git a/src/client/src/components/(playground)/api-keys/access.tsx b/src/client/src/components/(playground)/api-keys/access.tsx
new file mode 100644
index 00000000..a34e41da
--- /dev/null
+++ b/src/client/src/components/(playground)/api-keys/access.tsx
@@ -0,0 +1,37 @@
+"use client";
+// Community edition: API keys always have full access. The enterprise build
+// overrides this module with per-feature access controls.
+import { ShieldCheck } from "lucide-react";
+import { ApiKey } from "@/types/api-key";
+import getMessage from "@/constants/messages";
+
+// `null` = full access; an array restricts the key to those features.
+export type ApiKeyAccessValue = string[] | null;
+
+export function ApiKeyAccessSelector(_props: {
+ value: ApiKeyAccessValue;
+ onChange: (value: ApiKeyAccessValue) => void;
+}) {
+ return null;
+}
+
+export function ApiKeyAccessCell(_props: { apiKey: ApiKey }) {
+ const messages = getMessage();
+ return (
+ <span
+ title={messages.API_KEY_FULL_ACCESS_DESCRIPTION}
+ className="inline-flex items-center gap-1 rounded-md border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300"
+ >
+ <ShieldCheck className="h-3.5 w-3.5" />
+ {messages.API_KEY_FULL_ACCESS}
+ </span>
+ );
+}
+
+// Row action for editing a key's access; nothing to edit in this edition.
+export function ApiKeyAccessAction(_props: {
+ apiKey: ApiKey;
+ onUpdated: () => void;
+}) {
+ return null;
+}
diff --git a/src/client/src/components/(playground)/api-keys/generate.tsx b/src/client/src/components/(playground)/api-keys/generate.tsx
index 8c320ff9..40a8daeb 100644
--- a/src/client/src/components/(playground)/api-keys/generate.tsx
+++ b/src/client/src/components/(playground)/api-keys/generate.tsx
@@ -1,9 +1,9 @@
import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
-import { noop } from "@/utils/noop";
import copy from "copy-to-clipboard";
import { toast } from "sonner";
-import FormBuilder from "@/components/common/form-builder";
import {
Dialog,
DialogContent,
@@ -12,26 +12,46 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
import { jsonStringify } from "@/utils/json";
-import { useState } from "react";
+import { FormEvent, useEffect, useState } from "react";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
-import { FieldProps, FormBuilderEvent } from "@/types/form";
import getMessage from "@/constants/messages";
+import {
+ ApiKeyAccessSelector,
+ ApiKeyAccessValue,
+} from "@/components/(playground)/api-keys/access";
export default function Generate({ refresh }: { refresh: () => void }) {
const posthog = usePostHog();
const messages = getMessage();
const [isOpen, setIsOpen] = useState(false);
+ const [name, setName] = useState("default");
+ const [scopes, setScopes] = useState<ApiKeyAccessValue>(null);
const { fireRequest: fireCreateRequest, isLoading: isCreating } =
useFetchWrapper();
- const handleCreation: FormBuilderEvent = async (event, formdata) => {
+
+ useEffect(() => {
+ if (isOpen) {
+ setName("default");
+ setScopes(null);
+ }
+ }, [isOpen]);
+
+ const handleCreation = async (event: FormEvent) => {
event.preventDefault();
- if (formdata.name?.length < 3) {
+ if (isCreating) return;
+ if (name.trim().length < 3) {
toast.error("Name length should be greater than 2...", {
id: "api-key",
});
return;
}
+ if (Array.isArray(scopes) && scopes.length === 0) {
+ toast.error(messages.API_KEY_ACCESS_SELECT_FEATURE, {
+ id: "api-key",
+ });
+ return;
+ }
toast.loading("Generating api key...", {
id: "api-key",
});
@@ -39,7 +59,9 @@ export default function Generate({ refresh }: { refresh: () => void }) {
requestType: "POST",
url: `/api/api-key`,
body: jsonStringify({
- name: formdata.name,
+ name: name.trim(),
+ // Omitted (full access) unless the edition supports restricting it.
+ ...(Array.isArray(scopes) ? { scopes } : {}),
}),
successCb: (data: any) => {
copy(data.apiKey);
@@ -59,21 +81,6 @@ export default function Generate({ refresh }: { refresh: () => void }) {
});
};
- const formFields: FieldProps[] = [
- {
- label: "Name",
- description: "Assign a name to api key for better references in future",
- inputKey: `api-name`,
- fieldType: "INPUT",
- fieldTypeProps: {
- type: "text",
- name: "name",
- placeholder: "",
- defaultValue: "default",
- },
- },
- ];
-
return (
<Dialog onOpenChange={setIsOpen} open={isOpen}>
<DialogTrigger asChild>
@@ -85,21 +92,43 @@ export default function Generate({ refresh }: { refresh: () => void }) {
{messages.GENERATE_NEW_API_KEY}
</Button>
</DialogTrigger>
- <DialogContent className="max-w-lg">
+ <DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle className="dark:text-stone-200 text-stone-800">
{messages.CREATE_NEW_KEY}
</DialogTitle>
</DialogHeader>
- <div className="flex items-center overflow-y-auto">
- <FormBuilder
- alignment="vertical"
- fields={formFields}
- isLoading={isCreating}
- onSubmit={isCreating ? noop : handleCreation}
- submitButtonText={messages.CREATE}
- />
- </div>
+ <form
+ onSubmit={handleCreation}
+ className="flex flex-col gap-4 max-h-[70vh] overflow-y-auto"
+ >
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor="api-key-name"
+ className="text-sm font-medium text-stone-900 dark:text-stone-200"
+ >
+ Name
+ </Label>
+ <Input
+ id="api-key-name"
+ name="name"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ />
+ <span className="text-xs text-stone-500 dark:text-stone-400">
+ Assign a name to api key for better references in future
+ </span>
+ </div>
+ <ApiKeyAccessSelector value={scopes} onChange={setScopes} />
+ <Button
+ type="submit"
+ size="sm"
+ disabled={isCreating}
+ className="bg-primary hover:bg-primary dark:bg-primary dark:hover:bg-primary text-stone-100 dark:text-stone-100 px-8 h-8 self-end"
+ >
+ {messages.CREATE}
+ </Button>
+ </form>
</DialogContent>
</Dialog>
);
diff --git a/src/client/src/components/(playground)/api-keys/manage.tsx b/src/client/src/components/(playground)/api-keys/manage.tsx
index a15a1849..e9e7f613 100644
--- a/src/client/src/components/(playground)/api-keys/manage.tsx
+++ b/src/client/src/components/(playground)/api-keys/manage.tsx
@@ -18,6 +18,10 @@ import Link from "next/link";
import FeaturePageHeader from "@/components/(playground)/feature-page-header";
import getMessage from "@/constants/messages";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import {
+ ApiKeyAccessAction,
+ ApiKeyAccessCell,
+} from "@/components/(playground)/api-keys/access";
const columns: Columns<string, ApiKey> = {
name: {
@@ -34,6 +38,10 @@ const columns: Columns<string, ApiKey> = {
);
},
},
+ access: {
+ header: () => "Access",
+ cell: ({ row }) => <ApiKeyAccessCell apiKey={row} />,
+ },
createdBy: {
header: () => "Created By",
cell: ({ row }) => {
@@ -50,7 +58,11 @@ const columns: Columns<string, ApiKey> = {
header: () => "Actions",
cell: ({ row, extraFunctions }) => {
return (
- <div className="flex gap-4 justify-center">
+ <div className="flex items-center justify-center gap-1">
+ <ApiKeyAccessAction
+ apiKey={row}
+ onUpdated={extraFunctions?.refresh}
+ />
<ConfirmationModal
handleYes={extraFunctions?.handleYes}
title="Are you sure you want to delete?"
@@ -59,7 +71,14 @@ const columns: Columns<string, ApiKey> = {
id: row.id,
}}
>
- <TrashIcon className="w-4 cursor-pointer" />
+ <button
+ type="button"
+ aria-label={getMessage().API_KEY_DELETE}
+ title={getMessage().API_KEY_DELETE}
+ className="rounded-md p-1.5 text-stone-500 transition-colors hover:bg-red-50 hover:text-red-600 dark:text-stone-400 dark:hover:bg-red-950/40 dark:hover:text-red-400"
+ >
+ <TrashIcon className="h-4 w-4" />
+ </button>
</ConfirmationModal>
</div>
);
@@ -159,12 +178,14 @@ export default function ManageKeys() {
visibilityColumns={{
name: true,
apiKey: true,
+ access: true,
createdBy: true,
createdAt: true,
actions: true,
}}
extraFunctions={{
handleYes,
+ refresh: fetchData,
}}
/>
</div>
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 78be70c5..03c95da5 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -3136,3 +3136,13 @@ export const DATA_SOURCE_BINDING_FAILED = "Failed to update signal routing.";
export const DATA_SOURCE_LOAD_FAILED = "Failed to load data sources.";
export const DATA_SOURCE_RETRY = "Try again";
+export const API_KEY_FULL_ACCESS = "Full access";
+export const API_KEY_ACCESS_SELECT_FEATURE = "Select at least one feature.";
+export const API_KEY_FEATURE_ACCESS_DENIED =
+ "This API key does not have access to this feature";
+export const API_KEY_ACCESS_CONTROL_UNAVAILABLE =
+ "API key access control is not available in this edition.";
+export const API_KEY_FULL_ACCESS_DESCRIPTION =
+ "Can use every feature that accepts API keys.";
+export const API_KEY_DELETE = "Delete API key";
+export const API_KEY_INVALID_JSON = "Request body must be valid JSON.";
diff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.ts
index c834ea85..82ab5463 100644
--- a/src/client/src/constants/route.ts
+++ b/src/client/src/constants/route.ts
@@ -17,7 +17,6 @@ export const ALLOWED_OPENLIT_ROUTES_WITH_TOKEN = [
"/api/vault/get-secrets",
"/api/rule-engine/evaluate",
"/api/controller/poll",
- "/api/api-key",
"/api/db-config",
];
@@ -29,7 +28,6 @@ export const ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN = [
"/api/vault/",
"/api/metrics/",
"/api/chat/",
- "/api/api-key/",
];
export const CRON_JOB_ROUTES = [
diff --git a/src/client/src/lib/access/api-key-route.ts b/src/client/src/lib/access/api-key-route.ts
new file mode 100644
index 00000000..ca9058a1
--- /dev/null
+++ b/src/client/src/lib/access/api-key-route.ts
@@ -0,0 +1,16 @@
+/**
+ * CE fallback for API key route protection and audit hooks.
+ * Enterprise replaces this neutral module through its path aliases.
+ */
+export type ApiKeyAction = "read" | "create" | "update" | "delete";
+
+export function withApiKeyAccess<THandler>(
+ _action: ApiKeyAction,
+ handler: THandler
+): THandler {
+ return handler;
+}
+
+export function withApiKeyAudit<THandler>(handler: THandler): THandler {
+ return handler;
+}
diff --git a/src/client/src/lib/platform/api-key-access/scopes.ts b/src/client/src/lib/platform/api-key-access/scopes.ts
new file mode 100644
index 00000000..6571fbff
--- /dev/null
+++ b/src/client/src/lib/platform/api-key-access/scopes.ts
@@ -0,0 +1,38 @@
+// Community edition: API keys are not scoped and have access to every
+// API-key-enabled feature. The enterprise build overrides this module.
+
+export type ApiKeyScope = string;
+
+export type ApiKeyScopeDefinition = {
+ id: ApiKeyScope;
+ label: string;
+ description: string;
+ pathPrefixes: string[];
+ grantPermission: string;
+};
+
+export const API_KEY_SCOPES: ApiKeyScopeDefinition[] = [];
+
+export function isApiKeyScope(_value: unknown): _value is ApiKeyScope {
+ return false;
+}
+
+export function normalizeApiKeyScopes(_values: unknown): ApiKeyScope[] {
+ return [];
+}
+
+export function isApiKeyPathAllowed(
+ _pathname: string,
+ _scopes: string[] | null | undefined
+): boolean {
+ return true;
+}
+
+export function isApiKeyScopeAllowed(
+ _scopes: string[] | null | undefined,
+ _scope: ApiKeyScope
+): boolean {
+ return true;
+}
+
+export const API_KEY_SCOPES_ENABLED = false;
diff --git a/src/client/src/lib/platform/api-key-access/server.ts b/src/client/src/lib/platform/api-key-access/server.ts
new file mode 100644
index 00000000..52faff1f
--- /dev/null
+++ b/src/client/src/lib/platform/api-key-access/server.ts
@@ -0,0 +1,40 @@
+// Community edition: every API key has full access. Per-key feature access is
+// an enterprise feature; the enterprise build overrides this module.
+import getMessage from "@/constants/messages";
+
+export class ApiKeyAccessError extends Error {
+ constructor(message: string, public status = 400) {
+ super(message);
+ this.name = "ApiKeyAccessError";
+ }
+}
+
+export async function getApiKeyScopes(_apiKeyId: string): Promise<string[] | null> {
+ return null;
+}
+
+export async function getApiKeyScopesByIds(
+ _apiKeyIds: string[]
+): Promise<Record<string, string[] | null>> {
+ return {};
+}
+
+export async function resolveApiKeyScopeData(
+ _requested: unknown
+): Promise<Record<string, unknown>> {
+ return {};
+}
+
+export async function updateApiKeyScopes(
+ _apiKeyId: string,
+ _requested: unknown
+): Promise<{ id: string; scopes: string[] | null }> {
+ throw new ApiKeyAccessError(getMessage().API_KEY_ACCESS_CONTROL_UNAVAILABLE, 403);
+}
+
+export function apiKeyAccessErrorResponse(error: unknown) {
+ if (error instanceof ApiKeyAccessError) {
+ return Response.json({ error: error.message }, { status: error.status });
+ }
+ return null;
+}
diff --git a/src/client/src/lib/platform/api-keys/index.ts b/src/client/src/lib/platform/api-keys/index.ts
index 53d1d54e..8d00f7b7 100644
--- a/src/client/src/lib/platform/api-keys/index.ts
+++ b/src/client/src/lib/platform/api-keys/index.ts
@@ -7,6 +7,7 @@ import { throwIfError } from "@/utils/error";
import getMessage from "@/constants/messages";
import { recordOrganisationUsageEvent } from "@/lib/billing/usage-recorder";
import { getCurrentOrganisation } from "@/lib/organisation";
+import { getApiKeyScopesByIds } from "@/lib/platform/api-key-access/server";
const APIKEY_PREFIX = "openlit-";
@@ -58,7 +59,12 @@ function createAPIKey() {
return `${APIKEY_PREFIX}${key.toString("base64")}`;
}
-export async function generateAPIKey(name: string) {
+// `extraData` carries edition-specific columns (e.g. enterprise access scopes)
+// so they are written atomically with the key.
+export async function generateAPIKey(
+ name: string,
+ extraData: Record<string, unknown> = {}
+) {
const user = await getCurrentUser();
throwIfError(!user, getMessage().UNAUTHORIZED_USER);
@@ -83,8 +89,9 @@ export async function generateAPIKey(name: string) {
? dbConfig.environment.trim()
: "production";
- await prisma.aPIKeys.create({
+ const created = await prisma.aPIKeys.create({
data: {
+ ...extraData,
apiKey,
name,
databaseConfigId: dbConfig.id,
@@ -114,6 +121,7 @@ export async function generateAPIKey(name: string) {
}
return {
+ id: created.id,
apiKey,
databaseConfigId: dbConfig.id,
organisationId,
@@ -196,9 +204,12 @@ export async function getAllAPIKeys(databaseConfigId?: string) {
return data;
}
+ const scopesById = await getApiKeyScopesByIds(data.map((row) => row.id));
+
return data.map(({ apiKey, ...rest }) => ({
...rest,
apiKeyPreview: previewApiKey(apiKey),
+ scopes: scopesById[rest.id] ?? null,
}));
}
diff --git a/src/client/src/middleware/check-auth.ts b/src/client/src/middleware/check-auth.ts
index 618d2bf1..c23cec6d 100644
--- a/src/client/src/middleware/check-auth.ts
+++ b/src/client/src/middleware/check-auth.ts
@@ -18,6 +18,8 @@ import {
ONBOARDING_WHITELIST_API_ROUTES,
} from "@/constants/route";
import { isValidCronJobRequest } from "@/helpers/server/cron-auth";
+import { isApiKeyPathAllowed } from "@/lib/platform/api-key-access/scopes";
+import getMessage from "@/constants/messages";
const CLIENT_TENANT_HEADERS = [
"x-database-config-id",
@@ -146,6 +148,12 @@ export default function checkAuth(next: NextMiddleware) {
if (res.ok) {
const data = await res.json();
if (data.valid && data.databaseConfigId) {
+ if (!isApiKeyPathAllowed(pathname, data.scopes)) {
+ return NextResponse.json(
+ { error: getMessage().API_KEY_FEATURE_ACCESS_DENIED },
+ { status: 403 }
+ );
+ }
requestHeaders.set("x-database-config-id", data.databaseConfigId);
if (data.organisationId) {
requestHeaders.set(
diff --git a/src/client/src/types/api-key.ts b/src/client/src/types/api-key.ts
index ab016c0a..3c85b007 100644
--- a/src/client/src/types/api-key.ts
+++ b/src/client/src/types/api-key.ts
@@ -7,4 +7,6 @@ export type ApiKey = {
};
id: string;
name: string;
+ // Enterprise per-feature access. `null` = full access.
+ scopes?: string[] | null;
};