|
| 1 | +/* |
| 2 | + * Copyright 2025 Adobe. All rights reserved. |
| 3 | + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | + * of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | + * |
| 7 | + * Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | + * OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | + * governing permissions and limitations under the License. |
| 11 | + */ |
| 12 | + |
| 13 | +import { Response } from '@adobe/fetch'; |
| 14 | +import { hasText, isNonEmptyArray, isObject } from '@adobe/spacecat-shared-utils'; |
| 15 | + |
| 16 | +import { getBearerToken } from './handlers/utils/bearer.js'; |
| 17 | +import { loadPublicKey, validateToken } from './handlers/utils/token.js'; |
| 18 | + |
| 19 | +/** |
| 20 | + * Matches pre-split request segments against a route pattern with :param segments. |
| 21 | + * e.g. ['sites', 'abc-123', 'audits'] matches 'GET /sites/:siteId/audits' |
| 22 | + */ |
| 23 | +function matchRoute(method, requestSegments, routeKey) { |
| 24 | + const spaceIdx = routeKey.indexOf(' '); |
| 25 | + if (spaceIdx === -1) return false; |
| 26 | + |
| 27 | + const routeMethod = routeKey.slice(0, spaceIdx); |
| 28 | + if (routeMethod !== method) return false; |
| 29 | + |
| 30 | + const routeSegments = routeKey.slice(spaceIdx + 1).split('/').filter(Boolean); |
| 31 | + if (routeSegments.length !== requestSegments.length) return false; |
| 32 | + |
| 33 | + return routeSegments.every( |
| 34 | + (seg, i) => seg.charCodeAt(0) === 58 /* ':' */ || seg === requestSegments[i], |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Looks up the required capability for the current request from the |
| 40 | + * routeCapabilities map using the method and path from context.pathInfo. |
| 41 | + */ |
| 42 | +function resolveCapability(context, routeCapabilities) { |
| 43 | + const method = context.pathInfo?.method?.toUpperCase(); |
| 44 | + const path = context.pathInfo?.suffix; |
| 45 | + if (!method || !path) return null; |
| 46 | + |
| 47 | + const exactKey = `${method} ${path}`; |
| 48 | + if (routeCapabilities[exactKey]) return routeCapabilities[exactKey]; |
| 49 | + |
| 50 | + const requestSegments = path.split('/').filter(Boolean); |
| 51 | + const matchedKey = Object.keys(routeCapabilities) |
| 52 | + .find((key) => matchRoute(method, requestSegments, key)); |
| 53 | + return matchedKey ? routeCapabilities[matchedKey] : null; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * S2S consumer auth wrapper for the helix-shared-wrap `.with()` chain. |
| 58 | + * Validates a JWT bearer token and, when the token carries the |
| 59 | + * {@code is_s2s_consumer} claim, resolves the required capability for the |
| 60 | + * current route from the provided {@code routeCapabilities} map and verifies |
| 61 | + * the caller holds that capability in {@code tenants[].capabilities}. |
| 62 | + * |
| 63 | + * Non-S2S tokens (end-user) pass through untouched. |
| 64 | + * |
| 65 | + * @param {Function} fn - The handler to wrap. |
| 66 | + * @param {{ routeCapabilities: Object<string, string> }} opts - Map of route |
| 67 | + * patterns (e.g. 'GET /sites/:siteId') to capability strings (e.g. 'site:read'). |
| 68 | + * @returns {Function} A wrapped handler. |
| 69 | + */ |
| 70 | +export function s2sAuthWrapper(fn, { routeCapabilities } = {}) { |
| 71 | + let publicKey; |
| 72 | + |
| 73 | + return async (request, context) => { |
| 74 | + const { log } = context; |
| 75 | + |
| 76 | + try { |
| 77 | + if (!publicKey) { |
| 78 | + publicKey = await loadPublicKey(context); |
| 79 | + } |
| 80 | + |
| 81 | + const token = getBearerToken(context); |
| 82 | + if (!hasText(token)) { |
| 83 | + log.debug('[s2s] No bearer token provided'); |
| 84 | + return new Response('Unauthorized', { status: 401 }); |
| 85 | + } |
| 86 | + |
| 87 | + const payload = await validateToken(token, publicKey); |
| 88 | + |
| 89 | + if (!payload.is_s2s_consumer) { |
| 90 | + log.debug('[s2s] Token is not an S2S consumer token, passing through'); |
| 91 | + return fn(request, context); |
| 92 | + } |
| 93 | + |
| 94 | + const tenants = payload.tenants || []; |
| 95 | + const capabilities = tenants.flatMap((tenant) => tenant.capabilities || []); |
| 96 | + |
| 97 | + if (!isNonEmptyArray(capabilities)) { |
| 98 | + log.debug('[s2s] S2S consumer token has no capabilities'); |
| 99 | + return new Response('Forbidden', { status: 403 }); |
| 100 | + } |
| 101 | + |
| 102 | + if (isObject(routeCapabilities)) { |
| 103 | + const requiredCapability = resolveCapability(context, routeCapabilities); |
| 104 | + if (!hasText(requiredCapability)) { |
| 105 | + log.error(`[s2s] Route ${context.pathInfo?.method} ${context.pathInfo?.suffix} is not allowed for S2S consumers`); |
| 106 | + return new Response('Unauthorized', { status: 401 }); |
| 107 | + } |
| 108 | + if (!capabilities.includes(requiredCapability)) { |
| 109 | + log.error(`[s2s] Token is missing required capability: ${requiredCapability}`); |
| 110 | + return new Response('Forbidden', { status: 403 }); |
| 111 | + } |
| 112 | + } |
| 113 | + } catch (e) { |
| 114 | + log.error(`[s2s] Authentication failed: ${e.message}`); |
| 115 | + return new Response('Unauthorized', { status: 401 }); |
| 116 | + } |
| 117 | + |
| 118 | + return fn(request, context); |
| 119 | + }; |
| 120 | +} |
0 commit comments