diff --git a/src/api/functions/authorization.ts b/src/api/functions/authorization.ts index b201a2a..8bfecf2 100644 --- a/src/api/functions/authorization.ts +++ b/src/api/functions/authorization.ts @@ -9,7 +9,7 @@ import { DatabaseFetchError } from "../../common/errors/index.js"; import { allAppRoles, AppRoles } from "../../common/roles.js"; import { FastifyInstance } from "fastify"; -export const AUTH_DECISION_CACHE_SECONDS = 60; +export const AUTH_DECISION_CACHE_SECONDS = 180; export async function getUserRoles( dynamoClient: DynamoDBClient, @@ -72,11 +72,19 @@ export async function getGroupRoles( }, }); const response = await dynamoClient.send(command); - if (!response || !response.Item) { + if (!response) { throw new DatabaseFetchError({ message: "Could not get group roles for user", }); } + if (!response.Item) { + fastifyApp.nodeCache.set( + `grouproles-${groupId}`, + [], + AUTH_DECISION_CACHE_SECONDS, + ); + return []; + } const items = unmarshall(response.Item) as { roles: AppRoles[] | ["all"] }; if (!("roles" in items)) { fastifyApp.nodeCache.set( diff --git a/src/api/routes/iam.ts b/src/api/routes/iam.ts index 929632e..7989d64 100644 --- a/src/api/routes/iam.ts +++ b/src/api/routes/iam.ts @@ -1,5 +1,5 @@ import { FastifyPluginAsync } from "fastify"; -import { AppRoles } from "../../common/roles.js"; +import { allAppRoles, AppRoles } from "../../common/roles.js"; import { zodToJsonSchema } from "zod-to-json-schema"; import { addToTenant, @@ -34,6 +34,10 @@ import { EntraGroupActions, entraGroupMembershipListResponse, } from "../../common/types/iam.js"; +import { + AUTH_DECISION_CACHE_SECONDS, + getGroupRoles, +} from "api/functions/authorization.js"; const dynamoClient = new DynamoDBClient({ region: genericConfig.AwsRegion, @@ -61,19 +65,10 @@ const iamRoutes: FastifyPluginAsync = async (fastify, _options) => { }, }, async (request, reply) => { - const groupId = (request.params as Record).groupId; try { - const command = new GetItemCommand({ - TableName: `${genericConfig.IAMTablePrefix}-grouproles`, - Key: { groupUuid: { S: groupId } }, - }); - const response = await dynamoClient.send(command); - if (!response.Item) { - throw new NotFoundError({ - endpointName: `/api/v1/iam/groupRoles/${groupId}`, - }); - } - reply.send(unmarshall(response.Item)); + const groupId = (request.params as Record).groupId; + const roles = await getGroupRoles(dynamoClient, fastify, groupId); + return reply.send(roles); } catch (e: unknown) { if (e instanceof BaseError) { throw e; @@ -125,9 +120,14 @@ const iamRoutes: FastifyPluginAsync = async (fastify, _options) => { createdAt: timestamp, }), }); - await dynamoClient.send(command); + fastify.nodeCache.set( + `grouproles-${groupId}`, + request.body.roles, + AUTH_DECISION_CACHE_SECONDS, + ); } catch (e: unknown) { + fastify.nodeCache.del(`grouproles-${groupId}`); if (e instanceof BaseError) { throw e; }