-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathauthentication.ts
396 lines (344 loc) · 11.4 KB
/
authentication.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import * as Sentry from "@sentry/node"
import express from "express"
import crypto from "crypto"
import randomstring from "randomstring"
import * as db from "../db/db.js"
import {
CLOUDFLARE_AUD,
SECRET_KEY,
SESSION_COOKIE_AGE,
ADMIN_BASE_URL,
ENV,
} from "../settings/serverSettings.js"
import { BCryptHasher } from "../db/hashers.js"
import { Secret, verify } from "jsonwebtoken"
import { DbPlainSession, DbPlainUser, JsonError } from "@ourworldindata/utils"
import { exec } from "child_process"
export type Request = express.Request
export interface Response extends express.Response {
locals: { user: DbPlainUser; session: Session }
}
interface Session {
id: string
expiryDate: Date
}
const CLOUDFLARE_COOKIE_NAME = "CF_Authorization"
/*
* See authentication.php for detailed descriptions.
*/
export async function authCloudflareSSOMiddleware(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const jwt = req.cookies[CLOUDFLARE_COOKIE_NAME]
if (!jwt) return next()
const audTag = CLOUDFLARE_AUD
if (!audTag) {
console.error(
"Missing or empty audience tag. Please add CLOUDFLARE_AUD key in settings."
)
return next()
}
// Get the Cloudflare public key
const certsUrl = "https://owid.cloudflareaccess.com/cdn-cgi/access/certs"
const response = await fetch(certsUrl)
const certs = await response.json()
const publicCerts = certs.public_certs
if (!publicCerts) {
console.error("Missing public certificates from Cloudflare.")
return next()
}
// Verify the JWT token
let certVerificationErr
let payload: any
const verified = publicCerts.some((certObj: { cert: Secret }) => {
try {
payload = verify(jwt, certObj.cert, {
audience: audTag,
algorithms: ["RS256"],
})
return true
} catch (err) {
certVerificationErr = err
}
return false
})
if (!verified) {
// Authorization token invalid: verification failed, token expired or wrong audience.
console.error(certVerificationErr)
return next()
}
if (!payload.email) {
console.error("Missing email in JWT claims.")
return next()
}
// Here in the middleware we don't have access to the transaction yet so we get a knexinstance manually
const user = await db
.knexInstance()
.table("users")
.where({ email: payload.email })
.first()
if (!user) {
console.error(
`User with email ${payload.email} not found. Please contact an administrator.`
)
return next()
}
// Authenticate as the user stored in the token
const { id: sessionId } = await logInAsUser(user)
res.cookie("sessionid", sessionId, {
httpOnly: true,
sameSite: "lax",
secure: ENV !== "development",
})
// Prevents redirect to external URLs
let redirectTo = "/admin"
if (req.query.next) {
try {
redirectTo = new URL(req.query.next as string, ADMIN_BASE_URL)
.pathname
} catch (err) {
console.error(err)
}
}
return res.redirect(redirectTo)
}
export async function logOut(req: express.Request, res: express.Response) {
if (res.locals.user)
await db.knexReadWriteTransaction((trx) =>
db.knexRaw(trx, `DELETE FROM sessions WHERE session_key = ?`, [
res.locals.session.id,
])
)
res.clearCookie("sessionid")
res.clearCookie(CLOUDFLARE_COOKIE_NAME)
return res.redirect("/admin")
}
export async function authMiddleware(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
let user: DbPlainUser | null = null
let session: Session | undefined
const sessionid = req.cookies["sessionid"]
if (sessionid) {
const userAndSession = await db.knexReadWriteTransaction(
async (trx) => {
// Expire old sessions
await db.knexRaw(
trx,
"DELETE FROM sessions WHERE expire_date < NOW()"
)
const rows = await db.knexRaw<DbPlainSession>(
trx,
`SELECT * FROM sessions WHERE session_key = ?`,
[sessionid]
)
if (rows.length) {
const sessionData = Buffer.from(
rows[0].session_data,
"base64"
).toString("utf8")
const sessionJson = JSON.parse(
sessionData.split(":").slice(1).join(":")
)
const user = await trx
.table("users")
.where({ email: sessionJson.user_email })
.first<DbPlainUser>()
if (!user)
throw new JsonError(
"Invalid session (no such user)",
500
)
const session = {
id: sessionid,
expiryDate: rows[0].expire_date,
}
await trx
.table("users")
.where({ id: user.id })
.update({ lastSeen: new Date() })
return { user, session }
}
return null
}
)
user = userAndSession?.user ?? null
session = userAndSession?.session
}
// Authed urls shouldn't be cached
res.set("Cache-Control", "private, no-cache")
if (user?.isActive) {
res.locals.session = session
res.locals.user = user
Sentry.setUser({
id: user.id,
email: user.email,
username: user.fullName,
})
return next()
} else if (!req.path.startsWith("/admin") || req.path === "/admin/login")
return next()
return res.redirect(`/admin/login?next=${encodeURIComponent(req.url)}`)
}
function saltedHmac(salt: string, value: string): string {
const hmac = crypto.createHmac("sha1", salt + SECRET_KEY)
hmac.update(value)
return hmac.digest("hex")
}
export async function logInAsUser(user: Pick<DbPlainUser, "email" | "id">) {
const sessionId = randomstring.generate()
const sessionJson = JSON.stringify({
user_email: user.email,
})
const sessionHash = saltedHmac(
"django.contrib.sessions.SessionStore",
sessionJson
)
const sessionData = Buffer.from(`${sessionHash}:${sessionJson}`).toString(
"base64"
)
const now = new Date()
const expiryDate = new Date(now.getTime() + 1000 * SESSION_COOKIE_AGE)
await db.knexReadWriteTransaction(async (trx) => {
await db.knexRaw(
trx,
`INSERT INTO sessions (session_key, session_data, expire_date) VALUES (?, ?, ?)`,
[sessionId, sessionData, expiryDate]
)
await trx
.table("users")
.where({ id: user.id })
.update({ lastLogin: now })
})
return { id: sessionId, expiryDate: expiryDate }
}
export async function logInWithCredentials(
email: string,
password: string
): Promise<Session> {
// Here in the middleware we don't have access to the transaction yet so we get a knexinstance manually
const user = await db.knexInstance().table("users").where({ email }).first()
if (!user) throw new Error("No such user")
const hasher = new BCryptHasher()
if (await hasher.verify(password, user.password))
// Login successful
return logInAsUser(user)
throw new Error("Invalid password")
}
interface TailscaleStatus {
Self?: {
UserID: string
TailscaleIPs: string[]
}
Peer?: {
[key: string]: {
UserID: string
TailscaleIPs: string[]
HostName: string
Online: boolean
}
}
User?: {
[key: string]: {
DisplayName?: string
LoginName?: string
}
}
}
export async function tailscaleAuthMiddleware(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
// If there's a sessionid in cookies, proceed to `authMiddleware` middleware
if (req.cookies["sessionid"]) {
return next()
}
// Extract client's IP address
const clientIp = getClientIp(req)
// Get Tailscale IP-to-User mapping
const ipToUserMap = await getTailscaleIpToUserMap()
// Get the Tailscale display name / github username associated with the client's IP address
const githubUserName = ipToUserMap[clientIp]
// Next if user is not found, user can still log in as admin
if (!githubUserName) {
return next()
}
let user
try {
// Look up user by 'githubUsername'
user = await db
.knexInstance()
.table("users")
.where({ githubUsername: githubUserName })
.first()
} catch (error) {
console.error(`Error looking up user by githubUsername: ${error}`)
return next()
}
if (!user) {
console.error(
`User with githubUsername ${githubUserName} not found in MySQL.`
)
return next()
}
// Authenticate as the user stored in the token
const { id: sessionId } = await logInAsUser(user)
res.cookie("sessionid", sessionId, {
httpOnly: true,
sameSite: "lax",
secure: ENV !== "development",
})
// Save the sessionid in cookies for `authMiddleware` to log us in
req.cookies["sessionid"] = sessionId
return next()
}
function getClientIp(req: express.Request): string {
let ip =
(req.headers["x-forwarded-for"] as string) ||
req.socket.remoteAddress ||
req.ip
if (ip && ip.startsWith("::ffff:")) {
ip = ip.replace("::ffff:", "")
}
return ip
}
async function getTailscaleIpToUserMap(): Promise<Record<string, string>> {
return new Promise((resolve, reject) => {
exec("tailscale status --json", (error, stdout) => {
if (error) {
console.error(`Error getting Tailscale status: ${error}`)
return reject(error)
}
const tailscaleStatus: TailscaleStatus = JSON.parse(stdout)
const ipToUser: Record<string, string> = {}
// Map UserIDs to LoginNames
const userIdToLoginName: Record<string, string> = {}
if (tailscaleStatus.User) {
for (const [userId, userInfo] of Object.entries(
tailscaleStatus.User
)) {
if (userInfo.LoginName) {
userIdToLoginName[parseInt(userId)] = userInfo.LoginName
}
}
}
// Include Peers
if (tailscaleStatus.Peer) {
for (const peer of Object.values(tailscaleStatus.Peer)) {
if (peer.UserID in userIdToLoginName) {
const LoginName = userIdToLoginName[peer.UserID]
for (const ip of peer.TailscaleIPs) {
ipToUser[ip] = LoginName
}
}
}
}
resolve(ipToUser)
})
})
}