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

Implement GitHub OAuth to restrict access #73

Open
wants to merge 8 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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ PRIVATE_KEY= # Use `script/encode-key <path-to-pem-file>` to encode the private
CLIENT_ID=SomeClientId123
CLIENT_SECRET=secret
WEBHOOK_SECRET=secret
REDIRECT_URL_BASE=http://localhost:3000
2 changes: 2 additions & 0 deletions .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ jobs:
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
REDIRECT_URL_BASE: ${{ secrets.REDIRECT_URL_BASE }}
PLAYWRIGHT_GITHUB_USERNAME: ${{ secrets.PLAYWRIGHT_GITHUB_USERNAME }}
PLAYWRIGHT_GITHUB_PASSWORD: ${{ secrets.PLAYWRIGHT_GITHUB_PASSWORD }}
- uses: actions/upload-artifact@v4
if: always()
with:
Expand Down
14 changes: 14 additions & 0 deletions auth/callback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { cookie } from "./cookie.js";

export const handleOAuthCallback = async (app, request, response) => {
if (request.url.startsWith("/api/github/oauth/callback?code=")) {
const url = new URL(request.url, `http://${request.headers.host}`);
const { authentication: { token, expiresAt } } = await app.oauth.createToken({ code: url.searchParams.get("code") });

response.writeHead(302, {
"Location": "/",
...cookie("Token", token, "/", expiresAt)
});
return response.end();
}
};
67 changes: 67 additions & 0 deletions auth/callback.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { describe, it } from "node:test";
import expect from "node:assert";
import { handleOAuthCallback } from "./callback.js";

const app = {
oauth: {
createToken: async () => {},
checkToken: async () => {},
}
}

const response = {
writeHead: () => {},
end: () => {},
};

describe("handleOAuthCallback", () => {
it("should do nothing if the request isn't for the OAuth callback URL", async (t) => {
t.mock.method(app.oauth, "createToken");
t.mock.method(response, "writeHead");
t.mock.method(response, "end");

const request = {
url: "/some/path",
headers: {},
};

await handleOAuthCallback(app, request, response);

expect.strictEqual(app.oauth.createToken.mock.callCount(), 0);
expect.strictEqual(response.writeHead.mock.callCount(), 0);
expect.strictEqual(response.end.mock.callCount(), 0);
});

it("should use the code passed in through the URL to generate a token and save it as a cookie before redirecting to the index", async (t) => {
const createTokenResponse = {
authentication: {
token: "sometoken",
expiresAt: "9999-12-31T23:59:59.999Z",
},
};

t.mock.method(app.oauth, "createToken", () => createTokenResponse);
t.mock.method(response, "writeHead");
t.mock.method(response, "end");

const request = {
url: "/api/github/oauth/callback?code=foo",
headers: {},
};

await handleOAuthCallback(app, request, response);

expect.strictEqual(app.oauth.createToken.mock.callCount(), 1);
expect.strictEqual(response.writeHead.mock.callCount(), 1);
expect.strictEqual(response.end.mock.callCount(), 1);

expect.deepStrictEqual(app.oauth.createToken.mock.calls[0].arguments, [{ code: "foo" }]);
expect.deepStrictEqual(response.writeHead.mock.calls[0].arguments, [
302,
{
"Location": "/",
"Set-Cookie": "Token=sometoken; Path=/; Expires=Fri, 31 Dec 9999 23:59:59 GMT"
},
]);
});
});
16 changes: 16 additions & 0 deletions auth/cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

export const cookie = (key, value, path, expires) => {
const cookieFragments = [`${key}=${value}`];

if (path) {
cookieFragments.push(`Path=${path}`);
}

if (expires) {
cookieFragments.push(`Expires=${new Date(expires).toUTCString()}`);
}

return {
"Set-Cookie": cookieFragments.join("; "),
};
};
55 changes: 55 additions & 0 deletions auth/cookie.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, it } from "node:test";
import expect from "node:assert";
import { cookie } from "./cookie.js";

describe("cookie", () => {
it("should return the expected object when no path or expiry is given", () => {
const expected = {
"Set-Cookie": "Foo=bar",
};

const actual = cookie("Foo", "bar");

expect.deepStrictEqual(actual, expected);
});

it("should return the expected object when the path is given", () => {
const expected = {
"Set-Cookie": "Foo=bar; Path=/some/path",
};

const actual = cookie("Foo", "bar", "/some/path");

expect.deepStrictEqual(actual, expected);
});

it("should return the expected object when the expiry is given as a string", () => {
const expected = {
"Set-Cookie": "Foo=bar; Expires=Mon, 01 Jan 2024 12:34:56 GMT",
};

const actual = cookie("Foo", "bar", null, "2024-01-01T12:34:56.789Z");

expect.deepStrictEqual(actual, expected);
});

it("should return the expected object when the expiry is given as a date", () => {
const expected = {
"Set-Cookie": "Foo=bar; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
};

const actual = cookie("Foo", "bar", null, new Date(0));

expect.deepStrictEqual(actual, expected);
});

it("should return the expected object when the path and expiry is given", () => {
const expected = {
"Set-Cookie": "Foo=bar; Path=/some/path; Expires=Mon, 01 Jan 2024 12:34:56 GMT",
};

const actual = cookie("Foo", "bar", "/some/path", new Date("2024-01-01T12:34:56.789Z"));

expect.deepStrictEqual(actual, expected);
});
});
25 changes: 25 additions & 0 deletions auth/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import nunjucks from "nunjucks";
import { OctokitApp } from "../octokitApp.js";
import { handleOAuthCallback as handleOAuthCallbackImpl } from "./callback.js";
import { parseToken, isTokenValid } from "./token.js";
import { cookie } from "./cookie.js";

export const handleOAuthCallback = async (request, response) => handleOAuthCallbackImpl(OctokitApp.app, request, response);

export const getTokenOrPromptForLogin = async (request, response) => {
const token = parseToken(request);

if (!token || !(await isTokenValid(OctokitApp.app, token))) {
response.writeHead(200, {
...cookie("Token", "", "/", new Date(0)),
});

const template = nunjucks.render("login.njk");

response.end(template);

return undefined;
}

return token;
}
15 changes: 15 additions & 0 deletions auth/token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const parseToken = (request) => {
const match = request.headers?.cookie?.match(/Token=([^;]*)/);
return match?.[1];
};

export const isTokenValid = async (app, token) => {
try {
const { data: { app: { client_id }, created_at, expires_at }, authentication } = await app.oauth.checkToken({ token });

const now = new Date();
return client_id === authentication.clientId && new Date(created_at) < now && new Date(expires_at) > now;
} catch {
return false;
}
};
153 changes: 153 additions & 0 deletions auth/token.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { describe, it } from "node:test";
import expect from "node:assert";
import { isTokenValid, parseToken } from "./token.js";

const app = {
oauth: {
createToken: async () => {},
checkToken: async () => {},
}
};

describe("parseToken", () => {
it("should return undefined if there is no cookie", () => {
const request = {
headers: {
},
};

const actual = parseToken(request);

expect.strictEqual(actual, undefined);
});

it("should return undefined if there is no token in the cookie", () => {
const request = {
headers: {
cookie: "Foo=bar; Baz=quux"
},
};

const actual = parseToken(request);

expect.strictEqual(actual, undefined);
});

it("should return the token value if the token is the only cookie", () => {
const request = {
headers: {
cookie: "Token=tokenA"
},
};

const actual = parseToken(request);

expect.strictEqual(actual, "tokenA");
});

it("should return the token value if the token is not the only cookie", () => {
const request = {
headers: {
cookie: "Foo=bar; Token=tokenC; Baz=quux"
},
};

const actual = parseToken(request);

expect.strictEqual(actual, "tokenC");
});
});

describe("isTokenValid", () => {
it("should return false if the token is invalid", async (t) => {
t.mock.method(app.oauth, "checkToken", () => { throw "kaboom!"; });

const actual = await isTokenValid(app, "sometoken");

expect.strictEqual(actual, false);
});

it("should return false if the token is for the wrong app", async (t) => {
const checkTokenResponse = {
data: {
app: {
client_id: "foo",
},
created_at: "2024-01-01T12:34:56.789Z",
expires_at: "9999-12-31T23:59:59.999Z",
},
authentication: {
clientId: "bar",
},
};

t.mock.method(app.oauth, "checkToken", () => checkTokenResponse);

const actual = await isTokenValid(app, "sometoken");

expect.strictEqual(actual, false);
});

it("should return false if the token was created in the future", async (t) => {
const checkTokenResponse = {
data: {
app: {
client_id: "foo",
},
created_at: "9999-01-01T12:34:56.789Z",
expires_at: "9999-12-31T23:59:59.999Z",
},
authentication: {
clientId: "foo",
},
};

t.mock.method(app.oauth, "checkToken", () => checkTokenResponse);

const actual = await isTokenValid(app, "sometoken");

expect.strictEqual(actual, false);
});

it("should return false if the token expired in the past", async (t) => {
const checkTokenResponse = {
data: {
app: {
client_id: "foo",
},
created_at: "2024-01-01T12:34:56.789Z",
expires_at: "2023-12-31T23:59:59.999Z",
},
authentication: {
clientId: "foo",
},
};

t.mock.method(app.oauth, "checkToken", () => checkTokenResponse);

const actual = await isTokenValid(app, "sometoken");

expect.strictEqual(actual, false);
});

it("should return true if the token is valid", async (t) => {
const checkTokenResponse = {
data: {
app: {
client_id: "foo",
},
created_at: "2024-01-01T12:34:56.789Z",
expires_at: "9999-12-31T23:59:59.999Z",
},
authentication: {
clientId: "foo",
},
};

t.mock.method(app.oauth, "checkToken", () => checkTokenResponse);

const actual = await isTokenValid(app, "sometoken");

expect.strictEqual(actual, true);
});
});
30 changes: 30 additions & 0 deletions base.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{% import "./macros.njk" as macros %}

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Towtruck</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-stone-100 text-stone-800 dark:bg-stone-800 dark:text-stone-200">
<header class="bg-white dark:bg-stone-600">
<nav class="w-full flex items-baseline p-6 border-b-4 border-stone-200 dark:border-stone-900">
<h1 class="inline-block text-3xl"><a href="/" class="hover:underline">Towtruck</a></h1>
<div class="grow leading-9">&zwj;</div>
{% if loggedIn %}
<div class="leading-9"><a href="/logout" class="hover:underline">Logout</a></div>
{% endif %}
</nav>
</header>

<div class="container mx-auto flex flex-col mt-6 space-y-6">
{% block content %}
{% endblock %}
</div>
</body>
</html>
Loading
Loading