import { getLogger } from "@pie-api-gcp/shared/logging"; import { AuthInfo, getScopeVal, scopeExists } from "@pie-api-gcp/shared/auth"; import { forEachAsync, printDeep } from "@pie-api-gcp/shared/util"; import { AuthorizationError } from "./errors"; const logger = getLogger(); /** * Function to authorize that a token can be used for a particular resolver. * Throw AuthorizationError if not authorized. */ export type AuthorizeTokenFn = (token: AuthInfo, args?: any, context?: any) => Promise; /** * Stack authorizers. */ export const compose = (...authorizers: AuthorizeTokenFn[]): AuthorizeTokenFn => async (token: AuthInfo, args: any) => { await forEachAsync( authorizers.filter((a) => a != null), async (authorizer) => authorizer(token, args) ); }; /** * Token should have an admin property. */ export const shouldBeAdmin = async (token: AuthInfo) => { if (!token.admin) { throw new AuthorizationError("token holder is not an administrator"); } }; /** * Token should not have a scope with the given key. */ export const shouldNotHaveScopeKey = (...scopes: string[]): AuthorizeTokenFn => async (token: AuthInfo) => { const i = Object.keys(token.scopes ? token.scopes : {}).filter((t) => scopes.includes(t)); if (i.length > 0) { throw new AuthorizationError( `scope${i.length > 1 ? "s" : ""} ${i.join(",")} ${i.length > 1 ? "are" : "is"} not allowed for this function` ); } }; /** * Token should have a scope with the given key. */ export const shouldHaveScopeKey = (...scopes: string[]): AuthorizeTokenFn => async (token: AuthInfo) => { const tokenKeys = Object.keys(token.scopes ? token.scopes : {}); const d = scopes.filter((x) => !tokenKeys.includes(x)); if (d.length > 0) { throw new AuthorizationError( `scope${d.length > 1 ? "s" : ""} ${d.join(",")} ${d.length > 1 ? "are" : "is"} required this function` ); } }; /** * Find scope and run check function against it. */ export const checkScope = ( scopeKey: string, fn: (scopeVal: string, args: any) => void, isScopeRequired: boolean = false ): AuthorizeTokenFn => async (token: AuthInfo, args: any) => { const val = getScopeVal(token.scopes, scopeKey); if (val) { fn(val, args); } else if (isScopeRequired) { throw new AuthorizationError(`scope ${scopeKey} not found for token`); } }; /** * Scope should exist and have given string value. */ export const scopeShouldHaveValue = (scopeKey: string, scopeValue: string): AuthorizeTokenFn => checkScope( scopeKey, (v) => { if (v !== scopeValue) { throw new AuthorizationError( `function not allowed for token with ${scopeKey}: '${v}' (must be '${scopeValue}')` ); } }, true ); /** * The scope should NOT exist. */ export const scopeShouldNotExist = (scopeKey: string): AuthorizeTokenFn => async (token: AuthInfo, args: any) => { if (scopeExists(token.scopes, scopeKey)) { throw new AuthorizationError(`scope ${scopeKey} should not exist in ${printDeep(token.scopes)}`); } }; /** * Scope should exist and have given boolean value. */ export const scopeShouldHaveBooleanValue = (scopeKey: string, scopeValue: boolean): AuthorizeTokenFn => checkScope( scopeKey, (v) => { if (JSON.parse(v) !== scopeValue) { throw new AuthorizationError(`function not allowed for token with ${scopeKey}: '${v}' (must be ${scopeValue})`); } }, true ); /** * Scope should either not exist or if exists, not have the given string value. */ export const scopeShouldNotHaveValue = (scopeKey: string, scopeValue: string) => checkScope( scopeKey, (v) => { if (v === scopeValue) { throw new AuthorizationError(`function not allowed for token with ${scopeKey}: '${scopeValue})`); } }, false ); /** * Scope should either not exist or if exists, not have the given boolean value. */ export const scopeShouldNotHaveBooleanValue = (scopeKey: string, scopeValue: boolean) => checkScope( scopeKey, (v) => { if (JSON.parse(v) === scopeValue) { throw new AuthorizationError(`function not allowed for token with ${scopeKey}: '${scopeValue})`); } }, false ); /** * Check that a passed in argument either matches a value of the scope with the provided scope key * (or by default the same key as the arg) or that there is no scope with that key provided in the token. */ export const argShouldMatchScope = (arg: string, scopeKey: string = arg) => async (token: AuthInfo, args: any) => { const argVal = args[arg]; if (argVal) { const scopeVal = getScopeVal(token.scopes, scopeKey); if (scopeVal && argVal !== scopeVal) { throw new AuthorizationError(`${argVal} is not allowed for ${arg} (only ${scopeVal} is)`); } // else either scope is not set, or the arg matches the scope value, which both means we let it pass } }; /** * Check that a passed in argument passes the validation function or that there is no scope * with that key provided in the token. The validation function is only called when both the * argument and scope val exist. */ export const argShouldValidate = ( arg: string, scopeKey: string = arg, validationFn: (argVal: any, scopeVal: string) => void ) => async (token: AuthInfo, args: any) => { const argVal = args[arg]; if (argVal) { const scopeVal = getScopeVal(token.scopes, scopeKey); if (scopeVal) { return validationFn(argVal, scopeVal); } // else either scope is not set, or the arg matches the scope value, which both means we let it pass } }; /** * Check that a passed in versioned id (which consists of a base id and a semver) matches with * a base id if that is provided as a scope. */ export const versionedBaseIdShouldMatch = (arg: string = "versionedID", scopeKey: string = "api.baseId") => argShouldValidate(arg, scopeKey, (versionedID, baseId) => { const vid = versionedID; if (vid.id && vid.id !== baseId) { throw new AuthorizationError(`${vid.id} is not allowed for ${arg} (only ${baseId} is)`); } }); /** * Token should not have a { scope: 'player' } scope. */ export const shouldNotHavePlayerScope = scopeShouldNotHaveValue("scope", "player"); /** * Token should not have a { secure: true } scope. */ export const shouldNotHaveSecureScope = scopeShouldNotHaveBooleanValue("secure", true); /** * When a contentItemId is provided as an argument, there must either be a * matching contentId scope, or no contentId scope in the token. */ export const contentItemIdShouldMatchScope = argShouldMatchScope("contentItemId", "contentId"); /** * Standard token checks to guard against player access. */ export const playerProtections = compose( shouldNotHaveSecureScope, shouldNotHavePlayerScope, contentItemIdShouldMatchScope );