Skip to content

Enhance request with IP and location #202

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

Merged
merged 4 commits into from
Jul 6, 2025
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
77 changes: 49 additions & 28 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,75 @@
/* eslint import/no-nodejs-modules: ["error", {"allow": ["crypto"]}] */
/* eslint import/no-nodejs-modules: ["error", {"allow": ["crypto", "path", "url"]}] */

import { randomUUID } from "crypto";
import { fileURLToPath } from "url";
import path from "path";
import fastify, { FastifyInstance } from "fastify";
import FastifyAuthProvider from "@fastify/auth";
import fastifyStatic from "@fastify/static";
import fastifyAuthPlugin, { getSecretValue } from "./plugins/auth.js";
import protectedRoute from "./routes/protected.js";
import errorHandlerPlugin from "./plugins/errorHandler.js";
import { RunEnvironment, runEnvironments } from "../common/roles.js";
import { InternalServerError } from "../common/errors/index.js";
import eventsPlugin from "./routes/events.js";
import cors from "@fastify/cors";
import {
environmentConfig,
genericConfig,
SecretConfig,
} from "../common/config.js";
import organizationsPlugin from "./routes/organizations.js";
import authorizeFromSchemaPlugin from "./plugins/authorizeFromSchema.js";
import evaluatePoliciesPlugin from "./plugins/evaluatePolicies.js";
import icalPlugin from "./routes/ics.js";
import vendingPlugin from "./routes/vending.js";
import * as dotenv from "dotenv";
import iamRoutes from "./routes/iam.js";
import ticketsPlugin from "./routes/tickets.js";
import linkryRoutes from "./routes/linkry.js";
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
import NodeCache from "node-cache";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
import mobileWalletRoute from "./routes/mobileWallet.js";
import stripeRoutes from "./routes/stripe.js";
import membershipPlugin from "./routes/membership.js";
import path from "path"; // eslint-disable-line import/no-nodejs-modules
import roomRequestRoutes from "./routes/roomRequests.js";
import logsPlugin from "./routes/logs.js";

import {
fastifyZodOpenApiPlugin,
fastifyZodOpenApiTransform,
fastifyZodOpenApiTransformObject,
serializerCompiler,
validatorCompiler,
} from "fastify-zod-openapi";
import { ZodOpenApiVersion } from "zod-openapi";
import { type ZodOpenApiVersion } from "zod-openapi";
import { withTags } from "./components/index.js";
import RedisModule from "ioredis";

/** BEGIN EXTERNAL PLUGINS */
import fastifyIp from "fastify-ip";
import cors from "@fastify/cors";
import FastifyAuthProvider from "@fastify/auth";
import fastifyStatic from "@fastify/static";
/** END EXTERNAL PLUGINS */

/** BEGIN INTERNAL PLUGINS */
import locationPlugin from "./plugins/location.js";
import fastifyAuthPlugin, { getSecretValue } from "./plugins/auth.js";
import errorHandlerPlugin from "./plugins/errorHandler.js";
import authorizeFromSchemaPlugin from "./plugins/authorizeFromSchema.js";
import evaluatePoliciesPlugin from "./plugins/evaluatePolicies.js";
/** END INTERNAL PLUGINS */

/** BEGIN ROUTES */
import organizationsPlugin from "./routes/organizations.js";
import icalPlugin from "./routes/ics.js";
import vendingPlugin from "./routes/vending.js";
import iamRoutes from "./routes/iam.js";
import ticketsPlugin from "./routes/tickets.js";
import linkryRoutes from "./routes/linkry.js";
import mobileWalletRoute from "./routes/mobileWallet.js";
import stripeRoutes from "./routes/stripe.js";
import membershipPlugin from "./routes/membership.js";
import roomRequestRoutes from "./routes/roomRequests.js";
import logsPlugin from "./routes/logs.js";
import apiKeyRoute from "./routes/apiKey.js";
import clearSessionRoute from "./routes/clearSession.js";
import RedisModule from "ioredis";
import { fileURLToPath } from "url"; // eslint-disable-line import/no-nodejs-modules
import protectedRoute from "./routes/protected.js";
import eventsPlugin from "./routes/events.js";
/** END ROUTES */

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

dotenv.config();

const now = () => Date.now();
const isRunningInLambda =
process.env.LAMBDA_TASK_ROOT || process.env.AWS_LAMBDA_FUNCTION_NAME;

async function init(prettyPrint: boolean = false, initClients: boolean = true) {
const isRunningInLambda =
process.env.LAMBDA_TASK_ROOT || process.env.AWS_LAMBDA_FUNCTION_NAME;
let isSwaggerServer = false;
const transport = prettyPrint
? {
Expand Down Expand Up @@ -95,6 +106,7 @@ async function init(prettyPrint: boolean = false, initClients: boolean = true) {
await app.register(evaluatePoliciesPlugin);
await app.register(errorHandlerPlugin);
await app.register(fastifyZodOpenApiPlugin);
await app.register(locationPlugin);
if (!isRunningInLambda) {
try {
const fastifySwagger = import("@fastify/swagger");
Expand Down Expand Up @@ -278,6 +290,14 @@ async function init(prettyPrint: boolean = false, initClients: boolean = true) {
await app.refreshSecretConfig();
app.redisClient = new RedisModule.default(app.secretConfig.redis_url);
}
if (isRunningInLambda) {
await app.register(fastifyIp.default, {
order: ["x-forwarded-for"],
strict: true,
isAWS: false,
});
}

app.addHook("onRequest", (req, _, done) => {
req.startTime = now();
const hostname = req.hostname;
Expand Down Expand Up @@ -337,6 +357,7 @@ async function init(prettyPrint: boolean = false, initClients: boolean = true) {
origin: app.environmentConfig.ValidCorsOrigins,
methods: ["GET", "HEAD", "POST", "PATCH", "DELETE"],
});

app.addHook("onSend", async (request, reply) => {
reply.header("X-Request-Id", request.id);
});
Expand Down
1 change: 1 addition & 0 deletions src/api/lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const handler = async (event: APIGatewayEvent, context: Context) => {
isBase64Encoded: false,
};
}
delete event.headers["x-origin-verify"];
}
// else proceed with handler logic
return await realHandler(event, context).catch((e) => {
Expand Down
1 change: 1 addition & 0 deletions src/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"dotenv": "^16.5.0",
"esbuild": "^0.25.3",
"fastify": "^5.3.2",
"fastify-ip": "^1.2.0",
"fastify-plugin": "^5.0.1",
"fastify-raw-body": "^5.0.0",
"fastify-zod-openapi": "^5.0.1",
Expand Down
4 changes: 3 additions & 1 deletion src/api/plugins/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ const errorHandlerPlugin = fp(async (fastify) => {
},
);
fastify.setNotFoundHandler((request: FastifyRequest) => {
throw new NotFoundError({ endpointName: request.url });
throw new NotFoundError({
endpointName: `${request.method} ${request.url}`,
});
});
});

Expand Down
27 changes: 27 additions & 0 deletions src/api/plugins/location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import fp from "fastify-plugin";

const locationPlugin = fp(async (fastify, opts) => {
const processHeader = (headerValue: string | string[] | undefined) => {
if (Array.isArray(headerValue)) {
return headerValue.join(",");
}
return headerValue;
};

fastify.decorateRequest("location", {
getter() {
return {
country: processHeader(this.headers["cloudfront-viewer-country"]),
city: processHeader(this.headers["cloudfront-viewer-city"]),
region: processHeader(this.headers["cloudfront-viewer-country-region"]),
latitude: processHeader(this.headers["cloudfront-viewer-latitude"]),
longitude: processHeader(this.headers["cloudfront-viewer-longitude"]),
postalCode: processHeader(
this.headers["cloudfront-viewer-postal-code"],
),
};
},
});
});

export default locationPlugin;
6 changes: 3 additions & 3 deletions src/api/routes/apiKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ Key ID: acmuiuc_${keyId}

Key Description: ${description}

IP address: ${request.ip}.

IP address: ${request.ip}
${request.location.city && request.location.region && request.location.country ? `\nLocation: ${request.location.city}, ${request.location.region}, ${request.location.country}\n` : ""}
Roles: ${roles.join(", ")}.

If you did not create this API key, please secure your account and notify the ACM Infrastructure team.
Expand Down Expand Up @@ -210,7 +210,7 @@ This email confirms that an API key for the Core API has been deleted from your
Key ID: acmuiuc_${keyId}

IP address: ${request.ip}.

${request.location.city && request.location.region && request.location.country ? `\nLocation: ${request.location.city}, ${request.location.region}, ${request.location.country}\n` : ""}
If you did not delete this API key, please secure your account and notify the ACM Infrastructure team.
`,
callToActionButton: {
Expand Down
10 changes: 10 additions & 0 deletions src/api/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ import { AvailableAuthorizationPolicy } from "common/policies/definition.js";
import type RedisModule from "ioredis";
type Redis = RedisModule.default;

interface CloudfrontLocation {
country: string | undefined;
city: string | undefined;
region: string | undefined;
latitude: string | undefined;
longitude: string | undefined;
postalCode: string | undefined;
}

declare module "fastify" {
interface FastifyInstance {
authenticate: (
Expand Down Expand Up @@ -45,6 +54,7 @@ declare module "fastify" {
userRoles?: Set<AppRoles>;
tokenPayload?: AadToken;
policyRestrictions?: AvailableAuthorizationPolicy[];
location: CloudfrontLocation;
}
}

Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5633,6 +5633,13 @@ fastest-levenshtein@^1.0.16:
resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz#210e61b6ff181de91ea9b3d1b84fdedd47e034e5"
integrity sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==

fastify-ip@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/fastify-ip/-/fastify-ip-1.2.0.tgz#bd65121e843f407870da11f1a721afe5083f44a1"
integrity sha512-n7BqGlEMZmaG/zEdrp7/fShBUNWfgT6EKXfC3FERTzuSPZSo8gxfq0kjD8PhAjD1I1o7oqo5Wc/m7jr+Fn+HRg==
dependencies:
fastify-plugin "^5.0.1"

fastify-plugin@^5.0.0, fastify-plugin@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/fastify-plugin/-/fastify-plugin-5.0.1.tgz#82d44e6fe34d1420bb5a4f7bee434d501e41939f"
Expand Down
Loading