Skip to content

Audit Log Viewer #119

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 2 commits into from
Apr 20, 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,4 @@ __pycache__
/blob-report/
/playwright/.cache/
dist_devel/
!src/ui/pages/logs
2 changes: 2 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ 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";

dotenv.config();

Expand Down Expand Up @@ -135,6 +136,7 @@ async function init(prettyPrint: boolean = false) {
api.register(mobileWalletRoute, { prefix: "/mobileWallet" });
api.register(stripeRoutes, { prefix: "/stripe" });
api.register(roomRequestRoutes, { prefix: "/roomRequests" });
api.register(logsPlugin, { prefix: "/logs" });
if (app.runEnvironment === "dev") {
api.register(vendingPlugin, { prefix: "/vending" });
}
Expand Down
108 changes: 108 additions & 0 deletions src/api/routes/logs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { QueryCommand } from "@aws-sdk/client-dynamodb";
import { unmarshall } from "@aws-sdk/util-dynamodb";
import { createAuditLogEntry } from "api/functions/auditLog.js";
import rateLimiter from "api/plugins/rateLimiter.js";
import { genericConfig } from "common/config.js";
import {
BaseError,
DatabaseFetchError,
ValidationError,
} from "common/errors/index.js";
import { Modules } from "common/modules.js";
import { AppRoles } from "common/roles.js";
import fastify, { FastifyPluginAsync } from "fastify";

Check warning on line 13 in src/api/routes/logs.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

'fastify' is defined but never used. Allowed unused vars must match /^_/u
import { request } from "http";

Check warning on line 14 in src/api/routes/logs.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

'request' is defined but never used. Allowed unused vars must match /^_/u

type GetLogsRequest = {
Params: { module: string };
Querystring: { start: number; end: number };
Body: undefined;
};

const logsPlugin: FastifyPluginAsync = async (fastify, _options) => {
fastify.register(rateLimiter, {
limit: 10,
duration: 30,
rateLimitIdentifier: "logs",
});
fastify.get<GetLogsRequest>(
"/:module",
{
schema: {
querystring: {
type: "object",
required: ["start", "end"],
properties: {
start: { type: "number" },
end: { type: "number" },
},
additionalProperties: false,
},
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [AppRoles.AUDIT_LOG_VIEWER]);
},
preValidation: async (request, reply) => {

Check warning on line 45 in src/api/routes/logs.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

'reply' is defined but never used. Allowed unused args must match /^_/u
const { module } = request.params;
const { start, end } = request.query;

if (!Object.values(Modules).includes(module as Modules)) {
throw new ValidationError({ message: `Invalid module "${module}".` });
}
if (end <= start) {
throw new ValidationError({
message: `End must be greater than start.`,
});
}
},
},
async (request, reply) => {
const { module } = request.params;
const { start, end } = request.query;
const logPromise = createAuditLogEntry({
dynamoClient: fastify.dynamoClient,
entry: {
module: Modules.AUDIT_LOG,
actor: request.username!,
target: module,
message: `Viewed audit log from ${start} to ${end}.`,
},
});
const queryCommand = new QueryCommand({
TableName: genericConfig.AuditLogTable,
KeyConditionExpression: "#pk = :module AND #sk BETWEEN :start AND :end",
ExpressionAttributeNames: {
"#pk": "module",
"#sk": "createdAt",
},
ExpressionAttributeValues: {
":module": { S: module },
":start": { N: start.toString() },
":end": { N: end.toString() },
},
ScanIndexForward: false,
});
let response;
try {
response = await fastify.dynamoClient.send(queryCommand);
if (!response.Items) {
throw new DatabaseFetchError({
message: "Error occurred fetching audit log.",
});
}
} catch (e) {
if (e instanceof BaseError) {
throw e;
}
fastify.log.error(e);
throw new DatabaseFetchError({
message: "Error occurred fetching audit log.",
});
}
await logPromise;
reply.send(response.Items.map((x) => unmarshall(x)));
},
);
};

export default logsPlugin;
16 changes: 15 additions & 1 deletion src/common/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,19 @@ export enum Modules {
EMAIL_NOTIFICATION = "emailNotification",
PROVISION_NEW_MEMBER = "provisionNewMember",
MOBILE_WALLET = "mobileWallet",
LINKRY = "linkry"
LINKRY = "linkry",
AUDIT_LOG = "auditLog"
}


export const ModulesToHumanName: Record<Modules, string> = {
[Modules.IAM]: "IAM",
[Modules.EVENTS]: "Events",
[Modules.STRIPE]: "Stripe Integration",
[Modules.TICKETS]: "Ticketing/Merch",
[Modules.EMAIL_NOTIFICATION]: "Email Notifications",
[Modules.PROVISION_NEW_MEMBER]: "Member Provisioning",
[Modules.MOBILE_WALLET]: "Mobile Wallet",
[Modules.LINKRY]: "Link Shortener",
[Modules.AUDIT_LOG]: "Audit Log",
}
3 changes: 2 additions & 1 deletion src/common/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ export enum AppRoles {
STRIPE_LINK_CREATOR = "create:stripeLink",
BYPASS_OBJECT_LEVEL_AUTH = "bypass:ola",
ROOM_REQUEST_CREATE = "create:roomRequest",
ROOM_REQUEST_UPDATE = "update:roomRequest"
ROOM_REQUEST_UPDATE = "update:roomRequest",
AUDIT_LOG_VIEWER = "view:auditLog"
}
export const allAppRoles = Object.values(AppRoles).filter(
(value) => typeof value === "string",
Expand Down
5 changes: 5 additions & 0 deletions src/ui/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { ManageProfilePage } from './pages/profile/ManageProfile.page';
import { ManageStripeLinksPage } from './pages/stripe/ViewLinks.page';
import { ManageRoomRequestsPage } from './pages/roomRequest/RoomRequestLanding.page';
import { ViewRoomRequest } from './pages/roomRequest/ViewRoomRequest.page';
import { ViewLogsPage } from './pages/logs/ViewLogs.page';

const ProfileRediect: React.FC = () => {
const location = useLocation();
Expand Down Expand Up @@ -185,6 +186,10 @@ const authenticatedRouter = createBrowserRouter([
path: '/roomRequests/:semesterId/:requestId',
element: <ViewRoomRequest />,
},
{
path: '/logs',
element: <ViewLogsPage />,
},
// Catch-all route for authenticated users shows 404 page
{
path: '*',
Expand Down
8 changes: 8 additions & 0 deletions src/ui/components/AppShell/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
IconTicket,
IconLock,
IconDoor,
IconHistory,
} from '@tabler/icons-react';
import { ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
Expand Down Expand Up @@ -80,6 +81,13 @@ export const navItems = [
description: null,
validRoles: [AppRoles.LINKS_MANAGER, AppRoles.LINKS_ADMIN],
},
{
link: '/logs',
name: 'Audit Logs',
icon: IconHistory,
description: null,
validRoles: [AppRoles.AUDIT_LOG_VIEWER],
},
];

export const extLinks = [
Expand Down
Loading
Loading