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

Require API key for requests #81

Merged
merged 16 commits into from
Oct 10, 2023
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
97 changes: 97 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"nanoid": "^3.3.2",
"path": "^0.12.7",
"sequelize": "^6.21.3",
"sha3": "^2.1.4",
"typescript": "^4.6.3",
"uuid": "^8.3.2",
"winston": "^3.10.0"
Expand Down
22 changes: 22 additions & 0 deletions src/authorization.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Request } from "express";
import SHA3 from "sha3";
import { APIKey } from "./models/api_key";

const HASHER = new SHA3(256);

export async function getAPIKey(key: string): Promise<APIKey | null> {
HASHER.update(key);
const hashedKey = HASHER.digest("hex");
const apiKey = await APIKey.findOne({ where: { hashed_key: hashedKey } });
HASHER.reset();
return apiKey;
}

// TODO: Is there a better way to set this system up?
export function hasPermission(key: APIKey, req: Request): boolean {
const relativeURL = req.originalUrl;
const permissionsRoot = key.permissions_root;
const routePermission = permissionsRoot === null || relativeURL.startsWith(permissionsRoot);
const methodPermission = key.allowed_methods === null || key.allowed_methods.includes(req.method);
return routePermission && methodPermission;
}
40 changes: 40 additions & 0 deletions src/models/api_key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Sequelize, DataTypes, Model, InferAttributes, InferCreationAttributes, CreationOptional } from "sequelize";

export class APIKey extends Model<InferAttributes<APIKey>, InferCreationAttributes<APIKey>> {
declare id: CreationOptional<number>;
declare hashed_key: string;
declare client: string;
declare permissions_root: CreationOptional<string>;
declare allowed_methods: CreationOptional<string[]>;
}

export function initializeAPIKeyModel(sequelize: Sequelize) {
APIKey.init({
id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
hashed_key: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
client: {
type: DataTypes.STRING,
allowNull: false
},
permissions_root: {
type: DataTypes.STRING,
defaultValue: null
},
allowed_methods: {
type: DataTypes.JSON,
defaultValue: null
}
}, {
sequelize,
engine: "InnoDB"
});
}
2 changes: 2 additions & 0 deletions src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Student, initializeStudentModel } from "./student";
import { Sequelize } from "sequelize/types";
import { initializeStudentOptionsModel } from "./student_options";
import { initializeQuestionModel } from "./question";
import { initializeAPIKeyModel } from "./api_key";

export {
Class,
Expand All @@ -25,6 +26,7 @@ export {
StudentsClasses,
};
export function initializeModels(db: Sequelize) {
initializeAPIKeyModel(db);
initializeSessionModel(db);
initializeEducatorModel(db);
initializeClassModel(db);
Expand Down
35 changes: 29 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {
getQuestionsForStory,
} from "./database";

import { getAPIKey, hasPermission } from "./authorization";

import {
CreateClassResult,
LoginResult,
Expand All @@ -40,7 +42,7 @@ import {
import { CosmicDSSession } from "./models";

import { ParsedQs } from "qs";
import express, { Request, Response as ExpressResponse } from "express";
import express, { Request, Response as ExpressResponse, NextFunction } from "express";
import { Response } from "express-serve-static-core";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
Expand All @@ -49,8 +51,10 @@ import sequelizeStore from "connect-session-sequelize";
import { v4 } from "uuid";
import cors from "cors";
import jwt from "jsonwebtoken";

import { isStudentOption } from "./models/student_options";
import { isNumberArray, isStringArray } from "./utils";

export const app = express();

// TODO: Clean up these type definitions
Expand All @@ -72,10 +76,7 @@ export enum UserType {
Admin
}

const ALLOWED_ORIGINS = [
"http://192.168.99.136:8081",
"https://cosmicds.github.io"
];
const ALLOWED_HOSTS = process.env.ALLOWED_HOSTS ? process.env.ALLOWED_HOSTS.split(",") : [];

const corsOptions: cors.CorsOptions = {
origin: "*",
Expand Down Expand Up @@ -106,6 +107,26 @@ const store = new SequelizeStore({
}
});

async function apiKeyMiddleware(req: Request, res: ExpressResponse, next: NextFunction): Promise<void> {

// The whitelisting of hosts is temporary!
const host = req.headers.origin;
const validOrigin = host && ALLOWED_HOSTS.includes(host);
const key = req.get("Authorization");
const apiKey = key ? await getAPIKey(key) : null;
const apiKeyExists = apiKey !== null;
if (validOrigin || (apiKeyExists && hasPermission(apiKey, req))) {
next();
} else {
res.statusCode = apiKeyExists ? 403 : 401;
const message = apiKeyExists ?
"Your API key does not provide permission to access this endpoint!" :
"You must provide a valid CosmicDS API key!";
res.json({ message });
res.end();
}
}

const SECRET = "ADD_REAL_SECRET";
const SESSION_NAME = "cosmicds";

Expand All @@ -126,6 +147,8 @@ app.use(session({
}));
store.sync();

app.use(apiKeyMiddleware);

// parse requests of content-type - application/json
app.use(bodyParser.json());

Expand All @@ -136,7 +159,7 @@ app.use(function(req, res, next) {

const origin = req.get("origin");
console.log(origin);
if (origin !== undefined && ALLOWED_ORIGINS.includes(origin)) {
if (origin !== undefined && ALLOWED_HOSTS.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin);
}
next();
Expand Down
8 changes: 8 additions & 0 deletions src/sql/create_api_keys_table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE APIKeys (
id int(11) UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT,
hashed_key varchar(100) NOT NULL UNIQUE,
client varchar(64) NOT NULL,
permissions_root varchar(50) DEFAULT NULL,
allowed_methods JSON DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=0 DEFAULT CHARSET=UTF8 COLLATE = UTF8_UNICODE_CI PACK_KEYS=0;