Skip to content

Cache secrets in Fastify application #146

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
20 changes: 13 additions & 7 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,16 +232,22 @@ async function init(prettyPrint: boolean = false) {
app.runEnvironment = process.env.RunEnvironment as RunEnvironment;
app.environmentConfig =
environmentConfig[app.runEnvironment as RunEnvironment];
app.nodeCache = new NodeCache({ checkperiod: 30 });
app.nodeCache = new NodeCache({ checkperiod: 15 });
app.dynamoClient = dynamoClient;
app.secretsManagerClient = secretsManagerClient;
app.redisClient = redisClient;
app.secretConfig = secret;
app.refreshSecretConfig = async () => {
app.secretConfig = (await getSecretValue(
app.secretsManagerClient,
genericConfig.ConfigSecretName,
)) as SecretConfig;
app.getCachedSecret = async (secretName: string) => {
const cacheKey = `_SECRET:${secretName}`;
const cachedValue = app.nodeCache.get(cacheKey);
if (!cachedValue) {
const realValue = (await getSecretValue(
app.secretsManagerClient,
secretName,
)) as SecretConfig;
app.nodeCache.set(cacheKey, JSON.stringify(realValue), 90);
return realValue as SecretConfig;
}
return cachedValue as SecretConfig;
};
app.addHook("onRequest", (req, _, done) => {
req.startTime = now();
Expand Down
9 changes: 5 additions & 4 deletions src/api/plugins/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
UnauthenticatedError,
UnauthorizedError,
} from "../../common/errors/index.js";
import { SecretConfig } from "../../common/config.js";
import { genericConfig, SecretConfig } from "../../common/config.js";
import {
AUTH_DECISION_CACHE_SECONDS,
getGroupRoles,
Expand Down Expand Up @@ -193,10 +193,11 @@ const authPlugin: FastifyPluginAsync = async (fastify, _options) => {
message: "Custom JWTs cannot be used in Prod environment.",
});
}
const config = await fastify.getCachedSecret(
genericConfig.ConfigSecretName,
);
signingKey =
process.env.JwtSigningKey ||
(fastify.secretConfig.jwt_key as string) ||
"";
process.env.JwtSigningKey || (config.jwt_key as string) || "";
if (signingKey === "") {
throw new UnauthenticatedError({
message: "Invalid token.",
Expand Down
4 changes: 2 additions & 2 deletions src/api/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
try {
if (request.body.featured && !request.body.repeats) {
await updateDiscord(
fastify.secretConfig,
await fastify.getCachedSecret(genericConfig.ConfigSecretName),
entry,
request.username,
false,
Expand Down Expand Up @@ -496,7 +496,7 @@ const eventsPlugin: FastifyPluginAsyncZodOpenApi = async (
}),
);
await updateDiscord(
fastify.secretConfig,
await fastify.getCachedSecret(genericConfig.ConfigSecretName),
{ id } as IUpdateDiscord,
request.username,
true,
Expand Down
4 changes: 3 additions & 1 deletion src/api/routes/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ const stripeRoutes: FastifyPluginAsync = async (fastify, _options) => {
if (!request.username) {
throw new UnauthenticatedError({ message: "No username found" });
}
const secretApiConfig = fastify.secretConfig;
const secretApiConfig = await fastify.getCachedSecret(
genericConfig.ConfigSecretName,
);
const payload: StripeLinkCreateParams = {
...request.body,
createdBy: request.username,
Expand Down
3 changes: 1 addition & 2 deletions src/api/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ declare module "fastify" {
redisClient: Redis;
secretsManagerClient: SecretsManagerClient;
cloudfrontKvClient: CloudFrontKeyValueStoreClient;
secretConfig: SecretConfig;
refreshSecretConfig: CallableFunction;
getCachedSecret: (secretName: string) => Promise<SecretConfig>;
}
interface FastifyRequest {
startTime: number;
Expand Down
Loading