|
| 1 | +import { createHash, randomBytes } from "crypto"; |
| 2 | +import * as argon2 from "argon2"; |
| 3 | +import { UnauthenticatedError } from "common/errors/index.js"; |
| 4 | +import NodeCache from "node-cache"; |
| 5 | +import { |
| 6 | + DeleteItemCommand, |
| 7 | + DynamoDBClient, |
| 8 | + GetItemCommand, |
| 9 | +} from "@aws-sdk/client-dynamodb"; |
| 10 | +import { genericConfig } from "common/config.js"; |
| 11 | +import { AUTH_DECISION_CACHE_SECONDS as API_KEY_DATA_CACHE_SECONDS } from "./authorization.js"; |
| 12 | +import { unmarshall } from "@aws-sdk/util-dynamodb"; |
| 13 | +import { ApiKeyDynamoEntry, DecomposedApiKey } from "common/types/apiKey.js"; |
| 14 | + |
| 15 | +function min(a: number, b: number) { |
| 16 | + return a < b ? a : b; |
| 17 | +} |
| 18 | + |
| 19 | +export const API_KEY_CACHE_SECONDS = 120; |
| 20 | + |
| 21 | +export const createChecksum = (key: string) => { |
| 22 | + return createHash("sha256").update(key).digest("hex").slice(0, 6); |
| 23 | +}; |
| 24 | + |
| 25 | +export const createApiKey = async () => { |
| 26 | + const keyId = randomBytes(6).toString("hex"); |
| 27 | + const prefix = `acmuiuc_${keyId}`; |
| 28 | + const rawKey = randomBytes(32).toString("hex"); |
| 29 | + const checksum = createChecksum(rawKey); |
| 30 | + const apiKey = `${prefix}_${rawKey}_${checksum}`; |
| 31 | + const hashedKey = await argon2.hash(rawKey); |
| 32 | + return { apiKey, hashedKey, keyId }; |
| 33 | +}; |
| 34 | + |
| 35 | +export const getApiKeyParts = (apiKey: string): DecomposedApiKey => { |
| 36 | + const [prefix, id, rawKey, checksum] = apiKey.split("_"); |
| 37 | + if (!prefix || !id || !rawKey || !checksum) { |
| 38 | + throw new UnauthenticatedError({ |
| 39 | + message: "Invalid API key.", |
| 40 | + }); |
| 41 | + } |
| 42 | + if ( |
| 43 | + prefix != "acmuiuc" || |
| 44 | + id.length != 12 || |
| 45 | + rawKey.length != 64 || |
| 46 | + checksum.length != 6 |
| 47 | + ) { |
| 48 | + throw new UnauthenticatedError({ |
| 49 | + message: "Invalid API key.", |
| 50 | + }); |
| 51 | + } |
| 52 | + return { |
| 53 | + prefix, |
| 54 | + id, |
| 55 | + rawKey, |
| 56 | + checksum, |
| 57 | + }; |
| 58 | +}; |
| 59 | + |
| 60 | +export const verifyApiKey = async ({ |
| 61 | + apiKey, |
| 62 | + hashedKey, |
| 63 | +}: { |
| 64 | + apiKey: string; |
| 65 | + hashedKey: string; |
| 66 | +}) => { |
| 67 | + try { |
| 68 | + const { rawKey, checksum: submittedChecksum } = getApiKeyParts(apiKey); |
| 69 | + const isChecksumValid = createChecksum(rawKey) === submittedChecksum; |
| 70 | + if (!isChecksumValid) { |
| 71 | + return false; |
| 72 | + } |
| 73 | + return await argon2.verify(hashedKey, rawKey); |
| 74 | + } catch (e) { |
| 75 | + if (e instanceof UnauthenticatedError) { |
| 76 | + return false; |
| 77 | + } |
| 78 | + throw e; |
| 79 | + } |
| 80 | +}; |
| 81 | + |
| 82 | +export const getApiKeyData = async ({ |
| 83 | + nodeCache, |
| 84 | + dynamoClient, |
| 85 | + id, |
| 86 | +}: { |
| 87 | + nodeCache: NodeCache; |
| 88 | + dynamoClient: DynamoDBClient; |
| 89 | + id: string; |
| 90 | +}): Promise<ApiKeyDynamoEntry | undefined> => { |
| 91 | + const cacheKey = `auth_apikey_${id}`; |
| 92 | + const cachedValue = nodeCache.get(`auth_apikey_${id}`); |
| 93 | + if (cachedValue !== undefined) { |
| 94 | + return cachedValue as ApiKeyDynamoEntry; |
| 95 | + } |
| 96 | + const getCommand = new GetItemCommand({ |
| 97 | + TableName: genericConfig.ApiKeyTable, |
| 98 | + Key: { keyId: { S: id } }, |
| 99 | + }); |
| 100 | + const result = await dynamoClient.send(getCommand); |
| 101 | + if (!result || !result.Item) { |
| 102 | + nodeCache.set(cacheKey, null, API_KEY_DATA_CACHE_SECONDS); |
| 103 | + return undefined; |
| 104 | + } |
| 105 | + const unmarshalled = unmarshall(result.Item) as ApiKeyDynamoEntry; |
| 106 | + if ( |
| 107 | + unmarshalled.expiresAt && |
| 108 | + unmarshalled.expiresAt <= Math.floor(Date.now() / 1000) |
| 109 | + ) { |
| 110 | + dynamoClient.send( |
| 111 | + new DeleteItemCommand({ |
| 112 | + TableName: genericConfig.ApiKeyTable, |
| 113 | + Key: { keyId: { S: id } }, |
| 114 | + }), |
| 115 | + ); // don't need to wait for the response |
| 116 | + return undefined; |
| 117 | + } |
| 118 | + if (!("keyHash" in unmarshalled)) { |
| 119 | + return undefined; // bad data, don't cache it |
| 120 | + } |
| 121 | + let cacheTime = API_KEY_DATA_CACHE_SECONDS; |
| 122 | + if (unmarshalled["expiresAt"]) { |
| 123 | + const currentEpoch = Date.now(); |
| 124 | + cacheTime = min(cacheTime, unmarshalled["expiresAt"] - currentEpoch); |
| 125 | + } |
| 126 | + nodeCache.set(cacheKey, unmarshalled as ApiKeyDynamoEntry, cacheTime); |
| 127 | + return unmarshalled; |
| 128 | +}; |
0 commit comments