Skip to content
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

Linkry API routes - scaffolding #36

Open
wants to merge 7 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
6 changes: 6 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off"
}
},
{
"files": ["src/api/*", "src/api/**/*"],
"rules": {
"import/no-nodejs-modules": "off"
}
}
]
}
5 changes: 5 additions & 0 deletions .github/workflows/deploy-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ on:
pull_request:
branches:
- main
types: [opened, synchronize, reopened, ready_for_review]

jobs:
test-unit:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
name: Run Unit Tests
steps:
Expand All @@ -25,6 +28,7 @@ jobs:
- name: Run unit testing
run: make test_unit
deploy-dev:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
concurrency:
group: ${{ github.event.repository.name }}-dev-env
Expand Down Expand Up @@ -69,6 +73,7 @@ jobs:
branch: main

test-dev:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
name: Run Live Tests
needs:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ This repository is split into multiple parts:
* `src/common/` for common modules between the API and the UI (such as constants, types, errors, etc.)

## Getting Started
You will need node>=20 installed, as well as the AWS CLI and the AWS SAM CLI. The best way to work with all of this is to open the environment in a container within your IDE (VS Code should prompt you to do so: use "Clone in Container" for best performance). This container will have all needed software installed.
You will need node>=22 installed, as well as the AWS CLI and the AWS SAM CLI. The best way to work with all of this is to open the environment in a container within your IDE (VS Code should prompt you to do so: use "Clone in Container" for best performance). This container will have all needed software installed.

Then, run `make install` to install all packages, and `make local` to start the UI and API servers! The UI will be accessible on `http://localhost:5173/` and the API on `http://localhost:8080/`.

Expand Down
5 changes: 3 additions & 2 deletions cloudformation/iam.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,13 @@ Resources:
- !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/infra-core-api-iam-userroles/*
- !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/infra-core-api-iam-grouproles
- !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/infra-core-api-iam-grouproles/*

- !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/infra-core-api-linkry
- !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/infra-core-api-linkry/*
PolicyName: lambda-dynamo
Outputs:
MainFunctionRoleArn:
Description: Main API IAM role ARN
Value:
Fn::GetAtt:
- ApiLambdaIAMRole
- Arn
- Arn
28 changes: 28 additions & 0 deletions cloudformation/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,34 @@ Resources:
Projection:
ProjectionType: ALL

LinkryRecordsTable:
Type: "AWS::DynamoDB::Table"
Properties:
BillingMode: "PAY_PER_REQUEST"
TableName: "infra-core-api-linkry"
DeletionProtectionEnabled: true
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: !If [IsProd, true, false]
AttributeDefinitions:
- AttributeName: "slug"
AttributeType: "S"
- AttributeName: "access"
AttributeType: "S"
KeySchema:
- AttributeName: "slug"
KeyType: "HASH"
- AttributeName: "access"
KeyType: "RANGE"
GlobalSecondaryIndexes:
- IndexName: "AccessIndex"
KeySchema:
- AttributeName: "access"
KeyType: "HASH"
- AttributeName: "slug"
KeyType: "RANGE"
Projection:
ProjectionType: "ALL"

CacheRecordsTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: "Retain"
Expand Down
11 changes: 10 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint import/no-nodejs-modules: ["error", {"allow": ["crypto"]}] */
import { randomUUID } from "crypto";
import fastify, { FastifyInstance } from "fastify";
import FastifyAuthProvider from "@fastify/auth";
Expand All @@ -18,6 +17,9 @@ import * as dotenv from "dotenv";
import iamRoutes from "./routes/iam.js";
import ticketsPlugin from "./routes/tickets.js";
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
import linkryRoutes from "./routes/linkry.js";
import path from "node:path";
import { fileURLToPath } from "node:url";
import NodeCache from "node-cache";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
Expand Down Expand Up @@ -64,6 +66,12 @@ async function init() {
return event.requestContext.requestId;
},
});
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename);
await app.register(import("@fastify/static"), {
root: path.join(__dirname, "public"),
});

await app.register(fastifyAuthPlugin);
await app.register(fastifyZodValidationPlugin);
await app.register(FastifyAuthProvider);
Expand Down Expand Up @@ -111,6 +119,7 @@ async function init() {
api.register(icalPlugin, { prefix: "/ical" });
api.register(iamRoutes, { prefix: "/iam" });
api.register(ticketsPlugin, { prefix: "/tickets" });
api.register(linkryRoutes, { prefix: "/linkry" });
if (app.runEnvironment === "dev") {
api.register(vendingPlugin, { prefix: "/vending" });
}
Expand Down
1 change: 1 addition & 0 deletions src/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"prettier:write": "prettier --write *.ts **/*.ts"
},
"dependencies": {
"@fastify/static": "^8.0.4",
"@aws-sdk/client-dynamodb": "^3.624.0",
"@aws-sdk/client-secrets-manager": "^3.624.0",
"@aws-sdk/client-sts": "^3.726.0",
Expand Down
2 changes: 1 addition & 1 deletion src/api/plugins/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
} from "../../common/errors/index.js";
import { genericConfig, SecretConfig } from "../../common/config.js";
import { getGroupRoles, getUserRoles } from "../functions/authorization.js";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

Check warning on line 18 in src/api/plugins/auth.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

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

function intersection<T>(setA: Set<T>, setB: Set<T>): Set<T> {
export function intersection<T>(setA: Set<T>, setB: Set<T>): Set<T> {
const _intersection = new Set<T>();
for (const elem of setB) {
if (setA.has(elem)) {
Expand Down
65 changes: 65 additions & 0 deletions src/api/public/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Not Found | ACM @ UIUC</title>
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #1a1a1a;
color: #ffffff;
font-family: Arial, sans-serif;
text-align: center;
}

.container {
max-width: 600px;
}

h1 {
font-size: 10rem;
margin: 0;
color: #ffffff;
}

h1 span {
color: #ffa500;
}

p {
margin-top: 1rem;
font-size: 1.5rem;
color: #aaaaaa;
}

footer {
margin-top: 2rem;
font-size: 0.9rem;
color: #666666;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
const yearElement = document.getElementById('year');
const currentYear = new Date().getFullYear();
yearElement.textContent = currentYear;
});
</script>
</head>

<body>
<div class="container">
<h1>4<span>0</span>4</h1>
<p>The page you are looking for could not be found.</p>
<footer>&copy; <span id="year"></span> ACM @ UIUC</footer>
</div>
</body>

</html>
Binary file added src/api/public/favicon.ico
Binary file not shown.
154 changes: 154 additions & 0 deletions src/api/routes/linkry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { FastifyPluginAsync } from "fastify";
import { z } from "zod";
import { AppRoles } from "../../common/roles.js";
import {
BaseError,
DatabaseFetchError,
NotFoundError,

Check warning on line 7 in src/api/routes/linkry.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

'NotFoundError' is defined but never used. Allowed unused vars must match /^_/u
NotImplementedError,
} from "../../common/errors/index.js";
import { intersection } from "../plugins/auth.js";

Check warning on line 10 in src/api/routes/linkry.ts

View workflow job for this annotation

GitHub Actions / Run Unit Tests

'intersection' is defined but never used. Allowed unused vars must match /^_/u
import { NoDataRequest } from "../types.js";
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb";
import { genericConfig } from "../../common/config.js";
import { unmarshall } from "@aws-sdk/util-dynamodb";

type LinkrySlugOnlyRequest = {
Params: { id: string };
Querystring: undefined;
Body: undefined;
};

const rawRequest = {
slug: z.string().min(1),
redirect: z.string().url().min(1),
groups: z.optional(z.array(z.string()).min(1)),
};

const createRequest = z.object(rawRequest);
const patchRequest = z.object({ redirect: z.string().url().min(1) });

type LinkyCreateRequest = {
Params: undefined;
Querystring: undefined;
Body: z.infer<typeof createRequest>;
};

type LinkryPatchRequest = {
Params: { id: string };
Querystring: undefined;
Body: z.infer<typeof patchRequest>;
};

const dynamoClient = new DynamoDBClient({
region: genericConfig.AwsRegion,
});

const linkryRoutes: FastifyPluginAsync = async (fastify, _options) => {
fastify.get<LinkrySlugOnlyRequest>("/redir/:id", async (request, reply) => {
const id = request.params.id;
const command = new QueryCommand({
TableName: genericConfig.LinkryDynamoTableName,
KeyConditionExpression:
"#slug = :slugVal AND begins_with(#access, :accessVal)",
ExpressionAttributeNames: {
"#slug": "slug",
"#access": "access",
},
ExpressionAttributeValues: {
":slugVal": { S: id },
":accessVal": { S: "OWNER#" },
},
});
try {
const result = await dynamoClient.send(command);
if (!result || !result.Items || result.Items.length === 0) {
return reply
.headers({ "content-type": "text/html" })
.status(404)
.sendFile("404.html");
}
return reply.redirect(unmarshall(result.Items[0]).redirect);
} catch (e) {
if (e instanceof BaseError) {
throw e;
}
request.log.error(e);
throw new DatabaseFetchError({
message: "Could not retrieve mapping, please try again later.",
});
}
});
fastify.post<LinkyCreateRequest>(
"/redir",
{
preValidation: async (request, reply) => {
await fastify.zodValidateBody(request, reply, createRequest);
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [
AppRoles.LINKS_MANAGER,
AppRoles.LINKS_ADMIN,
]);
},
},
async (request, reply) => {
throw new NotImplementedError({});
},
);
fastify.patch<LinkryPatchRequest>(
"/redir/:id",
{
preValidation: async (request, reply) => {
await fastify.zodValidateBody(request, reply, patchRequest);
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [
AppRoles.LINKS_MANAGER,
AppRoles.LINKS_ADMIN,
]);
},
},
async (request, reply) => {
// make sure that a user can manage this link, either via owning or being in a group that has access to it, or is a LINKS_ADMIN.
// you can only change the URL it redirects to
throw new NotImplementedError({});
},
);
fastify.delete<LinkrySlugOnlyRequest>(
"/redir/:id",
{
preValidation: async (request, reply) => {
await fastify.zodValidateBody(request, reply, createRequest);
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [
AppRoles.LINKS_MANAGER,
AppRoles.LINKS_ADMIN,
]);
},
},
async (request, reply) => {
// make sure that a user can manage this link, either via owning or being in a group that has access to it, or is a LINKS_ADMIN.
throw new NotImplementedError({});
},
);
fastify.get<NoDataRequest>(
"/redir",
{
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [
AppRoles.LINKS_MANAGER,
AppRoles.LINKS_ADMIN,
]);
},
},
async (request, reply) => {
// if an admin, show all links
// if a links manager, show all my links + links I can manage
throw new NotImplementedError({});
},
);
};

export default linkryRoutes;
6 changes: 6 additions & 0 deletions src/api/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,9 @@ declare module "fastify" {
tokenPayload?: AadToken;
}
}

export type NoDataRequest = {
Params: undefined;
Querystring: undefined;
Body: undefined;
};
Loading
Loading