-
Notifications
You must be signed in to change notification settings - Fork 16
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
eced86b
feat(ApiKey): add CRUDL for API keys
34ff401
fixup! feat(ApiKey): add CRUDL for API keys
6e77e16
fixup! fixup! feat(ApiKey): add CRUDL for API keys
a6f05aa
fixup! fixup! fixup! feat(ApiKey): add CRUDL for API keys
cd4ee01
fixup! fixup! fixup! fixup! feat(ApiKey): add CRUDL for API keys
3854844
Merge branch 'main' into api_key_crudl
xjacka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | ||
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'); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?