mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-12 15:30:53 +02:00
add virtual api key schema and crud endpoints
This commit is contained in:
@@ -48,7 +48,8 @@ import {
|
||||
verifyResourcePolicyAccess,
|
||||
verifyAiProviderAccess,
|
||||
verifyAiModelAccess,
|
||||
verifyAiBudgetAccess
|
||||
verifyAiBudgetAccess,
|
||||
verifyVirtualApiKeyAccess
|
||||
} from "@server/middlewares";
|
||||
import { ActionsEnum } from "@server/auth/actions";
|
||||
import rateLimit, { ipKeyGenerator } from "express-rate-limit";
|
||||
@@ -60,6 +61,7 @@ import { checkRoundTripMessage } from "./ws";
|
||||
import * as labels from "@server/routers/labels";
|
||||
import * as aiProvider from "@server/routers/aiProvider";
|
||||
import * as aiBudget from "@server/routers/aiBudget";
|
||||
import * as virtualApiKey from "@server/routers/virtualApiKey";
|
||||
|
||||
// Root routes
|
||||
export const unauthenticated = Router();
|
||||
@@ -1633,6 +1635,44 @@ authenticated.delete(
|
||||
aiBudget.deleteAiBudget
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/virtual-api-key",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.createVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.createVirtualApiKey),
|
||||
virtualApiKey.createVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/virtual-api-keys",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.listVirtualApiKeys),
|
||||
virtualApiKey.listVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyVirtualApiKeyAccess,
|
||||
verifyUserHasAction(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.getVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyVirtualApiKeyAccess,
|
||||
verifyUserHasAction(ActionsEnum.updateVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.updateVirtualApiKey),
|
||||
virtualApiKey.updateVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.delete(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyVirtualApiKeyAccess,
|
||||
verifyUserHasAction(ActionsEnum.deleteVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.deleteVirtualApiKey),
|
||||
virtualApiKey.deleteVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/ai-provider/:providerId/ai-budgets",
|
||||
verifyAiProviderAccess,
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as idp from "./idp";
|
||||
import * as logs from "./auditLogs";
|
||||
import * as siteResource from "./siteResource";
|
||||
import * as aiProvider from "./aiProvider";
|
||||
import * as virtualApiKey from "./virtualApiKey";
|
||||
import {
|
||||
verifyApiKey,
|
||||
verifyApiKeyOrgAccess,
|
||||
@@ -34,6 +35,7 @@ import {
|
||||
verifyApiKeyResourcePolicyAccess,
|
||||
verifyApiKeyAiProviderAccess,
|
||||
verifyApiKeyAiModelAccess,
|
||||
verifyApiKeyVirtualApiKeyAccess,
|
||||
verifyUserHasAction
|
||||
} from "@server/middlewares";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -1633,3 +1635,41 @@ authenticated.delete(
|
||||
logActionAudit(ActionsEnum.deleteAiModel),
|
||||
aiProvider.deleteAiModel
|
||||
);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/virtual-api-key",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.createVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.createVirtualApiKey),
|
||||
virtualApiKey.createVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/org/:orgId/virtual-api-keys",
|
||||
verifyApiKeyOrgAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.listVirtualApiKeys),
|
||||
virtualApiKey.listVirtualApiKeys
|
||||
);
|
||||
|
||||
authenticated.get(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyApiKeyVirtualApiKeyAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.getVirtualApiKey),
|
||||
virtualApiKey.getVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.post(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyApiKeyVirtualApiKeyAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.updateVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.updateVirtualApiKey),
|
||||
virtualApiKey.updateVirtualApiKey
|
||||
);
|
||||
|
||||
authenticated.delete(
|
||||
"/virtual-api-key/:virtualApiKeyId",
|
||||
verifyApiKeyVirtualApiKeyAccess,
|
||||
verifyApiKeyHasAction(ActionsEnum.deleteVirtualApiKey),
|
||||
logActionAudit(ActionsEnum.deleteVirtualApiKey),
|
||||
virtualApiKey.deleteVirtualApiKey
|
||||
);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, userOrgs, virtualApiKeys } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { createDate, TimeSpan } from "oslo";
|
||||
import {
|
||||
assertManualKeyResourcesInOrg,
|
||||
encryptVirtualApiKeyToken,
|
||||
mintVirtualApiKeySecret,
|
||||
replaceVirtualApiKeyResources,
|
||||
toPublicVirtualApiKey
|
||||
} from "@server/lib/virtualApiKey";
|
||||
import type { CreateOrEditVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
import { createVirtualApiKeyBodySchema } from "@server/routers/virtualApiKey/validation";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "put",
|
||||
path: "/org/{orgId}/virtual-api-key",
|
||||
description: "Create a manual virtual API key for an organization.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: createVirtualApiKeyBodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {
|
||||
201: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function createVirtualApiKey(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = createVirtualApiKeyBodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
const {
|
||||
name,
|
||||
description,
|
||||
userId,
|
||||
allResources,
|
||||
resourceIds,
|
||||
validForSeconds
|
||||
} = parsedBody.data;
|
||||
|
||||
if (req.user && orgId && orgId !== req.userOrgId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
const [membership] = await db
|
||||
.select()
|
||||
.from(userOrgs)
|
||||
.where(
|
||||
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId))
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!membership) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User is not a member of this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const assignedResourceIds = allResources ? [] : (resourceIds ?? []);
|
||||
const resourceCheck = await assertManualKeyResourcesInOrg({
|
||||
allResources,
|
||||
resourceIds: assignedResourceIds,
|
||||
orgId
|
||||
});
|
||||
if (!resourceCheck.ok) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, resourceCheck.message)
|
||||
);
|
||||
}
|
||||
|
||||
const minted = mintVirtualApiKeySecret();
|
||||
const expiresAt = validForSeconds
|
||||
? createDate(new TimeSpan(validForSeconds, "s")).getTime()
|
||||
: null;
|
||||
const now = Date.now();
|
||||
|
||||
const created = await db.transaction(async (trx) => {
|
||||
const [row] = await trx
|
||||
.insert(virtualApiKeys)
|
||||
.values({
|
||||
virtualApiKeyId: minted.virtualApiKeyId,
|
||||
orgId,
|
||||
kind: "manual",
|
||||
userId: userId ?? null,
|
||||
name,
|
||||
description: description ?? null,
|
||||
token: encryptVirtualApiKeyToken(minted.secret),
|
||||
lastChars: minted.lastChars,
|
||||
allResources,
|
||||
expiresAt,
|
||||
lastUsedAt: null,
|
||||
createdAt: now,
|
||||
createdByUserId: req.user?.userId ?? null
|
||||
})
|
||||
.returning();
|
||||
|
||||
await replaceVirtualApiKeyResources(
|
||||
trx,
|
||||
row.virtualApiKeyId,
|
||||
assignedResourceIds
|
||||
);
|
||||
|
||||
return row;
|
||||
});
|
||||
|
||||
return response<CreateOrEditVirtualApiKeyResponse>(res, {
|
||||
data: {
|
||||
virtualApiKey: {
|
||||
...toPublicVirtualApiKey(created, { includeSecret: true }),
|
||||
resourceIds: assignedResourceIds
|
||||
}
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API key created successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, virtualApiKeys } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
virtualApiKeyId: z.string().nonempty()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "delete",
|
||||
path: "/virtual-api-key/{virtualApiKeyId}",
|
||||
description: "Delete a manual virtual API key.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function deleteVirtualApiKey(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { virtualApiKeyId } = parsedParams.data;
|
||||
|
||||
const [existing] =
|
||||
req.virtualApiKey &&
|
||||
req.virtualApiKey.virtualApiKeyId === virtualApiKeyId
|
||||
? [req.virtualApiKey]
|
||||
: await db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(
|
||||
eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!existing || existing.kind !== "manual") {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Virtual API key with ID ${virtualApiKeyId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(virtualApiKeys)
|
||||
.where(eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId));
|
||||
|
||||
return response(res, {
|
||||
data: null,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API key deleted successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, virtualApiKeyResources, virtualApiKeys } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { toPublicVirtualApiKey } from "@server/lib/virtualApiKey";
|
||||
import type { GetVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
virtualApiKeyId: z.string().nonempty()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/virtual-api-key/{virtualApiKeyId}",
|
||||
description:
|
||||
"Get a manual virtual API key by ID, including the decrypted secret.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function getVirtualApiKey(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { virtualApiKeyId } = parsedParams.data;
|
||||
|
||||
const [key] =
|
||||
req.virtualApiKey &&
|
||||
req.virtualApiKey.virtualApiKeyId === virtualApiKeyId
|
||||
? [req.virtualApiKey]
|
||||
: await db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(
|
||||
eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!key || key.kind !== "manual") {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Virtual API key with ID ${virtualApiKeyId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const resourceRows = await db
|
||||
.select({ resourceId: virtualApiKeyResources.resourceId })
|
||||
.from(virtualApiKeyResources)
|
||||
.where(eq(virtualApiKeyResources.virtualApiKeyId, virtualApiKeyId));
|
||||
|
||||
return response<GetVirtualApiKeyResponse>(res, {
|
||||
data: {
|
||||
virtualApiKey: {
|
||||
...toPublicVirtualApiKey(key, { includeSecret: true }),
|
||||
resourceIds: resourceRows.map((row) => row.resourceId)
|
||||
}
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API key retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./createVirtualApiKey";
|
||||
export * from "./listVirtualApiKeys";
|
||||
export * from "./getVirtualApiKey";
|
||||
export * from "./updateVirtualApiKey";
|
||||
export * from "./deleteVirtualApiKey";
|
||||
export * from "./types";
|
||||
@@ -0,0 +1,218 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
virtualApiKeyResources,
|
||||
virtualApiKeys,
|
||||
type VirtualApiKey
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { and, asc, eq, exists, inArray, like, or, sql } from "drizzle-orm";
|
||||
import { toPublicVirtualApiKey } from "@server/lib/virtualApiKey";
|
||||
import type { ListVirtualApiKeysResponse } from "@server/routers/virtualApiKey/types";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
});
|
||||
|
||||
const listSchema = z.object({
|
||||
pageSize: z.coerce
|
||||
.number<string>()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.catch(20)
|
||||
.default(20)
|
||||
.openapi({
|
||||
type: "integer",
|
||||
default: 20,
|
||||
description: "Number of items per page"
|
||||
}),
|
||||
page: z.coerce
|
||||
.number<string>()
|
||||
.int()
|
||||
.min(0)
|
||||
.optional()
|
||||
.catch(1)
|
||||
.default(1)
|
||||
.openapi({
|
||||
type: "integer",
|
||||
default: 1,
|
||||
description: "Page number to retrieve"
|
||||
}),
|
||||
search: z.string().optional(),
|
||||
userId: z.string().optional(),
|
||||
resourceId: z.coerce.number().int().positive().optional()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/org/{orgId}/virtual-api-keys",
|
||||
description: "List manual virtual API keys for an organization.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
query: listSchema
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listVirtualApiKeys(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedQuery = listSchema.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedQuery.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
if (req.user && orgId && orgId !== req.userOrgId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { pageSize, page, search, userId, resourceId } = parsedQuery.data;
|
||||
const conditions = [
|
||||
eq(virtualApiKeys.orgId, orgId),
|
||||
eq(virtualApiKeys.kind, "manual")
|
||||
];
|
||||
|
||||
if (userId) {
|
||||
conditions.push(eq(virtualApiKeys.userId, userId));
|
||||
}
|
||||
|
||||
if (search) {
|
||||
const term = "%" + search.toLowerCase() + "%";
|
||||
conditions.push(
|
||||
or(
|
||||
like(sql`LOWER(${virtualApiKeys.name})`, term),
|
||||
like(sql`LOWER(${virtualApiKeys.description})`, term),
|
||||
like(sql`LOWER(${virtualApiKeys.lastChars})`, term)
|
||||
)!
|
||||
);
|
||||
}
|
||||
|
||||
if (resourceId !== undefined) {
|
||||
conditions.push(
|
||||
or(
|
||||
eq(virtualApiKeys.allResources, true),
|
||||
exists(
|
||||
db
|
||||
.select()
|
||||
.from(virtualApiKeyResources)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
virtualApiKeyResources.virtualApiKeyId,
|
||||
virtualApiKeys.virtualApiKeyId
|
||||
),
|
||||
eq(
|
||||
virtualApiKeyResources.resourceId,
|
||||
resourceId
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)!
|
||||
);
|
||||
}
|
||||
|
||||
const whereClause = and(...conditions);
|
||||
|
||||
const [totalCount, rows] = await Promise.all([
|
||||
db.$count(
|
||||
db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(whereClause)
|
||||
.as("filtered_virtual_api_keys")
|
||||
),
|
||||
db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(whereClause)
|
||||
.limit(pageSize)
|
||||
.offset(pageSize * (page - 1))
|
||||
.orderBy(
|
||||
asc(virtualApiKeys.name),
|
||||
asc(virtualApiKeys.createdAt)
|
||||
)
|
||||
]);
|
||||
|
||||
const keyIds = rows.map((row) => row.virtualApiKeyId);
|
||||
const resourceRows =
|
||||
keyIds.length === 0
|
||||
? []
|
||||
: await db
|
||||
.select()
|
||||
.from(virtualApiKeyResources)
|
||||
.where(
|
||||
inArray(
|
||||
virtualApiKeyResources.virtualApiKeyId,
|
||||
keyIds
|
||||
)
|
||||
);
|
||||
|
||||
const resourceIdsByKey = new Map<string, number[]>();
|
||||
for (const row of resourceRows) {
|
||||
const existing = resourceIdsByKey.get(row.virtualApiKeyId) ?? [];
|
||||
existing.push(row.resourceId);
|
||||
resourceIdsByKey.set(row.virtualApiKeyId, existing);
|
||||
}
|
||||
|
||||
return response<ListVirtualApiKeysResponse>(res, {
|
||||
data: {
|
||||
virtualApiKeys: rows.map((row: VirtualApiKey) => ({
|
||||
...toPublicVirtualApiKey(row),
|
||||
resourceIds: resourceIdsByKey.get(row.virtualApiKeyId) ?? []
|
||||
})),
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
pageSize,
|
||||
page
|
||||
}
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API keys retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PublicVirtualApiKey } from "@server/lib/virtualApiKey";
|
||||
import type { PaginatedResponse } from "@server/types/Pagination";
|
||||
|
||||
export type { PublicVirtualApiKey };
|
||||
|
||||
export type ListVirtualApiKeysResponse = PaginatedResponse<{
|
||||
virtualApiKeys: (PublicVirtualApiKey & { resourceIds: number[] })[];
|
||||
}>;
|
||||
|
||||
export type GetVirtualApiKeyResponse = {
|
||||
virtualApiKey: PublicVirtualApiKey & { resourceIds: number[] };
|
||||
};
|
||||
|
||||
export type CreateOrEditVirtualApiKeyResponse = {
|
||||
virtualApiKey: PublicVirtualApiKey & { resourceIds: number[] };
|
||||
};
|
||||
@@ -0,0 +1,218 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
userOrgs,
|
||||
virtualApiKeyResources,
|
||||
virtualApiKeys
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { createDate, TimeSpan } from "oslo";
|
||||
import {
|
||||
assertManualKeyResourcesInOrg,
|
||||
replaceVirtualApiKeyResources,
|
||||
toPublicVirtualApiKey
|
||||
} from "@server/lib/virtualApiKey";
|
||||
import type { CreateOrEditVirtualApiKeyResponse } from "@server/routers/virtualApiKey/types";
|
||||
import { updateVirtualApiKeyBodySchema } from "@server/routers/virtualApiKey/validation";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
virtualApiKeyId: z.string().nonempty()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/virtual-api-key/{virtualApiKeyId}",
|
||||
description:
|
||||
"Update a manual virtual API key metadata and resource assignment.",
|
||||
tags: [OpenAPITags.VirtualApiKey],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: updateVirtualApiKeyBodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function updateVirtualApiKey(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = paramsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = updateVirtualApiKeyBodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { virtualApiKeyId } = parsedParams.data;
|
||||
const body = parsedBody.data;
|
||||
|
||||
const [existing] =
|
||||
req.virtualApiKey &&
|
||||
req.virtualApiKey.virtualApiKeyId === virtualApiKeyId
|
||||
? [req.virtualApiKey]
|
||||
: await db
|
||||
.select()
|
||||
.from(virtualApiKeys)
|
||||
.where(
|
||||
eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!existing || existing.kind !== "manual") {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Virtual API key with ID ${virtualApiKeyId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (body.userId) {
|
||||
const [membership] = await db
|
||||
.select()
|
||||
.from(userOrgs)
|
||||
.where(
|
||||
and(
|
||||
eq(userOrgs.userId, body.userId),
|
||||
eq(userOrgs.orgId, existing.orgId)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!membership) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User is not a member of this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const nextAllResources =
|
||||
body.allResources !== undefined
|
||||
? body.allResources
|
||||
: existing.allResources;
|
||||
|
||||
let nextResourceIds: number[] | undefined;
|
||||
if (nextAllResources) {
|
||||
nextResourceIds = [];
|
||||
} else if (body.resourceIds !== undefined) {
|
||||
nextResourceIds = body.resourceIds;
|
||||
}
|
||||
|
||||
if (nextResourceIds !== undefined) {
|
||||
const resourceCheck = await assertManualKeyResourcesInOrg({
|
||||
allResources: nextAllResources,
|
||||
resourceIds: nextResourceIds,
|
||||
orgId: existing.orgId
|
||||
});
|
||||
if (!resourceCheck.ok) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, resourceCheck.message)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const updates: Partial<typeof virtualApiKeys.$inferInsert> = {};
|
||||
|
||||
if (body.name !== undefined) {
|
||||
updates.name = body.name;
|
||||
}
|
||||
if (body.description !== undefined) {
|
||||
updates.description = body.description;
|
||||
}
|
||||
if (body.userId !== undefined) {
|
||||
updates.userId = body.userId;
|
||||
}
|
||||
if (body.allResources !== undefined) {
|
||||
updates.allResources = body.allResources;
|
||||
}
|
||||
if (body.validForSeconds !== undefined) {
|
||||
updates.expiresAt =
|
||||
body.validForSeconds === null
|
||||
? null
|
||||
: createDate(
|
||||
new TimeSpan(body.validForSeconds, "s")
|
||||
).getTime();
|
||||
}
|
||||
|
||||
const updated = await db.transaction(async (trx) => {
|
||||
let row = existing;
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
const [updatedRow] = await trx
|
||||
.update(virtualApiKeys)
|
||||
.set(updates)
|
||||
.where(eq(virtualApiKeys.virtualApiKeyId, virtualApiKeyId))
|
||||
.returning();
|
||||
row = updatedRow;
|
||||
}
|
||||
|
||||
if (nextResourceIds !== undefined) {
|
||||
await replaceVirtualApiKeyResources(
|
||||
trx,
|
||||
virtualApiKeyId,
|
||||
nextResourceIds
|
||||
);
|
||||
}
|
||||
|
||||
return row;
|
||||
});
|
||||
|
||||
const resourceRows = await db
|
||||
.select({ resourceId: virtualApiKeyResources.resourceId })
|
||||
.from(virtualApiKeyResources)
|
||||
.where(eq(virtualApiKeyResources.virtualApiKeyId, virtualApiKeyId));
|
||||
|
||||
return response<CreateOrEditVirtualApiKeyResponse>(res, {
|
||||
data: {
|
||||
virtualApiKey: {
|
||||
...toPublicVirtualApiKey(updated),
|
||||
resourceIds: resourceRows.map((row) => row.resourceId)
|
||||
}
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Virtual API key updated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const virtualApiKeyResourceIdsSchema = z
|
||||
.array(z.coerce.number().int().positive())
|
||||
.optional();
|
||||
|
||||
export const createVirtualApiKeyBodySchema = z.strictObject({
|
||||
name: z.string().nonempty(),
|
||||
description: z.string().optional().nullable(),
|
||||
userId: z.string().optional().nullable(),
|
||||
allResources: z.boolean().optional().default(false),
|
||||
resourceIds: virtualApiKeyResourceIdsSchema,
|
||||
validForSeconds: z.int().positive().optional()
|
||||
});
|
||||
|
||||
export const updateVirtualApiKeyBodySchema = z.strictObject({
|
||||
name: z.string().nonempty().optional(),
|
||||
description: z.string().optional().nullable(),
|
||||
userId: z.string().optional().nullable(),
|
||||
allResources: z.boolean().optional(),
|
||||
resourceIds: virtualApiKeyResourceIdsSchema,
|
||||
validForSeconds: z.int().positive().optional().nullable()
|
||||
});
|
||||
Reference in New Issue
Block a user