Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ApiKey): add CRUDL for API keys #9

Merged
merged 6 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions seeders/DatabaseSeeder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,17 @@ import { User } from '@/users/entities/user.entity';
import { getDefaultModel } from '@/runs/execution/factory';
import { SystemTools } from '@/tools/entities/tool-calls/system-call.entity';
import { ProjectApiKey } from '@/administration/entities/project-api-key.entity';
import { scryptApiKey } from '@/auth/utils';
import { API_KEY_PREFIX, scryptApiKey } from '@/auth/utils';
import {
ORGANIZATION_ID_DEFAULT,
ORGANIZATION_OWNER_ID_DEFAULT,
PROJECT_ADMIN_ID_DEFAULT,
PROJECT_ID_DEFAULT
} from '@/config';
import { redactProjectKeyValue } from '@/administration/api-keys.service';

const USER_EXTERNAL_ID = 'test';
const PROJECT_API_KEY = 'sk-testkey';
const PROJECT_API_KEY = `${API_KEY_PREFIX}testkey`;

export class DatabaseSeeder extends Seeder {
async run(em: EntityManager): Promise<void> {
Expand Down Expand Up @@ -83,8 +84,10 @@ export class DatabaseSeeder extends Seeder {
.getReference(projectUser.id, { wrapped: true });
const projectApiKey = new ProjectApiKey({
key: scryptApiKey(PROJECT_API_KEY),
name: 'test key',
createdBy: ref(projectUser),
project: ref(project)
project: ref(project),
redactedValue: redactProjectKeyValue(PROJECT_API_KEY)
});
const assistant = new Assistant({
model: getDefaultModel(),
Expand Down
130 changes: 130 additions & 0 deletions src/administration/api-keys.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { FastifyPluginAsyncJsonSchemaToTs } from '@fastify/type-provider-json-schema-to-ts';
import { StatusCodes } from 'http-status-codes';

import {
ApiKeyCreateBody,
apiKeyCreateBodySchema,
ApiKeyCreateParams,
apiKeyCreateParamsSchema,
apiKeyCreateResponseSchema
} from './dtos/api-key-create';
import {
ApiKeyReadParams,
apiKeyReadParamsSchema,
apiKeyReadResponseSchema
} from './dtos/api-key-read';
import {
ApiKeyUpdateBody,
apiKeyUpdateBodySchema,
ApiKeyUpdateParams,
apiKeyUpdateParamsSchema,
apiKeyUpdateResponseSchema
} from './dtos/api-key-update';
import {
apiKeysListParamsSchema,
ApiKeysListParams,
ApiKeysListQuery,
apiKeysListQuerySchema,
apiKeysListResponseSchema
} from './dtos/api-keys-list';
import {
ApiKeyDeleteParams,
apiKeyDeleteParamsSchema,
apiKeyDeleteResponseSchema
} from './dtos/api-key-delete';
import {
createApiKey,
deleteApiKey,
listApiKeys,
readApiKey,
updateApiKey
} from './api-keys.service';

import { AuthSecret } from '@/auth/utils';
import { Tag } from '@/swagger.js';

export const apiKeysModule: FastifyPluginAsyncJsonSchemaToTs = async (app) => {
app.post<{ Body: ApiKeyCreateBody; Params: ApiKeyCreateParams }>(
'/organization/projects/:project_id/api_keys',
{
schema: {
body: apiKeyCreateBodySchema,
params: apiKeyCreateParamsSchema,
response: { [StatusCodes.OK]: apiKeyCreateResponseSchema },
tags: [Tag.BEE_API]
},
preHandler: app.auth([AuthSecret.ACCESS_TOKEN])
},
async (req) => createApiKey({ ...req.body, ...req.params })
);

app.get<{ Params: ApiKeyReadParams }>(
'/organization/projects/:project_id/api_keys/:api_key_id',
{
schema: {
params: apiKeyReadParamsSchema,
response: { [StatusCodes.OK]: apiKeyReadResponseSchema },
tags: [Tag.BEE_API]
},
preHandler: app.auth([AuthSecret.ACCESS_TOKEN])
},
async (req) => readApiKey(req.params)
);

app.post<{ Params: ApiKeyUpdateParams; Body: ApiKeyUpdateBody }>(
'/organization/projects/:project_id/api_keys/:api_key_id',
{
schema: {
params: apiKeyUpdateParamsSchema,
body: apiKeyUpdateBodySchema,
response: { [StatusCodes.OK]: apiKeyUpdateResponseSchema },
tags: [Tag.BEE_API]
},
preHandler: app.auth([AuthSecret.ACCESS_TOKEN])
},
async (req) => updateApiKey({ ...req.params, ...req.body })
);

app.get<{ Querystring: ApiKeysListQuery; Params: ApiKeysListParams }>(
'/organization/projects/:project_id/api_keys',
{
schema: {
querystring: apiKeysListQuerySchema,
params: apiKeysListParamsSchema,
response: { [StatusCodes.OK]: apiKeysListResponseSchema },
tags: [Tag.BEE_API]
},
preHandler: app.auth([AuthSecret.ACCESS_TOKEN])
},
async (req) => listApiKeys({ ...req.params, ...req.query })
);

app.delete<{ Params: ApiKeyDeleteParams }>(
'/organization/projects/:project_id/api_keys/:api_key_id',
{
schema: {
params: apiKeyDeleteParamsSchema,
response: { [StatusCodes.OK]: apiKeyDeleteResponseSchema },
tags: [Tag.BEE_API]
},
preHandler: app.auth([AuthSecret.ACCESS_TOKEN])
},
async (req) => deleteApiKey(req.params)
);
};
148 changes: 148 additions & 0 deletions src/administration/api-keys.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { FilterQuery, Loaded, ref } from '@mikro-orm/core';
import dayjs from 'dayjs';

import { ProjectApiKey } from './entities/project-api-key.entity';
import { ApiKey as ApiKeyDto } from './dtos/api-key';
import { ApiKeyCreateBody, ApiKeyCreateParams, ApiKeyCreateResponse } from './dtos/api-key-create';
import { ApiKeyReadParams, ApiKeyReadResponse } from './dtos/api-key-read';
import { ApiKeyUpdateBody, ApiKeyUpdateParams, ApiKeyUpdateResponse } from './dtos/api-key-update';
import { ApiKeysListParams, ApiKeysListQuery, ApiKeysListResponse } from './dtos/api-keys-list';
import { ApiKeyDeleteParams, ApiKeyDeleteResponse } from './dtos/api-key-delete';
import { getProjectPrincipal } from './helpers';
import { Project } from './entities/project.entity';

import { createDeleteResponse } from '@/utils/delete';
import { API_KEY_PREFIX, generateApiKey, scryptApiKey } from '@/auth/utils';
import { getUpdatedValue } from '@/utils/update';
import { createPaginatedResponse, getListCursor } from '@/utils/pagination';
import { ORM } from '@/database';
import { APIError, APIErrorCode } from '@/errors/error.entity';

export function toDto(apiKey: Loaded<ProjectApiKey>, sensitiveId?: string): ApiKeyDto {
return {
object: 'organization.project.api_key',
id: apiKey.id,
name: apiKey.name,
created_at: dayjs(apiKey.createdAt).unix(),
secret: typeof sensitiveId === 'string' ? sensitiveId : apiKey.redactedValue
};
}

export async function createApiKey({
name,
project_id
}: ApiKeyCreateBody & ApiKeyCreateParams): Promise<ApiKeyCreateResponse> {
const authorProjectPrincipal = getProjectPrincipal();
const project = await ORM.em.getRepository(Project).findOneOrFail({ id: project_id });
Comment on lines +51 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider capping the number of keys per project.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, do you think this is needed?

if (authorProjectPrincipal.project.id !== project.id) {
throw new APIError({
message: 'Project user mismatch',
code: APIErrorCode.INVALID_INPUT
});
}
const keyValue = generateApiKey();
const key = scryptApiKey(keyValue);
const apiKey = new ProjectApiKey({
name,
key,
createdBy: ref(authorProjectPrincipal),
project: ref(project),
redactedValue: redactProjectKeyValue(keyValue)
});

await ORM.em.persistAndFlush(apiKey);

return toDto(apiKey, keyValue);
}

export const redactProjectKeyValue = (key: string) =>
key.replace(
key.substring(API_KEY_PREFIX.length + 2, key.length - 2),
'*'.repeat(key.length - 12)
);

async function getApiKey({ project_id, api_key_id }: { project_id: string; api_key_id: string }) {
const projectPrincipal = getProjectPrincipal();
// validate project is inside the Org
const project = await ORM.em.getRepository(Project).findOneOrFail({ id: project_id });
if (projectPrincipal.project.id !== project.id) {
throw new APIError({
message: 'Project user mismatch',
code: APIErrorCode.INVALID_INPUT
});
}
const apiKey = await ORM.em
.getRepository(ProjectApiKey)
.findOneOrFail({ id: api_key_id, project: project_id });

return apiKey;
}

export async function readApiKey({
api_key_id,
project_id
}: ApiKeyReadParams): Promise<ApiKeyReadResponse> {
const apiKey = await getApiKey({ project_id, api_key_id });
return toDto(apiKey);
}

export async function updateApiKey({
api_key_id,
project_id,
name
}: ApiKeyUpdateParams & ApiKeyUpdateBody): Promise<ApiKeyUpdateResponse> {
const apiKey = await getApiKey({ project_id, api_key_id });

apiKey.name = getUpdatedValue(name, apiKey.name);
await ORM.em.flush();

return toDto(apiKey);
}

export async function listApiKeys({
limit,
order,
order_by,
after,
before,
project_id
}: ApiKeysListQuery & ApiKeysListParams): Promise<ApiKeysListResponse> {
// validate project is in the org
await ORM.em.getRepository(Project).findOneOrFail({ id: project_id });
const filter: FilterQuery<ProjectApiKey> = { project: project_id };
pilartomas marked this conversation as resolved.
Show resolved Hide resolved

const cursor = await getListCursor<ProjectApiKey>(
filter,
{ limit, order, order_by, after, before },
ORM.em.getRepository(ProjectApiKey)
);
return createPaginatedResponse(cursor, toDto);
}

export async function deleteApiKey({
api_key_id,
project_id
}: ApiKeyDeleteParams): Promise<ApiKeyDeleteResponse> {
const apiKey = await getApiKey({ project_id, api_key_id });

apiKey.delete();
await ORM.em.flush();

return createDeleteResponse(api_key_id, 'organization.project.api_key');
}
36 changes: 36 additions & 0 deletions src/administration/dtos/api-key-create.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { FromSchema, JSONSchema } from 'json-schema-to-ts';

import { apiKeySchema } from './api-key.js';
import { apiKeysListParamsSchema } from './api-keys-list.js';

export const apiKeyCreateBodySchema = {
type: 'object',
additionalProperties: false,
required: ['name'],
properties: {
name: { type: 'string' }
}
} as const satisfies JSONSchema;
export type ApiKeyCreateBody = FromSchema<typeof apiKeyCreateBodySchema>;

export const apiKeyCreateParamsSchema = apiKeysListParamsSchema;
export type ApiKeyCreateParams = FromSchema<typeof apiKeyCreateParamsSchema>;

export const apiKeyCreateResponseSchema = apiKeySchema;
pilartomas marked this conversation as resolved.
Show resolved Hide resolved
export type ApiKeyCreateResponse = FromSchema<typeof apiKeyCreateResponseSchema>;
27 changes: 27 additions & 0 deletions src/administration/dtos/api-key-delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Copyright 2024 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { FromSchema } from 'json-schema-to-ts';

import { apiKeyReadParamsSchema } from './api-key-read';

import { createDeleteSchema } from '@/schema';

export const apiKeyDeleteParamsSchema = apiKeyReadParamsSchema;
export type ApiKeyDeleteParams = FromSchema<typeof apiKeyDeleteParamsSchema>;

export const apiKeyDeleteResponseSchema = createDeleteSchema('organization.project.api_key');
export type ApiKeyDeleteResponse = FromSchema<typeof apiKeyDeleteResponseSchema>;
Loading