All files / owid-grapher/adminSiteServer authentication.tsx

19.1% Statements 38/199
100% Branches 0/0
0% Functions 0/5
19.1% Lines 38/199

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2271x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                     1x                             1x                                                                                                           1x           1x                                                                                      
import * as express from "express"
import * as crypto from "crypto"
import * as randomstring from "randomstring"
import { User } from "../db/model/User"
import * as db from "../db/db"
import {
    CLOUDFLARE_AUD,
    SECRET_KEY,
    SESSION_COOKIE_AGE,
} from "../settings/serverSettings"
import { BCryptHasher } from "../db/hashers"
import fetch from "node-fetch"
import { Secret, verify } from "jsonwebtoken"
import { ADMIN_BASE_URL, ENV } from "../settings/serverSettings"
import { JsonError } from "../clientUtils/owidTypes"
 
export type CurrentUser = User
 
export type Request = express.Request
 
export interface Response extends express.Response {
    locals: { user: CurrentUser; 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()
    }

    const user = await User.findOne({ email: payload.email })
    if (!user) return next("User not found. Please contact an administrator.")

    // Authenticate as the user stored in the token
    const { id: sessionId } = await logInAsUser(user)
    res.cookie("sessionid", sessionId, {
        httpOnly: true,
        sameSite: "lax",
        secure: ENV === "production",
    })

    // Prevents redirect to external URLs
    let redirectTo = "/admin"
    if (req.query.next) {
        try {
            redirectTo = new URL(req.query.next, ADMIN_BASE_URL).pathname
        } catch (err) {
            console.error(err)
        }
    }
    return res.redirect(redirectTo)
}
 
export async function logOut(
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
) {
    if (res.locals.user)
        await db.queryMysql(`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: CurrentUser | undefined
    let session: Session | undefined

    const sessionid = req.cookies["sessionid"]
    if (sessionid) {
        // Expire old sessions
        await db.execute("DELETE FROM sessions WHERE expire_date < NOW()")

        const rows = await db.queryMysql(
            `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(":")
            )

            user = await User.findOne({ email: sessionJson.user_email })
            if (!user)
                throw new JsonError("Invalid session (no such user)", 500)
            session = { id: sessionid, expiryDate: rows[0].expiry_date }

            // Don't await this
            user.lastSeen = new Date()
            user.save()
        }
    }

    // Authed urls shouldn't be cached
    res.set("Cache-Control", "public, max-age=0, must-revalidate")

    if (user && user.isActive) {
        res.locals.session = session
        res.locals.user = user
        return next()
    } else if (
        !req.path.startsWith("/admin") ||
        req.path === "/admin/login" ||
        req.path === "/admin/register"
    )
        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")
}
 
async function logInAsUser(user: User) {
    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.execute(
        `INSERT INTO sessions (session_key, session_data, expire_date) VALUES (?, ?, ?)`,
        [sessionId, sessionData, expiryDate]
    )
 
    user.lastLogin = now
    await user.save()
 
    return { id: sessionId, expiryDate: expiryDate }
}
 
export async function logInWithCredentials(
    email: string,
    password: string
): Promise<Session> {
    const user = await User.findOne({ email: email })
    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")
}